WebDavMainPage.ets 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557
  1. import { BreadcrumbItem, RemoteDriveManager } from '../common/util/RemoteDriveManager';
  2. import { WebDavAccount } from '../viewmodel/WebDavAccount';
  3. import { Song } from '../viewmodel/Song';
  4. import { RemoteDriveManagerStates } from '../common/enums/RemoteDriveManagerStates';
  5. import Logger from '../common/util/Logger';
  6. import { promptAction, SymbolGlyphModifier, router, window } from '@kit.ArkUI';
  7. import { CommonConstants } from '../common/constants/CommonConstants';
  8. import { VideoItem } from '../viewmodel/VideoItem';
  9. import { GlobalContext } from '../common/util/GlobalContext';
  10. import { display } from '@kit.ArkUI';
  11. import { FileInfo } from '../viewmodel/FileInfo';
  12. import { emitter } from '@kit.BasicServicesKit';
  13. import { EventConstants } from '../common/constants/EventConstants';
  14. import { LazyDataSource } from '../common/util/LazyDataSource';
  15. import { PreferencesUtil, StrUtil } from '@pura/harmony-utils';
  16. import { DialogHelper } from '@pura/harmony-dialog';
  17. import { ButtonFancyModifier,
  18. MenuModifier,
  19. ShadowModifier, SymbolGlyphFancyModifier } from '../common/util/AttributeModifierUtil';
  20. import { getRemoteDriveAccountLabel, getRemoteDriveDisplayLabel, getRemoteDrivePlaylistPrefix } from '../common/util/RemoteDriveLabel';
  21. import { RemoteDriveType } from '../common/enums/RemoteDriveType';
  22. import { Utility } from '../common/util/Utility';
  23. import { SettingPage } from './SettingPage';
  24. import { getCloudDiskIcon } from '../dialog/RemoteDriveAccountDialog';
  25. /**
  26. * 歌单播放事件数据
  27. */
  28. interface PlaylistEventData {
  29. playlistId: string;
  30. playlistName: string;
  31. songCount: number;
  32. startIndex: number;
  33. isJump: boolean;
  34. songFilePaths: string[];
  35. // 移除webDavAuthInfo,现在直接使用videoItems中的webdav_account_id
  36. }
  37. interface WebDavMetadataUpdatePayload {
  38. filePath: string;
  39. pixelMapPath?: string;
  40. name?: string;
  41. artist?: string;
  42. }
  43. const TAG = 'heanup WebDavMainPage';
  44. // WebDAV歌曲数据全局内存存储
  45. let globalWebdavVideoItems: VideoItem[] = [];
  46. let globalWebdavCurrentPlayIndex: number = 0;
  47. // 导出函数供LocalMusic访问
  48. export function getWebdavVideoItems(): VideoItem[] {
  49. return globalWebdavVideoItems;
  50. }
  51. export function getWebdavCurrentPlayIndex(): number {
  52. return globalWebdavCurrentPlayIndex;
  53. }
  54. export function clearWebdavVideoItems(): void {
  55. globalWebdavVideoItems = [];
  56. globalWebdavCurrentPlayIndex = 0;
  57. }
  58. // URL解码函数
  59. function decodeUrlEncodedString(encodedStr: string): string {
  60. try {
  61. return decodeURIComponent(encodedStr);
  62. } catch (error) {
  63. // 如果解码失败,返回原始字符串
  64. return encodedStr;
  65. }
  66. }
  67. @Preview
  68. @Entry
  69. @Component
  70. export struct WebDavMainPage {
  71. @State isShowTitleBar: boolean = true //是否显示分类导航条
  72. private prevOffsetY: number = 0; // 记录上一次的Y轴偏移量
  73. @State autoHideTitle: boolean = true //滚动自动隐藏标题栏
  74. @State isCustomizeBg: boolean = false //自定义背景界面
  75. @StorageProp('isLandscape') isLandscape: boolean = false;
  76. @State blurValue: number = 0 //背景模糊
  77. @State bgBrightness: number = 0 //背景亮度
  78. @State customizeBgPath: string | undefined = '';
  79. private listScroller: ListScroller = new ListScroller()
  80. @StorageProp('bottomSafeHeight') bottomSafeHeight: number = 0;
  81. searchController: SearchController = new SearchController()
  82. @StorageProp('animationState') animationState: AnimationStatus= AnimationStatus.Running
  83. @State isNoJumpToHome: boolean = false //网盘播放不跳转首页
  84. @State isSearchMode: boolean = false
  85. @StorageLink('currentSong') currentSong: VideoItem | undefined = undefined;
  86. @StorageProp('topSafeHeight') topSafeHeight: number = 0;
  87. @State webdavManager: RemoteDriveManager = RemoteDriveManager.getInstance();
  88. @State accounts: WebDavAccount[] = [];
  89. @Prop @Watch('onSwitchAccount') selectedAccount: WebDavAccount;
  90. @State songs: VideoItem[] = [];
  91. @State dataSource:LazyDataSource<VideoItem> = new LazyDataSource(this.songs)
  92. @Link mType: number;
  93. @Link offsetX: number;
  94. @Link isShowDrawer: boolean;
  95. @State isLoading: boolean = false;
  96. @State webDavFiles: FileInfo[] = []; // 直接在页面中保存文件列表副本
  97. @StorageProp('themeColor') themeColor: string = CommonConstants.DEFAULT_THEME_COLOR;
  98. @StorageProp('isDarkMode') isDarkMode: boolean = false;
  99. @State breadcrumbs:BreadcrumbItem[] = []//面包屑导航
  100. @State visibleFoldersState: FileInfo[] = []; // 改为普通状态变量
  101. @State isShowFileName: boolean = false//是否显示文件名
  102. @State isLongNameRoLL: boolean = true//长歌名滚动
  103. @State sortType: number = 0 //默认排序方式
  104. @State listRefreshKey: number = 0 // 列表刷新标识
  105. @Consume isMultiSelect: boolean
  106. @State selectedSongs: VideoItem[] = []
  107. @State isAllSelected: boolean = false
  108. @State isDeletingSelection: boolean = false
  109. private readonly metadataUpdateEvent: emitter.InnerEvent = { eventId: EventConstants.EVENT_WEBDAV_METADATA_UPDATED };
  110. async onSwitchAccount(){
  111. console.log('onecold 切换账户:', this.selectedAccount.name);
  112. this.songs = [];
  113. this.visibleFoldersState = [];
  114. this.updateListData(this.songs)
  115. this.exitMultiSelect();
  116. // 注意:不再需要清空全局上下文,因为LocalMusic已改用实例变量缓存
  117. // 当新账户加载时,新的认证信息会自动覆盖旧的
  118. Logger.info(TAG, 'heanup 切换账户,准备加载新账户文件');
  119. this.isLoading = true;
  120. await this.webdavManager.loadFilesInfoFromAccount(this.selectedAccount)
  121. .catch((error: Error) => {
  122. Logger.error(TAG, '加载文件失败: ' + error.message);
  123. this.isLoading = false;
  124. });
  125. this.breadcrumbs = this.webdavManager.getBreadcrumbs();
  126. }
  127. updateListData(mList:Array<VideoItem>, noSort?: boolean){
  128. if (!noSort) {
  129. this.sortType = PreferencesUtil.getNumberSync('webDavSortType', 0)
  130. this.doSortType(this.sortType)
  131. }
  132. this.dataSource.pushArrayData(mList)
  133. if(mList.length > 0){
  134. setTimeout(() => {
  135. this.listScroller.scrollToIndex(0)
  136. },200)
  137. }
  138. }
  139. // 更新可见文件夹列表
  140. private updateVisibleFolders(): void {
  141. try {
  142. // 安全检查webDavFiles
  143. if (!this.webDavFiles || !Array.isArray(this.webDavFiles)) {
  144. this.visibleFoldersState = [];
  145. return;
  146. }
  147. const allFolders = this.webDavFiles.filter(f => f.isDirectory);
  148. const isNavAccount = this.selectedAccount?.webType === RemoteDriveType.Navidrome;
  149. if (isNavAccount) {
  150. const sortedNavFolders = allFolders.sort((a, b) => a.fileName.localeCompare(b.fileName));
  151. this.visibleFoldersState = sortedNavFolders;
  152. return;
  153. }
  154. const visible: FileInfo[] = [];
  155. for (let i = 0; i < allFolders.length; i++) {
  156. const folder = allFolders[i];
  157. // 安全检查folder对象
  158. if (!folder || typeof folder.fileName !== 'string') {
  159. continue;
  160. }
  161. let shouldShow = this.isDirectChildOfCurrentPath(folder);
  162. if (shouldShow) {
  163. visible.push(folder);
  164. }
  165. }
  166. console.log('更新文件夹列表:', visible);
  167. this.visibleFoldersState = visible;
  168. } catch (error) {
  169. Logger.error(TAG, '更新文件夹列表失败:', error.toString());
  170. this.visibleFoldersState = [];
  171. }
  172. }
  173. private isSongSelected(song: VideoItem): boolean {
  174. return this.selectedSongs.some(item => item.filePath === song.filePath);
  175. }
  176. private enterMultiSelect(song: VideoItem): void {
  177. if (!this.isMultiSelect) {
  178. this.isMultiSelect = true;
  179. this.selectedSongs = [song];
  180. this.isAllSelected = this.selectedSongs.length === this.songs.length && this.songs.length > 0;
  181. return;
  182. }
  183. if (!this.isSongSelected(song)) {
  184. this.toggleSongSelection(song);
  185. }
  186. }
  187. private toggleSongSelection(song: VideoItem): void {
  188. if (!this.isMultiSelect) {
  189. this.isMultiSelect = true;
  190. }
  191. const exists = this.isSongSelected(song);
  192. if (exists) {
  193. const next = this.selectedSongs.filter(item => item.filePath !== song.filePath);
  194. this.selectedSongs = next;
  195. this.isAllSelected = next.length > 0 && next.length === this.songs.length;
  196. if (next.length === 0) {
  197. this.exitMultiSelect();
  198. }
  199. } else {
  200. const next = [...this.selectedSongs, song];
  201. this.selectedSongs = next;
  202. this.isAllSelected = next.length === this.songs.length && this.songs.length > 0;
  203. }
  204. }
  205. private handleCheckboxSelection(song: VideoItem, checked: boolean): void {
  206. if (!this.isMultiSelect) {
  207. this.isMultiSelect = true;
  208. }
  209. const exists = this.isSongSelected(song);
  210. if (checked && !exists) {
  211. this.toggleSongSelection(song);
  212. } else if (!checked && exists) {
  213. this.toggleSongSelection(song);
  214. }
  215. }
  216. private toggleSelectAll(): void {
  217. if (this.isAllSelected) {
  218. this.selectedSongs = [];
  219. this.isAllSelected = false;
  220. return;
  221. }
  222. if (!this.isMultiSelect) {
  223. this.isMultiSelect = true;
  224. }
  225. this.selectedSongs = this.songs.slice();
  226. this.isAllSelected = this.selectedSongs.length > 0 && this.selectedSongs.length === this.songs.length;
  227. }
  228. private exitMultiSelect(): void {
  229. this.isMultiSelect = false;
  230. this.selectedSongs = [];
  231. this.isAllSelected = false;
  232. console.info('onecold this.isMultiSelect '+this.isMultiSelect)
  233. }
  234. private syncSelectionAfterRefresh(): void {
  235. if (!this.isMultiSelect) {
  236. return;
  237. }
  238. const currentKeys: Set<string> = new Set(this.songs.map(item => item.filePath));
  239. const filtered = this.selectedSongs.filter(item => currentKeys.has(item.filePath));
  240. if (filtered.length !== this.selectedSongs.length) {
  241. this.selectedSongs = filtered;
  242. }
  243. this.isAllSelected = filtered.length > 0 && filtered.length === this.songs.length;
  244. if (filtered.length === 0) {
  245. this.exitMultiSelect();
  246. }
  247. }
  248. private confirmDeleteSelected(): void {
  249. if (!this.selectedAccount) {
  250. this.getUIContext().getPromptAction().showToast({ message: `请先选择${getRemoteDriveAccountLabel()}` });
  251. return;
  252. }
  253. if (!this.isMultiSelect || this.selectedSongs.length === 0) {
  254. this.getUIContext().getPromptAction().showToast({ message: '请先选择要删除的文件' });
  255. return;
  256. }
  257. this.getUIContext().showAlertDialog({
  258. title: '删除文件',
  259. message: `确定删除选中的${this.selectedSongs.length}个文件吗?`,
  260. primaryButton: {
  261. value: '取消',
  262. action: () => {}
  263. },
  264. secondaryButton: {
  265. value: '删除',
  266. fontColor: Color.Red,
  267. action: () => {
  268. void this.performDeleteSelected();
  269. }
  270. }
  271. });
  272. }
  273. private async performDeleteSelected(): Promise<void> {
  274. if (!this.selectedAccount || this.selectedSongs.length === 0) {
  275. return;
  276. }
  277. this.isDeletingSelection = true;
  278. try {
  279. await this.webdavManager.deleteRemoteSongs(this.selectedAccount, this.selectedSongs.slice());
  280. await this.webdavManager.loadFilesInfoFromAccount(this.selectedAccount, this.webdavManager.currentPath);
  281. this.exitMultiSelect();
  282. this.getUIContext().getPromptAction().showToast({ message: '删除成功' });
  283. } catch (error) {
  284. const err = error as Error;
  285. this.getUIContext().getPromptAction().showToast({ message: `删除失败: ${err.message}` });
  286. } finally {
  287. this.isDeletingSelection = false;
  288. }
  289. }
  290. private buildSongMetaLine(song: VideoItem): string {
  291. const parts: string[] = [];
  292. if (StrUtil.isNotEmpty(song.duration)) {
  293. parts.push(song.duration as string);
  294. } else if (StrUtil.isNotEmpty(song.size)) {
  295. parts.push(decodeUrlEncodedString(song.size as string));
  296. }
  297. if (parts.length === 0 && StrUtil.isNotEmpty(song.cTime)) {
  298. parts.push(song.cTime as string);
  299. }
  300. return parts.join(' · ');
  301. }
  302. // 对话框控制器
  303. private accountDialogController: CustomDialogController | null = null;
  304. // 保存事件处理器引用,用于取消订阅
  305. private eventHandler: (event: string) => void = (event: string) => {
  306. this.handleWebdavEvent(event);
  307. };
  308. initSetting(){
  309. this.isCustomizeBg = PreferencesUtil.getBooleanSync(SettingPage.IS_CUSTOMIZE_BG, false)
  310. this.customizeBgPath = PreferencesUtil.getStringSync(SettingPage.IS_CUSTOMIZE_BG_PATH, '')
  311. this.blurValue = PreferencesUtil.getNumberSync(SettingPage.CUSTOMIZE_BG_BLUR, 0)
  312. this.bgBrightness = PreferencesUtil.getNumberSync(SettingPage.BG_BRIGHTNESS, 0)
  313. this.isShowFileName = PreferencesUtil.getBooleanSync('isShowFileName', false)
  314. this.isLongNameRoLL = PreferencesUtil.getBooleanSync('isLongNameRoLL', true)
  315. this.sortType = PreferencesUtil.getNumberSync('webDavSortType', 0)
  316. this.isNoJumpToHome = PreferencesUtil.getBooleanSync('isNoJumpToHome', true)
  317. this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, true)
  318. this.autoHideTitle = PreferencesUtil.getBooleanSync('autoHideTitle', true)
  319. }
  320. aboutToAppear(): void {
  321. this.initSetting()
  322. let eventSetting: emitter.InnerEvent = { eventId: 333 }
  323. // 监听广播事件(通用设置配置更新)
  324. emitter.on(eventSetting, (eventData: emitter.EventData) => {
  325. this.initSetting()
  326. });
  327. // 加载账户列表
  328. this.loadAccounts();
  329. this.loadFiles()
  330. this.breadcrumbs = this.webdavManager.getBreadcrumbs();
  331. // 订阅WebDAV状态变化
  332. this.webdavManager.subscribe(this.eventHandler);
  333. this.subscribeWebDavMetadataUpdates();
  334. }
  335. aboutToDisappear(): void {
  336. // 取消订阅
  337. this.webdavManager.unsubscribe(this.eventHandler);
  338. emitter.off(EventConstants.EVENT_WEBDAV_METADATA_UPDATED);
  339. }
  340. // 处理WebDAV事件
  341. private handleWebdavEvent(event: string): void {
  342. switch (event) {
  343. case RemoteDriveManagerStates.LoadFilesInfoSucceed:
  344. this.songs = this.webdavManager.webDavSongs;
  345. this.updateListData(this.songs)
  346. // 直接引用webdavManager的数组,避免@Observed序列化问题
  347. this.webDavFiles = this.webdavManager.webDavFiles;
  348. this.isLoading = false;
  349. // 更新可见文件夹列表
  350. this.updateVisibleFolders();
  351. this.breadcrumbs = this.webdavManager.getBreadcrumbs();
  352. this.syncSelectionAfterRefresh();
  353. // promptAction.showToast({
  354. // message: '加载成功: ' + this.webDavFiles.filter(f => f.isDirectory).length + '个文件夹, ' + this.songs.length + '首歌曲'
  355. // });
  356. break;
  357. case RemoteDriveManagerStates.LoadFilesInfoFailed:
  358. this.isLoading = false;
  359. // this.getUIContext().getPromptAction().showToast({ message: '加载失败' });
  360. break;
  361. case RemoteDriveManagerStates.InsertAccountSucceed:
  362. case RemoteDriveManagerStates.EditAccountSucceed:
  363. case RemoteDriveManagerStates.RemoveAccountSucceed:
  364. this.loadAccounts();
  365. break;
  366. }
  367. }
  368. private subscribeWebDavMetadataUpdates(): void {
  369. emitter.on(this.metadataUpdateEvent, (eventData: emitter.EventData) => {
  370. const payloads = eventData?.data as WebDavMetadataUpdatePayload[] | undefined;
  371. if (!payloads || payloads.length === 0) {
  372. Logger.info(TAG, 'WebDav metadata event received but payload empty');
  373. return;
  374. }
  375. Logger.info(TAG, `WebDav metadata event payload count: ${payloads.length}`);
  376. this.handleWebDavMetadataUpdates(payloads);
  377. });
  378. }
  379. private handleWebDavMetadataUpdates(payloads: WebDavMetadataUpdatePayload[]): void {
  380. if (!payloads || payloads.length === 0) {
  381. return;
  382. }
  383. Logger.info(TAG, 'handleWebDavMetadataUpdates start');
  384. let hasChanges = false;
  385. for (let i = 0; i < payloads.length; i++) {
  386. const payload = payloads[i];
  387. if (!payload || !payload.filePath) {
  388. continue;
  389. }
  390. Logger.info(TAG, `WebDav metadata detail path=${payload.pixelMapPath ?? 'null'}`);
  391. const songUpdated = this.updateSongMetadata(payload);
  392. if (songUpdated) {
  393. hasChanges = true;
  394. Logger.info(TAG, `metadata updated for ${payload.filePath}`);
  395. }
  396. }
  397. if (!hasChanges) {
  398. Logger.info(TAG, 'handleWebDavMetadataUpdates no changes detected');
  399. return;
  400. }
  401. const clonedSongs: VideoItem[] = [];
  402. for (let i = 0; i < this.songs.length; i++) {
  403. clonedSongs.push(this.cloneSong(this.songs[i]));
  404. }
  405. this.songs = clonedSongs;
  406. this.dataSource.pushArrayData(clonedSongs);
  407. this.listRefreshKey++;
  408. Logger.info(TAG, 'handleWebDavMetadataUpdates trigger refresh');
  409. }
  410. private updateSongMetadata(payload: WebDavMetadataUpdatePayload): boolean {
  411. if (!payload.filePath) {
  412. return false;
  413. }
  414. const targetIndex = this.findSongIndex(payload.filePath);
  415. if (targetIndex < 0) {
  416. return false;
  417. }
  418. const targetSong = this.songs[targetIndex];
  419. let mutated = false;
  420. if (payload.pixelMapPath && payload.pixelMapPath.length > 0) {
  421. targetSong.pixelMapPath = payload.pixelMapPath;
  422. mutated = true;
  423. }
  424. if (payload.name && payload.name.length > 0) {
  425. targetSong.name = payload.name;
  426. mutated = true;
  427. }
  428. if (payload.artist && payload.artist.length > 0) {
  429. targetSong.artist = payload.artist;
  430. mutated = true;
  431. }
  432. return mutated;
  433. }
  434. private findSongIndex(filePath: string): number {
  435. for (let i = 0; i < this.songs.length; i++) {
  436. if (this.songs[i].filePath === filePath) {
  437. return i;
  438. }
  439. }
  440. return -1;
  441. }
  442. private cloneSong(item: VideoItem): VideoItem {
  443. const clone = new VideoItem(
  444. item.name,
  445. item.id,
  446. item.filePath,
  447. item.type,
  448. item.videoSize,
  449. item.cTime,
  450. item.size,
  451. item.pixelMapPath,
  452. item.artist,
  453. item.album,
  454. item.fileName,
  455. item.lastPlayed
  456. );
  457. clone.duration = item.duration;
  458. clone.mimeType = item.mimeType;
  459. clone.trackCount = item.trackCount;
  460. clone.sampleRate = item.sampleRate;
  461. clone.size = item.size;
  462. clone.webdav_account_id = item.webdav_account_id;
  463. clone.remote_rel_path = item.remote_rel_path;
  464. clone.artist = item.artist;
  465. clone.album = item.album;
  466. clone.lyricContent = item.lyricContent;
  467. clone.pixelMapPath = item.pixelMapPath;
  468. clone.cTime = item.cTime;
  469. clone.fileName = item.fileName;
  470. clone.md5Str = item.md5Str;
  471. clone.bit_rate = item.bit_rate;
  472. clone.probe_score = item.probe_score;
  473. clone.year = item.year;
  474. clone.nb_streams = item.nb_streams;
  475. clone.nb_programs = item.nb_programs;
  476. clone.genre = item.genre;
  477. clone.track = item.track;
  478. clone.disc = item.disc;
  479. clone.channels = item.channels;
  480. clone.channel_layout = item.channel_layout;
  481. clone.start_time = item.start_time;
  482. clone.ALBUMARTIST = item.ALBUMARTIST;
  483. clone.COMPOSER = item.COMPOSER;
  484. clone.COMMENT = item.COMMENT;
  485. clone.LYRICIST = item.LYRICIST;
  486. clone.pyStr = item.pyStr;
  487. clone.extra_json = item.extra_json;
  488. clone.parentPath = item.parentPath;
  489. clone.isFav = item.isFav;
  490. clone.playCount = item.playCount;
  491. clone.lastPlayed = item.lastPlayed;
  492. clone.videoSize = item.videoSize;
  493. clone.isFav = item.isFav;
  494. return clone;
  495. }
  496. // 加载账户列表
  497. private loadAccounts(): void {
  498. this.accounts = this.webdavManager.getAllWebDavAccounts();
  499. }
  500. // 加载文件列表
  501. private loadFiles(): void {
  502. if (!this.selectedAccount) {
  503. this.getUIContext().getPromptAction().showToast({ message: '请先选择账户' });
  504. return;
  505. }
  506. this.isLoading = true;
  507. this.webdavManager.loadFilesInfoFromWebdav()
  508. .catch((error: Error) => {
  509. Logger.error(TAG, '加载文件失败: ' + error.message);
  510. this.isLoading = false;
  511. });
  512. }
  513. // 进入文件夹
  514. private enterFolder(folder: FileInfo): void {
  515. this.isLoading = true;
  516. this.webdavManager.enterFolder(folder)
  517. .catch((error: Error) => {
  518. Logger.error(TAG, '进入文件夹失败: ' + error.message);
  519. this.isLoading = false;
  520. });
  521. }
  522. // 检查是否为当前目录的直接子项
  523. private isDirectChildOfCurrentPath(folder: FileInfo): boolean {
  524. const currentPath = this.webdavManager.currentPath || '';
  525. // 如果在根目录(currentPath为空或'/'),显示所有第一级文件夹
  526. if (currentPath === '' || currentPath === '/') {
  527. const folderPath = folder.href.replace(/\/$/, ''); // 去掉尾部斜杠
  528. return folder.href.startsWith('/') &&
  529. folder.href !== '/' &&
  530. !folderPath.substring(1).includes('/');
  531. }
  532. // 非根目录情况,计算相对路径
  533. let relativePath = folder.href;
  534. if (currentPath !== '/') {
  535. relativePath = folder.href.replace(currentPath, '');
  536. }
  537. relativePath = relativePath.replace(/^\//, '').replace(/\/$/, '');
  538. // 只有相对路径不为空且不包含/时才认为是直接子项
  539. return relativePath !== '' && !relativePath.includes('/');
  540. }
  541. // 返回上级目录
  542. private goBack(): void {
  543. if(this.webdavManager.canGoBack()){
  544. this.isLoading = true;
  545. this.webdavManager.goBack()
  546. .catch((error: Error) => {
  547. Logger.error(TAG, '返回失败: ' + error.message);
  548. this.isLoading = false;
  549. });
  550. this.breadcrumbs = this.webdavManager.getBreadcrumbs();
  551. }
  552. }
  553. // 切换账户
  554. private switchAccount(account: WebDavAccount): void {
  555. this.selectedAccount = account;
  556. this.songs = [];
  557. this.updateListData(this.songs)
  558. }
  559. // 播放WebDAV歌曲
  560. private playSong(song: VideoItem, index: number,isJump:boolean=false): void {
  561. try {
  562. Logger.info(TAG, `heanup === WebDAV playSong 方法被调用 ===`);
  563. Logger.info(TAG, 'heanup 播放指定歌曲: ' + song.name + ', 索引: ' + index);
  564. Logger.info(TAG, 'heanup 歌曲列表长度: ' + this.songs.length);
  565. // 检查歌曲是否有webdav_account_id
  566. Logger.info(TAG, `heanup 播放歌曲的webdav_account_id: ${song.webdav_account_id || '未设置'}`);
  567. // 确保所有歌曲都设置了正确的webdav_account_id
  568. if (this.selectedAccount && this.selectedAccount.id) {
  569. const accountIds = this.songs.map(s => s.webdav_account_id).filter(id => id);
  570. Logger.info(TAG, `heanup 当前歌曲列表中有 ${accountIds.length}/${this.songs.length} 首歌曲设置了webdav_account_id`);
  571. // 如果发现歌曲缺少webdav_account_id,立即设置
  572. this.songs.forEach((item, idx) => {
  573. if (!item.webdav_account_id) {
  574. item.webdav_account_id = this.selectedAccount!.id.toString();
  575. Logger.info(TAG, `heanup 为歌曲 "${item.name}" 设置webdav_account_id: ${item.webdav_account_id}`);
  576. }
  577. });
  578. }
  579. // 直接使用当前的VideoItem数组
  580. const videoItems: VideoItem[] = this.songs;
  581. const songFilePaths: string[] = [];
  582. for (let i = 0; i < this.songs.length; i++) {
  583. const item = this.songs[i];
  584. songFilePaths.push(item.filePath); // 使用filePath作为文件路径
  585. }
  586. // 直接通过事件传递videoItems数据,不使用GlobalContext
  587. const eventPlaylistPlay: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYLIST_PLAY };
  588. const playlistData: PlaylistEventData = {
  589. playlistId: 'webdav-playlist', // 使用特殊的ID标识网盘播放列表
  590. playlistName: `${getRemoteDriveDisplayLabel(this.selectedAccount?.webType)} - ${this.selectedAccount?.name || '未知账户'}`,
  591. songCount: this.songs.length,
  592. startIndex: index,
  593. isJump: isJump,//设置true会弹出播放页
  594. songFilePaths: songFilePaths
  595. };
  596. // 保存videoItems到全局内存
  597. globalWebdavVideoItems = videoItems;
  598. globalWebdavCurrentPlayIndex = index;
  599. Logger.info(TAG, `heanup 保存WebDAV歌曲到全局内存,长度: ${videoItems.length}, 索引: ${index}`);
  600. // 发送播放请求事件,只传递索引信息
  601. emitter.emit(eventPlaylistPlay, { data: playlistData });
  602. Logger.info(TAG, `heanup 发送WebDAV播放事件,只传递索引: ${index}`);
  603. if(!this.isNoJumpToHome){
  604. // 跳转到首页播放器
  605. this.getUIContext()?.animateTo({ duration: 555 }, () => {
  606. this.mType = 0
  607. })
  608. }
  609. } catch (error) {
  610. const err = error as Error;
  611. Logger.error(TAG, '播放歌曲失败: ' + err.message);
  612. this.getUIContext().getPromptAction().showToast({ message: '播放失败' });
  613. }
  614. }
  615. /**
  616. * 一键创建歌单:将当前WebDAV歌曲全部加入新歌单
  617. */
  618. private async createPlaylistFromCurrentWebDav(): Promise<void> {
  619. try {
  620. Logger.info(TAG, 'heanup 一键创建歌单开始');
  621. if (!this.selectedAccount || !this.selectedAccount.id) {
  622. this.getUIContext().getPromptAction().showToast({ message: `请先选择${getRemoteDriveAccountLabel()}` });
  623. return;
  624. }
  625. if (!this.songs || this.songs.length === 0) {
  626. // 回退到manager内的歌曲(可能还未复制到页面state)
  627. this.songs = this.webdavManager.webDavSongs;
  628. Logger.info(TAG, `heanup 页面songs为空,回退webdavManager.webDavSongs,长度=${this.songs.length}`);
  629. if (this.songs.length === 0) {
  630. this.getUIContext().getPromptAction().showToast({ message: '当前目录没有可添加的歌曲' });
  631. return;
  632. }
  633. }
  634. Logger.info(TAG, `heanup 歌单创建前歌曲数量: ${this.songs.length}`);
  635. // 确保每首歌都有webdav_account_id
  636. for (let i = 0; i < this.songs.length; i++) {
  637. if (!this.songs[i].webdav_account_id) {
  638. this.songs[i].webdav_account_id = this.selectedAccount.id.toString();
  639. }
  640. }
  641. // 构建歌单名称:账户名 + 当前路径(简化)
  642. const rawPath = this.webdavManager.currentPath || '/';
  643. const shortPath = rawPath === '/' ? '根目录' : rawPath.replace(/\/$/, '').split('/').slice(-1)[0];
  644. const playlistName = `${getRemoteDrivePlaylistPrefix(this.selectedAccount.webType)}-${this.selectedAccount.name}-${shortPath}`;
  645. // 创建歌单
  646. // 安全获取HostContext
  647. const uiContext = this.getUIContext();
  648. const hostCtx = uiContext ? uiContext.getHostContext() : undefined;
  649. if (!hostCtx) {
  650. this.getUIContext().getPromptAction().showToast({ message: '无法获取上下文' });
  651. return;
  652. }
  653. const playlistModule = await import('../common/util/PlaylistTable');
  654. const mediaModule = await import('../common/util/MediaTable');
  655. const playlistTable = new playlistModule.default(hostCtx);
  656. const mediaTable = new mediaModule.default(hostCtx);
  657. // 等待MediaTable底层RDB初始化完成
  658. await new Promise<void>((resolve) => {
  659. mediaTable.getRdbStore(hostCtx, () => {
  660. Logger.info(TAG, 'heanup mediaTable RDB 初始化完成');
  661. resolve();
  662. });
  663. });
  664. // 先将WebDAV歌曲入库(若不存在)
  665. let upsertSuccess = 0;
  666. for (let i = 0; i < this.songs.length; i++) {
  667. const v = this.songs[i];
  668. if (!v.id || v.id === '') {
  669. // 使用filePath作为唯一ID
  670. v.id = v.filePath;
  671. }
  672. if (!v.parentPath) {
  673. const idxp = v.filePath.lastIndexOf('/');
  674. if (idxp > 0) {
  675. v.parentPath = v.filePath.substring(0, idxp);
  676. }
  677. }
  678. const ok = await mediaTable.upsertWebDavVideoItem(v);
  679. Logger.info(TAG, `heanup upsert 第${i+1}/${this.songs.length}首: ${v.filePath} => ${ok}`);
  680. if (ok) {
  681. upsertSuccess++;
  682. }
  683. }
  684. Logger.info(TAG, `heanup WebDAV歌曲入库完成: 成功 ${upsertSuccess}/${this.songs.length}`);
  685. // 先查询是否已有同名歌单,避免重复创建导致混淆
  686. const existing = (await playlistTable.queryAllPlaylists()).find(p => p.name === playlistName);
  687. if (existing) {
  688. this.getUIContext().getPromptAction().showToast({ message: '歌单已存在,直接追加歌曲' });
  689. const filePathsExist: string[] = this.songs.map(s => s.filePath);
  690. await playlistTable.addSongsToPlaylist(existing.id, filePathsExist);
  691. router.pushUrl({ url: 'pages/PlaylistDetailPage', params: { playlist: existing } });
  692. return;
  693. }
  694. Logger.info(TAG, `heanup 准备创建歌单: ${playlistName}`);
  695. const created = await playlistTable.createPlaylist(playlistName, `来自${getRemoteDriveDisplayLabel(this.selectedAccount.webType)}: ${this.selectedAccount.name} 路径: ${rawPath}`);
  696. if (!created) {
  697. this.getUIContext().getPromptAction().showToast({ message: '歌单创建失败' });
  698. return;
  699. }
  700. // 查询刚创建的歌单ID
  701. const playlists = await playlistTable.queryAllPlaylists();
  702. const target = playlists.reverse().find(p => p.name === playlistName); // 取最近创建的同名歌单
  703. if (!target) {
  704. this.getUIContext().getPromptAction().showToast({ message: '无法找到新建歌单' });
  705. return;
  706. }
  707. // 批量添加歌曲
  708. const filePaths: string[] = this.songs.map(s => s.filePath);
  709. Logger.info(TAG, `heanup 开始批量添加歌曲到歌单: ${target.id}`);
  710. const addResult = await playlistTable.addSongsToPlaylist(target.id, filePaths);
  711. Logger.info(TAG, `heanup 批量添加结果: ${addResult}`);
  712. if (!addResult) {
  713. Logger.warn(TAG, '批量添加歌曲返回false,可能全部已存在或写入失败');
  714. }
  715. this.getUIContext().getPromptAction().showToast({ message: `歌单创建成功: ${playlistName}` });
  716. Logger.info(TAG, `heanup 一键创建歌单成功: ${playlistName}, 添加 ${filePaths.length} 首歌曲`);
  717. // 跳转到歌单详情页面
  718. router.pushUrl({ url: 'pages/PlaylistDetailPage', params: { playlist: target } });
  719. } catch (error) {
  720. Logger.error(TAG, '一键创建歌单失败: ' + (error as Error).message);
  721. this.getUIContext().getPromptAction().showToast({ message: '一键创建歌单失败' });
  722. }
  723. }
  724. // 导航到指定层级的面包屑路径
  725. private async navigateToBreadcrumb(crumb: BreadcrumbItem): Promise<void> {
  726. if (!crumb) {
  727. return;
  728. }
  729. try {
  730. this.isLoading = true;
  731. await this.webdavManager.enterFolderFromPath(crumb.path);
  732. } catch (error) {
  733. Logger.error(TAG, '导航到面包屑路径失败: ' + (error as Error).message);
  734. this.isLoading = false;
  735. }
  736. }
  737. // 导航到上传页面
  738. private navigateToUploadPage(): void {
  739. if (!this.selectedAccount || !this.selectedAccount.id) {
  740. this.getUIContext().getPromptAction().showToast({ message: '请先选择账户' });
  741. return;
  742. }
  743. Logger.info(TAG, '导航到上传页面,账户ID: ' + this.selectedAccount.id);
  744. this.getUIContext().getRouter().pushUrl({
  745. url: 'pages/UploadMusicPage',
  746. params: {
  747. accountId: this.selectedAccount.id
  748. }
  749. }).catch((error: Error) => {
  750. Logger.error(TAG, '导航到上传页面失败: ' + error.message);
  751. this.getUIContext().getPromptAction().showToast({ message: '打开上传页面失败' });
  752. });
  753. }
  754. @Builder
  755. MoreMenuBuilder() {
  756. Menu() {
  757. MenuItem({
  758. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music_note_list')),
  759. content: $r('app.string.onekey_add_playlist')
  760. })
  761. .onClick(async () => {
  762. this.createPlaylistFromCurrentWebDav();
  763. })
  764. MenuItem({
  765. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.arrow_up_to_line')),
  766. content: $r('app.string.upload_music_file')
  767. })
  768. .onClick(async () => {
  769. this.navigateToUploadPage();
  770. })
  771. }.attributeModifier(new MenuModifier())
  772. }
  773. @Builder
  774. SortMenuBuilder() {
  775. Menu() {
  776. MenuItem({
  777. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_up')),
  778. content: $r('app.string.sort_by_name')
  779. })
  780. .onClick(async () => {
  781. this.doSortType(0)
  782. PreferencesUtil.put("webDavSortType", 0)
  783. })
  784. MenuItem({
  785. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_down')),
  786. content: '按名称降序'
  787. })
  788. .onClick(async () => {
  789. this.doSortType(1)
  790. PreferencesUtil.put("webDavSortType", 1)
  791. })
  792. MenuItem({
  793. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.clock')),
  794. content:'按时间升序'
  795. })
  796. .onClick(async () => {
  797. this.doSortType(2)
  798. PreferencesUtil.put("webDavSortType", 2)
  799. })
  800. MenuItem({
  801. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.timer')),
  802. content: '按时间降序'
  803. })
  804. .onClick(async () => {
  805. this.doSortType(3)
  806. PreferencesUtil.put("webDavSortType", 3)
  807. })
  808. MenuItem({
  809. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_up')),
  810. content:'按大小升序'
  811. })
  812. .onClick(async () => {
  813. this.doSortType(4)
  814. PreferencesUtil.put("webDavSortType", 4)
  815. })
  816. MenuItem({
  817. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_down')),
  818. content: '按大小降序'
  819. })
  820. .onClick(async () => {
  821. this.doSortType(5)
  822. PreferencesUtil.put("webDavSortType", 5)
  823. })
  824. }.attributeModifier(new MenuModifier())
  825. }
  826. doSortType(index: number) {
  827. // 对歌曲列表进行排序
  828. switch (index) {
  829. case 0:
  830. Utility.doSortListAscending(this.songs,this.isShowFileName)
  831. this.visibleFoldersState.sort((a, b) => {
  832. return a.fileName.localeCompare(b.fileName);
  833. });
  834. break;
  835. case 1:
  836. Utility.doSortListDescending(this.songs,this.isShowFileName)
  837. this.visibleFoldersState.sort((a, b) => {
  838. return b.fileName.localeCompare(a.fileName);
  839. });
  840. break;
  841. case 2:
  842. this.songs.sort((a, b) => {
  843. return a.cTime.localeCompare(b.cTime);
  844. });
  845. this.visibleFoldersState.sort((a, b) => {
  846. return a.time-b.time;
  847. });
  848. break;
  849. case 3:
  850. this.songs.sort((a, b) => {
  851. return b.cTime.localeCompare(a.cTime);
  852. });
  853. this.visibleFoldersState.sort((a, b) => {
  854. return b.time-a.time;
  855. });
  856. break;
  857. case 4:
  858. this.songs.sort((a, b) => {
  859. return a.videoSize - b.videoSize;
  860. });
  861. break;
  862. case 5:
  863. this.songs.sort((a, b) => {
  864. return b.videoSize - a.videoSize;
  865. });
  866. break;
  867. }
  868. this.updateListData(this.songs,true)
  869. }
  870. @Builder
  871. topTitleBar(){
  872. Column() {
  873. Row({ space: 15 }) {
  874. if (!this.isSearchMode ) {
  875. //左侧滑动按钮
  876. Button({ type: ButtonType.Circle, stateEffect: true }) {
  877. SymbolGlyph($r('sys.symbol.sort'))
  878. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  879. }
  880. .attributeModifier(new ButtonFancyModifier(40, 40))
  881. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  882. .animation({ duration: 300, curve: Curve.Ease })
  883. .onClick(() => {
  884. this.getUIContext().animateTo({ duration: 555 }, () => {
  885. // 动画闭包内控制Image组件的出现和消失
  886. this.isShowDrawer = !this.isShowDrawer
  887. this.offsetX = 0
  888. })
  889. })
  890. .attributeModifier(new ShadowModifier())
  891. .zIndex(0)
  892. Text(this.selectedAccount.name)
  893. .margin({left:3,right:10})
  894. .fontColor($r('app.color.text_color'))
  895. .fontSize(19)
  896. .maxLines(1)
  897. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  898. .layoutWeight(1)
  899. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  900. }else{
  901. //左侧搜索返回按钮
  902. Button({ type: ButtonType.Circle, stateEffect: true }) {
  903. SymbolGlyph($r('sys.symbol.chevron_left'))
  904. .attributeModifier(new SymbolGlyphFancyModifier(24, '', ''))
  905. }
  906. .attributeModifier(new ButtonFancyModifier(40, 40))
  907. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  908. .animation({ duration: 300, curve: Curve.Ease })
  909. .onClick(() => {
  910. this.isSearchMode = false
  911. this.onSearchInput('')
  912. })
  913. .attributeModifier(new ShadowModifier())
  914. .zIndex(0)
  915. }
  916. //搜索框
  917. Search({ controller: this.searchController,value: this.searchText, placeholder: '搜索标题、艺术家...' })
  918. .searchButton('搜索',{fontColor:this.themeColor})
  919. .searchIcon({
  920. src: $r('sys.media.ohos_ic_public_search_filled')
  921. })
  922. .cancelButton({
  923. style: CancelButtonStyle.CONSTANT,
  924. icon: {
  925. src: $r('sys.media.ohos_ic_public_cancel_filled')
  926. }
  927. })
  928. .layoutWeight(1)
  929. .height(35)
  930. .maxLength(20)
  931. .backgroundColor(this.isDarkMode?Color.Black:'#F5F5F5')
  932. .placeholderColor(Color.Grey)
  933. .placeholderFont({ size: 14, weight: 400 })
  934. .textFont({ size: 14, weight: 400 })
  935. .onSubmit((value: string) => {
  936. console.log('onecold onSubmit ='+value)
  937. this.searchController.stopEditing()
  938. this.onSearchInput(this.searchText);
  939. })
  940. .onChange((value: string) => {
  941. console.log('onecold onChange ='+value)
  942. this.onSearchInput(value);
  943. })
  944. .visibility(this.isSearchMode?Visibility.Visible:Visibility.None)
  945. .animation({ duration: 300, curve: Curve.Ease })
  946. //搜索按钮
  947. if (!this.isSearchMode) {
  948. Button({ type: ButtonType.Circle, stateEffect: true }) {
  949. SymbolGlyph($r('sys.symbol.magnifyingglass'))
  950. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  951. }
  952. .attributeModifier(new ButtonFancyModifier(40, 40))
  953. .animation({ duration: 300, curve: Curve.Ease })
  954. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  955. .attributeModifier(new ShadowModifier())
  956. .zIndex(0)
  957. .onClick(()=>{
  958. this.filteredFolderList = [...this.visibleFoldersState]; // 显示所有文件夹
  959. this.isSearchMode = true
  960. })
  961. //排序按钮
  962. Button({ type: ButtonType.Circle, stateEffect: true }) {
  963. SymbolGlyph($r('sys.symbol.list_number'))
  964. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  965. }
  966. .attributeModifier(new ButtonFancyModifier(40, 40))
  967. .animation({ duration: 300, curve: Curve.Ease })
  968. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  969. .bindMenu(this.SortMenuBuilder)
  970. .attributeModifier(new ShadowModifier())
  971. .zIndex(0)
  972. //添加/上传综合按钮
  973. Button({ type: ButtonType.Circle, stateEffect: true }) {
  974. SymbolGlyph($r('sys.symbol.plus'))
  975. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  976. }
  977. .attributeModifier(new ButtonFancyModifier(40, 40))
  978. .animation({ duration: 300, curve: Curve.Ease })
  979. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  980. .bindMenu(this.MoreMenuBuilder)
  981. .attributeModifier(new ShadowModifier())
  982. .zIndex(0)
  983. }
  984. }
  985. }
  986. .padding({ top: this.topSafeHeight + 10, left: 10, right: 10, bottom: 2 })
  987. .width('100%')
  988. }
  989. //搜索功能的实现
  990. @State searchText: string = ''; // 用户输入内容
  991. @State filteredList: Array<VideoItem> = []; // 过滤后的歌曲结果
  992. @State filteredFolderList: Array<FileInfo> = []; // 过滤后的文件夹结果
  993. // 实时搜索逻辑(带防抖)
  994. // 实时搜索逻辑(带防抖)
  995. private onSearchInput(value: string) {
  996. this.searchText = value.trim();
  997. let mSearchList: Array<VideoItem> = []
  998. mSearchList = this.songs
  999. // 新增条件判断:空输入时显示所有数据
  1000. if (this.searchText === '') {
  1001. this.filteredList = [...mSearchList]; // 创建新数组以触发状态更新
  1002. this.filteredFolderList = [...this.visibleFoldersState]; // 显示所有文件夹
  1003. } else {
  1004. this.filteredList = mSearchList.filter((item: VideoItem) => {
  1005. //支持模糊匹配和艺术家 专辑匹配
  1006. const regex = new RegExp(this.searchText.toLowerCase().replace(/\s+/g, '.*'), 'i');
  1007. return regex.test(item.name.toLowerCase())||
  1008. regex.test(item.fileName?.toLowerCase() ?? "") ||
  1009. regex.test(item.artist?.toLowerCase() ?? "") ||
  1010. regex.test(item.album?.toLowerCase() ?? "")
  1011. });
  1012. // 对文件夹进行过滤
  1013. this.filteredFolderList = this.visibleFoldersState.filter((folder: FileInfo) => {
  1014. const regex = new RegExp(this.searchText.toLowerCase().replace(/\s+/g, '.*'), 'i');
  1015. return regex.test(folder.fileName?.toLowerCase() ?? "") ||
  1016. regex.test(decodeUrlEncodedString(folder.fileName?.replace('/', '') ?? "").toLowerCase());
  1017. });
  1018. }
  1019. this.updateListData(this.filteredList);
  1020. }
  1021. build() {
  1022. Stack() {
  1023. if (this.accounts.length === 0) {
  1024. this.buildEmptyView();
  1025. } else {
  1026. this.buildContentView();
  1027. }
  1028. // 顶部区域:标题栏在上,面包屑在下
  1029. Column() {
  1030. this.topTitleBar()
  1031. this.breaker()
  1032. }
  1033. .width('100%')
  1034. .visibility(this.isShowTitleBar?Visibility.Visible:
  1035. this.autoHideTitle?Visibility.None:Visibility.Visible)
  1036. .animation({
  1037. duration: 500,
  1038. curve: Curve.Friction // 可选动画曲线
  1039. })
  1040. .position({ top: 0, left: 0 })
  1041. // .backgroundColor($r('app.color.start_window_background'))
  1042. // 多选操作条,位于播放条之上(仅在多选模式下显示)
  1043. if (this.isMultiSelect || this.isDeletingSelection) {
  1044. this.buildSelectionOverlay()
  1045. }
  1046. }
  1047. .width('100%')
  1048. .height('100%')
  1049. .alignContent(Alignment.Bottom)
  1050. .backgroundImage(this.isCustomizeBg?this.customizeBgPath:$r('app.color.start_window_background'))
  1051. .backgroundImageSize(this.isLandscape?{width:'100%'}:{ height: '100%'})
  1052. .backgroundImagePosition(Alignment.Center)
  1053. .backdropBlur(this.blurValue)
  1054. .backgroundBrightness({rate:this.isCustomizeBg?0.1:0,lightUpDegree:this.bgBrightness})
  1055. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM])
  1056. }
  1057. @Builder
  1058. breaker() {
  1059. // 面包屑导航
  1060. Column({ space: 8 }) {
  1061. // 面包屑导航
  1062. if (this.webdavManager.currentPath !== '') {
  1063. Row({ space: 8 }) {
  1064. Button({ type: ButtonType.Circle }) {
  1065. Image(this.webdavManager.canGoBack()?$r('app.media.back'):
  1066. this.selectedAccount.coverPath?this.selectedAccount.coverPath:getCloudDiskIcon(this.selectedAccount.webType))
  1067. .width(15)
  1068. .height(15)
  1069. .borderRadius(10)
  1070. .alt($r('app.media.cloudDisk'))
  1071. .fillColor(Color.White)
  1072. }
  1073. .width(20)
  1074. .height(20)
  1075. .margin({left:5})
  1076. .backgroundColor(this.themeColor)
  1077. .onClick(() => this.goBack())
  1078. Row({ space: 4 }) {
  1079. ForEach(this.breadcrumbs, (crumb: BreadcrumbItem, index: number) => {
  1080. Row() {
  1081. Text(crumb.label)
  1082. .fontSize(15)
  1083. .fontColor($r('app.color.text_color'))
  1084. .maxLines(1)
  1085. .textOverflow({ overflow: TextOverflow.Ellipsis })
  1086. }
  1087. .onClick(() => {
  1088. this.navigateToBreadcrumb(crumb);
  1089. })
  1090. // 添加分隔符(除了最后一个元素)
  1091. if (index < this.breadcrumbs.length - 1) {
  1092. Text('/')
  1093. .fontSize(15)
  1094. .fontColor($r('app.color.index_tab_font_color'))
  1095. .opacity(0.6)
  1096. }
  1097. })
  1098. }
  1099. .layoutWeight(1)
  1100. }
  1101. .width('100%')
  1102. .padding({ left: 4, right: 4 })
  1103. }
  1104. }
  1105. .width('100%')
  1106. .padding({ left: 12, right: 12, top: 8, bottom: 5 })
  1107. }
  1108. // 空状态视图
  1109. @Builder
  1110. buildEmptyView() {
  1111. Column({ space: 20 }) {
  1112. Image($r('app.media.cloudDisk'))
  1113. .width(120)
  1114. .height(120)
  1115. .opacity(0.3)
  1116. Text(`暂无${getRemoteDriveAccountLabel()}`)
  1117. .fontSize(16)
  1118. .fontColor($r('app.color.index_tab_font_color'))
  1119. .opacity(0.6)
  1120. }
  1121. .justifyContent(FlexAlign.Center)
  1122. .width('100%')
  1123. .padding({top: this.topSafeHeight+160})
  1124. .layoutWeight(1)
  1125. }
  1126. // 内容视图
  1127. @Builder
  1128. buildContentView() {
  1129. Column() {
  1130. // 加载状态
  1131. Row() {
  1132. LoadingProgress()
  1133. .width(30)
  1134. .height(30)
  1135. .color(this.themeColor)
  1136. Text('加载中...')
  1137. .fontSize(14)
  1138. .fontColor($r('app.color.index_tab_font_color'))
  1139. .margin({ left: 12 })
  1140. }
  1141. .padding({top: this.topSafeHeight + 90, left: 20, right: 20})
  1142. .visibility(this.isLoading?Visibility.Visible:Visibility.None)
  1143. .opacity(this.isLoading ? 1 : 0)
  1144. .animation({
  1145. duration: 800,
  1146. curve: Curve.Smooth // 可选动画曲线
  1147. })
  1148. // 文件列表(文件夹 + 歌曲)
  1149. if (this.webDavFiles.length > 0) {
  1150. List({ scroller: this.listScroller ,space: 0 }) {
  1151. // 显示文件夹 - 只显示当前目录下的直接子文件夹
  1152. ForEach(this.isSearchMode ? this.filteredFolderList : this.visibleFoldersState, (folder: FileInfo) => {
  1153. ListItem() {
  1154. this.buildFolderItem(folder)
  1155. }
  1156. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 600 }),
  1157. TransitionEffect.scale({ x: 0, y: 0 })))
  1158. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  1159. }, (folder: FileInfo) => folder.name+folder.fileName)
  1160. // 显示歌曲
  1161. LazyForEach(this.dataSource, (song: VideoItem, index: number) => {
  1162. ListItem() {
  1163. this.buildSongItem(song, index)
  1164. }
  1165. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 600 }),
  1166. TransitionEffect.scale({ x: 0, y: 0 })))
  1167. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  1168. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  1169. }
  1170. .scrollBar(BarState.Off)
  1171. .onScrollFrameBegin((offset: number) => {
  1172. // 获取当前滚动偏移量
  1173. if(this.autoHideTitle){
  1174. const currentOffsetY = this.listScroller.currentOffset().yOffset;
  1175. // 判断滚动方向
  1176. if (currentOffsetY > this.prevOffsetY) {
  1177. console.log("onecold 向上滚动");
  1178. this.isShowTitleBar = false
  1179. } else if (currentOffsetY < this.prevOffsetY) {
  1180. console.log("onecold 向下滚动");
  1181. this.isShowTitleBar = true
  1182. }
  1183. // 更新前一次偏移量
  1184. this.prevOffsetY = currentOffsetY;
  1185. }
  1186. return { offsetRemain: offset };
  1187. })
  1188. .contentStartOffset(this.topSafeHeight + 85)
  1189. .contentEndOffset(this.bottomSafeHeight+70)
  1190. .layoutWeight(1)
  1191. .margin({ top: 4 })
  1192. } else if (!this.isLoading) {
  1193. Column() {
  1194. Text('暂无内容')
  1195. .fontSize(14)
  1196. .fontColor($r('app.color.index_tab_font_color'))
  1197. .opacity(0.6)
  1198. Text('点击"左侧菜单"网盘加载')
  1199. .fontSize(12)
  1200. .fontColor($r('app.color.index_tab_font_color'))
  1201. .opacity(0.4)
  1202. .margin({ top: 8 })
  1203. }
  1204. .justifyContent(FlexAlign.Center)
  1205. .layoutWeight(1)
  1206. }
  1207. }
  1208. .layoutWeight(1)
  1209. }
  1210. @Builder
  1211. private buildMultiSelectBar() {
  1212. Row({ space: 12 }) {
  1213. Button(this.isAllSelected ? '反选' : '全选', { type: ButtonType.Circle, stateEffect: true })
  1214. .width(55)
  1215. .height(55)
  1216. .fontSize(13)
  1217. .backgroundColor(this.themeColor)
  1218. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  1219. .onClick(() => this.toggleSelectAll())
  1220. Button('删除', { type: ButtonType.Circle, stateEffect: true })
  1221. .width(55)
  1222. .height(55)
  1223. .fontSize(13)
  1224. .backgroundColor(this.themeColor)
  1225. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  1226. .enabled(this.selectedSongs.length > 0 && !this.isDeletingSelection)
  1227. .onClick(() => this.confirmDeleteSelected())
  1228. Button('取消', { type: ButtonType.Circle, stateEffect: true })
  1229. .width(55)
  1230. .height(55)
  1231. .fontSize(13)
  1232. .backgroundColor(this.themeColor)
  1233. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  1234. .onClick(() => this.exitMultiSelect())
  1235. }
  1236. .width('100%')
  1237. .padding({ bottom: 10, top: 12 })
  1238. .justifyContent(FlexAlign.Center)
  1239. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  1240. .opacity(this.isMultiSelect ? 1 : 0)
  1241. .animation({ duration: 300, curve: 'ease-in-out' })
  1242. }
  1243. @Builder
  1244. private buildSelectionOverlay() {
  1245. Column() {
  1246. Row({ space: 10 }) {
  1247. LoadingProgress()
  1248. .width(22)
  1249. .height(22)
  1250. .color(this.themeColor)
  1251. Text('正在删除...')
  1252. .fontSize(14)
  1253. .fontColor($r('app.color.index_tab_font_color'))
  1254. }
  1255. .padding({ top: 12, bottom: 6 })
  1256. .justifyContent(FlexAlign.Center)
  1257. .visibility(this.isDeletingSelection ? Visibility.Visible : Visibility.None)
  1258. this.buildMultiSelectBar()
  1259. }
  1260. .width('100%')
  1261. .padding({ left: 12, right: 12, bottom: this.bottomSafeHeight })
  1262. }
  1263. // 文件夹列表项
  1264. @Builder
  1265. buildFolderItem(folder: FileInfo) {
  1266. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  1267. Row({ space: 2 }) {
  1268. SymbolGlyph($r('sys.symbol.folder'))
  1269. .fontSize(48)
  1270. .fontColor([this.themeColor])
  1271. .alignSelf(ItemAlign.Center)
  1272. .margin({ left: 8, right: 6 })
  1273. // 文件夹信息
  1274. Column({ space: 4 }) {
  1275. Text(decodeUrlEncodedString(folder.fileName.replace('/', '')))
  1276. .fontSize(15)
  1277. .fontColor($r('app.color.index_tab_font_color'))
  1278. .maxLines(1)
  1279. .textOverflow({ overflow: TextOverflow.Ellipsis })
  1280. Text('文件夹')
  1281. .fontSize(13)
  1282. .fontColor($r('app.color.index_tab_font_color'))
  1283. .opacity(0.6)
  1284. }
  1285. .alignItems(HorizontalAlign.Start)
  1286. .layoutWeight(1)
  1287. }
  1288. }
  1289. .reuseId('dir_item')
  1290. .width('100%')
  1291. .padding(12)
  1292. .backgroundColor(Color.Transparent)
  1293. // .backgroundColor($r('app.color.start_window_background'))
  1294. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.8 })
  1295. .onClick(() => {
  1296. this.enterFolder(folder);
  1297. this.breadcrumbs = this.webdavManager.getBreadcrumbs();
  1298. })
  1299. }
  1300. // 歌曲列表项
  1301. @Builder
  1302. buildSongItem(song: VideoItem, index: number) {
  1303. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  1304. Row({ space: 12 }) {
  1305. // 序号
  1306. // 歌曲封面
  1307. Image(song.pixelMapPath ? song.pixelMapPath : $r('app.media.alt'))
  1308. .width(52)
  1309. .height(52)
  1310. .borderRadius(9)
  1311. .sourceSize({width:38, height:38})
  1312. .alt($r('app.media.alt'))
  1313. .fillColor(this.themeColor)
  1314. .objectFit(ImageFit.Cover)
  1315. .shadow({
  1316. radius: StrUtil.isEmpty(song.pixelMapPath) ?6:14,
  1317. type: ShadowType.BLUR,
  1318. color: 'on_primary'
  1319. })
  1320. .margin({ left: 8 })
  1321. .onClick(() => {
  1322. if (this.isMultiSelect) {
  1323. this.toggleSongSelection(song);
  1324. } else {
  1325. this.playSong(song, index, true);
  1326. }
  1327. })
  1328. // 歌曲信息
  1329. Column({ space: 4 }) {
  1330. Text(this.isShowFileName?song.fileName :song.name)
  1331. .fontSize(15)
  1332. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  1333. .fontColor(this.currentSong?.filePath==song.filePath?this.themeColor:$r('app.color.index_tab_font_color'))
  1334. .maxLines(1)
  1335. .textOverflow({ overflow: TextOverflow.Ellipsis })
  1336. Row(){
  1337. Text((song.artist ?? '') + " ")
  1338. .fontSize(13)
  1339. .fontColor(this.currentSong?.filePath==song.filePath?this.themeColor:$r('app.color.index_tab_font_color'))
  1340. .opacity(0.6)
  1341. .maxLines(1)
  1342. .visibility(song.artist?Visibility.Visible:Visibility.None)
  1343. .textOverflow({ overflow: TextOverflow.Ellipsis })
  1344. Text(this.buildSongMetaLine(song))
  1345. .fontSize(13)
  1346. .fontColor(this.currentSong?.filePath==song.filePath?this.themeColor:
  1347. $r('app.color.index_tab_font_color'))
  1348. .opacity(0.6)
  1349. .maxLines(1)
  1350. .textOverflow({ overflow: TextOverflow.Ellipsis })
  1351. }
  1352. .width('90%')
  1353. }
  1354. .alignItems(HorizontalAlign.Start)
  1355. .layoutWeight(1)
  1356. .padding({ right: 20 })
  1357. Column() {
  1358. Checkbox({ name: 'checkbox_' + index })
  1359. .select(this.isSongSelected(song))
  1360. .selectedColor(this.themeColor)
  1361. .opacity(this.isMultiSelect ? 1 : 0)
  1362. .animation({
  1363. duration: 300,
  1364. curve: 'Smooth'
  1365. })
  1366. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  1367. .onChange((checked: boolean) => this.handleCheckboxSelection(song, checked))
  1368. .margin({ left: 10, top: 8, bottom: 8, right: 12 })
  1369. .width(22)
  1370. .height(22)
  1371. ImageAnimator()
  1372. .images(CommonConstants.IMAGE_FRAME_INFO)// 动画数组
  1373. .duration(1000)// 持续
  1374. //.state(this.animationState)// 动画状态
  1375. .state(AnimationStatus.Running)// 动画状态
  1376. .fillMode(FillMode.Forwards)
  1377. .width(18)
  1378. .margin({ right: 12, top: 8, bottom: 8 })
  1379. .visibility(this.currentSong?.filePath==song.filePath ? (this.isMultiSelect ? Visibility.None : Visibility.Visible) :
  1380. Visibility.None)
  1381. .height(18)
  1382. .iterations(-1) // 播放次数
  1383. }
  1384. }
  1385. }
  1386. .width('100%')
  1387. .padding(12)
  1388. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.8 })
  1389. .backgroundColor(Color.Transparent)
  1390. .onClick(() => {
  1391. if (this.isMultiSelect) {
  1392. this.toggleSongSelection(song);
  1393. } else {
  1394. this.playSong(song, index);
  1395. }
  1396. })
  1397. .gesture(LongPressGesture().onAction(() => {
  1398. this.enterMultiSelect(song);
  1399. }))
  1400. }
  1401. }