All files / app/component/playlist playlist.component.ts

50% Statements 44/88
28.75% Branches 23/80
42.85% Functions 9/21
53.42% Lines 39/73

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 16476x                             76x           76x 76x 76x 76x 76x 76x               156x       76x 4x   4x 4x 4x 4x   4x               4x       4x 4x 4x 4x 4x   4x                                                                       4x 4x 4x 4x 4x 4x 4x 2x       4x                                                             10x 10x             3x 3x 1x     5x 5x              
import {
  ChangeDetectionStrategy,
  ChangeDetectorRef,
  Component,
  forwardRef,
  HostBinding,
  input,
  model,
  OnChanges,
  OnDestroy,
  SimpleChanges
} from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { computed } from 'mobx';
import { catchError, Observable, of, Subscription, switchMap, throwError } from 'rxjs';
import { Page } from '../../model/page';
import { Ref } from '../../model/ref';
import { AdminService } from '../../service/admin.service';
import { ProxyService } from '../../service/api/proxy.service';
import { RefService } from '../../service/api/ref.service';
import { Store } from '../../store/store';
import { downloadPlaylist } from '../../util/download';
import { getTitle } from '../../util/format';
import { getExtension } from '../../util/http';
import { hasTag } from '../../util/tag';
import { LoadingComponent } from '../loading/loading.component';
import { ViewerComponent } from '../viewer/viewer.component';
 
@Component({
  selector: 'app-playlist',
  templateUrl: './playlist.component.html',
  styleUrls: ['./playlist.component.scss'],
  changeDetection: ChangeDetectionStrategy.Eager,
  imports: [
    forwardRef(() => ViewerComponent),
    LoadingComponent,
  ],
})
export class PlaylistComponent implements OnChanges, OnDestroy {
  @HostBinding('class') css = 'playlist';
 
  ref = input<Ref | undefined>(undefined);
  index = model(0);
  repeat = model(true);
  autoplay = model(false);
 
  current = computed<Ref>(() => {
    const sources = this.sources();
    const index = this.index();
    const ref = this.ref();
    if (!sources || !ref) return { } as Ref;
    const url = ref.sources![index];
    return sources.content.find(ref => ref.url === url) || { url }
  });
  sources = model<Page<Ref> | undefined>(undefined);
  private loading?: Subscription;
 
  constructor(
    private admin: AdminService,
    private refs: RefService,
    private proxy: ProxyService,
    private store: Store,
    private cd: ChangeDetectorRef,
  ) {
    this.store.eventBus.events.pipe(takeUntilDestroyed()).subscribe(event => {
      if (event.event === 'media' && this.ref() && this.store.eventBus.isRef(event, this.ref()!) && this.sources()?.content.length) {
        const mediaList = [];
        for (const s of this.sources()!.content) {
          const file = this.getTag('plugin/file', s);
          const audio = this.getTag('plugin/audio', s);
          const video = this.getTag('plugin/video', s);
          const image = this.getTag('plugin/image', s);
          if (file) {
            mediaList.push(this.proxy.getFetch(s.url, s.origin, this.getFilename(s)));
          } else if (audio && (audio.startsWith('cache:') || this.admin.getPlugin('plugin/audio')?.config?.proxy)) {
            mediaList.push(this.proxy.getFetch(audio, s.origin, this.getFilename(s, $localize`Untitled Audio`)));
          } else if (video && (video.startsWith('cache:') || this.admin.getPlugin('plugin/video')?.config?.proxy)) {
            mediaList.push(this.proxy.getFetch(video, s.origin, this.getFilename(s, $localize`Untitled Video`)));
          } else if (image && (image.startsWith('cache:') || this.admin.getPlugin('plugin/image')?.config?.proxy)) {
            mediaList.push(this.proxy.getFetch(image, s.origin, this.getFilename(s, $localize`Untitled Image`)));
          }
        }
        downloadPlaylist(this.proxy, mediaList, this.ref()!.title || 'playlist');
      }
    });
  }
 
  getTag(tag: string, ref: Ref) {
    return this.admin.getPlugin(tag) &&
      hasTag(tag, ref) &&
      (ref?.plugins?.[tag]?.url || ref.url);
  }
 
  getFilename(ref: Ref, d = $localize`Untitled`) {
    const ext = getExtension(ref.url) || '';
    const filename = ref.title || d;
    return filename + (ext && !filename.toLowerCase().endsWith(ext) ? ext : '');
  }
 
  ngOnChanges(changes: SimpleChanges) {
    Iif (!changes.ref) return;
    this.loading?.unsubscribe();
    this.sources.set(undefined);
    const ref = changes.ref.currentValue as Ref | undefined;
    Iif (!ref?.sources?.length) return;
    this.index.set(0);
    this.loading = this.loadSources(ref.url, ref.sources.length)
      .subscribe(page => this.sources.set(page));
  }
 
  ngOnDestroy() {
    this.loading?.unsubscribe();
  }
 
  title(url?: string) {
    return getTitle(this.sources()?.content.find(s => s.url === url) || (url ? { url } : undefined));
  }
 
  seek(index: number) {
    this.index.set(index);
    this.cd.detectChanges();
  }
 
  back() {
    this.index.set((this.index() - 1 + this.ref()!.sources!.length) % this.ref()!.sources!.length);
    this.cd.detectChanges();
  }
 
  next(loop = true) {
    if (!loop && this.index() + 1 >= this.ref()!.sources!.length) return;
    this.index.set((this.index() + 1) % this.ref()!.sources!.length);
    this.cd.detectChanges();
  }
 
  private loadSources(
    url: string,
    fallbackTotalPages: number,
    size = 20,
    page = 0,
    content: Ref[] = [],
    totalPages?: number,
  ): Observable<Page<Ref>> {
    Iif (page >= (totalPages ?? fallbackTotalPages)) return of(Page.of(content));
    return this.refs.page({
      sources: url,
      page,
      size,
      sort: ['modified', 'origin'],
    }).pipe(
      switchMap(batch => {
        const next = [...content, ...batch.content];
        if (page + 1 >= batch.page.totalPages) return of(Page.of(next));
        return this.loadSources(url, fallbackTotalPages, size, page + 1, next, batch.page.totalPages);
      }),
      catchError(err => {
        Iif (err.status !== 413) return throwError(() => err);
        return size > 1
          ? this.loadSources(url, fallbackTotalPages, Math.max(1, Math.floor(size / 2)))
          : this.loadSources(url, fallbackTotalPages, size, page + 1, content, totalPages)
      }),
    );
  }
}