| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914 |
- // RemoteDriveManager - WebDAV管理器(简化版)
- import { VideoItem } from '../../viewmodel/VideoItem';
- import { common } from '@kit.AbilityKit';
- import { FileInfo } from '../../viewmodel/FileInfo';
- import { connection } from '@kit.NetworkKit';
- import FileManager, { merge2paths } from './FileManager';
- import { BusinessError } from '@kit.BasicServicesKit';
- import { RemoteDriveManagerStates } from '../enums/RemoteDriveManagerStates';
- import { RcpSocket } from './RcpSocketUtil';
- import { DataBaseUtil } from './DataBaseUtil';
- import { WebDavAccount } from '../../viewmodel/WebDavAccount';
- import { relationalStore } from '@kit.ArkData';
- import { Constants } from '../../Constants';
- import Logger from './Logger';
- import { buffer } from '@kit.ArkTS';
- import { CommonConstants } from '../constants/CommonConstants';
- import { GlobalContext, PreferencesUtil } from '@pura/harmony-utils';
- import { MusicInfo, parseMusicFileName, Utility } from './Utility';
- import { RemoteDriveType } from '../enums/RemoteDriveType';
- import { deleteSmbEntry, listSmbDirectory, SmbDirectoryEntry } from '../network/SmbBridge';
- import { NavidromeApi, NavidromeAlbumDetail, NavidromeArtist, NavidromeArtistDetail, NavidromeSong } from '../network/NavidromeApi';
- import { WebDavUrlUtil } from './WebDavUrlUtil';
- import MediaTable from './MediaTable';
- import { FtpClient, FileInfo as FtpEntryInfo, StringEncoding, AccessOptions } from '@liuzhosoft/ftp4h';
- import { BaiduConstants } from '../constants/BaiduConstants';
- import { appendAccessTokenToDlink, BaiduListEntry, BaiduFileMeta, buildAudioStreamingUrl, deleteFiles as deleteBaiduFiles, ensureAudioStreamReady, fetchFileMetas as fetchBaiduFileMetas, listDirectory as listBaiduDirectory, refreshAccessToken as refreshBaiduAccessToken } from '../network/BaiduPanClient';
- import { ServerLogUtil } from './ServerLogUtil';
- const TAG = 'heanup RemoteDriveManager';
- export interface BreadcrumbItem {
- label: string;
- path: string;
- }
- interface BaiduDlinkCacheEntry {
- url: string;
- token: string;
- expireAt: number;
- }
- // WebDAV认证信息接口
- export interface WebDavAuthInfo {
- headers: Record<string, string>;
- url: string;
- accountId?: string; // 添加账号ID字段,用于标识认证信息对应的账号
- }
- // 流媒体认证信息接口
- export interface StreamAuthInfo {
- url: string;
- headers: Record<string, string>;
- }
- // 百度网盘文件信息接口
- export interface BaiduFileInfo {
- size: number;
- dlink: string;
- streamUrl: string;
- }
- export interface TransferTask {
- song: VideoItem;
- account: WebDavAccount;
- retryCount?: number; // 已重试次数
- customUploadPath?: string; // 自定义上传路径(可选)
- }
- @Observed
- export class RemoteDriveManager {
- public rcpSocket: RcpSocket = RcpSocket.getInstance();
- private dataBaseUtil = DataBaseUtil.getInstance();
- public observers: Array<(event: string) => void> = [];
- public static instance: RemoteDriveManager;
- public context: common.Context | undefined;
- public DownloadDirectoryFilePath: string = '';
- public audioExtensions = Constants.AUDIO_EXTENSIONS;
- public lyricExtensions = Constants.LYRIC_EXTENSIONS;
- public imageExtensions = Constants.IMAGE_EXTENSIONS;
- // 数据表名称
- public preferenceName = Constants.WEBDAV_PREFERENCE_NAME;
- public webDavTable = 'WebDavAccount';
- public receivedSize: number = 0;
- public totalSize: number = 0;
- public webDavAccounts: WebDavAccount[] = [];
- public webDavSongs: VideoItem[] = [];
- public webDavFiles: FileInfo[] = []; // 当前目录的所有文件(包括文件夹)
- private static readonly BAIDU_DLINK_CACHE_TTL: number = 10 * 60 * 1000; // 10分钟
- private baiduDlinkCache: Map<string, BaiduDlinkCacheEntry> = new Map();
- // 路径导航
- public currentPath: string = ''; // 当前浏览的路径
- public pathHistory: string[] = []; // 路径历史记录
- // 错误信息
- public ErrorMessage: string | BusinessError = '';
- // 下载队列
- public downloadQueue: TransferTask[] = [];
- public finishDownloadQueue: TransferTask[] = [];
- public isProcessingQueue: boolean = false;
- public currentDownloadTask: TransferTask | null = null;
- public isPauseDownload: boolean = true;
- // 上传队列
- public uploadQueue: TransferTask[] = [];
- public finishUploadQueue: TransferTask[] = [];
- public isProcessingUploadQueue: boolean = false;
- public currentUploadTask: TransferTask | null = null;
- public isPauseUpload: boolean = true;
- public uploadReceivedSize: number = 0;
- public uploadTotalSize: number = 0;
-
- // 性能优化相关
- // 限制队列大小避免内存溢出:每个任务包含VideoItem对象,200个任务约占用几MB内存
- private readonly MAX_UPLOAD_QUEUE_SIZE: number = 200; // 最大上传队列大小
- // 进度更新节流:避免频繁UI刷新导致性能下降,每500ms最多更新一次
- private lastProgressNotifyTime: number = 0; // 上次进度通知时间
- private readonly PROGRESS_THROTTLE_MS: number = 500; // 进度更新节流时间(毫秒)
- private navidromeApi: NavidromeApi = new NavidromeApi();
- private pathDisplayNames: Map<string, string> = new Map();
- private lastAccountId: number | null = null;
- public currentAccount:WebDavAccount = new WebDavAccount();
- public constructor() {
- this.rcpSocket.subscribeHTTPDataTransfer((event: string) => {
- this.notifyObservers(event);
- });
- }
- public static getInstance(): RemoteDriveManager {
- if (!RemoteDriveManager.instance) {
- RemoteDriveManager.instance = new RemoteDriveManager();
- }
- return RemoteDriveManager.instance;
- }
- public setContext(context: common.Context): void {
- this.context = context;
- this.DownloadDirectoryFilePath = merge2paths(context.filesDir, 'Download');
- }
- // ==================== 观察者模式 ====================
- public subscribe(callback: (event: string) => void): void {
- this.observers.push(callback);
- }
- public unsubscribe(callback: (event: string) => void): void {
- const index = this.observers.indexOf(callback);
- if (index > -1) {
- this.observers.splice(index, 1);
- }
- }
- public notifyObservers(event: string): void {
- Logger.info(TAG, '通知观察者:', event);
- Logger.info(TAG, '观察者数量:', this.observers.length.toString());
- for (let i = 0; i < this.observers.length; i++) {
- const observer = this.observers[i];
- Logger.info(TAG, '调用观察者', i.toString(), ',事件:', event);
- observer(event);
- }
- }
- // ==================== 数据库操作 ====================
- /**
- * 根据webdav_account_id查询WebDAV账号信息
- * @param accountId WebDAV账号ID
- * @returns Promise<WebDavAccount | null> 返回WebDAV账号信息或null
- */
- public async getWebDavAccountById(accountId: string): Promise<WebDavAccount | null> {
- if (!accountId) {
- Logger.warn(TAG, 'webdav_account_id为空,无法查询账号信息');
- return null;
- }
- try {
- const db = await this.dataBaseUtil.getDB();
- const predicates = new relationalStore.RdbPredicates(this.webDavTable);
- predicates.equalTo('id', accountId);
- const resultSet = await db.query(predicates);
- if (resultSet.rowCount > 0) {
- resultSet.goToFirstRow();
- const account = new WebDavAccount();
- account.id = resultSet.getLong(resultSet.getColumnIndex('id'));
- account.name = resultSet.getString(resultSet.getColumnIndex('name'));
- account.host = resultSet.getString(resultSet.getColumnIndex('host'));
- account.localHost = resultSet.getString(resultSet.getColumnIndex('localHost'));
- account.isUseLocalHost = resultSet.getLong(resultSet.getColumnIndex('isUseLocalHost')) === 1;
- account.port = resultSet.getLong(resultSet.getColumnIndex('port'));
- account.filepath = resultSet.getString(resultSet.getColumnIndex('filepath'));
- account.imageFilePath = resultSet.getString(resultSet.getColumnIndex('imageFilePath'));
- account.lyricFilePath = resultSet.getString(resultSet.getColumnIndex('lyricFilePath'));
- account.uploadFilePath = resultSet.getString(resultSet.getColumnIndex('uploadFilePath'));
- account.account = resultSet.getString(resultSet.getColumnIndex('account'));
- account.password = resultSet.getString(resultSet.getColumnIndex('password'));
- account.enableHttps = resultSet.getLong(resultSet.getColumnIndex('enableHttps')) === 1;
- account.coverPath = resultSet.getString(resultSet.getColumnIndex('coverPath'));
- account.webType = resultSet.getLong(resultSet.getColumnIndex('webType'));
- const smbShareIndex = resultSet.getColumnIndex('smbShare');
- const smbDomainIndex = resultSet.getColumnIndex('smbDomain');
- const navBaseIndex = resultSet.getColumnIndex('navidromeBasePath');
- const ftpEncodingIndex = resultSet.getColumnIndex('ftpEncoding');
- const baiduAccessIndex = resultSet.getColumnIndex('baiduAccessToken');
- const baiduRefreshIndex = resultSet.getColumnIndex('baiduRefreshToken');
- const baiduExpireIndex = resultSet.getColumnIndex('baiduTokenExpiresAt');
- if (smbShareIndex >= 0) {
- account.smbShare = resultSet.getString(smbShareIndex) ?? '';
- }
- if (smbDomainIndex >= 0) {
- account.smbDomain = resultSet.getString(smbDomainIndex) ?? '';
- }
- if (navBaseIndex >= 0) {
- const stored = resultSet.getString(navBaseIndex);
- account.navidromeBasePath = stored && stored.length > 0 ? stored : '/rest';
- } else {
- account.navidromeBasePath = '/rest';
- }
- if (ftpEncodingIndex >= 0) {
- const encodingValue = resultSet.getString(ftpEncodingIndex);
- account.ftpEncoding = encodingValue && encodingValue.length > 0 ? encodingValue : 'utf-8';
- } else {
- account.ftpEncoding = 'utf-8';
- }
- if (baiduAccessIndex >= 0) {
- account.baiduAccessToken = resultSet.getString(baiduAccessIndex) ?? '';
- }
- if (baiduRefreshIndex >= 0) {
- account.baiduRefreshToken = resultSet.getString(baiduRefreshIndex) ?? '';
- }
- if (baiduExpireIndex >= 0) {
- account.baiduTokenExpiresAt = resultSet.getLong(baiduExpireIndex);
- }
- account.isActivate = resultSet.getLong(resultSet.getColumnIndex('isActivate')) === 1;
- resultSet.close();
- Logger.info(TAG, `成功查询到WebDAV账号: ${account.name}, ID: ${account.id}`);
- return account;
- } else {
- Logger.warn(TAG, `未找到ID为 ${accountId} 的WebDAV账号`);
- resultSet.close();
- return null;
- }
- } catch (error) {
- const err = error as Error;
- Logger.error(TAG, `查询WebDAV账号失败: ${err.message}`);
- return null;
- }
- }
- /**
- * 根据WebDAV账号构建认证信息
- * @param accountId WebDAV账号ID
- * @returns Promise<WebDavAuthInfo | null> 返回认证信息或null
- */
- public async buildAuthInfoByAccountId(accountId: string): Promise<WebDavAuthInfo | null> {
- const account = await this.getWebDavAccountById(accountId);
- if (!account) {
- Logger.warn(TAG, `无法构建认证信息,账号ID ${accountId} 对应的账号不存在`);
- return null;
- }
- try {
- // 构建基础URL
- const protocol = account.enableHttps ? 'https' : 'http';
- const host = account.isUseLocalHost && account.localHost ? account.localHost : account.host;
- const port = account.port && account.port !== 80 && account.port !== 443 ? `:${account.port}` : '';
- const baseUrl = `${protocol}://${host}${port}`;
- // 构建认证头
- const headers: Record<string, string> = {};
- if (account.account && account.password) {
- const credentials = `${account.account}:${account.password}`;
- // 简化base64编码实现,避免复杂的类型转换
- try {
- const bufferObj = buffer.from(credentials, 'utf-8');
- const base64Credentials = bufferObj.toString('base64');
- headers['Authorization'] = `Basic ${base64Credentials}`;
- } catch (error) {
- const err = error as Error;
- Logger.warn(TAG, `base64编码失败,使用原始凭据: ${err.message}`);
- headers['Authorization'] = `Basic ${credentials}`;
- }
- }
- Logger.info(TAG, `成功构建WebDAV认证信息,账号: ${account.name}, URL: ${baseUrl}`);
- return {
- headers: headers,
- url: baseUrl,
- accountId: accountId
- };
- } catch (error) {
- const err = error as Error;
- Logger.error(TAG, `构建WebDAV认证信息失败: ${err.message}`);
- return null;
- }
- }
- /**
- * 构建HTTP请求头,通过webdav_account_id查询认证信息
- * @param currentSong - 当前播放的歌曲信息
- * @param videoUrl - 当前歌曲的URL
- * @returns Promise<Map<string, string>> HTTP请求头
- */
- public async buildHttpHeadersWithAccountId(
- currentSong: VideoItem | undefined,
- videoUrl: string
- ): Promise<Map<string, string>> {
- const headers = new Map<string, string>();
- if (!currentSong) {
- return headers;
- }
- Logger.info(`heanup 当前歌曲信息 - name: ${currentSong.name}, type: ${currentSong.type}, filePath: ${currentSong.filePath}`);
- // 检查是否为WebDAV歌曲
- if (currentSong.type === CommonConstants.TYPE_WEBDAV) {
- // 优先使用webdav_account_id查询认证信息
- if (currentSong.webdav_account_id) {
- Logger.info(`heanup 使用webdav_account_id查询认证信息,账号ID: ${currentSong.webdav_account_id}`);
- try {
- const authInfo = await this.buildAuthInfoByAccountId(currentSong.webdav_account_id);
- if (authInfo) {
- // 添加WebDAV认证头
- Object.keys(authInfo.headers).forEach(key => {
- headers.set(key, authInfo.headers[key]);
- });
- Logger.info(`heanup 成功通过webdav_account_id获取WebDAV认证信息`);
- } else {
- Logger.warn(`heanup 无法通过webdav_account_id ${currentSong.webdav_account_id} 获取认证信息`);
- }
- } catch (error) {
- const err = error as Error;
- Logger.error(`heanup 查询webdav_account_id认证信息时出错: ${err.message}`);
- }
- } else {
- Logger.warn(`heanup WebDAV歌曲缺少webdav_account_id字段,无法查询认证信息`);
- }
- // 如果没有认证信息,记录警告
- if (headers.size === 0) {
- Logger.warn(`heanup WebDAV歌曲缺少认证信息,可能需要手动配置WebDAV账户`);
- }
- }
- if (currentSong.type === CommonConstants.TYPE_BAIDU) {
- headers.set('User-Agent', BaiduConstants.STREAMING_USER_AGENT);
- headers.set('Host', 'pan.baidu.com');
- headers.set('Accept', '*/*');
- headers.set('Connection', 'Keep-Alive');
- headers.set('Referer', 'https://pan.baidu.com/disk/home');
- headers.set('Accept-Encoding', 'identity');
- headers.set('Pragma', 'no-cache');
- headers.set('Cache-Control', 'no-cache');
- const headerSnapshot: Record<string, string> = {};
- headers.forEach((value, key) => {
- headerSnapshot[key] = value;
- });
- Logger.info(TAG, `构建百度请求头: ${JSON.stringify(headerSnapshot)}`);
- }
- return headers;
- }
- /**
- * 更新现有WebDAV歌曲的webdav_account_id字段
- * 用于修复旧版本数据库中缺少webdav_account_id的记录
- * @param accountId WebDAV账号ID
- */
- public async updateWebDavSongsAccountId(accountId: string): Promise<void> {
- try {
- const db = await this.dataBaseUtil.getDB();
- // 查询所有TYPE_WEBDAV且webdav_account_id为空或null的记录
- const querySql = `
- SELECT id, filePath FROM mediaTable
- WHERE mtype IN (${CommonConstants.TYPE_WEBDAV}, ${CommonConstants.TYPE_SMB}, ${CommonConstants.TYPE_FTP}, ${CommonConstants.TYPE_BAIDU})
- AND (webdav_account_id IS NULL OR webdav_account_id = '')
- `;
- const resultSet = await db.querySql(querySql);
- const updateCount = resultSet.rowCount;
- if (updateCount > 0) {
- Logger.info(TAG, `发现 ${updateCount} 个WebDAV歌曲缺少webdav_account_id,开始更新`);
- // 更新这些记录的webdav_account_id
- const updateSql = `
- UPDATE mediaTable
- SET webdav_account_id = ?
- WHERE mtype IN (${CommonConstants.TYPE_WEBDAV}, ${CommonConstants.TYPE_SMB}, ${CommonConstants.TYPE_FTP}, ${CommonConstants.TYPE_BAIDU})
- AND (webdav_account_id IS NULL OR webdav_account_id = '')
- `;
- await db.executeSql(updateSql, [accountId]);
- Logger.info(TAG, `成功更新 ${updateCount} 个WebDAV歌曲的webdav_account_id为: ${accountId}`);
- } else {
- Logger.info(TAG, `所有WebDAV歌曲都已有webdav_account_id,无需更新`);
- }
- resultSet.close();
- } catch (error) {
- const err = error as Error;
- Logger.error(TAG, `更新WebDAV歌曲webdav_account_id失败: ${err.message}`);
- }
- }
- /**
- * 修复所有WebDAV歌曲的webdav_account_id字段
- * 用于全局修复旧版本数据库中缺少webdav_account_id的记录
- * @param accountId WebDAV账号ID(可选,如果不提供则使用当前激活的账号)
- */
- public async fixAllWebDavSongsAccountId(accountId?: string): Promise<void> {
- try {
- // 如果没有提供accountId,尝试使用当前激活的账号
- if (!accountId) {
- const activeAccount = await this.getActiveWebDavAccount();
- if (activeAccount && activeAccount.id) {
- accountId = activeAccount.id.toString();
- } else {
- Logger.warn(TAG, `无法找到激活的WebDAV账号来修复歌曲记录`);
- return;
- }
- }
- Logger.info(TAG, `开始修复所有WebDAV歌曲的webdav_account_id,使用账号ID: ${accountId}`);
- await this.updateWebDavSongsAccountId(accountId);
- Logger.info(TAG, `WebDAV歌曲webdav_account_id修复完成`);
- } catch (error) {
- const err = error as Error;
- Logger.error(TAG, `修复WebDAV歌曲webdav_account_id失败: ${err.message}`);
- }
- }
- /**
- * 获取当前激活的WebDAV账号
- */
- private async getActiveWebDavAccount(): Promise<WebDavAccount | null> {
- try {
- const db = await this.dataBaseUtil.getDB();
- const predicates = new relationalStore.RdbPredicates(this.webDavTable);
- predicates.equalTo('isActivate', 1);
- predicates.limitAs(1);
- const resultSet = await db.query(predicates);
- if (resultSet.rowCount > 0) {
- resultSet.goToFirstRow();
- const account = new WebDavAccount();
- account.id = resultSet.getLong(resultSet.getColumnIndex('id'));
- account.name = resultSet.getString(resultSet.getColumnIndex('name'));
- account.host = resultSet.getString(resultSet.getColumnIndex('host'));
- account.localHost = resultSet.getString(resultSet.getColumnIndex('localHost'));
- account.isUseLocalHost = resultSet.getLong(resultSet.getColumnIndex('isUseLocalHost')) === 1;
- account.port = resultSet.getLong(resultSet.getColumnIndex('port'));
- account.filepath = resultSet.getString(resultSet.getColumnIndex('filepath'));
- account.imageFilePath = resultSet.getString(resultSet.getColumnIndex('imageFilePath'));
- account.lyricFilePath = resultSet.getString(resultSet.getColumnIndex('lyricFilePath'));
- account.uploadFilePath = resultSet.getString(resultSet.getColumnIndex('uploadFilePath'));
- account.account = resultSet.getString(resultSet.getColumnIndex('account'));
- account.password = resultSet.getString(resultSet.getColumnIndex('password'));
- account.enableHttps = resultSet.getLong(resultSet.getColumnIndex('enableHttps')) === 1;
- account.coverPath = resultSet.getString(resultSet.getColumnIndex('coverPath'));
- account.webType = resultSet.getLong(resultSet.getColumnIndex('webType'));
- const smbShareIndex = resultSet.getColumnIndex('smbShare');
- const smbDomainIndex = resultSet.getColumnIndex('smbDomain');
- const navBaseIndex = resultSet.getColumnIndex('navidromeBasePath');
- const baiduAccessIndex = resultSet.getColumnIndex('baiduAccessToken');
- const baiduRefreshIndex = resultSet.getColumnIndex('baiduRefreshToken');
- const baiduExpireIndex = resultSet.getColumnIndex('baiduTokenExpiresAt');
- if (smbShareIndex >= 0) {
- account.smbShare = resultSet.getString(smbShareIndex) ?? '';
- }
- if (smbDomainIndex >= 0) {
- account.smbDomain = resultSet.getString(smbDomainIndex) ?? '';
- }
- const ftpEncodingIndex = resultSet.getColumnIndex('ftpEncoding');
- if (navBaseIndex >= 0) {
- const stored = resultSet.getString(navBaseIndex);
- account.navidromeBasePath = stored && stored.length > 0 ? stored : '/rest';
- } else {
- account.navidromeBasePath = '/rest';
- }
- if (ftpEncodingIndex >= 0) {
- const encodingValue = resultSet.getString(ftpEncodingIndex);
- account.ftpEncoding = encodingValue && encodingValue.length > 0 ? encodingValue : 'utf-8';
- } else {
- account.ftpEncoding = 'utf-8';
- }
- if (baiduAccessIndex >= 0) {
- account.baiduAccessToken = resultSet.getString(baiduAccessIndex) ?? '';
- }
- if (baiduRefreshIndex >= 0) {
- account.baiduRefreshToken = resultSet.getString(baiduRefreshIndex) ?? '';
- }
- if (baiduExpireIndex >= 0) {
- account.baiduTokenExpiresAt = resultSet.getLong(baiduExpireIndex);
- }
- account.isActivate = resultSet.getLong(resultSet.getColumnIndex('isActivate')) === 1;
- resultSet.close();
- return account;
- } else {
- resultSet.close();
- return null;
- }
- } catch (error) {
- const err = error as Error;
- Logger.error(TAG, `获取激活的WebDAV账号失败: ${err.message}`);
- return null;
- }
- }
- // 创建WebDAV账户表
- public createWebDavTableInDB(): Promise<void> {
- const createTableSql = `CREATE TABLE IF NOT EXISTS ${this.webDavTable} (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- name TEXT,
- isActivate INTEGER DEFAULT 1,
- host TEXT,
- localHost TEXT,
- isUseLocalHost INTEGER DEFAULT 0,
- port INTEGER,
- filepath TEXT,
- imageFilePath TEXT,
- lyricFilePath TEXT,
- uploadFilePath TEXT,
- account TEXT,
- password TEXT,
- enableHttps INTEGER DEFAULT 0,
- coverPath TEXT,
- webType INTEGER DEFAULT 0,
- smbShare TEXT,
- smbDomain TEXT,
- navidromeBasePath TEXT,
- ftpEncoding TEXT
- )`;
- return this.dataBaseUtil.executeSql(createTableSql)
- .then(() => {
- Logger.info(TAG, 'WebDAV账户表创建成功');
- // 检查并添加新字段(用于数据库升级)
- return this.upgradeWebDavTable();
- })
- .catch((err: Error) => {
- Logger.error(TAG, '创建WebDAV账户表失败:', err.message);
- throw err;
- });
- }
- // 升级WebDAV表结构
- private async upgradeWebDavTable(): Promise<void> {
- try {
- // 直接尝试添加coverPath字段,如果字段已存在会失败但不影响应用运行
- Logger.info(TAG, '检查数据库表结构,尝试添加coverPath字段...');
- const addColumnSql = `ALTER TABLE ${this.webDavTable} ADD COLUMN coverPath TEXT`;
- await this.dataBaseUtil.executeSql(addColumnSql);
- Logger.info(TAG, 'coverPath字段添加成功,数据库升级完成');
- } catch (error) {
- // 如果添加字段失败(可能字段已存在),记录但不阻止应用启动
- }
- try {
- // 添加webType字段,用于标识WebDAV账户类型
- Logger.info(TAG, '检查数据库表结构,尝试添加webType字段...');
- const addWebTypeColumnSql = `ALTER TABLE ${this.webDavTable} ADD COLUMN webType INTEGER DEFAULT 0`;
- await this.dataBaseUtil.executeSql(addWebTypeColumnSql);
- Logger.info(TAG, 'webType字段添加成功,数据库升级完成');
- } catch (error) {
- // 如果添加字段失败(可能字段已存在),记录但不阻止应用启动
- }
- try {
- Logger.info(TAG, '尝试添加smbShare字段...');
- const addSmbShareSql = `ALTER TABLE ${this.webDavTable} ADD COLUMN smbShare TEXT`;
- await this.dataBaseUtil.executeSql(addSmbShareSql);
- Logger.info(TAG, 'smbShare字段添加成功');
- } catch (error) {
- }
- try {
- Logger.info(TAG, '尝试添加smbDomain字段...');
- const addSmbDomainSql = `ALTER TABLE ${this.webDavTable} ADD COLUMN smbDomain TEXT`;
- await this.dataBaseUtil.executeSql(addSmbDomainSql);
- Logger.info(TAG, 'smbDomain字段添加成功');
- } catch (error) {
- }
- try {
- Logger.info(TAG, '尝试添加navidromeBasePath字段...');
- const addNavBaseSql = `ALTER TABLE ${this.webDavTable} ADD COLUMN navidromeBasePath TEXT`;
- await this.dataBaseUtil.executeSql(addNavBaseSql);
- Logger.info(TAG, 'navidromeBasePath字段添加成功');
- } catch (error) {
- }
- try {
- Logger.info(TAG, '尝试添加ftpEncoding字段...');
- const addFtpEncodingSql = `ALTER TABLE ${this.webDavTable} ADD COLUMN ftpEncoding TEXT`;
- await this.dataBaseUtil.executeSql(addFtpEncodingSql);
- Logger.info(TAG, 'ftpEncoding字段添加成功');
- } catch (error) {
- }
- try {
- Logger.info(TAG, '尝试添加百度授权字段...');
- await this.dataBaseUtil.executeSql(`ALTER TABLE ${this.webDavTable} ADD COLUMN baiduAccessToken TEXT`);
- await this.dataBaseUtil.executeSql(`ALTER TABLE ${this.webDavTable} ADD COLUMN baiduRefreshToken TEXT`);
- await this.dataBaseUtil.executeSql(`ALTER TABLE ${this.webDavTable} ADD COLUMN baiduTokenExpiresAt INTEGER`);
- Logger.info(TAG, '百度授权字段添加成功');
- } catch (error) {
- }
- }
- // 从数据库查询所有账户
- public async queryWebDavAccountsFromDB(): Promise<void> {
- try {
- // 确保表结构是最新的
- await this.upgradeWebDavTable();
- const predicates = new relationalStore.RdbPredicates(this.webDavTable);
- // 先查询基础字段(确保这些字段在旧版本中存在)
- const baseColumns = ['id', 'name', 'isActivate', 'host', 'localHost', 'isUseLocalHost',
- 'port', 'filepath', 'imageFilePath', 'lyricFilePath', 'uploadFilePath',
- 'account', 'password', 'enableHttps', 'coverPath', 'webType', 'smbShare', 'smbDomain', 'navidromeBasePath', 'ftpEncoding',
- 'baiduAccessToken', 'baiduRefreshToken', 'baiduTokenExpiresAt'];
- const resultSet = await this.dataBaseUtil.queryData(this.webDavTable, baseColumns, predicates);
- this.webDavAccounts = [];
- while (resultSet.goToNextRow()) {
- const account = new WebDavAccount();
- account.id = resultSet.getLong(resultSet.getColumnIndex('id'));
- account.name = resultSet.getString(resultSet.getColumnIndex('name'));
- account.isActivate = resultSet.getLong(resultSet.getColumnIndex('isActivate')) === 1;
- account.host = resultSet.getString(resultSet.getColumnIndex('host'));
- account.localHost = resultSet.getString(resultSet.getColumnIndex('localHost'));
- account.isUseLocalHost = resultSet.getLong(resultSet.getColumnIndex('isUseLocalHost')) === 1;
- account.port = resultSet.getLong(resultSet.getColumnIndex('port'));
- account.filepath = resultSet.getString(resultSet.getColumnIndex('filepath'));
- account.imageFilePath = resultSet.getString(resultSet.getColumnIndex('imageFilePath'));
- account.lyricFilePath = resultSet.getString(resultSet.getColumnIndex('lyricFilePath'));
- account.uploadFilePath = resultSet.getString(resultSet.getColumnIndex('uploadFilePath'));
- account.account = resultSet.getString(resultSet.getColumnIndex('account'));
- account.password = resultSet.getString(resultSet.getColumnIndex('password'));
- account.enableHttps = resultSet.getLong(resultSet.getColumnIndex('enableHttps')) === 1;
- const coverPathIndex = resultSet.getColumnIndex('coverPath');
- if (coverPathIndex >= 0) {
- account.coverPath = resultSet.getString(coverPathIndex) ?? undefined;
- }
- const webTypeIndex = resultSet.getColumnIndex('webType');
- account.webType = webTypeIndex >= 0 ? resultSet.getLong(webTypeIndex) : 0;
- const smbShareIndex = resultSet.getColumnIndex('smbShare');
- if (smbShareIndex >= 0) {
- account.smbShare = resultSet.getString(smbShareIndex) ?? '';
- }
- const smbDomainIndex = resultSet.getColumnIndex('smbDomain');
- if (smbDomainIndex >= 0) {
- account.smbDomain = resultSet.getString(smbDomainIndex) ?? '';
- }
- const navBaseIndex = resultSet.getColumnIndex('navidromeBasePath');
- if (navBaseIndex >= 0) {
- const stored = resultSet.getString(navBaseIndex);
- account.navidromeBasePath = stored && stored.length > 0 ? stored : '/rest';
- } else {
- account.navidromeBasePath = '/rest';
- }
- const ftpEncodingIndex = resultSet.getColumnIndex('ftpEncoding');
- if (ftpEncodingIndex >= 0) {
- const encodingValue = resultSet.getString(ftpEncodingIndex);
- account.ftpEncoding = encodingValue && encodingValue.length > 0 ? encodingValue : 'utf-8';
- } else {
- account.ftpEncoding = 'utf-8';
- }
- const baiduAccessIndex = resultSet.getColumnIndex('baiduAccessToken');
- if (baiduAccessIndex >= 0) {
- account.baiduAccessToken = resultSet.getString(baiduAccessIndex) ?? '';
- }
- const baiduRefreshIndex = resultSet.getColumnIndex('baiduRefreshToken');
- if (baiduRefreshIndex >= 0) {
- account.baiduRefreshToken = resultSet.getString(baiduRefreshIndex) ?? '';
- }
- const baiduExpireIndex = resultSet.getColumnIndex('baiduTokenExpiresAt');
- if (baiduExpireIndex >= 0) {
- account.baiduTokenExpiresAt = resultSet.getLong(baiduExpireIndex);
- }
- this.webDavAccounts.push(account);
- }
- resultSet.close();
- Logger.info(TAG, '从数据库加载了', this.webDavAccounts.length.toString(), '个WebDAV账户');
- this.notifyObservers(RemoteDriveManagerStates.QueryAccountsSucceed);
- } catch (err) {
- const error = err as Error;
- Logger.error(TAG, '查询WebDAV账户失败:', error.message);
- this.notifyObservers(RemoteDriveManagerStates.QueryAccountsFailed);
- throw error;
- }
- }
- // 插入新账户
- public async insertAccount(
- name: string,
- host: string,
- localHost: string,
- isUseLocalHost: boolean,
- port: number,
- filepath: string,
- lyricFilePath: string,
- uploadFilePath: string,
- imageFilePath: string,
- account: string,
- password: string,
- enableHttps: boolean,
- coverPath?: string,
- webType: number = 0,
- smbShare: string = '',
- smbDomain: string = '',
- navidromeBasePath: string = '/rest',
- ftpEncoding: string = 'utf-8',
- baiduAccessToken: string = '',
- baiduRefreshToken: string = '',
- baiduTokenExpiresAt: number = 0
- ): Promise<void> {
- try {
- const values: relationalStore.ValuesBucket = {
- 'name': name,
- 'isActivate': 1,
- 'host': host,
- 'localHost': localHost,
- 'isUseLocalHost': isUseLocalHost ? 1 : 0,
- 'port': port,
- 'filepath': filepath,
- 'imageFilePath': imageFilePath,
- 'lyricFilePath': lyricFilePath,
- 'uploadFilePath': uploadFilePath,
- 'account': account,
- 'password': password,
- 'enableHttps': enableHttps ? 1 : 0,
- 'coverPath': coverPath || null,
- 'webType': webType,
- 'smbShare': smbShare,
- 'smbDomain': smbDomain,
- 'navidromeBasePath': navidromeBasePath,
- 'ftpEncoding': ftpEncoding,
- 'baiduAccessToken': baiduAccessToken,
- 'baiduRefreshToken': baiduRefreshToken,
- 'baiduTokenExpiresAt': baiduTokenExpiresAt
- };
- await this.dataBaseUtil.insertData(this.webDavTable, values);
- Logger.info(TAG, '插入WebDAV账户成功:', name);
- await this.queryWebDavAccountsFromDB();
- this.notifyObservers(RemoteDriveManagerStates.InsertAccountSucceed);
- } catch (err) {
- const error = err as Error;
- Logger.error(TAG, '插入WebDAV账户失败:', error.message);
- this.notifyObservers(RemoteDriveManagerStates.InsertAccountFailed);
- throw error;
- }
- }
- // 编辑账户
- public async editAccount(account: WebDavAccount): Promise<void> {
- try {
- const values: relationalStore.ValuesBucket = {
- 'name': account.name,
- 'isActivate': account.isActivate ? 1 : 0,
- 'host': account.host,
- 'localHost': account.localHost,
- 'isUseLocalHost': account.isUseLocalHost ? 1 : 0,
- 'port': account.port,
- 'filepath': account.filepath,
- 'imageFilePath': account.imageFilePath,
- 'lyricFilePath': account.lyricFilePath,
- 'uploadFilePath': account.uploadFilePath,
- 'account': account.account,
- 'password': account.password,
- 'enableHttps': account.enableHttps ? 1 : 0,
- 'coverPath': account.coverPath || null,
- 'webType': account.webType,
- 'smbShare': account.smbShare,
- 'smbDomain': account.smbDomain,
- 'navidromeBasePath': account.navidromeBasePath,
- 'ftpEncoding': account.ftpEncoding,
- 'baiduAccessToken': account.baiduAccessToken,
- 'baiduRefreshToken': account.baiduRefreshToken,
- 'baiduTokenExpiresAt': account.baiduTokenExpiresAt
- };
- const predicates = new relationalStore.RdbPredicates(this.webDavTable);
- predicates.equalTo('id', account.id);
- await this.dataBaseUtil.updateData(this.webDavTable, values, predicates);
- Logger.info(TAG, '更新WebDAV账户成功:', account.name);
- await this.queryWebDavAccountsFromDB();
- this.notifyObservers(RemoteDriveManagerStates.EditAccountSucceed);
- } catch (err) {
- const error = err as Error;
- Logger.error(TAG, '更新WebDAV账户失败:', error.message);
- this.notifyObservers(RemoteDriveManagerStates.EditAccountFailed);
- throw error;
- }
- }
- // 删除账户
- public async removeAccount(account: WebDavAccount): Promise<void> {
- try {
- const predicates = new relationalStore.RdbPredicates(this.webDavTable);
- predicates.equalTo('id', account.id);
- await this.dataBaseUtil.deleteData(predicates);
- Logger.info(TAG, '删除WebDAV账户成功:', account.name);
- await this.queryWebDavAccountsFromDB();
- this.notifyObservers(RemoteDriveManagerStates.RemoveAccountSucceed);
- } catch (err) {
- const error = err as Error;
- Logger.error(TAG, '删除WebDAV账户失败:', error.message);
- this.notifyObservers(RemoteDriveManagerStates.RemoveAccountFailed);
- throw error;
- }
- }
- // 获取所有账户
- public getAllWebDavAccounts(): WebDavAccount[] {
- return this.webDavAccounts;
- }
- // 获取激活的账户
- public getActivatedWebDavAccount(): WebDavAccount | null {
- if(this.currentAccount)
- return this.currentAccount;
- for (let i = 0; i < this.webDavAccounts.length; i++) {
- const account = this.webDavAccounts[i];
- if (account.isActivate) {
- return account;
- }
- }
- return null;
- }
- // ==================== 文件操作 ====================
- // 从WebDAV加载文件列表
- public async loadFilesInfoFromWebdav(customPath?: string): Promise<void> {
- const account = await this.getActiveWebDavAccount();
- if (!account) {
- Logger.error(TAG, '没有激活的WebDAV账户');
- this.notifyObservers(RemoteDriveManagerStates.LoadFilesInfoFailed);
- return;
- }
- await this.loadFilesInfoFromAccount(account, customPath);
- }
- public async loadFilesInfoFromAccount(account: WebDavAccount,customPath?: string): Promise<void> {
- this.currentAccount = account;
- if (this.lastAccountId !== account.id) {
- this.pathHistory = [];
- this.pathDisplayNames.clear();
- this.registerPathLabel('/', '根目录');
- }
- this.lastAccountId = account.id ?? null;
- // 更新现有WebDAV歌曲的webdav_account_id字段
- if (account && account.id) {
- await this.updateWebDavSongsAccountId(account.id.toString());
- }
- try {
- this.notifyObservers(RemoteDriveManagerStates.LoadFilesInfoStart);
- // 使用自定义路径或账户默认路径
- const normalizedFullPath = this.normalizeFullPath(customPath !== undefined ? customPath : account.filepath);
- this.currentPath = normalizedFullPath;
- if (account.webType === RemoteDriveType.Smb) {
- await this.loadSmbFiles(account, normalizedFullPath);
- } else if (account.webType === RemoteDriveType.Navidrome) {
- await this.loadNavidromeFiles(account, normalizedFullPath);
- } else if (account.webType === RemoteDriveType.Ftp) {
- await this.loadFtpFiles(account, normalizedFullPath);
- } else if (account.webType === RemoteDriveType.Baidu) {
- await this.loadBaiduFiles(account, normalizedFullPath);
- } else {
- await this.loadWebDavFiles(account, normalizedFullPath);
- }
- this.notifyObservers(RemoteDriveManagerStates.LoadFilesInfoSucceed);
- } catch (error) {
- this.ErrorMessage = error as BusinessError;
- this.notifyObservers(RemoteDriveManagerStates.LoadFilesInfoFailed);
- }
- }
- private normalizeFullPath(path?: string): string {
- if (!path || path.trim().length === 0) {
- return '/';
- }
- let normalized = path.trim().replace(/\\/g, '/');
- if (!normalized.startsWith('/')) {
- normalized = `/${normalized}`;
- }
- normalized = normalized.replace(/\/+/g, '/');
- if (normalized.length > 1 && normalized.endsWith('/')) {
- normalized = normalized.slice(0, -1);
- }
- return normalized || '/';
- }
- private getSongKey(song: VideoItem): string {
- if (!song) {
- return '';
- }
- if (song.filePath && song.filePath.length > 0) {
- return song.filePath;
- }
- if (song.name && song.name.length > 0) {
- return song.name;
- }
- return '';
- }
- private sanitizeRelativeUploadPath(path?: string): string {
- if (!path || path.length === 0) {
- return '';
- }
- let sanitized = path.replace(/\\/g, '/');
- sanitized = sanitized.replace(/^\/+/, '');
- sanitized = sanitized.replace(/\/+/g, '/');
- return sanitized;
- }
- private combineRemoteUploadPath(basePath: string, relativePath: string): string {
- const normalizedBase = this.normalizeFullPath(basePath);
- const cleanedRelative = this.sanitizeRelativeUploadPath(relativePath);
- if (!cleanedRelative || cleanedRelative.length === 0) {
- return normalizedBase;
- }
- if (normalizedBase === '/') {
- return this.normalizeFullPath(`/${cleanedRelative}`);
- }
- return this.normalizeFullPath(`${normalizedBase}/${cleanedRelative}`);
- }
- private getDirectoryFromRemotePath(remotePath: string): string {
- if (!remotePath || remotePath === '/') {
- return '/';
- }
- const normalized = this.normalizeFullPath(remotePath);
- const lastSlash = normalized.lastIndexOf('/');
- if (lastSlash <= 0) {
- return '/';
- }
- return normalized.substring(0, lastSlash);
- }
- private async ensureRemoteDirectories(account: WebDavAccount, directoryPath: string): Promise<void> {
- if (!directoryPath || directoryPath === '/') {
- return;
- }
- const normalizedDir = this.normalizeFullPath(directoryPath);
- if (normalizedDir === '/') {
- return;
- }
- const segments = normalizedDir.split('/').filter(segment => segment.length > 0);
- if (segments.length === 0) {
- return;
- }
- let currentPath = '';
- for (let i = 0; i < segments.length; i++) {
- currentPath = `${currentPath}/${segments[i]}`;
- const normalizedCurrent = this.normalizeFullPath(currentPath);
- await this.ensureSingleRemoteDirectory(account, normalizedCurrent);
- }
- }
- private async ensureSingleRemoteDirectory(account: WebDavAccount, directoryPath: string): Promise<void> {
- try {
- await this.rcpSocket.getFileList(
- account.host,
- account.localHost,
- account.isUseLocalHost,
- account.port,
- directoryPath,
- account.account,
- account.password,
- account.enableHttps
- );
- } catch (_error) {
- const host = account.isUseLocalHost && account.localHost ? account.localHost : account.host;
- try {
- await this.rcpSocket.createDirectory(
- host,
- account.port,
- account.account,
- account.password,
- directoryPath,
- account.enableHttps
- );
- Logger.info(TAG, `创建远程目录: ${directoryPath}`);
- } catch (createErr) {
- const err = createErr as Error;
- Logger.error(TAG, `创建远程目录失败 (${directoryPath}): ${err.message}`);
- throw err;
- }
- }
- }
- // 将 WebDAV 响应中的 href 统一转换为以 / 开头的相对路径
- private normalizeRemoteHref(rawHref: string): string {
- if (!rawHref || rawHref.trim().length === 0) {
- return '/';
- }
- const trimmed = rawHref.trim();
- const relativeFromHttp = WebDavUrlUtil.extractRelativePath(trimmed);
- if (relativeFromHttp) {
- return this.normalizeFullPath(relativeFromHttp);
- }
- if (trimmed.startsWith('//')) {
- const hostEnd = trimmed.indexOf('/', 2);
- if (hostEnd > 1) {
- return this.normalizeFullPath(trimmed.substring(hostEnd));
- }
- return '/';
- }
- return this.normalizeFullPath(trimmed);
- }
- private toRelativePath(fullPath: string): string {
- if (!fullPath || fullPath === '/') {
- return '';
- }
- return fullPath.replace(/^\/+/, '');
- }
- private async loadWebDavFiles(account: WebDavAccount, fullPath: string): Promise<void> {
- const files = await this.rcpSocket.getFileList(
- account.host,
- account.localHost,
- account.isUseLocalHost,
- account.port,
- fullPath,
- account.account,
- account.password,
- account.enableHttps
- );
- this.webDavFiles = files;
- this.webDavSongs = [];
- for (let i = 0; i < files.length; i++) {
- const file = files[i];
- if (!file.isDirectory && this.isAudioFile(file.fileName)) {
- this.webDavSongs.push(this.fileInfoToVideoItem(file, account));
- }
- }
- await this.enrichSongsWithDatabase(this.webDavSongs);
- Logger.info(TAG, `从WebDAV获取到 ${files.length} 个文件/文件夹`);
- }
- private async loadSmbFiles(account: WebDavAccount, fullPath: string): Promise<void> {
- if (!account.smbShare) {
- throw new Error('SMB账户缺少共享名称');
- }
- const relativePath = this.toRelativePath(fullPath);
- const host = account.isUseLocalHost && account.localHost ? account.localHost : account.host;
- const entries = await listSmbDirectory({
- host,
- share: account.smbShare,
- username: account.account,
- password: account.password,
- domain: account.smbDomain,
- path: relativePath
- });
- this.webDavFiles = [];
- this.webDavSongs = [];
- for (let i = 0; i < entries.length; i++) {
- const entry = entries[i];
- const fileInfo = this.smbEntryToFileInfo(entry, relativePath);
- this.webDavFiles.push(fileInfo);
- if (!entry.isDirectory && this.isAudioFile(entry.name)) {
- this.webDavSongs.push(this.fileInfoToVideoItem(fileInfo, account));
- }
- }
- await this.enrichSongsWithDatabase(this.webDavSongs);
- Logger.info(TAG, `从SMB获取到 ${entries.length} 个文件/文件夹`);
- }
- private resolveFtpHost(account: WebDavAccount): string {
- const host = account.isUseLocalHost && account.localHost ? account.localHost : account.host;
- return host?.trim() ?? '';
- }
- private getFtpEncoding(account: WebDavAccount): StringEncoding {
- if (account.ftpEncoding && account.ftpEncoding.length > 0) {
- return account.ftpEncoding as StringEncoding;
- }
- return 'utf-8';
- }
- private buildFtpAccessOptions(account: WebDavAccount): AccessOptions {
- const host = this.resolveFtpHost(account);
- if (!host) {
- throw new Error('FTP账户缺少服务器地址');
- }
- return {
- host,
- port: account.port && account.port > 0 ? account.port : 21,
- user: account.account && account.account.length > 0 ? account.account : undefined,
- password: account.password && account.password.length > 0 ? account.password : undefined,
- encoding: this.getFtpEncoding(account)
- };
- }
- private async loadFtpFiles(account: WebDavAccount, fullPath: string): Promise<void> {
- const client = new FtpClient();
- const options = this.buildFtpAccessOptions(account);
- await client.access(options);
- try {
- const listPath = this.normalizeFullPath(fullPath);
- const entries = await client.list(listPath === '/' ? '/' : listPath);
- this.webDavFiles = [];
- this.webDavSongs = [];
- for (let i = 0; i < entries.length; i++) {
- const entry = entries[i];
- const info = this.ftpEntryToFileInfo(entry, listPath);
- this.webDavFiles.push(info);
- if (info.isDirectory) {
- this.registerPathLabel(info.href, info.fileName);
- } else if (this.isAudioFile(info.fileName)) {
- this.webDavSongs.push(this.buildFtpVideoItem(info, account));
- }
- }
- await this.enrichSongsWithDatabase(this.webDavSongs);
- Logger.info(TAG, `从FTP获取到 ${entries.length} 个文件/文件夹`);
- } finally {
- await client.close();
- }
- }
- private async loadBaiduFiles(account: WebDavAccount, fullPath: string): Promise<void> {
- const accessToken = await this.ensureBaiduAccessToken(account);
- const directory = fullPath && fullPath.length > 0 ? fullPath : '/';
- const entries = await listBaiduDirectory(accessToken, directory);
- this.webDavFiles = [];
- this.webDavSongs = [];
- for (let i = 0; i < entries.length; i++) {
- const entry = entries[i];
- const info = this.baiduEntryToFileInfo(entry);
- this.webDavFiles.push(info);
- if (info.isDirectory) {
- this.registerPathLabel(info.href, info.fileName);
- } else if (this.isAudioFile(info.fileName)) {
- this.webDavSongs.push(this.buildBaiduVideoItem(entry, account));
- }
- }
- await this.enrichSongsWithDatabase(this.webDavSongs);
- Logger.info(TAG, `从百度网盘获取到 ${entries.length} 个文件/文件夹`);
- this.scheduleBaiduPrefetch(account, accessToken, entries);
- Logger.info(TAG, `百度预取任务已调度, account=${account.id}, 文件数=${entries.length}`);
- }
- public async deleteRemoteSongs(account: WebDavAccount, songs: VideoItem[]): Promise<void> {
- if (!account) {
- throw new Error('请先选择账户');
- }
- if (!songs || songs.length === 0) {
- return;
- }
- const deletable = songs.filter(item => item && item.filePath && item.filePath.length > 0);
- if (deletable.length === 0) {
- return;
- }
- if (account.webType === RemoteDriveType.WebDav) {
- await this.deleteWebDavSongs(account, deletable);
- } else if (account.webType === RemoteDriveType.Smb) {
- await this.deleteSmbSongs(account, deletable);
- } else if (account.webType === RemoteDriveType.Ftp) {
- await this.deleteFtpSongs(account, deletable);
- } else if (account.webType === RemoteDriveType.Baidu) {
- await this.deleteBaiduSongs(account, deletable);
- } else {
- throw new Error('当前账户类型暂不支持删除');
- }
- }
- private resolveWebDavDeletePath(song: VideoItem): string {
- if (song.remote_rel_path && song.remote_rel_path.length > 0) {
- return this.normalizeRemoteHref(song.remote_rel_path);
- }
- if (song.filePath) {
- const relative = WebDavUrlUtil.extractRelativePath(song.filePath);
- if (relative) {
- return this.normalizeRemoteHref(relative);
- }
- }
- throw new Error(`无法确定 WebDAV 文件路径: ${song.name}`);
- }
- private async deleteWebDavSongs(account: WebDavAccount, songs: VideoItem[]): Promise<void> {
- const host = account.isUseLocalHost && account.localHost ? account.localHost : account.host;
- if (!host || host.length === 0) {
- throw new Error('WebDAV账户缺少服务器地址');
- }
- for (let i = 0; i < songs.length; i++) {
- const song = songs[i];
- const relativePath = this.resolveWebDavDeletePath(song);
- try {
- await this.rcpSocket.RcpSendDelete(
- host,
- account.port,
- account.account,
- account.password,
- relativePath,
- account.enableHttps
- );
- } catch (error) {
- const err = error as Error;
- throw new Error(`删除 ${song.name} 失败: ${err.message}`);
- }
- }
- }
- private resolveSmbSongPath(song: VideoItem, account: WebDavAccount): string {
- if (song.remote_rel_path && song.remote_rel_path.length > 0) {
- return this.normalizeSmbRelativePath(song.remote_rel_path, account.smbShare);
- }
- if (song.filePath) {
- const withoutScheme = song.filePath.replace(/^smb:\/\//i, '').replace(/^[^/]+/i, '');
- return this.normalizeSmbRelativePath(withoutScheme, account.smbShare);
- }
- throw new Error(`无法确定SMB路径: ${song.name}`);
- }
- private async deleteSmbSongs(account: WebDavAccount, songs: VideoItem[]): Promise<void> {
- if (!account.smbShare || account.smbShare.length === 0) {
- throw new Error('SMB账户缺少共享名称');
- }
- const host = account.isUseLocalHost && account.localHost ? account.localHost : account.host;
- if (!host || host.length === 0) {
- throw new Error('SMB账户缺少服务器地址');
- }
- for (let i = 0; i < songs.length; i++) {
- const song = songs[i];
- const relativePath = this.resolveSmbSongPath(song, account);
- if (!relativePath || relativePath.length === 0 || relativePath === '/') {
- throw new Error(`无法确定SMB文件路径: ${song.name}`);
- }
- try {
- await deleteSmbEntry({
- host,
- share: account.smbShare,
- username: account.account,
- password: account.password,
- domain: account.smbDomain,
- path: relativePath,
- isDirectory: false
- });
- } catch (error) {
- const err = error as Error;
- throw new Error(`删除 ${song.name} 失败: ${err.message}`);
- }
- }
- }
- private resolveFtpSongPath(song: VideoItem): string {
- const target = song.remote_rel_path && song.remote_rel_path.length > 0 ? song.remote_rel_path : song.filePath;
- if (!target || target.length === 0) {
- throw new Error(`无法确定FTP路径: ${song.name}`);
- }
- return this.normalizeFullPath(target);
- }
- private async deleteFtpSongs(account: WebDavAccount, songs: VideoItem[]): Promise<void> {
- const options = this.buildFtpAccessOptions(account);
- const client = new FtpClient();
- try {
- await client.access(options);
- for (let i = 0; i < songs.length; i++) {
- const song = songs[i];
- const remotePath = this.resolveFtpSongPath(song);
- const success = await client.remove(remotePath);
- if (!success) {
- throw new Error(`删除 ${song.name} 失败`);
- }
- }
- } finally {
- await client.close();
- }
- }
- private async deleteBaiduSongs(account: WebDavAccount, songs: VideoItem[]): Promise<void> {
- const accessToken = await this.ensureBaiduAccessToken(account);
- const paths: string[] = [];
- for (let i = 0; i < songs.length; i++) {
- const path = songs[i].remote_rel_path;
- if (!path || path.length === 0) {
- throw new Error(`无法确定百度网盘路径: ${songs[i].name}`);
- }
- paths.push(path);
- }
- const batchSize = 20;
- for (let i = 0; i < paths.length; i += batchSize) {
- const batch = paths.slice(i, i + batchSize);
- try {
- await deleteBaiduFiles(accessToken, batch);
- } catch (error) {
- const err = error as Error;
- throw new Error(`删除文件失败: ${err.message}`);
- }
- }
- }
- private scheduleBaiduPrefetch(account: WebDavAccount, accessToken: string, entries: BaiduListEntry[]): void {
- const fileEntries = entries.filter(entry => entry.isdir === 0 && this.isAudioFile(entry.server_filename));
- if (fileEntries.length === 0) {
- return;
- }
- const fsIds = fileEntries.map(entry => entry.fs_id.toString());
- const chunkSize = 50;
- const prefetch = async () => {
- Logger.info(TAG, `开始预取百度dlink,文件数: ${fsIds.length}`);
- Logger.info(TAG, `Baidu dlink prefetch start: account=${account.id} files=${fsIds.length}`);
- for (let i = 0; i < fsIds.length; i += chunkSize) {
- const chunk = fsIds.slice(i, i + chunkSize);
- try {
- const metas = await fetchBaiduFileMetas(accessToken, chunk);
- metas.forEach((meta: BaiduFileMeta) => {
- if (!meta.dlink) {
- return;
- }
- const rawLink = meta.dlink.startsWith('https://') ? meta.dlink : meta.dlink.replace('http://', 'https://');
- const finalUrl = appendAccessTokenToDlink(rawLink, accessToken);
- this.cacheBaiduDlink(account, meta.fs_id.toString(), accessToken, finalUrl);
- });
- Logger.info(TAG, `Baidu dlink prefetch chunk success account=${account.id} size=${chunk.length}`);
- } catch (error) {
- const err = error as Error;
- Logger.warn(TAG, `百度dlink预取失败: ${err.message}`);
- break;
- }
- }
- Logger.info(TAG, `Baidu dlink prefetch finished account=${account.id}`);
- };
- void prefetch();
- }
- private async loadNavidromeFiles(account: WebDavAccount, fullPath: string): Promise<void> {
- const normalized = this.normalizeFullPath(fullPath);
- this.registerPathLabel('/', '根目录');
- const segments = normalized.split('/').filter(part => part.length > 0);
- void ServerLogUtil.info(TAG, `浏览 Navidrome 路径: ${normalized} account=${ServerLogUtil.sanitizeAccount(account)}`);
- if (normalized === '/' || segments.length === 0) {
- const artists: NavidromeArtist[] = await this.navidromeApi.getArtists(account);
- artists.sort((a, b) => a.name.localeCompare(b.name));
- this.webDavFiles = artists.map(artist => {
- const info = this.createNavDirectory(artist.name, `/artist/${artist.id}`);
- this.registerPathLabel(info.href, artist.name);
- return info;
- });
- this.webDavSongs = [];
- void ServerLogUtil.info(TAG, `获取艺术家列表,数量: ${artists.length}`);
- void ServerLogUtil.debug(TAG, `artists ids: ${artists.map(a => a.id).join(',')}`)
- return;
- }
- if (segments[0] === 'artist' && segments[1]) {
- const artistId = segments[1];
- const detail: NavidromeArtistDetail = await this.navidromeApi.getArtist(account, artistId);
- this.registerPathLabel(`/artist/${artistId}`, detail.name);
- this.webDavFiles = detail.albums.map(album => {
- const info = this.createNavDirectory(album.name, `/album/${album.id}`);
- this.registerPathLabel(info.href, album.name);
- return info;
- });
- this.webDavSongs = [];
- void ServerLogUtil.info(TAG, `进入艺术家 ${detail.name},专辑数: ${detail.albums.length}`);
- void ServerLogUtil.debug(TAG, `artist albums: ${detail.albums.map(a => a.id).join(',')}`)
- return;
- }
- if (segments[0] === 'album' && segments[1]) {
- const albumId = segments[1];
- const detail: NavidromeAlbumDetail = await this.navidromeApi.getAlbum(account, albumId);
- this.registerPathLabel(`/album/${albumId}`, detail.name);
- this.webDavFiles = detail.songs.map(song => this.createNavSongFileInfo(song, albumId));
- const albumCoverUrl = await this.navidromeApi.buildCoverArtUrl(account,
- detail.coverArt ?? (detail.id ? `al-${detail.id}` : undefined));
- this.webDavSongs = detail.songs.map(song => this.buildNavidromeVideoItem(song, account, detail, albumCoverUrl));
- await this.enrichSongsWithDatabase(this.webDavSongs);
- void ServerLogUtil.info(TAG, `进入专辑 ${detail.name},歌曲数: ${detail.songs.length}`);
- void ServerLogUtil.debug(TAG, `album songs ids: ${detail.songs.map(s => s.id).join(',')}`)
- return;
- }
- throw new Error(`不支持的Navidrome路径: ${fullPath}`);
- }
- private async enrichSongsWithDatabase(videoItems: VideoItem[]): Promise<void> {
- if (!this.context || !videoItems || videoItems.length === 0) {
- return;
- }
- try {
- const mediaTable = new MediaTable(this.context);
- await new Promise<void>((resolve) => {
- mediaTable.getRdbStore(this.context as common.Context, () => resolve());
- });
- const pathMap: Map<string, VideoItem[]> = new Map();
- for (let i = 0; i < videoItems.length; i++) {
- const item = videoItems[i];
- const storagePath = this.resolveStoragePathForItem(item);
- if (!storagePath) {
- continue;
- }
- if (!pathMap.has(storagePath)) {
- pathMap.set(storagePath, []);
- }
- pathMap.get(storagePath)?.push(item);
- }
- if (pathMap.size === 0) {
- return;
- }
- const tasks: Promise<void>[] = [];
- pathMap.forEach((targets, storagePath) => {
- tasks.push((async () => {
- try {
- const cached = await mediaTable.queryVideoByFilePath(storagePath);
- if (cached) {
- targets.forEach(target => this.mergeCachedMetadata(target, cached, storagePath));
- }
- } catch (error) {
- Logger.error(TAG, `查询缓存元数据失败: ${storagePath} - ${(error as Error).message}`);
- }
- })());
- });
- await Promise.all(tasks);
- } catch (error) {
- Logger.error(TAG, `补全云端歌曲元数据失败: ${(error as Error).message}`);
- }
- }
- private resolveStoragePathForItem(item: VideoItem): string | null {
- if (!item) {
- return null;
- }
- if (item.type === CommonConstants.TYPE_WEBDAV) {
- const relative = item.remote_rel_path || WebDavUrlUtil.toStoragePath(item.filePath);
- if (relative) {
- item.remote_rel_path = relative;
- return relative;
- }
- return null;
- }
- if (item.type === CommonConstants.TYPE_SMB || item.type === CommonConstants.TYPE_NAVIDROME ||
- item.type === CommonConstants.TYPE_FTP || item.type === CommonConstants.TYPE_BAIDU) {
- if (item.remote_rel_path) {
- return item.remote_rel_path;
- }
- return null;
- }
- return null;
- }
- private mergeCachedMetadata(target: VideoItem, cached: VideoItem, storagePath: string): void {
- target.id = cached.id || target.id || storagePath;
- target.name = cached.name || target.name;
- target.artist = cached.artist || target.artist;
- target.album = cached.album || target.album;
- target.duration = cached.duration || target.duration;
- target.size = cached.size || target.size;
- target.pixelMapPath = cached.pixelMapPath || target.pixelMapPath;
- target.lyricContent = cached.lyricContent || target.lyricContent;
- target.md5Str = cached.md5Str || target.md5Str;
- target.bit_rate = cached.bit_rate || target.bit_rate;
- target.sampleRate = cached.sampleRate || target.sampleRate;
- target.trackCount = cached.trackCount || target.trackCount;
- target.mimeType = cached.mimeType || target.mimeType;
- target.pyStr = cached.pyStr || target.pyStr;
- target.genre = cached.genre || target.genre;
- target.track = cached.track || target.track;
- target.year = cached.year || target.year;
- target.webdav_account_id = target.webdav_account_id || cached.webdav_account_id;
- target.remote_rel_path = target.remote_rel_path || cached.remote_rel_path || storagePath;
- }
- // 将FileInfo转换为VideoItem
- private fileInfoToVideoItem(fileInfo: FileInfo, account: WebDavAccount): VideoItem {
- if (account.webType === RemoteDriveType.Smb) {
- return this.buildSmbVideoItem(fileInfo, account);
- }
- if (account.webType === RemoteDriveType.Ftp) {
- return this.buildFtpVideoItem(fileInfo, account);
- }
- // 构建安全的WebDAV URL(不包含认证信息)
- const protocol = account.enableHttps ? 'https' : 'http';
- const host = account.isUseLocalHost ? account.localHost : account.host;
- const port = account.port;
- // 构建基础URL,确保路径重新编码(目录/文件名中的中文与空格)
- const safeHref = this.normalizeRemoteHref(fileInfo.href);
- const encodedHref = encodeURI(safeHref); // 仅编码非保留字符,已编码的百分号不重复编码
- const absoluteUrl = `${protocol}://${host}:${port}${encodedHref}`;
- // 创建VideoItem对象
- // 构造函数签名: (name, id, filePath, type, videoSize, cTime, size?, pixelMapPath?, artist?, album?, fileName?, lastPlayed?)
- const videoItem = new VideoItem(
- this.getFileNameWithoutExtension(fileInfo.fileName), // name: 歌曲名
- '', // id: 空字符串,WebDAV文件无本地ID
- absoluteUrl, // filePath: 绝对路径
- CommonConstants.TYPE_WEBDAV, // type: WebDAV类型
- fileInfo.contentLength, // videoSize: 文件大小
- Utility.getFormatDateStr(fileInfo.time,'yyyy-MM-dd HH:mm'), // cTime: 修改时间
- undefined, // size
- undefined, // pixelMapPath: 对于WebDAV歌曲不设置图片路径
- Constants.UNKNOWN_ARTIST, // artist: 艺术家
- undefined, // album: 专辑
- fileInfo.fileName // fileName: 真实文件名
- );
- videoItem.size = Utility.formatFSize(fileInfo.contentLength)
- //根据文件名解析艺术家
- const musicData:MusicInfo = parseMusicFileName(fileInfo.fileName);
- if (musicData.isValid) {
- console.log('onecold parseMusicFileName artist:', musicData.artist)
- videoItem.artist = musicData.artist
- videoItem.name = musicData.title
- }
- videoItem.album = ''
- // 设置WebDAV账号ID,用于后续认证信息查询
- if (account && account.id) {
- videoItem.webdav_account_id = account.id.toString();
- }
- // 计算并保存相对路径
- try {
- const relMatch = absoluteUrl.match(/^https?:\/\/[^\/]+(?::\d+)?(\/.*)$/i);
- if (relMatch && relMatch[1]) {
- videoItem.remote_rel_path = relMatch[1];
- }
- } catch (e) {
- Logger.warn(TAG, '计算相对路径失败: ' + (e as Error).message);
- }
- return videoItem;
- }
- private buildSmbVideoItem(fileInfo: FileInfo, account: WebDavAccount): VideoItem {
- const relativePath = fileInfo.href && fileInfo.href.length > 0 ? fileInfo.href : `/${fileInfo.fileName}`;
- const normalizedRelative = relativePath.startsWith('/') ? relativePath : `/${relativePath}`;
- const sanitizedRelative = this.normalizeSmbRelativePath(normalizedRelative, account.smbShare);
- const videoItem = new VideoItem(
- this.getFileNameWithoutExtension(fileInfo.fileName),
- '',
- sanitizedRelative,
- CommonConstants.TYPE_SMB,
- fileInfo.contentLength,
- Utility.getFormatDateStr(fileInfo.time, 'yyyy-MM-dd HH:mm'),
- undefined,
- undefined,
- Constants.UNKNOWN_ARTIST,
- undefined,
- fileInfo.fileName
- );
- videoItem.album = ''
- videoItem.size = Utility.formatFSize(fileInfo.contentLength);
- if (account && account.id) {
- videoItem.webdav_account_id = account.id.toString();
- }
- videoItem.remote_rel_path = sanitizedRelative;
- const hostForDisplay = account.host && account.host.trim().length > 0
- ? account.host.trim()
- : (account.id?.toString() ?? '');
- const cleanedShare = account.smbShare
- ? account.smbShare.replace(/^\/+|\/+$/g, '')
- : '';
- const relativeForDisplay = sanitizedRelative === '/' ? '' : sanitizedRelative;
- if (hostForDisplay.length > 0 && cleanedShare.length > 0) {
- videoItem.filePath = `smb://${hostForDisplay}/${cleanedShare}${relativeForDisplay}`;
- } else if (hostForDisplay.length > 0) {
- videoItem.filePath = `smb://${hostForDisplay}${relativeForDisplay}`;
- } else {
- videoItem.filePath = `smb://${account.id}${relativeForDisplay}`;
- }
- const musicData: MusicInfo = parseMusicFileName(fileInfo.fileName);
- if (musicData.isValid) {
- videoItem.artist = musicData.artist;
- videoItem.name = musicData.title;
- }
- return videoItem;
- }
- private ftpEntryToFileInfo(entry: FtpEntryInfo, basePath: string): FileInfo {
- const normalizedBase = this.normalizeFullPath(basePath);
- const targetPath = this.normalizeFullPath(`${normalizedBase === '/' ? '' : normalizedBase}/${entry.name}`);
- const info = new FileInfo(normalizedBase, entry.name, entry.size ?? 0, entry.modifiedAt ? entry.modifiedAt.getTime() : Date.now());
- info.fileName = entry.name;
- info.href = targetPath;
- info.isDirectory = Boolean(entry.isDirectory);
- info.contentLength = entry.size ?? 0;
- info.time = entry.modifiedAt ? entry.modifiedAt.getTime() : Date.now();
- return info;
- }
- private buildFtpVideoItem(fileInfo: FileInfo, account: WebDavAccount): VideoItem {
- const host = this.resolveFtpHost(account);
- if (!host) {
- throw new Error('FTP账号缺少服务器地址');
- }
- const normalizedPath = this.normalizeFullPath(fileInfo.href || `/${fileInfo.fileName}`);
- const encodedPath = encodeURI(normalizedPath);
- const port = account.port && account.port > 0 ? `:${account.port}` : '';
- const ftpUrl = `ftp://${host}${port}${encodedPath}`;
- const videoItem = new VideoItem(
- this.getFileNameWithoutExtension(fileInfo.fileName),
- '',
- ftpUrl,
- CommonConstants.TYPE_FTP,
- fileInfo.contentLength,
- Utility.getFormatDateStr(fileInfo.time, 'yyyy-MM-dd HH:mm')
- );
- videoItem.album = '';
- videoItem.size = Utility.formatFSize(fileInfo.contentLength);
- const musicData: MusicInfo = parseMusicFileName(fileInfo.fileName);
- if (musicData.isValid) {
- videoItem.artist = musicData.artist;
- videoItem.name = musicData.title;
- } else {
- videoItem.artist = Constants.UNKNOWN_ARTIST;
- }
- if (account && account.id) {
- videoItem.webdav_account_id = account.id.toString();
- }
- videoItem.remote_rel_path = normalizedPath;
- return videoItem;
- }
- private baiduEntryToFileInfo(entry: BaiduListEntry): FileInfo {
- const timestamp = (entry.server_mtime ?? Date.now()) * 1000;
- const info = new FileInfo('', entry.server_filename, entry.size, timestamp);
- info.fileName = entry.server_filename;
- info.href = entry.path;
- info.isDirectory = entry.isdir === 1;
- info.contentLength = entry.size;
- info.time = timestamp;
- return info;
- }
- private buildBaiduVideoItem(entry: BaiduListEntry, account: WebDavAccount): VideoItem {
- const timestamp = (entry.server_mtime ?? Date.now()) * 1000;
- const videoItem = new VideoItem(
- this.getFileNameWithoutExtension(entry.server_filename),
- entry.fs_id.toString(),
- `baidupan://${account.id ?? 0}${entry.path}`,
- CommonConstants.TYPE_BAIDU,
- entry.size,
- Utility.getFormatDateStr(timestamp, 'yyyy-MM-dd HH:mm'),
- Utility.formatFSize(entry.size)
- );
- videoItem.size = Utility.formatFSize(entry.size);
- videoItem.album = '';
- videoItem.remote_rel_path = entry.path;
- videoItem.baiduFsId = entry.fs_id.toString();
- if (account && account.id) {
- videoItem.webdav_account_id = account.id.toString();
- }
- const musicData: MusicInfo = parseMusicFileName(entry.server_filename);
- if (musicData.isValid) {
- videoItem.artist = musicData.artist;
- videoItem.name = musicData.title;
- } else {
- videoItem.artist = Constants.UNKNOWN_ARTIST;
- }
- return videoItem;
- }
- private async ensureBaiduAccessToken(account: WebDavAccount): Promise<string> {
- if (account.baiduAccessToken) {
- if (!account.baiduTokenExpiresAt || (account.baiduTokenExpiresAt - Date.now()) > 60 * 1000) {
- return account.baiduAccessToken;
- }
- }
- if (!account.baiduRefreshToken) {
- throw new Error('百度网盘授权已过期,请在账户设置中重新登录百度网盘');
- }
- const token = await refreshBaiduAccessToken(account.baiduRefreshToken);
- account.baiduAccessToken = token.access_token;
- account.baiduRefreshToken = token.refresh_token ?? account.baiduRefreshToken;
- account.baiduTokenExpiresAt = token.expires_in ? Date.now() + token.expires_in * 1000 : 0;
- await this.persistBaiduTokens(account);
- return account.baiduAccessToken;
- }
- private async persistBaiduTokens(account: WebDavAccount): Promise<void> {
- if (!account.id) {
- return;
- }
- const predicates = new relationalStore.RdbPredicates(this.webDavTable);
- predicates.equalTo('id', account.id);
- const values: relationalStore.ValuesBucket = {
- baiduAccessToken: account.baiduAccessToken,
- baiduRefreshToken: account.baiduRefreshToken,
- baiduTokenExpiresAt: account.baiduTokenExpiresAt
- };
- await this.dataBaseUtil.updateData(this.webDavTable, values, predicates);
- }
- private getBaiduCacheKey(account: WebDavAccount, fsId: string): string {
- return `${account.id ?? '0'}_${fsId}`;
- }
- private cacheBaiduDlink(account: WebDavAccount, fsId: string, token: string, url: string): void {
- const key = this.getBaiduCacheKey(account, fsId);
- const expireAt = Date.now() + RemoteDriveManager.BAIDU_DLINK_CACHE_TTL;
- this.baiduDlinkCache.set(key, { url, token, expireAt });
- }
- private getCachedBaiduDlink(account: WebDavAccount, fsId: string, token: string): string | null {
- const key = this.getBaiduCacheKey(account, fsId);
- const cached = this.baiduDlinkCache.get(key);
- if (!cached) {
- return null;
- }
- if (cached.token !== token || cached.expireAt <= Date.now()) {
- this.baiduDlinkCache.delete(key);
- return null;
- }
- return cached.url;
- }
- public async getBaiduDownloadUrl(account: WebDavAccount, song: VideoItem): Promise<string> {
- const accessToken = await this.ensureBaiduAccessToken(account);
- const fsId = song.baiduFsId || song.id;
- if (!fsId) {
- throw new Error('缺少百度网盘文件fs_id');
- }
- const cached = this.getCachedBaiduDlink(account, fsId, accessToken);
- if (cached) {
- Logger.info(TAG, `Baidu dlink cache hit, fsId=${fsId}`);
- return cached;
- }
- const metas = await fetchBaiduFileMetas(accessToken, [fsId]);
- if (!metas || metas.length === 0 || !metas[0].dlink) {
- throw new Error('无法获取下载链接');
- }
- const rawLink = metas[0].dlink.startsWith('https://') ? metas[0].dlink : metas[0].dlink.replace('http://', 'https://');
- const urlWithToken = appendAccessTokenToDlink(rawLink, accessToken);
- Logger.info(TAG, `Baidu dlink ready, fsId=${fsId} url=${urlWithToken}`);
- this.cacheBaiduDlink(account, fsId, accessToken, urlWithToken);
- return urlWithToken;
- }
- public async getBaiduFileInfo(account: WebDavAccount, fsId: string, remotePath?: string): Promise<BaiduFileInfo> {
- const accessToken = await this.ensureBaiduAccessToken(account);
- if (!fsId) {
- throw new Error('缺少百度网盘文件fs_id');
- }
- Logger.info(TAG, `查询百度网盘文件信息: fsId=${fsId}`);
- const metas = await fetchBaiduFileMetas(accessToken, [fsId]);
- if (!metas || metas.length === 0) {
- throw new Error('无法获取文件信息');
- }
- const meta = metas[0];
- if (!meta.dlink) {
- throw new Error('无法获取下载链接');
- }
- const rawLink = meta.dlink.startsWith('https://') ? meta.dlink : meta.dlink.replace('http://', 'https://');
- const urlWithToken = appendAccessTokenToDlink(rawLink, accessToken);
- let streamUrl = urlWithToken;
- if (remotePath) {
- try {
- await ensureAudioStreamReady(accessToken, remotePath);
- streamUrl = buildAudioStreamingUrl(accessToken, remotePath);
- Logger.info(TAG, `百度网盘文件信息获取成功: fsId=${fsId}, size=${meta.size}, streamUrl=${streamUrl}`);
- } catch (streamError) {
- const err = streamError as Error;
- Logger.warn(TAG, `百度音频流暂不可用,回退到下载链接: ${err.message}`);
- streamUrl = urlWithToken;
- }
- } else {
- Logger.warn(TAG, `缺少百度网盘文件路径,使用下载链接播放: fsId=${fsId}`);
- }
- // 缓存 dlink
- this.cacheBaiduDlink(account, fsId, accessToken, urlWithToken);
- const result: BaiduFileInfo = {
- size: meta.size,
- dlink: urlWithToken,
- streamUrl
- };
- return result;
- }
- private smbEntryToFileInfo(entry: SmbDirectoryEntry, basePath: string): FileInfo {
- const normalizedPath = this.combineRemotePath(basePath, entry.name, entry.isDirectory);
- const info = new FileInfo('', entry.name, entry.size, Date.now());
- info.fileName = entry.name;
- info.href = normalizedPath;
- info.contentLength = entry.size ?? 0;
- info.isDirectory = entry.isDirectory;
- return info;
- }
- private combineRemotePath(basePath: string, name: string, isDirectory: boolean): string {
- const segments: string[] = [];
- const trimmedBase = basePath ? basePath.replace(/^\/+/, '').replace(/\/+/g, '/') : '';
- if (trimmedBase.length > 0) {
- segments.push(trimmedBase);
- }
- const cleanedName = name.replace(/^\/+/, '').replace(/\/+/g, '/');
- if (cleanedName.length > 0) {
- segments.push(cleanedName);
- }
- let fullPath = `/${segments.filter(part => part.length > 0).join('/')}`;
- if (isDirectory && !fullPath.endsWith('/')) {
- fullPath = `${fullPath}/`;
- }
- if (!isDirectory && fullPath.endsWith('/')) {
- fullPath = fullPath.slice(0, -1);
- }
- return fullPath;
- }
- private createNavDirectory(name: string, href: string): FileInfo {
- const info = new FileInfo('', name, 0, Date.now());
- info.fileName = name;
- info.href = this.normalizeFullPath(href);
- info.isDirectory = true;
- return info;
- }
- private createNavSongFileInfo(song: NavidromeSong, albumId: string): FileInfo {
- const displayName = song.title ?? '未知曲目';
- const info = new FileInfo('', displayName, song.size ?? 0, Date.now());
- info.fileName = `${displayName}${song.suffix ? '.' + song.suffix : ''}`;
- info.href = this.normalizeFullPath(`/album/${albumId}/${song.id}`);
- info.isDirectory = false;
- info.contentLength = song.size ?? 0;
- return info;
- }
- private buildNavidromeVideoItem(song: NavidromeSong, account: WebDavAccount, album?: NavidromeAlbumDetail, coverUrl?: string): VideoItem {
- const title = song.title ?? '未知曲目';
- const fileName = `${title}${song.suffix ? '.' + song.suffix : ''}`;
- const videoItem = new VideoItem(
- title,
- song.id,
- `navidrome://${account.id ?? 0}/${song.id}`,
- CommonConstants.TYPE_NAVIDROME,
- song.size ?? 0,
- Utility.getFormatDateStr(Date.now(), 'yyyy-MM-dd HH:mm'),
- Utility.formatFSize(song.size ?? 0),
- undefined,
- song.artist ?? album?.artist ?? Constants.UNKNOWN_ARTIST,
- album?.name ?? song.album,
- fileName
- );
- videoItem.size = Utility.formatFSize(song.size ?? 0);
- videoItem.webdav_account_id = account.id?.toString();
- videoItem.remote_rel_path = song.id;
- videoItem.bit_rate = song.bitRate ? song.bitRate.toString() : undefined;
- videoItem.mimeType = song.contentType;
- videoItem.pixelMapPath = coverUrl;
- if (song.track !== undefined && song.track !== null) {
- videoItem.track = song.track.toString();
- }
- if (song.year !== undefined && song.year !== null) {
- videoItem.year = song.year.toString();
- }
- return videoItem;
- }
- private registerPathLabel(path: string, label: string): void {
- if (!path || label === undefined) {
- return;
- }
- const normalized = this.normalizeFullPath(path);
- const sanitizedLabel = this.sanitizeLabel(label);
- this.pathDisplayNames.set(normalized, sanitizedLabel);
- }
- private sanitizeLabel(label: string): string {
- if (!label) {
- return '';
- }
- if (label === '根目录') {
- return label;
- }
- let sanitized = label.trim();
- sanitized = sanitized.replace(/\/+$/, '');
- if (sanitized.length === 0) {
- sanitized = '/';
- }
- try {
- sanitized = decodeURIComponent(sanitized);
- } catch (error) {
- // ignore decode failure, keep original label
- }
- return sanitized;
- }
- private getBasePath(account: WebDavAccount | null = this.currentAccount): string {
- if (account && account.filepath) {
- return this.normalizeFullPath(account.filepath);
- }
- return '/';
- }
- private getRelativePath(fullPath: string, basePath: string): string {
- const normalizedFull = this.normalizeFullPath(fullPath);
- const normalizedBase = this.normalizeFullPath(basePath);
- if (normalizedFull === normalizedBase) {
- return '';
- }
- if (normalizedFull.startsWith(normalizedBase) && normalizedBase !== '/') {
- return normalizedFull.substring(normalizedBase.length).replace(/^\/+/, '');
- }
- return normalizedFull.replace(/^\/+/, '');
- }
- private normalizeSmbRelativePath(path: string, shareName?: string): string {
- if (!path || path.trim().length === 0) {
- return '/';
- }
- let normalized = path.replace(/\/+/g, '/');
- if (!normalized.startsWith('/')) {
- normalized = `/${normalized}`;
- }
- if (normalized.length > 1 && normalized.endsWith('/')) {
- normalized = normalized.slice(0, -1);
- }
- if (shareName) {
- const cleanedShare = shareName.replace(/^\/+|\/+$/g, '');
- if (cleanedShare.length > 0) {
- const prefix = `/${cleanedShare}`;
- if (normalized === prefix) {
- normalized = '/';
- } else if (normalized.startsWith(`${prefix}/`)) {
- normalized = normalized.substring(prefix.length);
- if (!normalized.startsWith('/')) {
- normalized = `/${normalized}`;
- }
- }
- }
- }
- return normalized || '/';
- }
- // 判断是否为音频文件
- private isAudioFile(fileName: string): boolean {
- const ext = this.getFileExtension(fileName).toLowerCase();
- for (let i = 0; i < this.audioExtensions.length; i++) {
- if (ext === this.audioExtensions[i]) {
- return true;
- }
- }
- return false;
- }
- // 获取文件扩展名
- private getFileExtension(fileName: string): string {
- const lastDotIndex = fileName.lastIndexOf('.');
- if (lastDotIndex === -1) {
- return '';
- }
- return fileName.substring(lastDotIndex);
- }
- // 获取不带扩展名的文件名
- private getFileNameWithoutExtension(fileName: string): string {
- const lastDotIndex = fileName.lastIndexOf('.');
- if (lastDotIndex === -1) {
- return fileName;
- }
- return fileName.substring(0, lastDotIndex);
- }
- // 进入文件夹
- public async enterFolder(folder: FileInfo): Promise<void> {
- if (!folder.isDirectory) {
- Logger.error(TAG, '不是文件夹,无法进入');
- return;
- }
- Logger.info(TAG, '准备进入文件夹:', folder.fileName);
- Logger.info(TAG, '当前路径:', this.currentPath);
- Logger.info(TAG, '目标路径:', folder.href);
- // 保存当前路径到历史记录
- this.registerPathLabel(folder.href, folder.fileName);
- this.pathHistory.push(this.currentPath);
- Logger.info(TAG, '路径历史:', JSON.stringify(this.pathHistory));
- // 加载文件夹内容
- await this.loadFilesInfoFromAccount(this.currentAccount, folder.href);
- }
- public async enterFolderFromPath(path: string): Promise<void> {
- const normalizedTarget = this.normalizeFullPath(path);
- Logger.info(TAG, '当前路径:', this.currentPath);
- Logger.info(TAG, '目标路径:', normalizedTarget);
- this.rebuildPathHistoryForTarget(normalizedTarget);
- Logger.info(TAG, '路径历史:', JSON.stringify(this.pathHistory));
- await this.loadFilesInfoFromAccount(this.currentAccount, normalizedTarget);
- }
- private rebuildPathHistoryForTarget(targetPath: string): void {
- if (!targetPath) {
- this.pathHistory = [];
- return;
- }
- const normalizedTarget = this.normalizeFullPath(targetPath);
- const basePath = this.getBasePath();
- if (normalizedTarget === basePath) {
- this.pathHistory = [];
- return;
- }
- const relativePath = this.getRelativePath(normalizedTarget, basePath);
- if (!relativePath) {
- this.pathHistory = [];
- return;
- }
- const parts = relativePath.split('/').filter(part => part.length > 0);
- const rebuiltHistory: string[] = [];
- // 把账户根路径作为栈底,以便可以返回
- rebuiltHistory.push(basePath);
- let cumulative = basePath;
- for (let i = 0; i < parts.length - 1; i++) {
- const segment = parts[i];
- cumulative = this.normalizeFullPath(`${cumulative === '/' ? '' : cumulative}/${segment}`);
- rebuiltHistory.push(cumulative);
- }
- this.pathHistory = rebuiltHistory;
- }
- // 返回上级目录
- public async goBack(): Promise<void> {
- if (this.pathHistory.length === 0) {
- Logger.info(TAG, '已经在根目录,无法返回');
- return;
- }
- // 从历史记录中取出上一级路径
- const previousPath = this.pathHistory.pop();
- if (previousPath !== undefined) {
- await this.loadFilesInfoFromAccount(this.currentAccount, previousPath);
- }
- }
- // 获取面包屑路径数组
- public getBreadcrumbs(): BreadcrumbItem[] {
- const basePath = this.getBasePath();
- const breadcrumbs: BreadcrumbItem[] = [{
- label: '根目录',
- path: basePath
- }];
- if (!this.currentPath || this.normalizeFullPath(this.currentPath) === basePath) {
- return breadcrumbs;
- }
- const relativePath = this.getRelativePath(this.currentPath, basePath);
- if (!relativePath) {
- return breadcrumbs;
- }
- const parts = relativePath.split('/').filter(part => part.length > 0);
- let cumulative = basePath;
- for (let i = 0; i < parts.length; i++) {
- const segment = parts[i];
- const targetPath = this.normalizeFullPath(`${cumulative === '/' ? '' : cumulative}/${segment}`);
- const label = this.pathDisplayNames.get(targetPath) ?? segment;
- breadcrumbs.push({
- label: this.sanitizeLabel(label),
- path: targetPath
- });
- cumulative = targetPath;
- }
- return breadcrumbs;
- }
- // 是否可以返回上级
- public canGoBack(): boolean {
- if(this.currentPath==='/')
- return false
- return this.pathHistory.length > 0;
- }
- // ==================== Preferences操作 ====================
- // 加载历史数据(从Preferences迁移)
- public async loadInfo(): Promise<void> {
- try {
- // 这里可以添加从Preferences加载历史配置的逻辑
- Logger.info(TAG, '从Preferences加载配置');
- } catch (error) {
- Logger.error(TAG, '从Preferences加载配置失败:', error.toString());
- }
- }
- // 保存配置到Preferences
- public async saveInfo(): Promise<void> {
- try {
- // 这里可以添加保存配置到Preferences的逻辑
- Logger.info(TAG, '保存配置到Preferences');
- } catch (error) {
- Logger.error(TAG, '保存配置到Preferences失败:', error.toString());
- }
- }
- // ==================== 下载队列管理 ====================
- // 添加到下载队列
- public addToDownloadQueue(song: VideoItem, account: WebDavAccount): void {
- const task: TransferTask = { song, account };
- this.downloadQueue.push(task);
- Logger.info(TAG, '添加到下载队列:', song.name);
- this.notifyObservers(RemoteDriveManagerStates.DownloadQueueChanged);
- }
- // 从下载队列移除
- public removeFromDownloadQueue(index: number): void {
- if (index >= 0 && index < this.downloadQueue.length) {
- const task = this.downloadQueue[index];
- this.downloadQueue.splice(index, 1);
- Logger.info(TAG, '从下载队列移除:', task.song.name);
- this.notifyObservers(RemoteDriveManagerStates.DownloadQueueChanged);
- }
- }
- // 清空下载队列
- public clearDownloadQueue(): void {
- this.downloadQueue = [];
- Logger.info(TAG, '清空下载队列');
- this.notifyObservers(RemoteDriveManagerStates.DownloadQueueChanged);
- }
- // ==================== 上传队列管理 ====================
- /**
- * 添加歌曲到上传队列
- * @param songs 要上传的歌曲列表
- * @param account 目标WebDAV账户
- * @param customUploadPath 自定义上传路径(可选,如果不提供则使用账户默认路径)
- */
- public addToUploadQueue(songs: VideoItem[], account: WebDavAccount, customUploadPath?: string): void {
- Logger.info(TAG, '========== 添加上传任务 ==========');
- Logger.info(TAG, `请求添加: ${songs.length} 个文件`);
- Logger.info(TAG, `目标账户: ${account.name} (ID: ${account.id})`);
- Logger.info(TAG, `自定义上传路径: ${customUploadPath || '未指定,使用账户默认路径'}`);
- Logger.info(TAG, `当前队列: ${this.uploadQueue.length}/${this.MAX_UPLOAD_QUEUE_SIZE}`);
-
- // 检查队列大小限制
- const availableSlots = this.MAX_UPLOAD_QUEUE_SIZE - this.uploadQueue.length;
- if (availableSlots <= 0) {
- Logger.warn(TAG, `上传队列已满(最大${this.MAX_UPLOAD_QUEUE_SIZE}个任务),无法添加更多任务`);
- Logger.warn(TAG, '====================================');
- return;
- }
-
- // 限制添加数量
- const songsToAdd = songs.length > availableSlots ? songs.slice(0, availableSlots) : songs;
- const existingKeys = new Set<string>();
- for (let i = 0; i < this.uploadQueue.length; i++) {
- const key = this.getSongKey(this.uploadQueue[i].song);
- if (key) {
- existingKeys.add(key);
- }
- }
- const filteredSongs: VideoItem[] = [];
- for (let i = 0; i < songsToAdd.length; i++) {
- const song = songsToAdd[i];
- const key = this.getSongKey(song);
- if (key && existingKeys.has(key)) {
- Logger.warn(TAG, `检测到重复任务,已跳过: ${song.name}`);
- continue;
- }
- if (key) {
- existingKeys.add(key);
- }
- filteredSongs.push(song);
- }
-
- Logger.info(TAG, `实际添加: ${filteredSongs.length} 个文件`);
-
- for (let i = 0; i < filteredSongs.length; i++) {
- const song = filteredSongs[i];
- const task: TransferTask = {
- song,
- account,
- customUploadPath: customUploadPath // 保存自定义上传路径
- };
- this.uploadQueue.push(task);
- Logger.info(TAG, `[${i + 1}/${songsToAdd.length}] ${song.name}`);
- }
-
- if (songs.length > songsToAdd.length) {
- Logger.warn(TAG, `队列空间不足,仅处理前${songsToAdd.length}/${songs.length}个任务`);
- }
-
- Logger.info(TAG, `新队列大小: ${this.uploadQueue.length}/${this.MAX_UPLOAD_QUEUE_SIZE}`);
- Logger.info(TAG, '====================================');
-
- this.notifyObservers(RemoteDriveManagerStates.UploadQueueChanged);
- this.notifyObservers(RemoteDriveManagerStates.ChangeUploadQueue);
- }
- /**
- * 开始处理上传队列
- */
- public async startUploadQueue(): Promise<void> {
- if (this.isProcessingUploadQueue) {
- Logger.warn(TAG, '上传队列正在处理中');
- return;
- }
- if (this.uploadQueue.length === 0) {
- Logger.info(TAG, '上传队列为空');
- return;
- }
- this.isProcessingUploadQueue = true;
- this.isPauseUpload = false;
- Logger.info(TAG, '开始处理上传队列,共', this.uploadQueue.length.toString(), '个任务');
- await this.processNextUploadTask();
- }
- /**
- * 处理下一个上传任务
- */
- private async processNextUploadTask(): Promise<void> {
- if (this.isPauseUpload) {
- Logger.info(TAG, '========== 上传队列已暂停 ==========');
- Logger.info(TAG, `剩余任务数: ${this.uploadQueue.length}`);
- Logger.info(TAG, '====================================');
- this.isProcessingUploadQueue = false;
- return;
- }
- if (this.uploadQueue.length === 0) {
- Logger.info(TAG, '========== 上传队列已完成 ==========');
- Logger.info(TAG, `成功上传: ${this.finishUploadQueue.length} 个文件`);
- Logger.info(TAG, '====================================');
-
- this.isProcessingUploadQueue = false;
- this.currentUploadTask = null;
- this.notifyObservers(RemoteDriveManagerStates.SetCurrentUploadTask);
-
- // 检查是否需要自动清理完成队列
- const autoClear = PreferencesUtil.getBooleanSync('webdavUploadAutoClear', false);
- if (autoClear && this.finishUploadQueue.length > 0) {
- Logger.info(TAG, '自动清理完成队列');
- this.finishUploadQueue = [];
- this.notifyObservers(RemoteDriveManagerStates.ChangeFinishUploadQueue);
- }
-
- return;
- }
- const task = this.uploadQueue[0];
- this.currentUploadTask = task;
-
- Logger.info(TAG, '========== 处理上传队列 ==========');
- Logger.info(TAG, `当前任务: ${task.song.name}`);
- Logger.info(TAG, `队列位置: 1/${this.uploadQueue.length}`);
- Logger.info(TAG, `已完成: ${this.finishUploadQueue.length}`);
- Logger.info(TAG, '====================================');
-
- this.notifyObservers(RemoteDriveManagerStates.SetCurrentUploadTask);
- try {
- await this.uploadSingleFile(task);
-
- // 上传成功,移到完成队列
- Logger.info(TAG, `任务成功,移至完成队列: ${task.song.name}`);
- this.uploadQueue.shift();
- this.finishUploadQueue.push(task);
- this.notifyObservers(RemoteDriveManagerStates.UploadSuccess);
- this.notifyObservers(RemoteDriveManagerStates.ChangeUploadQueue);
- this.notifyObservers(RemoteDriveManagerStates.ChangeFinishUploadQueue);
- // 继续处理下一个任务
- await this.processNextUploadTask();
- } catch (error) {
- const err = error as Error;
- Logger.error(TAG, '---------- 任务失败 ----------');
- Logger.error(TAG, `文件: ${task.song.name}`);
- Logger.error(TAG, `错误: ${err.message}`);
-
- // 获取重试次数设置
- const maxRetryCount = PreferencesUtil.getNumberSync('webdavUploadRetryCount', 3);
- const currentRetryCount = task.retryCount || 0;
-
- if (currentRetryCount < maxRetryCount) {
- // 还可以重试
- task.retryCount = currentRetryCount + 1;
- Logger.info(TAG, `准备重试上传 (${task.retryCount}/${maxRetryCount}): ${task.song.name}`);
- Logger.info(TAG, '将任务移至队列末尾');
-
- // 将任务移到队列末尾重试
- this.uploadQueue.shift();
- this.uploadQueue.push(task);
- this.notifyObservers(RemoteDriveManagerStates.ChangeUploadQueue);
- } else {
- // 已达到最大重试次数,放弃上传
- Logger.error(TAG, `上传失败,已达到最大重试次数 (${maxRetryCount}): ${task.song.name}`);
- Logger.error(TAG, '从队列中移除该任务');
- this.uploadQueue.shift();
- this.notifyObservers(RemoteDriveManagerStates.UploadFailed);
- this.notifyObservers(RemoteDriveManagerStates.ChangeUploadQueue);
- }
-
- Logger.error(TAG, '------------------------------');
- // 继续处理下一个任务
- await this.processNextUploadTask();
- }
- }
- /**
- * 暂停上传队列
- */
- public pauseUploadQueue(): void {
- Logger.info(TAG, '========== 暂停上传队列 ==========');
-
- if (!this.isProcessingUploadQueue) {
- Logger.warn(TAG, '上传队列未在处理中,无需暂停');
- Logger.info(TAG, '====================================');
- return;
- }
- this.isPauseUpload = true;
- Logger.info(TAG, `当前任务: ${this.currentUploadTask?.song.name || '无'}`);
- Logger.info(TAG, `剩余任务: ${this.uploadQueue.length}`);
- Logger.info(TAG, '上传队列已暂停');
- Logger.info(TAG, '====================================');
-
- this.notifyObservers(RemoteDriveManagerStates.UploadPaused);
- this.notifyObservers(RemoteDriveManagerStates.SetIsPauseUpload);
- }
- /**
- * 恢复上传队列
- */
- public async resumeUploadQueue(): Promise<void> {
- Logger.info(TAG, '========== 恢复上传队列 ==========');
-
- if (!this.isPauseUpload) {
- Logger.warn(TAG, '上传队列未暂停,无需恢复');
- Logger.info(TAG, '====================================');
- return;
- }
- this.isPauseUpload = false;
- Logger.info(TAG, `剩余任务: ${this.uploadQueue.length}`);
- Logger.info(TAG, '上传队列已恢复');
- Logger.info(TAG, '====================================');
-
- this.notifyObservers(RemoteDriveManagerStates.UploadResumed);
- this.notifyObservers(RemoteDriveManagerStates.SetIsPauseUpload);
- if (!this.isProcessingUploadQueue) {
- this.isProcessingUploadQueue = true;
- await this.processNextUploadTask();
- }
- }
- /**
- * 从队列中移除任务
- * @param task 要移除的任务
- */
- public removeFromUploadQueue(task: TransferTask): void {
- const index = this.uploadQueue.indexOf(task);
- if (index >= 0) {
- Logger.info(TAG, '========== 移除上传任务 ==========');
- Logger.info(TAG, `文件名: ${task.song.name}`);
- Logger.info(TAG, `队列位置: ${index + 1}/${this.uploadQueue.length}`);
-
- this.uploadQueue.splice(index, 1);
-
- Logger.info(TAG, `新队列大小: ${this.uploadQueue.length}`);
- Logger.info(TAG, '====================================');
-
- this.notifyObservers(RemoteDriveManagerStates.UploadQueueChanged);
- this.notifyObservers(RemoteDriveManagerStates.ChangeUploadQueue);
- } else {
- Logger.warn(TAG, `任务不在队列中: ${task.song.name}`);
- }
- }
-
- /**
- * 清空上传队列
- */
- public clearUploadQueue(): void {
- Logger.info(TAG, '========== 清空上传队列 ==========');
- Logger.info(TAG, `清空前队列大小: ${this.uploadQueue.length}`);
-
- this.uploadQueue = [];
- this.currentUploadTask = null;
-
- Logger.info(TAG, '上传队列已清空');
- Logger.info(TAG, '====================================');
-
- this.notifyObservers(RemoteDriveManagerStates.UploadQueueChanged);
- this.notifyObservers(RemoteDriveManagerStates.ChangeUploadQueue);
- this.notifyObservers(RemoteDriveManagerStates.SetCurrentUploadTask);
- }
- /**
- * 检查是否允许在当前网络下上传
- */
- private async checkNetworkAllowed(): Promise<boolean> {
- try {
- Logger.info(TAG, '检查网络连接状态...');
- const allowMobile = PreferencesUtil.getBooleanSync('webdavUploadAllowMobile', false);
- Logger.info(TAG, `用户设置 - 允许移动网络上传: ${allowMobile}`);
-
- // 如果允许移动网络上传,直接返回true
- if (allowMobile) {
- Logger.info(TAG, '用户已允许移动网络上传,跳过网络类型检查');
- return true;
- }
- // 检查当前网络类型
- Logger.info(TAG, '获取当前网络类型...');
- const netHandle = await connection.getDefaultNet();
- const netCapabilities = await connection.getNetCapabilities(netHandle);
-
- // 检查是否为移动网络
- const isCellular = netCapabilities.bearerTypes.includes(connection.NetBearType.BEARER_CELLULAR);
- const isWifi = netCapabilities.bearerTypes.includes(connection.NetBearType.BEARER_WIFI);
- const isEthernet = netCapabilities.bearerTypes.includes(connection.NetBearType.BEARER_ETHERNET);
-
- Logger.info(TAG, `网络类型 - 移动网络: ${isCellular}, WiFi: ${isWifi}, 以太网: ${isEthernet}`);
-
- if (isCellular) {
- Logger.warn(TAG, '当前为移动网络,且未允许移动网络上传');
- Logger.warn(TAG, '请连接WiFi或在设置中允许移动网络上传');
- return false;
- }
-
- Logger.info(TAG, '网络检查通过,允许上传');
- return true;
- } catch (error) {
- const err = error as Error;
- Logger.error(TAG, '检查网络类型失败:', err.message);
- Logger.warn(TAG, '网络检查失败,默认允许上传');
- // 检查失败时默认允许上传
- return true;
- }
- }
- /**
- * 上传单个文件
- * @param task 上传任务
- */
- private async uploadSingleFile(task: TransferTask): Promise<void> {
- const song = task.song;
- const account = task.account;
- const startTime = Date.now();
- // 详细日志:上传开始
- Logger.info(TAG, '========== 上传任务开始 ==========');
- Logger.info(TAG, `文件名: ${song.name}`);
- Logger.info(TAG, `文件路径: ${song.filePath}`);
- Logger.info(TAG, `文件大小: ${song.videoSize || 0} 字节`);
- Logger.info(TAG, `目标账户: ${account.name} (ID: ${account.id})`);
- Logger.info(TAG, `目标主机: ${account.host}:${account.port}`);
- Logger.info(TAG, `使用HTTPS: ${account.enableHttps}`);
- Logger.info(TAG, `重试次数: ${task.retryCount || 0}`);
-
- try {
- // 检查网络是否允许上传
- Logger.info(TAG, '检查网络连接状态...');
- const networkAllowed = await this.checkNetworkAllowed();
- if (!networkAllowed) {
- const errorMsg = '当前网络不允许上传,请连接WiFi或在设置中允许移动网络上传';
- Logger.error(TAG, `网络检查失败: ${errorMsg}`);
- throw new Error(errorMsg);
- }
- Logger.info(TAG, '网络检查通过');
-
- this.notifyObservers(RemoteDriveManagerStates.UploadStart);
- // 构建远程路径 - 优先使用任务中的自定义路径,否则使用账户默认路径
- const uploadPath = task.customUploadPath || account.uploadFilePath || '/';
- const normalizedPath = this.normalizeFullPath(uploadPath);
- const relativeSegment = this.sanitizeRelativeUploadPath(song.remote_rel_path);
- const fallbackFileName = song.fileName || song.name || `upload-${Date.now()}`;
- const relativePath = relativeSegment.length > 0 ? relativeSegment : fallbackFileName;
- const remotePath = this.combineRemoteUploadPath(normalizedPath, relativePath);
- Logger.info(TAG, '---------- 路径信息 ----------');
- Logger.info(TAG, `任务自定义路径: ${task.customUploadPath || '未指定'}`);
- Logger.info(TAG, `账户默认路径: ${account.uploadFilePath || '未配置'}`);
- Logger.info(TAG, `实际使用路径: ${uploadPath}`);
- Logger.info(TAG, `规范化后的路径: ${normalizedPath}`);
- Logger.info(TAG, `文件名 (fileName): ${song.fileName}`);
- Logger.info(TAG, `文件名 (name): ${song.name}`);
- Logger.info(TAG, `文件相对路径: ${relativePath}`);
- Logger.info(TAG, `最终远程路径: ${remotePath}`);
- Logger.info(TAG, `完整URL将是: ${account.enableHttps ? 'https' : 'http'}://${account.host}:${account.port}${remotePath}`);
- Logger.info(TAG, '------------------------------');
- // 检查文件是否存在
- Logger.info(TAG, '检查远程文件是否存在...');
- const exists = await this.checkFileExists(account, remotePath);
- if (exists) {
- // 根据用户配置的重复文件处理方式来处理
- const duplicateAction = PreferencesUtil.getStringSync('webdavUploadDuplicateAction', 'skip');
- Logger.info(TAG, `文件已存在,处理方式: ${duplicateAction}`);
-
- if (duplicateAction === 'skip') {
- Logger.warn(TAG, '文件已存在,跳过上传:', remotePath);
- return;
- } else if (duplicateAction === 'overwrite') {
- Logger.warn(TAG, '文件已存在,将覆盖:', remotePath);
- } else if (duplicateAction === 'rename') {
- Logger.warn(TAG, '文件已存在,将重命名上传');
- // 重命名逻辑可以在这里实现
- }
- } else {
- Logger.info(TAG, '远程文件不存在,可以上传');
- }
- const remoteDirectory = this.getDirectoryFromRemotePath(remotePath);
- await this.ensureRemoteDirectories(account, remoteDirectory);
- // 执行上传
- Logger.info(TAG, '开始上传文件数据...');
- const host = account.isUseLocalHost && account.localHost ? account.localHost : account.host;
- await this.rcpSocket.uploadFile(
- song.filePath,
- remotePath,
- host,
- account.port,
- account.account,
- account.password,
- account.enableHttps,
- (uploaded: number, total: number) => {
- this.uploadReceivedSize = uploaded;
- this.uploadTotalSize = total;
- // 直接通知UI更新,因为RcpSocketUtil层已经做了节流
- // 详细日志:上传进度
- const progress = total > 0 ? Math.min(100, ((uploaded / total) * 100)) : 0;
- const currentTime = Date.now();
- const elapsedSeconds = (currentTime - startTime) / 1000;
- const speedMBps = uploaded > 0 && elapsedSeconds > 0 ? (uploaded / (1024 * 1024) / elapsedSeconds).toFixed(2) : '0.00';
- Logger.info(TAG, `上传进度: ${progress.toFixed(2)}%, 已上传: ${uploaded}/${total} 字节, 速度: ${speedMBps} MB/s`);
- this.notifyObservers(RemoteDriveManagerStates.UploadProgress);
- }
- );
- // 上传成功
- const endTime = Date.now();
- const duration = ((endTime - startTime) / 1000).toFixed(2);
- const avgSpeed = song.videoSize > 0 ? ((song.videoSize / (1024 * 1024)) / parseFloat(duration)).toFixed(2) : '0.00';
-
- Logger.info(TAG, '========== 上传任务成功 ==========');
- Logger.info(TAG, `文件名: ${song.name}`);
- Logger.info(TAG, `耗时: ${duration} 秒`);
- Logger.info(TAG, `平均速度: ${avgSpeed} MB/s`);
- Logger.info(TAG, `目标路径: ${remotePath}`);
- Logger.info(TAG, '====================================');
-
- } catch (error) {
- const err = error as Error;
- const endTime = Date.now();
- const duration = ((endTime - startTime) / 1000).toFixed(2);
-
- // 详细错误日志
- Logger.error(TAG, '========== 上传任务失败 ==========');
- Logger.error(TAG, `文件名: ${song.name}`);
- Logger.error(TAG, `文件路径: ${song.filePath}`);
- Logger.error(TAG, `目标账户: ${account.name} (ID: ${account.id})`);
- Logger.error(TAG, `目标主机: ${account.host}:${account.port}`);
- Logger.error(TAG, `耗时: ${duration} 秒`);
- Logger.error(TAG, `错误类型: ${this.getErrorType(err)}`);
- Logger.error(TAG, `错误信息: ${err.message}`);
- Logger.error(TAG, `错误堆栈: ${err.stack || '无堆栈信息'}`);
- Logger.error(TAG, `重试次数: ${task.retryCount || 0}`);
- Logger.error(TAG, '====================================');
-
- // 根据错误类型进行分类处理
- this.handleUploadError(err, task);
-
- // 重新抛出错误以便上层处理
- throw err;
- }
- }
-
- /**
- * 获取错误类型
- * @param error 错误对象
- * @returns 错误类型字符串
- */
- private getErrorType(error: Error): string {
- const message = error.message.toLowerCase();
-
- if (message.includes('network') || message.includes('连接') || message.includes('timeout') || message.includes('超时')) {
- return '网络错误';
- } else if (message.includes('auth') || message.includes('认证') || message.includes('401') || message.includes('403')) {
- return '认证错误';
- } else if (message.includes('file') || message.includes('文件') || message.includes('not found') || message.includes('不存在')) {
- return '文件错误';
- } else if (message.includes('server') || message.includes('服务器') || message.includes('500') || message.includes('503')) {
- return '服务器错误';
- } else if (message.includes('space') || message.includes('空间') || message.includes('disk') || message.includes('磁盘')) {
- return '存储空间错误';
- } else {
- return '未知错误';
- }
- }
-
- /**
- * 处理上传错误
- * @param error 错误对象
- * @param task 上传任务
- */
- private handleUploadError(error: Error, task: TransferTask): void {
- const errorType = this.getErrorType(error);
-
- Logger.info(TAG, `处理上传错误,类型: ${errorType}`);
-
- // 根据错误类型决定是否自动暂停
- if (errorType === '网络错误') {
- Logger.warn(TAG, '检测到网络错误,自动暂停上传队列');
- this.pauseUploadQueue();
- } else if (errorType === '认证错误') {
- Logger.error(TAG, '检测到认证错误,请检查账户密码是否正确');
- // 认证错误通常不需要暂停整个队列,但应该提示用户
- } else if (errorType === '服务器错误') {
- Logger.error(TAG, '检测到服务器错误,服务器可能暂时不可用');
- // 服务器错误可能是临时的,可以继续尝试其他文件
- } else if (errorType === '存储空间错误') {
- Logger.error(TAG, '检测到存储空间不足,暂停上传队列');
- this.pauseUploadQueue();
- }
- }
- /**
- * 检查文件是否存在
- * @param account WebDAV账户
- * @param remotePath 远程路径
- */
- private async checkFileExists(account: WebDavAccount, remotePath: string): Promise<boolean> {
- try {
- Logger.info(TAG, `检查远程文件是否存在: ${remotePath}`);
- const host = account.isUseLocalHost && account.localHost ? account.localHost : account.host;
- const fileSize = await this.rcpSocket.RcpSendHead(
- host,
- account.port,
- account.account,
- account.password,
- remotePath,
- account.enableHttps
- );
-
- const exists = fileSize > 0;
- Logger.info(TAG, `文件${exists ? '存在' : '不存在'}, 大小: ${fileSize} 字节`);
- return exists;
- } catch (error) {
- const err = error as Error;
- // HEAD请求失败,说明文件不存在或网络错误
- Logger.info(TAG, `HEAD请求失败: ${err.message}, 假定文件不存在`);
- return false;
- }
- }
- /**
- * 处理重复文件
- * @param account WebDAV账户
- * @param remotePath 远程路径
- * @param action 处理动作:'skip' | 'overwrite' | 'rename'
- */
- private async handleDuplicateFile(
- account: WebDavAccount,
- remotePath: string,
- action: string
- ): Promise<string> {
- if (action === 'skip') {
- throw new Error('文件已存在,跳过上传');
- }
- if (action === 'overwrite') {
- // 删除现有文件
- const host = account.isUseLocalHost && account.localHost ? account.localHost : account.host;
- await this.rcpSocket.RcpSendDelete(
- host,
- account.port,
- account.account,
- account.password,
- remotePath,
- account.enableHttps
- );
- return remotePath;
- }
- if (action === 'rename') {
- // 生成新文件名
- const lastDotIndex = remotePath.lastIndexOf('.');
- const lastSlashIndex = remotePath.lastIndexOf('/');
- let basePath = '';
- let fileName = '';
- let extension = '';
- if (lastSlashIndex >= 0) {
- basePath = remotePath.substring(0, lastSlashIndex + 1);
- fileName = remotePath.substring(lastSlashIndex + 1);
- } else {
- fileName = remotePath;
- }
- if (lastDotIndex > lastSlashIndex) {
- extension = fileName.substring(lastDotIndex);
- fileName = fileName.substring(0, lastDotIndex - lastSlashIndex - 1);
- }
- // 尝试添加序号
- let counter = 1;
- let newPath = '';
- let exists = true;
- while (exists && counter < 100) {
- newPath = `${basePath}${fileName}(${counter})${extension}`;
- exists = await this.checkFileExists(account, newPath);
- counter++;
- }
- if (exists) {
- throw new Error('无法生成唯一文件名');
- }
- return newPath;
- }
- return remotePath;
- }
- // ==================== 安全认证方法 ====================
- // 获取WebDAV认证信息(用于播放器)
- public async getWebDavAuthHeaders(accountId: string): Promise<WebDavAuthInfo | null> {
- const account = await this.getWebDavAccountById(accountId);
- if (!account || !account.account || !account.password) {
- Logger.error(TAG, '无效的WebDAV账户或缺少认证信息');
- return null;
- }
- // 构建基础URL
- const protocol: string = account.enableHttps ? 'https' : 'http';
- const host: string = account.isUseLocalHost && account.localHost ? account.localHost : account.host;
- const port: number = account.port;
- // 构建认证头
- const credentials = buffer
- .from(`${account.account}:${account.password}`)
- .toString("base64");
- const authInfo: WebDavAuthInfo = {
- headers: {
- 'Authorization': `Basic ${credentials}`,
- 'User-Agent': 'TTMusic/1.0'
- },
- url: `${protocol}://${host}:${port}`,
- accountId: accountId
- };
- return authInfo;
- }
- }
- /**
- * 构建HTTP请求头,特别处理WebDAV认证
- * @param currentSong - 当前播放的歌曲信息
- * @param videoUrl - 当前歌曲的URL
- * @param webDavAuthItem - 当前WebDAV认证信息(实例变量)
- * @returns Promise<Map<string, string>> HTTP请求头
- */
- export async function buildHttpHeadersWithWebDav(
- currentSong: VideoItem | undefined,
- videoUrl: string,
- webDavAuthItem: WebDavAuthItem
- ): Promise<Map<string, string>> {
- const headers = new Map<string, string>();
- let isWebDavSong = false;
- if (currentSong) {
- Logger.info(`heanup 当前歌曲信息 - name: ${currentSong.name}, type: ${currentSong.type}, filePath: ${currentSong.filePath}`);
- // 检查是否为WebDAV歌曲
- if (currentSong.type === CommonConstants.TYPE_WEBDAV) {
- isWebDavSong = true;
- // 优先从实例变量获取认证信息
- if (webDavAuthItem) {
- Logger.info(`heanup 从实例变量获取到WebDAV认证信息,账户ID: ${webDavAuthItem.accountId}`);
- } else {
- // 回退到全局上下文
- try {
- const globalContext = GlobalContext.getContext();
- webDavAuthItem = globalContext.getObject('webDavAuthInfo') as WebDavAuthItem;
- if (webDavAuthItem) {
- Logger.info(`heanup 从全局上下文获取到WebDAV认证信息,账户ID: ${webDavAuthItem.accountId}`);
- } else {
- Logger.warn(`heanup 全局上下文中没有WebDAV认证信息`);
- }
- } catch (error) {
- Logger.error(`heanup 获取全局上下文失败:`, error.toString());
- }
- }
- // 如果识别为WebDAV但没有认证信息,记录警告
- if (!webDavAuthItem) {
- Logger.warn(`heanup 识别为WebDAV播放但缺少认证信息,可能需要手动配置WebDAV账户`);
- }
- }
- if (isWebDavSong && webDavAuthItem) {
- Logger.info(`heanup 检测到WebDAV播放,添加安全认证头`);
- Logger.info(`heanup 歌曲URL: ${videoUrl}`);
- try {
- if (webDavAuthItem && webDavAuthItem.accountId) {
- Logger.info(`heanup 找到WebDAV认证信息,账户ID: ${webDavAuthItem.accountId}`);
- // 使用RemoteDriveManager获取认证头
- const webdavManager = RemoteDriveManager.getInstance();
- const authHeaders = await webdavManager.getWebDavAuthHeaders(webDavAuthItem.accountId.toString());
- if (authHeaders) {
- // 添加Basic认证头(使用规范字段名)
- headers.set("Authorization", authHeaders.headers.Authorization);
- } else {
- Logger.error(`heanup 无法获取WebDAV认证头`);
- }
- } else {
- Logger.error(`heanup WebDAV认证信息无效或缺少accountId`);
- }
- } catch (error) {
- Logger.error(`heanup 获取WebDAV认证信息失败:`, error.toString());
- }
- // 添加标准的WebDAV请求头
- headers.set("User-Agent", "TTMusic-WebDAV/1.0");
- headers.set("Accept", "*/*");
- // 请求首段数据,触发服务器返回 206(部分内容)以适配流式播放
- headers.set("Range", "bytes=0-");
- Logger.info(`heanup WebDAV安全认证头设置完成`);
- }
- }
- // 输出所有设置的头部信息用于调试
- console.log(`heanup 设置的HTTP头部信息:`);
- const headerIterator = headers.entries();
- let headerEntry = headerIterator.next();
- while (!headerEntry.done) {
- const key = headerEntry.value[0];
- const value = headerEntry.value[1];
- console.log(`heanup ${key}: ${value}`);
- headerEntry = headerIterator.next();
- }
- return headers;
- }
- /**
- * WebDAV认证信息(LocalMusic专用)
- */
- export interface WebDavAuthItem {
- accountId: number;
- host: string;
- port: number;
- account: string;
- password: string;
- enableHttps: boolean;
- }
|