RemoteDriveManager.ets 111 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914
  1. // RemoteDriveManager - WebDAV管理器(简化版)
  2. import { VideoItem } from '../../viewmodel/VideoItem';
  3. import { common } from '@kit.AbilityKit';
  4. import { FileInfo } from '../../viewmodel/FileInfo';
  5. import { connection } from '@kit.NetworkKit';
  6. import FileManager, { merge2paths } from './FileManager';
  7. import { BusinessError } from '@kit.BasicServicesKit';
  8. import { RemoteDriveManagerStates } from '../enums/RemoteDriveManagerStates';
  9. import { RcpSocket } from './RcpSocketUtil';
  10. import { DataBaseUtil } from './DataBaseUtil';
  11. import { WebDavAccount } from '../../viewmodel/WebDavAccount';
  12. import { relationalStore } from '@kit.ArkData';
  13. import { Constants } from '../../Constants';
  14. import Logger from './Logger';
  15. import { buffer } from '@kit.ArkTS';
  16. import { CommonConstants } from '../constants/CommonConstants';
  17. import { GlobalContext, PreferencesUtil } from '@pura/harmony-utils';
  18. import { MusicInfo, parseMusicFileName, Utility } from './Utility';
  19. import { RemoteDriveType } from '../enums/RemoteDriveType';
  20. import { deleteSmbEntry, listSmbDirectory, SmbDirectoryEntry } from '../network/SmbBridge';
  21. import { NavidromeApi, NavidromeAlbumDetail, NavidromeArtist, NavidromeArtistDetail, NavidromeSong } from '../network/NavidromeApi';
  22. import { WebDavUrlUtil } from './WebDavUrlUtil';
  23. import MediaTable from './MediaTable';
  24. import { FtpClient, FileInfo as FtpEntryInfo, StringEncoding, AccessOptions } from '@liuzhosoft/ftp4h';
  25. import { BaiduConstants } from '../constants/BaiduConstants';
  26. import { appendAccessTokenToDlink, BaiduListEntry, BaiduFileMeta, buildAudioStreamingUrl, deleteFiles as deleteBaiduFiles, ensureAudioStreamReady, fetchFileMetas as fetchBaiduFileMetas, listDirectory as listBaiduDirectory, refreshAccessToken as refreshBaiduAccessToken } from '../network/BaiduPanClient';
  27. import { ServerLogUtil } from './ServerLogUtil';
  28. const TAG = 'heanup RemoteDriveManager';
  29. export interface BreadcrumbItem {
  30. label: string;
  31. path: string;
  32. }
  33. interface BaiduDlinkCacheEntry {
  34. url: string;
  35. token: string;
  36. expireAt: number;
  37. }
  38. // WebDAV认证信息接口
  39. export interface WebDavAuthInfo {
  40. headers: Record<string, string>;
  41. url: string;
  42. accountId?: string; // 添加账号ID字段,用于标识认证信息对应的账号
  43. }
  44. // 流媒体认证信息接口
  45. export interface StreamAuthInfo {
  46. url: string;
  47. headers: Record<string, string>;
  48. }
  49. // 百度网盘文件信息接口
  50. export interface BaiduFileInfo {
  51. size: number;
  52. dlink: string;
  53. streamUrl: string;
  54. }
  55. export interface TransferTask {
  56. song: VideoItem;
  57. account: WebDavAccount;
  58. retryCount?: number; // 已重试次数
  59. customUploadPath?: string; // 自定义上传路径(可选)
  60. }
  61. @Observed
  62. export class RemoteDriveManager {
  63. public rcpSocket: RcpSocket = RcpSocket.getInstance();
  64. private dataBaseUtil = DataBaseUtil.getInstance();
  65. public observers: Array<(event: string) => void> = [];
  66. public static instance: RemoteDriveManager;
  67. public context: common.Context | undefined;
  68. public DownloadDirectoryFilePath: string = '';
  69. public audioExtensions = Constants.AUDIO_EXTENSIONS;
  70. public lyricExtensions = Constants.LYRIC_EXTENSIONS;
  71. public imageExtensions = Constants.IMAGE_EXTENSIONS;
  72. // 数据表名称
  73. public preferenceName = Constants.WEBDAV_PREFERENCE_NAME;
  74. public webDavTable = 'WebDavAccount';
  75. public receivedSize: number = 0;
  76. public totalSize: number = 0;
  77. public webDavAccounts: WebDavAccount[] = [];
  78. public webDavSongs: VideoItem[] = [];
  79. public webDavFiles: FileInfo[] = []; // 当前目录的所有文件(包括文件夹)
  80. private static readonly BAIDU_DLINK_CACHE_TTL: number = 10 * 60 * 1000; // 10分钟
  81. private baiduDlinkCache: Map<string, BaiduDlinkCacheEntry> = new Map();
  82. // 路径导航
  83. public currentPath: string = ''; // 当前浏览的路径
  84. public pathHistory: string[] = []; // 路径历史记录
  85. // 错误信息
  86. public ErrorMessage: string | BusinessError = '';
  87. // 下载队列
  88. public downloadQueue: TransferTask[] = [];
  89. public finishDownloadQueue: TransferTask[] = [];
  90. public isProcessingQueue: boolean = false;
  91. public currentDownloadTask: TransferTask | null = null;
  92. public isPauseDownload: boolean = true;
  93. // 上传队列
  94. public uploadQueue: TransferTask[] = [];
  95. public finishUploadQueue: TransferTask[] = [];
  96. public isProcessingUploadQueue: boolean = false;
  97. public currentUploadTask: TransferTask | null = null;
  98. public isPauseUpload: boolean = true;
  99. public uploadReceivedSize: number = 0;
  100. public uploadTotalSize: number = 0;
  101. // 性能优化相关
  102. // 限制队列大小避免内存溢出:每个任务包含VideoItem对象,200个任务约占用几MB内存
  103. private readonly MAX_UPLOAD_QUEUE_SIZE: number = 200; // 最大上传队列大小
  104. // 进度更新节流:避免频繁UI刷新导致性能下降,每500ms最多更新一次
  105. private lastProgressNotifyTime: number = 0; // 上次进度通知时间
  106. private readonly PROGRESS_THROTTLE_MS: number = 500; // 进度更新节流时间(毫秒)
  107. private navidromeApi: NavidromeApi = new NavidromeApi();
  108. private pathDisplayNames: Map<string, string> = new Map();
  109. private lastAccountId: number | null = null;
  110. public currentAccount:WebDavAccount = new WebDavAccount();
  111. public constructor() {
  112. this.rcpSocket.subscribeHTTPDataTransfer((event: string) => {
  113. this.notifyObservers(event);
  114. });
  115. }
  116. public static getInstance(): RemoteDriveManager {
  117. if (!RemoteDriveManager.instance) {
  118. RemoteDriveManager.instance = new RemoteDriveManager();
  119. }
  120. return RemoteDriveManager.instance;
  121. }
  122. public setContext(context: common.Context): void {
  123. this.context = context;
  124. this.DownloadDirectoryFilePath = merge2paths(context.filesDir, 'Download');
  125. }
  126. // ==================== 观察者模式 ====================
  127. public subscribe(callback: (event: string) => void): void {
  128. this.observers.push(callback);
  129. }
  130. public unsubscribe(callback: (event: string) => void): void {
  131. const index = this.observers.indexOf(callback);
  132. if (index > -1) {
  133. this.observers.splice(index, 1);
  134. }
  135. }
  136. public notifyObservers(event: string): void {
  137. Logger.info(TAG, '通知观察者:', event);
  138. Logger.info(TAG, '观察者数量:', this.observers.length.toString());
  139. for (let i = 0; i < this.observers.length; i++) {
  140. const observer = this.observers[i];
  141. Logger.info(TAG, '调用观察者', i.toString(), ',事件:', event);
  142. observer(event);
  143. }
  144. }
  145. // ==================== 数据库操作 ====================
  146. /**
  147. * 根据webdav_account_id查询WebDAV账号信息
  148. * @param accountId WebDAV账号ID
  149. * @returns Promise<WebDavAccount | null> 返回WebDAV账号信息或null
  150. */
  151. public async getWebDavAccountById(accountId: string): Promise<WebDavAccount | null> {
  152. if (!accountId) {
  153. Logger.warn(TAG, 'webdav_account_id为空,无法查询账号信息');
  154. return null;
  155. }
  156. try {
  157. const db = await this.dataBaseUtil.getDB();
  158. const predicates = new relationalStore.RdbPredicates(this.webDavTable);
  159. predicates.equalTo('id', accountId);
  160. const resultSet = await db.query(predicates);
  161. if (resultSet.rowCount > 0) {
  162. resultSet.goToFirstRow();
  163. const account = new WebDavAccount();
  164. account.id = resultSet.getLong(resultSet.getColumnIndex('id'));
  165. account.name = resultSet.getString(resultSet.getColumnIndex('name'));
  166. account.host = resultSet.getString(resultSet.getColumnIndex('host'));
  167. account.localHost = resultSet.getString(resultSet.getColumnIndex('localHost'));
  168. account.isUseLocalHost = resultSet.getLong(resultSet.getColumnIndex('isUseLocalHost')) === 1;
  169. account.port = resultSet.getLong(resultSet.getColumnIndex('port'));
  170. account.filepath = resultSet.getString(resultSet.getColumnIndex('filepath'));
  171. account.imageFilePath = resultSet.getString(resultSet.getColumnIndex('imageFilePath'));
  172. account.lyricFilePath = resultSet.getString(resultSet.getColumnIndex('lyricFilePath'));
  173. account.uploadFilePath = resultSet.getString(resultSet.getColumnIndex('uploadFilePath'));
  174. account.account = resultSet.getString(resultSet.getColumnIndex('account'));
  175. account.password = resultSet.getString(resultSet.getColumnIndex('password'));
  176. account.enableHttps = resultSet.getLong(resultSet.getColumnIndex('enableHttps')) === 1;
  177. account.coverPath = resultSet.getString(resultSet.getColumnIndex('coverPath'));
  178. account.webType = resultSet.getLong(resultSet.getColumnIndex('webType'));
  179. const smbShareIndex = resultSet.getColumnIndex('smbShare');
  180. const smbDomainIndex = resultSet.getColumnIndex('smbDomain');
  181. const navBaseIndex = resultSet.getColumnIndex('navidromeBasePath');
  182. const ftpEncodingIndex = resultSet.getColumnIndex('ftpEncoding');
  183. const baiduAccessIndex = resultSet.getColumnIndex('baiduAccessToken');
  184. const baiduRefreshIndex = resultSet.getColumnIndex('baiduRefreshToken');
  185. const baiduExpireIndex = resultSet.getColumnIndex('baiduTokenExpiresAt');
  186. if (smbShareIndex >= 0) {
  187. account.smbShare = resultSet.getString(smbShareIndex) ?? '';
  188. }
  189. if (smbDomainIndex >= 0) {
  190. account.smbDomain = resultSet.getString(smbDomainIndex) ?? '';
  191. }
  192. if (navBaseIndex >= 0) {
  193. const stored = resultSet.getString(navBaseIndex);
  194. account.navidromeBasePath = stored && stored.length > 0 ? stored : '/rest';
  195. } else {
  196. account.navidromeBasePath = '/rest';
  197. }
  198. if (ftpEncodingIndex >= 0) {
  199. const encodingValue = resultSet.getString(ftpEncodingIndex);
  200. account.ftpEncoding = encodingValue && encodingValue.length > 0 ? encodingValue : 'utf-8';
  201. } else {
  202. account.ftpEncoding = 'utf-8';
  203. }
  204. if (baiduAccessIndex >= 0) {
  205. account.baiduAccessToken = resultSet.getString(baiduAccessIndex) ?? '';
  206. }
  207. if (baiduRefreshIndex >= 0) {
  208. account.baiduRefreshToken = resultSet.getString(baiduRefreshIndex) ?? '';
  209. }
  210. if (baiduExpireIndex >= 0) {
  211. account.baiduTokenExpiresAt = resultSet.getLong(baiduExpireIndex);
  212. }
  213. account.isActivate = resultSet.getLong(resultSet.getColumnIndex('isActivate')) === 1;
  214. resultSet.close();
  215. Logger.info(TAG, `成功查询到WebDAV账号: ${account.name}, ID: ${account.id}`);
  216. return account;
  217. } else {
  218. Logger.warn(TAG, `未找到ID为 ${accountId} 的WebDAV账号`);
  219. resultSet.close();
  220. return null;
  221. }
  222. } catch (error) {
  223. const err = error as Error;
  224. Logger.error(TAG, `查询WebDAV账号失败: ${err.message}`);
  225. return null;
  226. }
  227. }
  228. /**
  229. * 根据WebDAV账号构建认证信息
  230. * @param accountId WebDAV账号ID
  231. * @returns Promise<WebDavAuthInfo | null> 返回认证信息或null
  232. */
  233. public async buildAuthInfoByAccountId(accountId: string): Promise<WebDavAuthInfo | null> {
  234. const account = await this.getWebDavAccountById(accountId);
  235. if (!account) {
  236. Logger.warn(TAG, `无法构建认证信息,账号ID ${accountId} 对应的账号不存在`);
  237. return null;
  238. }
  239. try {
  240. // 构建基础URL
  241. const protocol = account.enableHttps ? 'https' : 'http';
  242. const host = account.isUseLocalHost && account.localHost ? account.localHost : account.host;
  243. const port = account.port && account.port !== 80 && account.port !== 443 ? `:${account.port}` : '';
  244. const baseUrl = `${protocol}://${host}${port}`;
  245. // 构建认证头
  246. const headers: Record<string, string> = {};
  247. if (account.account && account.password) {
  248. const credentials = `${account.account}:${account.password}`;
  249. // 简化base64编码实现,避免复杂的类型转换
  250. try {
  251. const bufferObj = buffer.from(credentials, 'utf-8');
  252. const base64Credentials = bufferObj.toString('base64');
  253. headers['Authorization'] = `Basic ${base64Credentials}`;
  254. } catch (error) {
  255. const err = error as Error;
  256. Logger.warn(TAG, `base64编码失败,使用原始凭据: ${err.message}`);
  257. headers['Authorization'] = `Basic ${credentials}`;
  258. }
  259. }
  260. Logger.info(TAG, `成功构建WebDAV认证信息,账号: ${account.name}, URL: ${baseUrl}`);
  261. return {
  262. headers: headers,
  263. url: baseUrl,
  264. accountId: accountId
  265. };
  266. } catch (error) {
  267. const err = error as Error;
  268. Logger.error(TAG, `构建WebDAV认证信息失败: ${err.message}`);
  269. return null;
  270. }
  271. }
  272. /**
  273. * 构建HTTP请求头,通过webdav_account_id查询认证信息
  274. * @param currentSong - 当前播放的歌曲信息
  275. * @param videoUrl - 当前歌曲的URL
  276. * @returns Promise<Map<string, string>> HTTP请求头
  277. */
  278. public async buildHttpHeadersWithAccountId(
  279. currentSong: VideoItem | undefined,
  280. videoUrl: string
  281. ): Promise<Map<string, string>> {
  282. const headers = new Map<string, string>();
  283. if (!currentSong) {
  284. return headers;
  285. }
  286. Logger.info(`heanup 当前歌曲信息 - name: ${currentSong.name}, type: ${currentSong.type}, filePath: ${currentSong.filePath}`);
  287. // 检查是否为WebDAV歌曲
  288. if (currentSong.type === CommonConstants.TYPE_WEBDAV) {
  289. // 优先使用webdav_account_id查询认证信息
  290. if (currentSong.webdav_account_id) {
  291. Logger.info(`heanup 使用webdav_account_id查询认证信息,账号ID: ${currentSong.webdav_account_id}`);
  292. try {
  293. const authInfo = await this.buildAuthInfoByAccountId(currentSong.webdav_account_id);
  294. if (authInfo) {
  295. // 添加WebDAV认证头
  296. Object.keys(authInfo.headers).forEach(key => {
  297. headers.set(key, authInfo.headers[key]);
  298. });
  299. Logger.info(`heanup 成功通过webdav_account_id获取WebDAV认证信息`);
  300. } else {
  301. Logger.warn(`heanup 无法通过webdav_account_id ${currentSong.webdav_account_id} 获取认证信息`);
  302. }
  303. } catch (error) {
  304. const err = error as Error;
  305. Logger.error(`heanup 查询webdav_account_id认证信息时出错: ${err.message}`);
  306. }
  307. } else {
  308. Logger.warn(`heanup WebDAV歌曲缺少webdav_account_id字段,无法查询认证信息`);
  309. }
  310. // 如果没有认证信息,记录警告
  311. if (headers.size === 0) {
  312. Logger.warn(`heanup WebDAV歌曲缺少认证信息,可能需要手动配置WebDAV账户`);
  313. }
  314. }
  315. if (currentSong.type === CommonConstants.TYPE_BAIDU) {
  316. headers.set('User-Agent', BaiduConstants.STREAMING_USER_AGENT);
  317. headers.set('Host', 'pan.baidu.com');
  318. headers.set('Accept', '*/*');
  319. headers.set('Connection', 'Keep-Alive');
  320. headers.set('Referer', 'https://pan.baidu.com/disk/home');
  321. headers.set('Accept-Encoding', 'identity');
  322. headers.set('Pragma', 'no-cache');
  323. headers.set('Cache-Control', 'no-cache');
  324. const headerSnapshot: Record<string, string> = {};
  325. headers.forEach((value, key) => {
  326. headerSnapshot[key] = value;
  327. });
  328. Logger.info(TAG, `构建百度请求头: ${JSON.stringify(headerSnapshot)}`);
  329. }
  330. return headers;
  331. }
  332. /**
  333. * 更新现有WebDAV歌曲的webdav_account_id字段
  334. * 用于修复旧版本数据库中缺少webdav_account_id的记录
  335. * @param accountId WebDAV账号ID
  336. */
  337. public async updateWebDavSongsAccountId(accountId: string): Promise<void> {
  338. try {
  339. const db = await this.dataBaseUtil.getDB();
  340. // 查询所有TYPE_WEBDAV且webdav_account_id为空或null的记录
  341. const querySql = `
  342. SELECT id, filePath FROM mediaTable
  343. WHERE mtype IN (${CommonConstants.TYPE_WEBDAV}, ${CommonConstants.TYPE_SMB}, ${CommonConstants.TYPE_FTP}, ${CommonConstants.TYPE_BAIDU})
  344. AND (webdav_account_id IS NULL OR webdav_account_id = '')
  345. `;
  346. const resultSet = await db.querySql(querySql);
  347. const updateCount = resultSet.rowCount;
  348. if (updateCount > 0) {
  349. Logger.info(TAG, `发现 ${updateCount} 个WebDAV歌曲缺少webdav_account_id,开始更新`);
  350. // 更新这些记录的webdav_account_id
  351. const updateSql = `
  352. UPDATE mediaTable
  353. SET webdav_account_id = ?
  354. WHERE mtype IN (${CommonConstants.TYPE_WEBDAV}, ${CommonConstants.TYPE_SMB}, ${CommonConstants.TYPE_FTP}, ${CommonConstants.TYPE_BAIDU})
  355. AND (webdav_account_id IS NULL OR webdav_account_id = '')
  356. `;
  357. await db.executeSql(updateSql, [accountId]);
  358. Logger.info(TAG, `成功更新 ${updateCount} 个WebDAV歌曲的webdav_account_id为: ${accountId}`);
  359. } else {
  360. Logger.info(TAG, `所有WebDAV歌曲都已有webdav_account_id,无需更新`);
  361. }
  362. resultSet.close();
  363. } catch (error) {
  364. const err = error as Error;
  365. Logger.error(TAG, `更新WebDAV歌曲webdav_account_id失败: ${err.message}`);
  366. }
  367. }
  368. /**
  369. * 修复所有WebDAV歌曲的webdav_account_id字段
  370. * 用于全局修复旧版本数据库中缺少webdav_account_id的记录
  371. * @param accountId WebDAV账号ID(可选,如果不提供则使用当前激活的账号)
  372. */
  373. public async fixAllWebDavSongsAccountId(accountId?: string): Promise<void> {
  374. try {
  375. // 如果没有提供accountId,尝试使用当前激活的账号
  376. if (!accountId) {
  377. const activeAccount = await this.getActiveWebDavAccount();
  378. if (activeAccount && activeAccount.id) {
  379. accountId = activeAccount.id.toString();
  380. } else {
  381. Logger.warn(TAG, `无法找到激活的WebDAV账号来修复歌曲记录`);
  382. return;
  383. }
  384. }
  385. Logger.info(TAG, `开始修复所有WebDAV歌曲的webdav_account_id,使用账号ID: ${accountId}`);
  386. await this.updateWebDavSongsAccountId(accountId);
  387. Logger.info(TAG, `WebDAV歌曲webdav_account_id修复完成`);
  388. } catch (error) {
  389. const err = error as Error;
  390. Logger.error(TAG, `修复WebDAV歌曲webdav_account_id失败: ${err.message}`);
  391. }
  392. }
  393. /**
  394. * 获取当前激活的WebDAV账号
  395. */
  396. private async getActiveWebDavAccount(): Promise<WebDavAccount | null> {
  397. try {
  398. const db = await this.dataBaseUtil.getDB();
  399. const predicates = new relationalStore.RdbPredicates(this.webDavTable);
  400. predicates.equalTo('isActivate', 1);
  401. predicates.limitAs(1);
  402. const resultSet = await db.query(predicates);
  403. if (resultSet.rowCount > 0) {
  404. resultSet.goToFirstRow();
  405. const account = new WebDavAccount();
  406. account.id = resultSet.getLong(resultSet.getColumnIndex('id'));
  407. account.name = resultSet.getString(resultSet.getColumnIndex('name'));
  408. account.host = resultSet.getString(resultSet.getColumnIndex('host'));
  409. account.localHost = resultSet.getString(resultSet.getColumnIndex('localHost'));
  410. account.isUseLocalHost = resultSet.getLong(resultSet.getColumnIndex('isUseLocalHost')) === 1;
  411. account.port = resultSet.getLong(resultSet.getColumnIndex('port'));
  412. account.filepath = resultSet.getString(resultSet.getColumnIndex('filepath'));
  413. account.imageFilePath = resultSet.getString(resultSet.getColumnIndex('imageFilePath'));
  414. account.lyricFilePath = resultSet.getString(resultSet.getColumnIndex('lyricFilePath'));
  415. account.uploadFilePath = resultSet.getString(resultSet.getColumnIndex('uploadFilePath'));
  416. account.account = resultSet.getString(resultSet.getColumnIndex('account'));
  417. account.password = resultSet.getString(resultSet.getColumnIndex('password'));
  418. account.enableHttps = resultSet.getLong(resultSet.getColumnIndex('enableHttps')) === 1;
  419. account.coverPath = resultSet.getString(resultSet.getColumnIndex('coverPath'));
  420. account.webType = resultSet.getLong(resultSet.getColumnIndex('webType'));
  421. const smbShareIndex = resultSet.getColumnIndex('smbShare');
  422. const smbDomainIndex = resultSet.getColumnIndex('smbDomain');
  423. const navBaseIndex = resultSet.getColumnIndex('navidromeBasePath');
  424. const baiduAccessIndex = resultSet.getColumnIndex('baiduAccessToken');
  425. const baiduRefreshIndex = resultSet.getColumnIndex('baiduRefreshToken');
  426. const baiduExpireIndex = resultSet.getColumnIndex('baiduTokenExpiresAt');
  427. if (smbShareIndex >= 0) {
  428. account.smbShare = resultSet.getString(smbShareIndex) ?? '';
  429. }
  430. if (smbDomainIndex >= 0) {
  431. account.smbDomain = resultSet.getString(smbDomainIndex) ?? '';
  432. }
  433. const ftpEncodingIndex = resultSet.getColumnIndex('ftpEncoding');
  434. if (navBaseIndex >= 0) {
  435. const stored = resultSet.getString(navBaseIndex);
  436. account.navidromeBasePath = stored && stored.length > 0 ? stored : '/rest';
  437. } else {
  438. account.navidromeBasePath = '/rest';
  439. }
  440. if (ftpEncodingIndex >= 0) {
  441. const encodingValue = resultSet.getString(ftpEncodingIndex);
  442. account.ftpEncoding = encodingValue && encodingValue.length > 0 ? encodingValue : 'utf-8';
  443. } else {
  444. account.ftpEncoding = 'utf-8';
  445. }
  446. if (baiduAccessIndex >= 0) {
  447. account.baiduAccessToken = resultSet.getString(baiduAccessIndex) ?? '';
  448. }
  449. if (baiduRefreshIndex >= 0) {
  450. account.baiduRefreshToken = resultSet.getString(baiduRefreshIndex) ?? '';
  451. }
  452. if (baiduExpireIndex >= 0) {
  453. account.baiduTokenExpiresAt = resultSet.getLong(baiduExpireIndex);
  454. }
  455. account.isActivate = resultSet.getLong(resultSet.getColumnIndex('isActivate')) === 1;
  456. resultSet.close();
  457. return account;
  458. } else {
  459. resultSet.close();
  460. return null;
  461. }
  462. } catch (error) {
  463. const err = error as Error;
  464. Logger.error(TAG, `获取激活的WebDAV账号失败: ${err.message}`);
  465. return null;
  466. }
  467. }
  468. // 创建WebDAV账户表
  469. public createWebDavTableInDB(): Promise<void> {
  470. const createTableSql = `CREATE TABLE IF NOT EXISTS ${this.webDavTable} (
  471. id INTEGER PRIMARY KEY AUTOINCREMENT,
  472. name TEXT,
  473. isActivate INTEGER DEFAULT 1,
  474. host TEXT,
  475. localHost TEXT,
  476. isUseLocalHost INTEGER DEFAULT 0,
  477. port INTEGER,
  478. filepath TEXT,
  479. imageFilePath TEXT,
  480. lyricFilePath TEXT,
  481. uploadFilePath TEXT,
  482. account TEXT,
  483. password TEXT,
  484. enableHttps INTEGER DEFAULT 0,
  485. coverPath TEXT,
  486. webType INTEGER DEFAULT 0,
  487. smbShare TEXT,
  488. smbDomain TEXT,
  489. navidromeBasePath TEXT,
  490. ftpEncoding TEXT
  491. )`;
  492. return this.dataBaseUtil.executeSql(createTableSql)
  493. .then(() => {
  494. Logger.info(TAG, 'WebDAV账户表创建成功');
  495. // 检查并添加新字段(用于数据库升级)
  496. return this.upgradeWebDavTable();
  497. })
  498. .catch((err: Error) => {
  499. Logger.error(TAG, '创建WebDAV账户表失败:', err.message);
  500. throw err;
  501. });
  502. }
  503. // 升级WebDAV表结构
  504. private async upgradeWebDavTable(): Promise<void> {
  505. try {
  506. // 直接尝试添加coverPath字段,如果字段已存在会失败但不影响应用运行
  507. Logger.info(TAG, '检查数据库表结构,尝试添加coverPath字段...');
  508. const addColumnSql = `ALTER TABLE ${this.webDavTable} ADD COLUMN coverPath TEXT`;
  509. await this.dataBaseUtil.executeSql(addColumnSql);
  510. Logger.info(TAG, 'coverPath字段添加成功,数据库升级完成');
  511. } catch (error) {
  512. // 如果添加字段失败(可能字段已存在),记录但不阻止应用启动
  513. }
  514. try {
  515. // 添加webType字段,用于标识WebDAV账户类型
  516. Logger.info(TAG, '检查数据库表结构,尝试添加webType字段...');
  517. const addWebTypeColumnSql = `ALTER TABLE ${this.webDavTable} ADD COLUMN webType INTEGER DEFAULT 0`;
  518. await this.dataBaseUtil.executeSql(addWebTypeColumnSql);
  519. Logger.info(TAG, 'webType字段添加成功,数据库升级完成');
  520. } catch (error) {
  521. // 如果添加字段失败(可能字段已存在),记录但不阻止应用启动
  522. }
  523. try {
  524. Logger.info(TAG, '尝试添加smbShare字段...');
  525. const addSmbShareSql = `ALTER TABLE ${this.webDavTable} ADD COLUMN smbShare TEXT`;
  526. await this.dataBaseUtil.executeSql(addSmbShareSql);
  527. Logger.info(TAG, 'smbShare字段添加成功');
  528. } catch (error) {
  529. }
  530. try {
  531. Logger.info(TAG, '尝试添加smbDomain字段...');
  532. const addSmbDomainSql = `ALTER TABLE ${this.webDavTable} ADD COLUMN smbDomain TEXT`;
  533. await this.dataBaseUtil.executeSql(addSmbDomainSql);
  534. Logger.info(TAG, 'smbDomain字段添加成功');
  535. } catch (error) {
  536. }
  537. try {
  538. Logger.info(TAG, '尝试添加navidromeBasePath字段...');
  539. const addNavBaseSql = `ALTER TABLE ${this.webDavTable} ADD COLUMN navidromeBasePath TEXT`;
  540. await this.dataBaseUtil.executeSql(addNavBaseSql);
  541. Logger.info(TAG, 'navidromeBasePath字段添加成功');
  542. } catch (error) {
  543. }
  544. try {
  545. Logger.info(TAG, '尝试添加ftpEncoding字段...');
  546. const addFtpEncodingSql = `ALTER TABLE ${this.webDavTable} ADD COLUMN ftpEncoding TEXT`;
  547. await this.dataBaseUtil.executeSql(addFtpEncodingSql);
  548. Logger.info(TAG, 'ftpEncoding字段添加成功');
  549. } catch (error) {
  550. }
  551. try {
  552. Logger.info(TAG, '尝试添加百度授权字段...');
  553. await this.dataBaseUtil.executeSql(`ALTER TABLE ${this.webDavTable} ADD COLUMN baiduAccessToken TEXT`);
  554. await this.dataBaseUtil.executeSql(`ALTER TABLE ${this.webDavTable} ADD COLUMN baiduRefreshToken TEXT`);
  555. await this.dataBaseUtil.executeSql(`ALTER TABLE ${this.webDavTable} ADD COLUMN baiduTokenExpiresAt INTEGER`);
  556. Logger.info(TAG, '百度授权字段添加成功');
  557. } catch (error) {
  558. }
  559. }
  560. // 从数据库查询所有账户
  561. public async queryWebDavAccountsFromDB(): Promise<void> {
  562. try {
  563. // 确保表结构是最新的
  564. await this.upgradeWebDavTable();
  565. const predicates = new relationalStore.RdbPredicates(this.webDavTable);
  566. // 先查询基础字段(确保这些字段在旧版本中存在)
  567. const baseColumns = ['id', 'name', 'isActivate', 'host', 'localHost', 'isUseLocalHost',
  568. 'port', 'filepath', 'imageFilePath', 'lyricFilePath', 'uploadFilePath',
  569. 'account', 'password', 'enableHttps', 'coverPath', 'webType', 'smbShare', 'smbDomain', 'navidromeBasePath', 'ftpEncoding',
  570. 'baiduAccessToken', 'baiduRefreshToken', 'baiduTokenExpiresAt'];
  571. const resultSet = await this.dataBaseUtil.queryData(this.webDavTable, baseColumns, predicates);
  572. this.webDavAccounts = [];
  573. while (resultSet.goToNextRow()) {
  574. const account = new WebDavAccount();
  575. account.id = resultSet.getLong(resultSet.getColumnIndex('id'));
  576. account.name = resultSet.getString(resultSet.getColumnIndex('name'));
  577. account.isActivate = resultSet.getLong(resultSet.getColumnIndex('isActivate')) === 1;
  578. account.host = resultSet.getString(resultSet.getColumnIndex('host'));
  579. account.localHost = resultSet.getString(resultSet.getColumnIndex('localHost'));
  580. account.isUseLocalHost = resultSet.getLong(resultSet.getColumnIndex('isUseLocalHost')) === 1;
  581. account.port = resultSet.getLong(resultSet.getColumnIndex('port'));
  582. account.filepath = resultSet.getString(resultSet.getColumnIndex('filepath'));
  583. account.imageFilePath = resultSet.getString(resultSet.getColumnIndex('imageFilePath'));
  584. account.lyricFilePath = resultSet.getString(resultSet.getColumnIndex('lyricFilePath'));
  585. account.uploadFilePath = resultSet.getString(resultSet.getColumnIndex('uploadFilePath'));
  586. account.account = resultSet.getString(resultSet.getColumnIndex('account'));
  587. account.password = resultSet.getString(resultSet.getColumnIndex('password'));
  588. account.enableHttps = resultSet.getLong(resultSet.getColumnIndex('enableHttps')) === 1;
  589. const coverPathIndex = resultSet.getColumnIndex('coverPath');
  590. if (coverPathIndex >= 0) {
  591. account.coverPath = resultSet.getString(coverPathIndex) ?? undefined;
  592. }
  593. const webTypeIndex = resultSet.getColumnIndex('webType');
  594. account.webType = webTypeIndex >= 0 ? resultSet.getLong(webTypeIndex) : 0;
  595. const smbShareIndex = resultSet.getColumnIndex('smbShare');
  596. if (smbShareIndex >= 0) {
  597. account.smbShare = resultSet.getString(smbShareIndex) ?? '';
  598. }
  599. const smbDomainIndex = resultSet.getColumnIndex('smbDomain');
  600. if (smbDomainIndex >= 0) {
  601. account.smbDomain = resultSet.getString(smbDomainIndex) ?? '';
  602. }
  603. const navBaseIndex = resultSet.getColumnIndex('navidromeBasePath');
  604. if (navBaseIndex >= 0) {
  605. const stored = resultSet.getString(navBaseIndex);
  606. account.navidromeBasePath = stored && stored.length > 0 ? stored : '/rest';
  607. } else {
  608. account.navidromeBasePath = '/rest';
  609. }
  610. const ftpEncodingIndex = resultSet.getColumnIndex('ftpEncoding');
  611. if (ftpEncodingIndex >= 0) {
  612. const encodingValue = resultSet.getString(ftpEncodingIndex);
  613. account.ftpEncoding = encodingValue && encodingValue.length > 0 ? encodingValue : 'utf-8';
  614. } else {
  615. account.ftpEncoding = 'utf-8';
  616. }
  617. const baiduAccessIndex = resultSet.getColumnIndex('baiduAccessToken');
  618. if (baiduAccessIndex >= 0) {
  619. account.baiduAccessToken = resultSet.getString(baiduAccessIndex) ?? '';
  620. }
  621. const baiduRefreshIndex = resultSet.getColumnIndex('baiduRefreshToken');
  622. if (baiduRefreshIndex >= 0) {
  623. account.baiduRefreshToken = resultSet.getString(baiduRefreshIndex) ?? '';
  624. }
  625. const baiduExpireIndex = resultSet.getColumnIndex('baiduTokenExpiresAt');
  626. if (baiduExpireIndex >= 0) {
  627. account.baiduTokenExpiresAt = resultSet.getLong(baiduExpireIndex);
  628. }
  629. this.webDavAccounts.push(account);
  630. }
  631. resultSet.close();
  632. Logger.info(TAG, '从数据库加载了', this.webDavAccounts.length.toString(), '个WebDAV账户');
  633. this.notifyObservers(RemoteDriveManagerStates.QueryAccountsSucceed);
  634. } catch (err) {
  635. const error = err as Error;
  636. Logger.error(TAG, '查询WebDAV账户失败:', error.message);
  637. this.notifyObservers(RemoteDriveManagerStates.QueryAccountsFailed);
  638. throw error;
  639. }
  640. }
  641. // 插入新账户
  642. public async insertAccount(
  643. name: string,
  644. host: string,
  645. localHost: string,
  646. isUseLocalHost: boolean,
  647. port: number,
  648. filepath: string,
  649. lyricFilePath: string,
  650. uploadFilePath: string,
  651. imageFilePath: string,
  652. account: string,
  653. password: string,
  654. enableHttps: boolean,
  655. coverPath?: string,
  656. webType: number = 0,
  657. smbShare: string = '',
  658. smbDomain: string = '',
  659. navidromeBasePath: string = '/rest',
  660. ftpEncoding: string = 'utf-8',
  661. baiduAccessToken: string = '',
  662. baiduRefreshToken: string = '',
  663. baiduTokenExpiresAt: number = 0
  664. ): Promise<void> {
  665. try {
  666. const values: relationalStore.ValuesBucket = {
  667. 'name': name,
  668. 'isActivate': 1,
  669. 'host': host,
  670. 'localHost': localHost,
  671. 'isUseLocalHost': isUseLocalHost ? 1 : 0,
  672. 'port': port,
  673. 'filepath': filepath,
  674. 'imageFilePath': imageFilePath,
  675. 'lyricFilePath': lyricFilePath,
  676. 'uploadFilePath': uploadFilePath,
  677. 'account': account,
  678. 'password': password,
  679. 'enableHttps': enableHttps ? 1 : 0,
  680. 'coverPath': coverPath || null,
  681. 'webType': webType,
  682. 'smbShare': smbShare,
  683. 'smbDomain': smbDomain,
  684. 'navidromeBasePath': navidromeBasePath,
  685. 'ftpEncoding': ftpEncoding,
  686. 'baiduAccessToken': baiduAccessToken,
  687. 'baiduRefreshToken': baiduRefreshToken,
  688. 'baiduTokenExpiresAt': baiduTokenExpiresAt
  689. };
  690. await this.dataBaseUtil.insertData(this.webDavTable, values);
  691. Logger.info(TAG, '插入WebDAV账户成功:', name);
  692. await this.queryWebDavAccountsFromDB();
  693. this.notifyObservers(RemoteDriveManagerStates.InsertAccountSucceed);
  694. } catch (err) {
  695. const error = err as Error;
  696. Logger.error(TAG, '插入WebDAV账户失败:', error.message);
  697. this.notifyObservers(RemoteDriveManagerStates.InsertAccountFailed);
  698. throw error;
  699. }
  700. }
  701. // 编辑账户
  702. public async editAccount(account: WebDavAccount): Promise<void> {
  703. try {
  704. const values: relationalStore.ValuesBucket = {
  705. 'name': account.name,
  706. 'isActivate': account.isActivate ? 1 : 0,
  707. 'host': account.host,
  708. 'localHost': account.localHost,
  709. 'isUseLocalHost': account.isUseLocalHost ? 1 : 0,
  710. 'port': account.port,
  711. 'filepath': account.filepath,
  712. 'imageFilePath': account.imageFilePath,
  713. 'lyricFilePath': account.lyricFilePath,
  714. 'uploadFilePath': account.uploadFilePath,
  715. 'account': account.account,
  716. 'password': account.password,
  717. 'enableHttps': account.enableHttps ? 1 : 0,
  718. 'coverPath': account.coverPath || null,
  719. 'webType': account.webType,
  720. 'smbShare': account.smbShare,
  721. 'smbDomain': account.smbDomain,
  722. 'navidromeBasePath': account.navidromeBasePath,
  723. 'ftpEncoding': account.ftpEncoding,
  724. 'baiduAccessToken': account.baiduAccessToken,
  725. 'baiduRefreshToken': account.baiduRefreshToken,
  726. 'baiduTokenExpiresAt': account.baiduTokenExpiresAt
  727. };
  728. const predicates = new relationalStore.RdbPredicates(this.webDavTable);
  729. predicates.equalTo('id', account.id);
  730. await this.dataBaseUtil.updateData(this.webDavTable, values, predicates);
  731. Logger.info(TAG, '更新WebDAV账户成功:', account.name);
  732. await this.queryWebDavAccountsFromDB();
  733. this.notifyObservers(RemoteDriveManagerStates.EditAccountSucceed);
  734. } catch (err) {
  735. const error = err as Error;
  736. Logger.error(TAG, '更新WebDAV账户失败:', error.message);
  737. this.notifyObservers(RemoteDriveManagerStates.EditAccountFailed);
  738. throw error;
  739. }
  740. }
  741. // 删除账户
  742. public async removeAccount(account: WebDavAccount): Promise<void> {
  743. try {
  744. const predicates = new relationalStore.RdbPredicates(this.webDavTable);
  745. predicates.equalTo('id', account.id);
  746. await this.dataBaseUtil.deleteData(predicates);
  747. Logger.info(TAG, '删除WebDAV账户成功:', account.name);
  748. await this.queryWebDavAccountsFromDB();
  749. this.notifyObservers(RemoteDriveManagerStates.RemoveAccountSucceed);
  750. } catch (err) {
  751. const error = err as Error;
  752. Logger.error(TAG, '删除WebDAV账户失败:', error.message);
  753. this.notifyObservers(RemoteDriveManagerStates.RemoveAccountFailed);
  754. throw error;
  755. }
  756. }
  757. // 获取所有账户
  758. public getAllWebDavAccounts(): WebDavAccount[] {
  759. return this.webDavAccounts;
  760. }
  761. // 获取激活的账户
  762. public getActivatedWebDavAccount(): WebDavAccount | null {
  763. if(this.currentAccount)
  764. return this.currentAccount;
  765. for (let i = 0; i < this.webDavAccounts.length; i++) {
  766. const account = this.webDavAccounts[i];
  767. if (account.isActivate) {
  768. return account;
  769. }
  770. }
  771. return null;
  772. }
  773. // ==================== 文件操作 ====================
  774. // 从WebDAV加载文件列表
  775. public async loadFilesInfoFromWebdav(customPath?: string): Promise<void> {
  776. const account = await this.getActiveWebDavAccount();
  777. if (!account) {
  778. Logger.error(TAG, '没有激活的WebDAV账户');
  779. this.notifyObservers(RemoteDriveManagerStates.LoadFilesInfoFailed);
  780. return;
  781. }
  782. await this.loadFilesInfoFromAccount(account, customPath);
  783. }
  784. public async loadFilesInfoFromAccount(account: WebDavAccount,customPath?: string): Promise<void> {
  785. this.currentAccount = account;
  786. if (this.lastAccountId !== account.id) {
  787. this.pathHistory = [];
  788. this.pathDisplayNames.clear();
  789. this.registerPathLabel('/', '根目录');
  790. }
  791. this.lastAccountId = account.id ?? null;
  792. // 更新现有WebDAV歌曲的webdav_account_id字段
  793. if (account && account.id) {
  794. await this.updateWebDavSongsAccountId(account.id.toString());
  795. }
  796. try {
  797. this.notifyObservers(RemoteDriveManagerStates.LoadFilesInfoStart);
  798. // 使用自定义路径或账户默认路径
  799. const normalizedFullPath = this.normalizeFullPath(customPath !== undefined ? customPath : account.filepath);
  800. this.currentPath = normalizedFullPath;
  801. if (account.webType === RemoteDriveType.Smb) {
  802. await this.loadSmbFiles(account, normalizedFullPath);
  803. } else if (account.webType === RemoteDriveType.Navidrome) {
  804. await this.loadNavidromeFiles(account, normalizedFullPath);
  805. } else if (account.webType === RemoteDriveType.Ftp) {
  806. await this.loadFtpFiles(account, normalizedFullPath);
  807. } else if (account.webType === RemoteDriveType.Baidu) {
  808. await this.loadBaiduFiles(account, normalizedFullPath);
  809. } else {
  810. await this.loadWebDavFiles(account, normalizedFullPath);
  811. }
  812. this.notifyObservers(RemoteDriveManagerStates.LoadFilesInfoSucceed);
  813. } catch (error) {
  814. this.ErrorMessage = error as BusinessError;
  815. this.notifyObservers(RemoteDriveManagerStates.LoadFilesInfoFailed);
  816. }
  817. }
  818. private normalizeFullPath(path?: string): string {
  819. if (!path || path.trim().length === 0) {
  820. return '/';
  821. }
  822. let normalized = path.trim().replace(/\\/g, '/');
  823. if (!normalized.startsWith('/')) {
  824. normalized = `/${normalized}`;
  825. }
  826. normalized = normalized.replace(/\/+/g, '/');
  827. if (normalized.length > 1 && normalized.endsWith('/')) {
  828. normalized = normalized.slice(0, -1);
  829. }
  830. return normalized || '/';
  831. }
  832. private getSongKey(song: VideoItem): string {
  833. if (!song) {
  834. return '';
  835. }
  836. if (song.filePath && song.filePath.length > 0) {
  837. return song.filePath;
  838. }
  839. if (song.name && song.name.length > 0) {
  840. return song.name;
  841. }
  842. return '';
  843. }
  844. private sanitizeRelativeUploadPath(path?: string): string {
  845. if (!path || path.length === 0) {
  846. return '';
  847. }
  848. let sanitized = path.replace(/\\/g, '/');
  849. sanitized = sanitized.replace(/^\/+/, '');
  850. sanitized = sanitized.replace(/\/+/g, '/');
  851. return sanitized;
  852. }
  853. private combineRemoteUploadPath(basePath: string, relativePath: string): string {
  854. const normalizedBase = this.normalizeFullPath(basePath);
  855. const cleanedRelative = this.sanitizeRelativeUploadPath(relativePath);
  856. if (!cleanedRelative || cleanedRelative.length === 0) {
  857. return normalizedBase;
  858. }
  859. if (normalizedBase === '/') {
  860. return this.normalizeFullPath(`/${cleanedRelative}`);
  861. }
  862. return this.normalizeFullPath(`${normalizedBase}/${cleanedRelative}`);
  863. }
  864. private getDirectoryFromRemotePath(remotePath: string): string {
  865. if (!remotePath || remotePath === '/') {
  866. return '/';
  867. }
  868. const normalized = this.normalizeFullPath(remotePath);
  869. const lastSlash = normalized.lastIndexOf('/');
  870. if (lastSlash <= 0) {
  871. return '/';
  872. }
  873. return normalized.substring(0, lastSlash);
  874. }
  875. private async ensureRemoteDirectories(account: WebDavAccount, directoryPath: string): Promise<void> {
  876. if (!directoryPath || directoryPath === '/') {
  877. return;
  878. }
  879. const normalizedDir = this.normalizeFullPath(directoryPath);
  880. if (normalizedDir === '/') {
  881. return;
  882. }
  883. const segments = normalizedDir.split('/').filter(segment => segment.length > 0);
  884. if (segments.length === 0) {
  885. return;
  886. }
  887. let currentPath = '';
  888. for (let i = 0; i < segments.length; i++) {
  889. currentPath = `${currentPath}/${segments[i]}`;
  890. const normalizedCurrent = this.normalizeFullPath(currentPath);
  891. await this.ensureSingleRemoteDirectory(account, normalizedCurrent);
  892. }
  893. }
  894. private async ensureSingleRemoteDirectory(account: WebDavAccount, directoryPath: string): Promise<void> {
  895. try {
  896. await this.rcpSocket.getFileList(
  897. account.host,
  898. account.localHost,
  899. account.isUseLocalHost,
  900. account.port,
  901. directoryPath,
  902. account.account,
  903. account.password,
  904. account.enableHttps
  905. );
  906. } catch (_error) {
  907. const host = account.isUseLocalHost && account.localHost ? account.localHost : account.host;
  908. try {
  909. await this.rcpSocket.createDirectory(
  910. host,
  911. account.port,
  912. account.account,
  913. account.password,
  914. directoryPath,
  915. account.enableHttps
  916. );
  917. Logger.info(TAG, `创建远程目录: ${directoryPath}`);
  918. } catch (createErr) {
  919. const err = createErr as Error;
  920. Logger.error(TAG, `创建远程目录失败 (${directoryPath}): ${err.message}`);
  921. throw err;
  922. }
  923. }
  924. }
  925. // 将 WebDAV 响应中的 href 统一转换为以 / 开头的相对路径
  926. private normalizeRemoteHref(rawHref: string): string {
  927. if (!rawHref || rawHref.trim().length === 0) {
  928. return '/';
  929. }
  930. const trimmed = rawHref.trim();
  931. const relativeFromHttp = WebDavUrlUtil.extractRelativePath(trimmed);
  932. if (relativeFromHttp) {
  933. return this.normalizeFullPath(relativeFromHttp);
  934. }
  935. if (trimmed.startsWith('//')) {
  936. const hostEnd = trimmed.indexOf('/', 2);
  937. if (hostEnd > 1) {
  938. return this.normalizeFullPath(trimmed.substring(hostEnd));
  939. }
  940. return '/';
  941. }
  942. return this.normalizeFullPath(trimmed);
  943. }
  944. private toRelativePath(fullPath: string): string {
  945. if (!fullPath || fullPath === '/') {
  946. return '';
  947. }
  948. return fullPath.replace(/^\/+/, '');
  949. }
  950. private async loadWebDavFiles(account: WebDavAccount, fullPath: string): Promise<void> {
  951. const files = await this.rcpSocket.getFileList(
  952. account.host,
  953. account.localHost,
  954. account.isUseLocalHost,
  955. account.port,
  956. fullPath,
  957. account.account,
  958. account.password,
  959. account.enableHttps
  960. );
  961. this.webDavFiles = files;
  962. this.webDavSongs = [];
  963. for (let i = 0; i < files.length; i++) {
  964. const file = files[i];
  965. if (!file.isDirectory && this.isAudioFile(file.fileName)) {
  966. this.webDavSongs.push(this.fileInfoToVideoItem(file, account));
  967. }
  968. }
  969. await this.enrichSongsWithDatabase(this.webDavSongs);
  970. Logger.info(TAG, `从WebDAV获取到 ${files.length} 个文件/文件夹`);
  971. }
  972. private async loadSmbFiles(account: WebDavAccount, fullPath: string): Promise<void> {
  973. if (!account.smbShare) {
  974. throw new Error('SMB账户缺少共享名称');
  975. }
  976. const relativePath = this.toRelativePath(fullPath);
  977. const host = account.isUseLocalHost && account.localHost ? account.localHost : account.host;
  978. const entries = await listSmbDirectory({
  979. host,
  980. share: account.smbShare,
  981. username: account.account,
  982. password: account.password,
  983. domain: account.smbDomain,
  984. path: relativePath
  985. });
  986. this.webDavFiles = [];
  987. this.webDavSongs = [];
  988. for (let i = 0; i < entries.length; i++) {
  989. const entry = entries[i];
  990. const fileInfo = this.smbEntryToFileInfo(entry, relativePath);
  991. this.webDavFiles.push(fileInfo);
  992. if (!entry.isDirectory && this.isAudioFile(entry.name)) {
  993. this.webDavSongs.push(this.fileInfoToVideoItem(fileInfo, account));
  994. }
  995. }
  996. await this.enrichSongsWithDatabase(this.webDavSongs);
  997. Logger.info(TAG, `从SMB获取到 ${entries.length} 个文件/文件夹`);
  998. }
  999. private resolveFtpHost(account: WebDavAccount): string {
  1000. const host = account.isUseLocalHost && account.localHost ? account.localHost : account.host;
  1001. return host?.trim() ?? '';
  1002. }
  1003. private getFtpEncoding(account: WebDavAccount): StringEncoding {
  1004. if (account.ftpEncoding && account.ftpEncoding.length > 0) {
  1005. return account.ftpEncoding as StringEncoding;
  1006. }
  1007. return 'utf-8';
  1008. }
  1009. private buildFtpAccessOptions(account: WebDavAccount): AccessOptions {
  1010. const host = this.resolveFtpHost(account);
  1011. if (!host) {
  1012. throw new Error('FTP账户缺少服务器地址');
  1013. }
  1014. return {
  1015. host,
  1016. port: account.port && account.port > 0 ? account.port : 21,
  1017. user: account.account && account.account.length > 0 ? account.account : undefined,
  1018. password: account.password && account.password.length > 0 ? account.password : undefined,
  1019. encoding: this.getFtpEncoding(account)
  1020. };
  1021. }
  1022. private async loadFtpFiles(account: WebDavAccount, fullPath: string): Promise<void> {
  1023. const client = new FtpClient();
  1024. const options = this.buildFtpAccessOptions(account);
  1025. await client.access(options);
  1026. try {
  1027. const listPath = this.normalizeFullPath(fullPath);
  1028. const entries = await client.list(listPath === '/' ? '/' : listPath);
  1029. this.webDavFiles = [];
  1030. this.webDavSongs = [];
  1031. for (let i = 0; i < entries.length; i++) {
  1032. const entry = entries[i];
  1033. const info = this.ftpEntryToFileInfo(entry, listPath);
  1034. this.webDavFiles.push(info);
  1035. if (info.isDirectory) {
  1036. this.registerPathLabel(info.href, info.fileName);
  1037. } else if (this.isAudioFile(info.fileName)) {
  1038. this.webDavSongs.push(this.buildFtpVideoItem(info, account));
  1039. }
  1040. }
  1041. await this.enrichSongsWithDatabase(this.webDavSongs);
  1042. Logger.info(TAG, `从FTP获取到 ${entries.length} 个文件/文件夹`);
  1043. } finally {
  1044. await client.close();
  1045. }
  1046. }
  1047. private async loadBaiduFiles(account: WebDavAccount, fullPath: string): Promise<void> {
  1048. const accessToken = await this.ensureBaiduAccessToken(account);
  1049. const directory = fullPath && fullPath.length > 0 ? fullPath : '/';
  1050. const entries = await listBaiduDirectory(accessToken, directory);
  1051. this.webDavFiles = [];
  1052. this.webDavSongs = [];
  1053. for (let i = 0; i < entries.length; i++) {
  1054. const entry = entries[i];
  1055. const info = this.baiduEntryToFileInfo(entry);
  1056. this.webDavFiles.push(info);
  1057. if (info.isDirectory) {
  1058. this.registerPathLabel(info.href, info.fileName);
  1059. } else if (this.isAudioFile(info.fileName)) {
  1060. this.webDavSongs.push(this.buildBaiduVideoItem(entry, account));
  1061. }
  1062. }
  1063. await this.enrichSongsWithDatabase(this.webDavSongs);
  1064. Logger.info(TAG, `从百度网盘获取到 ${entries.length} 个文件/文件夹`);
  1065. this.scheduleBaiduPrefetch(account, accessToken, entries);
  1066. Logger.info(TAG, `百度预取任务已调度, account=${account.id}, 文件数=${entries.length}`);
  1067. }
  1068. public async deleteRemoteSongs(account: WebDavAccount, songs: VideoItem[]): Promise<void> {
  1069. if (!account) {
  1070. throw new Error('请先选择账户');
  1071. }
  1072. if (!songs || songs.length === 0) {
  1073. return;
  1074. }
  1075. const deletable = songs.filter(item => item && item.filePath && item.filePath.length > 0);
  1076. if (deletable.length === 0) {
  1077. return;
  1078. }
  1079. if (account.webType === RemoteDriveType.WebDav) {
  1080. await this.deleteWebDavSongs(account, deletable);
  1081. } else if (account.webType === RemoteDriveType.Smb) {
  1082. await this.deleteSmbSongs(account, deletable);
  1083. } else if (account.webType === RemoteDriveType.Ftp) {
  1084. await this.deleteFtpSongs(account, deletable);
  1085. } else if (account.webType === RemoteDriveType.Baidu) {
  1086. await this.deleteBaiduSongs(account, deletable);
  1087. } else {
  1088. throw new Error('当前账户类型暂不支持删除');
  1089. }
  1090. }
  1091. private resolveWebDavDeletePath(song: VideoItem): string {
  1092. if (song.remote_rel_path && song.remote_rel_path.length > 0) {
  1093. return this.normalizeRemoteHref(song.remote_rel_path);
  1094. }
  1095. if (song.filePath) {
  1096. const relative = WebDavUrlUtil.extractRelativePath(song.filePath);
  1097. if (relative) {
  1098. return this.normalizeRemoteHref(relative);
  1099. }
  1100. }
  1101. throw new Error(`无法确定 WebDAV 文件路径: ${song.name}`);
  1102. }
  1103. private async deleteWebDavSongs(account: WebDavAccount, songs: VideoItem[]): Promise<void> {
  1104. const host = account.isUseLocalHost && account.localHost ? account.localHost : account.host;
  1105. if (!host || host.length === 0) {
  1106. throw new Error('WebDAV账户缺少服务器地址');
  1107. }
  1108. for (let i = 0; i < songs.length; i++) {
  1109. const song = songs[i];
  1110. const relativePath = this.resolveWebDavDeletePath(song);
  1111. try {
  1112. await this.rcpSocket.RcpSendDelete(
  1113. host,
  1114. account.port,
  1115. account.account,
  1116. account.password,
  1117. relativePath,
  1118. account.enableHttps
  1119. );
  1120. } catch (error) {
  1121. const err = error as Error;
  1122. throw new Error(`删除 ${song.name} 失败: ${err.message}`);
  1123. }
  1124. }
  1125. }
  1126. private resolveSmbSongPath(song: VideoItem, account: WebDavAccount): string {
  1127. if (song.remote_rel_path && song.remote_rel_path.length > 0) {
  1128. return this.normalizeSmbRelativePath(song.remote_rel_path, account.smbShare);
  1129. }
  1130. if (song.filePath) {
  1131. const withoutScheme = song.filePath.replace(/^smb:\/\//i, '').replace(/^[^/]+/i, '');
  1132. return this.normalizeSmbRelativePath(withoutScheme, account.smbShare);
  1133. }
  1134. throw new Error(`无法确定SMB路径: ${song.name}`);
  1135. }
  1136. private async deleteSmbSongs(account: WebDavAccount, songs: VideoItem[]): Promise<void> {
  1137. if (!account.smbShare || account.smbShare.length === 0) {
  1138. throw new Error('SMB账户缺少共享名称');
  1139. }
  1140. const host = account.isUseLocalHost && account.localHost ? account.localHost : account.host;
  1141. if (!host || host.length === 0) {
  1142. throw new Error('SMB账户缺少服务器地址');
  1143. }
  1144. for (let i = 0; i < songs.length; i++) {
  1145. const song = songs[i];
  1146. const relativePath = this.resolveSmbSongPath(song, account);
  1147. if (!relativePath || relativePath.length === 0 || relativePath === '/') {
  1148. throw new Error(`无法确定SMB文件路径: ${song.name}`);
  1149. }
  1150. try {
  1151. await deleteSmbEntry({
  1152. host,
  1153. share: account.smbShare,
  1154. username: account.account,
  1155. password: account.password,
  1156. domain: account.smbDomain,
  1157. path: relativePath,
  1158. isDirectory: false
  1159. });
  1160. } catch (error) {
  1161. const err = error as Error;
  1162. throw new Error(`删除 ${song.name} 失败: ${err.message}`);
  1163. }
  1164. }
  1165. }
  1166. private resolveFtpSongPath(song: VideoItem): string {
  1167. const target = song.remote_rel_path && song.remote_rel_path.length > 0 ? song.remote_rel_path : song.filePath;
  1168. if (!target || target.length === 0) {
  1169. throw new Error(`无法确定FTP路径: ${song.name}`);
  1170. }
  1171. return this.normalizeFullPath(target);
  1172. }
  1173. private async deleteFtpSongs(account: WebDavAccount, songs: VideoItem[]): Promise<void> {
  1174. const options = this.buildFtpAccessOptions(account);
  1175. const client = new FtpClient();
  1176. try {
  1177. await client.access(options);
  1178. for (let i = 0; i < songs.length; i++) {
  1179. const song = songs[i];
  1180. const remotePath = this.resolveFtpSongPath(song);
  1181. const success = await client.remove(remotePath);
  1182. if (!success) {
  1183. throw new Error(`删除 ${song.name} 失败`);
  1184. }
  1185. }
  1186. } finally {
  1187. await client.close();
  1188. }
  1189. }
  1190. private async deleteBaiduSongs(account: WebDavAccount, songs: VideoItem[]): Promise<void> {
  1191. const accessToken = await this.ensureBaiduAccessToken(account);
  1192. const paths: string[] = [];
  1193. for (let i = 0; i < songs.length; i++) {
  1194. const path = songs[i].remote_rel_path;
  1195. if (!path || path.length === 0) {
  1196. throw new Error(`无法确定百度网盘路径: ${songs[i].name}`);
  1197. }
  1198. paths.push(path);
  1199. }
  1200. const batchSize = 20;
  1201. for (let i = 0; i < paths.length; i += batchSize) {
  1202. const batch = paths.slice(i, i + batchSize);
  1203. try {
  1204. await deleteBaiduFiles(accessToken, batch);
  1205. } catch (error) {
  1206. const err = error as Error;
  1207. throw new Error(`删除文件失败: ${err.message}`);
  1208. }
  1209. }
  1210. }
  1211. private scheduleBaiduPrefetch(account: WebDavAccount, accessToken: string, entries: BaiduListEntry[]): void {
  1212. const fileEntries = entries.filter(entry => entry.isdir === 0 && this.isAudioFile(entry.server_filename));
  1213. if (fileEntries.length === 0) {
  1214. return;
  1215. }
  1216. const fsIds = fileEntries.map(entry => entry.fs_id.toString());
  1217. const chunkSize = 50;
  1218. const prefetch = async () => {
  1219. Logger.info(TAG, `开始预取百度dlink,文件数: ${fsIds.length}`);
  1220. Logger.info(TAG, `Baidu dlink prefetch start: account=${account.id} files=${fsIds.length}`);
  1221. for (let i = 0; i < fsIds.length; i += chunkSize) {
  1222. const chunk = fsIds.slice(i, i + chunkSize);
  1223. try {
  1224. const metas = await fetchBaiduFileMetas(accessToken, chunk);
  1225. metas.forEach((meta: BaiduFileMeta) => {
  1226. if (!meta.dlink) {
  1227. return;
  1228. }
  1229. const rawLink = meta.dlink.startsWith('https://') ? meta.dlink : meta.dlink.replace('http://', 'https://');
  1230. const finalUrl = appendAccessTokenToDlink(rawLink, accessToken);
  1231. this.cacheBaiduDlink(account, meta.fs_id.toString(), accessToken, finalUrl);
  1232. });
  1233. Logger.info(TAG, `Baidu dlink prefetch chunk success account=${account.id} size=${chunk.length}`);
  1234. } catch (error) {
  1235. const err = error as Error;
  1236. Logger.warn(TAG, `百度dlink预取失败: ${err.message}`);
  1237. break;
  1238. }
  1239. }
  1240. Logger.info(TAG, `Baidu dlink prefetch finished account=${account.id}`);
  1241. };
  1242. void prefetch();
  1243. }
  1244. private async loadNavidromeFiles(account: WebDavAccount, fullPath: string): Promise<void> {
  1245. const normalized = this.normalizeFullPath(fullPath);
  1246. this.registerPathLabel('/', '根目录');
  1247. const segments = normalized.split('/').filter(part => part.length > 0);
  1248. void ServerLogUtil.info(TAG, `浏览 Navidrome 路径: ${normalized} account=${ServerLogUtil.sanitizeAccount(account)}`);
  1249. if (normalized === '/' || segments.length === 0) {
  1250. const artists: NavidromeArtist[] = await this.navidromeApi.getArtists(account);
  1251. artists.sort((a, b) => a.name.localeCompare(b.name));
  1252. this.webDavFiles = artists.map(artist => {
  1253. const info = this.createNavDirectory(artist.name, `/artist/${artist.id}`);
  1254. this.registerPathLabel(info.href, artist.name);
  1255. return info;
  1256. });
  1257. this.webDavSongs = [];
  1258. void ServerLogUtil.info(TAG, `获取艺术家列表,数量: ${artists.length}`);
  1259. void ServerLogUtil.debug(TAG, `artists ids: ${artists.map(a => a.id).join(',')}`)
  1260. return;
  1261. }
  1262. if (segments[0] === 'artist' && segments[1]) {
  1263. const artistId = segments[1];
  1264. const detail: NavidromeArtistDetail = await this.navidromeApi.getArtist(account, artistId);
  1265. this.registerPathLabel(`/artist/${artistId}`, detail.name);
  1266. this.webDavFiles = detail.albums.map(album => {
  1267. const info = this.createNavDirectory(album.name, `/album/${album.id}`);
  1268. this.registerPathLabel(info.href, album.name);
  1269. return info;
  1270. });
  1271. this.webDavSongs = [];
  1272. void ServerLogUtil.info(TAG, `进入艺术家 ${detail.name},专辑数: ${detail.albums.length}`);
  1273. void ServerLogUtil.debug(TAG, `artist albums: ${detail.albums.map(a => a.id).join(',')}`)
  1274. return;
  1275. }
  1276. if (segments[0] === 'album' && segments[1]) {
  1277. const albumId = segments[1];
  1278. const detail: NavidromeAlbumDetail = await this.navidromeApi.getAlbum(account, albumId);
  1279. this.registerPathLabel(`/album/${albumId}`, detail.name);
  1280. this.webDavFiles = detail.songs.map(song => this.createNavSongFileInfo(song, albumId));
  1281. const albumCoverUrl = await this.navidromeApi.buildCoverArtUrl(account,
  1282. detail.coverArt ?? (detail.id ? `al-${detail.id}` : undefined));
  1283. this.webDavSongs = detail.songs.map(song => this.buildNavidromeVideoItem(song, account, detail, albumCoverUrl));
  1284. await this.enrichSongsWithDatabase(this.webDavSongs);
  1285. void ServerLogUtil.info(TAG, `进入专辑 ${detail.name},歌曲数: ${detail.songs.length}`);
  1286. void ServerLogUtil.debug(TAG, `album songs ids: ${detail.songs.map(s => s.id).join(',')}`)
  1287. return;
  1288. }
  1289. throw new Error(`不支持的Navidrome路径: ${fullPath}`);
  1290. }
  1291. private async enrichSongsWithDatabase(videoItems: VideoItem[]): Promise<void> {
  1292. if (!this.context || !videoItems || videoItems.length === 0) {
  1293. return;
  1294. }
  1295. try {
  1296. const mediaTable = new MediaTable(this.context);
  1297. await new Promise<void>((resolve) => {
  1298. mediaTable.getRdbStore(this.context as common.Context, () => resolve());
  1299. });
  1300. const pathMap: Map<string, VideoItem[]> = new Map();
  1301. for (let i = 0; i < videoItems.length; i++) {
  1302. const item = videoItems[i];
  1303. const storagePath = this.resolveStoragePathForItem(item);
  1304. if (!storagePath) {
  1305. continue;
  1306. }
  1307. if (!pathMap.has(storagePath)) {
  1308. pathMap.set(storagePath, []);
  1309. }
  1310. pathMap.get(storagePath)?.push(item);
  1311. }
  1312. if (pathMap.size === 0) {
  1313. return;
  1314. }
  1315. const tasks: Promise<void>[] = [];
  1316. pathMap.forEach((targets, storagePath) => {
  1317. tasks.push((async () => {
  1318. try {
  1319. const cached = await mediaTable.queryVideoByFilePath(storagePath);
  1320. if (cached) {
  1321. targets.forEach(target => this.mergeCachedMetadata(target, cached, storagePath));
  1322. }
  1323. } catch (error) {
  1324. Logger.error(TAG, `查询缓存元数据失败: ${storagePath} - ${(error as Error).message}`);
  1325. }
  1326. })());
  1327. });
  1328. await Promise.all(tasks);
  1329. } catch (error) {
  1330. Logger.error(TAG, `补全云端歌曲元数据失败: ${(error as Error).message}`);
  1331. }
  1332. }
  1333. private resolveStoragePathForItem(item: VideoItem): string | null {
  1334. if (!item) {
  1335. return null;
  1336. }
  1337. if (item.type === CommonConstants.TYPE_WEBDAV) {
  1338. const relative = item.remote_rel_path || WebDavUrlUtil.toStoragePath(item.filePath);
  1339. if (relative) {
  1340. item.remote_rel_path = relative;
  1341. return relative;
  1342. }
  1343. return null;
  1344. }
  1345. if (item.type === CommonConstants.TYPE_SMB || item.type === CommonConstants.TYPE_NAVIDROME ||
  1346. item.type === CommonConstants.TYPE_FTP || item.type === CommonConstants.TYPE_BAIDU) {
  1347. if (item.remote_rel_path) {
  1348. return item.remote_rel_path;
  1349. }
  1350. return null;
  1351. }
  1352. return null;
  1353. }
  1354. private mergeCachedMetadata(target: VideoItem, cached: VideoItem, storagePath: string): void {
  1355. target.id = cached.id || target.id || storagePath;
  1356. target.name = cached.name || target.name;
  1357. target.artist = cached.artist || target.artist;
  1358. target.album = cached.album || target.album;
  1359. target.duration = cached.duration || target.duration;
  1360. target.size = cached.size || target.size;
  1361. target.pixelMapPath = cached.pixelMapPath || target.pixelMapPath;
  1362. target.lyricContent = cached.lyricContent || target.lyricContent;
  1363. target.md5Str = cached.md5Str || target.md5Str;
  1364. target.bit_rate = cached.bit_rate || target.bit_rate;
  1365. target.sampleRate = cached.sampleRate || target.sampleRate;
  1366. target.trackCount = cached.trackCount || target.trackCount;
  1367. target.mimeType = cached.mimeType || target.mimeType;
  1368. target.pyStr = cached.pyStr || target.pyStr;
  1369. target.genre = cached.genre || target.genre;
  1370. target.track = cached.track || target.track;
  1371. target.year = cached.year || target.year;
  1372. target.webdav_account_id = target.webdav_account_id || cached.webdav_account_id;
  1373. target.remote_rel_path = target.remote_rel_path || cached.remote_rel_path || storagePath;
  1374. }
  1375. // 将FileInfo转换为VideoItem
  1376. private fileInfoToVideoItem(fileInfo: FileInfo, account: WebDavAccount): VideoItem {
  1377. if (account.webType === RemoteDriveType.Smb) {
  1378. return this.buildSmbVideoItem(fileInfo, account);
  1379. }
  1380. if (account.webType === RemoteDriveType.Ftp) {
  1381. return this.buildFtpVideoItem(fileInfo, account);
  1382. }
  1383. // 构建安全的WebDAV URL(不包含认证信息)
  1384. const protocol = account.enableHttps ? 'https' : 'http';
  1385. const host = account.isUseLocalHost ? account.localHost : account.host;
  1386. const port = account.port;
  1387. // 构建基础URL,确保路径重新编码(目录/文件名中的中文与空格)
  1388. const safeHref = this.normalizeRemoteHref(fileInfo.href);
  1389. const encodedHref = encodeURI(safeHref); // 仅编码非保留字符,已编码的百分号不重复编码
  1390. const absoluteUrl = `${protocol}://${host}:${port}${encodedHref}`;
  1391. // 创建VideoItem对象
  1392. // 构造函数签名: (name, id, filePath, type, videoSize, cTime, size?, pixelMapPath?, artist?, album?, fileName?, lastPlayed?)
  1393. const videoItem = new VideoItem(
  1394. this.getFileNameWithoutExtension(fileInfo.fileName), // name: 歌曲名
  1395. '', // id: 空字符串,WebDAV文件无本地ID
  1396. absoluteUrl, // filePath: 绝对路径
  1397. CommonConstants.TYPE_WEBDAV, // type: WebDAV类型
  1398. fileInfo.contentLength, // videoSize: 文件大小
  1399. Utility.getFormatDateStr(fileInfo.time,'yyyy-MM-dd HH:mm'), // cTime: 修改时间
  1400. undefined, // size
  1401. undefined, // pixelMapPath: 对于WebDAV歌曲不设置图片路径
  1402. Constants.UNKNOWN_ARTIST, // artist: 艺术家
  1403. undefined, // album: 专辑
  1404. fileInfo.fileName // fileName: 真实文件名
  1405. );
  1406. videoItem.size = Utility.formatFSize(fileInfo.contentLength)
  1407. //根据文件名解析艺术家
  1408. const musicData:MusicInfo = parseMusicFileName(fileInfo.fileName);
  1409. if (musicData.isValid) {
  1410. console.log('onecold parseMusicFileName artist:', musicData.artist)
  1411. videoItem.artist = musicData.artist
  1412. videoItem.name = musicData.title
  1413. }
  1414. videoItem.album = ''
  1415. // 设置WebDAV账号ID,用于后续认证信息查询
  1416. if (account && account.id) {
  1417. videoItem.webdav_account_id = account.id.toString();
  1418. }
  1419. // 计算并保存相对路径
  1420. try {
  1421. const relMatch = absoluteUrl.match(/^https?:\/\/[^\/]+(?::\d+)?(\/.*)$/i);
  1422. if (relMatch && relMatch[1]) {
  1423. videoItem.remote_rel_path = relMatch[1];
  1424. }
  1425. } catch (e) {
  1426. Logger.warn(TAG, '计算相对路径失败: ' + (e as Error).message);
  1427. }
  1428. return videoItem;
  1429. }
  1430. private buildSmbVideoItem(fileInfo: FileInfo, account: WebDavAccount): VideoItem {
  1431. const relativePath = fileInfo.href && fileInfo.href.length > 0 ? fileInfo.href : `/${fileInfo.fileName}`;
  1432. const normalizedRelative = relativePath.startsWith('/') ? relativePath : `/${relativePath}`;
  1433. const sanitizedRelative = this.normalizeSmbRelativePath(normalizedRelative, account.smbShare);
  1434. const videoItem = new VideoItem(
  1435. this.getFileNameWithoutExtension(fileInfo.fileName),
  1436. '',
  1437. sanitizedRelative,
  1438. CommonConstants.TYPE_SMB,
  1439. fileInfo.contentLength,
  1440. Utility.getFormatDateStr(fileInfo.time, 'yyyy-MM-dd HH:mm'),
  1441. undefined,
  1442. undefined,
  1443. Constants.UNKNOWN_ARTIST,
  1444. undefined,
  1445. fileInfo.fileName
  1446. );
  1447. videoItem.album = ''
  1448. videoItem.size = Utility.formatFSize(fileInfo.contentLength);
  1449. if (account && account.id) {
  1450. videoItem.webdav_account_id = account.id.toString();
  1451. }
  1452. videoItem.remote_rel_path = sanitizedRelative;
  1453. const hostForDisplay = account.host && account.host.trim().length > 0
  1454. ? account.host.trim()
  1455. : (account.id?.toString() ?? '');
  1456. const cleanedShare = account.smbShare
  1457. ? account.smbShare.replace(/^\/+|\/+$/g, '')
  1458. : '';
  1459. const relativeForDisplay = sanitizedRelative === '/' ? '' : sanitizedRelative;
  1460. if (hostForDisplay.length > 0 && cleanedShare.length > 0) {
  1461. videoItem.filePath = `smb://${hostForDisplay}/${cleanedShare}${relativeForDisplay}`;
  1462. } else if (hostForDisplay.length > 0) {
  1463. videoItem.filePath = `smb://${hostForDisplay}${relativeForDisplay}`;
  1464. } else {
  1465. videoItem.filePath = `smb://${account.id}${relativeForDisplay}`;
  1466. }
  1467. const musicData: MusicInfo = parseMusicFileName(fileInfo.fileName);
  1468. if (musicData.isValid) {
  1469. videoItem.artist = musicData.artist;
  1470. videoItem.name = musicData.title;
  1471. }
  1472. return videoItem;
  1473. }
  1474. private ftpEntryToFileInfo(entry: FtpEntryInfo, basePath: string): FileInfo {
  1475. const normalizedBase = this.normalizeFullPath(basePath);
  1476. const targetPath = this.normalizeFullPath(`${normalizedBase === '/' ? '' : normalizedBase}/${entry.name}`);
  1477. const info = new FileInfo(normalizedBase, entry.name, entry.size ?? 0, entry.modifiedAt ? entry.modifiedAt.getTime() : Date.now());
  1478. info.fileName = entry.name;
  1479. info.href = targetPath;
  1480. info.isDirectory = Boolean(entry.isDirectory);
  1481. info.contentLength = entry.size ?? 0;
  1482. info.time = entry.modifiedAt ? entry.modifiedAt.getTime() : Date.now();
  1483. return info;
  1484. }
  1485. private buildFtpVideoItem(fileInfo: FileInfo, account: WebDavAccount): VideoItem {
  1486. const host = this.resolveFtpHost(account);
  1487. if (!host) {
  1488. throw new Error('FTP账号缺少服务器地址');
  1489. }
  1490. const normalizedPath = this.normalizeFullPath(fileInfo.href || `/${fileInfo.fileName}`);
  1491. const encodedPath = encodeURI(normalizedPath);
  1492. const port = account.port && account.port > 0 ? `:${account.port}` : '';
  1493. const ftpUrl = `ftp://${host}${port}${encodedPath}`;
  1494. const videoItem = new VideoItem(
  1495. this.getFileNameWithoutExtension(fileInfo.fileName),
  1496. '',
  1497. ftpUrl,
  1498. CommonConstants.TYPE_FTP,
  1499. fileInfo.contentLength,
  1500. Utility.getFormatDateStr(fileInfo.time, 'yyyy-MM-dd HH:mm')
  1501. );
  1502. videoItem.album = '';
  1503. videoItem.size = Utility.formatFSize(fileInfo.contentLength);
  1504. const musicData: MusicInfo = parseMusicFileName(fileInfo.fileName);
  1505. if (musicData.isValid) {
  1506. videoItem.artist = musicData.artist;
  1507. videoItem.name = musicData.title;
  1508. } else {
  1509. videoItem.artist = Constants.UNKNOWN_ARTIST;
  1510. }
  1511. if (account && account.id) {
  1512. videoItem.webdav_account_id = account.id.toString();
  1513. }
  1514. videoItem.remote_rel_path = normalizedPath;
  1515. return videoItem;
  1516. }
  1517. private baiduEntryToFileInfo(entry: BaiduListEntry): FileInfo {
  1518. const timestamp = (entry.server_mtime ?? Date.now()) * 1000;
  1519. const info = new FileInfo('', entry.server_filename, entry.size, timestamp);
  1520. info.fileName = entry.server_filename;
  1521. info.href = entry.path;
  1522. info.isDirectory = entry.isdir === 1;
  1523. info.contentLength = entry.size;
  1524. info.time = timestamp;
  1525. return info;
  1526. }
  1527. private buildBaiduVideoItem(entry: BaiduListEntry, account: WebDavAccount): VideoItem {
  1528. const timestamp = (entry.server_mtime ?? Date.now()) * 1000;
  1529. const videoItem = new VideoItem(
  1530. this.getFileNameWithoutExtension(entry.server_filename),
  1531. entry.fs_id.toString(),
  1532. `baidupan://${account.id ?? 0}${entry.path}`,
  1533. CommonConstants.TYPE_BAIDU,
  1534. entry.size,
  1535. Utility.getFormatDateStr(timestamp, 'yyyy-MM-dd HH:mm'),
  1536. Utility.formatFSize(entry.size)
  1537. );
  1538. videoItem.size = Utility.formatFSize(entry.size);
  1539. videoItem.album = '';
  1540. videoItem.remote_rel_path = entry.path;
  1541. videoItem.baiduFsId = entry.fs_id.toString();
  1542. if (account && account.id) {
  1543. videoItem.webdav_account_id = account.id.toString();
  1544. }
  1545. const musicData: MusicInfo = parseMusicFileName(entry.server_filename);
  1546. if (musicData.isValid) {
  1547. videoItem.artist = musicData.artist;
  1548. videoItem.name = musicData.title;
  1549. } else {
  1550. videoItem.artist = Constants.UNKNOWN_ARTIST;
  1551. }
  1552. return videoItem;
  1553. }
  1554. private async ensureBaiduAccessToken(account: WebDavAccount): Promise<string> {
  1555. if (account.baiduAccessToken) {
  1556. if (!account.baiduTokenExpiresAt || (account.baiduTokenExpiresAt - Date.now()) > 60 * 1000) {
  1557. return account.baiduAccessToken;
  1558. }
  1559. }
  1560. if (!account.baiduRefreshToken) {
  1561. throw new Error('百度网盘授权已过期,请在账户设置中重新登录百度网盘');
  1562. }
  1563. const token = await refreshBaiduAccessToken(account.baiduRefreshToken);
  1564. account.baiduAccessToken = token.access_token;
  1565. account.baiduRefreshToken = token.refresh_token ?? account.baiduRefreshToken;
  1566. account.baiduTokenExpiresAt = token.expires_in ? Date.now() + token.expires_in * 1000 : 0;
  1567. await this.persistBaiduTokens(account);
  1568. return account.baiduAccessToken;
  1569. }
  1570. private async persistBaiduTokens(account: WebDavAccount): Promise<void> {
  1571. if (!account.id) {
  1572. return;
  1573. }
  1574. const predicates = new relationalStore.RdbPredicates(this.webDavTable);
  1575. predicates.equalTo('id', account.id);
  1576. const values: relationalStore.ValuesBucket = {
  1577. baiduAccessToken: account.baiduAccessToken,
  1578. baiduRefreshToken: account.baiduRefreshToken,
  1579. baiduTokenExpiresAt: account.baiduTokenExpiresAt
  1580. };
  1581. await this.dataBaseUtil.updateData(this.webDavTable, values, predicates);
  1582. }
  1583. private getBaiduCacheKey(account: WebDavAccount, fsId: string): string {
  1584. return `${account.id ?? '0'}_${fsId}`;
  1585. }
  1586. private cacheBaiduDlink(account: WebDavAccount, fsId: string, token: string, url: string): void {
  1587. const key = this.getBaiduCacheKey(account, fsId);
  1588. const expireAt = Date.now() + RemoteDriveManager.BAIDU_DLINK_CACHE_TTL;
  1589. this.baiduDlinkCache.set(key, { url, token, expireAt });
  1590. }
  1591. private getCachedBaiduDlink(account: WebDavAccount, fsId: string, token: string): string | null {
  1592. const key = this.getBaiduCacheKey(account, fsId);
  1593. const cached = this.baiduDlinkCache.get(key);
  1594. if (!cached) {
  1595. return null;
  1596. }
  1597. if (cached.token !== token || cached.expireAt <= Date.now()) {
  1598. this.baiduDlinkCache.delete(key);
  1599. return null;
  1600. }
  1601. return cached.url;
  1602. }
  1603. public async getBaiduDownloadUrl(account: WebDavAccount, song: VideoItem): Promise<string> {
  1604. const accessToken = await this.ensureBaiduAccessToken(account);
  1605. const fsId = song.baiduFsId || song.id;
  1606. if (!fsId) {
  1607. throw new Error('缺少百度网盘文件fs_id');
  1608. }
  1609. const cached = this.getCachedBaiduDlink(account, fsId, accessToken);
  1610. if (cached) {
  1611. Logger.info(TAG, `Baidu dlink cache hit, fsId=${fsId}`);
  1612. return cached;
  1613. }
  1614. const metas = await fetchBaiduFileMetas(accessToken, [fsId]);
  1615. if (!metas || metas.length === 0 || !metas[0].dlink) {
  1616. throw new Error('无法获取下载链接');
  1617. }
  1618. const rawLink = metas[0].dlink.startsWith('https://') ? metas[0].dlink : metas[0].dlink.replace('http://', 'https://');
  1619. const urlWithToken = appendAccessTokenToDlink(rawLink, accessToken);
  1620. Logger.info(TAG, `Baidu dlink ready, fsId=${fsId} url=${urlWithToken}`);
  1621. this.cacheBaiduDlink(account, fsId, accessToken, urlWithToken);
  1622. return urlWithToken;
  1623. }
  1624. public async getBaiduFileInfo(account: WebDavAccount, fsId: string, remotePath?: string): Promise<BaiduFileInfo> {
  1625. const accessToken = await this.ensureBaiduAccessToken(account);
  1626. if (!fsId) {
  1627. throw new Error('缺少百度网盘文件fs_id');
  1628. }
  1629. Logger.info(TAG, `查询百度网盘文件信息: fsId=${fsId}`);
  1630. const metas = await fetchBaiduFileMetas(accessToken, [fsId]);
  1631. if (!metas || metas.length === 0) {
  1632. throw new Error('无法获取文件信息');
  1633. }
  1634. const meta = metas[0];
  1635. if (!meta.dlink) {
  1636. throw new Error('无法获取下载链接');
  1637. }
  1638. const rawLink = meta.dlink.startsWith('https://') ? meta.dlink : meta.dlink.replace('http://', 'https://');
  1639. const urlWithToken = appendAccessTokenToDlink(rawLink, accessToken);
  1640. let streamUrl = urlWithToken;
  1641. if (remotePath) {
  1642. try {
  1643. await ensureAudioStreamReady(accessToken, remotePath);
  1644. streamUrl = buildAudioStreamingUrl(accessToken, remotePath);
  1645. Logger.info(TAG, `百度网盘文件信息获取成功: fsId=${fsId}, size=${meta.size}, streamUrl=${streamUrl}`);
  1646. } catch (streamError) {
  1647. const err = streamError as Error;
  1648. Logger.warn(TAG, `百度音频流暂不可用,回退到下载链接: ${err.message}`);
  1649. streamUrl = urlWithToken;
  1650. }
  1651. } else {
  1652. Logger.warn(TAG, `缺少百度网盘文件路径,使用下载链接播放: fsId=${fsId}`);
  1653. }
  1654. // 缓存 dlink
  1655. this.cacheBaiduDlink(account, fsId, accessToken, urlWithToken);
  1656. const result: BaiduFileInfo = {
  1657. size: meta.size,
  1658. dlink: urlWithToken,
  1659. streamUrl
  1660. };
  1661. return result;
  1662. }
  1663. private smbEntryToFileInfo(entry: SmbDirectoryEntry, basePath: string): FileInfo {
  1664. const normalizedPath = this.combineRemotePath(basePath, entry.name, entry.isDirectory);
  1665. const info = new FileInfo('', entry.name, entry.size, Date.now());
  1666. info.fileName = entry.name;
  1667. info.href = normalizedPath;
  1668. info.contentLength = entry.size ?? 0;
  1669. info.isDirectory = entry.isDirectory;
  1670. return info;
  1671. }
  1672. private combineRemotePath(basePath: string, name: string, isDirectory: boolean): string {
  1673. const segments: string[] = [];
  1674. const trimmedBase = basePath ? basePath.replace(/^\/+/, '').replace(/\/+/g, '/') : '';
  1675. if (trimmedBase.length > 0) {
  1676. segments.push(trimmedBase);
  1677. }
  1678. const cleanedName = name.replace(/^\/+/, '').replace(/\/+/g, '/');
  1679. if (cleanedName.length > 0) {
  1680. segments.push(cleanedName);
  1681. }
  1682. let fullPath = `/${segments.filter(part => part.length > 0).join('/')}`;
  1683. if (isDirectory && !fullPath.endsWith('/')) {
  1684. fullPath = `${fullPath}/`;
  1685. }
  1686. if (!isDirectory && fullPath.endsWith('/')) {
  1687. fullPath = fullPath.slice(0, -1);
  1688. }
  1689. return fullPath;
  1690. }
  1691. private createNavDirectory(name: string, href: string): FileInfo {
  1692. const info = new FileInfo('', name, 0, Date.now());
  1693. info.fileName = name;
  1694. info.href = this.normalizeFullPath(href);
  1695. info.isDirectory = true;
  1696. return info;
  1697. }
  1698. private createNavSongFileInfo(song: NavidromeSong, albumId: string): FileInfo {
  1699. const displayName = song.title ?? '未知曲目';
  1700. const info = new FileInfo('', displayName, song.size ?? 0, Date.now());
  1701. info.fileName = `${displayName}${song.suffix ? '.' + song.suffix : ''}`;
  1702. info.href = this.normalizeFullPath(`/album/${albumId}/${song.id}`);
  1703. info.isDirectory = false;
  1704. info.contentLength = song.size ?? 0;
  1705. return info;
  1706. }
  1707. private buildNavidromeVideoItem(song: NavidromeSong, account: WebDavAccount, album?: NavidromeAlbumDetail, coverUrl?: string): VideoItem {
  1708. const title = song.title ?? '未知曲目';
  1709. const fileName = `${title}${song.suffix ? '.' + song.suffix : ''}`;
  1710. const videoItem = new VideoItem(
  1711. title,
  1712. song.id,
  1713. `navidrome://${account.id ?? 0}/${song.id}`,
  1714. CommonConstants.TYPE_NAVIDROME,
  1715. song.size ?? 0,
  1716. Utility.getFormatDateStr(Date.now(), 'yyyy-MM-dd HH:mm'),
  1717. Utility.formatFSize(song.size ?? 0),
  1718. undefined,
  1719. song.artist ?? album?.artist ?? Constants.UNKNOWN_ARTIST,
  1720. album?.name ?? song.album,
  1721. fileName
  1722. );
  1723. videoItem.size = Utility.formatFSize(song.size ?? 0);
  1724. videoItem.webdav_account_id = account.id?.toString();
  1725. videoItem.remote_rel_path = song.id;
  1726. videoItem.bit_rate = song.bitRate ? song.bitRate.toString() : undefined;
  1727. videoItem.mimeType = song.contentType;
  1728. videoItem.pixelMapPath = coverUrl;
  1729. if (song.track !== undefined && song.track !== null) {
  1730. videoItem.track = song.track.toString();
  1731. }
  1732. if (song.year !== undefined && song.year !== null) {
  1733. videoItem.year = song.year.toString();
  1734. }
  1735. return videoItem;
  1736. }
  1737. private registerPathLabel(path: string, label: string): void {
  1738. if (!path || label === undefined) {
  1739. return;
  1740. }
  1741. const normalized = this.normalizeFullPath(path);
  1742. const sanitizedLabel = this.sanitizeLabel(label);
  1743. this.pathDisplayNames.set(normalized, sanitizedLabel);
  1744. }
  1745. private sanitizeLabel(label: string): string {
  1746. if (!label) {
  1747. return '';
  1748. }
  1749. if (label === '根目录') {
  1750. return label;
  1751. }
  1752. let sanitized = label.trim();
  1753. sanitized = sanitized.replace(/\/+$/, '');
  1754. if (sanitized.length === 0) {
  1755. sanitized = '/';
  1756. }
  1757. try {
  1758. sanitized = decodeURIComponent(sanitized);
  1759. } catch (error) {
  1760. // ignore decode failure, keep original label
  1761. }
  1762. return sanitized;
  1763. }
  1764. private getBasePath(account: WebDavAccount | null = this.currentAccount): string {
  1765. if (account && account.filepath) {
  1766. return this.normalizeFullPath(account.filepath);
  1767. }
  1768. return '/';
  1769. }
  1770. private getRelativePath(fullPath: string, basePath: string): string {
  1771. const normalizedFull = this.normalizeFullPath(fullPath);
  1772. const normalizedBase = this.normalizeFullPath(basePath);
  1773. if (normalizedFull === normalizedBase) {
  1774. return '';
  1775. }
  1776. if (normalizedFull.startsWith(normalizedBase) && normalizedBase !== '/') {
  1777. return normalizedFull.substring(normalizedBase.length).replace(/^\/+/, '');
  1778. }
  1779. return normalizedFull.replace(/^\/+/, '');
  1780. }
  1781. private normalizeSmbRelativePath(path: string, shareName?: string): string {
  1782. if (!path || path.trim().length === 0) {
  1783. return '/';
  1784. }
  1785. let normalized = path.replace(/\/+/g, '/');
  1786. if (!normalized.startsWith('/')) {
  1787. normalized = `/${normalized}`;
  1788. }
  1789. if (normalized.length > 1 && normalized.endsWith('/')) {
  1790. normalized = normalized.slice(0, -1);
  1791. }
  1792. if (shareName) {
  1793. const cleanedShare = shareName.replace(/^\/+|\/+$/g, '');
  1794. if (cleanedShare.length > 0) {
  1795. const prefix = `/${cleanedShare}`;
  1796. if (normalized === prefix) {
  1797. normalized = '/';
  1798. } else if (normalized.startsWith(`${prefix}/`)) {
  1799. normalized = normalized.substring(prefix.length);
  1800. if (!normalized.startsWith('/')) {
  1801. normalized = `/${normalized}`;
  1802. }
  1803. }
  1804. }
  1805. }
  1806. return normalized || '/';
  1807. }
  1808. // 判断是否为音频文件
  1809. private isAudioFile(fileName: string): boolean {
  1810. const ext = this.getFileExtension(fileName).toLowerCase();
  1811. for (let i = 0; i < this.audioExtensions.length; i++) {
  1812. if (ext === this.audioExtensions[i]) {
  1813. return true;
  1814. }
  1815. }
  1816. return false;
  1817. }
  1818. // 获取文件扩展名
  1819. private getFileExtension(fileName: string): string {
  1820. const lastDotIndex = fileName.lastIndexOf('.');
  1821. if (lastDotIndex === -1) {
  1822. return '';
  1823. }
  1824. return fileName.substring(lastDotIndex);
  1825. }
  1826. // 获取不带扩展名的文件名
  1827. private getFileNameWithoutExtension(fileName: string): string {
  1828. const lastDotIndex = fileName.lastIndexOf('.');
  1829. if (lastDotIndex === -1) {
  1830. return fileName;
  1831. }
  1832. return fileName.substring(0, lastDotIndex);
  1833. }
  1834. // 进入文件夹
  1835. public async enterFolder(folder: FileInfo): Promise<void> {
  1836. if (!folder.isDirectory) {
  1837. Logger.error(TAG, '不是文件夹,无法进入');
  1838. return;
  1839. }
  1840. Logger.info(TAG, '准备进入文件夹:', folder.fileName);
  1841. Logger.info(TAG, '当前路径:', this.currentPath);
  1842. Logger.info(TAG, '目标路径:', folder.href);
  1843. // 保存当前路径到历史记录
  1844. this.registerPathLabel(folder.href, folder.fileName);
  1845. this.pathHistory.push(this.currentPath);
  1846. Logger.info(TAG, '路径历史:', JSON.stringify(this.pathHistory));
  1847. // 加载文件夹内容
  1848. await this.loadFilesInfoFromAccount(this.currentAccount, folder.href);
  1849. }
  1850. public async enterFolderFromPath(path: string): Promise<void> {
  1851. const normalizedTarget = this.normalizeFullPath(path);
  1852. Logger.info(TAG, '当前路径:', this.currentPath);
  1853. Logger.info(TAG, '目标路径:', normalizedTarget);
  1854. this.rebuildPathHistoryForTarget(normalizedTarget);
  1855. Logger.info(TAG, '路径历史:', JSON.stringify(this.pathHistory));
  1856. await this.loadFilesInfoFromAccount(this.currentAccount, normalizedTarget);
  1857. }
  1858. private rebuildPathHistoryForTarget(targetPath: string): void {
  1859. if (!targetPath) {
  1860. this.pathHistory = [];
  1861. return;
  1862. }
  1863. const normalizedTarget = this.normalizeFullPath(targetPath);
  1864. const basePath = this.getBasePath();
  1865. if (normalizedTarget === basePath) {
  1866. this.pathHistory = [];
  1867. return;
  1868. }
  1869. const relativePath = this.getRelativePath(normalizedTarget, basePath);
  1870. if (!relativePath) {
  1871. this.pathHistory = [];
  1872. return;
  1873. }
  1874. const parts = relativePath.split('/').filter(part => part.length > 0);
  1875. const rebuiltHistory: string[] = [];
  1876. // 把账户根路径作为栈底,以便可以返回
  1877. rebuiltHistory.push(basePath);
  1878. let cumulative = basePath;
  1879. for (let i = 0; i < parts.length - 1; i++) {
  1880. const segment = parts[i];
  1881. cumulative = this.normalizeFullPath(`${cumulative === '/' ? '' : cumulative}/${segment}`);
  1882. rebuiltHistory.push(cumulative);
  1883. }
  1884. this.pathHistory = rebuiltHistory;
  1885. }
  1886. // 返回上级目录
  1887. public async goBack(): Promise<void> {
  1888. if (this.pathHistory.length === 0) {
  1889. Logger.info(TAG, '已经在根目录,无法返回');
  1890. return;
  1891. }
  1892. // 从历史记录中取出上一级路径
  1893. const previousPath = this.pathHistory.pop();
  1894. if (previousPath !== undefined) {
  1895. await this.loadFilesInfoFromAccount(this.currentAccount, previousPath);
  1896. }
  1897. }
  1898. // 获取面包屑路径数组
  1899. public getBreadcrumbs(): BreadcrumbItem[] {
  1900. const basePath = this.getBasePath();
  1901. const breadcrumbs: BreadcrumbItem[] = [{
  1902. label: '根目录',
  1903. path: basePath
  1904. }];
  1905. if (!this.currentPath || this.normalizeFullPath(this.currentPath) === basePath) {
  1906. return breadcrumbs;
  1907. }
  1908. const relativePath = this.getRelativePath(this.currentPath, basePath);
  1909. if (!relativePath) {
  1910. return breadcrumbs;
  1911. }
  1912. const parts = relativePath.split('/').filter(part => part.length > 0);
  1913. let cumulative = basePath;
  1914. for (let i = 0; i < parts.length; i++) {
  1915. const segment = parts[i];
  1916. const targetPath = this.normalizeFullPath(`${cumulative === '/' ? '' : cumulative}/${segment}`);
  1917. const label = this.pathDisplayNames.get(targetPath) ?? segment;
  1918. breadcrumbs.push({
  1919. label: this.sanitizeLabel(label),
  1920. path: targetPath
  1921. });
  1922. cumulative = targetPath;
  1923. }
  1924. return breadcrumbs;
  1925. }
  1926. // 是否可以返回上级
  1927. public canGoBack(): boolean {
  1928. if(this.currentPath==='/')
  1929. return false
  1930. return this.pathHistory.length > 0;
  1931. }
  1932. // ==================== Preferences操作 ====================
  1933. // 加载历史数据(从Preferences迁移)
  1934. public async loadInfo(): Promise<void> {
  1935. try {
  1936. // 这里可以添加从Preferences加载历史配置的逻辑
  1937. Logger.info(TAG, '从Preferences加载配置');
  1938. } catch (error) {
  1939. Logger.error(TAG, '从Preferences加载配置失败:', error.toString());
  1940. }
  1941. }
  1942. // 保存配置到Preferences
  1943. public async saveInfo(): Promise<void> {
  1944. try {
  1945. // 这里可以添加保存配置到Preferences的逻辑
  1946. Logger.info(TAG, '保存配置到Preferences');
  1947. } catch (error) {
  1948. Logger.error(TAG, '保存配置到Preferences失败:', error.toString());
  1949. }
  1950. }
  1951. // ==================== 下载队列管理 ====================
  1952. // 添加到下载队列
  1953. public addToDownloadQueue(song: VideoItem, account: WebDavAccount): void {
  1954. const task: TransferTask = { song, account };
  1955. this.downloadQueue.push(task);
  1956. Logger.info(TAG, '添加到下载队列:', song.name);
  1957. this.notifyObservers(RemoteDriveManagerStates.DownloadQueueChanged);
  1958. }
  1959. // 从下载队列移除
  1960. public removeFromDownloadQueue(index: number): void {
  1961. if (index >= 0 && index < this.downloadQueue.length) {
  1962. const task = this.downloadQueue[index];
  1963. this.downloadQueue.splice(index, 1);
  1964. Logger.info(TAG, '从下载队列移除:', task.song.name);
  1965. this.notifyObservers(RemoteDriveManagerStates.DownloadQueueChanged);
  1966. }
  1967. }
  1968. // 清空下载队列
  1969. public clearDownloadQueue(): void {
  1970. this.downloadQueue = [];
  1971. Logger.info(TAG, '清空下载队列');
  1972. this.notifyObservers(RemoteDriveManagerStates.DownloadQueueChanged);
  1973. }
  1974. // ==================== 上传队列管理 ====================
  1975. /**
  1976. * 添加歌曲到上传队列
  1977. * @param songs 要上传的歌曲列表
  1978. * @param account 目标WebDAV账户
  1979. * @param customUploadPath 自定义上传路径(可选,如果不提供则使用账户默认路径)
  1980. */
  1981. public addToUploadQueue(songs: VideoItem[], account: WebDavAccount, customUploadPath?: string): void {
  1982. Logger.info(TAG, '========== 添加上传任务 ==========');
  1983. Logger.info(TAG, `请求添加: ${songs.length} 个文件`);
  1984. Logger.info(TAG, `目标账户: ${account.name} (ID: ${account.id})`);
  1985. Logger.info(TAG, `自定义上传路径: ${customUploadPath || '未指定,使用账户默认路径'}`);
  1986. Logger.info(TAG, `当前队列: ${this.uploadQueue.length}/${this.MAX_UPLOAD_QUEUE_SIZE}`);
  1987. // 检查队列大小限制
  1988. const availableSlots = this.MAX_UPLOAD_QUEUE_SIZE - this.uploadQueue.length;
  1989. if (availableSlots <= 0) {
  1990. Logger.warn(TAG, `上传队列已满(最大${this.MAX_UPLOAD_QUEUE_SIZE}个任务),无法添加更多任务`);
  1991. Logger.warn(TAG, '====================================');
  1992. return;
  1993. }
  1994. // 限制添加数量
  1995. const songsToAdd = songs.length > availableSlots ? songs.slice(0, availableSlots) : songs;
  1996. const existingKeys = new Set<string>();
  1997. for (let i = 0; i < this.uploadQueue.length; i++) {
  1998. const key = this.getSongKey(this.uploadQueue[i].song);
  1999. if (key) {
  2000. existingKeys.add(key);
  2001. }
  2002. }
  2003. const filteredSongs: VideoItem[] = [];
  2004. for (let i = 0; i < songsToAdd.length; i++) {
  2005. const song = songsToAdd[i];
  2006. const key = this.getSongKey(song);
  2007. if (key && existingKeys.has(key)) {
  2008. Logger.warn(TAG, `检测到重复任务,已跳过: ${song.name}`);
  2009. continue;
  2010. }
  2011. if (key) {
  2012. existingKeys.add(key);
  2013. }
  2014. filteredSongs.push(song);
  2015. }
  2016. Logger.info(TAG, `实际添加: ${filteredSongs.length} 个文件`);
  2017. for (let i = 0; i < filteredSongs.length; i++) {
  2018. const song = filteredSongs[i];
  2019. const task: TransferTask = {
  2020. song,
  2021. account,
  2022. customUploadPath: customUploadPath // 保存自定义上传路径
  2023. };
  2024. this.uploadQueue.push(task);
  2025. Logger.info(TAG, `[${i + 1}/${songsToAdd.length}] ${song.name}`);
  2026. }
  2027. if (songs.length > songsToAdd.length) {
  2028. Logger.warn(TAG, `队列空间不足,仅处理前${songsToAdd.length}/${songs.length}个任务`);
  2029. }
  2030. Logger.info(TAG, `新队列大小: ${this.uploadQueue.length}/${this.MAX_UPLOAD_QUEUE_SIZE}`);
  2031. Logger.info(TAG, '====================================');
  2032. this.notifyObservers(RemoteDriveManagerStates.UploadQueueChanged);
  2033. this.notifyObservers(RemoteDriveManagerStates.ChangeUploadQueue);
  2034. }
  2035. /**
  2036. * 开始处理上传队列
  2037. */
  2038. public async startUploadQueue(): Promise<void> {
  2039. if (this.isProcessingUploadQueue) {
  2040. Logger.warn(TAG, '上传队列正在处理中');
  2041. return;
  2042. }
  2043. if (this.uploadQueue.length === 0) {
  2044. Logger.info(TAG, '上传队列为空');
  2045. return;
  2046. }
  2047. this.isProcessingUploadQueue = true;
  2048. this.isPauseUpload = false;
  2049. Logger.info(TAG, '开始处理上传队列,共', this.uploadQueue.length.toString(), '个任务');
  2050. await this.processNextUploadTask();
  2051. }
  2052. /**
  2053. * 处理下一个上传任务
  2054. */
  2055. private async processNextUploadTask(): Promise<void> {
  2056. if (this.isPauseUpload) {
  2057. Logger.info(TAG, '========== 上传队列已暂停 ==========');
  2058. Logger.info(TAG, `剩余任务数: ${this.uploadQueue.length}`);
  2059. Logger.info(TAG, '====================================');
  2060. this.isProcessingUploadQueue = false;
  2061. return;
  2062. }
  2063. if (this.uploadQueue.length === 0) {
  2064. Logger.info(TAG, '========== 上传队列已完成 ==========');
  2065. Logger.info(TAG, `成功上传: ${this.finishUploadQueue.length} 个文件`);
  2066. Logger.info(TAG, '====================================');
  2067. this.isProcessingUploadQueue = false;
  2068. this.currentUploadTask = null;
  2069. this.notifyObservers(RemoteDriveManagerStates.SetCurrentUploadTask);
  2070. // 检查是否需要自动清理完成队列
  2071. const autoClear = PreferencesUtil.getBooleanSync('webdavUploadAutoClear', false);
  2072. if (autoClear && this.finishUploadQueue.length > 0) {
  2073. Logger.info(TAG, '自动清理完成队列');
  2074. this.finishUploadQueue = [];
  2075. this.notifyObservers(RemoteDriveManagerStates.ChangeFinishUploadQueue);
  2076. }
  2077. return;
  2078. }
  2079. const task = this.uploadQueue[0];
  2080. this.currentUploadTask = task;
  2081. Logger.info(TAG, '========== 处理上传队列 ==========');
  2082. Logger.info(TAG, `当前任务: ${task.song.name}`);
  2083. Logger.info(TAG, `队列位置: 1/${this.uploadQueue.length}`);
  2084. Logger.info(TAG, `已完成: ${this.finishUploadQueue.length}`);
  2085. Logger.info(TAG, '====================================');
  2086. this.notifyObservers(RemoteDriveManagerStates.SetCurrentUploadTask);
  2087. try {
  2088. await this.uploadSingleFile(task);
  2089. // 上传成功,移到完成队列
  2090. Logger.info(TAG, `任务成功,移至完成队列: ${task.song.name}`);
  2091. this.uploadQueue.shift();
  2092. this.finishUploadQueue.push(task);
  2093. this.notifyObservers(RemoteDriveManagerStates.UploadSuccess);
  2094. this.notifyObservers(RemoteDriveManagerStates.ChangeUploadQueue);
  2095. this.notifyObservers(RemoteDriveManagerStates.ChangeFinishUploadQueue);
  2096. // 继续处理下一个任务
  2097. await this.processNextUploadTask();
  2098. } catch (error) {
  2099. const err = error as Error;
  2100. Logger.error(TAG, '---------- 任务失败 ----------');
  2101. Logger.error(TAG, `文件: ${task.song.name}`);
  2102. Logger.error(TAG, `错误: ${err.message}`);
  2103. // 获取重试次数设置
  2104. const maxRetryCount = PreferencesUtil.getNumberSync('webdavUploadRetryCount', 3);
  2105. const currentRetryCount = task.retryCount || 0;
  2106. if (currentRetryCount < maxRetryCount) {
  2107. // 还可以重试
  2108. task.retryCount = currentRetryCount + 1;
  2109. Logger.info(TAG, `准备重试上传 (${task.retryCount}/${maxRetryCount}): ${task.song.name}`);
  2110. Logger.info(TAG, '将任务移至队列末尾');
  2111. // 将任务移到队列末尾重试
  2112. this.uploadQueue.shift();
  2113. this.uploadQueue.push(task);
  2114. this.notifyObservers(RemoteDriveManagerStates.ChangeUploadQueue);
  2115. } else {
  2116. // 已达到最大重试次数,放弃上传
  2117. Logger.error(TAG, `上传失败,已达到最大重试次数 (${maxRetryCount}): ${task.song.name}`);
  2118. Logger.error(TAG, '从队列中移除该任务');
  2119. this.uploadQueue.shift();
  2120. this.notifyObservers(RemoteDriveManagerStates.UploadFailed);
  2121. this.notifyObservers(RemoteDriveManagerStates.ChangeUploadQueue);
  2122. }
  2123. Logger.error(TAG, '------------------------------');
  2124. // 继续处理下一个任务
  2125. await this.processNextUploadTask();
  2126. }
  2127. }
  2128. /**
  2129. * 暂停上传队列
  2130. */
  2131. public pauseUploadQueue(): void {
  2132. Logger.info(TAG, '========== 暂停上传队列 ==========');
  2133. if (!this.isProcessingUploadQueue) {
  2134. Logger.warn(TAG, '上传队列未在处理中,无需暂停');
  2135. Logger.info(TAG, '====================================');
  2136. return;
  2137. }
  2138. this.isPauseUpload = true;
  2139. Logger.info(TAG, `当前任务: ${this.currentUploadTask?.song.name || '无'}`);
  2140. Logger.info(TAG, `剩余任务: ${this.uploadQueue.length}`);
  2141. Logger.info(TAG, '上传队列已暂停');
  2142. Logger.info(TAG, '====================================');
  2143. this.notifyObservers(RemoteDriveManagerStates.UploadPaused);
  2144. this.notifyObservers(RemoteDriveManagerStates.SetIsPauseUpload);
  2145. }
  2146. /**
  2147. * 恢复上传队列
  2148. */
  2149. public async resumeUploadQueue(): Promise<void> {
  2150. Logger.info(TAG, '========== 恢复上传队列 ==========');
  2151. if (!this.isPauseUpload) {
  2152. Logger.warn(TAG, '上传队列未暂停,无需恢复');
  2153. Logger.info(TAG, '====================================');
  2154. return;
  2155. }
  2156. this.isPauseUpload = false;
  2157. Logger.info(TAG, `剩余任务: ${this.uploadQueue.length}`);
  2158. Logger.info(TAG, '上传队列已恢复');
  2159. Logger.info(TAG, '====================================');
  2160. this.notifyObservers(RemoteDriveManagerStates.UploadResumed);
  2161. this.notifyObservers(RemoteDriveManagerStates.SetIsPauseUpload);
  2162. if (!this.isProcessingUploadQueue) {
  2163. this.isProcessingUploadQueue = true;
  2164. await this.processNextUploadTask();
  2165. }
  2166. }
  2167. /**
  2168. * 从队列中移除任务
  2169. * @param task 要移除的任务
  2170. */
  2171. public removeFromUploadQueue(task: TransferTask): void {
  2172. const index = this.uploadQueue.indexOf(task);
  2173. if (index >= 0) {
  2174. Logger.info(TAG, '========== 移除上传任务 ==========');
  2175. Logger.info(TAG, `文件名: ${task.song.name}`);
  2176. Logger.info(TAG, `队列位置: ${index + 1}/${this.uploadQueue.length}`);
  2177. this.uploadQueue.splice(index, 1);
  2178. Logger.info(TAG, `新队列大小: ${this.uploadQueue.length}`);
  2179. Logger.info(TAG, '====================================');
  2180. this.notifyObservers(RemoteDriveManagerStates.UploadQueueChanged);
  2181. this.notifyObservers(RemoteDriveManagerStates.ChangeUploadQueue);
  2182. } else {
  2183. Logger.warn(TAG, `任务不在队列中: ${task.song.name}`);
  2184. }
  2185. }
  2186. /**
  2187. * 清空上传队列
  2188. */
  2189. public clearUploadQueue(): void {
  2190. Logger.info(TAG, '========== 清空上传队列 ==========');
  2191. Logger.info(TAG, `清空前队列大小: ${this.uploadQueue.length}`);
  2192. this.uploadQueue = [];
  2193. this.currentUploadTask = null;
  2194. Logger.info(TAG, '上传队列已清空');
  2195. Logger.info(TAG, '====================================');
  2196. this.notifyObservers(RemoteDriveManagerStates.UploadQueueChanged);
  2197. this.notifyObservers(RemoteDriveManagerStates.ChangeUploadQueue);
  2198. this.notifyObservers(RemoteDriveManagerStates.SetCurrentUploadTask);
  2199. }
  2200. /**
  2201. * 检查是否允许在当前网络下上传
  2202. */
  2203. private async checkNetworkAllowed(): Promise<boolean> {
  2204. try {
  2205. Logger.info(TAG, '检查网络连接状态...');
  2206. const allowMobile = PreferencesUtil.getBooleanSync('webdavUploadAllowMobile', false);
  2207. Logger.info(TAG, `用户设置 - 允许移动网络上传: ${allowMobile}`);
  2208. // 如果允许移动网络上传,直接返回true
  2209. if (allowMobile) {
  2210. Logger.info(TAG, '用户已允许移动网络上传,跳过网络类型检查');
  2211. return true;
  2212. }
  2213. // 检查当前网络类型
  2214. Logger.info(TAG, '获取当前网络类型...');
  2215. const netHandle = await connection.getDefaultNet();
  2216. const netCapabilities = await connection.getNetCapabilities(netHandle);
  2217. // 检查是否为移动网络
  2218. const isCellular = netCapabilities.bearerTypes.includes(connection.NetBearType.BEARER_CELLULAR);
  2219. const isWifi = netCapabilities.bearerTypes.includes(connection.NetBearType.BEARER_WIFI);
  2220. const isEthernet = netCapabilities.bearerTypes.includes(connection.NetBearType.BEARER_ETHERNET);
  2221. Logger.info(TAG, `网络类型 - 移动网络: ${isCellular}, WiFi: ${isWifi}, 以太网: ${isEthernet}`);
  2222. if (isCellular) {
  2223. Logger.warn(TAG, '当前为移动网络,且未允许移动网络上传');
  2224. Logger.warn(TAG, '请连接WiFi或在设置中允许移动网络上传');
  2225. return false;
  2226. }
  2227. Logger.info(TAG, '网络检查通过,允许上传');
  2228. return true;
  2229. } catch (error) {
  2230. const err = error as Error;
  2231. Logger.error(TAG, '检查网络类型失败:', err.message);
  2232. Logger.warn(TAG, '网络检查失败,默认允许上传');
  2233. // 检查失败时默认允许上传
  2234. return true;
  2235. }
  2236. }
  2237. /**
  2238. * 上传单个文件
  2239. * @param task 上传任务
  2240. */
  2241. private async uploadSingleFile(task: TransferTask): Promise<void> {
  2242. const song = task.song;
  2243. const account = task.account;
  2244. const startTime = Date.now();
  2245. // 详细日志:上传开始
  2246. Logger.info(TAG, '========== 上传任务开始 ==========');
  2247. Logger.info(TAG, `文件名: ${song.name}`);
  2248. Logger.info(TAG, `文件路径: ${song.filePath}`);
  2249. Logger.info(TAG, `文件大小: ${song.videoSize || 0} 字节`);
  2250. Logger.info(TAG, `目标账户: ${account.name} (ID: ${account.id})`);
  2251. Logger.info(TAG, `目标主机: ${account.host}:${account.port}`);
  2252. Logger.info(TAG, `使用HTTPS: ${account.enableHttps}`);
  2253. Logger.info(TAG, `重试次数: ${task.retryCount || 0}`);
  2254. try {
  2255. // 检查网络是否允许上传
  2256. Logger.info(TAG, '检查网络连接状态...');
  2257. const networkAllowed = await this.checkNetworkAllowed();
  2258. if (!networkAllowed) {
  2259. const errorMsg = '当前网络不允许上传,请连接WiFi或在设置中允许移动网络上传';
  2260. Logger.error(TAG, `网络检查失败: ${errorMsg}`);
  2261. throw new Error(errorMsg);
  2262. }
  2263. Logger.info(TAG, '网络检查通过');
  2264. this.notifyObservers(RemoteDriveManagerStates.UploadStart);
  2265. // 构建远程路径 - 优先使用任务中的自定义路径,否则使用账户默认路径
  2266. const uploadPath = task.customUploadPath || account.uploadFilePath || '/';
  2267. const normalizedPath = this.normalizeFullPath(uploadPath);
  2268. const relativeSegment = this.sanitizeRelativeUploadPath(song.remote_rel_path);
  2269. const fallbackFileName = song.fileName || song.name || `upload-${Date.now()}`;
  2270. const relativePath = relativeSegment.length > 0 ? relativeSegment : fallbackFileName;
  2271. const remotePath = this.combineRemoteUploadPath(normalizedPath, relativePath);
  2272. Logger.info(TAG, '---------- 路径信息 ----------');
  2273. Logger.info(TAG, `任务自定义路径: ${task.customUploadPath || '未指定'}`);
  2274. Logger.info(TAG, `账户默认路径: ${account.uploadFilePath || '未配置'}`);
  2275. Logger.info(TAG, `实际使用路径: ${uploadPath}`);
  2276. Logger.info(TAG, `规范化后的路径: ${normalizedPath}`);
  2277. Logger.info(TAG, `文件名 (fileName): ${song.fileName}`);
  2278. Logger.info(TAG, `文件名 (name): ${song.name}`);
  2279. Logger.info(TAG, `文件相对路径: ${relativePath}`);
  2280. Logger.info(TAG, `最终远程路径: ${remotePath}`);
  2281. Logger.info(TAG, `完整URL将是: ${account.enableHttps ? 'https' : 'http'}://${account.host}:${account.port}${remotePath}`);
  2282. Logger.info(TAG, '------------------------------');
  2283. // 检查文件是否存在
  2284. Logger.info(TAG, '检查远程文件是否存在...');
  2285. const exists = await this.checkFileExists(account, remotePath);
  2286. if (exists) {
  2287. // 根据用户配置的重复文件处理方式来处理
  2288. const duplicateAction = PreferencesUtil.getStringSync('webdavUploadDuplicateAction', 'skip');
  2289. Logger.info(TAG, `文件已存在,处理方式: ${duplicateAction}`);
  2290. if (duplicateAction === 'skip') {
  2291. Logger.warn(TAG, '文件已存在,跳过上传:', remotePath);
  2292. return;
  2293. } else if (duplicateAction === 'overwrite') {
  2294. Logger.warn(TAG, '文件已存在,将覆盖:', remotePath);
  2295. } else if (duplicateAction === 'rename') {
  2296. Logger.warn(TAG, '文件已存在,将重命名上传');
  2297. // 重命名逻辑可以在这里实现
  2298. }
  2299. } else {
  2300. Logger.info(TAG, '远程文件不存在,可以上传');
  2301. }
  2302. const remoteDirectory = this.getDirectoryFromRemotePath(remotePath);
  2303. await this.ensureRemoteDirectories(account, remoteDirectory);
  2304. // 执行上传
  2305. Logger.info(TAG, '开始上传文件数据...');
  2306. const host = account.isUseLocalHost && account.localHost ? account.localHost : account.host;
  2307. await this.rcpSocket.uploadFile(
  2308. song.filePath,
  2309. remotePath,
  2310. host,
  2311. account.port,
  2312. account.account,
  2313. account.password,
  2314. account.enableHttps,
  2315. (uploaded: number, total: number) => {
  2316. this.uploadReceivedSize = uploaded;
  2317. this.uploadTotalSize = total;
  2318. // 直接通知UI更新,因为RcpSocketUtil层已经做了节流
  2319. // 详细日志:上传进度
  2320. const progress = total > 0 ? Math.min(100, ((uploaded / total) * 100)) : 0;
  2321. const currentTime = Date.now();
  2322. const elapsedSeconds = (currentTime - startTime) / 1000;
  2323. const speedMBps = uploaded > 0 && elapsedSeconds > 0 ? (uploaded / (1024 * 1024) / elapsedSeconds).toFixed(2) : '0.00';
  2324. Logger.info(TAG, `上传进度: ${progress.toFixed(2)}%, 已上传: ${uploaded}/${total} 字节, 速度: ${speedMBps} MB/s`);
  2325. this.notifyObservers(RemoteDriveManagerStates.UploadProgress);
  2326. }
  2327. );
  2328. // 上传成功
  2329. const endTime = Date.now();
  2330. const duration = ((endTime - startTime) / 1000).toFixed(2);
  2331. const avgSpeed = song.videoSize > 0 ? ((song.videoSize / (1024 * 1024)) / parseFloat(duration)).toFixed(2) : '0.00';
  2332. Logger.info(TAG, '========== 上传任务成功 ==========');
  2333. Logger.info(TAG, `文件名: ${song.name}`);
  2334. Logger.info(TAG, `耗时: ${duration} 秒`);
  2335. Logger.info(TAG, `平均速度: ${avgSpeed} MB/s`);
  2336. Logger.info(TAG, `目标路径: ${remotePath}`);
  2337. Logger.info(TAG, '====================================');
  2338. } catch (error) {
  2339. const err = error as Error;
  2340. const endTime = Date.now();
  2341. const duration = ((endTime - startTime) / 1000).toFixed(2);
  2342. // 详细错误日志
  2343. Logger.error(TAG, '========== 上传任务失败 ==========');
  2344. Logger.error(TAG, `文件名: ${song.name}`);
  2345. Logger.error(TAG, `文件路径: ${song.filePath}`);
  2346. Logger.error(TAG, `目标账户: ${account.name} (ID: ${account.id})`);
  2347. Logger.error(TAG, `目标主机: ${account.host}:${account.port}`);
  2348. Logger.error(TAG, `耗时: ${duration} 秒`);
  2349. Logger.error(TAG, `错误类型: ${this.getErrorType(err)}`);
  2350. Logger.error(TAG, `错误信息: ${err.message}`);
  2351. Logger.error(TAG, `错误堆栈: ${err.stack || '无堆栈信息'}`);
  2352. Logger.error(TAG, `重试次数: ${task.retryCount || 0}`);
  2353. Logger.error(TAG, '====================================');
  2354. // 根据错误类型进行分类处理
  2355. this.handleUploadError(err, task);
  2356. // 重新抛出错误以便上层处理
  2357. throw err;
  2358. }
  2359. }
  2360. /**
  2361. * 获取错误类型
  2362. * @param error 错误对象
  2363. * @returns 错误类型字符串
  2364. */
  2365. private getErrorType(error: Error): string {
  2366. const message = error.message.toLowerCase();
  2367. if (message.includes('network') || message.includes('连接') || message.includes('timeout') || message.includes('超时')) {
  2368. return '网络错误';
  2369. } else if (message.includes('auth') || message.includes('认证') || message.includes('401') || message.includes('403')) {
  2370. return '认证错误';
  2371. } else if (message.includes('file') || message.includes('文件') || message.includes('not found') || message.includes('不存在')) {
  2372. return '文件错误';
  2373. } else if (message.includes('server') || message.includes('服务器') || message.includes('500') || message.includes('503')) {
  2374. return '服务器错误';
  2375. } else if (message.includes('space') || message.includes('空间') || message.includes('disk') || message.includes('磁盘')) {
  2376. return '存储空间错误';
  2377. } else {
  2378. return '未知错误';
  2379. }
  2380. }
  2381. /**
  2382. * 处理上传错误
  2383. * @param error 错误对象
  2384. * @param task 上传任务
  2385. */
  2386. private handleUploadError(error: Error, task: TransferTask): void {
  2387. const errorType = this.getErrorType(error);
  2388. Logger.info(TAG, `处理上传错误,类型: ${errorType}`);
  2389. // 根据错误类型决定是否自动暂停
  2390. if (errorType === '网络错误') {
  2391. Logger.warn(TAG, '检测到网络错误,自动暂停上传队列');
  2392. this.pauseUploadQueue();
  2393. } else if (errorType === '认证错误') {
  2394. Logger.error(TAG, '检测到认证错误,请检查账户密码是否正确');
  2395. // 认证错误通常不需要暂停整个队列,但应该提示用户
  2396. } else if (errorType === '服务器错误') {
  2397. Logger.error(TAG, '检测到服务器错误,服务器可能暂时不可用');
  2398. // 服务器错误可能是临时的,可以继续尝试其他文件
  2399. } else if (errorType === '存储空间错误') {
  2400. Logger.error(TAG, '检测到存储空间不足,暂停上传队列');
  2401. this.pauseUploadQueue();
  2402. }
  2403. }
  2404. /**
  2405. * 检查文件是否存在
  2406. * @param account WebDAV账户
  2407. * @param remotePath 远程路径
  2408. */
  2409. private async checkFileExists(account: WebDavAccount, remotePath: string): Promise<boolean> {
  2410. try {
  2411. Logger.info(TAG, `检查远程文件是否存在: ${remotePath}`);
  2412. const host = account.isUseLocalHost && account.localHost ? account.localHost : account.host;
  2413. const fileSize = await this.rcpSocket.RcpSendHead(
  2414. host,
  2415. account.port,
  2416. account.account,
  2417. account.password,
  2418. remotePath,
  2419. account.enableHttps
  2420. );
  2421. const exists = fileSize > 0;
  2422. Logger.info(TAG, `文件${exists ? '存在' : '不存在'}, 大小: ${fileSize} 字节`);
  2423. return exists;
  2424. } catch (error) {
  2425. const err = error as Error;
  2426. // HEAD请求失败,说明文件不存在或网络错误
  2427. Logger.info(TAG, `HEAD请求失败: ${err.message}, 假定文件不存在`);
  2428. return false;
  2429. }
  2430. }
  2431. /**
  2432. * 处理重复文件
  2433. * @param account WebDAV账户
  2434. * @param remotePath 远程路径
  2435. * @param action 处理动作:'skip' | 'overwrite' | 'rename'
  2436. */
  2437. private async handleDuplicateFile(
  2438. account: WebDavAccount,
  2439. remotePath: string,
  2440. action: string
  2441. ): Promise<string> {
  2442. if (action === 'skip') {
  2443. throw new Error('文件已存在,跳过上传');
  2444. }
  2445. if (action === 'overwrite') {
  2446. // 删除现有文件
  2447. const host = account.isUseLocalHost && account.localHost ? account.localHost : account.host;
  2448. await this.rcpSocket.RcpSendDelete(
  2449. host,
  2450. account.port,
  2451. account.account,
  2452. account.password,
  2453. remotePath,
  2454. account.enableHttps
  2455. );
  2456. return remotePath;
  2457. }
  2458. if (action === 'rename') {
  2459. // 生成新文件名
  2460. const lastDotIndex = remotePath.lastIndexOf('.');
  2461. const lastSlashIndex = remotePath.lastIndexOf('/');
  2462. let basePath = '';
  2463. let fileName = '';
  2464. let extension = '';
  2465. if (lastSlashIndex >= 0) {
  2466. basePath = remotePath.substring(0, lastSlashIndex + 1);
  2467. fileName = remotePath.substring(lastSlashIndex + 1);
  2468. } else {
  2469. fileName = remotePath;
  2470. }
  2471. if (lastDotIndex > lastSlashIndex) {
  2472. extension = fileName.substring(lastDotIndex);
  2473. fileName = fileName.substring(0, lastDotIndex - lastSlashIndex - 1);
  2474. }
  2475. // 尝试添加序号
  2476. let counter = 1;
  2477. let newPath = '';
  2478. let exists = true;
  2479. while (exists && counter < 100) {
  2480. newPath = `${basePath}${fileName}(${counter})${extension}`;
  2481. exists = await this.checkFileExists(account, newPath);
  2482. counter++;
  2483. }
  2484. if (exists) {
  2485. throw new Error('无法生成唯一文件名');
  2486. }
  2487. return newPath;
  2488. }
  2489. return remotePath;
  2490. }
  2491. // ==================== 安全认证方法 ====================
  2492. // 获取WebDAV认证信息(用于播放器)
  2493. public async getWebDavAuthHeaders(accountId: string): Promise<WebDavAuthInfo | null> {
  2494. const account = await this.getWebDavAccountById(accountId);
  2495. if (!account || !account.account || !account.password) {
  2496. Logger.error(TAG, '无效的WebDAV账户或缺少认证信息');
  2497. return null;
  2498. }
  2499. // 构建基础URL
  2500. const protocol: string = account.enableHttps ? 'https' : 'http';
  2501. const host: string = account.isUseLocalHost && account.localHost ? account.localHost : account.host;
  2502. const port: number = account.port;
  2503. // 构建认证头
  2504. const credentials = buffer
  2505. .from(`${account.account}:${account.password}`)
  2506. .toString("base64");
  2507. const authInfo: WebDavAuthInfo = {
  2508. headers: {
  2509. 'Authorization': `Basic ${credentials}`,
  2510. 'User-Agent': 'TTMusic/1.0'
  2511. },
  2512. url: `${protocol}://${host}:${port}`,
  2513. accountId: accountId
  2514. };
  2515. return authInfo;
  2516. }
  2517. }
  2518. /**
  2519. * 构建HTTP请求头,特别处理WebDAV认证
  2520. * @param currentSong - 当前播放的歌曲信息
  2521. * @param videoUrl - 当前歌曲的URL
  2522. * @param webDavAuthItem - 当前WebDAV认证信息(实例变量)
  2523. * @returns Promise<Map<string, string>> HTTP请求头
  2524. */
  2525. export async function buildHttpHeadersWithWebDav(
  2526. currentSong: VideoItem | undefined,
  2527. videoUrl: string,
  2528. webDavAuthItem: WebDavAuthItem
  2529. ): Promise<Map<string, string>> {
  2530. const headers = new Map<string, string>();
  2531. let isWebDavSong = false;
  2532. if (currentSong) {
  2533. Logger.info(`heanup 当前歌曲信息 - name: ${currentSong.name}, type: ${currentSong.type}, filePath: ${currentSong.filePath}`);
  2534. // 检查是否为WebDAV歌曲
  2535. if (currentSong.type === CommonConstants.TYPE_WEBDAV) {
  2536. isWebDavSong = true;
  2537. // 优先从实例变量获取认证信息
  2538. if (webDavAuthItem) {
  2539. Logger.info(`heanup 从实例变量获取到WebDAV认证信息,账户ID: ${webDavAuthItem.accountId}`);
  2540. } else {
  2541. // 回退到全局上下文
  2542. try {
  2543. const globalContext = GlobalContext.getContext();
  2544. webDavAuthItem = globalContext.getObject('webDavAuthInfo') as WebDavAuthItem;
  2545. if (webDavAuthItem) {
  2546. Logger.info(`heanup 从全局上下文获取到WebDAV认证信息,账户ID: ${webDavAuthItem.accountId}`);
  2547. } else {
  2548. Logger.warn(`heanup 全局上下文中没有WebDAV认证信息`);
  2549. }
  2550. } catch (error) {
  2551. Logger.error(`heanup 获取全局上下文失败:`, error.toString());
  2552. }
  2553. }
  2554. // 如果识别为WebDAV但没有认证信息,记录警告
  2555. if (!webDavAuthItem) {
  2556. Logger.warn(`heanup 识别为WebDAV播放但缺少认证信息,可能需要手动配置WebDAV账户`);
  2557. }
  2558. }
  2559. if (isWebDavSong && webDavAuthItem) {
  2560. Logger.info(`heanup 检测到WebDAV播放,添加安全认证头`);
  2561. Logger.info(`heanup 歌曲URL: ${videoUrl}`);
  2562. try {
  2563. if (webDavAuthItem && webDavAuthItem.accountId) {
  2564. Logger.info(`heanup 找到WebDAV认证信息,账户ID: ${webDavAuthItem.accountId}`);
  2565. // 使用RemoteDriveManager获取认证头
  2566. const webdavManager = RemoteDriveManager.getInstance();
  2567. const authHeaders = await webdavManager.getWebDavAuthHeaders(webDavAuthItem.accountId.toString());
  2568. if (authHeaders) {
  2569. // 添加Basic认证头(使用规范字段名)
  2570. headers.set("Authorization", authHeaders.headers.Authorization);
  2571. } else {
  2572. Logger.error(`heanup 无法获取WebDAV认证头`);
  2573. }
  2574. } else {
  2575. Logger.error(`heanup WebDAV认证信息无效或缺少accountId`);
  2576. }
  2577. } catch (error) {
  2578. Logger.error(`heanup 获取WebDAV认证信息失败:`, error.toString());
  2579. }
  2580. // 添加标准的WebDAV请求头
  2581. headers.set("User-Agent", "TTMusic-WebDAV/1.0");
  2582. headers.set("Accept", "*/*");
  2583. // 请求首段数据,触发服务器返回 206(部分内容)以适配流式播放
  2584. headers.set("Range", "bytes=0-");
  2585. Logger.info(`heanup WebDAV安全认证头设置完成`);
  2586. }
  2587. }
  2588. // 输出所有设置的头部信息用于调试
  2589. console.log(`heanup 设置的HTTP头部信息:`);
  2590. const headerIterator = headers.entries();
  2591. let headerEntry = headerIterator.next();
  2592. while (!headerEntry.done) {
  2593. const key = headerEntry.value[0];
  2594. const value = headerEntry.value[1];
  2595. console.log(`heanup ${key}: ${value}`);
  2596. headerEntry = headerIterator.next();
  2597. }
  2598. return headers;
  2599. }
  2600. /**
  2601. * WebDAV认证信息(LocalMusic专用)
  2602. */
  2603. export interface WebDavAuthItem {
  2604. accountId: number;
  2605. host: string;
  2606. port: number;
  2607. account: string;
  2608. password: string;
  2609. enableHttps: boolean;
  2610. }