main.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. let argv = require('minimist')(process.argv.slice(2));
  2. const fs = require('fs');
  3. const express = require('express');
  4. const app = express();
  5. const mysql = require('mysql2')
  6. const SendSeekable = require('send-seekable');
  7. const pool = mysql.createPool({
  8. keepAliveInitialDelay: 0, enableKeepAlive: true,
  9. })
  10. require('cnchar');
  11. require('sort-array');
  12. const Kind = {
  13. 0: "去和声伴奏",
  14. 1: "和声伴奏",
  15. 2: "人声",
  16. 3: "贝斯",
  17. 4: "鼓",
  18. 5: "其他",
  19. }
  20. const db = mysql.createConnection({
  21. host: 'mc.andyxie.cn',
  22. user: 'instrunet',
  23. password: 'Moyingren2015',
  24. database: "instrunet_data",
  25. pool: pool,
  26. enableKeepAlive: true,
  27. keepAliveInitialDelay: 0,
  28. })
  29. const nodemailer = require('nodemailer')
  30. let Queue = require('js-queue');
  31. const webp = require('webp-converter')
  32. webp.grant_permission()
  33. let queue = new Queue();
  34. queue.autoRun = false;
  35. const bodyParser = require("body-parser");
  36. const nrc = require('node-run-cmd')
  37. const https = require("node:https");
  38. const {OpenCC} = require("opencc");
  39. const {HttpsProxyAgent} = require("https-proxy-agent");
  40. const sortArray = require("sort-array");
  41. const converters2t = new OpenCC('s2t.json')
  42. const convertert2s = new OpenCC('t2s.json')
  43. app.use(bodyParser.json({"limit": "200mb"}));
  44. app.use(express.json());
  45. app.use(SendSeekable)
  46. const transporter = nodemailer.createTransport({
  47. host: 'smtp.qq.com', port: 465, secure: true, auth: {
  48. user: '3095864740@qq.com', pass: 'caemyuagapsadfff',
  49. }
  50. })
  51. let ncmAPIUrl = "http://localhost:5999";
  52. let currentTask = [];
  53. function Submit(req) {
  54. let uuid = crypto.randomUUID()
  55. db.connect(function (err) {
  56. if (err) {
  57. console.log(err)
  58. }
  59. })
  60. let albumCover = null;
  61. try {
  62. fetch(req.body.file).then(res => {
  63. res.arrayBuffer().then(r => fs.writeFileSync("./" + uuid, Buffer.from(r)));
  64. })
  65. if (URL.canParse(req.body.albumCover)) {
  66. console.log("can parse ")
  67. fetch(req.body.albumCover).then(res => {
  68. res.arrayBuffer().then(async r => {
  69. if (!fs.existsSync("tmp")) {
  70. fs.mkdirSync("tmp")
  71. }
  72. fs.writeFileSync("tmp/" + uuid, new Buffer.from(r));
  73. await webp.cwebp("tmp/" + uuid, "tmp/" + uuid + ".webp", "-q 50 -mt ", "-v")
  74. try{
  75. albumCover = fs.readFileSync("tmp/" + uuid + ".webp")
  76. }catch (e) {
  77. albumCover = null;
  78. }
  79. })
  80. })
  81. }
  82. } catch (err) {
  83. console.log(err)
  84. return
  85. }
  86. const callback = function (d) {
  87. console.log(d.toString());
  88. }
  89. const errcb = function (d) {
  90. console.log(d.toString());
  91. }
  92. let kind_of = [];
  93. switch (req.body.kind) {
  94. case 0:
  95. kind_of[0] = `audio-separator ./${uuid} --model_filename UVR-MDX-NET-Inst_HQ_4.onnx --mdx_enable_denoise --mdx_segment_size 4000 --mdx_overlap 0.85 --mdx_batch_size 300 --output_format mp3 --output_dir output`
  96. kind_of[1] = `./output/${uuid}_(Instrumental)_UVR-MDX-NET-Inst_HQ_4.mp3`
  97. kind_of[2] = `${uuid}_(Instrumental)_UVR-MDX-NET-Inst_HQ_4.mp3`
  98. kind_of[3] = `./output/${uuid}_(Vocals)_UVR-MDX-NET-Inst_HQ_4.mp3`
  99. break;
  100. case 1:
  101. kind_of[0] = `audio-separator ./${uuid} --model_filename UVR_MDXNET_KARA_2.onnx --mdx_enable_denoise --mdx_segment_size 4000 --mdx_overlap 0.85 --mdx_batch_size 300 --output_format mp3 --output_dir output`
  102. kind_of[1] = `./output/${uuid}_(Instrumental)_UVR_MDXNET_KARA_2.mp3`
  103. kind_of[2] = `${uuid}_(Instrumental)_UVR_MDXNET_KARA_2.mp3`
  104. kind_of[3] = `./output/${uuid}_(Vocals)_UVR_MDXNET_KARA_2.mp3`
  105. break;
  106. case 3:
  107. kind_of[0] = `audio-separator ./${uuid} --model_filename kuielab_a_bass.onnx --mdx_enable_denoise --mdx_segment_size 4000 --mdx_overlap 0.75 --sample_rate=48000 --output_format mp3 --mdx_batch_size 300 --output_dir output`
  108. kind_of[1] = `./output/${uuid}_(Bass)_kuielab_a_bass.mp3`
  109. kind_of[2] = `${uuid}_(Bass)_kuielab_a_bass.mp3`
  110. kind_of[3] = `./output/${uuid}_(No Bass)_kuielab_a_bass.mp3`
  111. break;
  112. case 4:
  113. kind_of[0] = `audio-separator ./${uuid} --model_filename kuielab_a_drums.onnx --mdx_enable_denoise --mdx_segment_size 4000 --mdx_overlap 0.75 --sample_rate=48000 --output_format mp3 --mdx_batch_size 300 --output_dir output`
  114. kind_of[1] = `./output/${uuid}_(Drums)_kuielab_a_drums.mp3`
  115. kind_of[2] = `${uuid}_(Drums)_kuielab_a_drums.mp3`
  116. kind_of[3] = `./output/${uuid}_(No Drums)_kuielab_a_drums.mp3`
  117. break;
  118. }
  119. nrc.run([kind_of[0]], {
  120. onData: callback, onError: errcb
  121. }).then(() => {
  122. db.execute(("INSERT INTO instrunet_entry (uuid, song_name, album_name, link_to, databinary, artist,kind, albumcover, email) VALUES (?,?,?,?,?,?,?,?,?)"), [uuid, req.body.name, req.body.albumName, req.body.link, fs.readFileSync(kind_of[1]), req.body.artist, req.body.kind, albumCover === null ? new Buffer.from([]) : albumCover, (req.body.email === null || req.body.email === undefined || req.body.email === "") ? "" : req.body.email])
  123. db.unprepare()
  124. fs.rm(kind_of[1], (err) => {
  125. if (err) {
  126. console.log(err);
  127. }
  128. })
  129. fs.rm(kind_of[3], (err) => {
  130. if (err) {
  131. console.log(err);
  132. }
  133. })
  134. fs.rm(uuid, (err) => {
  135. if (err) {
  136. console.log(err);
  137. }
  138. })
  139. try {
  140. fs.rmSync("tmp/" + uuid)
  141. fs.rmSync("tmp/" + uuid + ".webp")
  142. } catch (err) {
  143. }
  144. if (req.body.email !== undefined && req.body.email !== "") {
  145. console.log(req.body.email)
  146. transporter.sendMail({
  147. from: '"xiey0" <xiey0@qq.com>',
  148. to: req.body.email,
  149. subject: "你的音频已处理完成。",
  150. text: "你的音频已处理完成。",
  151. html: fs.readFileSync("./Template.html", "utf8").toString().replace("{song_name}", req.body.name).replace("{href_link}", "https://andyxie.cn:4000/player?play=" + uuid).replace("{kind}", Kind[req.body.kind]).replace("{album}", req.body.albumName)
  152. }).then((result) => {
  153. console.log("Message sent: %s", result.messageId)
  154. })
  155. }
  156. currentTask.shift();
  157. console.log(queue.contents)
  158. console.log(currentTask)
  159. queue.next()
  160. })
  161. }
  162. app.get('/queue', (req, res) => {
  163. res.header("Access-Control-Allow-Origin", "*");
  164. res.end(JSON.stringify(currentTask));
  165. })
  166. app.post('/submit', SubmitWrapper)
  167. async function SubmitWrapper(req, res) {
  168. // TODO
  169. // May extract logic for dupe check in the future.
  170. if(req.body.name !== undefined && req.body.name !== "" && req.body.name !== null){
  171. db.execute(("SELECT uuid, song_name, album_name, artist, kind FROM instrunet_entry WHERE song_name = ? and artist = ? and kind = ?"), [await converters2t.convertPromise(req.body.name), await converters2t.convertPromise(req.body.artist), req.body.kind], async (err, rowsT) => {
  172. db.execute("SELECT uuid, song_name, album_name, artist, kind FROM instrunet_entry WHERE song_name = ? and artist = ? and kind = ?", [await convertert2s.convertPromise(req.body.name), await convertert2s.convertPromise(req.body.artist), req.body.kind], (err, rowsS) => {
  173. let dedupe = [];
  174. rowsT.forEach(row => {
  175. dedupe = dedupe.concat(row);
  176. })
  177. rowsS.forEach(row => {
  178. if (JSON.stringify(dedupe).indexOf(JSON.stringify(row)) === -1) {
  179. dedupe = dedupe.concat(row);
  180. }
  181. })
  182. if (dedupe.length === 0) {
  183. // Verify
  184. if (req.body.file.substring(0, 5) !== "data:") {
  185. res.status(500).header("Access-Control-Allow-Origin", "*").end("想都别想");
  186. return
  187. }
  188. for (const item of currentTask) {
  189. if (req.body.name === item.name) {
  190. if (req.body.albumName === item.albumName) {
  191. if (req.body.kind === item.kind) {
  192. res.header("Access-Control-Allow-Origin", "*");
  193. res.statusCode = 500
  194. res.end("傻逼,重复了。请在盲目上传之前看看库里有没有好么傻逼?")
  195. return
  196. }
  197. }
  198. }
  199. }
  200. for (let prop of [req.body.name, req.body.albumName, req.body.artist]) {
  201. if (prop === undefined || prop === "" || prop === null) {
  202. res.status(500).header("Access-Control-Allow-Origin", "*").end("想都别想");
  203. return
  204. }
  205. }
  206. if (req.body.link === undefined) {
  207. req.body.link = ""
  208. }
  209. queue.add(() => {
  210. Submit(req)
  211. })
  212. currentTask.push({
  213. name: req.body.name,
  214. albumName: req.body.albumName,
  215. kind: req.body.kind,
  216. artist: req.body.artist,
  217. email: req.body.email !== undefined ? req.body.email : null,
  218. })
  219. console.log(queue.contents)
  220. console.log(currentTask)
  221. if (currentTask.length === 1) {
  222. queue.next()
  223. }
  224. res.header("Access-Control-Allow-Origin", "*");
  225. res.end("api_success")
  226. } else {
  227. res.header("Access-Control-Allow-Origin", "*");
  228. res.statusCode = 500
  229. res.end("傻逼,重复了。请在盲目上传之前看看库里有没有好么傻逼?")
  230. }
  231. })
  232. })
  233. }else{
  234. res.header("Access-Control-Allow-Origin", "*");
  235. res.end("api_success")
  236. }
  237. }
  238. app.post('/lyric', async (req, res) => {
  239. let name = req.body.name
  240. let artist = req.body.artist;
  241. let album = req.body.albumName;
  242. let lrc = null;
  243. await fetchThatShit()
  244. async function fetchThatShit() {
  245. try {
  246. let fetched = (await (await fetch(`http://192.168.1.166:28883/jsonapi?title=${convertert2s.convertSync(name)}&artist=${convertert2s.convertSync(artist)}&album=${convertert2s.convertSync(album)}`)).text())
  247. lrc = fetched
  248. } catch (err) {
  249. await fetchThatShit()
  250. }
  251. }
  252. res.header("Access-Control-Allow-Origin", "*");
  253. res.end(lrc)
  254. })
  255. app.options('/lyric', async (req, res) => {
  256. res.header("Access-Control-Allow-Origin", "*");
  257. res.header("Access-Control-Allow-Headers", "Content-Type");
  258. res.end()
  259. })
  260. app.options('/submit', function (req, res) {
  261. res.header("Access-Control-Allow-Origin", "*");
  262. res.header("Access-Control-Allow-Headers", "Content-Type");
  263. res.end()
  264. })
  265. app.post('/search_api', async function (req, res) {
  266. db.execute("SELECT uuid, song_name, album_name, artist, kind FROM instrunet_entry WHERE song_name like ? or album_name like ? or artist like ?", [`%${await converters2t.convertPromise(req.body.searchStr)}%`, `%${await converters2t.convertPromise(req.body.searchStr)}%`, `%${await converters2t.convertPromise(req.body.searchStr)}%`], async (err, rowsT) => {
  267. db.execute("SELECT uuid, song_name, album_name, artist, kind FROM instrunet_entry WHERE song_name like ? or album_name like ? or artist like ?", [`%${await convertert2s.convertPromise(req.body.searchStr)}%`, `%${await convertert2s.convertPromise(req.body.searchStr)}%`, `%${await convertert2s.convertPromise(req.body.searchStr)}%`], (err, rowsS) => {
  268. try {
  269. let prepare = [];
  270. rowsT.forEach(row => {
  271. prepare = prepare.concat(row);
  272. })
  273. rowsS.forEach(row => {
  274. if (JSON.stringify(prepare).indexOf(JSON.stringify(row)) === -1) {
  275. prepare = prepare.concat(row);
  276. }
  277. })
  278. for (let obj of prepare) {
  279. obj.stroke = obj.song_name[0].stroke() // Problematic as shit. Do not use.
  280. obj.spell = obj.song_name.spell()
  281. }
  282. sortArray(prepare, {
  283. by: 'spell'
  284. })
  285. res.header("Access-Control-Allow-Origin", "*");
  286. res.end(JSON.stringify(prepare));
  287. } catch (e) {
  288. console.log(e)
  289. }
  290. });
  291. })
  292. })
  293. app.options('/search_api', function (req, res) {
  294. res.header("Access-Control-Allow-Origin", "*");
  295. res.header("Access-Control-Allow-Headers", "Content-Type");
  296. res.end()
  297. })
  298. app.get("/getSingle", function (req, res) {
  299. let uuid = crypto.randomUUID()
  300. if (req.query.id) {
  301. if (req.query.albumcover === "true") {
  302. db.execute("SELECT albumcover FROM instrunet_entry WHERE uuid = ?", [req.query.id], async function (err, rows) {
  303. if (err) {
  304. console.log(err);
  305. }
  306. res.contentType("application/json");
  307. res.header("Access-Control-Allow-Origin", "*");
  308. res.header("Access-Control-Allow-Headers", "Content-Type");
  309. if (rows[0] !== undefined) {
  310. if (rows[0].albumcover !== null) {
  311. if (!fs.existsSync("tmp")) {
  312. fs.mkdirSync("tmp")
  313. }
  314. fs.writeFileSync("tmp/" + uuid, rows[0].albumcover);
  315. await webp.cwebp("tmp/" + uuid, "tmp/" + uuid + ".webp", "-q 50 -mt", "-v")
  316. rows[0].albumcover = fs.readFileSync("tmp/" + uuid + ".webp")
  317. }
  318. }
  319. res.end(JSON.stringify(rows[0]));
  320. try {
  321. fs.rmSync("tmp/" + uuid)
  322. fs.rmSync("tmp/" + uuid + ".webp")
  323. } catch (err) {
  324. }
  325. })
  326. } else
  327. db.execute("SELECT song_name, album_name, artist, kind FROM instrunet_entry WHERE uuid = ?", [req.query.id], async function (err, rows) {
  328. if (err) {
  329. console.log(err);
  330. }
  331. res.contentType("application/json");
  332. res.header("Access-Control-Allow-Origin", "*");
  333. res.header("Access-Control-Allow-Headers", "Content-Type");
  334. res.end(JSON.stringify(rows[0]));
  335. })
  336. } else {
  337. res.contentType("application/json");
  338. res.header("Access-Control-Allow-Origin", "*");
  339. res.header("Access-Control-Allow-Headers", "Content-Type");
  340. res.end("{}")
  341. }
  342. })
  343. // 163
  344. app.options('/ncm/url', function (req, res) {
  345. res.header("Access-Control-Allow-Origin", "*");
  346. res.header("Access-Control-Allow-Headers", "Content-Type");
  347. res.end()
  348. })
  349. app.post("/ncm/url", function (req, res) {
  350. if (Number.isNaN(Number(req.body.id))) {
  351. res.status(500).header("Access-Control-Allow-Origin", "*").end("格式错误");
  352. return
  353. }
  354. if (req.body.id !== undefined && req.body.kind !== undefined) {
  355. try {
  356. let id = req.body.id
  357. fetch(ncmAPIUrl + "/song/download/url/v1?id=" + id + "&level=hires", {
  358. headers: {
  359. Cookie: "MUSIC_U=0087F9D8E102A1C1661EBE1792412F3351DA64D1BD3D862BA77E45E9024524725F3A1983345D9B5A4014C725D19C069DD71081F6FE3659F9E1FD412DC427FB809FAF7789AEEA10E9DE6F06C58D1959BA209D2A83C3FA753261036C4CFD0D143B6C7748B8A6D2DD5C2E96E75D1E847E4AAE035CB2C86B175D9AFC6A164C522ED76E24AE654740AB6BAF5B29597F7E3B0158B2EC1C37F2688279871873FA7ADAEF8280A059E84C4BBFB9E4F225F9A2065DF652247D5496587A7B1E3D35DB0CD3F825C06FE5BFE5CFEF1770847099704360504B73C9B396E37CECE4F9DDEE6001588C3C4F5B2861D9ADF339FC47DD480858CA800620785EA032215B63B81025304DB3331F384793FF8EE681247E34C7931176F2F618B66C122F0602F1EA15F963E422DEC79C257F3577A197BECE71E316C751C3B9F5F3CD07BFDC0270A287A1BB6576"
  360. }
  361. }).then(async result => {
  362. if (result.status === 200 || result.status === 304) {
  363. let result_json = await result.json()
  364. if (result_json.data.url !== null) {
  365. let infos = await (await fetch(ncmAPIUrl + "/song/detail?ids=" + id)).json();
  366. req.body.file = "data:audio/flac;base64," + Buffer.from(await (await fetch(result_json.data.url)).arrayBuffer()).toString("base64")
  367. req.body.name = infos.songs[0].name;
  368. req.body.albumName = infos.songs[0].al.name
  369. req.body.albumCover = infos.songs[0].al.picUrl
  370. req.body.link = result_json.data.url
  371. req.body.artist = infos.songs[0].ar[0].name
  372. /// Complete
  373. SubmitWrapper(req, res)
  374. } else {
  375. res.status(500).header("Access-Control-Allow-Origin", "*").end("不存在");
  376. }
  377. } else {
  378. res.status(404).header("Access-Control-Allow-Origin", "*").send("未找到或出现错误")
  379. }
  380. })
  381. } catch (err) {
  382. res.status(500).header("Access-Control-Allow-Origin", "*");
  383. console.log(err)
  384. }
  385. } else {
  386. res.contentType("application/json");
  387. res.header("Access-Control-Allow-Origin", "*");
  388. res.header("Access-Control-Allow-Headers", "Content-Type");
  389. res.end("傻逼。")
  390. }
  391. })
  392. app.get("/favicon.ico", function (req, res) {
  393. res.end("");
  394. })
  395. let availCache = {};
  396. // setInterval(() => {
  397. // availCache = {};
  398. // }, 1800000)
  399. // Fetch
  400. app.get('/:uuid', function (req, res) {
  401. let uuid = req.params.uuid;
  402. function Provider(err, rows) {
  403. try {
  404. availCache[uuid] = rows[0]
  405. res.contentType("audio/mp3");
  406. res.header("Access-Control-Allow-Origin", "*");
  407. res.header("Access-Control-Allow-Headers", "Content-Type");
  408. res.header('Content-Disposition', `attachment; filename="${encodeURI(availCache[uuid].song_name)}.mp3"`);
  409. /** @type {ArrayBuffer}*/
  410. res.sendSeekable(availCache[uuid].databinary)
  411. } catch (e) {
  412. res.contentType("text/plain");
  413. res.status(500).header("Access-Control-Allow-Origin", "*").end("Err.");
  414. console.log(e)
  415. console.log("Triggered err");
  416. }
  417. }
  418. if (availCache[uuid] !== undefined) {
  419. res.contentType("audio/mp3");
  420. res.header("Access-Control-Allow-Origin", "*");
  421. res.header("Access-Control-Allow-Headers", "Content-Type");
  422. res.header("Access-Control-Allow-Origin", "*");
  423. res.header('Content-Disposition', `attachment; filename="${encodeURI(availCache[uuid].song_name)}.mp3"`);
  424. res.sendSeekable(availCache[uuid].databinary)
  425. } else {
  426. db.execute("SELECT song_name, databinary FROM instrunet_entry WHERE uuid = ?", [uuid], Provider)
  427. }
  428. })
  429. if (argv.https === "true") {
  430. https.createServer({
  431. key: fs.readFileSync('andyxie.cn.key'), cert: fs.readFileSync('andyxie.cn.pem')
  432. }, app).listen(8080)
  433. console.log("Listening on port 8080 with TLS")
  434. } else {
  435. app.listen(8080)
  436. console.log("Listening on port 8080")
  437. }