quark_api.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. /**
  2. * File: /workspaces/TVSpider/lib/quark_api.js
  3. * Project: /workspaces/TVSpider
  4. * Created Date: Monday, May 20th 2024, 6:38:12 am
  5. * Author: jade
  6. * -----
  7. * Last Modified: Tue May 21 2024
  8. * Modified By: jade
  9. * -----
  10. * Copyright (c) 2024 samples
  11. * ------------------------------------
  12. * Javascript will save your soul!
  13. */
  14. import {_,Crypto} from "../lib/cat.js";
  15. import * as Utils from "../lib/utils.js"
  16. import {Item} from "../lib/quark_object.js"
  17. class Quark{
  18. constructor(){
  19. this.apiUrl = "https://drive-pc.quark.cn/1/clouddrive/"
  20. this.cookie = ""
  21. this.ckey = ""
  22. this.shareTokenCache = {}
  23. this.pr = "pr=ucpro&fr=pc"
  24. this.subtitleExts = ['.srt', '.ass', '.scc', '.stl', '.ttml'];
  25. this.saveFileIdCaches = {}
  26. this.saveDirId = null
  27. this.saveDirName = 'TV';
  28. this.isVip = false;
  29. }
  30. async initQuark(cookie) {
  31. this.ckey = Crypto.enc.Hex.stringify(Crypto.MD5(cookie)).toString();
  32. this.cookie = cookie
  33. this.isVip = await this.getVip()
  34. }
  35. getHeaders(){
  36. return {
  37. 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) quark-cloud-drive/2.5.20 Chrome/100.0.4896.160 Electron/18.3.5.4-b478491100 Safari/537.36 Channel/pckk_other_ch',
  38. 'Referer': 'https://pan.quark.cn/',
  39. "Content-Type":"application/json",
  40. "Cookie":this.cookie,
  41. "Host":"drive-pc.quark.cn"
  42. };
  43. }
  44. async api(url,data,retry,method){
  45. const leftRetry = retry || 3;
  46. let resp = await req(this.apiUrl + url,{
  47. method:method || "post",
  48. data:data,
  49. headers:this.getHeaders()
  50. })
  51. if (resp.headers['set-cookie']) {
  52. const puus = [resp.headers['set-cookie']].join(';;;').match(/__puus=([^;]+)/);
  53. if (puus) {
  54. if (this.cookie.match(/__puus=([^;]+)/)[1] != puus[1]) {
  55. this.cookie = this.cookie.replace(/__puus=[^;]+/, `__puus=${puus[1]}`);
  56. }
  57. }
  58. }
  59. if (resp.code !== 200 && leftRetry > 0) {
  60. Utils.sleep(1)
  61. return await this.api(url, data, leftRetry - 1);
  62. }
  63. return JSON.parse(resp.content) || {};
  64. }
  65. getShareData(url) {
  66. let regex = /https:\/\/pan\.quark\.cn\/s\/([^\\|#/]+)/;
  67. let matches = regex.exec(url);
  68. if (matches) {
  69. return {
  70. shareId: matches[1],
  71. folderId: '0',
  72. };
  73. }
  74. return null;
  75. }
  76. async getVip(){
  77. const listData = await this.api(`member?pr=ucpro&fr=pc&uc_param_str=&fetch_subscribe=true&_ch=home&fetch_identity=true`, null,null, 'get');
  78. if (listData.data.member_type==="EXP_SVIP"){
  79. return true
  80. }else{
  81. return false
  82. }
  83. }
  84. getPlayFormatList(){
  85. if(this.isVip){
  86. return ["4K","超清","高清","普画"]
  87. }else{
  88. return ["普画"]
  89. }
  90. }
  91. getPlayFormtQuarkList(){
  92. if(this.isVip){
  93. return ["4k","2k","super","high","normal","low"]
  94. }{
  95. return ["low"]
  96. }
  97. }
  98. async getShareToken(shareData) {
  99. if (!this.shareTokenCache[shareData.shareId]) {
  100. delete this.shareTokenCache[shareData.shareId];
  101. const shareToken = await this.api(`share/sharepage/token?${this.pr}`, {
  102. pwd_id: shareData.shareId,
  103. passcode: shareData.sharePwd || '',
  104. });
  105. if (shareToken.data && shareToken.data.stoken) {
  106. this.shareTokenCache[shareData.shareId] = shareToken.data;
  107. }
  108. }
  109. }
  110. async listFile (shareIndex,shareData,videos,subtitles,shareId, folderId, page) {
  111. const prePage = 200;
  112. page = page || 1;
  113. const listData = await this.api(`share/sharepage/detail?${this.pr}&pwd_id=${shareId}&stoken=${encodeURIComponent(this.shareTokenCache[shareId].stoken)}&pdir_fid=${folderId}&force=0&_page=${page}&_size=${prePage}&_sort=file_type:asc,file_name:asc`, null,null, 'get');
  114. if (!listData.data) return [];
  115. const items = listData.data.list;
  116. if (!items) return [];
  117. const subDir = [];
  118. for (const item of items) {
  119. if (item.dir === true) {
  120. subDir.push(item);
  121. } else if (item.file === true && item.obj_category === 'video') {
  122. if (item.size < 1024 * 1024 * 5) continue;
  123. item.stoken = this.shareTokenCache[shareData.shareId].stoken;
  124. videos.push(Item.objectFrom(item,shareData.shareId,shareIndex));
  125. } else if (item.type === 'file' && this.subtitleExts.some((x) => item.file_name.endsWith(x))) {
  126. subtitles.push(Item.objectFrom(item,shareData,shareIndex));
  127. }
  128. }
  129. if (page < Math.ceil(listData.metadata._total / prePage)) {
  130. const nextItems = await this.listFile(shareIndex,shareData.shareId,videos,subtitles,shareId, folderId, page + 1);
  131. for (const item of nextItems) {
  132. items.push(item);
  133. }
  134. }
  135. for (const dir of subDir) {
  136. const subItems = await this.listFile(shareIndex,shareData,videos,subtitles,shareId, dir.fid);
  137. for (const item of subItems) {
  138. items.push(item);
  139. }
  140. }
  141. return items;
  142. };
  143. findBestLCS(mainItem, targetItems) {
  144. const results = [];
  145. let bestMatchIndex = 0;
  146. for (let i = 0; i < targetItems.length; i++) {
  147. const currentLCS = Utils.lcs(mainItem.name, targetItems[i].name);
  148. results.push({ target: targetItems[i], lcs: currentLCS });
  149. if (currentLCS.length > results[bestMatchIndex].lcs.length) {
  150. bestMatchIndex = i;
  151. }
  152. }
  153. const bestMatch = results[bestMatchIndex];
  154. return { allLCS: results, bestMatch: bestMatch, bestMatchIndex: bestMatchIndex };
  155. }
  156. async getFilesByShareUrl(shareIndex,shareInfo,videos,subtitles){
  157. const shareData = typeof shareInfo === 'string' ? this.getShareData(shareInfo) : shareInfo;
  158. if (!shareData) return [];
  159. await this.getShareToken(shareData);
  160. if (!this.shareTokenCache[shareData.shareId]) return [];
  161. await this.listFile(shareIndex,shareData,videos,subtitles,shareData.shareId, shareData.folderId);
  162. if (subtitles.length > 0) {
  163. videos.forEach((item) => {
  164. var matchSubtitle = this.findBestLCS(item, subtitles);
  165. if (matchSubtitle.bestMatch) {
  166. item.subtitle = matchSubtitle.bestMatch.target;
  167. }
  168. });
  169. }
  170. }
  171. clean(){
  172. const saves = Object.keys(this.saveFileIdCaches);
  173. for (const save of saves) {
  174. delete this.saveFileIdCaches[save];
  175. }
  176. }
  177. async clearSaveDir() {
  178. const listData = await this.api(`file/sort?${this.pr}&pdir_fid=${this.saveDirId}&_page=1&_size=200&_sort=file_type:asc,updated_at:desc`, {}, {}, 'get');
  179. if (listData.data && listData.data.list && listData.data.list.length > 0) {
  180. await this.api(`file/delete?${this.pr}`, {
  181. action_type: 2,
  182. filelist: listData.data.list.map((v) => v.fid),
  183. exclude_fids: [],
  184. });
  185. }
  186. }
  187. async createSaveDir(clean) {
  188. if (this.saveDirId) {
  189. // 删除所有子文件
  190. if (clean) await this.clearSaveDir();
  191. return;
  192. }
  193. const listData = await this.api(`file/sort?${this.pr}&pdir_fid=0&_page=1&_size=200&_sort=file_type:asc,updated_at:desc`, {}, {}, 'get');
  194. if (listData.data && listData.data.list)
  195. for (const item of listData.data.list) {
  196. if (item.file_name === this.saveDirName) {
  197. this.saveDirId = item.fid;
  198. await this.clearSaveDir();
  199. break;
  200. }
  201. }
  202. if (!this.saveDirId) {
  203. const create = await this.api(`file?${this.pr}`, {
  204. pdir_fid: '0',
  205. file_name: this.saveDirName,
  206. dir_path: '',
  207. dir_init_lock: false,
  208. });
  209. if (create.data && create.data.fid) {
  210. this.saveDirId = create.data.fid;
  211. }
  212. }
  213. }
  214. async save(shareId, stoken, fileId, fileToken, clean) {
  215. await this.createSaveDir(clean);
  216. if (clean) {
  217. this.clean()
  218. }
  219. if (!this.saveDirId) return null;
  220. if (!stoken) {
  221. await this.getShareToken({
  222. shareId: shareId,
  223. });
  224. if (!this.shareTokenCache[shareId]) return null;
  225. }
  226. const saveResult = await this.api(`share/sharepage/save?${this.pr}`, {
  227. fid_list: [fileId],
  228. fid_token_list: [fileToken],
  229. to_pdir_fid: this.saveDirId,
  230. pwd_id: shareId,
  231. stoken: stoken || this.shareTokenCache[shareId].stoken,
  232. pdir_fid: '0',
  233. scene: 'link',
  234. });
  235. if (saveResult.data && saveResult.data.task_id) {
  236. let retry = 0;
  237. // wait task finish
  238. while (true) {
  239. const taskResult = await this.api(`task?${this.pr}&task_id=${saveResult.data.task_id}&retry_index=${retry}`, {}, {}, 'get');
  240. if (taskResult.data && taskResult.data.save_as && taskResult.data.save_as.save_as_top_fids && taskResult.data.save_as.save_as_top_fids.length > 0) {
  241. return taskResult.data.save_as.save_as_top_fids[0];
  242. }
  243. retry++;
  244. if (retry > 2) break;
  245. Utils.sleep(1);
  246. }
  247. }
  248. return false;
  249. }
  250. async getLiveTranscoding(shareId, stoken, fileId, fileToken,flag) {
  251. if (!this.saveFileIdCaches[fileId]) {
  252. const saveFileId = await this.save(shareId, stoken, fileId, fileToken, true);
  253. if (!saveFileId) return null;
  254. this.saveFileIdCaches[fileId] = saveFileId;
  255. }
  256. const transcoding = await this.api(`file/v2/play?${this.pr}`, {
  257. fid: this.saveFileIdCaches[fileId],
  258. resolutions: 'normal,low,high,super,2k,4k',
  259. supports: 'fmp4',
  260. });
  261. if (transcoding.data && transcoding.data.video_list) {
  262. let flag_id = flag.split("-").slice(-1)[0]
  263. let index = Utils.findAllIndexes(this.getPlayFormatList(),flag_id);
  264. let quarkFormat = this.getPlayFormtQuarkList()[index]
  265. for (const video of transcoding.data.video_list){
  266. if (video.resolution === quarkFormat){
  267. return video.video_info.url
  268. }
  269. }
  270. return transcoding.data.video_list[index].video_info.url
  271. }
  272. return null;
  273. }
  274. async getDownload(shareId, stoken, fileId, fileToken, clean) {
  275. if (!this.saveFileIdCaches[fileId]) {
  276. const saveFileId = await this.save(shareId, stoken, fileId, fileToken, clean);
  277. if (!saveFileId) return null;
  278. this.saveFileIdCaches[fileId] = saveFileId;
  279. }
  280. const down = await this.api(`file/download?${this.pr}&uc_param_str=`, {
  281. fids: [this.saveFileIdCaches[fileId]],
  282. });
  283. if (down.data) {
  284. return down.data[0];
  285. }
  286. return null;
  287. }
  288. }
  289. export {Quark}