-
Notifications
You must be signed in to change notification settings - Fork 3
/
ftpserver.js
383 lines (296 loc) · 9.36 KB
/
ftpserver.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
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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
const {FtpSrv, FileSystem} = require('ftp-srv');
const FTPErrors = require('ftp-srv/src/errors');
const Path = require('path');
const { Readable } = require("stream");
const Utils = require('./utils');
const FS = require('fs');
const { loggers } = require('winston');
const Log = Utils.Log;
class MyFileSystem extends FileSystem {
constructor(connection, {root, cwd} = {}) {
super(connection, {root: '/', cwd: '/'});
}
chdir(path) {
// console.log('chdir', this.cwd, `"${path}"`);
if ( path.startsWith('/') ) {
this.cwd = '/'; // Path.join(this.cwd, path);
}
if ( path.endsWith('.strm') ) {
Log.error(`[FTP] .strm file is not a directory: ${this.cwd} - ${path}`);
throw new FTPErrors.FileSystemError(`Folder not exists ${this.cwd} - ${path}`);
}
this.cwd = Path.join(this.cwd, path);
Log.info(`[FTP] chdir to ${this.cwd}`, );
return this.cwd;
}
get(fileName) {
let fullpath = Path.join(this.cwd, fileName);
Log.info(`[FTP] get ${fullpath}`);
let parts = (fullpath.startsWith('/') ? fullpath.substring(1) : fullpath).split('/');
if ( parts.length > 2 ) {
if ( parts[2].endsWith('.strm') ) {
if ( parts.length > 3 ) {
Log.error(`[FTP] Invalid path requested: ${fullpath}`);
throw new FTPErrors.FileSystemError(`Invalid path requested: ${fullpath}`);
}
} else {
Log.error(`[FTP] Invalid file requested: ${fullpath}`);
throw new FTPErrors.FileSystemError(`Invalid file requested: ${fullpath}`);
}
}
let lastPath = parts.pop();
Log.info(`[FTP] get part -> ${lastPath || 'tvchannels'}`);
let isFile = fileName.endsWith('.strm');
let list = this.loopFolder(isFile, fullpath);
let size = 0;
if (isFile) {
let chl = list; // list.find(c => c.name == lastPath );
if ( !chl ) {
Log.error(`[FTP] Cannot found channel by name ${fileName}`);
throw new FTPErrors.FileSystemError(`Cannot read channel ${fileName}`);
}
size = chl.size;
} else if ( list.length > 0 ) {
size = list.reduce( (acc, item) => {
acc = isNaN(acc) ? 0 : acc;
acc += item.size;
return acc;
})
}
Log.info(`[FTP] Responding get -> ${lastPath || 'tvchannels'} - size: ${size} - file: ${isFile}`);
return {
name: lastPath || 'tvchannels',
uid: lastPath || 'tvchannels',
mtime: Date.now(),
birthtimeMs: Date.now(),
size: size,
isDirectory: function() {
return !isFile;
},
isFile: function() {
return isFile;
}
};
}
get root() {
return this._root;
}
currentDirectory() {
return this.cwd;
}
list(path) {
return this.loopFolder(false);
}
write(fileName, {append = false, start = undefined} = {}) {
throw new FTPErrors.FileSystemError('cannot write');
}
read(fileName, {start = undefined} = {}) {
// console.log('try to read', fileName, start);
let filepath = Path.join(this.cwd, fileName);
Log.info(`[FTP] Responding file ${filepath}`);
let list = this.loopFolder(false);
let chl = list.find(c => c.name == fileName );
if ( !chl ) {
Log.error(`[FTP] Cannot found channel by name ${fileName}`);
throw new FTPErrors.FileSystemError(`Cannot read channel ${fileName}`);
}
Log.info( `[FTP] Found streamUrl for ${chl.name} -> ${chl.link}`);
let stream = Readable.from([chl.link]);
stream.path = filepath
// console.log('Found file', stream.path, 'for ->', chl.link);
return stream;
// FS.writeFileSync('/Users/fatshotty/Desktop/myfile.strm', `${chl.link}\n`, 'utf-8');
// return FS.createReadStream('/Users/fatshotty/Desktop/myfile.strm');
}
delete(path) {
throw new FTPErrors.FileSystemError('Cannot delete');
}
mkdir(path) {
throw new FTPErrors.FileSystemError('Cannot create directory');
}
rename(from, to) {
throw new FTPErrors.FileSystemError('Cannot rename');
}
chmod(path, mode) {
throw new FTPErrors.FileSystemError('Cannot change permission');
}
getUniqueName() {
Log.info('[FTP] get uniqe');
return Date.now(); // uuid.v4().replace(/\W/g, '');
}
loopFolder(single, currentPath) {
Log.info(`[FTP] Listing ${currentPath || this.cwd}`);
currentPath = currentPath || this.cwd;
if ( currentPath == '/' ) {
currentPath = '';
}
let parts = currentPath.split( '/' );
let resObj = [];
let currList = null;
let steps = ['lists', 'groups', 'channels'];
for (let i = 0, part; i < parts.length; i++) {
let part = parts[i];
let step = steps[ i ];
switch( step ) {
case 'lists':
Log.debug(`[FTP] compute all lists`);
resObj = remapLists();
break;
case 'groups':
currList = Ftp.M3U().find(m => m.Name == part );
if ( !currList ) {
throw new FTPErrors.FileSystemError(`[FTP] list ${part} not exists`);
}
Log.info(`[FTP] compute groups for ${currList.Name}`);
resObj = remapGroups( currList );
break;
case 'channels':
let grp = currList.groups.find( g => g.Name == part );
if ( !currList ) {
throw new FTPErrors.FileSystemError(`[FTP] group ${part} not exists`);
}
Log.info(`[FTP] compute channels for ${grp.Name}`);
resObj = remapChannels( grp );
break;
}
}
let lastPart = parts.pop();
single = single || lastPart.endsWith('.strm');
if ( single ) {
resObj = resObj.find(i => i.name == lastPart );
}
Log.info(`[FTP] Respond ${single ? 'first result' : resObj.length + ' items'}`);
return single ? resObj : resObj;
}
}
function remapLists() {
return Ftp.M3U().map( (m) => {
let m3uc = Ftp.M3UConfig().find( c => c.Name == m.Name );
return {
name: m.Name,
uid: m3uc.UUID,
mtime: Date.now(),
birthtimeMs: Date.now(),
size: 0,
isDirectory: function() {
return true;
},
isFile: function() {
return false;
}
};
})
}
function remapGroups(m3u) {
return m3u.groups.map( g => {
return {
name: g.Name,
uid: g.Id,
mtime: Date.now(),
birthtimeMs: Date.now(),
size: 0,
isDirectory: function() {
return true;
},
isFile: function() {
return false;
}
};
})
}
function remapChannels(group) {
return group.channels.map( c => {
let chl = c.clone();
return {
name: `${chl.Name}.strm`.trim(),
uid: chl.TvgId,
mtime: Date.now(),
birthtimeMs: Date.now(),
size: Buffer.byteLength(chl.StreamUrl, 'utf-8'),
isDirectory: function() {
return false;
},
isFile: function() {
return true;
},
link: chl.StreamUrl
};
})
}
let FtpServer = null;
const Ftp = {
M3U: null,
M3UConfig: null,
Config: null,
setM3UList(getter) {
this.M3U = getter;
},
setM3UConfig(getter) {
this.M3UConfig = getter;
},
setConfig(getter) {
this.Config = getter;
},
async stop() {
if ( FtpServer ) {
Log.info(`[FTP] Stopping FTP server`);
await FtpServer.close();
FtpServer = null;
}
},
async start() {
await this.stop();
let self = this;
Log.info(`[FTP] Starting FTP server on ${process.env.BIND_IP || '127.0.0.1'}:${this.Config().FtpPort}`);
FtpServer = new FtpSrv({
url: `ftp://${process.env.BIND_IP || '127.0.0.1'}:${this.Config().FtpPort}`,
root: "/",
pasv_url: `${process.env.BIND_IP || '127.0.0.1'}`,
pasv_range: '8400-8500'
});
let HAS_BASIC_AUTH = process.env.BASIC_AUTH == "true";
let BASIC_AUTH_OVERALL = process.env.BASIC_AUTH_OVERALL == 'true';
function checkLocalRequest(connection) {
let ip_local = self.Config().LocalIp;
let ip_remot = connection.ip;
if ( ip_local ) {
ip_local = ip_local.split(':').shift();
}
if ( ip_local == 'localhost') {
ip_local = '127.0.0.1';
}
Log.debug(`[FTP] local ip is: ${ip_local} - remote ip is: ${ip_remot}`);
if ( ip_local === ip_remot ) {
return true;
} else {
let ip_local_str = ip_local.split('.').slice(0, -2).join('.');
let ip_remot_str = ip_remot.split('.').slice(0, -2).join('.');
return ip_local_str === ip_remot_str;
}
}
// let MYFS = new MyFileSystem();
FtpServer.on('login', ({connection, username, password}, resolve, reject) => {
// check login
let isLocal = checkLocalRequest(connection);
if ( (!isLocal && HAS_BASIC_AUTH) || (HAS_BASIC_AUTH && BASIC_AUTH_OVERALL == 'true')) {
if ( username != process.env.BASIC_USER || password != process.env.BASIC_PWD ){
Log.error(`[FTP] cannot login`)
return reject();
}
}
Log.info(`[FTP] connection logged in successfully`)
resolve({fs: new MyFileSystem(connection)});
// resolve({root: '/Users/fatshotty/Desktop', cwd: '/'});
});
FtpServer.on ( 'client-error', (connection, context, error) => {
console.log ( 'client-error:', connection, context, error );
Log.error(`[FTP] client-error ${error}`);
});
FtpServer.on ( 'error', (connection, context, error) => {
console.log ( 'error:', connection, context, error );
Log.error(`[FTP] error ${error}`);
});
FtpServer.listen();
}
}
module.exports = Ftp;