-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathfileHandler.js
350 lines (303 loc) · 9.79 KB
/
fileHandler.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
const obj = {
/*
* Searches system for media files
*
* @param {Object} fs
* Native NodeJS fs module
* @param {Object} os
* Native NodeJS os module
* @param {Object} utils
* Utils object from main.js
* @param {Object} settings
* Settings from settings file
* @param {Boolean} silent
* If it should log errors
* @return {Promise}
*/
searchSystem: (fs, os, path, utils, settings, silent) => {
let paths = [];
const songsArr = [];
const videosObj = {};
const subtitlesArr = [];
const playlistsArr = [];
const foundFileNames = [];
const audioFileExtensions = settings.audioFileExtensions.val;
const videoFileExtensions = settings.videoFileExtensions.val;
if (settings.checkOsHomedirs.val) {
// Folders that have to be searched
paths.push(path.join(os.homedir(), '/Music/'));
paths.push(path.join(os.homedir(), '/Videos/'));
}
if (settings.mediaPaths.val != '')
paths = paths.concat(settings.mediaPaths.val);
utils.colorLog(utils.logDate() + ' [[fgBlue, SEARCHSYSTEM:]] Starting checking files');
return new Promise((resolve, reject) => {
if (paths.length < 1)
reject('No paths specified for checking.');
const homedir = os.homedir();
const checkDirs = paths.map(val => {
return handleFolders(val.replace('{homedir}', homedir), utils, path);
});
// Wait untill the functions finish
Promise.all(checkDirs).then(() => {
setTimeout(() => {
jsonFileArr = {
audio: {
playlists: playlistsArr,
songs: songsArr
},
video: {
subtitles: subtitlesArr,
videos: videosObj,
}
};
fs.writeFile(path.join(__dirname, '/JSON.json'), JSON.stringify(jsonFileArr, 2), err => {
if (err) reject(err);
else {
utils.colorLog(utils.logDate() + ' [[fgBlue, SEARCHSYSTEM:]] Updated the Json file');
resolve(jsonFileArr);
}
});
}, 1000);
}).catch(reject);
});
/*
* Responsible for recursive file search in a particular folder
*
* @param {String} path
* @param {Object} utils
* The utils object in main.js
* @return {Promise}
*/
async function handleFolders(path, utils, pathModule) {
const exists = await utils.fileExists(path);
if (!exists)
throw Error('Directory not found: ' + path);
const addToVidArr = (path, fileName, fullPath, mtime) => {
const getFolderFromPath = path => {
return path.replace(/\\/g, '/').split('/').filter(val => { return val.trim().length > 0 }).pop();
}
let folderName = getFolderFromPath(path);
if (paths.map(val => { return getFolderFromPath(val) }).includes(folderName))
folderName = 'Root';
if (folderName in videosObj)
videosObj[folderName].push({ path, fileName, fullPath, lastChanged: mtime });
else
videosObj[folderName] = [{ path, fileName, fullPath, lastChanged: mtime }];
}
// Loop through all the files
const promiseArr = (await fs.promises.readdir(path)).map(async object => {
if (object.toLowerCase() !== 'desktop.ini') {
// Check if file has same name
if (foundFileNames.includes(object))
console.wrn(`There are files with the same name: '${object}'`);
else {
const fileExtention = utils.getFileExtension(object.toLowerCase());
const stats = await fs.promises.stat(pathModule.join(path, object));
const fullPath = pathModule.join(path, object);
const mtime = new Date(stats.mtime.toString());
// Check if the file has a file extension that is in the arrays in index.js or that it is a playlist
// If it is a file just execute this function again
if (audioFileExtensions.includes(fileExtention)) {
songsArr.push({ path, fileName: object, fullPath, lastChanged: mtime });
foundFileNames.push(object);
} else if (videoFileExtensions.includes(fileExtention)) {
addToVidArr(path, object, fullPath, mtime);
foundFileNames.push(object)
} else if (fileExtention == '.m3u') {
playlistsArr.push({ path, fileName: object, fullPath, lastChanged: mtime });
foundFileNames.push(object);
} else if (fileExtention == '.vtt') {
subtitlesArr.push({ path, fileName: object, fullPath });
foundFileNames.push(object);
} else if (!fileExtention && fs.lstatSync(pathModule.join(path, object)).isDirectory()) {
handleFolders(pathModule.join(path, object, '/'), utils, pathModule);
} else if (fileExtention && !silent) {
console.wrn('File extention not supported', object);
} else if (fileExtention && silent) {
} else {
console.wrn('Something is weird...', 'FILENAME:' + object, 'EXTENSION:' + fileExtention);
}
}
}
});
return await Promise.all(promiseArr);
}
},
/*
* Returns a Promise with all all the playlists on the system an their contents
*
* @param {Object} audio
* Array from fileHandler.getJSON.audio
* @return {Promise}
*/
getPlaylists: (audio, fs, fileHandler, utils, full = false) => {
const handleM3UFiles = () => {
return Promise.all(audio.playlists.map(async object => {
const songsArr = await fileHandler.readPlayList(fs, object.fullPath, utils, audio.songs);
if (full)
return songsArr;
return object.fileName;
if (songsArr.length > 0)
return object.fileName;
else
throw Error(`Playlist '${object.fileName}' is empty`);
}));
}
const handlePlaylistsFile = async () => {
const playlistsFileLoc = './playlists.json';
if (!await utils.fileExists(playlistsFileLoc))
return [];
try {
const data = await fs.promises.readFile(playlistsFileLoc, 'utf-8');
if (!data)
return [];
const parsedData = await utils.safeJSONParse(data);
if (full)
return parsedData;
return Object.keys(parsedData);
} catch (err) {
console.err('getPlaylists: handlePlaylistsFile:');
console.err(err);
return [];
}
}
return Promise.all([handleM3UFiles(), handlePlaylistsFile()]);
},
/*
* Parses a .m3u file
*
* @param {Object} fs
* Native NodeJS fs module
* @param {String} path
* The playlist file path
* @param {Array} songsArr
* Array from fileHandler.getJSON.audio.songs
* @return {Promise}
*/
readPlayList: async (fs, path, utils, songsArr) => {
const songs = [];
songsArr = songsArr.map(val => val.fileName);
if (!await utils.fileExists(path))
throw Error(`'${path}' does not exist`);
// Split by every song
(await fs.promises.readFile(path, 'utf-8'))
.replace('#EXTM3U', '')
.split(/#EXTINF:[0-9]+,.+/)
.forEach(object => {
object = object.trim();
if (object != '') {
const match = object.match(/(.+)(\/|\\)(.+)$/);
if (match) {
const songName = match[3].toString().trim();
if (songsArr.includes(songName))
songs.push(songName);
}
}
});
return songs;
},
updatePlaylist: async (fs, body, utils) => {
const jsonPath = './playlists.json';
const write = async (content, alreadyExists) => {
await fs.promises.writeFile(jsonPath, JSON.stringify(content, null, '\t'));
if (alreadyExists)
return `Playlist with the name '${body.name}' successfuly updated`
else
return `Playlist with the name '${body.name}' successfuly added`;
}
if (await utils.fileExists(jsonPath)) {
const data = await utils.safeJSONParse(await fs.promises.readFile(jsonPath, 'utf-8'));
if (body.delete == true) {
if (!(body.name in data))
throw Error(`'${body.name}' not found in 'playlists.json'`);
delete data[body.name];
return await write(data, true);
} else {
data[body.name] = body.songs;
return await write(data, (body.name in data));
}
} else {
const obj = {};
obj[body.name] = body.songs;
return await write(obj, false);
}
},
/*
* Reads the JSON.json file
*
* @param {Object} fs
* Native NodeJS fs module
* @param {Object} os
* Native NodeJS os module
* @param {Object}
* Utils object in main.js
* @param {Object} settings
* Settings from settings.js
* @return {Promise}
*/
getJSON: async (fs, os, path, utils, settings) => {
const JSONPath = './JSON.json';
if (await utils.fileExists(JSONPath)) {
const data = await fs.promises.readFile(JSONPath, 'utf-8');
return await utils.safeJSONParse(data);
} else {
console.wrn('The JSON file does not exist, so one is created...');
return await obj.searchSystem(fs, os, path, utils, settings);
}
},
/*
* Uses id3 module to get song tags
*
* @param {String} path
* File location
* @param {Object} id3
* id3 module
* @param {Object} utils
* MusicStream utils object
* @return {Promise}
*/
getSongInfo: (path, id3, utils) => {
return new Promise((resolve, reject) => {
utils.fileExists(path).then(exists => {
if (!exists)
reject('File does not exist');
else {
id3.read(path, (err, tags) => {
if (err)
reject(err);
else
resolve(tags);
});
}
});
});
},
/*
* Loops through the Plugins dir and organizes them for further handling
*
* @return {Promise}
*/
getPlugins: async (pathModule, utils, fs) => {
const path = pathModule.join(__dirname, '/Plugins/');
if (!await utils.fileExists(path))
return [];
else {
return await Promise.all((await fs.promises.readdir(path)).map(async object => {
const indexPath = pathModule.join(path, object, '/index.js');
if (await utils.fileExists(indexPath)) {
return {
module: require(indexPath),
folder: object,
};
} else {
console.err('No index.js file found in ' + path);
return {
notfound: true
};
}
}));
}
}
};
module.exports = obj;