LjFileHelper.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. var request = require('request');
  2. var fs = require('fs');
  3. var ffmpeg = require('fluent-ffmpeg');
  4. var ljConst = require("../common/LjConst.js");
  5. var path = require('path');
  6. var logHelper = require("./LjLogHelper");
  7. /**
  8. * The helper of file
  9. */
  10. class LjFileHelper
  11. {
  12. /**
  13. * Download file
  14. * @param fileUrl the file url
  15. * @returns {boolean}
  16. */
  17. static downloadFile(fileUrl)
  18. {
  19. //获取文件属性对象
  20. var filePropObj = this.getFileProperty(fileUrl);
  21. if (filePropObj == null)
  22. {
  23. return false;
  24. }
  25. console.info(filePropObj);
  26. //视频处理
  27. if (filePropObj.fileType == ljConst.VIDEO_TYPE_M3U8)
  28. {
  29. //未加密视频本地存储路径
  30. var localFileDir = filePropObj.folderDir + filePropObj.fileName + ".mp4"
  31. //M3U8视频转换MP4
  32. ffmpeg(fileUrl).format(ljConst.VIDEO_TYPE_MP4)
  33. .on('start', function (err)
  34. {
  35. logHelper.info("Starting down video:" + fileUrl);
  36. })
  37. .on('error', function (err)
  38. {
  39. logHelper.error("Succeeded to down video[" + fileUrl + "]: " + err.message);
  40. })
  41. .on('end', function ()
  42. {
  43. //加密视频存储路径
  44. let localFileDirNew = filePropObj.folderDir + filePropObj.fileName + "_new" + ".mp4"
  45. logHelper.info("Succeeded to down video:" + localFileDirNew);
  46. //加密存储
  47. LjFileHelper.writeEncryptedStream(localFileDir, localFileDirNew);
  48. logHelper.info("Succeeded to encrypt video:" + localFileDirNew);
  49. //删除文件(加密存储完成后删除未加密文件)
  50. fs.unlink(localFileDir, function (err)
  51. {
  52. if (err)
  53. {
  54. //删除失败
  55. logHelper.info("Failed to delete video[" + err.message + "]:" + localFileDir);
  56. throw err;
  57. }
  58. else
  59. {
  60. logHelper.info('Succeeded to delete video:' + localFileDir)
  61. }
  62. })
  63. })
  64. .save(localFileDir);
  65. }//有声读物处理
  66. else if (filePropObj.fileType == ljConst.VIDEO_TYPE_MP3)
  67. {
  68. //未加密有声读物本地存储地址
  69. var localFileDir = filePropObj.folderDir + filePropObj.fileName + "." + filePropObj.fileType;
  70. //读取有声读物
  71. request(fileUrl).pipe(fs.createWriteStream(localFileDir)).on('close', function ()
  72. {
  73. //加密有声读物存储地址
  74. var localFileDirNew = filePropObj.folderDir + filePropObj.fileName + "_new." + filePropObj.fileType;
  75. logHelper.info("Succeeded to down audio:" + localFileDirNew);
  76. //加密有声读物
  77. LjFileHelper.writeEncryptedStream(localFileDir, localFileDirNew);
  78. logHelper.info("Succeeded to image audio:" + localFileDirNew);
  79. //删除文件(加密存储完成后删除未加密文件)
  80. fs.unlink(localFileDir, function (err)
  81. {
  82. if (err)
  83. {
  84. //删除失败
  85. logHelper.erro("Failed to delete audio[" + err.message + "]:" + localFileDir);
  86. throw err;
  87. }
  88. else
  89. {
  90. logHelper.info('Succeeded to delete audio:' + localFileDir)
  91. }
  92. })
  93. });
  94. }//图片处理
  95. else
  96. {
  97. //未加密图片本地存储地址
  98. var localFileDir = filePropObj.folderDir + filePropObj.fileName + "." + filePropObj.fileType;
  99. //读取图片
  100. request(fileUrl).pipe(fs.createWriteStream(localFileDir)).on('close', function ()
  101. {
  102. //加密图片存储地址
  103. var localFileDirNew = filePropObj.folderDir + filePropObj.fileName + "_new." + filePropObj.fileType;
  104. logHelper.info("Succeeded to down image:" + localFileDirNew);
  105. //加密图片
  106. LjFileHelper.writeEncryptedStream(localFileDir, localFileDirNew);
  107. logHelper.info("Succeeded to image image:" + localFileDirNew);
  108. //删除文件(加密存储完成后删除未加密文件)
  109. fs.unlink(localFileDir, function (err)
  110. {
  111. if (err)
  112. {
  113. //删除失败
  114. logHelper.erro("Failed to delete image[" + err.message + "]:" + localFileDir);
  115. throw err;
  116. }
  117. else
  118. {
  119. logHelper.info('Succeeded to delete image:' + localFileDir)
  120. }
  121. })
  122. });
  123. }
  124. }
  125. /**
  126. * Delete file
  127. * @param fileUrl the file url
  128. * @returns {boolean}
  129. */
  130. static delFile(fileUrl)
  131. {
  132. //获取文件属性对象
  133. var filePropObj = this.getFileProperty(fileUrl);
  134. if (filePropObj == null)
  135. {
  136. return false;
  137. }
  138. //视频处理
  139. if (filePropObj.fileType == ljConst.VIDEO_TYPE_M3U8)
  140. {
  141. //加密视频存储路径
  142. let localFileDirNew = filePropObj.folderDir + filePropObj.fileName + "_new" + ".mp4"
  143. logHelper.info("Succeeded to down video:" + localFileDirNew);
  144. //删除加密文件
  145. fs.unlink(localFileDirNew, function (err)
  146. {
  147. if (err)
  148. {
  149. //删除失败
  150. logHelper.info("Failed to delete video[" + err.message + "]:" + localFileDir);
  151. throw err;
  152. }
  153. else
  154. {
  155. logHelper.info('Succeeded to delete video:' + localFileDir)
  156. }
  157. })
  158. }//图片处理
  159. else
  160. {
  161. //加密图片存储地址
  162. var localFileDirNew = filePropObj.folderDir + filePropObj.fileName + "_new." + filePropObj.fileType;
  163. logHelper.info("Succeeded to down image:" + localFileDirNew);
  164. //删除加密文件
  165. fs.unlink(localFileDirNew, function (err)
  166. {
  167. if (err)
  168. {
  169. //删除失败
  170. logHelper.erro("Failed to delete image[" + err.message + "]:" + localFileDir);
  171. throw err;
  172. }
  173. else
  174. {
  175. logHelper.info('Succeeded to delete image:' + localFileDir)
  176. }
  177. })
  178. }
  179. }
  180. /**
  181. * Gets file directory
  182. * @param fileName the file name
  183. * @returns {*|string} the file directory
  184. */
  185. static getFileDir(fileName)
  186. {
  187. var fileType = fileName.split(".")[1]
  188. var newFileDir = "";
  189. if (fileType == "m3u8")
  190. {
  191. fileName = fileName.replace(".m3u8", "_new.mp4")
  192. newFileDir = ljConst.BASE_DIR + fileName.replace(/\*/g, '\\');
  193. }
  194. else
  195. {
  196. fileName = fileName.replace(".", "_new.")
  197. newFileDir = ljConst.BASE_DIR + fileName.replace(/\*/g, '\\');
  198. }
  199. return newFileDir;
  200. }
  201. /**
  202. * Makes directory
  203. * @param dirname the directory name
  204. * @returns {boolean} true or false
  205. */
  206. static mkdirsSync(dirname)
  207. {
  208. if (fs.existsSync(dirname))
  209. {
  210. return true;
  211. }
  212. else
  213. {
  214. if (this.mkdirsSync(path.dirname(dirname)))
  215. {
  216. fs.mkdirSync(dirname);
  217. return true;
  218. }
  219. }
  220. }
  221. /**
  222. * Gets the file property object
  223. * @param fileUrl the file URL
  224. * @returns {null}
  225. */
  226. static getFileProperty(fileUrl)
  227. {
  228. /*--文件夹目录-Begin--*/
  229. var folderDir = ljConst.BASE_DIR;
  230. var splitArr = fileUrl.split('/')
  231. var arrLen = splitArr.length;
  232. for (var i = 3; i < arrLen - 1; i++)
  233. {
  234. folderDir += splitArr[i] + "\\";
  235. }
  236. //创建文件夹目录
  237. this.mkdirsSync(folderDir);
  238. var filePropObj = {};
  239. filePropObj.folderDir = folderDir;
  240. //获取文件名称
  241. filePropObj.fileName = splitArr[arrLen - 1].split(".")[0];
  242. //获取文件类型
  243. filePropObj.fileType = splitArr[arrLen - 1].split(".")[1];
  244. /*--文件夹目录-Begin--*/
  245. return filePropObj;
  246. }
  247. static Encrypted(c)
  248. {
  249. var b = '';
  250. for (var i = 0; i < c.length; i++)
  251. {
  252. var ch = c[i];
  253. if (ch == '0')
  254. {
  255. ch = 'f';
  256. }
  257. else if (ch == 'f')
  258. {
  259. ch = '0';
  260. }
  261. b = b + ch;
  262. //console.log(ch);
  263. }
  264. return b;
  265. }
  266. static Decrypted(c)
  267. {
  268. var b = '';
  269. for (var i = 0; i < c.length; i++)
  270. {
  271. var ch = c[i];
  272. if (ch == 'f')
  273. {
  274. ch = '0';
  275. }
  276. else if (ch == '0')
  277. {
  278. ch = 'f';
  279. }
  280. b = b + ch;
  281. //console.log(ch);
  282. }
  283. return b;
  284. }
  285. /**
  286. * Writes encrypted content, which is read from given source file, into given dest file
  287. * @param fSrc the source file
  288. * @param fDest the dest file
  289. */
  290. static writeEncryptedStream(fSrc, fDest)
  291. {
  292. var rs = fs.createReadStream(fSrc);
  293. var ws = fs.createWriteStream(fDest);
  294. rs.on('data', function (chunk)
  295. {
  296. let b = new Buffer(chunk, 'hex');
  297. //console.log(b);
  298. let c = b.toString('hex');
  299. c = LjFileHelper.encryptedContent(c);
  300. let d = Buffer.from(c, 'hex');
  301. ws.write(d);
  302. });
  303. rs.on('end', function ()
  304. {
  305. ws.end();
  306. logHelper.info('Succeeded in writing into encrypted stream[' + fDest + '].');
  307. });
  308. rs.on('error', function (err)
  309. {
  310. console.log(err.stack);
  311. });
  312. }
  313. /**
  314. * Encrypts the content
  315. * @param c the content to be encrypted
  316. * @return the encrypted content
  317. */
  318. static encryptedContent(c)
  319. {
  320. var b = '';
  321. for (var i = 0; i < c.length; i++)
  322. {
  323. var ch = c[i];
  324. if (ch == '0')
  325. {
  326. ch = 'f';
  327. }
  328. else if (ch == 'f')
  329. {
  330. ch = '0';
  331. }
  332. else if (ch == '1')
  333. {
  334. ch = 'e';
  335. }
  336. else if (ch == 'e')
  337. {
  338. ch = '1';
  339. }
  340. else if (ch == '2')
  341. {
  342. ch = 'd';
  343. }
  344. else if (ch == 'd')
  345. {
  346. ch = '2';
  347. }
  348. else if (ch == '3')
  349. {
  350. ch = 'c';
  351. }
  352. else if (ch == 'c')
  353. {
  354. ch = '3';
  355. }
  356. b = b + ch;
  357. //console.log(ch);
  358. }
  359. return b;
  360. }
  361. /**
  362. * Decrypts the encrypted content
  363. * @param c the encrypted content
  364. * @return the decrypted content
  365. */
  366. static decryptedContent(c)
  367. {
  368. var b = '';
  369. for (var i = 0; i < c.length; i++)
  370. {
  371. var ch = c[i];
  372. if (ch == 'f')
  373. {
  374. ch = '0';
  375. }
  376. else if (ch == '0')
  377. {
  378. ch = 'f';
  379. }
  380. else if (ch == 'e')
  381. {
  382. ch = '1';
  383. }
  384. else if (ch == '1')
  385. {
  386. ch = 'e';
  387. }
  388. else if (ch == 'd')
  389. {
  390. ch = '2';
  391. }
  392. else if (ch == '2')
  393. {
  394. ch = 'd';
  395. }
  396. else if (ch == 'c')
  397. {
  398. ch = '3';
  399. }
  400. else if (ch == '3')
  401. {
  402. ch = 'c';
  403. }
  404. b = b + ch;
  405. //console.log(ch);
  406. }
  407. return b;
  408. }
  409. /**
  410. * Reads decrypted content, which is read from given encrypted file, into HTTP response stream
  411. * @param res the HTTP response stream
  412. * @param fDest the encrypted file
  413. */
  414. static readDecryptedStream(res, fDest, contentType)
  415. {
  416. res.writeHead(200, {'Content-Type': contentType});
  417. var rs = fs.createReadStream(fDest);
  418. rs.on('data', function (chunk)
  419. {
  420. let b = new Buffer(chunk, 'hex');
  421. let c = b.toString('hex');
  422. c = LjFileHelper.decryptedContent(c);
  423. let d = Buffer.from(c, 'hex');
  424. res.write(d);
  425. });
  426. rs.on('end', function ()
  427. {
  428. res.end();
  429. console.log('Succeeded in reading from decrypted stream[' + fDest + '].');
  430. });
  431. rs.on('error', function (err)
  432. {
  433. console.log(err.stack);
  434. });
  435. }
  436. /**
  437. * Is video
  438. * @param dir the directory
  439. * @returns {boolean}
  440. */
  441. isVideo(dir)
  442. {
  443. if (dir == "")
  444. {
  445. return false;
  446. }
  447. var fileType = dir.split(".")[1];
  448. if ("m3u8" == fileType)
  449. {
  450. return true;
  451. }
  452. return false;
  453. }
  454. }
  455. module.exports = LjFileHelper;