video-playlist.ts 18 KB

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