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 import { AccountModelId } from '../../typings/models'
23 function playlistObjectToDBAttributes (playlistObject: PlaylistObject, byAccount: AccountModelId, to: string[]) {
24 const privacy = to.indexOf(ACTIVITY_PUB.PUBLIC) !== -1 ? VideoPlaylistPrivacy.PUBLIC : VideoPlaylistPrivacy.UNLISTED
27 name: playlistObject.name,
28 description: playlistObject.content,
30 url: playlistObject.id,
31 uuid: playlistObject.uuid,
32 ownerAccountId: byAccount.id,
34 createdAt: new Date(playlistObject.published),
35 updatedAt: new Date(playlistObject.updated)
39 function playlistElementObjectToDBAttributes (elementObject: PlaylistElementObject, videoPlaylist: VideoPlaylistModel, video: VideoModel) {
41 position: elementObject.position,
42 url: elementObject.id,
43 startTimestamp: elementObject.startTimestamp || null,
44 stopTimestamp: elementObject.stopTimestamp || null,
45 videoPlaylistId: videoPlaylist.id,
50 async function createAccountPlaylists (playlistUrls: string[], account: AccountModel) {
51 await Bluebird.map(playlistUrls, async playlistUrl => {
53 const exists = await VideoPlaylistModel.doesPlaylistExist(playlistUrl)
54 if (exists === true) return
57 const { body } = await doRequest<PlaylistObject>({
63 if (!isPlaylistObjectValid(body)) {
64 throw new Error(`Invalid playlist object when fetch account playlists: ${JSON.stringify(body)}`)
67 if (!isArray(body.to)) {
68 throw new Error('Playlist does not have an audience.')
71 return createOrUpdateVideoPlaylist(body, account, body.to)
73 logger.warn('Cannot add playlist element %s.', playlistUrl, { err })
75 }, { concurrency: CRAWL_REQUEST_CONCURRENCY })
78 async function createOrUpdateVideoPlaylist (playlistObject: PlaylistObject, byAccount: AccountModelId, to: string[]) {
79 const playlistAttributes = playlistObjectToDBAttributes(playlistObject, byAccount, to)
81 if (isArray(playlistObject.attributedTo) && playlistObject.attributedTo.length === 1) {
82 const actor = await getOrCreateActorAndServerAndModel(playlistObject.attributedTo[0])
84 if (actor.VideoChannel) {
85 playlistAttributes.videoChannelId = actor.VideoChannel.id
87 logger.warn('Attributed to of video playlist %s is not a video channel.', playlistObject.id, { playlistObject })
91 const [ playlist ] = await VideoPlaylistModel.upsert<VideoPlaylistModel>(playlistAttributes, { returning: true })
93 let accItems: string[] = []
94 await crawlCollectionPage<string>(playlistObject.id, items => {
95 accItems = accItems.concat(items)
97 return Promise.resolve()
100 const refreshedPlaylist = await VideoPlaylistModel.loadWithAccountAndChannel(playlist.id, null)
102 if (playlistObject.icon) {
104 const thumbnailModel = await createPlaylistMiniatureFromUrl(playlistObject.icon.url, refreshedPlaylist)
105 await refreshedPlaylist.setAndSaveThumbnail(thumbnailModel, undefined)
107 logger.warn('Cannot generate thumbnail of %s.', playlistObject.id, { err })
109 } else if (refreshedPlaylist.hasThumbnail()) {
110 await refreshedPlaylist.Thumbnail.destroy()
111 refreshedPlaylist.Thumbnail = null
114 return resetVideoPlaylistElements(accItems, refreshedPlaylist)
117 async function refreshVideoPlaylistIfNeeded (videoPlaylist: VideoPlaylistModel): Promise<VideoPlaylistModel> {
118 if (!videoPlaylist.isOutdated()) return videoPlaylist
121 const { statusCode, playlistObject } = await fetchRemoteVideoPlaylist(videoPlaylist.url)
122 if (statusCode === 404) {
123 logger.info('Cannot refresh remote video playlist %s: it does not exist anymore. Deleting it.', videoPlaylist.url)
125 await videoPlaylist.destroy()
129 if (playlistObject === undefined) {
130 logger.warn('Cannot refresh remote playlist %s: invalid body.', videoPlaylist.url)
132 await videoPlaylist.setAsRefreshed()
136 const byAccount = videoPlaylist.OwnerAccount
137 await createOrUpdateVideoPlaylist(playlistObject, byAccount, playlistObject.to)
141 logger.warn('Cannot refresh video playlist %s.', videoPlaylist.url, { err })
143 await videoPlaylist.setAsRefreshed()
148 // ---------------------------------------------------------------------------
151 createAccountPlaylists,
152 playlistObjectToDBAttributes,
153 playlistElementObjectToDBAttributes,
154 createOrUpdateVideoPlaylist,
155 refreshVideoPlaylistIfNeeded
158 // ---------------------------------------------------------------------------
160 async function resetVideoPlaylistElements (elementUrls: string[], playlist: VideoPlaylistModel) {
161 const elementsToCreate: FilteredModelAttributes<VideoPlaylistElementModel>[] = []
163 await Bluebird.map(elementUrls, async elementUrl => {
166 const { body } = await doRequest<PlaylistElementObject>({
172 if (!isPlaylistElementObjectValid(body)) throw new Error(`Invalid body in video get playlist element ${elementUrl}`)
174 if (checkUrlsSameHost(body.id, elementUrl) !== true) {
175 throw new Error(`Playlist element url ${elementUrl} host is different from the AP object id ${body.id}`)
178 const { video } = await getOrCreateVideoAndAccountAndChannel({ videoObject: { id: body.url }, fetchType: 'only-video' })
180 elementsToCreate.push(playlistElementObjectToDBAttributes(body, playlist, video))
182 logger.warn('Cannot add playlist element %s.', elementUrl, { err })
184 }, { concurrency: CRAWL_REQUEST_CONCURRENCY })
186 await sequelizeTypescript.transaction(async t => {
187 await VideoPlaylistElementModel.deleteAllOf(playlist.id, t)
189 for (const element of elementsToCreate) {
190 await VideoPlaylistElementModel.create(element, { transaction: t })
194 logger.info('Reset playlist %s with %s elements.', playlist.url, elementsToCreate.length)
199 async function fetchRemoteVideoPlaylist (playlistUrl: string): Promise<{ statusCode: number, playlistObject: PlaylistObject }> {
207 logger.info('Fetching remote playlist %s.', playlistUrl)
209 const { response, body } = await doRequest(options)
211 if (isPlaylistObjectValid(body) === false || checkUrlsSameHost(body.id, playlistUrl) !== true) {
212 logger.debug('Remote video playlist JSON is not valid.', { body })
213 return { statusCode: response.statusCode, playlistObject: undefined }
216 return { statusCode: response.statusCode, playlistObject: body }