WebdavManager.ets 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188
  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. import { MusicInfo, parseMusicFileName, Utility } from './Utility';
  18. const TAG = 'heanup WebdavManager';
  19. // WebDAV认证信息接口
  20. export interface WebDavAuthInfo {
  21. headers: Record<string, string>;
  22. url: string;
  23. accountId?: string; // 添加账号ID字段,用于标识认证信息对应的账号
  24. }
  25. // 流媒体认证信息接口
  26. export interface StreamAuthInfo {
  27. url: string;
  28. headers: Record<string, string>;
  29. }
  30. export interface TransferTask {
  31. song: VideoItem;
  32. account: WebDavAccount;
  33. }
  34. @Observed
  35. export class WebdavManager {
  36. public rcpSocket: RcpSocket = RcpSocket.getInstance();
  37. private dataBaseUtil = DataBaseUtil.getInstance();
  38. public observers: Array<(event: string) => void> = [];
  39. public static instance: WebdavManager;
  40. public context: common.Context | undefined;
  41. public DownloadDirectoryFilePath: string = '';
  42. public audioExtensions = Constants.AUDIO_EXTENSIONS;
  43. public lyricExtensions = Constants.LYRIC_EXTENSIONS;
  44. public imageExtensions = Constants.IMAGE_EXTENSIONS;
  45. // 数据表名称
  46. public preferenceName = Constants.WEBDAV_PREFERENCE_NAME;
  47. public webDavTable = 'WebDavAccount';
  48. public receivedSize: number = 0;
  49. public totalSize: number = 0;
  50. public webDavAccounts: WebDavAccount[] = [];
  51. public webDavSongs: VideoItem[] = [];
  52. public webDavFiles: FileInfo[] = []; // 当前目录的所有文件(包括文件夹)
  53. // 路径导航
  54. public currentPath: string = ''; // 当前浏览的路径
  55. public pathHistory: string[] = []; // 路径历史记录
  56. // 错误信息
  57. public ErrorMessage: string | BusinessError = '';
  58. // 下载队列
  59. public downloadQueue: TransferTask[] = [];
  60. public finishDownloadQueue: TransferTask[] = [];
  61. public isProcessingQueue: boolean = false;
  62. public currentDownloadTask: TransferTask | null = null;
  63. public isPauseDownload: boolean = true;
  64. // 上传队列
  65. public uploadQueue: TransferTask[] = [];
  66. public finishUploadQueue: TransferTask[] = [];
  67. public isProcessingUploadQueue: boolean = false;
  68. public currentUploadTask: TransferTask | null = null;
  69. public isPauseUpload: boolean = true;
  70. public currentAccount:WebDavAccount = new WebDavAccount();
  71. public constructor() {
  72. this.rcpSocket.subscribeHTTPDataTransfer((event: string) => {
  73. this.notifyObservers(event);
  74. });
  75. }
  76. public static getInstance(): WebdavManager {
  77. if (!WebdavManager.instance) {
  78. WebdavManager.instance = new WebdavManager();
  79. }
  80. return WebdavManager.instance;
  81. }
  82. public setContext(context: common.Context): void {
  83. this.context = context;
  84. this.DownloadDirectoryFilePath = merge2paths(context.filesDir, 'Download');
  85. }
  86. // ==================== 观察者模式 ====================
  87. public subscribe(callback: (event: string) => void): void {
  88. this.observers.push(callback);
  89. }
  90. public unsubscribe(callback: (event: string) => void): void {
  91. const index = this.observers.indexOf(callback);
  92. if (index > -1) {
  93. this.observers.splice(index, 1);
  94. }
  95. }
  96. public notifyObservers(event: string): void {
  97. Logger.info(TAG, '通知观察者:', event);
  98. Logger.info(TAG, '观察者数量:', this.observers.length.toString());
  99. for (let i = 0; i < this.observers.length; i++) {
  100. const observer = this.observers[i];
  101. Logger.info(TAG, '调用观察者', i.toString(), ',事件:', event);
  102. observer(event);
  103. }
  104. }
  105. // ==================== 数据库操作 ====================
  106. /**
  107. * 根据webdav_account_id查询WebDAV账号信息
  108. * @param accountId WebDAV账号ID
  109. * @returns Promise<WebDavAccount | null> 返回WebDAV账号信息或null
  110. */
  111. public async getWebDavAccountById(accountId: string): Promise<WebDavAccount | null> {
  112. if (!accountId) {
  113. Logger.warn(TAG, 'webdav_account_id为空,无法查询账号信息');
  114. return null;
  115. }
  116. try {
  117. const db = await this.dataBaseUtil.getDB();
  118. const predicates = new relationalStore.RdbPredicates(this.webDavTable);
  119. predicates.equalTo('id', accountId);
  120. const resultSet = await db.query(predicates);
  121. if (resultSet.rowCount > 0) {
  122. resultSet.goToFirstRow();
  123. const account = new WebDavAccount();
  124. account.id = resultSet.getLong(resultSet.getColumnIndex('id'));
  125. account.name = resultSet.getString(resultSet.getColumnIndex('name'));
  126. account.host = resultSet.getString(resultSet.getColumnIndex('host'));
  127. account.localHost = resultSet.getString(resultSet.getColumnIndex('localHost'));
  128. account.isUseLocalHost = resultSet.getLong(resultSet.getColumnIndex('isUseLocalHost')) === 1;
  129. account.port = resultSet.getLong(resultSet.getColumnIndex('port'));
  130. account.filepath = resultSet.getString(resultSet.getColumnIndex('filepath'));
  131. account.imageFilePath = resultSet.getString(resultSet.getColumnIndex('imageFilePath'));
  132. account.lyricFilePath = resultSet.getString(resultSet.getColumnIndex('lyricFilePath'));
  133. account.uploadFilePath = resultSet.getString(resultSet.getColumnIndex('uploadFilePath'));
  134. account.account = resultSet.getString(resultSet.getColumnIndex('account'));
  135. account.password = resultSet.getString(resultSet.getColumnIndex('password'));
  136. account.enableHttps = resultSet.getLong(resultSet.getColumnIndex('enableHttps')) === 1;
  137. account.coverPath = resultSet.getString(resultSet.getColumnIndex('coverPath'));
  138. account.webType = resultSet.getLong(resultSet.getColumnIndex('webType'));
  139. account.isActivate = resultSet.getLong(resultSet.getColumnIndex('isActivate')) === 1;
  140. resultSet.close();
  141. Logger.info(TAG, `成功查询到WebDAV账号: ${account.name}, ID: ${account.id}`);
  142. return account;
  143. } else {
  144. Logger.warn(TAG, `未找到ID为 ${accountId} 的WebDAV账号`);
  145. resultSet.close();
  146. return null;
  147. }
  148. } catch (error) {
  149. const err = error as Error;
  150. Logger.error(TAG, `查询WebDAV账号失败: ${err.message}`);
  151. return null;
  152. }
  153. }
  154. /**
  155. * 根据WebDAV账号构建认证信息
  156. * @param accountId WebDAV账号ID
  157. * @returns Promise<WebDavAuthInfo | null> 返回认证信息或null
  158. */
  159. public async buildAuthInfoByAccountId(accountId: string): Promise<WebDavAuthInfo | null> {
  160. const account = await this.getWebDavAccountById(accountId);
  161. if (!account) {
  162. Logger.warn(TAG, `无法构建认证信息,账号ID ${accountId} 对应的账号不存在`);
  163. return null;
  164. }
  165. try {
  166. // 构建基础URL
  167. const protocol = account.enableHttps ? 'https' : 'http';
  168. const host = account.isUseLocalHost && account.localHost ? account.localHost : account.host;
  169. const port = account.port && account.port !== 80 && account.port !== 443 ? `:${account.port}` : '';
  170. const baseUrl = `${protocol}://${host}${port}`;
  171. // 构建认证头
  172. const headers: Record<string, string> = {};
  173. if (account.account && account.password) {
  174. const credentials = `${account.account}:${account.password}`;
  175. // 简化base64编码实现,避免复杂的类型转换
  176. try {
  177. const bufferObj = buffer.from(credentials, 'utf-8');
  178. const base64Credentials = bufferObj.toString('base64');
  179. headers['Authorization'] = `Basic ${base64Credentials}`;
  180. } catch (error) {
  181. const err = error as Error;
  182. Logger.warn(TAG, `base64编码失败,使用原始凭据: ${err.message}`);
  183. headers['Authorization'] = `Basic ${credentials}`;
  184. }
  185. }
  186. Logger.info(TAG, `成功构建WebDAV认证信息,账号: ${account.name}, URL: ${baseUrl}`);
  187. return {
  188. headers: headers,
  189. url: baseUrl,
  190. accountId: accountId
  191. };
  192. } catch (error) {
  193. const err = error as Error;
  194. Logger.error(TAG, `构建WebDAV认证信息失败: ${err.message}`);
  195. return null;
  196. }
  197. }
  198. /**
  199. * 构建HTTP请求头,通过webdav_account_id查询认证信息
  200. * @param currentSong - 当前播放的歌曲信息
  201. * @param videoUrl - 当前歌曲的URL
  202. * @returns Promise<Map<string, string>> HTTP请求头
  203. */
  204. public async buildHttpHeadersWithAccountId(
  205. currentSong: VideoItem | undefined,
  206. videoUrl: string
  207. ): Promise<Map<string, string>> {
  208. const headers = new Map<string, string>();
  209. if (!currentSong) {
  210. return headers;
  211. }
  212. Logger.info(`heanup 当前歌曲信息 - name: ${currentSong.name}, type: ${currentSong.type}, filePath: ${currentSong.filePath}`);
  213. // 检查是否为WebDAV歌曲
  214. if (currentSong.type === CommonConstants.TYPE_WEBDAV) {
  215. // 优先使用webdav_account_id查询认证信息
  216. if (currentSong.webdav_account_id) {
  217. Logger.info(`heanup 使用webdav_account_id查询认证信息,账号ID: ${currentSong.webdav_account_id}`);
  218. try {
  219. const authInfo = await this.buildAuthInfoByAccountId(currentSong.webdav_account_id);
  220. if (authInfo) {
  221. // 添加WebDAV认证头
  222. Object.keys(authInfo.headers).forEach(key => {
  223. headers.set(key, authInfo.headers[key]);
  224. });
  225. Logger.info(`heanup 成功通过webdav_account_id获取WebDAV认证信息`);
  226. } else {
  227. Logger.warn(`heanup 无法通过webdav_account_id ${currentSong.webdav_account_id} 获取认证信息`);
  228. }
  229. } catch (error) {
  230. const err = error as Error;
  231. Logger.error(`heanup 查询webdav_account_id认证信息时出错: ${err.message}`);
  232. }
  233. } else {
  234. Logger.warn(`heanup WebDAV歌曲缺少webdav_account_id字段,无法查询认证信息`);
  235. }
  236. // 如果没有认证信息,记录警告
  237. if (headers.size === 0) {
  238. Logger.warn(`heanup WebDAV歌曲缺少认证信息,可能需要手动配置WebDAV账户`);
  239. }
  240. }
  241. return headers;
  242. }
  243. /**
  244. * 更新现有WebDAV歌曲的webdav_account_id字段
  245. * 用于修复旧版本数据库中缺少webdav_account_id的记录
  246. * @param accountId WebDAV账号ID
  247. */
  248. public async updateWebDavSongsAccountId(accountId: string): Promise<void> {
  249. try {
  250. const db = await this.dataBaseUtil.getDB();
  251. // 查询所有TYPE_WEBDAV且webdav_account_id为空或null的记录
  252. const querySql = `
  253. SELECT id, filePath FROM mediaTable
  254. WHERE mtype = ${CommonConstants.TYPE_WEBDAV}
  255. AND (webdav_account_id IS NULL OR webdav_account_id = '')
  256. `;
  257. const resultSet = await db.querySql(querySql);
  258. const updateCount = resultSet.rowCount;
  259. if (updateCount > 0) {
  260. Logger.info(TAG, `发现 ${updateCount} 个WebDAV歌曲缺少webdav_account_id,开始更新`);
  261. // 更新这些记录的webdav_account_id
  262. const updateSql = `
  263. UPDATE mediaTable
  264. SET webdav_account_id = ?
  265. WHERE mtype = ${CommonConstants.TYPE_WEBDAV}
  266. AND (webdav_account_id IS NULL OR webdav_account_id = '')
  267. `;
  268. await db.executeSql(updateSql, [accountId]);
  269. Logger.info(TAG, `成功更新 ${updateCount} 个WebDAV歌曲的webdav_account_id为: ${accountId}`);
  270. } else {
  271. Logger.info(TAG, `所有WebDAV歌曲都已有webdav_account_id,无需更新`);
  272. }
  273. resultSet.close();
  274. } catch (error) {
  275. const err = error as Error;
  276. Logger.error(TAG, `更新WebDAV歌曲webdav_account_id失败: ${err.message}`);
  277. }
  278. }
  279. /**
  280. * 修复所有WebDAV歌曲的webdav_account_id字段
  281. * 用于全局修复旧版本数据库中缺少webdav_account_id的记录
  282. * @param accountId WebDAV账号ID(可选,如果不提供则使用当前激活的账号)
  283. */
  284. public async fixAllWebDavSongsAccountId(accountId?: string): Promise<void> {
  285. try {
  286. // 如果没有提供accountId,尝试使用当前激活的账号
  287. if (!accountId) {
  288. const activeAccount = await this.getActiveWebDavAccount();
  289. if (activeAccount && activeAccount.id) {
  290. accountId = activeAccount.id.toString();
  291. } else {
  292. Logger.warn(TAG, `无法找到激活的WebDAV账号来修复歌曲记录`);
  293. return;
  294. }
  295. }
  296. Logger.info(TAG, `开始修复所有WebDAV歌曲的webdav_account_id,使用账号ID: ${accountId}`);
  297. await this.updateWebDavSongsAccountId(accountId);
  298. Logger.info(TAG, `WebDAV歌曲webdav_account_id修复完成`);
  299. } catch (error) {
  300. const err = error as Error;
  301. Logger.error(TAG, `修复WebDAV歌曲webdav_account_id失败: ${err.message}`);
  302. }
  303. }
  304. /**
  305. * 获取当前激活的WebDAV账号
  306. */
  307. private async getActiveWebDavAccount(): Promise<WebDavAccount | null> {
  308. try {
  309. const db = await this.dataBaseUtil.getDB();
  310. const predicates = new relationalStore.RdbPredicates(this.webDavTable);
  311. predicates.equalTo('isActivate', 1);
  312. predicates.limitAs(1);
  313. const resultSet = await db.query(predicates);
  314. if (resultSet.rowCount > 0) {
  315. resultSet.goToFirstRow();
  316. const account = new WebDavAccount();
  317. account.id = resultSet.getLong(resultSet.getColumnIndex('id'));
  318. account.name = resultSet.getString(resultSet.getColumnIndex('name'));
  319. account.host = resultSet.getString(resultSet.getColumnIndex('host'));
  320. account.localHost = resultSet.getString(resultSet.getColumnIndex('localHost'));
  321. account.isUseLocalHost = resultSet.getLong(resultSet.getColumnIndex('isUseLocalHost')) === 1;
  322. account.port = resultSet.getLong(resultSet.getColumnIndex('port'));
  323. account.filepath = resultSet.getString(resultSet.getColumnIndex('filepath'));
  324. account.imageFilePath = resultSet.getString(resultSet.getColumnIndex('imageFilePath'));
  325. account.lyricFilePath = resultSet.getString(resultSet.getColumnIndex('lyricFilePath'));
  326. account.uploadFilePath = resultSet.getString(resultSet.getColumnIndex('uploadFilePath'));
  327. account.account = resultSet.getString(resultSet.getColumnIndex('account'));
  328. account.password = resultSet.getString(resultSet.getColumnIndex('password'));
  329. account.enableHttps = resultSet.getLong(resultSet.getColumnIndex('enableHttps')) === 1;
  330. account.coverPath = resultSet.getString(resultSet.getColumnIndex('coverPath'));
  331. account.webType = resultSet.getLong(resultSet.getColumnIndex('webType'));
  332. account.isActivate = resultSet.getLong(resultSet.getColumnIndex('isActivate')) === 1;
  333. resultSet.close();
  334. return account;
  335. } else {
  336. resultSet.close();
  337. return null;
  338. }
  339. } catch (error) {
  340. const err = error as Error;
  341. Logger.error(TAG, `获取激活的WebDAV账号失败: ${err.message}`);
  342. return null;
  343. }
  344. }
  345. // 创建WebDAV账户表
  346. public createWebDavTableInDB(): Promise<void> {
  347. const createTableSql = `CREATE TABLE IF NOT EXISTS ${this.webDavTable} (
  348. id INTEGER PRIMARY KEY AUTOINCREMENT,
  349. name TEXT,
  350. isActivate INTEGER DEFAULT 1,
  351. host TEXT,
  352. localHost TEXT,
  353. isUseLocalHost INTEGER DEFAULT 0,
  354. port INTEGER,
  355. filepath TEXT,
  356. imageFilePath TEXT,
  357. lyricFilePath TEXT,
  358. uploadFilePath TEXT,
  359. account TEXT,
  360. password TEXT,
  361. enableHttps INTEGER DEFAULT 0,
  362. coverPath TEXT,
  363. webType INTEGER DEFAULT 0
  364. )`;
  365. return this.dataBaseUtil.executeSql(createTableSql)
  366. .then(() => {
  367. Logger.info(TAG, 'WebDAV账户表创建成功');
  368. // 检查并添加新字段(用于数据库升级)
  369. return this.upgradeWebDavTable();
  370. })
  371. .catch((err: Error) => {
  372. Logger.error(TAG, '创建WebDAV账户表失败:', err.message);
  373. throw err;
  374. });
  375. }
  376. // 升级WebDAV表结构
  377. private async upgradeWebDavTable(): Promise<void> {
  378. try {
  379. // 直接尝试添加coverPath字段,如果字段已存在会失败但不影响应用运行
  380. Logger.info(TAG, '检查数据库表结构,尝试添加coverPath字段...');
  381. const addColumnSql = `ALTER TABLE ${this.webDavTable} ADD COLUMN coverPath TEXT`;
  382. await this.dataBaseUtil.executeSql(addColumnSql);
  383. Logger.info(TAG, 'coverPath字段添加成功,数据库升级完成');
  384. } catch (error) {
  385. // 如果添加字段失败(可能字段已存在),记录但不阻止应用启动
  386. Logger.info(TAG, 'coverPath字段可能已存在或添加失败,继续正常运行');
  387. }
  388. try {
  389. // 添加webType字段,用于标识WebDAV账户类型
  390. Logger.info(TAG, '检查数据库表结构,尝试添加webType字段...');
  391. const addWebTypeColumnSql = `ALTER TABLE ${this.webDavTable} ADD COLUMN webType INTEGER DEFAULT 0`;
  392. await this.dataBaseUtil.executeSql(addWebTypeColumnSql);
  393. Logger.info(TAG, 'webType字段添加成功,数据库升级完成');
  394. } catch (error) {
  395. // 如果添加字段失败(可能字段已存在),记录但不阻止应用启动
  396. Logger.info(TAG, 'webType字段可能已存在或添加失败,继续正常运行');
  397. }
  398. }
  399. // 从数据库查询所有账户
  400. public async queryWebDavAccountsFromDB(): Promise<void> {
  401. try {
  402. // 确保表结构是最新的
  403. await this.upgradeWebDavTable();
  404. const predicates = new relationalStore.RdbPredicates(this.webDavTable);
  405. // 先查询基础字段(确保这些字段在旧版本中存在)
  406. const baseColumns = ['id', 'name', 'isActivate', 'host', 'localHost', 'isUseLocalHost',
  407. 'port', 'filepath', 'imageFilePath', 'lyricFilePath', 'uploadFilePath',
  408. 'account', 'password', 'enableHttps'];
  409. const resultSet = await this.dataBaseUtil.queryData(this.webDavTable, baseColumns, predicates);
  410. this.webDavAccounts = [];
  411. while (resultSet.goToNextRow()) {
  412. const account = new WebDavAccount();
  413. account.id = resultSet.getLong(resultSet.getColumnIndex('id'));
  414. account.name = resultSet.getString(resultSet.getColumnIndex('name'));
  415. account.isActivate = resultSet.getLong(resultSet.getColumnIndex('isActivate')) === 1;
  416. account.host = resultSet.getString(resultSet.getColumnIndex('host'));
  417. account.localHost = resultSet.getString(resultSet.getColumnIndex('localHost'));
  418. account.isUseLocalHost = resultSet.getLong(resultSet.getColumnIndex('isUseLocalHost')) === 1;
  419. account.port = resultSet.getLong(resultSet.getColumnIndex('port'));
  420. account.filepath = resultSet.getString(resultSet.getColumnIndex('filepath'));
  421. account.imageFilePath = resultSet.getString(resultSet.getColumnIndex('imageFilePath'));
  422. account.lyricFilePath = resultSet.getString(resultSet.getColumnIndex('lyricFilePath'));
  423. account.uploadFilePath = resultSet.getString(resultSet.getColumnIndex('uploadFilePath'));
  424. account.account = resultSet.getString(resultSet.getColumnIndex('account'));
  425. account.password = resultSet.getString(resultSet.getColumnIndex('password'));
  426. account.enableHttps = resultSet.getLong(resultSet.getColumnIndex('enableHttps')) === 1;
  427. // 设置coverPath和webType为默认值undefined,稍后会尝试更新
  428. account.coverPath = undefined;
  429. account.webType = 0;
  430. this.webDavAccounts.push(account);
  431. }
  432. resultSet.close();
  433. // 尝试查询coverPath字段(如果升级成功)
  434. try {
  435. const coverPathResultSet = await this.dataBaseUtil.queryData(this.webDavTable, ['id', 'coverPath'], predicates);
  436. if (coverPathResultSet.goToFirstRow()) {
  437. // 创建一个映射来存储coverPath
  438. const coverPathMap = new Map<number, string>();
  439. do {
  440. const accountId = coverPathResultSet.getLong(coverPathResultSet.getColumnIndex('id'));
  441. const coverPathIndex = coverPathResultSet.getColumnIndex('coverPath');
  442. const coverPath = coverPathIndex >= 0 ? coverPathResultSet.getString(coverPathIndex) : undefined;
  443. if (coverPath) {
  444. coverPathMap.set(accountId, coverPath);
  445. }
  446. } while (coverPathResultSet.goToNextRow());
  447. // 将coverPath值赋给对应的账户
  448. for (const account of this.webDavAccounts) {
  449. if (coverPathMap.has(account.id)) {
  450. account.coverPath = coverPathMap.get(account.id);
  451. }
  452. }
  453. }
  454. coverPathResultSet.close();
  455. } catch (error) {
  456. // 如果查询coverPath失败,说明字段可能不存在,忽略错误
  457. Logger.info(TAG, 'coverPath字段不存在或查询失败,使用默认值');
  458. }
  459. Logger.info(TAG, '从数据库加载了', this.webDavAccounts.length.toString(), '个WebDAV账户');
  460. this.notifyObservers(WebdavManagerStates.QueryAccountsSucceed);
  461. } catch (err) {
  462. const error = err as Error;
  463. Logger.error(TAG, '查询WebDAV账户失败:', error.message);
  464. this.notifyObservers(WebdavManagerStates.QueryAccountsFailed);
  465. throw error;
  466. }
  467. }
  468. // 插入新账户
  469. public async insertAccount(
  470. name: string,
  471. host: string,
  472. localHost: string,
  473. isUseLocalHost: boolean,
  474. port: number,
  475. filepath: string,
  476. lyricFilePath: string,
  477. uploadFilePath: string,
  478. imageFilePath: string,
  479. account: string,
  480. password: string,
  481. enableHttps: boolean,
  482. coverPath?: string,
  483. webType: number = 0
  484. ): Promise<void> {
  485. try {
  486. const values: relationalStore.ValuesBucket = {
  487. 'name': name,
  488. 'isActivate': 1,
  489. 'host': host,
  490. 'localHost': localHost,
  491. 'isUseLocalHost': isUseLocalHost ? 1 : 0,
  492. 'port': port,
  493. 'filepath': filepath,
  494. 'imageFilePath': imageFilePath,
  495. 'lyricFilePath': lyricFilePath,
  496. 'uploadFilePath': uploadFilePath,
  497. 'account': account,
  498. 'password': password,
  499. 'enableHttps': enableHttps ? 1 : 0,
  500. 'coverPath': coverPath || null,
  501. 'webType': webType
  502. };
  503. await this.dataBaseUtil.insertData(this.webDavTable, values);
  504. Logger.info(TAG, '插入WebDAV账户成功:', name);
  505. await this.queryWebDavAccountsFromDB();
  506. this.notifyObservers(WebdavManagerStates.InsertAccountSucceed);
  507. } catch (err) {
  508. const error = err as Error;
  509. Logger.error(TAG, '插入WebDAV账户失败:', error.message);
  510. this.notifyObservers(WebdavManagerStates.InsertAccountFailed);
  511. throw error;
  512. }
  513. }
  514. // 编辑账户
  515. public async editAccount(account: WebDavAccount): Promise<void> {
  516. try {
  517. const values: relationalStore.ValuesBucket = {
  518. 'name': account.name,
  519. 'isActivate': account.isActivate ? 1 : 0,
  520. 'host': account.host,
  521. 'localHost': account.localHost,
  522. 'isUseLocalHost': account.isUseLocalHost ? 1 : 0,
  523. 'port': account.port,
  524. 'filepath': account.filepath,
  525. 'imageFilePath': account.imageFilePath,
  526. 'lyricFilePath': account.lyricFilePath,
  527. 'uploadFilePath': account.uploadFilePath,
  528. 'account': account.account,
  529. 'password': account.password,
  530. 'enableHttps': account.enableHttps ? 1 : 0,
  531. 'coverPath': account.coverPath || null,
  532. 'webType': account.webType
  533. };
  534. const predicates = new relationalStore.RdbPredicates(this.webDavTable);
  535. predicates.equalTo('id', account.id);
  536. await this.dataBaseUtil.updateData(this.webDavTable, values, predicates);
  537. Logger.info(TAG, '更新WebDAV账户成功:', account.name);
  538. await this.queryWebDavAccountsFromDB();
  539. this.notifyObservers(WebdavManagerStates.EditAccountSucceed);
  540. } catch (err) {
  541. const error = err as Error;
  542. Logger.error(TAG, '更新WebDAV账户失败:', error.message);
  543. this.notifyObservers(WebdavManagerStates.EditAccountFailed);
  544. throw error;
  545. }
  546. }
  547. // 删除账户
  548. public async removeAccount(account: WebDavAccount): Promise<void> {
  549. try {
  550. const predicates = new relationalStore.RdbPredicates(this.webDavTable);
  551. predicates.equalTo('id', account.id);
  552. await this.dataBaseUtil.deleteData(predicates);
  553. Logger.info(TAG, '删除WebDAV账户成功:', account.name);
  554. await this.queryWebDavAccountsFromDB();
  555. this.notifyObservers(WebdavManagerStates.RemoveAccountSucceed);
  556. } catch (err) {
  557. const error = err as Error;
  558. Logger.error(TAG, '删除WebDAV账户失败:', error.message);
  559. this.notifyObservers(WebdavManagerStates.RemoveAccountFailed);
  560. throw error;
  561. }
  562. }
  563. // 获取所有账户
  564. public getAllWebDavAccounts(): WebDavAccount[] {
  565. return this.webDavAccounts;
  566. }
  567. // 获取激活的账户
  568. public getActivatedWebDavAccount(): WebDavAccount | null {
  569. if(this.currentAccount)
  570. return this.currentAccount;
  571. for (let i = 0; i < this.webDavAccounts.length; i++) {
  572. const account = this.webDavAccounts[i];
  573. if (account.isActivate) {
  574. return account;
  575. }
  576. }
  577. return null;
  578. }
  579. // ==================== 文件操作 ====================
  580. // 从WebDAV加载文件列表
  581. public async loadFilesInfoFromWebdav(customPath?: string): Promise<void> {
  582. const account = this.getActivatedWebDavAccount();
  583. if (!account) {
  584. Logger.error(TAG, '没有激活的WebDAV账户');
  585. this.notifyObservers(WebdavManagerStates.LoadFilesInfoFailed);
  586. return;
  587. }
  588. try {
  589. this.notifyObservers(WebdavManagerStates.LoadFilesInfoStart);
  590. // 使用自定义路径或账户默认路径
  591. const path = customPath !== undefined ? customPath : account.filepath;
  592. this.currentPath = path;
  593. const files = await this.rcpSocket.getFileList(
  594. account.host,
  595. account.localHost,
  596. account.isUseLocalHost,
  597. account.port,
  598. path,
  599. account.account,
  600. account.password,
  601. account.enableHttps
  602. );
  603. // 保存所有文件(包括文件夹)
  604. // 直接使用从RcpSocketUtil返回的FileInfo对象
  605. this.webDavFiles = [];
  606. for (let i = 0; i < files.length; i++) {
  607. const file = files[i];
  608. // 直接添加原始文件对象
  609. this.webDavFiles.push(file);
  610. }
  611. // 调试:输出获取到的文件总数
  612. Logger.info(TAG, '从WebDAV获取到 ' + files.length + ' 个文件/文件夹');
  613. // 分别统计文件夹和音频文件
  614. let folderCount = 0;
  615. let audioCount = 0;
  616. // 过滤音频文件
  617. this.webDavSongs = [];
  618. for (let i = 0; i < files.length; i++) {
  619. const file = files[i];
  620. const fileName = file.fileName;
  621. if (file.isDirectory) {
  622. folderCount++;
  623. } else if (this.isAudioFile(fileName)) {
  624. audioCount++;
  625. const song = this.fileInfoToVideoItem(file, account);
  626. this.webDavSongs.push(song);
  627. }
  628. }
  629. this.notifyObservers(WebdavManagerStates.LoadFilesInfoSucceed);
  630. } catch (error) {
  631. this.ErrorMessage = error as BusinessError;
  632. this.notifyObservers(WebdavManagerStates.LoadFilesInfoFailed);
  633. }
  634. }
  635. public async loadFilesInfoFromAccount(account: WebDavAccount,customPath?: string): Promise<void> {
  636. this.currentAccount = account;
  637. // 更新现有WebDAV歌曲的webdav_account_id字段
  638. if (account && account.id) {
  639. await this.updateWebDavSongsAccountId(account.id.toString());
  640. }
  641. try {
  642. this.notifyObservers(WebdavManagerStates.LoadFilesInfoStart);
  643. // 使用自定义路径或账户默认路径
  644. const path = customPath !== undefined ? customPath : account.filepath;
  645. this.currentPath = path;
  646. const files = await this.rcpSocket.getFileList(
  647. account.host,
  648. account.localHost,
  649. account.isUseLocalHost,
  650. account.port,
  651. path,
  652. account.account,
  653. account.password,
  654. account.enableHttps
  655. );
  656. // 保存所有文件(包括文件夹)
  657. // 直接使用从RcpSocketUtil返回的FileInfo对象
  658. this.webDavFiles = [];
  659. for (let i = 0; i < files.length; i++) {
  660. const file = files[i];
  661. // 直接添加原始文件对象
  662. this.webDavFiles.push(file);
  663. }
  664. // 调试:输出获取到的文件总数
  665. Logger.info(TAG, '从WebDAV获取到 ' + files.length + ' 个文件/文件夹');
  666. // 分别统计文件夹和音频文件
  667. let folderCount = 0;
  668. let audioCount = 0;
  669. // 过滤音频文件
  670. this.webDavSongs = [];
  671. for (let i = 0; i < files.length; i++) {
  672. const file = files[i];
  673. const fileName = file.fileName;
  674. if (file.isDirectory) {
  675. folderCount++;
  676. } else if (this.isAudioFile(fileName)) {
  677. audioCount++;
  678. const song = this.fileInfoToVideoItem(file, account);
  679. this.webDavSongs.push(song);
  680. }
  681. }
  682. this.notifyObservers(WebdavManagerStates.LoadFilesInfoSucceed);
  683. } catch (error) {
  684. this.ErrorMessage = error as BusinessError;
  685. this.notifyObservers(WebdavManagerStates.LoadFilesInfoFailed);
  686. }
  687. }
  688. // 将FileInfo转换为VideoItem
  689. private fileInfoToVideoItem(fileInfo: FileInfo, account: WebDavAccount): VideoItem {
  690. // 构建安全的WebDAV URL(不包含认证信息)
  691. const protocol = account.enableHttps ? 'https' : 'http';
  692. const host = account.isUseLocalHost ? account.localHost : account.host;
  693. const port = account.port;
  694. // 构建基础URL,确保路径重新编码(目录/文件名中的中文与空格)
  695. const encodedHref = encodeURI(fileInfo.href); // 仅编码非保留字符,已编码的百分号不重复编码
  696. const absoluteUrl = `${protocol}://${host}:${port}${encodedHref}`;
  697. // 创建VideoItem对象
  698. // 构造函数签名: (name, id, filePath, type, videoSize, cTime, pixelMap?, size?, pixelMapPath?, artist?, album?, fileName?, lastPlayed?)
  699. const videoItem = new VideoItem(
  700. this.getFileNameWithoutExtension(fileInfo.fileName), // name: 歌曲名
  701. '', // id: 空字符串,WebDAV文件无本地ID
  702. absoluteUrl, // filePath: 绝对路径
  703. CommonConstants.TYPE_WEBDAV, // type: WebDAV类型
  704. fileInfo.contentLength, // videoSize: 文件大小
  705. Utility.getFormatDateStr(fileInfo.time,'yyyy-MM-dd HH:mm'), // cTime: 修改时间
  706. undefined, // pixelMap
  707. undefined, // size
  708. undefined, // pixelMapPath: 对于WebDAV歌曲不设置图片路径
  709. Constants.UNKNOWN_ARTIST, // artist: 艺术家
  710. undefined, // album: 专辑
  711. fileInfo.fileName // fileName: 真实文件名
  712. );
  713. videoItem.size = Utility.formatFSize(fileInfo.contentLength)
  714. //根据文件名解析艺术家
  715. const musicData:MusicInfo = parseMusicFileName(fileInfo.fileName);
  716. if (musicData.isValid) {
  717. console.log('onecold parseMusicFileName artist:', musicData.artist)
  718. videoItem.artist = musicData.artist
  719. videoItem.name = musicData.title
  720. }
  721. // 设置WebDAV账号ID,用于后续认证信息查询
  722. if (account && account.id) {
  723. videoItem.webdav_account_id = account.id.toString();
  724. }
  725. // 计算并保存相对路径
  726. try {
  727. const relMatch = absoluteUrl.match(/^https?:\/\/[^\/]+(?::\d+)?(\/.*)$/i);
  728. if (relMatch && relMatch[1]) {
  729. videoItem.remote_rel_path = relMatch[1];
  730. }
  731. } catch (e) {
  732. Logger.warn(TAG, '计算相对路径失败: ' + (e as Error).message);
  733. }
  734. return videoItem;
  735. }
  736. // 判断是否为音频文件
  737. private isAudioFile(fileName: string): boolean {
  738. const ext = this.getFileExtension(fileName).toLowerCase();
  739. for (let i = 0; i < this.audioExtensions.length; i++) {
  740. if (ext === this.audioExtensions[i]) {
  741. return true;
  742. }
  743. }
  744. return false;
  745. }
  746. // 获取文件扩展名
  747. private getFileExtension(fileName: string): string {
  748. const lastDotIndex = fileName.lastIndexOf('.');
  749. if (lastDotIndex === -1) {
  750. return '';
  751. }
  752. return fileName.substring(lastDotIndex);
  753. }
  754. // 获取不带扩展名的文件名
  755. private getFileNameWithoutExtension(fileName: string): string {
  756. const lastDotIndex = fileName.lastIndexOf('.');
  757. if (lastDotIndex === -1) {
  758. return fileName;
  759. }
  760. return fileName.substring(0, lastDotIndex);
  761. }
  762. // 进入文件夹
  763. public async enterFolder(folder: FileInfo): Promise<void> {
  764. if (!folder.isDirectory) {
  765. Logger.error(TAG, '不是文件夹,无法进入');
  766. return;
  767. }
  768. Logger.info(TAG, '准备进入文件夹:', folder.fileName);
  769. Logger.info(TAG, '当前路径:', this.currentPath);
  770. Logger.info(TAG, '目标路径:', folder.href);
  771. // 保存当前路径到历史记录
  772. this.pathHistory.push(this.currentPath);
  773. Logger.info(TAG, '路径历史:', JSON.stringify(this.pathHistory));
  774. // 加载文件夹内容
  775. await this.loadFilesInfoFromWebdav(folder.href);
  776. }
  777. public async enterFolderFromPath(path: string): Promise<void> {
  778. Logger.info(TAG, '当前路径:', this.currentPath);
  779. Logger.info(TAG, '目标路径:', path);
  780. // 保存当前路径到历史记录
  781. this.pathHistory.push(this.currentPath);
  782. Logger.info(TAG, '路径历史:', JSON.stringify(this.pathHistory));
  783. // 加载文件夹内容
  784. await this.loadFilesInfoFromWebdav(path);
  785. }
  786. // 在 WebdavManager 类中添加以下方法
  787. navigateToBreadcrumb(breadcrumbIndex: number): Promise<string> {
  788. return new Promise((resolve, reject) => {
  789. try {
  790. // 面包屑索引0是"根目录"
  791. if (breadcrumbIndex === 0) {
  792. resolve('/');
  793. return;
  794. }
  795. // 根据当前路径构建目标路径
  796. const pathParts = this.currentPath.split('/').filter(part => part !== '');
  797. // 验证索引有效性
  798. if (breadcrumbIndex > pathParts.length) {
  799. reject(new Error('Invalid breadcrumb index'));
  800. return;
  801. }
  802. // 构建目标路径
  803. let targetPath = '/';
  804. for (let i = 0; i < breadcrumbIndex; i++) {
  805. targetPath += pathParts[i] + '/';
  806. }
  807. resolve(targetPath);
  808. } catch (error) {
  809. reject(error);
  810. }
  811. });
  812. }
  813. // 返回上级目录
  814. public async goBack(): Promise<void> {
  815. if (this.pathHistory.length === 0) {
  816. Logger.info(TAG, '已经在根目录,无法返回');
  817. return;
  818. }
  819. // 从历史记录中取出上一级路径
  820. const previousPath = this.pathHistory.pop();
  821. if (previousPath !== undefined) {
  822. await this.loadFilesInfoFromWebdav(previousPath);
  823. }
  824. }
  825. // 获取面包屑路径数组
  826. public getBreadcrumbs(): string[] {
  827. if (!this.currentPath || this.currentPath === '/') {
  828. return ['根目录'];
  829. }
  830. const parts = this.currentPath.split('/').filter(part => part !== '');
  831. const breadcrumbs = ['根目录'];
  832. for (let i = 0; i < parts.length; i++) {
  833. breadcrumbs.push(parts[i]);
  834. }
  835. return breadcrumbs;
  836. }
  837. // 是否可以返回上级
  838. public canGoBack(): boolean {
  839. if(this.currentPath==='/')
  840. return false
  841. return this.pathHistory.length > 0;
  842. }
  843. // ==================== Preferences操作 ====================
  844. // 加载历史数据(从Preferences迁移)
  845. public async loadInfo(): Promise<void> {
  846. try {
  847. // 这里可以添加从Preferences加载历史配置的逻辑
  848. Logger.info(TAG, '从Preferences加载配置');
  849. } catch (error) {
  850. Logger.error(TAG, '从Preferences加载配置失败:', error.toString());
  851. }
  852. }
  853. // 保存配置到Preferences
  854. public async saveInfo(): Promise<void> {
  855. try {
  856. // 这里可以添加保存配置到Preferences的逻辑
  857. Logger.info(TAG, '保存配置到Preferences');
  858. } catch (error) {
  859. Logger.error(TAG, '保存配置到Preferences失败:', error.toString());
  860. }
  861. }
  862. // ==================== 下载队列管理 ====================
  863. // 添加到下载队列
  864. public addToDownloadQueue(song: VideoItem, account: WebDavAccount): void {
  865. const task: TransferTask = { song, account };
  866. this.downloadQueue.push(task);
  867. Logger.info(TAG, '添加到下载队列:', song.name);
  868. this.notifyObservers(WebdavManagerStates.DownloadQueueChanged);
  869. }
  870. // 从下载队列移除
  871. public removeFromDownloadQueue(index: number): void {
  872. if (index >= 0 && index < this.downloadQueue.length) {
  873. const task = this.downloadQueue[index];
  874. this.downloadQueue.splice(index, 1);
  875. Logger.info(TAG, '从下载队列移除:', task.song.name);
  876. this.notifyObservers(WebdavManagerStates.DownloadQueueChanged);
  877. }
  878. }
  879. // 清空下载队列
  880. public clearDownloadQueue(): void {
  881. this.downloadQueue = [];
  882. Logger.info(TAG, '清空下载队列');
  883. this.notifyObservers(WebdavManagerStates.DownloadQueueChanged);
  884. }
  885. // ==================== 上传队列管理 ====================
  886. // 添加到上传队列
  887. public addToUploadQueue(song: VideoItem, account: WebDavAccount): void {
  888. const task: TransferTask = { song, account };
  889. this.uploadQueue.push(task);
  890. Logger.info(TAG, '添加到上传队列:', song.name);
  891. this.notifyObservers(WebdavManagerStates.UploadQueueChanged);
  892. }
  893. // 从上传队列移除
  894. public removeFromUploadQueue(index: number): void {
  895. if (index >= 0 && index < this.uploadQueue.length) {
  896. const task = this.uploadQueue[index];
  897. this.uploadQueue.splice(index, 1);
  898. Logger.info(TAG, '从上传队列移除:', task.song.name);
  899. this.notifyObservers(WebdavManagerStates.UploadQueueChanged);
  900. }
  901. }
  902. // 清空上传队列
  903. public clearUploadQueue(): void {
  904. this.uploadQueue = [];
  905. Logger.info(TAG, '清空上传队列');
  906. this.notifyObservers(WebdavManagerStates.UploadQueueChanged);
  907. }
  908. // ==================== 安全认证方法 ====================
  909. // 获取WebDAV认证信息(用于播放器)
  910. public async getWebDavAuthHeaders(accountId: string): Promise<WebDavAuthInfo | null> {
  911. const account = await this.getWebDavAccountById(accountId);
  912. if (!account || !account.account || !account.password) {
  913. Logger.error(TAG, '无效的WebDAV账户或缺少认证信息');
  914. return null;
  915. }
  916. // 构建基础URL
  917. const protocol: string = account.enableHttps ? 'https' : 'http';
  918. const host: string = account.isUseLocalHost && account.localHost ? account.localHost : account.host;
  919. const port: number = account.port;
  920. // 构建认证头
  921. const credentials = buffer
  922. .from(`${account.account}:${account.password}`)
  923. .toString("base64");
  924. const authInfo: WebDavAuthInfo = {
  925. headers: {
  926. 'Authorization': `Basic ${credentials}`,
  927. 'User-Agent': 'TTMusic/1.0'
  928. },
  929. url: `${protocol}://${host}:${port}`,
  930. accountId: accountId
  931. };
  932. return authInfo;
  933. }
  934. }
  935. /**
  936. * 构建HTTP请求头,特别处理WebDAV认证
  937. * @param currentSong - 当前播放的歌曲信息
  938. * @param videoUrl - 当前歌曲的URL
  939. * @param webDavAuthItem - 当前WebDAV认证信息(实例变量)
  940. * @returns Promise<Map<string, string>> HTTP请求头
  941. */
  942. export async function buildHttpHeadersWithWebDav(
  943. currentSong: VideoItem | undefined,
  944. videoUrl: string,
  945. webDavAuthItem: WebDavAuthItem
  946. ): Promise<Map<string, string>> {
  947. const headers = new Map<string, string>();
  948. let isWebDavSong = false;
  949. if (currentSong) {
  950. Logger.info(`heanup 当前歌曲信息 - name: ${currentSong.name}, type: ${currentSong.type}, filePath: ${currentSong.filePath}`);
  951. // 检查是否为WebDAV歌曲
  952. if (currentSong.type === CommonConstants.TYPE_WEBDAV) {
  953. isWebDavSong = true;
  954. // 优先从实例变量获取认证信息
  955. if (webDavAuthItem) {
  956. Logger.info(`heanup 从实例变量获取到WebDAV认证信息,账户ID: ${webDavAuthItem.accountId}`);
  957. } else {
  958. // 回退到全局上下文
  959. try {
  960. const globalContext = GlobalContext.getContext();
  961. webDavAuthItem = globalContext.getObject('webDavAuthInfo') as WebDavAuthItem;
  962. if (webDavAuthItem) {
  963. Logger.info(`heanup 从全局上下文获取到WebDAV认证信息,账户ID: ${webDavAuthItem.accountId}`);
  964. } else {
  965. Logger.warn(`heanup 全局上下文中没有WebDAV认证信息`);
  966. }
  967. } catch (error) {
  968. Logger.error(`heanup 获取全局上下文失败:`, error.toString());
  969. }
  970. }
  971. // 如果识别为WebDAV但没有认证信息,记录警告
  972. if (!webDavAuthItem) {
  973. Logger.warn(`heanup 识别为WebDAV播放但缺少认证信息,可能需要手动配置WebDAV账户`);
  974. }
  975. }
  976. if (isWebDavSong && webDavAuthItem) {
  977. Logger.info(`heanup 检测到WebDAV播放,添加安全认证头`);
  978. Logger.info(`heanup 歌曲URL: ${videoUrl}`);
  979. try {
  980. if (webDavAuthItem && webDavAuthItem.accountId) {
  981. Logger.info(`heanup 找到WebDAV认证信息,账户ID: ${webDavAuthItem.accountId}`);
  982. // 使用WebdavManager获取认证头
  983. const webdavManager = WebdavManager.getInstance();
  984. const authHeaders = await webdavManager.getWebDavAuthHeaders(webDavAuthItem.accountId.toString());
  985. if (authHeaders) {
  986. // 添加Basic认证头(使用规范字段名)
  987. headers.set("Authorization", authHeaders.headers.Authorization);
  988. } else {
  989. Logger.error(`heanup 无法获取WebDAV认证头`);
  990. }
  991. } else {
  992. Logger.error(`heanup WebDAV认证信息无效或缺少accountId`);
  993. }
  994. } catch (error) {
  995. Logger.error(`heanup 获取WebDAV认证信息失败:`, error.toString());
  996. }
  997. // 添加标准的WebDAV请求头
  998. headers.set("User-Agent", "TTMusic-WebDAV/1.0");
  999. headers.set("Accept", "*/*");
  1000. // 请求首段数据,触发服务器返回 206(部分内容)以适配流式播放
  1001. headers.set("Range", "bytes=0-");
  1002. Logger.info(`heanup WebDAV安全认证头设置完成`);
  1003. }
  1004. }
  1005. // 输出所有设置的头部信息用于调试
  1006. console.log(`heanup 设置的HTTP头部信息:`);
  1007. const headerIterator = headers.entries();
  1008. let headerEntry = headerIterator.next();
  1009. while (!headerEntry.done) {
  1010. const key = headerEntry.value[0];
  1011. const value = headerEntry.value[1];
  1012. console.log(`heanup ${key}: ${value}`);
  1013. headerEntry = headerIterator.next();
  1014. }
  1015. return headers;
  1016. }
  1017. /**
  1018. * WebDAV认证信息(LocalMusic专用)
  1019. */
  1020. export interface WebDavAuthItem {
  1021. accountId: number;
  1022. host: string;
  1023. port: number;
  1024. account: string;
  1025. password: string;
  1026. enableHttps: boolean;
  1027. }