ali_api.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677
  1. /*
  2. * @Author: samples jadehh@live.com
  3. * @Date: 2023-12-14 11:03:04
  4. * @LastEditors: samples jadehh@live.com
  5. * @LastEditTime: 2023-12-14 11:03:04
  6. * @FilePath: /lib/ali_api.js
  7. * @Description: 阿里云盘Api
  8. */
  9. import {_, jinja2} from "./cat.js";
  10. import * as Utils from "./utils.js";
  11. import {JadeLogging} from "./log.js";
  12. import {
  13. Code, Drive, getHeader, getOAuthCache, getUserCache, Item, OAuth, post, postJson, Sub, User, CLIENT_ID
  14. } from "./ali_object.js";
  15. let quality = {}, tempIds = [], shareToken = "", shareId = "", oauth = new OAuth(), user = new User(),
  16. driveInfo = new Drive(), tmpFolderName = "TV", curTmpFolderFileId = "",
  17. JadeLog = new JadeLogging("阿里云盘", "INFO");
  18. async function initSome() {
  19. let user_cache_str = await getUserCache();
  20. user = User.objectFrom(user_cache_str);
  21. if (!_.isEmpty(user.getRefreshToken())) {
  22. await JadeLog.info("读取用户缓存成功", true);
  23. } else {
  24. await JadeLog.error("读取用户缓存失败", true);
  25. }
  26. let oauth_cache_str = await getOAuthCache();
  27. oauth = OAuth.objectFrom(oauth_cache_str);
  28. if (!_.isEmpty(oauth.getAccessToken())) {
  29. await JadeLog.info("读取授权成功", true)
  30. } else {
  31. await JadeLog.error("读取授权失败", true)
  32. }
  33. // quality = {
  34. // "4K": "UHD", "2k": "QHD", "超清": "FHD", "高清": "HD", "标清": "SD", "流畅": "LD"
  35. // };
  36. quality = {
  37. "4K": "UHD", "2k": "QHD", "超清": "QHD", "高清": "HD", "标清": "SD", "流畅": "LD"
  38. };
  39. await JadeLog.info("阿里Api初始化完成")
  40. }
  41. async function getTempFileId() {
  42. curTmpFolderFileId = await createTmpFolder();
  43. }
  44. async function clearFile() {
  45. try {
  46. await deleteTmpFolderAndRecreate();
  47. } catch (e) {
  48. await JadeLog.error("清空缓存文件失败,失败原因为:{}" + e)
  49. }
  50. await cleanRecord()
  51. }
  52. async function cleanRecord() {
  53. await local.set("file", "file_id", JSON.stringify({}))
  54. }
  55. async function setShareId(share_id) {
  56. getOAuthCache().length === 0 && (await oauth.clean().save());
  57. getUserCache().length === 0 && (await user.clean().save());
  58. shareId = share_id;
  59. return await refreshShareToken();
  60. }
  61. function getHeaderAuth(shareToken) {
  62. const params = {};
  63. params["x-share-token"] = shareToken;
  64. params["X-Canary"] = "client=Android,app=adrive,version=v4.3.1";
  65. if (user.isAuthed()) {
  66. params.authorization = user.getAuthorization();
  67. }
  68. return params;
  69. }
  70. function getHeaderShare() {
  71. const params = getHeader();
  72. params["x-share-token"] = shareToken;
  73. params["X-Canary"] = "client=Android,app=adrive,version=v4.3.1";
  74. return params;
  75. }
  76. function getHeaderOpen() {
  77. const params = {};
  78. params.authorization = oauth.getAuthorization();
  79. return params;
  80. }
  81. function aliExpection(data_str) {
  82. if (data_str.indexOf("TooManyRequests") > -1) {
  83. Utils.sleep(1)
  84. return {code: 429, content: data_str}
  85. } else if (data_str.indexOf("AccessTokenInvalid") > -1) {
  86. return {code: 400, content: data_str}
  87. } else if (data_str.indexOf("AccessTokenExpired") > -1) {
  88. return {code: 401, content: data_str}
  89. } else if (data_str.indexOf("BadRequest") > -1) {
  90. return {code: 402, content: data_str}
  91. } else if (data_str.indexOf("NotFound.File") > -1 || data_str.indexOf("ForbiddenFileInTheRecycleBin") > -1) {
  92. return {code: 403, content: data_str}
  93. } else if (data_str.indexOf("user not allowed access drive") > -1){
  94. return {code: 404, content: data_str}
  95. } else if (data_str.indexOf("ForbiddenNoPermission.File") > -1) {
  96. return {code: 500, content: data_str}
  97. } else if (data_str.indexOf("InvalidParameter.ToParentFileId") > -1) {
  98. return {code: 501, content: data_str}
  99. } else if (data_str.indexOf("NotFound.ParentFileId") > -1) {
  100. return {code: 502, content: data_str}
  101. } else if (data_str.indexOf("The resource drive has exceeded the limit. File size exceeded drive capacity") > -1) {
  102. return {code: 503, content: data_str}
  103. }else if (data_str.indexOf("The resource drive has exceeded the limit. File size exceeded drive capacity") > -1) {
  104. return {code: 503, content: data_str}
  105. }
  106. return {code: 200, content: data_str}
  107. }
  108. async function alistManyRequest(data_str) {
  109. if (!(data_str.indexOf("Too Many Requests") > -1)) {
  110. return false;
  111. }
  112. await oauth.clean().save();
  113. return true;
  114. }
  115. // Alist Token获取
  116. async function alist(url_param, params) {
  117. let url = "https://api-cf.nn.ci/alist/ali_open/" + url_param;
  118. let response = await postJson(url, params, getHeader()), response_content = response.content;
  119. if (await alistManyRequest(response_content)) {
  120. await JadeLog.error(`Alist授权Token失败,失败原因为:太多请求,失败详情为:${response_content}`)
  121. return false;
  122. }
  123. oauth = await OAuth.objectFrom(response_content).save();
  124. return true;
  125. }
  126. // 阿里云盘用户Api
  127. async function auth(url, params, shareToken, retry) {
  128. url = url.startsWith("https") ? url : "https://api.aliyundrive.com/" + url;
  129. let response = await postJson(url, params, getHeaderAuth(shareToken));
  130. await JadeLog.debug(`正在请求需要阿里登录的url:${url},参数为:${JSON.stringify(params)}`)
  131. response = aliExpection(response.content)
  132. if (retry && (response.code === 400)) {
  133. await JadeLog.error("登录阿里云盘失败,失败原因为:登录Token无效,准备重新授权,失败详情:" + response.content)
  134. await refreshAccessToken("")
  135. return await auth(url, params, shareToken, false);
  136. }
  137. await JadeLog.debug(`完成请求需要阿里登录的url:${url},参数为:${JSON.stringify(params)},请求结果为${response.content}`)
  138. return response.content;
  139. }
  140. // 需要授权的Api
  141. async function oauthFunc(url, params, retry) {
  142. url = url.startsWith("https") ? url : "https://open.aliyundrive.com/adrive/v1.0/" + url;
  143. await JadeLog.debug(`正在请求需要阿里授权的url:${url},参数为:${JSON.stringify(params)}`)
  144. let open_header = getHeaderOpen();
  145. let response = await postJson(url, params, open_header);
  146. response = aliExpection(response.content)
  147. if (retry && (response.code === 400 || response.code === 401 || response.code === 429 || response.code === 402 || response.code === 403 || response.code === 404)) {
  148. if (response.code === 400) {
  149. await JadeLog.error("阿里授权失败,失败原因为:授权Token无效,准备重新授权,失败详情:" + response.content)
  150. await activateRefreshOpenToken()
  151. } else if (response.code === 401) {
  152. await JadeLog.error("阿里授权失败,失败原因为:授权Token失效,准备重新授权,失败详情:" + response.content)
  153. await activateRefreshOpenToken()
  154. } else if (response.code === 402) {
  155. await JadeLog.error("阿里授权失败,失败原因为:授权Token失效,准备重新授权,失败详情:" + response.content)
  156. return await oauthFunc(url, params, true)
  157. } else if (response.code === 403) {
  158. await JadeLog.error("阿里授权失败,失败原因为:没有找到缓存文件,失败详情:" + response.content)
  159. await cleanRecord()
  160. return "retry"
  161. }else if (response.code === 404) {
  162. await JadeLog.error("阿里授权失败,失败原因为:用户没有权限" + response.content)
  163. return await oauthFunc(url, params, true)
  164. }else if (response.code === 429) {
  165. await JadeLog.error(`正在请求需要阿里授权的url:${url},请求过于频繁,稍后重试,10分钟后再重试`)
  166. Utils.sleep(10 * 60)
  167. return await oauthFunc(url, params, true)
  168. }
  169. return await oauthFunc(url, params, false)
  170. }
  171. await JadeLog.debug(`完成请求需要阿里授权的url:${url},参数为:${JSON.stringify(params)},请求结果为:${JSON.stringify(response)}`)
  172. return response.content;
  173. }
  174. async function shareFunc(url, params) {
  175. url = url.startsWith("https") ? url : "https://api.aliyundrive.com/" + url;
  176. let headers = getHeaderShare(), response = await postJson(url, params, headers);
  177. return response.content;
  178. }
  179. //主动刷新授权Token
  180. async function activateRefreshOpenToken() {
  181. await oauth.clean().save()
  182. await refreshOpenToken()
  183. }
  184. async function refreshShareToken() {
  185. try {
  186. let params = {};
  187. params.share_id = shareId;
  188. params.share_pwd = "";
  189. let response_content = await post("v2/share_link/get_share_token", params),
  190. response_json = JSON.parse(response_content);
  191. if (response_json["code"] === "ShareLink.Cancelled") {
  192. await JadeLog.error("分享链接被取消了")
  193. }
  194. shareToken = response_json.share_token;
  195. return shareToken
  196. } catch (e) {
  197. await JadeLog.error("刷新Share Token失败" + e)
  198. }
  199. }
  200. //支持切换Token
  201. async function refreshAccessToken(token) {
  202. try {
  203. if (_.isEmpty(user.getAccessToken()) || user.getRefreshToken() !== token) {
  204. let refresh_token_params = {};
  205. refresh_token_params.refresh_token = user.getRefreshToken();
  206. refresh_token_params.grant_type = "refresh_token";
  207. await JadeLog.info(`准备登录阿里云盘,登录Token为:${user.getRefreshToken()}`)
  208. let response_conetent = await post("https://auth.aliyundrive.com/v2/account/token", refresh_token_params);
  209. if (response_conetent.indexOf("InvalidParameter.RefreshToken") > 1 || _.isEmpty(response_conetent)) {
  210. if (_.isEmpty(response_conetent)) {
  211. await JadeLog.error(`登录阿里云盘失败,登录Token为:${user.getRefreshToken()},失败原因为:检查Token是否正确`)
  212. } else {
  213. await JadeLog.error(`登录阿里云盘失败,登录Token为:${user.getRefreshToken()},失败原因为:检查Token是否正确,返回结果为:${response_conetent}`)
  214. }
  215. } else {
  216. await JadeLog.info(`登录阿里云盘成功,登录Token为:${user.getRefreshToken()}`)
  217. user = await User.objectFrom(response_conetent).save();
  218. }
  219. } else {
  220. await JadeLog.info(`阿里云盘已登录,无需重复登录,登录Token为:${user.getRefreshToken()}`)
  221. }
  222. return true;
  223. } catch (e) {
  224. await JadeLog.error(`登录阿里云盘失败,登录Token为:${user.getRefreshToken()},失败原因为:${e}`)
  225. await user.clean().save();
  226. return true;
  227. }
  228. }
  229. async function oauthRequest() {
  230. try {
  231. let params = {};
  232. params.authorize = 1;
  233. params.scope = "user:base,file:all:read,file:all:write";
  234. let url = "https://open.aliyundrive.com/oauth/users/authorize?client_id=" + CLIENT_ID + "&redirect_uri=https://alist.nn.ci/tool/aliyundrive/callback&scope=user:base,file:all:read,file:all:write&state="
  235. await JadeLog.debug(`正在请求获取阿里授权码的url:${url},参数为:${params}`)
  236. let response_str = await auth(url, params, shareToken, true);
  237. await JadeLog.debug(`完成请求获取阿里授权码的url:${url},参数为:${params},返回值为:${response_str}`)
  238. if (_.isEmpty(response_str) || response_str.indexOf("AccessTokenInvalid") > -1) {
  239. if (_.isEmpty(response_str)) {
  240. await JadeLog.error(`请求获取阿里授权码失败,失败原因为:还未登录`)
  241. } else {
  242. await JadeLog.error(`请求获取阿里授权码失败,失败原因为:还未登录,失败详情为:${response_str}`)
  243. }
  244. } else {
  245. await JadeLog.info(`请求获取阿里授权码成功,返回值为:${response_str}`)
  246. return await oauthRedirect(Code.objectFrom(response_str).getCode());
  247. }
  248. } catch (e) {
  249. await JadeLog.error(`请求获取阿里授权失败,失败原因为:${e}`)
  250. return false;
  251. }
  252. }
  253. async function oauthRedirect(code) {
  254. try {
  255. let params = {};
  256. params.code = code;
  257. params.grant_type = "authorization_code";
  258. return await alist("code", params);
  259. } catch (e) {
  260. // // console.debug(_0x114c46);
  261. await oauth.clean().save();
  262. return false;
  263. }
  264. }
  265. async function refreshOpenToken() {
  266. try {
  267. // 刷新 Refresh Token
  268. if (_.isEmpty(oauth.getRefreshToken())) {
  269. return await oauthRequest();
  270. }
  271. // 刷新Access Token
  272. if (_.isEmpty(oauth.getAccessToken())) {
  273. let params = {};
  274. params.grant_type = "refresh_token";
  275. params.refresh_token = oauth.getRefreshToken();
  276. return await alist("token", params);
  277. }
  278. return true;
  279. } catch (e) {
  280. await JadeLog.error("刷新授权Token失败,失败原因为:" + e);
  281. await oauth.clean().save();
  282. return false;
  283. }
  284. }
  285. async function getFileByShare(index,share_token, share_url, video_item_list, sub_item_list) {
  286. let params = {};
  287. params.share_id = shareId;
  288. let file_id = share_url.split("folder/").slice(-1)[0]
  289. if (file_id.length !== 40) {
  290. file_id = ""
  291. }
  292. let response_str = await post("adrive/v3/share_link/get_share_by_anonymous", params),
  293. response_json = JSON.parse(response_str), item_file_id = getParentFileId(file_id, response_json),
  294. item = new Item(item_file_id);
  295. await listFiles(index,item, video_item_list, sub_item_list, share_token);
  296. }
  297. async function listFiles(index,item, video_item_list, sub_item_list, share_token) {
  298. return await listFilesMarker(index,item, video_item_list, sub_item_list, "", share_token);
  299. }
  300. async function listFilesMarker(index,item, video_item_list, sub_item_list, netxt_markers, share_token) {
  301. let new_item = {}, file_list = [];
  302. new_item.limit = 200;
  303. new_item.share_id = shareId;
  304. new_item.share_token = share_token
  305. new_item.parent_file_id = item.getFileId();
  306. new_item.order_by = "name";
  307. new_item.order_direction = "ASC";
  308. new_item.share_index = index
  309. if (netxt_markers.length > 0) {
  310. new_item.marker = netxt_markers;
  311. }
  312. let items = Item.objectFrom(await shareFunc("adrive/v2/file/list_by_share", new_item), shareToken,index);
  313. for (const r_item of items.getItems()) {
  314. if (r_item.getType() === "folder") {
  315. file_list.push(r_item);
  316. } else {
  317. if ((r_item.getCategory() === "video" || r_item.getCategory() === "audio")) {
  318. //判断数组中是否有file_id
  319. //
  320. let is_video_file_exists = false
  321. for (const video_item of video_item_list) {
  322. if (r_item.getFileId() === video_item.getFileId()) {
  323. is_video_file_exists = true
  324. await JadeLog.debug('视频分享文件重复,无需添加')
  325. }
  326. }
  327. if (!is_video_file_exists) {
  328. if (r_item.getCategory() === "video" && r_item.size / 1000000 > 10) {
  329. video_item_list.push(r_item.parentFunc(item.getName()));
  330. }
  331. }
  332. } else {
  333. if (Utils.isSub(r_item.getExt())) {
  334. let is_sub_file_exists = false
  335. for (const sub_item of sub_item_list) {
  336. if (r_item.getFileId() === sub_item.getFileId()) {
  337. is_sub_file_exists = true
  338. await JadeLog.debug('字幕分享文件重复,无需添加')
  339. }
  340. }
  341. if (!is_sub_file_exists) {
  342. sub_item_list.push(r_item);
  343. }
  344. }
  345. }
  346. }
  347. }
  348. items.getNextMarker().length > 0 && (await listFilesMarker(index,item, video_item_list, sub_item_list, items.getNextMarker()));
  349. for (const file of file_list) {
  350. await listFiles(index,file, video_item_list, sub_item_list);
  351. }
  352. }
  353. function getParentFileId(file_id, items) {
  354. let file_infos = items.file_infos;
  355. if (!_.isEmpty(file_id)) {
  356. return file_id;
  357. }
  358. if (file_infos.length === 0) {
  359. return "";
  360. }
  361. let item = file_infos[0];
  362. if (item.type === "folder") {
  363. return item.file_id;
  364. }
  365. if (item.type === "file" && item.category === "video") {
  366. return "root";
  367. }
  368. return "";
  369. }
  370. async function getSubs(sub_list, share_id) {
  371. let sub_url_list = [];
  372. for (const sub_str of sub_list) {
  373. if (!(sub_str.indexOf("@@@") > -1)) {
  374. continue;
  375. }
  376. let sub_split_list = sub_str.split("@@@"), sub_name = sub_split_list[0], sub_ext = sub_split_list[1],
  377. sub_file_id = sub_split_list[2], sub_url = await getDownloadUrl(sub_file_id, share_id);
  378. sub_url_list.push(Sub.create().setName(sub_name).setExt(sub_ext).setUrl(sub_url));
  379. }
  380. return sub_url_list;
  381. }
  382. async function getDriveInfo() {
  383. if (!_.isEmpty(driveInfo) && !_.isEmpty(driveInfo.default_drive_id)) {
  384. return driveInfo;
  385. }
  386. let _0x3740f3 = await oauthFunc("user/getDriveInfo", {}, true), _0x56fde5 = JSON.parse(_0x3740f3);
  387. driveInfo = {
  388. default_drive_id: _0x56fde5.default_drive_id,
  389. resource_drive_id: _0x56fde5.resource_drive_id,
  390. backup_drive_id: _0x56fde5.backup_drive_id
  391. };
  392. return driveInfo;
  393. }
  394. async function getDriveId() {
  395. if (_.isEmpty(user.getDriveId())) {
  396. let drive = await getDriveInfo();
  397. return drive.resource_drive_id;
  398. }
  399. return user.getDriveId();
  400. }
  401. async function getDownloadUrl(file_id, share_id, share_token) {
  402. let drive_id = await getDriveId();
  403. tempIds.unshift(await copy(file_id, share_id, share_token));
  404. let params = {};
  405. params.file_id = tempIds[0];
  406. params.drive_id = drive_id;
  407. if (tempIds[0] !== null) {
  408. let response_str = await oauthFunc("openFile/getDownloadUrl", params, true);
  409. if (response_str === "retry") {
  410. await JadeLog.info("尝试重新获取下载链接");
  411. return await getDownloadUrl(file_id, share_id)
  412. } else {
  413. await JadeLog.info("获取下载链接成功:返回结果为:" + response_str + "请求参数为:" + JSON.stringify(params));
  414. return JSON.parse(response_str).url;
  415. }
  416. } else {
  417. await JadeLog.error("获取下载链接失败:失败原因:请检查转存文件失败原因")
  418. return null;
  419. }
  420. }
  421. async function getVideoPreviewPlayInfo(file_id, share_id, shareToken) {
  422. let drive_id = await getDriveId();
  423. tempIds.unshift(await copy(file_id, share_id, shareToken));
  424. let params = {};
  425. params.file_id = tempIds[0];
  426. params.drive_id = drive_id;
  427. params.category = "live_transcoding";
  428. params.url_expire_sec = "14400";
  429. let response_str = await oauthFunc("openFile/getVideoPreviewPlayInfo", params, true);
  430. return JSON.parse(response_str).video_preview_play_info;
  431. }
  432. async function playerContent(file_id, share_id, share_token) {
  433. try {
  434. await JadeLog.info("正在获取原画的播放地址和字幕下载链接", true)
  435. let download_url = await getDownloadUrl(file_id, share_id, share_token);
  436. // let sub_list = await getSubs(file_id_list,share_id);
  437. await JadeLog.info("获取原画的播放地址和字幕下载链接成功", true)
  438. await JadeLog.info(`下载地址为:${download_url}`)
  439. return download_url;
  440. } catch (e) {
  441. await JadeLog.error("获取原画的播放地址和字幕下载链接失败:失败原因为:" + e);
  442. }
  443. }
  444. // 转码头的Url和字幕
  445. async function playerContentByFlag(file_id, flag, share_id, shareToken) {
  446. try {
  447. await JadeLog.info("正在获取转码后的播放地址和字幕下载链接", true)
  448. let video_preview_play_info = await getVideoPreviewPlayInfo(file_id, share_id, shareToken),
  449. video_preview_url = getPreviewUrl(video_preview_play_info, flag);
  450. // let sub_list = await getSubs(file_id_list,share_id),
  451. // sub_p_list = getSubsByPlayInfo(video_preview_play_info);
  452. // for (const sub_p of sub_p_list) {
  453. // sub_list.push(sub_p);
  454. // }
  455. await JadeLog.info("获取转码后的播放地址和字幕下载链接成功", true)
  456. await JadeLog.info(`下载地址为:${video_preview_url}`)
  457. return video_preview_url;
  458. } catch (e) {
  459. await JadeLog.error(`获取转码后的播放地址和字幕下载链接失败,失败原因为:${e}`)
  460. }
  461. }
  462. function getPreviewUrl(video_preview_play_info, flag) {
  463. if (!video_preview_play_info.hasOwnProperty("live_transcoding_task_list")) {
  464. return "";
  465. }
  466. let live_transcoding_task_list = video_preview_play_info.live_transcoding_task_list;
  467. for (let index = 0; index < live_transcoding_task_list.length; ++index) {
  468. let live_transcoding_task = live_transcoding_task_list[index];
  469. if (live_transcoding_task.template_id === quality[flag]) {
  470. return live_transcoding_task.url;
  471. }
  472. }
  473. return live_transcoding_task_list.slice(-1)[0].url;
  474. }
  475. function getSubsByPlayInfo(video_preview_play_info) {
  476. if (!video_preview_play_info.hasOwnProperty("live_transcoding_subtitle_task_list")) {
  477. return [];
  478. }
  479. let live_transcoding_subtitle_task_list = video_preview_play_info.live_transcoding_subtitle_task_list,
  480. sub_p_list = [];
  481. for (let index = 0; index < live_transcoding_subtitle_task_list.length; ++index) {
  482. let live_transcoding_subtitle_task = live_transcoding_subtitle_task_list[index],
  483. language = live_transcoding_subtitle_task.language, url = live_transcoding_subtitle_task.url;
  484. sub_p_list.push(Sub.create().setUrl(url).setName(language).setLang(language).setExt("vtt"));
  485. }
  486. return sub_p_list;
  487. }
  488. async function copy(file_id, shareId, shareToken) {
  489. let copy_file_id
  490. let cache_dic = {}
  491. try {
  492. cache_dic = JSON.parse(await local.get("file", "file_id"))
  493. } catch (e) {
  494. }
  495. copy_file_id = cache_dic[file_id]
  496. if (typeof (copy_file_id) == "string") {
  497. await JadeLog.info(`file id为:${file_id},已经缓存过,copy file id为:${copy_file_id}`)
  498. } else {
  499. let params_str = "{\"requests\":[{\"body\":{\"file_id\":\"{{data.fileId}}\",\"share_id\":\"{{data.shareId}}\",\"auto_rename\":true,\"to_parent_file_id\":\"{{data.tmpFolderFileId}}\",\"to_drive_id\":\"{{data.driveId}}\"},\"headers\":{\"Content-Type\":\"application/json\"},\"id\":\"0\",\"method\":\"POST\",\"url\":\"/file/copy\"}],\"resource\":\"file\"}",
  500. drive_id = await getDriveId(), params = {
  501. fileId: file_id, shareId: shareId, driveId: drive_id, tmpFolderFileId: curTmpFolderFileId
  502. };
  503. params_str = jinja2(params_str, {
  504. data: params
  505. });
  506. await JadeLog.debug(`正在转存文件,文件id为:${file_id}`, true)
  507. let response_str = await auth("adrive/v2/batch", JSON.parse(params_str), shareToken, true);
  508. let response = aliExpection(response_str)
  509. if (response.code === 500 || response.code === 501 || response.code === 502 || response.code === 503 || response.code === 403) {
  510. if (response.code === 500) {
  511. await JadeLog.error("转存文件失败,失败详情:" + response.content)
  512. return copy(file_id);
  513. } else if (response.code === 501) {
  514. await JadeLog.error("转存文件失败,失败详情:" + response.content)
  515. return copy(file_id)
  516. } else if (response.code === 502) {
  517. await JadeLog.error("转存文件失败,失败原因为:转存文件夹不存在,失败详情:" + response.content)
  518. return null;
  519. } else if (response.code === 503) {
  520. await JadeLog.error("转存文件失败,失败原因为:转存文件夹大小被限制" + response.content)
  521. await clearFile()
  522. return copy(file_id)
  523. } else if (response.code === 403) {
  524. await JadeLog.error("转存文件失败,失败原因为:没有找到File Id,失败详情:" + response.content)
  525. return null;
  526. }
  527. }
  528. await JadeLog.debug(`转存文件成功,文件id为:${file_id},请求结果为:${response_str}`)
  529. copy_file_id = JSON.parse(response_str).responses[0].body.file_id;
  530. let file_dic = {}
  531. try {
  532. JSON.parse(await local.get("file", "file_id"))
  533. } catch (e) {
  534. }
  535. file_dic[file_id] = copy_file_id
  536. await local.set("file", "file_id", JSON.stringify(file_dic))
  537. }
  538. return copy_file_id;
  539. }
  540. async function deleteTmpFolderAndRecreate() {
  541. // 删除缓存文件夹
  542. let file_id = await tmpFolderExistsFunc();
  543. file_id && (await trashFile(file_id), await recyclebinClear());
  544. await getTempFileId();
  545. }
  546. //放入回车站
  547. async function trashFile(file_id) {
  548. let params_str = "{\"requests\":[{\"body\":{\"file_id\":\"{{data.fileId}}\",\"drive_id\":\"{{data.driveId}}\"},\"headers\":{\"Content-Type\":\"application/json\"},\"id\":\"0\",\"method\":\"POST\",\"url\":\"/recyclebin/trash\"}],\"resource\":\"file\"}",
  549. drive_id = await getDriveId(), params = {
  550. fileId: file_id, driveId: drive_id
  551. };
  552. params_str = jinja2(params_str, {
  553. data: params
  554. });
  555. await JadeLog.debug(`正在准备删除文件,文件id为:${file_id}`, true)
  556. let response = await auth("v2/batch", JSON.parse(params_str), shareToken, true);
  557. await JadeLog.debug(`删除文件成功,文件id为:${file_id},请求结果为:${response}`)
  558. return true;
  559. }
  560. //清空回车站
  561. async function recyclebinClear() {
  562. let drive_id = await getDriveId(), params = {
  563. drive_id: drive_id
  564. };
  565. await auth("v2/recyclebin/clear", params, shareToken, true);
  566. await JadeLog.info("清空回车站成功", true)
  567. return true;
  568. }
  569. async function createTmpFolder() {
  570. //创建文件夹
  571. let file_id = await tmpFolderExistsFunc();
  572. if (file_id) {
  573. await JadeLog.info("文件夹存在,无需重新创建")
  574. return file_id;
  575. }
  576. await JadeLog.debug("文件夹不存在,重新创建文件夹")
  577. let drive_id = await getDriveId(), params = {
  578. check_name_mode: "refuse", drive_id: drive_id, name: tmpFolderName, parent_file_id: "root", type: "folder"
  579. }, response_str = await oauthFunc("openFile/create", params, true);
  580. let response_json = JSON.parse(response_str);
  581. if (_.isEmpty(response_json.drive_id)) {
  582. await JadeLog.error(`创建文件夹失败,失败原因为:${response_str}`)
  583. return null;
  584. }
  585. await JadeLog.info(`创建文件夹成功`, true)
  586. return response_json.file_id;
  587. }
  588. async function tmpFolderExistsFunc() {
  589. let drive_id = await getDriveId(), params = {
  590. drive_id: drive_id, parent_file_id: "root", limit: 100, order_by: "updated_at", order_direction: "DESC"
  591. }, response_str = await oauthFunc("openFile/list", params, true);
  592. let response_json = JSON.parse(response_str);
  593. if (_.isEmpty(response_json.items)) {
  594. return false;
  595. }
  596. for (const item of response_json.items) {
  597. if (item.name === tmpFolderName) {
  598. return item.file_id;
  599. }
  600. }
  601. return false;
  602. }
  603. async function setToken(token) {
  604. // Token设置
  605. user.setRefreshToken(token);
  606. await refreshAccessToken(token);
  607. await refreshOpenToken();
  608. }
  609. export {
  610. initSome, setToken, clearFile, setShareId, getFileByShare, playerContent, playerContentByFlag, getTempFileId
  611. };