PlayQueueHelper.ets 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import { StrUtil } from '@pura/harmony-utils'
  2. import { VideoItem } from '../../viewmodel/VideoItem'
  3. export enum QueueInsertStatus {
  4. INVALID_SONG = 0,
  5. START_PLAY = 1,
  6. INSERTED = 2,
  7. ALREADY_PLAYING = 3
  8. }
  9. export interface QueueInsertResult {
  10. status: QueueInsertStatus
  11. queue: VideoItem[]
  12. currentIndex: number
  13. insertedIndex: number
  14. }
  15. function resolveCurrentQueueIndex(queue: VideoItem[], currentFilePath: string, fallbackIndex: number): number {
  16. if (queue.length <= 0) {
  17. return -1
  18. }
  19. if (StrUtil.isNotEmpty(currentFilePath)) {
  20. const queueIndex = queue.findIndex((item: VideoItem) => item.filePath === currentFilePath)
  21. if (queueIndex >= 0) {
  22. return queueIndex
  23. }
  24. }
  25. if (fallbackIndex >= 0 && fallbackIndex < queue.length) {
  26. return fallbackIndex
  27. }
  28. return 0
  29. }
  30. export function insertSongToNextPlayQueue(queue: VideoItem[], currentFilePath: string, fallbackIndex: number,
  31. song: VideoItem): QueueInsertResult {
  32. if (!song || StrUtil.isEmpty(song.filePath)) {
  33. return {
  34. status: QueueInsertStatus.INVALID_SONG,
  35. queue: queue.slice(),
  36. currentIndex: resolveCurrentQueueIndex(queue, currentFilePath, fallbackIndex),
  37. insertedIndex: -1
  38. }
  39. }
  40. if (queue.length <= 0) {
  41. return {
  42. status: QueueInsertStatus.START_PLAY,
  43. queue: [song],
  44. currentIndex: 0,
  45. insertedIndex: 0
  46. }
  47. }
  48. const nextQueue = queue.slice()
  49. let currentIndex = resolveCurrentQueueIndex(nextQueue, currentFilePath, fallbackIndex)
  50. const currentPath = currentIndex >= 0 && currentIndex < nextQueue.length ? nextQueue[currentIndex].filePath : ''
  51. if (song.filePath === currentPath) {
  52. return {
  53. status: QueueInsertStatus.ALREADY_PLAYING,
  54. queue: nextQueue,
  55. currentIndex,
  56. insertedIndex: currentIndex
  57. }
  58. }
  59. const existingIndex = nextQueue.findIndex((item: VideoItem) => item.filePath === song.filePath)
  60. if (existingIndex >= 0) {
  61. const movedSong = nextQueue.splice(existingIndex, 1)[0]
  62. if (existingIndex < currentIndex) {
  63. currentIndex -= 1
  64. }
  65. nextQueue.splice(currentIndex + 1, 0, movedSong)
  66. } else {
  67. nextQueue.splice(currentIndex + 1, 0, song)
  68. }
  69. return {
  70. status: QueueInsertStatus.INSERTED,
  71. queue: nextQueue,
  72. currentIndex,
  73. insertedIndex: currentIndex + 1
  74. }
  75. }