forked from nodeSolidServer/node-solid-server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.mjs
More file actions
258 lines (241 loc) · 7.04 KB
/
Copy pathutils.mjs
File metadata and controls
258 lines (241 loc) · 7.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
/* eslint-disable node/no-deprecated-api */
import fs from 'fs'
import path from 'path'
import util from 'util'
import $rdf from 'rdflib'
import from from 'from2'
import url from 'url'
import { fs as debug } from './debug.mjs'
import getSize from 'get-folder-size'
import ns from 'solid-namespace'
import { createRequire } from 'module'
const require = createRequire(import.meta.url)
const nsObj = ns($rdf)
/**
* Returns a fully qualified URL from an Express.js Request object.
* (It's insane that Express does not provide this natively.)
*
* Usage:
*
* ```
* var fullURL = utils.fullUrlForReq(req)
* ```
*
* @method fullUrlForReq
*
* @param req {IncomingMessage} Express.js request object
*
* @return {string} Fully qualified URL of the request
*/
export function fullUrlForReq (req) {
const protocol = req.secure || req.get('X-Forwarded-Proto') === 'https' ? 'https' : 'http'
return protocol + '://' + req.get('host') + req.originalUrl
}
/**
* Routes the resolved file. Serves static files with content negotiation.
*
* @method routeResolvedFile
* @param req {IncomingMessage} Express.js request object
* @param res {ServerResponse} Express.js response object
* @param file {string} resolved filename
* @param contentType {string} MIME type of the resolved file
* @param container {boolean} whether this is a container
* @param next {Function} Express.js next callback
*/
export function routeResolvedFile (router, path, file, appendFileName = true) {
const fullPath = appendFileName ? path + file.match(/[^/]+$/) : path
const fullFile = require.resolve(file)
router.get(fullPath, (req, res) => res.sendFile(fullFile))
}
/**
* Get the content type from a headers object
* @param headers An Express or Fetch API headers object
* @return {string} A content type string
*/
export function getContentType (headers) {
const value = headers.get ? headers.get('content-type') : headers['content-type']
return value ? value.replace(/;.*/, '') : ''
}
/**
* Returns the base filename (without directory) for a given path.
*
* @method pathBasename
*
* @param fullpath {string}
*
* @return {string}
*/
export function pathBasename (fullpath) {
let bname = path.basename(fullpath)
if (hasSuffix(bname, '.ttl')) {
bname = bname.substring(0, bname.length - 4)
} else if (hasSuffix(bname, '.jsonld')) {
bname = bname.substring(0, bname.length - 7)
}
return bname
}
/**
* Checks to see whether a string has the given suffix.
*
* @method hasSuffix
*
* @param str {string}
* @param suffix {string}
*
* @return {boolean}
*/
export function hasSuffix (str, suffix) {
if (!str || str.length === 0) {
return false
}
return str.indexOf(suffix, str.length - suffix.length) !== -1
}
/**
* Serializes an `rdflib` graph to a string.
*
* @method serialize
*
* @param graph {Graph} rdflib Graph object
* @param base {string} Base URL
* @param contentType {string}
*
* @return {string}
*/
export function serialize (graph, base, contentType) {
// Implementation placeholder
return $rdf.serialize(graph, base, contentType)
}
/**
* Translates common RDF content types to `rdflib` parser names.
*
* @method translate
*
* @param contentType {string}
*
* @return {string}
*/
export function translate (contentType) {
if (contentType) {
if (contentType === 'text/n3' || contentType === 'text/turtle' || contentType === 'application/turtle') {
return 'text/turtle'
}
if (contentType === 'application/rdf+xml') {
return 'application/rdf+xml'
}
if (contentType === 'application/xhtml+xml') {
return 'application/xhtml+xml'
}
if (contentType === 'text/html') {
return 'text/html'
}
if (contentType.includes('json')) {
return 'application/ld+json'
}
}
return contentType
}
/**
* Converts a given string to a Node.js Readable Stream.
*
* @method stringToStream
*
* @param string {string}
*
* @return {ReadableStream}
*/
export function stringToStream (string) {
return from(function (size, next) {
if (string.length <= 0) return next(null, null)
const chunk = string.slice(0, size)
string = string.slice(size)
next(null, chunk)
})
}
/**
* Removes opening and closing angle brackets from a string.
*
* @method debrack
* @param str {string}
* @return {string}
*/
export function debrack (str) {
if (str && str.startsWith('<') && str.endsWith('>')) {
return str.substring(1, str.length - 1)
}
return str
}
/**
* Removes line ending characters (\n and \r) from a string.
*
* @method stripLineEndings
* @param str {string}
* @return {string}
*/
export function stripLineEndings (str) {
return str.replace(/[\r\n]/g, '')
}
/**
* Returns the quota for a user in a root
* @param root
* @param serverUri
* @returns {Promise<Number>} The quota in bytes
*/
export async function getQuota (root, serverUri) {
let prefs
try {
prefs = await _asyncReadfile(path.join(root, 'settings/serverSide.ttl'))
} catch (error) {
debug('Setting no quota. While reading serverSide.ttl, got ' + error)
return Infinity
}
const graph = $rdf.graph()
const storageUri = serverUri.endsWith('/') ? serverUri : serverUri + '/'
try {
$rdf.parse(prefs, graph, storageUri, 'text/turtle')
} catch (error) {
throw new Error('Failed to parse serverSide.ttl, got ' + error)
}
return Number(graph.anyValue($rdf.sym(storageUri), nsObj.solid('storageQuota'))) || Infinity
}
/**
* Returns true of the user has already exceeded their quota, i.e. it
* will check if new requests should be rejected, which means they
* could PUT a large file and get away with it.
*/
export async function overQuota (root, serverUri) {
const quota = await getQuota(root, serverUri)
if (quota === Infinity) {
return false
}
// TODO: cache this value?
const size = await actualSize(root)
return (size > quota)
}
/**
* Returns the number of bytes that is occupied by the actual files in
* the file system. IMPORTANT NOTE: Since it traverses the directory
* to find the actual file sizes, this does a costly operation, but
* neglible for the small quotas we currently allow. If the quotas
* grow bigger, this will significantly reduce write performance, and
* so it needs to be rewritten.
*/
function actualSize (root) {
return util.promisify(getSize)(root)
}
function _asyncReadfile (filename) {
return util.promisify(fs.readFile)(filename, 'utf-8')
}
/**
* Parse RDF content based on content type.
*
* @method parse
* @param graph {Graph} rdflib Graph object to parse into
* @param data {string} Data to parse
* @param base {string} Base URL
* @param contentType {string} Content type
* @return {Graph} The parsed graph
*/
export function parse (graph, data, base, contentType) {
// Implementation placeholder - need to check original implementation
return $rdf.parse(data, graph, base, translate(contentType))
}