WebdavManager.ets 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880
  1. // WebdavManager - WebDAV管理器(简化版)
  2. import { VideoItem } from '../../viewmodel/VideoItem';
  3. import { common } from '@kit.AbilityKit';
  4. import { FileInfo } from '../../viewmodel/FileInfo';
  5. import FileManager, { merge2paths } from './FileManager';
  6. import { BusinessError } from '@kit.BasicServicesKit';
  7. import { WebdavManagerStates } from '../enums/WebdavManagerStates';
  8. import { RcpSocket } from './RcpSocketUtil';
  9. import { DataBaseUtil } from './DataBaseUtil';
  10. import { WebDavAccount } from '../../viewmodel/WebDavAccount';
  11. import { relationalStore } from '@kit.ArkData';
  12. import { Constants } from '../../Constants';
  13. import Logger from './Logger';
  14. import { buffer } from '@kit.ArkTS';
  15. import { CommonConstants } from '../constants/CommonConstants';
  16. import { GlobalContext } from '@pura/harmony-utils';
  17. const TAG = 'heanup WebdavManager';
  18. // WebDAV认证信息接口
  19. export interface WebDavAuthInfo {
  20. headers: Record<string, string>;
  21. url: string;
  22. }
  23. // 流媒体认证信息接口
  24. export interface StreamAuthInfo {
  25. url: string;
  26. headers: Record<string, string>;
  27. }
  28. export interface TransferTask {
  29. song: VideoItem;
  30. account: WebDavAccount;
  31. }
  32. @Observed
  33. export class WebdavManager {
  34. public rcpSocket: RcpSocket = RcpSocket.getInstance();
  35. private dataBaseUtil = DataBaseUtil.getInstance();
  36. public observers: Array<(event: string) => void> = [];
  37. public static instance: WebdavManager;
  38. public context: common.Context | undefined;
  39. public DownloadDirectoryFilePath: string = '';
  40. public audioExtensions = Constants.AUDIO_EXTENSIONS;
  41. public lyricExtensions = Constants.LYRIC_EXTENSIONS;
  42. public imageExtensions = Constants.IMAGE_EXTENSIONS;
  43. // 数据表名称
  44. public preferenceName = Constants.WEBDAV_PREFERENCE_NAME;
  45. public webDavTable = 'WebDavAccount';
  46. public receivedSize: number = 0;
  47. public totalSize: number = 0;
  48. public webDavAccounts: WebDavAccount[] = [];
  49. public webDavSongs: VideoItem[] = [];
  50. public webDavFiles: FileInfo[] = []; // 当前目录的所有文件(包括文件夹)
  51. // 路径导航
  52. public currentPath: string = ''; // 当前浏览的路径
  53. public pathHistory: string[] = []; // 路径历史记录
  54. // 错误信息
  55. public ErrorMessage: string | BusinessError = '';
  56. // 下载队列
  57. public downloadQueue: TransferTask[] = [];
  58. public finishDownloadQueue: TransferTask[] = [];
  59. public isProcessingQueue: boolean = false;
  60. public currentDownloadTask: TransferTask | null = null;
  61. public isPauseDownload: boolean = true;
  62. // 上传队列
  63. public uploadQueue: TransferTask[] = [];
  64. public finishUploadQueue: TransferTask[] = [];
  65. public isProcessingUploadQueue: boolean = false;
  66. public currentUploadTask: TransferTask | null = null;
  67. public isPauseUpload: boolean = true;
  68. public currentAccount:WebDavAccount = new WebDavAccount();
  69. public constructor() {
  70. this.rcpSocket.subscribeHTTPDataTransfer((event: string) => {
  71. this.notifyObservers(event);
  72. });
  73. }
  74. public static getInstance(): WebdavManager {
  75. if (!WebdavManager.instance) {
  76. WebdavManager.instance = new WebdavManager();
  77. }
  78. return WebdavManager.instance;
  79. }
  80. public setContext(context: common.Context): void {
  81. this.context = context;
  82. this.DownloadDirectoryFilePath = merge2paths(context.filesDir, 'Download');
  83. }
  84. // ==================== 观察者模式 ====================
  85. public subscribe(callback: (event: string) => void): void {
  86. this.observers.push(callback);
  87. }
  88. public unsubscribe(callback: (event: string) => void): void {
  89. const index = this.observers.indexOf(callback);
  90. if (index > -1) {
  91. this.observers.splice(index, 1);
  92. }
  93. }
  94. public notifyObservers(event: string): void {
  95. Logger.info(TAG, '通知观察者:', event);
  96. Logger.info(TAG, '观察者数量:', this.observers.length.toString());
  97. for (let i = 0; i < this.observers.length; i++) {
  98. const observer = this.observers[i];
  99. Logger.info(TAG, '调用观察者', i.toString(), ',事件:', event);
  100. observer(event);
  101. }
  102. }
  103. // ==================== 数据库操作 ====================
  104. // 创建WebDAV账户表
  105. public createWebDavTableInDB(): Promise<void> {
  106. const createTableSql = `CREATE TABLE IF NOT EXISTS ${this.webDavTable} (
  107. id INTEGER PRIMARY KEY AUTOINCREMENT,
  108. name TEXT,
  109. isActivate INTEGER DEFAULT 1,
  110. host TEXT,
  111. localHost TEXT,
  112. isUseLocalHost INTEGER DEFAULT 0,
  113. port INTEGER,
  114. filepath TEXT,
  115. imageFilePath TEXT,
  116. lyricFilePath TEXT,
  117. uploadFilePath TEXT,
  118. account TEXT,
  119. password TEXT,
  120. enableHttps INTEGER DEFAULT 0,
  121. coverPath TEXT
  122. )`;
  123. return this.dataBaseUtil.executeSql(createTableSql)
  124. .then(() => {
  125. Logger.info(TAG, 'WebDAV账户表创建成功');
  126. // 检查并添加新字段(用于数据库升级)
  127. return this.upgradeWebDavTable();
  128. })
  129. .catch((err: Error) => {
  130. Logger.error(TAG, '创建WebDAV账户表失败:', err.message);
  131. throw err;
  132. });
  133. }
  134. // 升级WebDAV表结构
  135. private async upgradeWebDavTable(): Promise<void> {
  136. try {
  137. // 直接尝试添加coverPath字段,如果字段已存在会失败但不影响应用运行
  138. Logger.info(TAG, '检查数据库表结构,尝试添加coverPath字段...');
  139. const addColumnSql = `ALTER TABLE ${this.webDavTable} ADD COLUMN coverPath TEXT`;
  140. await this.dataBaseUtil.executeSql(addColumnSql);
  141. Logger.info(TAG, 'coverPath字段添加成功,数据库升级完成');
  142. } catch (error) {
  143. // 如果添加字段失败(可能字段已存在),记录但不阻止应用启动
  144. Logger.info(TAG, 'coverPath字段可能已存在或添加失败,继续正常运行');
  145. }
  146. }
  147. // 从数据库查询所有账户
  148. public async queryWebDavAccountsFromDB(): Promise<void> {
  149. try {
  150. // 确保表结构是最新的
  151. await this.upgradeWebDavTable();
  152. const predicates = new relationalStore.RdbPredicates(this.webDavTable);
  153. // 先查询基础字段(确保这些字段在旧版本中存在)
  154. const baseColumns = ['id', 'name', 'isActivate', 'host', 'localHost', 'isUseLocalHost',
  155. 'port', 'filepath', 'imageFilePath', 'lyricFilePath', 'uploadFilePath',
  156. 'account', 'password', 'enableHttps'];
  157. const resultSet = await this.dataBaseUtil.queryData(this.webDavTable, baseColumns, predicates);
  158. this.webDavAccounts = [];
  159. while (resultSet.goToNextRow()) {
  160. const account = new WebDavAccount();
  161. account.id = resultSet.getLong(resultSet.getColumnIndex('id'));
  162. account.name = resultSet.getString(resultSet.getColumnIndex('name'));
  163. account.isActivate = resultSet.getLong(resultSet.getColumnIndex('isActivate')) === 1;
  164. account.host = resultSet.getString(resultSet.getColumnIndex('host'));
  165. account.localHost = resultSet.getString(resultSet.getColumnIndex('localHost'));
  166. account.isUseLocalHost = resultSet.getLong(resultSet.getColumnIndex('isUseLocalHost')) === 1;
  167. account.port = resultSet.getLong(resultSet.getColumnIndex('port'));
  168. account.filepath = resultSet.getString(resultSet.getColumnIndex('filepath'));
  169. account.imageFilePath = resultSet.getString(resultSet.getColumnIndex('imageFilePath'));
  170. account.lyricFilePath = resultSet.getString(resultSet.getColumnIndex('lyricFilePath'));
  171. account.uploadFilePath = resultSet.getString(resultSet.getColumnIndex('uploadFilePath'));
  172. account.account = resultSet.getString(resultSet.getColumnIndex('account'));
  173. account.password = resultSet.getString(resultSet.getColumnIndex('password'));
  174. account.enableHttps = resultSet.getLong(resultSet.getColumnIndex('enableHttps')) === 1;
  175. // 设置coverPath为默认值undefined,稍后会尝试更新
  176. account.coverPath = undefined;
  177. this.webDavAccounts.push(account);
  178. }
  179. resultSet.close();
  180. // 尝试查询coverPath字段(如果升级成功)
  181. try {
  182. const coverPathResultSet = await this.dataBaseUtil.queryData(this.webDavTable, ['id', 'coverPath'], predicates);
  183. if (coverPathResultSet.goToFirstRow()) {
  184. // 创建一个映射来存储coverPath
  185. const coverPathMap = new Map<number, string>();
  186. do {
  187. const accountId = coverPathResultSet.getLong(coverPathResultSet.getColumnIndex('id'));
  188. const coverPathIndex = coverPathResultSet.getColumnIndex('coverPath');
  189. const coverPath = coverPathIndex >= 0 ? coverPathResultSet.getString(coverPathIndex) : undefined;
  190. if (coverPath) {
  191. coverPathMap.set(accountId, coverPath);
  192. }
  193. } while (coverPathResultSet.goToNextRow());
  194. // 将coverPath值赋给对应的账户
  195. for (const account of this.webDavAccounts) {
  196. if (coverPathMap.has(account.id)) {
  197. account.coverPath = coverPathMap.get(account.id);
  198. }
  199. }
  200. }
  201. coverPathResultSet.close();
  202. } catch (error) {
  203. // 如果查询coverPath失败,说明字段可能不存在,忽略错误
  204. Logger.info(TAG, 'coverPath字段不存在或查询失败,使用默认值');
  205. }
  206. Logger.info(TAG, '从数据库加载了', this.webDavAccounts.length.toString(), '个WebDAV账户');
  207. this.notifyObservers(WebdavManagerStates.QueryAccountsSucceed);
  208. } catch (err) {
  209. const error = err as Error;
  210. Logger.error(TAG, '查询WebDAV账户失败:', error.message);
  211. this.notifyObservers(WebdavManagerStates.QueryAccountsFailed);
  212. throw error;
  213. }
  214. }
  215. // 插入新账户
  216. public async insertAccount(
  217. name: string,
  218. host: string,
  219. localHost: string,
  220. isUseLocalHost: boolean,
  221. port: number,
  222. filepath: string,
  223. lyricFilePath: string,
  224. uploadFilePath: string,
  225. imageFilePath: string,
  226. account: string,
  227. password: string,
  228. enableHttps: boolean,
  229. coverPath?: string
  230. ): Promise<void> {
  231. try {
  232. const values: relationalStore.ValuesBucket = {
  233. 'name': name,
  234. 'isActivate': 1,
  235. 'host': host,
  236. 'localHost': localHost,
  237. 'isUseLocalHost': isUseLocalHost ? 1 : 0,
  238. 'port': port,
  239. 'filepath': filepath,
  240. 'imageFilePath': imageFilePath,
  241. 'lyricFilePath': lyricFilePath,
  242. 'uploadFilePath': uploadFilePath,
  243. 'account': account,
  244. 'password': password,
  245. 'enableHttps': enableHttps ? 1 : 0,
  246. 'coverPath': coverPath || null
  247. };
  248. await this.dataBaseUtil.insertData(this.webDavTable, values);
  249. Logger.info(TAG, '插入WebDAV账户成功:', name);
  250. await this.queryWebDavAccountsFromDB();
  251. this.notifyObservers(WebdavManagerStates.InsertAccountSucceed);
  252. } catch (err) {
  253. const error = err as Error;
  254. Logger.error(TAG, '插入WebDAV账户失败:', error.message);
  255. this.notifyObservers(WebdavManagerStates.InsertAccountFailed);
  256. throw error;
  257. }
  258. }
  259. // 编辑账户
  260. public async editAccount(account: WebDavAccount): Promise<void> {
  261. try {
  262. const values: relationalStore.ValuesBucket = {
  263. 'name': account.name,
  264. 'isActivate': account.isActivate ? 1 : 0,
  265. 'host': account.host,
  266. 'localHost': account.localHost,
  267. 'isUseLocalHost': account.isUseLocalHost ? 1 : 0,
  268. 'port': account.port,
  269. 'filepath': account.filepath,
  270. 'imageFilePath': account.imageFilePath,
  271. 'lyricFilePath': account.lyricFilePath,
  272. 'uploadFilePath': account.uploadFilePath,
  273. 'account': account.account,
  274. 'password': account.password,
  275. 'enableHttps': account.enableHttps ? 1 : 0,
  276. 'coverPath': account.coverPath || null
  277. };
  278. const predicates = new relationalStore.RdbPredicates(this.webDavTable);
  279. predicates.equalTo('id', account.id);
  280. await this.dataBaseUtil.updateData(this.webDavTable, values, predicates);
  281. Logger.info(TAG, '更新WebDAV账户成功:', account.name);
  282. await this.queryWebDavAccountsFromDB();
  283. this.notifyObservers(WebdavManagerStates.EditAccountSucceed);
  284. } catch (err) {
  285. const error = err as Error;
  286. Logger.error(TAG, '更新WebDAV账户失败:', error.message);
  287. this.notifyObservers(WebdavManagerStates.EditAccountFailed);
  288. throw error;
  289. }
  290. }
  291. // 删除账户
  292. public async removeAccount(account: WebDavAccount): Promise<void> {
  293. try {
  294. const predicates = new relationalStore.RdbPredicates(this.webDavTable);
  295. predicates.equalTo('id', account.id);
  296. await this.dataBaseUtil.deleteData(predicates);
  297. Logger.info(TAG, '删除WebDAV账户成功:', account.name);
  298. await this.queryWebDavAccountsFromDB();
  299. this.notifyObservers(WebdavManagerStates.RemoveAccountSucceed);
  300. } catch (err) {
  301. const error = err as Error;
  302. Logger.error(TAG, '删除WebDAV账户失败:', error.message);
  303. this.notifyObservers(WebdavManagerStates.RemoveAccountFailed);
  304. throw error;
  305. }
  306. }
  307. // 获取所有账户
  308. public getAllWebDavAccounts(): WebDavAccount[] {
  309. return this.webDavAccounts;
  310. }
  311. // 获取激活的账户
  312. public getActivatedWebDavAccount(): WebDavAccount | null {
  313. if(this.currentAccount)
  314. return this.currentAccount;
  315. for (let i = 0; i < this.webDavAccounts.length; i++) {
  316. const account = this.webDavAccounts[i];
  317. if (account.isActivate) {
  318. return account;
  319. }
  320. }
  321. return null;
  322. }
  323. // ==================== 文件操作 ====================
  324. // 从WebDAV加载文件列表
  325. public async loadFilesInfoFromWebdav(customPath?: string): Promise<void> {
  326. const account = this.getActivatedWebDavAccount();
  327. if (!account) {
  328. Logger.error(TAG, '没有激活的WebDAV账户');
  329. this.notifyObservers(WebdavManagerStates.LoadFilesInfoFailed);
  330. return;
  331. }
  332. try {
  333. this.notifyObservers(WebdavManagerStates.LoadFilesInfoStart);
  334. // 使用自定义路径或账户默认路径
  335. const path = customPath !== undefined ? customPath : account.filepath;
  336. this.currentPath = path;
  337. const files = await this.rcpSocket.getFileList(
  338. account.host,
  339. account.localHost,
  340. account.isUseLocalHost,
  341. account.port,
  342. path,
  343. account.account,
  344. account.password,
  345. account.enableHttps
  346. );
  347. // 保存所有文件(包括文件夹)
  348. // 直接使用从RcpSocketUtil返回的FileInfo对象
  349. this.webDavFiles = [];
  350. for (let i = 0; i < files.length; i++) {
  351. const file = files[i];
  352. // 直接添加原始文件对象
  353. this.webDavFiles.push(file);
  354. }
  355. // 调试:输出获取到的文件总数
  356. Logger.info(TAG, '从WebDAV获取到 ' + files.length + ' 个文件/文件夹');
  357. // 分别统计文件夹和音频文件
  358. let folderCount = 0;
  359. let audioCount = 0;
  360. // 过滤音频文件
  361. this.webDavSongs = [];
  362. for (let i = 0; i < files.length; i++) {
  363. const file = files[i];
  364. const fileName = file.fileName;
  365. if (file.isDirectory) {
  366. folderCount++;
  367. } else if (this.isAudioFile(fileName)) {
  368. audioCount++;
  369. const song = this.fileInfoToVideoItem(file, account);
  370. this.webDavSongs.push(song);
  371. }
  372. }
  373. this.notifyObservers(WebdavManagerStates.LoadFilesInfoSucceed);
  374. } catch (error) {
  375. this.ErrorMessage = error as BusinessError;
  376. this.notifyObservers(WebdavManagerStates.LoadFilesInfoFailed);
  377. }
  378. }
  379. public async loadFilesInfoFromAccount(account: WebDavAccount,customPath?: string): Promise<void> {
  380. this.currentAccount = account;
  381. try {
  382. this.notifyObservers(WebdavManagerStates.LoadFilesInfoStart);
  383. // 使用自定义路径或账户默认路径
  384. const path = customPath !== undefined ? customPath : account.filepath;
  385. this.currentPath = path;
  386. const files = await this.rcpSocket.getFileList(
  387. account.host,
  388. account.localHost,
  389. account.isUseLocalHost,
  390. account.port,
  391. path,
  392. account.account,
  393. account.password,
  394. account.enableHttps
  395. );
  396. // 保存所有文件(包括文件夹)
  397. // 直接使用从RcpSocketUtil返回的FileInfo对象
  398. this.webDavFiles = [];
  399. for (let i = 0; i < files.length; i++) {
  400. const file = files[i];
  401. // 直接添加原始文件对象
  402. this.webDavFiles.push(file);
  403. }
  404. // 调试:输出获取到的文件总数
  405. Logger.info(TAG, '从WebDAV获取到 ' + files.length + ' 个文件/文件夹');
  406. // 分别统计文件夹和音频文件
  407. let folderCount = 0;
  408. let audioCount = 0;
  409. // 过滤音频文件
  410. this.webDavSongs = [];
  411. for (let i = 0; i < files.length; i++) {
  412. const file = files[i];
  413. const fileName = file.fileName;
  414. if (file.isDirectory) {
  415. folderCount++;
  416. } else if (this.isAudioFile(fileName)) {
  417. audioCount++;
  418. const song = this.fileInfoToVideoItem(file, account);
  419. this.webDavSongs.push(song);
  420. }
  421. }
  422. this.notifyObservers(WebdavManagerStates.LoadFilesInfoSucceed);
  423. } catch (error) {
  424. this.ErrorMessage = error as BusinessError;
  425. this.notifyObservers(WebdavManagerStates.LoadFilesInfoFailed);
  426. }
  427. }
  428. // 将FileInfo转换为VideoItem
  429. private fileInfoToVideoItem(fileInfo: FileInfo, account: WebDavAccount): VideoItem {
  430. // 构建安全的WebDAV URL(不包含认证信息)
  431. const protocol = account.enableHttps ? 'https' : 'http';
  432. const host = account.isUseLocalHost ? account.localHost : account.host;
  433. const port = account.port;
  434. // 构建基础URL,不包含认证信息
  435. const filePath = `${protocol}://${host}:${port}${fileInfo.href}`;
  436. // 创建VideoItem对象
  437. // 构造函数签名: (name, id, filePath, type, videoSize, cTime, pixelMap?, size?, pixelMapPath?, artist?, album?, fileName?, lastPlayed?)
  438. const videoItem = new VideoItem(
  439. this.getFileNameWithoutExtension(fileInfo.fileName), // name: 歌曲名
  440. '', // id: 空字符串,WebDAV文件无本地ID
  441. filePath, // filePath: 文件路径
  442. CommonConstants.TYPE_WEBDAV, // type: WebDAV类型
  443. fileInfo.contentLength, // videoSize: 文件大小
  444. fileInfo.time.toString(), // cTime: 修改时间
  445. undefined, // pixelMap
  446. undefined, // size
  447. undefined, // pixelMapPath: 对于WebDAV歌曲不设置图片路径
  448. Constants.UNKNOWN_ARTIST, // artist: 艺术家
  449. undefined, // album: 专辑
  450. fileInfo.fileName // fileName: 真实文件名
  451. );
  452. return videoItem;
  453. }
  454. // 判断是否为音频文件
  455. private isAudioFile(fileName: string): boolean {
  456. const ext = this.getFileExtension(fileName).toLowerCase();
  457. for (let i = 0; i < this.audioExtensions.length; i++) {
  458. if (ext === this.audioExtensions[i]) {
  459. return true;
  460. }
  461. }
  462. return false;
  463. }
  464. // 获取文件扩展名
  465. private getFileExtension(fileName: string): string {
  466. const lastDotIndex = fileName.lastIndexOf('.');
  467. if (lastDotIndex === -1) {
  468. return '';
  469. }
  470. return fileName.substring(lastDotIndex);
  471. }
  472. // 获取不带扩展名的文件名
  473. private getFileNameWithoutExtension(fileName: string): string {
  474. const lastDotIndex = fileName.lastIndexOf('.');
  475. if (lastDotIndex === -1) {
  476. return fileName;
  477. }
  478. return fileName.substring(0, lastDotIndex);
  479. }
  480. // 进入文件夹
  481. public async enterFolder(folder: FileInfo): Promise<void> {
  482. if (!folder.isDirectory) {
  483. Logger.error(TAG, '不是文件夹,无法进入');
  484. return;
  485. }
  486. Logger.info(TAG, '准备进入文件夹:', folder.fileName);
  487. Logger.info(TAG, '当前路径:', this.currentPath);
  488. Logger.info(TAG, '目标路径:', folder.href);
  489. // 保存当前路径到历史记录
  490. this.pathHistory.push(this.currentPath);
  491. Logger.info(TAG, '路径历史:', JSON.stringify(this.pathHistory));
  492. // 加载文件夹内容
  493. await this.loadFilesInfoFromWebdav(folder.href);
  494. }
  495. public async enterFolderFromPath(path: string): Promise<void> {
  496. Logger.info(TAG, '当前路径:', this.currentPath);
  497. Logger.info(TAG, '目标路径:', path);
  498. // 保存当前路径到历史记录
  499. this.pathHistory.push(this.currentPath);
  500. Logger.info(TAG, '路径历史:', JSON.stringify(this.pathHistory));
  501. // 加载文件夹内容
  502. await this.loadFilesInfoFromWebdav(path);
  503. }
  504. // 在 WebdavManager 类中添加以下方法
  505. navigateToBreadcrumb(breadcrumbIndex: number): Promise<string> {
  506. return new Promise((resolve, reject) => {
  507. try {
  508. // 面包屑索引0是"根目录"
  509. if (breadcrumbIndex === 0) {
  510. resolve('/');
  511. return;
  512. }
  513. // 根据当前路径构建目标路径
  514. const pathParts = this.currentPath.split('/').filter(part => part !== '');
  515. // 验证索引有效性
  516. if (breadcrumbIndex > pathParts.length) {
  517. reject(new Error('Invalid breadcrumb index'));
  518. return;
  519. }
  520. // 构建目标路径
  521. let targetPath = '/';
  522. for (let i = 0; i < breadcrumbIndex; i++) {
  523. targetPath += pathParts[i] + '/';
  524. }
  525. resolve(targetPath);
  526. } catch (error) {
  527. reject(error);
  528. }
  529. });
  530. }
  531. // 返回上级目录
  532. public async goBack(): Promise<void> {
  533. if (this.pathHistory.length === 0) {
  534. Logger.info(TAG, '已经在根目录,无法返回');
  535. return;
  536. }
  537. // 从历史记录中取出上一级路径
  538. const previousPath = this.pathHistory.pop();
  539. if (previousPath !== undefined) {
  540. await this.loadFilesInfoFromWebdav(previousPath);
  541. }
  542. }
  543. // 获取面包屑路径数组
  544. public getBreadcrumbs(): string[] {
  545. if (!this.currentPath || this.currentPath === '/') {
  546. return ['根目录'];
  547. }
  548. const parts = this.currentPath.split('/').filter(part => part !== '');
  549. const breadcrumbs = ['根目录'];
  550. for (let i = 0; i < parts.length; i++) {
  551. breadcrumbs.push(parts[i]);
  552. }
  553. return breadcrumbs;
  554. }
  555. // 是否可以返回上级
  556. public canGoBack(): boolean {
  557. return this.pathHistory.length > 0;
  558. }
  559. // ==================== Preferences操作 ====================
  560. // 加载历史数据(从Preferences迁移)
  561. public async loadInfo(): Promise<void> {
  562. try {
  563. // 这里可以添加从Preferences加载历史配置的逻辑
  564. Logger.info(TAG, '从Preferences加载配置');
  565. } catch (error) {
  566. Logger.error(TAG, '从Preferences加载配置失败:', error.toString());
  567. }
  568. }
  569. // 保存配置到Preferences
  570. public async saveInfo(): Promise<void> {
  571. try {
  572. // 这里可以添加保存配置到Preferences的逻辑
  573. Logger.info(TAG, '保存配置到Preferences');
  574. } catch (error) {
  575. Logger.error(TAG, '保存配置到Preferences失败:', error.toString());
  576. }
  577. }
  578. // ==================== 下载队列管理 ====================
  579. // 添加到下载队列
  580. public addToDownloadQueue(song: VideoItem, account: WebDavAccount): void {
  581. const task: TransferTask = { song, account };
  582. this.downloadQueue.push(task);
  583. Logger.info(TAG, '添加到下载队列:', song.name);
  584. this.notifyObservers(WebdavManagerStates.DownloadQueueChanged);
  585. }
  586. // 从下载队列移除
  587. public removeFromDownloadQueue(index: number): void {
  588. if (index >= 0 && index < this.downloadQueue.length) {
  589. const task = this.downloadQueue[index];
  590. this.downloadQueue.splice(index, 1);
  591. Logger.info(TAG, '从下载队列移除:', task.song.name);
  592. this.notifyObservers(WebdavManagerStates.DownloadQueueChanged);
  593. }
  594. }
  595. // 清空下载队列
  596. public clearDownloadQueue(): void {
  597. this.downloadQueue = [];
  598. Logger.info(TAG, '清空下载队列');
  599. this.notifyObservers(WebdavManagerStates.DownloadQueueChanged);
  600. }
  601. // ==================== 上传队列管理 ====================
  602. // 添加到上传队列
  603. public addToUploadQueue(song: VideoItem, account: WebDavAccount): void {
  604. const task: TransferTask = { song, account };
  605. this.uploadQueue.push(task);
  606. Logger.info(TAG, '添加到上传队列:', song.name);
  607. this.notifyObservers(WebdavManagerStates.UploadQueueChanged);
  608. }
  609. // 从上传队列移除
  610. public removeFromUploadQueue(index: number): void {
  611. if (index >= 0 && index < this.uploadQueue.length) {
  612. const task = this.uploadQueue[index];
  613. this.uploadQueue.splice(index, 1);
  614. Logger.info(TAG, '从上传队列移除:', task.song.name);
  615. this.notifyObservers(WebdavManagerStates.UploadQueueChanged);
  616. }
  617. }
  618. // 清空上传队列
  619. public clearUploadQueue(): void {
  620. this.uploadQueue = [];
  621. Logger.info(TAG, '清空上传队列');
  622. this.notifyObservers(WebdavManagerStates.UploadQueueChanged);
  623. }
  624. // ==================== 安全认证方法 ====================
  625. // 获取WebDAV认证信息(用于播放器)
  626. public getWebDavAuthHeaders(accountId: number): WebDavAuthInfo | null {
  627. const account = this.getWebDavAccountById(accountId);
  628. if (!account || !account.account || !account.password) {
  629. Logger.error(TAG, '无效的WebDAV账户或缺少认证信息');
  630. return null;
  631. }
  632. // 构建基础URL
  633. const protocol = account.enableHttps ? 'https' : 'http';
  634. const host = account.isUseLocalHost ? account.localHost : account.host;
  635. const port = account.port;
  636. // 构建认证头
  637. const credentials = buffer
  638. .from(`${account.account}:${account.password}`)
  639. .toString("base64");
  640. const authInfo: WebDavAuthInfo = {
  641. headers: {
  642. 'Authorization': `Basic ${credentials}`,
  643. 'User-Agent': 'TTMusic/1.0'
  644. },
  645. url: `${protocol}://${host}:${port}`
  646. };
  647. return authInfo;
  648. }
  649. // 根据ID获取WebDAV账户
  650. private getWebDavAccountById(accountId: number): WebDavAccount | null {
  651. for (let i = 0; i < this.webDavAccounts.length; i++) {
  652. const account = this.webDavAccounts[i];
  653. if (account.id === accountId) {
  654. return account;
  655. }
  656. }
  657. return null;
  658. }
  659. }
  660. /**
  661. * 构建HTTP请求头,特别处理WebDAV认证
  662. * @param currentSong - 当前播放的歌曲信息
  663. * @param videoUrl - 当前歌曲的URL
  664. * @param webDavAuthItem - 当前WebDAV认证信息(实例变量)
  665. * @returns Map<string, string> HTTP请求头
  666. */
  667. export function buildHttpHeadersWithWebDav(
  668. currentSong: VideoItem | undefined,
  669. videoUrl: string,
  670. webDavAuthItem: WebDavAuthItem
  671. ): Map<string, string> {
  672. const headers = new Map<string, string>();
  673. let isWebDavSong = false;
  674. if (currentSong) {
  675. Logger.info(`heanup 当前歌曲信息 - name: ${currentSong.name}, type: ${currentSong.type}, filePath: ${currentSong.filePath}`);
  676. // 检查是否为WebDAV歌曲
  677. if (currentSong.type === CommonConstants.TYPE_WEBDAV) {
  678. isWebDavSong = true;
  679. // 优先从实例变量获取认证信息
  680. if (webDavAuthItem) {
  681. Logger.info(`heanup 从实例变量获取到WebDAV认证信息,账户ID: ${webDavAuthItem.accountId}`);
  682. } else {
  683. // 回退到全局上下文
  684. try {
  685. const globalContext = GlobalContext.getContext();
  686. webDavAuthItem = globalContext.getObject('webDavAuthInfo') as WebDavAuthItem;
  687. if (webDavAuthItem) {
  688. Logger.info(`heanup 从全局上下文获取到WebDAV认证信息,账户ID: ${webDavAuthItem.accountId}`);
  689. } else {
  690. Logger.warn(`heanup 全局上下文中没有WebDAV认证信息`);
  691. }
  692. } catch (error) {
  693. Logger.error(`heanup 获取全局上下文失败:`, error.toString());
  694. }
  695. }
  696. // 如果识别为WebDAV但没有认证信息,记录警告
  697. if (!webDavAuthItem) {
  698. Logger.warn(`heanup 识别为WebDAV播放但缺少认证信息,可能需要手动配置WebDAV账户`);
  699. }
  700. }
  701. if (isWebDavSong && webDavAuthItem) {
  702. Logger.info(`heanup 检测到WebDAV播放,添加安全认证头`);
  703. Logger.info(`heanup 歌曲URL: ${videoUrl}`);
  704. try {
  705. if (webDavAuthItem && webDavAuthItem.accountId) {
  706. Logger.info(`heanup 找到WebDAV认证信息,账户ID: ${webDavAuthItem.accountId}`);
  707. // 使用WebdavManager获取认证头
  708. const webdavManager = WebdavManager.getInstance();
  709. const authHeaders = webdavManager.getWebDavAuthHeaders(webDavAuthItem.accountId);
  710. if (authHeaders) {
  711. // 添加Basic认证头
  712. headers.set("authorization", authHeaders.headers.Authorization);
  713. } else {
  714. Logger.error(`heanup 无法获取WebDAV认证头`);
  715. }
  716. } else {
  717. Logger.error(`heanup WebDAV认证信息无效或缺少accountId`);
  718. }
  719. } catch (error) {
  720. Logger.error(`heanup 获取WebDAV认证信息失败:`, error.toString());
  721. }
  722. // 添加标准的WebDAV请求头
  723. headers.set("user_agent", "TTMusic-WebDAV/1.0");
  724. headers.set("accept", "*/*");
  725. headers.set("accept-range", "bytes");
  726. Logger.info(`heanup WebDAV安全认证头设置完成`);
  727. }
  728. }
  729. // 输出所有设置的头部信息用于调试
  730. console.log(`heanup 设置的HTTP头部信息:`);
  731. const headerIterator = headers.entries();
  732. let headerEntry = headerIterator.next();
  733. while (!headerEntry.done) {
  734. const key = headerEntry.value[0];
  735. const value = headerEntry.value[1];
  736. console.log(`heanup ${key}: ${value}`);
  737. headerEntry = headerIterator.next();
  738. }
  739. return headers;
  740. }
  741. /**
  742. * WebDAV认证信息(LocalMusic专用)
  743. */
  744. export interface WebDavAuthItem {
  745. accountId: number;
  746. host: string;
  747. port: number;
  748. account: string;
  749. password: string;
  750. enableHttps: boolean;
  751. }