video-playlist.service.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. import * as debug from 'debug'
  2. import { merge, Observable, of, ReplaySubject, Subject } from 'rxjs'
  3. import { catchError, filter, map, share, switchMap, tap } from 'rxjs/operators'
  4. import { HttpClient, HttpContext, HttpParams } from '@angular/common/http'
  5. import { Injectable } from '@angular/core'
  6. import { AuthService, AuthUser, ComponentPaginationLight, RestExtractor, RestService, ServerService } from '@app/core'
  7. import { buildBulkObservable, objectToFormData } from '@app/helpers'
  8. import { Account, AccountService, VideoChannel, VideoChannelService } from '@app/shared/shared-main'
  9. import { NGX_LOADING_BAR_IGNORED } from '@ngx-loading-bar/http-client'
  10. import {
  11. CachedVideoExistInPlaylist,
  12. CachedVideosExistInPlaylists,
  13. ResultList,
  14. VideoExistInPlaylist,
  15. VideoPlaylist as VideoPlaylistServerModel,
  16. VideoPlaylistCreate,
  17. VideoPlaylistElement as ServerVideoPlaylistElement,
  18. VideoPlaylistElementCreate,
  19. VideoPlaylistElementUpdate,
  20. VideoPlaylistReorder,
  21. VideoPlaylistUpdate,
  22. VideosExistInPlaylists
  23. } from '@shared/models'
  24. import { environment } from '../../../environments/environment'
  25. import { VideoPlaylistElement } from './video-playlist-element.model'
  26. import { VideoPlaylist } from './video-playlist.model'
  27. const debugLogger = debug('peertube:playlists:VideoPlaylistService')
  28. export type CachedPlaylist = VideoPlaylist | { id: number, displayName: string }
  29. @Injectable()
  30. export class VideoPlaylistService {
  31. static BASE_VIDEO_PLAYLIST_URL = environment.apiUrl + '/api/v1/video-playlists/'
  32. static MY_VIDEO_PLAYLIST_URL = environment.apiUrl + '/api/v1/users/me/video-playlists/'
  33. // Use a replay subject because we "next" a value before subscribing
  34. private videoExistsInPlaylistNotifier = new ReplaySubject<number>(1)
  35. private videoExistsInPlaylistCacheSubject = new Subject<CachedVideosExistInPlaylists>()
  36. private readonly videoExistsInPlaylistObservable: Observable<CachedVideosExistInPlaylists>
  37. private videoExistsObservableCache: { [ id: number ]: Observable<CachedVideoExistInPlaylist[]> } = {}
  38. private videoExistsCache: { [ id: number ]: CachedVideoExistInPlaylist[] } = {}
  39. private myAccountPlaylistCache: ResultList<CachedPlaylist> = undefined
  40. private myAccountPlaylistCacheRunning: Observable<ResultList<CachedPlaylist>>
  41. private myAccountPlaylistCacheSubject = new Subject<ResultList<CachedPlaylist>>()
  42. constructor (
  43. private authHttp: HttpClient,
  44. private auth: AuthService,
  45. private serverService: ServerService,
  46. private restExtractor: RestExtractor,
  47. private restService: RestService
  48. ) {
  49. this.videoExistsInPlaylistObservable = merge(
  50. buildBulkObservable({
  51. time: 500,
  52. bulkGet: (videoIds: number[]) => {
  53. // We added a delay to the request, so ensure the user is still logged in
  54. if (this.auth.isLoggedIn()) {
  55. return this.doVideosExistInPlaylist(videoIds)
  56. }
  57. return of({})
  58. },
  59. notifierObservable: this.videoExistsInPlaylistNotifier
  60. }).pipe(map(({ response }) => response)),
  61. this.videoExistsInPlaylistCacheSubject
  62. )
  63. }
  64. listChannelPlaylists (videoChannel: VideoChannel, componentPagination: ComponentPaginationLight): Observable<ResultList<VideoPlaylist>> {
  65. const url = VideoChannelService.BASE_VIDEO_CHANNEL_URL + videoChannel.nameWithHost + '/video-playlists'
  66. const pagination = this.restService.componentToRestPagination(componentPagination)
  67. let params = new HttpParams()
  68. params = this.restService.addRestGetParams(params, pagination)
  69. return this.authHttp.get<ResultList<VideoPlaylist>>(url, { params })
  70. .pipe(
  71. switchMap(res => this.extractPlaylists(res)),
  72. catchError(err => this.restExtractor.handleError(err))
  73. )
  74. }
  75. listMyPlaylistWithCache (user: AuthUser, search?: string) {
  76. if (!search) {
  77. if (this.myAccountPlaylistCacheRunning) return this.myAccountPlaylistCacheRunning
  78. if (this.myAccountPlaylistCache) return of(this.myAccountPlaylistCache)
  79. }
  80. const obs = this.listAccountPlaylists(user.account, undefined, '-updatedAt', search)
  81. .pipe(
  82. tap(result => {
  83. if (!search) {
  84. this.myAccountPlaylistCacheRunning = undefined
  85. this.myAccountPlaylistCache = result
  86. }
  87. }),
  88. share()
  89. )
  90. if (!search) this.myAccountPlaylistCacheRunning = obs
  91. return obs
  92. }
  93. listAccountPlaylists (
  94. account: Account,
  95. componentPagination: ComponentPaginationLight,
  96. sort: string,
  97. search?: string
  98. ): Observable<ResultList<VideoPlaylist>> {
  99. const url = AccountService.BASE_ACCOUNT_URL + account.nameWithHost + '/video-playlists'
  100. const pagination = componentPagination
  101. ? this.restService.componentToRestPagination(componentPagination)
  102. : undefined
  103. let params = new HttpParams()
  104. params = this.restService.addRestGetParams(params, pagination, sort)
  105. if (search) params = this.restService.addObjectParams(params, { search })
  106. return this.authHttp.get<ResultList<VideoPlaylist>>(url, { params })
  107. .pipe(
  108. switchMap(res => this.extractPlaylists(res)),
  109. catchError(err => this.restExtractor.handleError(err))
  110. )
  111. }
  112. getVideoPlaylist (id: string | number) {
  113. const url = VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + id
  114. return this.authHttp.get<VideoPlaylist>(url)
  115. .pipe(
  116. switchMap(res => this.extractPlaylist(res)),
  117. catchError(err => this.restExtractor.handleError(err))
  118. )
  119. }
  120. createVideoPlaylist (body: VideoPlaylistCreate) {
  121. const data = objectToFormData(body)
  122. return this.authHttp.post<{ videoPlaylist: { id: number } }>(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL, data)
  123. .pipe(
  124. tap(res => {
  125. if (!this.myAccountPlaylistCache) return
  126. this.myAccountPlaylistCache.total++
  127. this.myAccountPlaylistCache.data.push({
  128. id: res.videoPlaylist.id,
  129. displayName: body.displayName
  130. })
  131. this.myAccountPlaylistCacheSubject.next(this.myAccountPlaylistCache)
  132. }),
  133. catchError(err => this.restExtractor.handleError(err))
  134. )
  135. }
  136. updateVideoPlaylist (videoPlaylist: VideoPlaylist, body: VideoPlaylistUpdate) {
  137. const data = objectToFormData(body)
  138. return this.authHttp.put(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + videoPlaylist.id, data)
  139. .pipe(
  140. tap(() => {
  141. if (!this.myAccountPlaylistCache) return
  142. const playlist = this.myAccountPlaylistCache.data.find(p => p.id === videoPlaylist.id)
  143. playlist.displayName = body.displayName
  144. this.myAccountPlaylistCacheSubject.next(this.myAccountPlaylistCache)
  145. }),
  146. catchError(err => this.restExtractor.handleError(err))
  147. )
  148. }
  149. removeVideoPlaylist (videoPlaylist: VideoPlaylist) {
  150. return this.authHttp.delete(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + videoPlaylist.id)
  151. .pipe(
  152. tap(() => {
  153. if (!this.myAccountPlaylistCache) return
  154. this.myAccountPlaylistCache.total--
  155. this.myAccountPlaylistCache.data = this.myAccountPlaylistCache.data
  156. .filter(p => p.id !== videoPlaylist.id)
  157. this.myAccountPlaylistCacheSubject.next(this.myAccountPlaylistCache)
  158. }),
  159. catchError(err => this.restExtractor.handleError(err))
  160. )
  161. }
  162. addVideoInPlaylist (playlistId: number, body: VideoPlaylistElementCreate) {
  163. const url = VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + playlistId + '/videos'
  164. return this.authHttp.post<{ videoPlaylistElement: { id: number } }>(url, body)
  165. .pipe(
  166. tap(res => {
  167. const existsResult = this.videoExistsCache[body.videoId]
  168. existsResult.push({
  169. playlistId,
  170. playlistElementId: res.videoPlaylistElement.id,
  171. startTimestamp: body.startTimestamp,
  172. stopTimestamp: body.stopTimestamp
  173. })
  174. this.runPlaylistCheck(body.videoId)
  175. }),
  176. catchError(err => this.restExtractor.handleError(err))
  177. )
  178. }
  179. updateVideoOfPlaylist (playlistId: number, playlistElementId: number, body: VideoPlaylistElementUpdate, videoId: number) {
  180. return this.authHttp.put(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + playlistId + '/videos/' + playlistElementId, body)
  181. .pipe(
  182. tap(() => {
  183. const existsResult = this.videoExistsCache[videoId]
  184. if (existsResult) {
  185. const elem = existsResult.find(e => e.playlistElementId === playlistElementId)
  186. elem.startTimestamp = body.startTimestamp
  187. elem.stopTimestamp = body.stopTimestamp
  188. }
  189. this.runPlaylistCheck(videoId)
  190. }),
  191. catchError(err => this.restExtractor.handleError(err))
  192. )
  193. }
  194. removeVideoFromPlaylist (playlistId: number, playlistElementId: number, videoId?: number) {
  195. return this.authHttp.delete(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + playlistId + '/videos/' + playlistElementId)
  196. .pipe(
  197. tap(() => {
  198. if (!videoId) return
  199. if (this.videoExistsCache[videoId]) {
  200. this.videoExistsCache[videoId] = this.videoExistsCache[videoId]
  201. .filter(e => e.playlistElementId !== playlistElementId)
  202. }
  203. this.runPlaylistCheck(videoId)
  204. }),
  205. catchError(err => this.restExtractor.handleError(err))
  206. )
  207. }
  208. reorderPlaylist (playlistId: number, oldPosition: number, newPosition: number) {
  209. const body: VideoPlaylistReorder = {
  210. startPosition: oldPosition,
  211. insertAfterPosition: newPosition
  212. }
  213. return this.authHttp.post(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + playlistId + '/videos/reorder', body)
  214. .pipe(catchError(err => this.restExtractor.handleError(err)))
  215. }
  216. getPlaylistVideos (options: {
  217. videoPlaylistId: number | string
  218. componentPagination: ComponentPaginationLight
  219. }): Observable<ResultList<VideoPlaylistElement>> {
  220. const path = VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + options.videoPlaylistId + '/videos'
  221. const pagination = this.restService.componentToRestPagination(options.componentPagination)
  222. let params = new HttpParams()
  223. params = this.restService.addRestGetParams(params, pagination)
  224. return this.authHttp
  225. .get<ResultList<ServerVideoPlaylistElement>>(path, { params })
  226. .pipe(
  227. switchMap(res => this.extractVideoPlaylistElements(res)),
  228. catchError(err => this.restExtractor.handleError(err))
  229. )
  230. }
  231. listenToMyAccountPlaylistsChange () {
  232. return this.myAccountPlaylistCacheSubject.asObservable()
  233. }
  234. listenToVideoPlaylistChange (videoId: number) {
  235. if (this.videoExistsObservableCache[videoId]) {
  236. return this.videoExistsObservableCache[videoId]
  237. }
  238. const obs = this.videoExistsInPlaylistObservable
  239. .pipe(
  240. map(existsResult => existsResult[videoId]),
  241. filter(r => !!r),
  242. tap(result => this.videoExistsCache[videoId] = result)
  243. )
  244. this.videoExistsObservableCache[videoId] = obs
  245. return obs
  246. }
  247. runPlaylistCheck (videoId: number) {
  248. debugLogger('Running playlist check.')
  249. if (this.videoExistsCache[videoId]) {
  250. debugLogger('Found cache for %d.', videoId)
  251. return this.videoExistsInPlaylistCacheSubject.next({ [videoId]: this.videoExistsCache[videoId] })
  252. }
  253. debugLogger('Fetching from network for %d.', videoId)
  254. return this.videoExistsInPlaylistNotifier.next(videoId)
  255. }
  256. extractPlaylists (result: ResultList<VideoPlaylistServerModel>) {
  257. return this.serverService.getServerLocale()
  258. .pipe(
  259. map(translations => {
  260. const playlistsJSON = result.data
  261. const total = result.total
  262. const playlists: VideoPlaylist[] = []
  263. for (const playlistJSON of playlistsJSON) {
  264. playlists.push(new VideoPlaylist(playlistJSON, translations))
  265. }
  266. return { data: playlists, total }
  267. })
  268. )
  269. }
  270. extractPlaylist (playlist: VideoPlaylistServerModel) {
  271. return this.serverService.getServerLocale()
  272. .pipe(map(translations => new VideoPlaylist(playlist, translations)))
  273. }
  274. extractVideoPlaylistElements (result: ResultList<ServerVideoPlaylistElement>) {
  275. return this.serverService.getServerLocale()
  276. .pipe(
  277. map(translations => {
  278. const elementsJson = result.data
  279. const total = result.total
  280. const elements: VideoPlaylistElement[] = []
  281. for (const elementJson of elementsJson) {
  282. elements.push(new VideoPlaylistElement(elementJson, translations))
  283. }
  284. return { total, data: elements }
  285. })
  286. )
  287. }
  288. doVideosExistInPlaylist (videoIds: number[]): Observable<VideosExistInPlaylists> {
  289. const url = VideoPlaylistService.MY_VIDEO_PLAYLIST_URL + 'videos-exist'
  290. let params = new HttpParams()
  291. params = this.restService.addObjectParams(params, { videoIds })
  292. return this.authHttp.get<VideoExistInPlaylist>(url, { params, context: new HttpContext().set(NGX_LOADING_BAR_IGNORED, true) })
  293. .pipe(catchError(err => this.restExtractor.handleError(err)))
  294. }
  295. }