videos.ts 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724
  1. import * as Bluebird from 'bluebird'
  2. import * as sequelize from 'sequelize'
  3. import * as magnetUtil from 'magnet-uri'
  4. import * as request from 'request'
  5. import {
  6. ActivityHashTagObject,
  7. ActivityMagnetUrlObject,
  8. ActivityPlaylistSegmentHashesObject,
  9. ActivityPlaylistUrlObject, ActivityTagObject,
  10. ActivityUrlObject,
  11. ActivityVideoUrlObject,
  12. VideoState
  13. } from '../../../shared/index'
  14. import { VideoTorrentObject } from '../../../shared/models/activitypub/objects'
  15. import { VideoPrivacy } from '../../../shared/models/videos'
  16. import { sanitizeAndCheckVideoTorrentObject } from '../../helpers/custom-validators/activitypub/videos'
  17. import { isVideoFileInfoHashValid } from '../../helpers/custom-validators/videos'
  18. import { deleteNonExistingModels, resetSequelizeInstance, retryTransactionWrapper } from '../../helpers/database-utils'
  19. import { logger } from '../../helpers/logger'
  20. import { doRequest, doRequestAndSaveToFile } from '../../helpers/requests'
  21. import {
  22. ACTIVITY_PUB,
  23. MIMETYPES,
  24. P2P_MEDIA_LOADER_PEER_VERSION,
  25. PREVIEWS_SIZE,
  26. REMOTE_SCHEME,
  27. STATIC_PATHS
  28. } from '../../initializers/constants'
  29. import { TagModel } from '../../models/video/tag'
  30. import { VideoModel } from '../../models/video/video'
  31. import { VideoFileModel } from '../../models/video/video-file'
  32. import { getOrCreateActorAndServerAndModel } from './actor'
  33. import { addVideoComments } from './video-comments'
  34. import { crawlCollectionPage } from './crawl'
  35. import { sendCreateVideo, sendUpdateVideo } from './send'
  36. import { isArray } from '../../helpers/custom-validators/misc'
  37. import { VideoCaptionModel } from '../../models/video/video-caption'
  38. import { JobQueue } from '../job-queue'
  39. import { ActivitypubHttpFetcherPayload } from '../job-queue/handlers/activitypub-http-fetcher'
  40. import { createRates } from './video-rates'
  41. import { addVideoShares, shareVideoByServerAndChannel } from './share'
  42. import { fetchVideoByUrl, VideoFetchByUrlType } from '../../helpers/video'
  43. import { checkUrlsSameHost, getAPId } from '../../helpers/activitypub'
  44. import { Notifier } from '../notifier'
  45. import { VideoStreamingPlaylistModel } from '../../models/video/video-streaming-playlist'
  46. import { VideoStreamingPlaylistType } from '../../../shared/models/videos/video-streaming-playlist.type'
  47. import { AccountVideoRateModel } from '../../models/account/account-video-rate'
  48. import { VideoShareModel } from '../../models/video/video-share'
  49. import { VideoCommentModel } from '../../models/video/video-comment'
  50. import { sequelizeTypescript } from '../../initializers/database'
  51. import { createPlaceholderThumbnail, createVideoMiniatureFromUrl } from '../thumbnail'
  52. import { ThumbnailType } from '../../../shared/models/videos/thumbnail.type'
  53. import { join } from 'path'
  54. import { FilteredModelAttributes } from '../../typings/sequelize'
  55. import { autoBlacklistVideoIfNeeded } from '../video-blacklist'
  56. import { ActorFollowScoreCache } from '../files-cache'
  57. import {
  58. MAccountIdActor,
  59. MChannelAccountLight,
  60. MChannelDefault,
  61. MChannelId,
  62. MStreamingPlaylist,
  63. MVideo,
  64. MVideoAccountLight,
  65. MVideoAccountLightBlacklistAllFiles,
  66. MVideoAP,
  67. MVideoAPWithoutCaption,
  68. MVideoFile,
  69. MVideoFullLight,
  70. MVideoId,
  71. MVideoThumbnail
  72. } from '../../typings/models'
  73. import { MThumbnail } from '../../typings/models/video/thumbnail'
  74. async function federateVideoIfNeeded (videoArg: MVideoAPWithoutCaption, isNewVideo: boolean, transaction?: sequelize.Transaction) {
  75. const video = videoArg as MVideoAP
  76. if (
  77. // Check this is not a blacklisted video, or unfederated blacklisted video
  78. (video.isBlacklisted() === false || (isNewVideo === false && video.VideoBlacklist.unfederated === false)) &&
  79. // Check the video is public/unlisted and published
  80. video.privacy !== VideoPrivacy.PRIVATE && video.state === VideoState.PUBLISHED
  81. ) {
  82. // Fetch more attributes that we will need to serialize in AP object
  83. if (isArray(video.VideoCaptions) === false) {
  84. video.VideoCaptions = await video.$get('VideoCaptions', {
  85. attributes: [ 'language' ],
  86. transaction
  87. }) as VideoCaptionModel[]
  88. }
  89. if (isNewVideo) {
  90. // Now we'll add the video's meta data to our followers
  91. await sendCreateVideo(video, transaction)
  92. await shareVideoByServerAndChannel(video, transaction)
  93. } else {
  94. await sendUpdateVideo(video, transaction)
  95. }
  96. }
  97. }
  98. async function fetchRemoteVideo (videoUrl: string): Promise<{ response: request.RequestResponse, videoObject: VideoTorrentObject }> {
  99. const options = {
  100. uri: videoUrl,
  101. method: 'GET',
  102. json: true,
  103. activityPub: true
  104. }
  105. logger.info('Fetching remote video %s.', videoUrl)
  106. const { response, body } = await doRequest(options)
  107. if (sanitizeAndCheckVideoTorrentObject(body) === false || checkUrlsSameHost(body.id, videoUrl) !== true) {
  108. logger.debug('Remote video JSON is not valid.', { body })
  109. return { response, videoObject: undefined }
  110. }
  111. return { response, videoObject: body }
  112. }
  113. async function fetchRemoteVideoDescription (video: MVideoAccountLight) {
  114. const host = video.VideoChannel.Account.Actor.Server.host
  115. const path = video.getDescriptionAPIPath()
  116. const options = {
  117. uri: REMOTE_SCHEME.HTTP + '://' + host + path,
  118. json: true
  119. }
  120. const { body } = await doRequest(options)
  121. return body.description ? body.description : ''
  122. }
  123. function fetchRemoteVideoStaticFile (video: MVideoAccountLight, path: string, destPath: string) {
  124. const url = buildRemoteBaseUrl(video, path)
  125. // We need to provide a callback, if no we could have an uncaught exception
  126. return doRequestAndSaveToFile({ uri: url }, destPath)
  127. }
  128. function buildRemoteBaseUrl (video: MVideoAccountLight, path: string) {
  129. const host = video.VideoChannel.Account.Actor.Server.host
  130. return REMOTE_SCHEME.HTTP + '://' + host + path
  131. }
  132. function getOrCreateVideoChannelFromVideoObject (videoObject: VideoTorrentObject) {
  133. const channel = videoObject.attributedTo.find(a => a.type === 'Group')
  134. if (!channel) throw new Error('Cannot find associated video channel to video ' + videoObject.url)
  135. if (checkUrlsSameHost(channel.id, videoObject.id) !== true) {
  136. throw new Error(`Video channel url ${channel.id} does not have the same host than video object id ${videoObject.id}`)
  137. }
  138. return getOrCreateActorAndServerAndModel(channel.id, 'all')
  139. }
  140. type SyncParam = {
  141. likes: boolean
  142. dislikes: boolean
  143. shares: boolean
  144. comments: boolean
  145. thumbnail: boolean
  146. refreshVideo?: boolean
  147. }
  148. async function syncVideoExternalAttributes (video: MVideo, fetchedVideo: VideoTorrentObject, syncParam: SyncParam) {
  149. logger.info('Adding likes/dislikes/shares/comments of video %s.', video.uuid)
  150. const jobPayloads: ActivitypubHttpFetcherPayload[] = []
  151. if (syncParam.likes === true) {
  152. const handler = items => createRates(items, video, 'like')
  153. const cleaner = crawlStartDate => AccountVideoRateModel.cleanOldRatesOf(video.id, 'like' as 'like', crawlStartDate)
  154. await crawlCollectionPage<string>(fetchedVideo.likes, handler, cleaner)
  155. .catch(err => logger.error('Cannot add likes of video %s.', video.uuid, { err }))
  156. } else {
  157. jobPayloads.push({ uri: fetchedVideo.likes, videoId: video.id, type: 'video-likes' as 'video-likes' })
  158. }
  159. if (syncParam.dislikes === true) {
  160. const handler = items => createRates(items, video, 'dislike')
  161. const cleaner = crawlStartDate => AccountVideoRateModel.cleanOldRatesOf(video.id, 'dislike' as 'dislike', crawlStartDate)
  162. await crawlCollectionPage<string>(fetchedVideo.dislikes, handler, cleaner)
  163. .catch(err => logger.error('Cannot add dislikes of video %s.', video.uuid, { err }))
  164. } else {
  165. jobPayloads.push({ uri: fetchedVideo.dislikes, videoId: video.id, type: 'video-dislikes' as 'video-dislikes' })
  166. }
  167. if (syncParam.shares === true) {
  168. const handler = items => addVideoShares(items, video)
  169. const cleaner = crawlStartDate => VideoShareModel.cleanOldSharesOf(video.id, crawlStartDate)
  170. await crawlCollectionPage<string>(fetchedVideo.shares, handler, cleaner)
  171. .catch(err => logger.error('Cannot add shares of video %s.', video.uuid, { err }))
  172. } else {
  173. jobPayloads.push({ uri: fetchedVideo.shares, videoId: video.id, type: 'video-shares' as 'video-shares' })
  174. }
  175. if (syncParam.comments === true) {
  176. const handler = items => addVideoComments(items)
  177. const cleaner = crawlStartDate => VideoCommentModel.cleanOldCommentsOf(video.id, crawlStartDate)
  178. await crawlCollectionPage<string>(fetchedVideo.comments, handler, cleaner)
  179. .catch(err => logger.error('Cannot add comments of video %s.', video.uuid, { err }))
  180. } else {
  181. jobPayloads.push({ uri: fetchedVideo.comments, videoId: video.id, type: 'video-comments' as 'video-comments' })
  182. }
  183. await Bluebird.map(jobPayloads, payload => JobQueue.Instance.createJob({ type: 'activitypub-http-fetcher', payload }))
  184. }
  185. function getOrCreateVideoAndAccountAndChannel (options: {
  186. videoObject: { id: string } | string,
  187. syncParam?: SyncParam,
  188. fetchType?: 'all',
  189. allowRefresh?: boolean
  190. }): Promise<{ video: MVideoAccountLightBlacklistAllFiles, created: boolean, autoBlacklisted?: boolean }>
  191. function getOrCreateVideoAndAccountAndChannel (options: {
  192. videoObject: { id: string } | string,
  193. syncParam?: SyncParam,
  194. fetchType?: VideoFetchByUrlType,
  195. allowRefresh?: boolean
  196. }): Promise<{ video: MVideoAccountLightBlacklistAllFiles | MVideoThumbnail, created: boolean, autoBlacklisted?: boolean }>
  197. async function getOrCreateVideoAndAccountAndChannel (options: {
  198. videoObject: { id: string } | string,
  199. syncParam?: SyncParam,
  200. fetchType?: VideoFetchByUrlType,
  201. allowRefresh?: boolean // true by default
  202. }): Promise<{ video: MVideoAccountLightBlacklistAllFiles | MVideoThumbnail, created: boolean, autoBlacklisted?: boolean }> {
  203. // Default params
  204. const syncParam = options.syncParam || { likes: true, dislikes: true, shares: true, comments: true, thumbnail: true, refreshVideo: false }
  205. const fetchType = options.fetchType || 'all'
  206. const allowRefresh = options.allowRefresh !== false
  207. // Get video url
  208. const videoUrl = getAPId(options.videoObject)
  209. let videoFromDatabase = await fetchVideoByUrl(videoUrl, fetchType)
  210. if (videoFromDatabase) {
  211. if (videoFromDatabase.isOutdated() && allowRefresh === true) {
  212. const refreshOptions = {
  213. video: videoFromDatabase,
  214. fetchedType: fetchType,
  215. syncParam
  216. }
  217. if (syncParam.refreshVideo === true) videoFromDatabase = await refreshVideoIfNeeded(refreshOptions)
  218. else await JobQueue.Instance.createJob({ type: 'activitypub-refresher', payload: { type: 'video', url: videoFromDatabase.url } })
  219. }
  220. return { video: videoFromDatabase, created: false }
  221. }
  222. const { videoObject: fetchedVideo } = await fetchRemoteVideo(videoUrl)
  223. if (!fetchedVideo) throw new Error('Cannot fetch remote video with url: ' + videoUrl)
  224. const actor = await getOrCreateVideoChannelFromVideoObject(fetchedVideo)
  225. const videoChannel = actor.VideoChannel
  226. const { autoBlacklisted, videoCreated } = await retryTransactionWrapper(createVideo, fetchedVideo, videoChannel, syncParam.thumbnail)
  227. await syncVideoExternalAttributes(videoCreated, fetchedVideo, syncParam)
  228. return { video: videoCreated, created: true, autoBlacklisted }
  229. }
  230. async function updateVideoFromAP (options: {
  231. video: MVideoAccountLightBlacklistAllFiles,
  232. videoObject: VideoTorrentObject,
  233. account: MAccountIdActor,
  234. channel: MChannelDefault,
  235. overrideTo?: string[]
  236. }) {
  237. const { video, videoObject, account, channel, overrideTo } = options
  238. logger.debug('Updating remote video "%s".', options.videoObject.uuid, { account, channel })
  239. let videoFieldsSave: any
  240. const wasPrivateVideo = video.privacy === VideoPrivacy.PRIVATE
  241. const wasUnlistedVideo = video.privacy === VideoPrivacy.UNLISTED
  242. try {
  243. let thumbnailModel: MThumbnail
  244. try {
  245. thumbnailModel = await createVideoMiniatureFromUrl(videoObject.icon.url, video, ThumbnailType.MINIATURE)
  246. } catch (err) {
  247. logger.warn('Cannot generate thumbnail of %s.', videoObject.id, { err })
  248. }
  249. const videoUpdated = await sequelizeTypescript.transaction(async t => {
  250. const sequelizeOptions = { transaction: t }
  251. videoFieldsSave = video.toJSON()
  252. // Check actor has the right to update the video
  253. const videoChannel = video.VideoChannel
  254. if (videoChannel.Account.id !== account.id) {
  255. throw new Error('Account ' + account.Actor.url + ' does not own video channel ' + videoChannel.Actor.url)
  256. }
  257. const to = overrideTo ? overrideTo : videoObject.to
  258. const videoData = await videoActivityObjectToDBAttributes(channel, videoObject, to)
  259. video.name = videoData.name
  260. video.uuid = videoData.uuid
  261. video.url = videoData.url
  262. video.category = videoData.category
  263. video.licence = videoData.licence
  264. video.language = videoData.language
  265. video.description = videoData.description
  266. video.support = videoData.support
  267. video.nsfw = videoData.nsfw
  268. video.commentsEnabled = videoData.commentsEnabled
  269. video.downloadEnabled = videoData.downloadEnabled
  270. video.waitTranscoding = videoData.waitTranscoding
  271. video.state = videoData.state
  272. video.duration = videoData.duration
  273. video.createdAt = videoData.createdAt
  274. video.publishedAt = videoData.publishedAt
  275. video.originallyPublishedAt = videoData.originallyPublishedAt
  276. video.privacy = videoData.privacy
  277. video.channelId = videoData.channelId
  278. video.views = videoData.views
  279. const videoUpdated = await video.save(sequelizeOptions) as MVideoFullLight
  280. if (thumbnailModel) await videoUpdated.addAndSaveThumbnail(thumbnailModel, t)
  281. // FIXME: use icon URL instead
  282. const previewUrl = buildRemoteBaseUrl(videoUpdated, join(STATIC_PATHS.PREVIEWS, videoUpdated.getPreview().filename))
  283. const previewModel = createPlaceholderThumbnail(previewUrl, video, ThumbnailType.PREVIEW, PREVIEWS_SIZE)
  284. await videoUpdated.addAndSaveThumbnail(previewModel, t)
  285. {
  286. const videoFileAttributes = videoFileActivityUrlToDBAttributes(videoUpdated, videoObject.url)
  287. const newVideoFiles = videoFileAttributes.map(a => new VideoFileModel(a))
  288. // Remove video files that do not exist anymore
  289. const destroyTasks = deleteNonExistingModels(videoUpdated.VideoFiles, newVideoFiles, t)
  290. await Promise.all(destroyTasks)
  291. // Update or add other one
  292. const upsertTasks = newVideoFiles.map(f => VideoFileModel.customUpsert(f, 'video', t))
  293. videoUpdated.VideoFiles = await Promise.all(upsertTasks)
  294. }
  295. {
  296. const streamingPlaylistAttributes = streamingPlaylistActivityUrlToDBAttributes(videoUpdated, videoObject, videoUpdated.VideoFiles)
  297. const newStreamingPlaylists = streamingPlaylistAttributes.map(a => new VideoStreamingPlaylistModel(a))
  298. // Remove video playlists that do not exist anymore
  299. const destroyTasks = deleteNonExistingModels(videoUpdated.VideoStreamingPlaylists, newStreamingPlaylists, t)
  300. await Promise.all(destroyTasks)
  301. let oldStreamingPlaylistFiles: MVideoFile[] = []
  302. for (const videoStreamingPlaylist of videoUpdated.VideoStreamingPlaylists) {
  303. oldStreamingPlaylistFiles = oldStreamingPlaylistFiles.concat(videoStreamingPlaylist.VideoFiles)
  304. }
  305. videoUpdated.VideoStreamingPlaylists = []
  306. for (const playlistAttributes of streamingPlaylistAttributes) {
  307. const streamingPlaylistModel = await VideoStreamingPlaylistModel.upsert(playlistAttributes, { returning: true, transaction: t })
  308. .then(([ streamingPlaylist ]) => streamingPlaylist)
  309. const newVideoFiles: MVideoFile[] = videoFileActivityUrlToDBAttributes(streamingPlaylistModel, playlistAttributes.tagAPObject)
  310. .map(a => new VideoFileModel(a))
  311. const destroyTasks = deleteNonExistingModels(oldStreamingPlaylistFiles, newVideoFiles, t)
  312. await Promise.all(destroyTasks)
  313. // Update or add other one
  314. const upsertTasks = newVideoFiles.map(f => VideoFileModel.customUpsert(f, 'streaming-playlist', t))
  315. streamingPlaylistModel.VideoFiles = await Promise.all(upsertTasks)
  316. videoUpdated.VideoStreamingPlaylists.push(streamingPlaylistModel)
  317. }
  318. }
  319. {
  320. // Update Tags
  321. const tags = videoObject.tag
  322. .filter(isAPHashTagObject)
  323. .map(tag => tag.name)
  324. const tagInstances = await TagModel.findOrCreateTags(tags, t)
  325. await videoUpdated.$set('Tags', tagInstances, sequelizeOptions)
  326. }
  327. {
  328. // Update captions
  329. await VideoCaptionModel.deleteAllCaptionsOfRemoteVideo(videoUpdated.id, t)
  330. const videoCaptionsPromises = videoObject.subtitleLanguage.map(c => {
  331. return VideoCaptionModel.insertOrReplaceLanguage(videoUpdated.id, c.identifier, t)
  332. })
  333. await Promise.all(videoCaptionsPromises)
  334. }
  335. return videoUpdated
  336. })
  337. await autoBlacklistVideoIfNeeded({
  338. video: videoUpdated,
  339. user: undefined,
  340. isRemote: true,
  341. isNew: false,
  342. transaction: undefined
  343. })
  344. if (wasPrivateVideo || wasUnlistedVideo) Notifier.Instance.notifyOnNewVideoIfNeeded(videoUpdated) // Notify our users?
  345. logger.info('Remote video with uuid %s updated', videoObject.uuid)
  346. return videoUpdated
  347. } catch (err) {
  348. if (video !== undefined && videoFieldsSave !== undefined) {
  349. resetSequelizeInstance(video, videoFieldsSave)
  350. }
  351. // This is just a debug because we will retry the insert
  352. logger.debug('Cannot update the remote video.', { err })
  353. throw err
  354. }
  355. }
  356. async function refreshVideoIfNeeded (options: {
  357. video: MVideoThumbnail,
  358. fetchedType: VideoFetchByUrlType,
  359. syncParam: SyncParam
  360. }): Promise<MVideoThumbnail> {
  361. if (!options.video.isOutdated()) return options.video
  362. // We need more attributes if the argument video was fetched with not enough joints
  363. const video = options.fetchedType === 'all'
  364. ? options.video as MVideoAccountLightBlacklistAllFiles
  365. : await VideoModel.loadByUrlAndPopulateAccount(options.video.url)
  366. try {
  367. const { response, videoObject } = await fetchRemoteVideo(video.url)
  368. if (response.statusCode === 404) {
  369. logger.info('Cannot refresh remote video %s: video does not exist anymore. Deleting it.', video.url)
  370. // Video does not exist anymore
  371. await video.destroy()
  372. return undefined
  373. }
  374. if (videoObject === undefined) {
  375. logger.warn('Cannot refresh remote video %s: invalid body.', video.url)
  376. await video.setAsRefreshed()
  377. return video
  378. }
  379. const channelActor = await getOrCreateVideoChannelFromVideoObject(videoObject)
  380. const updateOptions = {
  381. video,
  382. videoObject,
  383. account: channelActor.VideoChannel.Account,
  384. channel: channelActor.VideoChannel
  385. }
  386. await retryTransactionWrapper(updateVideoFromAP, updateOptions)
  387. await syncVideoExternalAttributes(video, videoObject, options.syncParam)
  388. ActorFollowScoreCache.Instance.addGoodServerId(video.VideoChannel.Actor.serverId)
  389. return video
  390. } catch (err) {
  391. logger.warn('Cannot refresh video %s.', options.video.url, { err })
  392. ActorFollowScoreCache.Instance.addBadServerId(video.VideoChannel.Actor.serverId)
  393. // Don't refresh in loop
  394. await video.setAsRefreshed()
  395. return video
  396. }
  397. }
  398. export {
  399. updateVideoFromAP,
  400. refreshVideoIfNeeded,
  401. federateVideoIfNeeded,
  402. fetchRemoteVideo,
  403. getOrCreateVideoAndAccountAndChannel,
  404. fetchRemoteVideoStaticFile,
  405. fetchRemoteVideoDescription,
  406. getOrCreateVideoChannelFromVideoObject
  407. }
  408. // ---------------------------------------------------------------------------
  409. function isAPVideoUrlObject (url: any): url is ActivityVideoUrlObject {
  410. const mimeTypes = Object.keys(MIMETYPES.VIDEO.MIMETYPE_EXT)
  411. const urlMediaType = url.mediaType
  412. return mimeTypes.indexOf(urlMediaType) !== -1 && urlMediaType.startsWith('video/')
  413. }
  414. function isAPStreamingPlaylistUrlObject (url: ActivityUrlObject): url is ActivityPlaylistUrlObject {
  415. return url && url.mediaType === 'application/x-mpegURL'
  416. }
  417. function isAPPlaylistSegmentHashesUrlObject (tag: any): tag is ActivityPlaylistSegmentHashesObject {
  418. return tag && tag.name === 'sha256' && tag.type === 'Link' && tag.mediaType === 'application/json'
  419. }
  420. function isAPMagnetUrlObject (url: any): url is ActivityMagnetUrlObject {
  421. return url && url.mediaType === 'application/x-bittorrent;x-scheme-handler/magnet'
  422. }
  423. function isAPHashTagObject (url: any): url is ActivityHashTagObject {
  424. return url && url.type === 'Hashtag'
  425. }
  426. async function createVideo (videoObject: VideoTorrentObject, channel: MChannelAccountLight, waitThumbnail = false) {
  427. logger.debug('Adding remote video %s.', videoObject.id)
  428. const videoData = await videoActivityObjectToDBAttributes(channel, videoObject, videoObject.to)
  429. const video = VideoModel.build(videoData) as MVideoThumbnail
  430. const promiseThumbnail = createVideoMiniatureFromUrl(videoObject.icon.url, video, ThumbnailType.MINIATURE)
  431. let thumbnailModel: MThumbnail
  432. if (waitThumbnail === true) {
  433. thumbnailModel = await promiseThumbnail
  434. }
  435. const { autoBlacklisted, videoCreated } = await sequelizeTypescript.transaction(async t => {
  436. const sequelizeOptions = { transaction: t }
  437. const videoCreated = await video.save(sequelizeOptions) as MVideoFullLight
  438. videoCreated.VideoChannel = channel
  439. if (thumbnailModel) await videoCreated.addAndSaveThumbnail(thumbnailModel, t)
  440. // FIXME: use icon URL instead
  441. const previewUrl = buildRemoteBaseUrl(videoCreated, join(STATIC_PATHS.PREVIEWS, video.generatePreviewName()))
  442. const previewModel = createPlaceholderThumbnail(previewUrl, video, ThumbnailType.PREVIEW, PREVIEWS_SIZE)
  443. if (thumbnailModel) await videoCreated.addAndSaveThumbnail(previewModel, t)
  444. // Process files
  445. const videoFileAttributes = videoFileActivityUrlToDBAttributes(videoCreated, videoObject.url)
  446. const videoFilePromises = videoFileAttributes.map(f => VideoFileModel.create(f, { transaction: t }))
  447. const videoFiles = await Promise.all(videoFilePromises)
  448. const streamingPlaylistsAttributes = streamingPlaylistActivityUrlToDBAttributes(videoCreated, videoObject, videoFiles)
  449. videoCreated.VideoStreamingPlaylists = []
  450. for (const playlistAttributes of streamingPlaylistsAttributes) {
  451. const playlistModel = await VideoStreamingPlaylistModel.create(playlistAttributes, { transaction: t })
  452. const playlistFiles = videoFileActivityUrlToDBAttributes(playlistModel, playlistAttributes.tagAPObject)
  453. const videoFilePromises = playlistFiles.map(f => VideoFileModel.create(f, { transaction: t }))
  454. playlistModel.VideoFiles = await Promise.all(videoFilePromises)
  455. videoCreated.VideoStreamingPlaylists.push(playlistModel)
  456. }
  457. // Process tags
  458. const tags = videoObject.tag
  459. .filter(isAPHashTagObject)
  460. .map(t => t.name)
  461. const tagInstances = await TagModel.findOrCreateTags(tags, t)
  462. await videoCreated.$set('Tags', tagInstances, sequelizeOptions)
  463. // Process captions
  464. const videoCaptionsPromises = videoObject.subtitleLanguage.map(c => {
  465. return VideoCaptionModel.insertOrReplaceLanguage(videoCreated.id, c.identifier, t)
  466. })
  467. await Promise.all(videoCaptionsPromises)
  468. videoCreated.VideoFiles = videoFiles
  469. videoCreated.Tags = tagInstances
  470. const autoBlacklisted = await autoBlacklistVideoIfNeeded({
  471. video: videoCreated,
  472. user: undefined,
  473. isRemote: true,
  474. isNew: true,
  475. transaction: t
  476. })
  477. logger.info('Remote video with uuid %s inserted.', videoObject.uuid)
  478. return { autoBlacklisted, videoCreated }
  479. })
  480. if (waitThumbnail === false) {
  481. promiseThumbnail.then(thumbnailModel => {
  482. thumbnailModel = videoCreated.id
  483. return thumbnailModel.save()
  484. })
  485. }
  486. return { autoBlacklisted, videoCreated }
  487. }
  488. async function videoActivityObjectToDBAttributes (videoChannel: MChannelId, videoObject: VideoTorrentObject, to: string[] = []) {
  489. const privacy = to.indexOf(ACTIVITY_PUB.PUBLIC) !== -1 ? VideoPrivacy.PUBLIC : VideoPrivacy.UNLISTED
  490. const duration = videoObject.duration.replace(/[^\d]+/, '')
  491. let language: string | undefined
  492. if (videoObject.language) {
  493. language = videoObject.language.identifier
  494. }
  495. let category: number | undefined
  496. if (videoObject.category) {
  497. category = parseInt(videoObject.category.identifier, 10)
  498. }
  499. let licence: number | undefined
  500. if (videoObject.licence) {
  501. licence = parseInt(videoObject.licence.identifier, 10)
  502. }
  503. const description = videoObject.content || null
  504. const support = videoObject.support || null
  505. return {
  506. name: videoObject.name,
  507. uuid: videoObject.uuid,
  508. url: videoObject.id,
  509. category,
  510. licence,
  511. language,
  512. description,
  513. support,
  514. nsfw: videoObject.sensitive,
  515. commentsEnabled: videoObject.commentsEnabled,
  516. downloadEnabled: videoObject.downloadEnabled,
  517. waitTranscoding: videoObject.waitTranscoding,
  518. state: videoObject.state,
  519. channelId: videoChannel.id,
  520. duration: parseInt(duration, 10),
  521. createdAt: new Date(videoObject.published),
  522. publishedAt: new Date(videoObject.published),
  523. originallyPublishedAt: videoObject.originallyPublishedAt ? new Date(videoObject.originallyPublishedAt) : null,
  524. // FIXME: updatedAt does not seems to be considered by Sequelize
  525. updatedAt: new Date(videoObject.updated),
  526. views: videoObject.views,
  527. likes: 0,
  528. dislikes: 0,
  529. remote: true,
  530. privacy
  531. }
  532. }
  533. function videoFileActivityUrlToDBAttributes (
  534. videoOrPlaylist: MVideo | MStreamingPlaylist,
  535. urls: (ActivityTagObject | ActivityUrlObject)[]
  536. ) {
  537. const fileUrls = urls.filter(u => isAPVideoUrlObject(u)) as ActivityVideoUrlObject[]
  538. if (fileUrls.length === 0) return []
  539. const attributes: FilteredModelAttributes<VideoFileModel>[] = []
  540. for (const fileUrl of fileUrls) {
  541. // Fetch associated magnet uri
  542. const magnet = urls.filter(isAPMagnetUrlObject)
  543. .find(u => u.height === fileUrl.height)
  544. if (!magnet) throw new Error('Cannot find associated magnet uri for file ' + fileUrl.href)
  545. const parsed = magnetUtil.decode(magnet.href)
  546. if (!parsed || isVideoFileInfoHashValid(parsed.infoHash) === false) {
  547. throw new Error('Cannot parse magnet URI ' + magnet.href)
  548. }
  549. const mediaType = fileUrl.mediaType
  550. const attribute = {
  551. extname: MIMETYPES.VIDEO.MIMETYPE_EXT[ mediaType ],
  552. infoHash: parsed.infoHash,
  553. resolution: fileUrl.height,
  554. size: fileUrl.size,
  555. fps: fileUrl.fps || -1,
  556. // This is a video file owned by a video or by a streaming playlist
  557. videoId: (videoOrPlaylist as MStreamingPlaylist).playlistUrl ? null : videoOrPlaylist.id,
  558. videoStreamingPlaylistId: (videoOrPlaylist as MStreamingPlaylist).playlistUrl ? videoOrPlaylist.id : null
  559. }
  560. attributes.push(attribute)
  561. }
  562. return attributes
  563. }
  564. function streamingPlaylistActivityUrlToDBAttributes (video: MVideoId, videoObject: VideoTorrentObject, videoFiles: MVideoFile[]) {
  565. const playlistUrls = videoObject.url.filter(u => isAPStreamingPlaylistUrlObject(u)) as ActivityPlaylistUrlObject[]
  566. if (playlistUrls.length === 0) return []
  567. const attributes: (FilteredModelAttributes<VideoStreamingPlaylistModel> & { tagAPObject?: ActivityTagObject[] })[] = []
  568. for (const playlistUrlObject of playlistUrls) {
  569. const segmentsSha256UrlObject = playlistUrlObject.tag.find(isAPPlaylistSegmentHashesUrlObject)
  570. let files: unknown[] = playlistUrlObject.tag.filter(u => isAPVideoUrlObject(u)) as ActivityVideoUrlObject[]
  571. // FIXME: backward compatibility introduced in v2.1.0
  572. if (files.length === 0) files = videoFiles
  573. if (!segmentsSha256UrlObject) {
  574. logger.warn('No segment sha256 URL found in AP playlist object.', { playlistUrl: playlistUrlObject })
  575. continue
  576. }
  577. const attribute = {
  578. type: VideoStreamingPlaylistType.HLS,
  579. playlistUrl: playlistUrlObject.href,
  580. segmentsSha256Url: segmentsSha256UrlObject.href,
  581. p2pMediaLoaderInfohashes: VideoStreamingPlaylistModel.buildP2PMediaLoaderInfoHashes(playlistUrlObject.href, files),
  582. p2pMediaLoaderPeerVersion: P2P_MEDIA_LOADER_PEER_VERSION,
  583. videoId: video.id,
  584. tagAPObject: playlistUrlObject.tag
  585. }
  586. attributes.push(attribute)
  587. }
  588. return attributes
  589. }