+ account: MAccountIdActor,
+ channel: MChannelDefault,
+ overrideTo?: string[]
+}) {
+ const { video, videoObject, account, channel, overrideTo } = options
+
+ logger.debug('Updating remote video "%s".', options.videoObject.uuid, { account, channel })
+
+ let videoFieldsSave: any
+ const wasPrivateVideo = video.privacy === VideoPrivacy.PRIVATE
+ const wasUnlistedVideo = video.privacy === VideoPrivacy.UNLISTED
+
+ try {
+ let thumbnailModel: MThumbnail
+
+ try {
+ thumbnailModel = await createVideoMiniatureFromUrl(videoObject.icon.url, video, ThumbnailType.MINIATURE)
+ } catch (err) {
+ logger.warn('Cannot generate thumbnail of %s.', videoObject.id, { err })
+ }
+
+ const videoUpdated = await sequelizeTypescript.transaction(async t => {
+ const sequelizeOptions = { transaction: t }
+
+ videoFieldsSave = video.toJSON()
+
+ // Check actor has the right to update the video
+ const videoChannel = video.VideoChannel
+ if (videoChannel.Account.id !== account.id) {
+ throw new Error('Account ' + account.Actor.url + ' does not own video channel ' + videoChannel.Actor.url)
+ }
+
+ const to = overrideTo ? overrideTo : videoObject.to
+ const videoData = await videoActivityObjectToDBAttributes(channel, videoObject, to)
+ video.name = videoData.name
+ video.uuid = videoData.uuid
+ video.url = videoData.url
+ video.category = videoData.category
+ video.licence = videoData.licence
+ video.language = videoData.language
+ video.description = videoData.description
+ video.support = videoData.support
+ video.nsfw = videoData.nsfw
+ video.commentsEnabled = videoData.commentsEnabled
+ video.downloadEnabled = videoData.downloadEnabled
+ video.waitTranscoding = videoData.waitTranscoding
+ video.state = videoData.state
+ video.duration = videoData.duration
+ video.createdAt = videoData.createdAt
+ video.publishedAt = videoData.publishedAt
+ video.originallyPublishedAt = videoData.originallyPublishedAt
+ video.privacy = videoData.privacy
+ video.channelId = videoData.channelId
+ video.views = videoData.views
+
+ const videoUpdated = await video.save(sequelizeOptions) as MVideoFullLight
+
+ if (thumbnailModel) await videoUpdated.addAndSaveThumbnail(thumbnailModel, t)
+
+ // FIXME: use icon URL instead
+ const previewUrl = buildRemoteBaseUrl(videoUpdated, join(STATIC_PATHS.PREVIEWS, videoUpdated.getPreview().filename))
+ const previewModel = createPlaceholderThumbnail(previewUrl, video, ThumbnailType.PREVIEW, PREVIEWS_SIZE)
+ await videoUpdated.addAndSaveThumbnail(previewModel, t)
+
+ {
+ const videoFileAttributes = videoFileActivityUrlToDBAttributes(videoUpdated, videoObject.url)
+ const newVideoFiles = videoFileAttributes.map(a => new VideoFileModel(a))
+
+ // Remove video files that do not exist anymore
+ const destroyTasks = deleteNonExistingModels(videoUpdated.VideoFiles, newVideoFiles, t)
+ await Promise.all(destroyTasks)
+
+ // Update or add other one
+ const upsertTasks = newVideoFiles.map(f => VideoFileModel.customUpsert(f, 'video', t))
+ videoUpdated.VideoFiles = await Promise.all(upsertTasks)
+ }
+
+ {
+ const streamingPlaylistAttributes = streamingPlaylistActivityUrlToDBAttributes(videoUpdated, videoObject, videoUpdated.VideoFiles)
+ const newStreamingPlaylists = streamingPlaylistAttributes.map(a => new VideoStreamingPlaylistModel(a))
+
+ // Remove video playlists that do not exist anymore
+ const destroyTasks = deleteNonExistingModels(videoUpdated.VideoStreamingPlaylists, newStreamingPlaylists, t)
+ await Promise.all(destroyTasks)
+
+ let oldStreamingPlaylistFiles: MVideoFile[] = []
+ for (const videoStreamingPlaylist of videoUpdated.VideoStreamingPlaylists) {
+ oldStreamingPlaylistFiles = oldStreamingPlaylistFiles.concat(videoStreamingPlaylist.VideoFiles)
+ }
+
+ videoUpdated.VideoStreamingPlaylists = []
+
+ for (const playlistAttributes of streamingPlaylistAttributes) {
+ const streamingPlaylistModel = await VideoStreamingPlaylistModel.upsert(playlistAttributes, { returning: true, transaction: t })
+ .then(([ streamingPlaylist ]) => streamingPlaylist)
+
+ const newVideoFiles: MVideoFile[] = videoFileActivityUrlToDBAttributes(streamingPlaylistModel, playlistAttributes.tagAPObject)
+ .map(a => new VideoFileModel(a))
+ const destroyTasks = deleteNonExistingModels(oldStreamingPlaylistFiles, newVideoFiles, t)
+ await Promise.all(destroyTasks)
+
+ // Update or add other one
+ const upsertTasks = newVideoFiles.map(f => VideoFileModel.customUpsert(f, 'streaming-playlist', t))
+ streamingPlaylistModel.VideoFiles = await Promise.all(upsertTasks)
+
+ videoUpdated.VideoStreamingPlaylists.push(streamingPlaylistModel)
+ }
+ }
+
+ {
+ // Update Tags
+ const tags = videoObject.tag
+ .filter(isAPHashTagObject)
+ .map(tag => tag.name)
+ const tagInstances = await TagModel.findOrCreateTags(tags, t)
+ await videoUpdated.$set('Tags', tagInstances, sequelizeOptions)
+ }
+
+ {
+ // Update captions
+ await VideoCaptionModel.deleteAllCaptionsOfRemoteVideo(videoUpdated.id, t)
+
+ const videoCaptionsPromises = videoObject.subtitleLanguage.map(c => {
+ return VideoCaptionModel.insertOrReplaceLanguage(videoUpdated.id, c.identifier, t)
+ })
+ await Promise.all(videoCaptionsPromises)
+ }
+
+ return videoUpdated
+ })
+
+ await autoBlacklistVideoIfNeeded({
+ video: videoUpdated,
+ user: undefined,
+ isRemote: true,
+ isNew: false,
+ transaction: undefined
+ })
+
+ if (wasPrivateVideo || wasUnlistedVideo) Notifier.Instance.notifyOnNewVideoIfNeeded(videoUpdated) // Notify our users?
+
+ logger.info('Remote video with uuid %s updated', videoObject.uuid)
+
+ return videoUpdated
+ } catch (err) {
+ if (video !== undefined && videoFieldsSave !== undefined) {
+ resetSequelizeInstance(video, videoFieldsSave)
+ }
+
+ // This is just a debug because we will retry the insert
+ logger.debug('Cannot update the remote video.', { err })
+ throw err
+ }
+}
+
+async function refreshVideoIfNeeded (options: {
+ video: MVideoThumbnail,
+ fetchedType: VideoFetchByUrlType,
+ syncParam: SyncParam
+}): Promise<MVideoThumbnail> {
+ if (!options.video.isOutdated()) return options.video
+
+ // We need more attributes if the argument video was fetched with not enough joints
+ const video = options.fetchedType === 'all'
+ ? options.video as MVideoAccountLightBlacklistAllFiles
+ : await VideoModel.loadByUrlAndPopulateAccount(options.video.url)
+
+ try {
+ const { response, videoObject } = await fetchRemoteVideo(video.url)
+ if (response.statusCode === 404) {
+ logger.info('Cannot refresh remote video %s: video does not exist anymore. Deleting it.', video.url)
+
+ // Video does not exist anymore
+ await video.destroy()
+ return undefined
+ }
+
+ if (videoObject === undefined) {
+ logger.warn('Cannot refresh remote video %s: invalid body.', video.url)
+
+ await video.setAsRefreshed()
+ return video
+ }
+
+ const channelActor = await getOrCreateVideoChannelFromVideoObject(videoObject)
+
+ const updateOptions = {
+ video,
+ videoObject,
+ account: channelActor.VideoChannel.Account,
+ channel: channelActor.VideoChannel
+ }
+ await retryTransactionWrapper(updateVideoFromAP, updateOptions)
+ await syncVideoExternalAttributes(video, videoObject, options.syncParam)
+
+ ActorFollowScoreCache.Instance.addGoodServerId(video.VideoChannel.Actor.serverId)
+
+ return video
+ } catch (err) {
+ logger.warn('Cannot refresh video %s.', options.video.url, { err })
+
+ ActorFollowScoreCache.Instance.addBadServerId(video.VideoChannel.Actor.serverId)
+
+ // Don't refresh in loop
+ await video.setAsRefreshed()
+ return video
+ }
+}
+
+export {
+ updateVideoFromAP,
+ refreshVideoIfNeeded,
+ federateVideoIfNeeded,
+ fetchRemoteVideo,
+ getOrCreateVideoAndAccountAndChannel,
+ fetchRemoteVideoStaticFile,
+ fetchRemoteVideoDescription,
+ getOrCreateVideoChannelFromVideoObject
+}
+
+// ---------------------------------------------------------------------------
+
+function isAPVideoUrlObject (url: any): url is ActivityVideoUrlObject {
+ const mimeTypes = Object.keys(MIMETYPES.VIDEO.MIMETYPE_EXT)
+
+ const urlMediaType = url.mediaType
+ return mimeTypes.indexOf(urlMediaType) !== -1 && urlMediaType.startsWith('video/')
+}
+
+function isAPStreamingPlaylistUrlObject (url: ActivityUrlObject): url is ActivityPlaylistUrlObject {
+ return url && url.mediaType === 'application/x-mpegURL'
+}
+
+function isAPPlaylistSegmentHashesUrlObject (tag: any): tag is ActivityPlaylistSegmentHashesObject {
+ return tag && tag.name === 'sha256' && tag.type === 'Link' && tag.mediaType === 'application/json'
+}
+
+function isAPMagnetUrlObject (url: any): url is ActivityMagnetUrlObject {
+ return url && url.mediaType === 'application/x-bittorrent;x-scheme-handler/magnet'
+}
+
+function isAPHashTagObject (url: any): url is ActivityHashTagObject {
+ return url && url.type === 'Hashtag'
+}
+
+async function createVideo (videoObject: VideoTorrentObject, channel: MChannelAccountLight, waitThumbnail = false) {
+ logger.debug('Adding remote video %s.', videoObject.id)
+
+ const videoData = await videoActivityObjectToDBAttributes(channel, videoObject, videoObject.to)
+ const video = VideoModel.build(videoData) as MVideoThumbnail
+
+ const promiseThumbnail = createVideoMiniatureFromUrl(videoObject.icon.url, video, ThumbnailType.MINIATURE)
+
+ let thumbnailModel: MThumbnail
+ if (waitThumbnail === true) {
+ thumbnailModel = await promiseThumbnail
+ }
+
+ const { autoBlacklisted, videoCreated } = await sequelizeTypescript.transaction(async t => {
+ const sequelizeOptions = { transaction: t }
+
+ const videoCreated = await video.save(sequelizeOptions) as MVideoFullLight
+ videoCreated.VideoChannel = channel
+
+ if (thumbnailModel) await videoCreated.addAndSaveThumbnail(thumbnailModel, t)
+
+ // FIXME: use icon URL instead
+ const previewUrl = buildRemoteBaseUrl(videoCreated, join(STATIC_PATHS.PREVIEWS, video.generatePreviewName()))
+ const previewModel = createPlaceholderThumbnail(previewUrl, video, ThumbnailType.PREVIEW, PREVIEWS_SIZE)
+ if (thumbnailModel) await videoCreated.addAndSaveThumbnail(previewModel, t)
+
+ // Process files
+ const videoFileAttributes = videoFileActivityUrlToDBAttributes(videoCreated, videoObject.url)
+
+ const videoFilePromises = videoFileAttributes.map(f => VideoFileModel.create(f, { transaction: t }))
+ const videoFiles = await Promise.all(videoFilePromises)
+
+ const streamingPlaylistsAttributes = streamingPlaylistActivityUrlToDBAttributes(videoCreated, videoObject, videoFiles)
+ videoCreated.VideoStreamingPlaylists = []
+
+ for (const playlistAttributes of streamingPlaylistsAttributes) {
+ const playlistModel = await VideoStreamingPlaylistModel.create(playlistAttributes, { transaction: t })
+
+ const playlistFiles = videoFileActivityUrlToDBAttributes(playlistModel, playlistAttributes.tagAPObject)
+ const videoFilePromises = playlistFiles.map(f => VideoFileModel.create(f, { transaction: t }))
+ playlistModel.VideoFiles = await Promise.all(videoFilePromises)
+
+ videoCreated.VideoStreamingPlaylists.push(playlistModel)
+ }
+
+ // Process tags
+ const tags = videoObject.tag
+ .filter(isAPHashTagObject)
+ .map(t => t.name)
+ const tagInstances = await TagModel.findOrCreateTags(tags, t)
+ await videoCreated.$set('Tags', tagInstances, sequelizeOptions)
+
+ // Process captions
+ const videoCaptionsPromises = videoObject.subtitleLanguage.map(c => {
+ return VideoCaptionModel.insertOrReplaceLanguage(videoCreated.id, c.identifier, t)
+ })
+ await Promise.all(videoCaptionsPromises)
+
+ videoCreated.VideoFiles = videoFiles
+ videoCreated.Tags = tagInstances
+
+ const autoBlacklisted = await autoBlacklistVideoIfNeeded({
+ video: videoCreated,
+ user: undefined,
+ isRemote: true,
+ isNew: true,
+ transaction: t
+ })
+
+ logger.info('Remote video with uuid %s inserted.', videoObject.uuid)
+
+ return { autoBlacklisted, videoCreated }
+ })
+
+ if (waitThumbnail === false) {
+ promiseThumbnail.then(thumbnailModel => {
+ thumbnailModel = videoCreated.id
+
+ return thumbnailModel.save()
+ })
+ }
+
+ return { autoBlacklisted, videoCreated }
+}
+
+async function videoActivityObjectToDBAttributes (videoChannel: MChannelId, videoObject: VideoTorrentObject, to: string[] = []) {