17 } from 'sequelize-typescript'
18 import * as Sequelize from 'sequelize'
19 import { VideoPlaylistPrivacy } from '../../../shared/models/videos/playlist/video-playlist-privacy.model'
20 import { buildServerIdsFollowedBy, buildWhereIdOrUUID, getSort, isOutdated, throwIfNotValid } from '../utils'
22 isVideoPlaylistDescriptionValid,
23 isVideoPlaylistNameValid,
24 isVideoPlaylistPrivacyValid
25 } from '../../helpers/custom-validators/video-playlists'
26 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
33 VIDEO_PLAYLIST_PRIVACIES,
35 } from '../../initializers'
36 import { VideoPlaylist } from '../../../shared/models/videos/playlist/video-playlist.model'
37 import { AccountModel, ScopeNames as AccountScopeNames } from '../account/account'
38 import { ScopeNames as VideoChannelScopeNames, VideoChannelModel } from './video-channel'
39 import { join } from 'path'
40 import { VideoPlaylistElementModel } from './video-playlist-element'
41 import { PlaylistObject } from '../../../shared/models/activitypub/objects/playlist-object'
42 import { activityPubCollectionPagination } from '../../helpers/activitypub'
43 import { remove } from 'fs-extra'
44 import { logger } from '../../helpers/logger'
45 import { VideoPlaylistType } from '../../../shared/models/videos/playlist/video-playlist-type.model'
48 AVAILABLE_FOR_LIST = 'AVAILABLE_FOR_LIST',
49 WITH_VIDEOS_LENGTH = 'WITH_VIDEOS_LENGTH',
50 WITH_ACCOUNT_AND_CHANNEL_SUMMARY = 'WITH_ACCOUNT_AND_CHANNEL_SUMMARY',
51 WITH_ACCOUNT = 'WITH_ACCOUNT',
52 WITH_ACCOUNT_AND_CHANNEL = 'WITH_ACCOUNT_AND_CHANNEL'
55 type AvailableForListOptions = {
56 followerActorId: number
57 type?: VideoPlaylistType
59 videoChannelId?: number
60 privateAndUnlisted?: boolean
64 [ ScopeNames.WITH_VIDEOS_LENGTH ]: {
68 Sequelize.literal('(SELECT COUNT("id") FROM "videoPlaylistElement" WHERE "videoPlaylistId" = "VideoPlaylistModel"."id")'),
74 [ ScopeNames.WITH_ACCOUNT ]: {
77 model: () => AccountModel,
82 [ ScopeNames.WITH_ACCOUNT_AND_CHANNEL_SUMMARY ]: {
85 model: () => AccountModel.scope(AccountScopeNames.SUMMARY),
89 model: () => VideoChannelModel.scope(VideoChannelScopeNames.SUMMARY),
94 [ ScopeNames.WITH_ACCOUNT_AND_CHANNEL ]: {
97 model: () => AccountModel,
101 model: () => VideoChannelModel,
106 [ ScopeNames.AVAILABLE_FOR_LIST ]: (options: AvailableForListOptions) => {
107 // Only list local playlists OR playlists that are on an instance followed by actorId
108 const inQueryInstanceFollow = buildServerIdsFollowedBy(options.followerActorId)
110 [ Sequelize.Op.or ]: [
116 [ Sequelize.Op.in ]: Sequelize.literal(inQueryInstanceFollow)
122 const whereAnd: any[] = []
124 if (options.privateAndUnlisted !== true) {
126 privacy: VideoPlaylistPrivacy.PUBLIC
130 if (options.accountId) {
132 ownerAccountId: options.accountId
136 if (options.videoChannelId) {
138 videoChannelId: options.videoChannelId
149 [Sequelize.Op.and]: whereAnd
152 const accountScope = {
153 method: [ AccountScopeNames.SUMMARY, actorWhere ]
160 model: AccountModel.scope(accountScope),
164 model: VideoChannelModel.scope(VideoChannelScopeNames.SUMMARY),
173 tableName: 'videoPlaylist',
176 fields: [ 'ownerAccountId' ]
179 fields: [ 'videoChannelId' ]
187 export class VideoPlaylistModel extends Model<VideoPlaylistModel> {
195 @Is('VideoPlaylistName', value => throwIfNotValid(value, isVideoPlaylistNameValid, 'name'))
200 @Is('VideoPlaylistDescription', value => throwIfNotValid(value, isVideoPlaylistDescriptionValid, 'description'))
205 @Is('VideoPlaylistPrivacy', value => throwIfNotValid(value, isVideoPlaylistPrivacyValid, 'privacy'))
207 privacy: VideoPlaylistPrivacy
210 @Is('VideoPlaylistUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
211 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_PLAYLISTS.URL.max))
215 @Default(DataType.UUIDV4)
217 @Column(DataType.UUID)
221 @Default(VideoPlaylistType.REGULAR)
223 type: VideoPlaylistType
225 @ForeignKey(() => AccountModel)
227 ownerAccountId: number
229 @BelongsTo(() => AccountModel, {
235 OwnerAccount: AccountModel
237 @ForeignKey(() => VideoChannelModel)
239 videoChannelId: number
241 @BelongsTo(() => VideoChannelModel, {
247 VideoChannel: VideoChannelModel
249 @HasMany(() => VideoPlaylistElementModel, {
251 name: 'videoPlaylistId',
256 VideoPlaylistElements: VideoPlaylistElementModel[]
259 static async removeFiles (instance: VideoPlaylistModel) {
260 logger.info('Removing files of video playlist %s.', instance.url)
262 return instance.removeThumbnail()
265 static listForApi (options: {
266 followerActorId: number
270 type?: VideoPlaylistType,
272 videoChannelId?: number,
273 privateAndUnlisted?: boolean
276 offset: options.start,
277 limit: options.count,
278 order: getSort(options.sort)
284 ScopeNames.AVAILABLE_FOR_LIST,
287 followerActorId: options.followerActorId,
288 accountId: options.accountId,
289 videoChannelId: options.videoChannelId,
290 privateAndUnlisted: options.privateAndUnlisted
291 } as AvailableForListOptions
293 } as any, // FIXME: typings
294 ScopeNames.WITH_VIDEOS_LENGTH
297 return VideoPlaylistModel
299 .findAndCountAll(query)
300 .then(({ rows, count }) => {
301 return { total: count, data: rows }
305 static listPublicUrlsOfForAP (accountId: number, start: number, count: number) {
307 attributes: [ 'url' ],
311 ownerAccountId: accountId,
312 privacy: VideoPlaylistPrivacy.PUBLIC
316 return VideoPlaylistModel.findAndCountAll(query)
317 .then(({ rows, count }) => {
318 return { total: count, data: rows.map(p => p.url) }
322 static listPlaylistIdsOf (accountId: number, videoIds: number[]) {
324 attributes: [ 'id' ],
326 ownerAccountId: accountId
330 attributes: [ 'videoId', 'startTimestamp', 'stopTimestamp' ],
331 model: VideoPlaylistElementModel.unscoped(),
334 [Sequelize.Op.any]: videoIds
342 return VideoPlaylistModel.findAll(query)
345 static doesPlaylistExist (url: string) {
353 return VideoPlaylistModel
358 static loadWithAccountAndChannelSummary (id: number | string, transaction: Sequelize.Transaction) {
359 const where = buildWhereIdOrUUID(id)
366 return VideoPlaylistModel
367 .scope([ ScopeNames.WITH_ACCOUNT_AND_CHANNEL_SUMMARY, ScopeNames.WITH_VIDEOS_LENGTH ])
371 static loadWithAccountAndChannel (id: number | string, transaction: Sequelize.Transaction) {
372 const where = buildWhereIdOrUUID(id)
379 return VideoPlaylistModel
380 .scope([ ScopeNames.WITH_ACCOUNT_AND_CHANNEL, ScopeNames.WITH_VIDEOS_LENGTH ])
384 static loadByUrlAndPopulateAccount (url: string) {
391 return VideoPlaylistModel.scope(ScopeNames.WITH_ACCOUNT).findOne(query)
394 static getPrivacyLabel (privacy: VideoPlaylistPrivacy) {
395 return VIDEO_PLAYLIST_PRIVACIES[privacy] || 'Unknown'
398 static getTypeLabel (type: VideoPlaylistType) {
399 return VIDEO_PLAYLIST_TYPES[type] || 'Unknown'
402 static resetPlaylistsOfChannel (videoChannelId: number, transaction: Sequelize.Transaction) {
410 return VideoPlaylistModel.update({ privacy: VideoPlaylistPrivacy.PRIVATE, videoChannelId: null }, query)
413 getThumbnailName () {
414 const extension = '.jpg'
416 return 'playlist-' + this.uuid + extension
420 return CONFIG.WEBSERVER.URL + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
423 getThumbnailStaticPath () {
424 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
428 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
429 return remove(thumbnailPath)
430 .catch(err => logger.warn('Cannot delete thumbnail %s.', thumbnailPath, { err }))
434 this.changed('updatedAt', true)
440 return this.OwnerAccount.isOwned()
444 if (this.isOwned()) return false
446 return isOutdated(this, ACTIVITY_PUB.VIDEO_PLAYLIST_REFRESH_INTERVAL)
449 toFormattedJSON (): VideoPlaylist {
453 isLocal: this.isOwned(),
455 displayName: this.name,
456 description: this.description,
459 label: VideoPlaylistModel.getPrivacyLabel(this.privacy)
462 thumbnailPath: this.getThumbnailStaticPath(),
466 label: VideoPlaylistModel.getTypeLabel(this.type)
469 videosLength: this.get('videosLength'),
471 createdAt: this.createdAt,
472 updatedAt: this.updatedAt,
474 ownerAccount: this.OwnerAccount.toFormattedSummaryJSON(),
475 videoChannel: this.VideoChannel ? this.VideoChannel.toFormattedSummaryJSON() : null
479 toActivityPubObject (page: number, t: Sequelize.Transaction): Promise<PlaylistObject> {
480 const handler = (start: number, count: number) => {
481 return VideoPlaylistElementModel.listUrlsOfForAP(this.id, start, count, t)
484 return activityPubCollectionPagination(this.url, handler, page)
486 return Object.assign(o, {
487 type: 'Playlist' as 'Playlist',
489 content: this.description,
491 published: this.createdAt.toISOString(),
492 updated: this.updatedAt.toISOString(),
493 attributedTo: this.VideoChannel ? [ this.VideoChannel.Actor.url ] : [],
495 type: 'Image' as 'Image',
496 url: this.getThumbnailUrl(),
497 mediaType: 'image/jpeg' as 'image/jpeg',
498 width: THUMBNAILS_SIZE.width,
499 height: THUMBNAILS_SIZE.height