2
1

video-playlist.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. import * as express from 'express'
  2. import { getFormattedObjects, getServerActor } from '../../helpers/utils'
  3. import {
  4. asyncMiddleware,
  5. asyncRetryTransactionMiddleware,
  6. authenticate,
  7. commonVideosFiltersValidator,
  8. optionalAuthenticate,
  9. paginationValidator,
  10. setDefaultPagination,
  11. setDefaultSort
  12. } from '../../middlewares'
  13. import { videoPlaylistsSortValidator } from '../../middlewares/validators'
  14. import { buildNSFWFilter, createReqFiles, isUserAbleToSearchRemoteURI } from '../../helpers/express-utils'
  15. import { MIMETYPES, VIDEO_PLAYLIST_PRIVACIES } from '../../initializers/constants'
  16. import { logger } from '../../helpers/logger'
  17. import { resetSequelizeInstance } from '../../helpers/database-utils'
  18. import { VideoPlaylistModel } from '../../models/video/video-playlist'
  19. import {
  20. commonVideoPlaylistFiltersValidator,
  21. videoPlaylistsAddValidator,
  22. videoPlaylistsAddVideoValidator,
  23. videoPlaylistsDeleteValidator,
  24. videoPlaylistsGetValidator,
  25. videoPlaylistsReorderVideosValidator,
  26. videoPlaylistsUpdateOrRemoveVideoValidator,
  27. videoPlaylistsUpdateValidator
  28. } from '../../middlewares/validators/videos/video-playlists'
  29. import { VideoPlaylistCreate } from '../../../shared/models/videos/playlist/video-playlist-create.model'
  30. import { VideoPlaylistPrivacy } from '../../../shared/models/videos/playlist/video-playlist-privacy.model'
  31. import { join } from 'path'
  32. import { sendCreateVideoPlaylist, sendDeleteVideoPlaylist, sendUpdateVideoPlaylist } from '../../lib/activitypub/send'
  33. import { getVideoPlaylistActivityPubUrl, getVideoPlaylistElementActivityPubUrl } from '../../lib/activitypub/url'
  34. import { VideoPlaylistUpdate } from '../../../shared/models/videos/playlist/video-playlist-update.model'
  35. import { VideoModel } from '../../models/video/video'
  36. import { VideoPlaylistElementModel } from '../../models/video/video-playlist-element'
  37. import { VideoPlaylistElementCreate } from '../../../shared/models/videos/playlist/video-playlist-element-create.model'
  38. import { VideoPlaylistElementUpdate } from '../../../shared/models/videos/playlist/video-playlist-element-update.model'
  39. import { AccountModel } from '../../models/account/account'
  40. import { VideoPlaylistReorder } from '../../../shared/models/videos/playlist/video-playlist-reorder.model'
  41. import { JobQueue } from '../../lib/job-queue'
  42. import { CONFIG } from '../../initializers/config'
  43. import { sequelizeTypescript } from '../../initializers/database'
  44. import { createPlaylistMiniatureFromExisting } from '../../lib/thumbnail'
  45. const reqThumbnailFile = createReqFiles([ 'thumbnailfile' ], MIMETYPES.IMAGE.MIMETYPE_EXT, { thumbnailfile: CONFIG.STORAGE.TMP_DIR })
  46. const videoPlaylistRouter = express.Router()
  47. videoPlaylistRouter.get('/privacies', listVideoPlaylistPrivacies)
  48. videoPlaylistRouter.get('/',
  49. paginationValidator,
  50. videoPlaylistsSortValidator,
  51. setDefaultSort,
  52. setDefaultPagination,
  53. commonVideoPlaylistFiltersValidator,
  54. asyncMiddleware(listVideoPlaylists)
  55. )
  56. videoPlaylistRouter.get('/:playlistId',
  57. asyncMiddleware(videoPlaylistsGetValidator),
  58. getVideoPlaylist
  59. )
  60. videoPlaylistRouter.post('/',
  61. authenticate,
  62. reqThumbnailFile,
  63. asyncMiddleware(videoPlaylistsAddValidator),
  64. asyncRetryTransactionMiddleware(addVideoPlaylist)
  65. )
  66. videoPlaylistRouter.put('/:playlistId',
  67. authenticate,
  68. reqThumbnailFile,
  69. asyncMiddleware(videoPlaylistsUpdateValidator),
  70. asyncRetryTransactionMiddleware(updateVideoPlaylist)
  71. )
  72. videoPlaylistRouter.delete('/:playlistId',
  73. authenticate,
  74. asyncMiddleware(videoPlaylistsDeleteValidator),
  75. asyncRetryTransactionMiddleware(removeVideoPlaylist)
  76. )
  77. videoPlaylistRouter.get('/:playlistId/videos',
  78. asyncMiddleware(videoPlaylistsGetValidator),
  79. paginationValidator,
  80. setDefaultPagination,
  81. optionalAuthenticate,
  82. commonVideosFiltersValidator,
  83. asyncMiddleware(getVideoPlaylistVideos)
  84. )
  85. videoPlaylistRouter.post('/:playlistId/videos',
  86. authenticate,
  87. asyncMiddleware(videoPlaylistsAddVideoValidator),
  88. asyncRetryTransactionMiddleware(addVideoInPlaylist)
  89. )
  90. videoPlaylistRouter.post('/:playlistId/videos/reorder',
  91. authenticate,
  92. asyncMiddleware(videoPlaylistsReorderVideosValidator),
  93. asyncRetryTransactionMiddleware(reorderVideosPlaylist)
  94. )
  95. videoPlaylistRouter.put('/:playlistId/videos/:videoId',
  96. authenticate,
  97. asyncMiddleware(videoPlaylistsUpdateOrRemoveVideoValidator),
  98. asyncRetryTransactionMiddleware(updateVideoPlaylistElement)
  99. )
  100. videoPlaylistRouter.delete('/:playlistId/videos/:videoId',
  101. authenticate,
  102. asyncMiddleware(videoPlaylistsUpdateOrRemoveVideoValidator),
  103. asyncRetryTransactionMiddleware(removeVideoFromPlaylist)
  104. )
  105. // ---------------------------------------------------------------------------
  106. export {
  107. videoPlaylistRouter
  108. }
  109. // ---------------------------------------------------------------------------
  110. function listVideoPlaylistPrivacies (req: express.Request, res: express.Response) {
  111. res.json(VIDEO_PLAYLIST_PRIVACIES)
  112. }
  113. async function listVideoPlaylists (req: express.Request, res: express.Response) {
  114. const serverActor = await getServerActor()
  115. const resultList = await VideoPlaylistModel.listForApi({
  116. followerActorId: serverActor.id,
  117. start: req.query.start,
  118. count: req.query.count,
  119. sort: req.query.sort,
  120. type: req.query.type
  121. })
  122. return res.json(getFormattedObjects(resultList.data, resultList.total))
  123. }
  124. function getVideoPlaylist (req: express.Request, res: express.Response) {
  125. const videoPlaylist = res.locals.videoPlaylist
  126. if (videoPlaylist.isOutdated()) {
  127. JobQueue.Instance.createJob({ type: 'activitypub-refresher', payload: { type: 'video-playlist', url: videoPlaylist.url } })
  128. .catch(err => logger.error('Cannot create AP refresher job for playlist %s.', videoPlaylist.url, { err }))
  129. }
  130. return res.json(videoPlaylist.toFormattedJSON())
  131. }
  132. async function addVideoPlaylist (req: express.Request, res: express.Response) {
  133. const videoPlaylistInfo: VideoPlaylistCreate = req.body
  134. const user = res.locals.oauth.token.User
  135. const videoPlaylist = new VideoPlaylistModel({
  136. name: videoPlaylistInfo.displayName,
  137. description: videoPlaylistInfo.description,
  138. privacy: videoPlaylistInfo.privacy || VideoPlaylistPrivacy.PRIVATE,
  139. ownerAccountId: user.Account.id
  140. })
  141. videoPlaylist.url = getVideoPlaylistActivityPubUrl(videoPlaylist) // We use the UUID, so set the URL after building the object
  142. if (videoPlaylistInfo.videoChannelId) {
  143. const videoChannel = res.locals.videoChannel
  144. videoPlaylist.videoChannelId = videoChannel.id
  145. videoPlaylist.VideoChannel = videoChannel
  146. }
  147. const thumbnailField = req.files['thumbnailfile']
  148. const thumbnailModel = thumbnailField
  149. ? await createPlaylistMiniatureFromExisting(thumbnailField[0].path, videoPlaylist)
  150. : undefined
  151. const videoPlaylistCreated: VideoPlaylistModel = await sequelizeTypescript.transaction(async t => {
  152. const videoPlaylistCreated = await videoPlaylist.save({ transaction: t })
  153. if (thumbnailModel) await videoPlaylistCreated.setAndSaveThumbnail(thumbnailModel, t)
  154. // We need more attributes for the federation
  155. videoPlaylistCreated.OwnerAccount = await AccountModel.load(user.Account.id, t)
  156. await sendCreateVideoPlaylist(videoPlaylistCreated, t)
  157. return videoPlaylistCreated
  158. })
  159. logger.info('Video playlist with uuid %s created.', videoPlaylist.uuid)
  160. return res.json({
  161. videoPlaylist: {
  162. id: videoPlaylistCreated.id,
  163. uuid: videoPlaylistCreated.uuid
  164. }
  165. }).end()
  166. }
  167. async function updateVideoPlaylist (req: express.Request, res: express.Response) {
  168. const videoPlaylistInstance = res.locals.videoPlaylist
  169. const videoPlaylistFieldsSave = videoPlaylistInstance.toJSON()
  170. const videoPlaylistInfoToUpdate = req.body as VideoPlaylistUpdate
  171. const wasPrivatePlaylist = videoPlaylistInstance.privacy === VideoPlaylistPrivacy.PRIVATE
  172. const wasNotPrivatePlaylist = videoPlaylistInstance.privacy !== VideoPlaylistPrivacy.PRIVATE
  173. const thumbnailField = req.files['thumbnailfile']
  174. const thumbnailModel = thumbnailField
  175. ? await createPlaylistMiniatureFromExisting(thumbnailField[0].path, videoPlaylistInstance)
  176. : undefined
  177. try {
  178. await sequelizeTypescript.transaction(async t => {
  179. const sequelizeOptions = {
  180. transaction: t
  181. }
  182. if (videoPlaylistInfoToUpdate.videoChannelId !== undefined) {
  183. if (videoPlaylistInfoToUpdate.videoChannelId === null) {
  184. videoPlaylistInstance.videoChannelId = null
  185. } else {
  186. const videoChannel = res.locals.videoChannel
  187. videoPlaylistInstance.videoChannelId = videoChannel.id
  188. videoPlaylistInstance.VideoChannel = videoChannel
  189. }
  190. }
  191. if (videoPlaylistInfoToUpdate.displayName !== undefined) videoPlaylistInstance.name = videoPlaylistInfoToUpdate.displayName
  192. if (videoPlaylistInfoToUpdate.description !== undefined) videoPlaylistInstance.description = videoPlaylistInfoToUpdate.description
  193. if (videoPlaylistInfoToUpdate.privacy !== undefined) {
  194. videoPlaylistInstance.privacy = parseInt(videoPlaylistInfoToUpdate.privacy.toString(), 10)
  195. if (wasNotPrivatePlaylist === true && videoPlaylistInstance.privacy === VideoPlaylistPrivacy.PRIVATE) {
  196. await sendDeleteVideoPlaylist(videoPlaylistInstance, t)
  197. }
  198. }
  199. const playlistUpdated = await videoPlaylistInstance.save(sequelizeOptions)
  200. if (thumbnailModel) await playlistUpdated.setAndSaveThumbnail(thumbnailModel, t)
  201. const isNewPlaylist = wasPrivatePlaylist && playlistUpdated.privacy !== VideoPlaylistPrivacy.PRIVATE
  202. if (isNewPlaylist) {
  203. await sendCreateVideoPlaylist(playlistUpdated, t)
  204. } else {
  205. await sendUpdateVideoPlaylist(playlistUpdated, t)
  206. }
  207. logger.info('Video playlist %s updated.', videoPlaylistInstance.uuid)
  208. return playlistUpdated
  209. })
  210. } catch (err) {
  211. logger.debug('Cannot update the video playlist.', { err })
  212. // Force fields we want to update
  213. // If the transaction is retried, sequelize will think the object has not changed
  214. // So it will skip the SQL request, even if the last one was ROLLBACKed!
  215. resetSequelizeInstance(videoPlaylistInstance, videoPlaylistFieldsSave)
  216. throw err
  217. }
  218. return res.type('json').status(204).end()
  219. }
  220. async function removeVideoPlaylist (req: express.Request, res: express.Response) {
  221. const videoPlaylistInstance = res.locals.videoPlaylist
  222. await sequelizeTypescript.transaction(async t => {
  223. await videoPlaylistInstance.destroy({ transaction: t })
  224. await sendDeleteVideoPlaylist(videoPlaylistInstance, t)
  225. logger.info('Video playlist %s deleted.', videoPlaylistInstance.uuid)
  226. })
  227. return res.type('json').status(204).end()
  228. }
  229. async function addVideoInPlaylist (req: express.Request, res: express.Response) {
  230. const body: VideoPlaylistElementCreate = req.body
  231. const videoPlaylist = res.locals.videoPlaylist
  232. const video = res.locals.video
  233. const playlistElement: VideoPlaylistElementModel = await sequelizeTypescript.transaction(async t => {
  234. const position = await VideoPlaylistElementModel.getNextPositionOf(videoPlaylist.id, t)
  235. const playlistElement = await VideoPlaylistElementModel.create({
  236. url: getVideoPlaylistElementActivityPubUrl(videoPlaylist, video),
  237. position,
  238. startTimestamp: body.startTimestamp || null,
  239. stopTimestamp: body.stopTimestamp || null,
  240. videoPlaylistId: videoPlaylist.id,
  241. videoId: video.id
  242. }, { transaction: t })
  243. videoPlaylist.changed('updatedAt', true)
  244. await videoPlaylist.save({ transaction: t })
  245. await sendUpdateVideoPlaylist(videoPlaylist, t)
  246. return playlistElement
  247. })
  248. // If the user did not set a thumbnail, automatically take the video thumbnail
  249. if (videoPlaylist.hasThumbnail() === false) {
  250. logger.info('Generating default thumbnail to playlist %s.', videoPlaylist.url)
  251. const inputPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, video.getMiniature().filename)
  252. const thumbnailModel = await createPlaylistMiniatureFromExisting(inputPath, videoPlaylist, true)
  253. thumbnailModel.videoPlaylistId = videoPlaylist.id
  254. await thumbnailModel.save()
  255. }
  256. logger.info('Video added in playlist %s at position %d.', videoPlaylist.uuid, playlistElement.position)
  257. return res.json({
  258. videoPlaylistElement: {
  259. id: playlistElement.id
  260. }
  261. }).end()
  262. }
  263. async function updateVideoPlaylistElement (req: express.Request, res: express.Response) {
  264. const body: VideoPlaylistElementUpdate = req.body
  265. const videoPlaylist = res.locals.videoPlaylist
  266. const videoPlaylistElement = res.locals.videoPlaylistElement
  267. const playlistElement: VideoPlaylistElementModel = await sequelizeTypescript.transaction(async t => {
  268. if (body.startTimestamp !== undefined) videoPlaylistElement.startTimestamp = body.startTimestamp
  269. if (body.stopTimestamp !== undefined) videoPlaylistElement.stopTimestamp = body.stopTimestamp
  270. const element = await videoPlaylistElement.save({ transaction: t })
  271. videoPlaylist.changed('updatedAt', true)
  272. await videoPlaylist.save({ transaction: t })
  273. await sendUpdateVideoPlaylist(videoPlaylist, t)
  274. return element
  275. })
  276. logger.info('Element of position %d of playlist %s updated.', playlistElement.position, videoPlaylist.uuid)
  277. return res.type('json').status(204).end()
  278. }
  279. async function removeVideoFromPlaylist (req: express.Request, res: express.Response) {
  280. const videoPlaylistElement = res.locals.videoPlaylistElement
  281. const videoPlaylist = res.locals.videoPlaylist
  282. const positionToDelete = videoPlaylistElement.position
  283. await sequelizeTypescript.transaction(async t => {
  284. await videoPlaylistElement.destroy({ transaction: t })
  285. // Decrease position of the next elements
  286. await VideoPlaylistElementModel.increasePositionOf(videoPlaylist.id, positionToDelete, null, -1, t)
  287. videoPlaylist.changed('updatedAt', true)
  288. await videoPlaylist.save({ transaction: t })
  289. await sendUpdateVideoPlaylist(videoPlaylist, t)
  290. logger.info('Video playlist element %d of playlist %s deleted.', videoPlaylistElement.position, videoPlaylist.uuid)
  291. })
  292. return res.type('json').status(204).end()
  293. }
  294. async function reorderVideosPlaylist (req: express.Request, res: express.Response) {
  295. const videoPlaylist = res.locals.videoPlaylist
  296. const body: VideoPlaylistReorder = req.body
  297. const start: number = body.startPosition
  298. const insertAfter: number = body.insertAfterPosition
  299. const reorderLength: number = body.reorderLength || 1
  300. if (start === insertAfter) {
  301. return res.status(204).end()
  302. }
  303. // Example: if we reorder position 2 and insert after position 5 (so at position 6): # 1 2 3 4 5 6 7 8 9
  304. // * increase position when position > 5 # 1 2 3 4 5 7 8 9 10
  305. // * update position 2 -> position 6 # 1 3 4 5 6 7 8 9 10
  306. // * decrease position when position position > 2 # 1 2 3 4 5 6 7 8 9
  307. await sequelizeTypescript.transaction(async t => {
  308. const newPosition = insertAfter + 1
  309. // Add space after the position when we want to insert our reordered elements (increase)
  310. await VideoPlaylistElementModel.increasePositionOf(videoPlaylist.id, newPosition, null, reorderLength, t)
  311. let oldPosition = start
  312. // We incremented the position of the elements we want to reorder
  313. if (start >= newPosition) oldPosition += reorderLength
  314. const endOldPosition = oldPosition + reorderLength - 1
  315. // Insert our reordered elements in their place (update)
  316. await VideoPlaylistElementModel.reassignPositionOf(videoPlaylist.id, oldPosition, endOldPosition, newPosition, t)
  317. // Decrease positions of elements after the old position of our ordered elements (decrease)
  318. await VideoPlaylistElementModel.increasePositionOf(videoPlaylist.id, oldPosition, null, -reorderLength, t)
  319. videoPlaylist.changed('updatedAt', true)
  320. await videoPlaylist.save({ transaction: t })
  321. await sendUpdateVideoPlaylist(videoPlaylist, t)
  322. })
  323. logger.info(
  324. 'Reordered playlist %s (inserted after %d elements %d - %d).',
  325. videoPlaylist.uuid, insertAfter, start, start + reorderLength - 1
  326. )
  327. return res.type('json').status(204).end()
  328. }
  329. async function getVideoPlaylistVideos (req: express.Request, res: express.Response) {
  330. const videoPlaylistInstance = res.locals.videoPlaylist
  331. const followerActorId = isUserAbleToSearchRemoteURI(res) ? null : undefined
  332. const resultList = await VideoModel.listForApi({
  333. followerActorId,
  334. start: req.query.start,
  335. count: req.query.count,
  336. sort: 'VideoPlaylistElements.position',
  337. includeLocalVideos: true,
  338. categoryOneOf: req.query.categoryOneOf,
  339. licenceOneOf: req.query.licenceOneOf,
  340. languageOneOf: req.query.languageOneOf,
  341. tagsOneOf: req.query.tagsOneOf,
  342. tagsAllOf: req.query.tagsAllOf,
  343. filter: req.query.filter,
  344. nsfw: buildNSFWFilter(res, req.query.nsfw),
  345. withFiles: false,
  346. videoPlaylistId: videoPlaylistInstance.id,
  347. user: res.locals.oauth ? res.locals.oauth.token.User : undefined
  348. })
  349. const additionalAttributes = { playlistInfo: true }
  350. return res.json(getFormattedObjects(resultList.data, resultList.total, { additionalAttributes }))
  351. }