playlist.ts 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. import { PlaylistObject } from '../../../shared/models/activitypub/objects/playlist-object'
  2. import { crawlCollectionPage } from './crawl'
  3. import { ACTIVITY_PUB, CRAWL_REQUEST_CONCURRENCY } from '../../initializers/constants'
  4. import { AccountModel } from '../../models/account/account'
  5. import { isArray } from '../../helpers/custom-validators/misc'
  6. import { getOrCreateActorAndServerAndModel } from './actor'
  7. import { logger } from '../../helpers/logger'
  8. import { VideoPlaylistModel } from '../../models/video/video-playlist'
  9. import { doRequest } from '../../helpers/requests'
  10. import { checkUrlsSameHost } from '../../helpers/activitypub'
  11. import * as Bluebird from 'bluebird'
  12. import { PlaylistElementObject } from '../../../shared/models/activitypub/objects/playlist-element-object'
  13. import { getOrCreateVideoAndAccountAndChannel } from './videos'
  14. import { isPlaylistElementObjectValid, isPlaylistObjectValid } from '../../helpers/custom-validators/activitypub/playlist'
  15. import { VideoPlaylistElementModel } from '../../models/video/video-playlist-element'
  16. import { VideoModel } from '../../models/video/video'
  17. import { VideoPlaylistPrivacy } from '../../../shared/models/videos/playlist/video-playlist-privacy.model'
  18. import { sequelizeTypescript } from '../../initializers/database'
  19. import { createPlaylistMiniatureFromUrl } from '../thumbnail'
  20. import { FilteredModelAttributes } from '../../typings/sequelize'
  21. function playlistObjectToDBAttributes (playlistObject: PlaylistObject, byAccount: AccountModel, to: string[]) {
  22. const privacy = to.indexOf(ACTIVITY_PUB.PUBLIC) !== -1 ? VideoPlaylistPrivacy.PUBLIC : VideoPlaylistPrivacy.UNLISTED
  23. return {
  24. name: playlistObject.name,
  25. description: playlistObject.content,
  26. privacy,
  27. url: playlistObject.id,
  28. uuid: playlistObject.uuid,
  29. ownerAccountId: byAccount.id,
  30. videoChannelId: null,
  31. createdAt: new Date(playlistObject.published),
  32. updatedAt: new Date(playlistObject.updated)
  33. }
  34. }
  35. function playlistElementObjectToDBAttributes (elementObject: PlaylistElementObject, videoPlaylist: VideoPlaylistModel, video: VideoModel) {
  36. return {
  37. position: elementObject.position,
  38. url: elementObject.id,
  39. startTimestamp: elementObject.startTimestamp || null,
  40. stopTimestamp: elementObject.stopTimestamp || null,
  41. videoPlaylistId: videoPlaylist.id,
  42. videoId: video.id
  43. }
  44. }
  45. async function createAccountPlaylists (playlistUrls: string[], account: AccountModel) {
  46. await Bluebird.map(playlistUrls, async playlistUrl => {
  47. try {
  48. const exists = await VideoPlaylistModel.doesPlaylistExist(playlistUrl)
  49. if (exists === true) return
  50. // Fetch url
  51. const { body } = await doRequest<PlaylistObject>({
  52. uri: playlistUrl,
  53. json: true,
  54. activityPub: true
  55. })
  56. if (!isPlaylistObjectValid(body)) {
  57. throw new Error(`Invalid playlist object when fetch account playlists: ${JSON.stringify(body)}`)
  58. }
  59. if (!isArray(body.to)) {
  60. throw new Error('Playlist does not have an audience.')
  61. }
  62. return createOrUpdateVideoPlaylist(body, account, body.to)
  63. } catch (err) {
  64. logger.warn('Cannot add playlist element %s.', playlistUrl, { err })
  65. }
  66. }, { concurrency: CRAWL_REQUEST_CONCURRENCY })
  67. }
  68. async function createOrUpdateVideoPlaylist (playlistObject: PlaylistObject, byAccount: AccountModel, to: string[]) {
  69. const playlistAttributes = playlistObjectToDBAttributes(playlistObject, byAccount, to)
  70. if (isArray(playlistObject.attributedTo) && playlistObject.attributedTo.length === 1) {
  71. const actor = await getOrCreateActorAndServerAndModel(playlistObject.attributedTo[0])
  72. if (actor.VideoChannel) {
  73. playlistAttributes.videoChannelId = actor.VideoChannel.id
  74. } else {
  75. logger.warn('Attributed to of video playlist %s is not a video channel.', playlistObject.id, { playlistObject })
  76. }
  77. }
  78. const [ playlist ] = await VideoPlaylistModel.upsert<VideoPlaylistModel>(playlistAttributes, { returning: true })
  79. let accItems: string[] = []
  80. await crawlCollectionPage<string>(playlistObject.id, items => {
  81. accItems = accItems.concat(items)
  82. return Promise.resolve()
  83. })
  84. const refreshedPlaylist = await VideoPlaylistModel.loadWithAccountAndChannel(playlist.id, null)
  85. if (playlistObject.icon) {
  86. try {
  87. const thumbnailModel = await createPlaylistMiniatureFromUrl(playlistObject.icon.url, refreshedPlaylist)
  88. await refreshedPlaylist.setAndSaveThumbnail(thumbnailModel, undefined)
  89. } catch (err) {
  90. logger.warn('Cannot generate thumbnail of %s.', playlistObject.id, { err })
  91. }
  92. }
  93. return resetVideoPlaylistElements(accItems, refreshedPlaylist)
  94. }
  95. async function refreshVideoPlaylistIfNeeded (videoPlaylist: VideoPlaylistModel): Promise<VideoPlaylistModel> {
  96. if (!videoPlaylist.isOutdated()) return videoPlaylist
  97. try {
  98. const { statusCode, playlistObject } = await fetchRemoteVideoPlaylist(videoPlaylist.url)
  99. if (statusCode === 404) {
  100. logger.info('Cannot refresh remote video playlist %s: it does not exist anymore. Deleting it.', videoPlaylist.url)
  101. await videoPlaylist.destroy()
  102. return undefined
  103. }
  104. if (playlistObject === undefined) {
  105. logger.warn('Cannot refresh remote playlist %s: invalid body.', videoPlaylist.url)
  106. await videoPlaylist.setAsRefreshed()
  107. return videoPlaylist
  108. }
  109. const byAccount = videoPlaylist.OwnerAccount
  110. await createOrUpdateVideoPlaylist(playlistObject, byAccount, playlistObject.to)
  111. return videoPlaylist
  112. } catch (err) {
  113. logger.warn('Cannot refresh video playlist %s.', videoPlaylist.url, { err })
  114. await videoPlaylist.setAsRefreshed()
  115. return videoPlaylist
  116. }
  117. }
  118. // ---------------------------------------------------------------------------
  119. export {
  120. createAccountPlaylists,
  121. playlistObjectToDBAttributes,
  122. playlistElementObjectToDBAttributes,
  123. createOrUpdateVideoPlaylist,
  124. refreshVideoPlaylistIfNeeded
  125. }
  126. // ---------------------------------------------------------------------------
  127. async function resetVideoPlaylistElements (elementUrls: string[], playlist: VideoPlaylistModel) {
  128. const elementsToCreate: FilteredModelAttributes<VideoPlaylistElementModel>[] = []
  129. await Bluebird.map(elementUrls, async elementUrl => {
  130. try {
  131. // Fetch url
  132. const { body } = await doRequest<PlaylistElementObject>({
  133. uri: elementUrl,
  134. json: true,
  135. activityPub: true
  136. })
  137. if (!isPlaylistElementObjectValid(body)) throw new Error(`Invalid body in video get playlist element ${elementUrl}`)
  138. if (checkUrlsSameHost(body.id, elementUrl) !== true) {
  139. throw new Error(`Playlist element url ${elementUrl} host is different from the AP object id ${body.id}`)
  140. }
  141. const { video } = await getOrCreateVideoAndAccountAndChannel({ videoObject: { id: body.url }, fetchType: 'only-video' })
  142. elementsToCreate.push(playlistElementObjectToDBAttributes(body, playlist, video))
  143. } catch (err) {
  144. logger.warn('Cannot add playlist element %s.', elementUrl, { err })
  145. }
  146. }, { concurrency: CRAWL_REQUEST_CONCURRENCY })
  147. await sequelizeTypescript.transaction(async t => {
  148. await VideoPlaylistElementModel.deleteAllOf(playlist.id, t)
  149. for (const element of elementsToCreate) {
  150. await VideoPlaylistElementModel.create(element, { transaction: t })
  151. }
  152. })
  153. logger.info('Reset playlist %s with %s elements.', playlist.url, elementsToCreate.length)
  154. return undefined
  155. }
  156. async function fetchRemoteVideoPlaylist (playlistUrl: string): Promise<{ statusCode: number, playlistObject: PlaylistObject }> {
  157. const options = {
  158. uri: playlistUrl,
  159. method: 'GET',
  160. json: true,
  161. activityPub: true
  162. }
  163. logger.info('Fetching remote playlist %s.', playlistUrl)
  164. const { response, body } = await doRequest(options)
  165. if (isPlaylistObjectValid(body) === false || checkUrlsSameHost(body.id, playlistUrl) !== true) {
  166. logger.debug('Remote video playlist JSON is not valid.', { body })
  167. return { statusCode: response.statusCode, playlistObject: undefined }
  168. }
  169. return { statusCode: response.statusCode, playlistObject: body }
  170. }