| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614 |
- // WebdavManager - WebDAV管理器(简化版)
- import { Song } from '../../viewmodel/Song';
- import { common } from '@kit.AbilityKit';
- import { FileInfo } from '../../viewmodel/FileInfo';
- import FileManager, { merge2paths } from './FileManager';
- import { BusinessError } from '@kit.BasicServicesKit';
- import { WebdavManagerStates } from '../enums/WebdavManagerStates';
- import { SongType } from '../enums/SongType';
- 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';
- const TAG = 'heanup WebdavManager';
- // WebDAV认证信息接口
- export interface WebDavAuthInfo {
- headers: Record<string, string>;
- url: string;
- }
- // 流媒体认证信息接口
- export interface StreamAuthInfo {
- url: string;
- headers: Record<string, string>;
- }
- export interface TransferTask {
- song: Song;
- account: WebDavAccount;
- }
- @Observed
- export class WebdavManager {
- public rcpSocket: RcpSocket = RcpSocket.getInstance();
- private dataBaseUtil = DataBaseUtil.getInstance();
- public observers: Array<(event: string) => void> = [];
- public static instance: WebdavManager;
- 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: Song[] = [];
- public webDavFiles: FileInfo[] = []; // 当前目录的所有文件(包括文件夹)
- // 路径导航
- 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 constructor() {
- this.rcpSocket.subscribeHTTPDataTransfer((event: string) => {
- this.notifyObservers(event);
- });
- }
- public static getInstance(): WebdavManager {
- if (!WebdavManager.instance) {
- WebdavManager.instance = new WebdavManager();
- }
- return WebdavManager.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账户表
- public createWebDavTableInDB(): Promise<void> {
- const sql = `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
- )`;
- return this.dataBaseUtil.executeSql(sql)
- .then(() => {
- Logger.info(TAG, 'WebDAV账户表创建成功');
- })
- .catch((err: Error) => {
- Logger.error(TAG, '创建WebDAV账户表失败:', err.message);
- throw err;
- });
- }
- // 从数据库查询所有账户
- public async queryWebDavAccountsFromDB(): Promise<void> {
- try {
- const predicates = new relationalStore.RdbPredicates(this.webDavTable);
- const columns = ['id', 'name', 'isActivate', 'host', 'localHost', 'isUseLocalHost',
- 'port', 'filepath', 'imageFilePath', 'lyricFilePath', 'uploadFilePath',
- 'account', 'password', 'enableHttps'];
- const resultSet = await this.dataBaseUtil.queryData(this.webDavTable, columns, 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;
- this.webDavAccounts.push(account);
- }
- resultSet.close();
- Logger.info(TAG, '从数据库加载了', this.webDavAccounts.length.toString(), '个WebDAV账户');
- this.notifyObservers(WebdavManagerStates.QueryAccountsSucceed);
- } catch (err) {
- const error = err as Error;
- Logger.error(TAG, '查询WebDAV账户失败:', error.message);
- this.notifyObservers(WebdavManagerStates.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
- ): 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
- };
- await this.dataBaseUtil.insertData(this.webDavTable, values);
- Logger.info(TAG, '插入WebDAV账户成功:', name);
- await this.queryWebDavAccountsFromDB();
- this.notifyObservers(WebdavManagerStates.InsertAccountSucceed);
- } catch (err) {
- const error = err as Error;
- Logger.error(TAG, '插入WebDAV账户失败:', error.message);
- this.notifyObservers(WebdavManagerStates.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
- };
- 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(WebdavManagerStates.EditAccountSucceed);
- } catch (err) {
- const error = err as Error;
- Logger.error(TAG, '更新WebDAV账户失败:', error.message);
- this.notifyObservers(WebdavManagerStates.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(WebdavManagerStates.RemoveAccountSucceed);
- } catch (err) {
- const error = err as Error;
- Logger.error(TAG, '删除WebDAV账户失败:', error.message);
- this.notifyObservers(WebdavManagerStates.RemoveAccountFailed);
- throw error;
- }
- }
- // 获取所有账户
- public getAllWebDavAccounts(): WebDavAccount[] {
- return this.webDavAccounts;
- }
- // 获取激活的账户
- public getActivatedWebDavAccount(): WebDavAccount | null {
- 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 = this.getActivatedWebDavAccount();
- if (!account) {
- Logger.error(TAG, '没有激活的WebDAV账户');
- this.notifyObservers(WebdavManagerStates.LoadFilesInfoFailed);
- return;
- }
- try {
- this.notifyObservers(WebdavManagerStates.LoadFilesInfoStart);
- // 使用自定义路径或账户默认路径
- const path = customPath !== undefined ? customPath : account.filepath;
- this.currentPath = path;
- const files = await this.rcpSocket.getFileList(
- account.host,
- account.localHost,
- account.isUseLocalHost,
- account.port,
- path,
- account.account,
- account.password,
- account.enableHttps
- );
- // 保存所有文件(包括文件夹)
- // 直接使用从RcpSocketUtil返回的FileInfo对象
- this.webDavFiles = [];
- for (let i = 0; i < files.length; i++) {
- const file = files[i];
- // 直接添加原始文件对象
- this.webDavFiles.push(file);
- }
- // 调试:输出获取到的文件总数
- Logger.info(TAG, '从WebDAV获取到 ' + files.length + ' 个文件/文件夹');
- // 分别统计文件夹和音频文件
- let folderCount = 0;
- let audioCount = 0;
- // 过滤音频文件
- this.webDavSongs = [];
- for (let i = 0; i < files.length; i++) {
- const file = files[i];
- const fileName = file.fileName;
- if (file.isDirectory) {
- folderCount++;
- } else if (this.isAudioFile(fileName)) {
- audioCount++;
- const song = this.fileInfoToSong(file, account);
- this.webDavSongs.push(song);
- }
- }
- this.notifyObservers(WebdavManagerStates.LoadFilesInfoSucceed);
- } catch (error) {
- this.ErrorMessage = error as BusinessError;
- this.notifyObservers(WebdavManagerStates.LoadFilesInfoFailed);
- }
- }
- // 将FileInfo转换为Song
- private fileInfoToSong(fileInfo: FileInfo, account: WebDavAccount): Song {
- const song = new Song(-1, '');
- song.title = this.getFileNameWithoutExtension(fileInfo.fileName);
- song.artist = Constants.UNKNOWN_ARTIST;
- song.name = fileInfo.fileName;
- // 构建安全的WebDAV URL(不包含认证信息)
- const protocol = account.enableHttps ? 'https' : 'http';
- const host = account.isUseLocalHost ? account.localHost : account.host;
- const port = account.port;
- // 构建基础URL,不包含认证信息
- song.src = `${protocol}://${host}:${port}${fileInfo.href}`;
- song.songType = SongType.WebDav;
- song.webDavAccountId = account.id;
- song.webFilePath = fileInfo.href;
- song.fileSize = fileInfo.contentLength;
- song.time = fileInfo.time;
- song.img = Constants.COMMON_SONG_DEFAULT_IMAGE;
- return song;
- }
- // 判断是否为音频文件
- 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.pathHistory.push(this.currentPath);
- Logger.info(TAG, '路径历史:', JSON.stringify(this.pathHistory));
- // 加载文件夹内容
- await this.loadFilesInfoFromWebdav(folder.href);
- }
- // 返回上级目录
- public async goBack(): Promise<void> {
- if (this.pathHistory.length === 0) {
- Logger.info(TAG, '已经在根目录,无法返回');
- return;
- }
- // 从历史记录中取出上一级路径
- const previousPath = this.pathHistory.pop();
- if (previousPath !== undefined) {
- await this.loadFilesInfoFromWebdav(previousPath);
- }
- }
- // 获取面包屑路径数组
- public getBreadcrumbs(): string[] {
- if (!this.currentPath || this.currentPath === '/') {
- return ['根目录'];
- }
- const parts = this.currentPath.split('/').filter(part => part !== '');
- const breadcrumbs = ['根目录'];
- for (let i = 0; i < parts.length; i++) {
- breadcrumbs.push(parts[i]);
- }
- return breadcrumbs;
- }
- // 是否可以返回上级
- public canGoBack(): boolean {
- 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: Song, account: WebDavAccount): void {
- const task: TransferTask = { song, account };
- this.downloadQueue.push(task);
- Logger.info(TAG, '添加到下载队列:', song.title);
- this.notifyObservers(WebdavManagerStates.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.title);
- this.notifyObservers(WebdavManagerStates.DownloadQueueChanged);
- }
- }
- // 清空下载队列
- public clearDownloadQueue(): void {
- this.downloadQueue = [];
- Logger.info(TAG, '清空下载队列');
- this.notifyObservers(WebdavManagerStates.DownloadQueueChanged);
- }
- // ==================== 上传队列管理 ====================
- // 添加到上传队列
- public addToUploadQueue(song: Song, account: WebDavAccount): void {
- const task: TransferTask = { song, account };
- this.uploadQueue.push(task);
- Logger.info(TAG, '添加到上传队列:', song.title);
- this.notifyObservers(WebdavManagerStates.UploadQueueChanged);
- }
- // 从上传队列移除
- public removeFromUploadQueue(index: number): void {
- if (index >= 0 && index < this.uploadQueue.length) {
- const task = this.uploadQueue[index];
- this.uploadQueue.splice(index, 1);
- Logger.info(TAG, '从上传队列移除:', task.song.title);
- this.notifyObservers(WebdavManagerStates.UploadQueueChanged);
- }
- }
- // 清空上传队列
- public clearUploadQueue(): void {
- this.uploadQueue = [];
- Logger.info(TAG, '清空上传队列');
- this.notifyObservers(WebdavManagerStates.UploadQueueChanged);
- }
- // ==================== 安全认证方法 ====================
- // 获取WebDAV认证信息(用于播放器)
- public getWebDavAuthHeaders(accountId: number): WebDavAuthInfo | null {
- const account = this.getWebDavAccountById(accountId);
- if (!account || !account.account || !account.password) {
- Logger.error(TAG, '无效的WebDAV账户或缺少认证信息');
- return null;
- }
- // 构建基础URL
- const protocol = account.enableHttps ? 'https' : 'http';
- const host = account.isUseLocalHost ? account.localHost : account.host;
- const port = 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}`
- };
- return authInfo;
- }
- // 根据ID获取WebDAV账户
- private getWebDavAccountById(accountId: number): WebDavAccount | null {
- for (let i = 0; i < this.webDavAccounts.length; i++) {
- const account = this.webDavAccounts[i];
- if (account.id === accountId) {
- return account;
- }
- }
- return null;
- }
- // 获取安全的播放URL(不包含认证信息)
- public getSecurePlayUrl(song: Song): string | null {
- if (song.songType !== SongType.WebDav || !song.webDavAccountId) {
- return song.src;
- }
- const authInfo = this.getWebDavAuthHeaders(song.webDavAccountId);
- if (!authInfo) {
- return null;
- }
- return authInfo.url + song.webFilePath;
- }
- }
|