This repository was archived by the owner on Oct 13, 2022. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
executable file
·245 lines (181 loc) · 5.98 KB
/
Copy pathindex.js
File metadata and controls
executable file
·245 lines (181 loc) · 5.98 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
#!/usr/bin/env node
'use strict';
// ################################### //
// Custom Modules
const observer = require('./modules/observer.js');
const log = observer.log
, pl = observer.playlist
, timer = observer.timer;
const HOSTNAME = observer.settings.server.hostname
, PORT = observer.settings.server.port
, ROOT_PATH = observer.settings.path.root;
const SUPPORTED_MEDIA_TYPES = observer.settings.supported_media_types;
// NPM Modules
const fs = require('fs')
, express = require('express')
, cookieParser = require('cookie-parser');
// Express.js setting
const app = express();
app.use(cookieParser());
app.use(express.static('app'));
// ################################### //
// Routers
app.all('/', (req, res) => {
res.send('<script>location.replace("./drive/");</script>');
})
// Render Pages
let driveSection = /^\/drive\//;
app.all(driveSection, (req, res) => {
log.create(`<${req.ip}> Rendering UI for client.`);
var path = getPath(req.path.replace(driveSection, ''));
let files = [
fs.readFileSync('app/header.partial.html'),
fs.readFileSync(`app/stat/explorer/index.html`),
fs.readFileSync(`app/stat/audio-player/index.html`),
fs.readFileSync('app/footer.partial.html')
]
Promise.all(files)
.then(files => files = files.map(f => f = f.toString('utf-8')))
.then(files => {
const content = files.join('');
res.send(content);
})
})
// Render JSON data of a directory.
let driveJsonSection = /^\/json\//;
app.all(driveJsonSection, (req, res) => {
var path = getPath(req.path.replace(driveJsonSection, ''));
// Error handler
if (!fs.existsSync(path)) {
res.json({error: 'not found!'});
return;
} else if (!fs.statSync(path).isDirectory()) {
res.json({error: 'not a directory!'});
return;
}
timer.start('loading!');
// Parse directory data into useful form.
let files = fs.readdirSync(path).map(f => {
let source = {
name: f,
type: fileType(path + f),
secured: false // not yet.
}
if (source.type == 'folder') {
source.name += '/';
}
return source;
});
// Temporal action to prevent mac OS hidden files from appearing. + and unwanted files.
files = files.filter(f => {
return !f.name.includes('._') && !f.name.includes('CENSORED');
})
res.json(files);
// Time time time
let speed = timer.end('finished loading');
log.create(`<${req.ip}> accessed to [${path}], JSON rendering took ${speed} ms.`);
})
let playlistSection = /^\/playlist\//;
app.all(playlistSection, (req, res) => {
let params = req.path.replace(playlistSection, '').split('/');
// 1. Get user data from path string. >> /playlist/:userID/:playlistID/
let clientID = params[0],
playlistID = params[1];
// 2. is save mode?
if ('save' in req.query) {
let playlist = new Array();
// 2-1. Each value has path string that is encoded by encodeURIcompoent().
for (let key in req.query) {
if (key == 'save') {
continue
}
playlist.push(decodeURIComponent(req.query[key]));
}
// 2-2. Save the playlist using custom module.
pl.setPlaylist(clientID, playlistID, playlist);
// 3. Record what's going on.
log.create(`<${req.ip}> (${clientID}) saved playlist (${playlistID}).`);
} else {
log.create(`<${req.ip}> (${clientID}) downloaded playlist (${playlistID}).`);
}
// 4. Get the playlist using custom module.
let content = pl.getPlaylist(clientID, playlistID);
res.json(content);
})
let streamSection = /^\/stream\//;
app.all(streamSection, (req, res) => {
var path = getPath(req.path.replace(streamSection, ''));
if (!fs.existsSync(path)) {
console.log('404: stream: ', path);
res.send(null);
return;
}
log.create(`<${req.ip}> downloaded [${path}]`);
let filetype = fileType(path),
extension = path.match(/[^.]+$/)[0];
if (extension == 'mp3') {
extension = 'mpeg';
}
let contentType = `${filetype}/${extension}`;
// Level ACCESS
const stat = fs.statSync(path);
const fileSize = stat.size;
const range = req.headers.range;
if (range) {
const parts = range.replace(/bytes=/, "").split("-");
const start = parseInt(parts[0], 10);
const end = parts[1]
? parseInt(parts[1], 10)
: fileSize-1;
const chunksize = (end-start)+1
const file = fs.createReadStream(path, {start, end})
const head = {
'Content-Range': `bytes ${start}-${end}/${fileSize}`,
'Accept-Ranges': 'bytes',
'Content-Length': chunksize,
'Content-Type': contentType,
}
res.writeHead(206, head);
file.pipe(res);
} else {
const head = {
'Content-Length': fileSize,
'Content-Type': contentType,
}
res.writeHead(200, head)
fs.createReadStream(path).pipe(res)
}
})
// ################################### //
// Launch Server!
app.listen(80, () => {
log.create(`\nSet root directory [${ROOT_PATH}]\nSelf-cloud-server listening on [${HOSTNAME}:${PORT}]!`);
})
// ################################### //
// Functions
function getPath(path) {
path = ROOT_PATH + decodeURIComponent(path);
path = path.replace('//', '/');
return path;
}
/**
* Return the type of a file.
* @param {string} path
* @return {string}
*/
function fileType(path) {
if (!fs.existsSync(path)) {
return null;
}
let stat = fs.statSync(path);
if (stat.isDirectory()) {
return 'folder';
}
let extension = path.match(/([^.]*)$/)[0];
for (let type in SUPPORTED_MEDIA_TYPES) {
if (SUPPORTED_MEDIA_TYPES[type].includes(extension)) {
return type;
}
}
return 'file';
}