-
Notifications
You must be signed in to change notification settings - Fork 305
/
Copy pathget.js
222 lines (191 loc) · 7.16 KB
/
get.js
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
/* eslint-disable no-mixed-operators, no-async-promise-executor */
module.exports = handler
const fs = require('fs')
const glob = require('glob')
const _path = require('path')
const $rdf = require('rdflib')
const Negotiator = require('negotiator')
const mime = require('mime-types')
const debug = require('debug')('solid:get')
const debugGlob = require('debug')('solid:glob')
const allow = require('./allow')
const translate = require('../utils.js').translate
const error = require('../http-error')
const RDFs = require('../ldp').mimeTypesAsArray()
async function handler (req, res, next) {
const ldp = req.app.locals.ldp
const includeBody = req.method === 'GET'
const negotiator = new Negotiator(req)
const baseUri = ldp.resourceMapper.resolveUrl(req.hostname, req.path)
const path = res.locals.path || req.path
const requestedType = negotiator.mediaType()
const possibleRDFType = negotiator.mediaType(RDFs)
res.header('MS-Author-Via', 'SPARQL')
// Set live updates
if (ldp.live) {
res.header('Updates-Via', ldp.resourceMapper.resolveUrl(req.hostname).replace(/^http/, 'ws'))
}
debug(req.originalUrl + ' on ' + req.hostname)
const options = {
hostname: req.hostname,
path: path,
includeBody: includeBody,
possibleRDFType: possibleRDFType,
range: req.headers.range,
contentType: req.headers.accept
}
let ret
try {
ret = await ldp.get(options, req.accepts(['html', 'turtle', 'rdf+xml', 'n3', 'ld+json']) === 'html')
} catch (err) {
// use globHandler if magic is detected
if (err.status === 404 && glob.hasMagic(path)) {
debug('forwarding to glob request')
return globHandler(req, res, next)
} else {
debug(req.method + ' -- Error: ' + err.status + ' ' + err.message)
return next(err)
}
}
let stream
let contentType
let container
let contentRange
let chunksize
if (ret) {
stream = ret.stream
contentType = ret.contentType
container = ret.container
contentRange = ret.contentRange
chunksize = ret.chunksize
}
// Till here it must exist
if (!includeBody) {
debug('HEAD only')
res.setHeader('Content-Type', ret.contentType)
return res.status(200).send('OK')
}
// Handle dataBrowser
if (requestedType && requestedType.includes('text/html')) {
const { path: filename } = await ldp.resourceMapper.mapUrlToFile({ url: options })
const mimeTypeByExt = mime.lookup(_path.basename(filename))
const isHtmlResource = mimeTypeByExt && mimeTypeByExt.includes('html')
const useDataBrowser = ldp.dataBrowserPath && (
container ||
RDFs.includes(contentType) && !isHtmlResource && !ldp.suppressDataBrowser)
if (useDataBrowser) {
res.set('Content-Type', 'text/html')
const defaultDataBrowser = require.resolve('mashlib/dist/databrowser.html')
const dataBrowserPath = ldp.dataBrowserPath === 'default' ? defaultDataBrowser : ldp.dataBrowserPath
debug(' sending data browser file: ' + dataBrowserPath)
res.sendFile(dataBrowserPath)
return
} else if (stream) {
res.setHeader('Content-Type', contentType)
return stream.pipe(res)
}
}
// If request accepts the content-type we found
if (stream && negotiator.mediaType([contentType])) {
res.setHeader('Content-Type', contentType)
if (contentRange) {
const headers = { 'Content-Range': contentRange, 'Accept-Ranges': 'bytes', 'Content-Length': chunksize }
res.writeHead(206, headers)
return stream.pipe(res)
} else {
return stream.pipe(res)
}
}
// If it is not in our RDFs we can't even translate,
// Sorry, we can't help
if (!possibleRDFType) {
return next(error(406, 'Cannot serve requested type: ' + contentType))
}
try {
// Translate from the contentType found to the possibleRDFType desired
const data = await translate(stream, baseUri, contentType, possibleRDFType)
debug(req.originalUrl + ' translating ' + contentType + ' -> ' + possibleRDFType)
res.setHeader('Content-Type', possibleRDFType)
res.send(data)
return next()
} catch (err) {
if (err.message === '404') {
return next(error(404, 'HTML do not contain data island'))
}
debug('error translating: ' + req.originalUrl + ' ' + contentType + ' -> ' + possibleRDFType + ' -- ' + 500 + ' ' + err.message)
return next(error(500, 'Error translating between RDF formats'))
}
}
async function globHandler (req, res, next) {
const { ldp } = req.app.locals
// Ensure this is a glob for all files in a single folder
// https://github.com/solid/solid-spec/pull/148
const requestUrl = await ldp.resourceMapper.getRequestUrl(req)
if (!/^[^*]+\/\*$/.test(requestUrl)) {
return next(error(404, 'Unsupported glob pattern'))
}
// Extract the folder on the file system from the URL glob
const folderUrl = requestUrl.substr(0, requestUrl.length - 1)
const folderPath = (await ldp.resourceMapper.mapUrlToFile({ url: folderUrl, searchIndex: false })).path
const globOptions = {
noext: true,
nobrace: true,
nodir: true
}
glob(`${folderPath}*`, globOptions, async (err, matches) => {
if (err || matches.length === 0) {
debugGlob('No files matching the pattern')
return next(error(404, 'No files matching glob pattern'))
}
// Matches found
const globGraph = $rdf.graph()
debugGlob('found matches ' + matches)
await Promise.all(matches.map(match => new Promise(async (resolve, reject) => {
const urlData = await ldp.resourceMapper.mapFileToUrl({ path: match, hostname: req.hostname })
fs.readFile(match, { encoding: 'utf8' }, function (err, fileData) {
if (err) {
debugGlob('error ' + err)
return resolve()
}
// Files should be Turtle
if (urlData.contentType !== 'text/turtle') {
return resolve()
}
// The agent should have Read access to the file
hasReadPermissions(match, req, res, function (allowed) {
if (allowed) {
try {
$rdf.parse(fileData, globGraph, urlData.url, 'text/turtle')
} catch (parseErr) {
debugGlob(`error parsing ${match}: ${parseErr}`)
}
}
return resolve()
})
})
})))
const data = $rdf.serialize(undefined, globGraph, requestUrl, 'text/turtle')
// TODO this should be added as a middleware in the routes
res.setHeader('Content-Type', 'text/turtle')
debugGlob('returning turtle')
res.send(data)
next()
})
}
// TODO: get rid of this ugly hack that uses the Allow handler to check read permissions
function hasReadPermissions (file, req, res, callback) {
const ldp = req.app.locals.ldp
if (!ldp.webid) {
// FIXME: what is the rule that causes
// "Unexpected literal in error position of callback" in `npm run standard`?
// eslint-disable-next-line
return callback(true)
}
const root = ldp.resourceMapper.resolveFilePath(req.hostname)
const relativePath = '/' + _path.relative(root, file)
res.locals.path = relativePath
// FIXME: what is the rule that causes
// "Unexpected literal in error position of callback" in `npm run standard`?
// eslint-disable-next-line
allow('Read')(req, res, err => callback(!err))
}