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, 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'
32 VIDEO_PLAYLIST_PRIVACIES,
34 } from '../../initializers'
35 import { VideoPlaylist } from '../../../shared/models/videos/playlist/video-playlist.model'
36 import { AccountModel, ScopeNames as AccountScopeNames } from '../account/account'
37 import { ScopeNames as VideoChannelScopeNames, VideoChannelModel } from './video-channel'
38 import { join } from 'path'
39 import { VideoPlaylistElementModel } from './video-playlist-element'
40 import { PlaylistObject } from '../../../shared/models/activitypub/objects/playlist-object'
41 import { activityPubCollectionPagination } from '../../helpers/activitypub'
42 import { remove } from 'fs-extra'
43 import { logger } from '../../helpers/logger'
44 import { VideoPlaylistType } from '../../../shared/models/videos/playlist/video-playlist-type.model'
47 AVAILABLE_FOR_LIST = 'AVAILABLE_FOR_LIST',
48 WITH_VIDEOS_LENGTH = 'WITH_VIDEOS_LENGTH',
49 WITH_ACCOUNT_AND_CHANNEL_SUMMARY = 'WITH_ACCOUNT_AND_CHANNEL_SUMMARY',
50 WITH_ACCOUNT = 'WITH_ACCOUNT',
51 WITH_ACCOUNT_AND_CHANNEL = 'WITH_ACCOUNT_AND_CHANNEL'
54 type AvailableForListOptions = {
55 followerActorId: number
56 type?: VideoPlaylistType
58 videoChannelId?: number
59 privateAndUnlisted?: boolean
63 [ ScopeNames.WITH_VIDEOS_LENGTH ]: {
67 Sequelize.literal('(SELECT COUNT("id") FROM "videoPlaylistElement" WHERE "videoPlaylistId" = "VideoPlaylistModel"."id")'),
73 [ ScopeNames.WITH_ACCOUNT ]: {
76 model: () => AccountModel,
81 [ ScopeNames.WITH_ACCOUNT_AND_CHANNEL_SUMMARY ]: {
84 model: () => AccountModel.scope(AccountScopeNames.SUMMARY),
88 model: () => VideoChannelModel.scope(VideoChannelScopeNames.SUMMARY),
93 [ ScopeNames.WITH_ACCOUNT_AND_CHANNEL ]: {
96 model: () => AccountModel,
100 model: () => VideoChannelModel,
105 [ ScopeNames.AVAILABLE_FOR_LIST ]: (options: AvailableForListOptions) => {
106 // Only list local playlists OR playlists that are on an instance followed by actorId
107 const inQueryInstanceFollow = buildServerIdsFollowedBy(options.followerActorId)
109 [ Sequelize.Op.or ]: [
115 [ Sequelize.Op.in ]: Sequelize.literal(inQueryInstanceFollow)
121 const whereAnd: any[] = []
123 if (options.privateAndUnlisted !== true) {
125 privacy: VideoPlaylistPrivacy.PUBLIC
129 if (options.accountId) {
131 ownerAccountId: options.accountId
135 if (options.videoChannelId) {
137 videoChannelId: options.videoChannelId
148 [Sequelize.Op.and]: whereAnd
151 const accountScope = {
152 method: [ AccountScopeNames.SUMMARY, actorWhere ]
159 model: AccountModel.scope(accountScope),
163 model: VideoChannelModel.scope(VideoChannelScopeNames.SUMMARY),
172 tableName: 'videoPlaylist',
175 fields: [ 'ownerAccountId' ]
178 fields: [ 'videoChannelId' ]
186 export class VideoPlaylistModel extends Model<VideoPlaylistModel> {
194 @Is('VideoPlaylistName', value => throwIfNotValid(value, isVideoPlaylistNameValid, 'name'))
199 @Is('VideoPlaylistDescription', value => throwIfNotValid(value, isVideoPlaylistDescriptionValid, 'description'))
204 @Is('VideoPlaylistPrivacy', value => throwIfNotValid(value, isVideoPlaylistPrivacyValid, 'privacy'))
206 privacy: VideoPlaylistPrivacy
209 @Is('VideoPlaylistUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
210 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_PLAYLISTS.URL.max))
214 @Default(DataType.UUIDV4)
216 @Column(DataType.UUID)
220 @Default(VideoPlaylistType.REGULAR)
222 type: VideoPlaylistType
224 @ForeignKey(() => AccountModel)
226 ownerAccountId: number
228 @BelongsTo(() => AccountModel, {
234 OwnerAccount: AccountModel
236 @ForeignKey(() => VideoChannelModel)
238 videoChannelId: number
240 @BelongsTo(() => VideoChannelModel, {
246 VideoChannel: VideoChannelModel
248 @HasMany(() => VideoPlaylistElementModel, {
250 name: 'videoPlaylistId',
255 VideoPlaylistElements: VideoPlaylistElementModel[]
258 static async removeFiles (instance: VideoPlaylistModel) {
259 logger.info('Removing files of video playlist %s.', instance.url)
261 return instance.removeThumbnail()
264 static listForApi (options: {
265 followerActorId: number
269 type?: VideoPlaylistType,
271 videoChannelId?: number,
272 privateAndUnlisted?: boolean
275 offset: options.start,
276 limit: options.count,
277 order: getSort(options.sort)
283 ScopeNames.AVAILABLE_FOR_LIST,
286 followerActorId: options.followerActorId,
287 accountId: options.accountId,
288 videoChannelId: options.videoChannelId,
289 privateAndUnlisted: options.privateAndUnlisted
290 } as AvailableForListOptions
292 } as any, // FIXME: typings
293 ScopeNames.WITH_VIDEOS_LENGTH
296 return VideoPlaylistModel
298 .findAndCountAll(query)
299 .then(({ rows, count }) => {
300 return { total: count, data: rows }
304 static listPublicUrlsOfForAP (accountId: number, start: number, count: number) {
306 attributes: [ 'url' ],
310 ownerAccountId: accountId,
311 privacy: VideoPlaylistPrivacy.PUBLIC
315 return VideoPlaylistModel.findAndCountAll(query)
316 .then(({ rows, count }) => {
317 return { total: count, data: rows.map(p => p.url) }
321 static listPlaylistIdsOf (accountId: number, videoIds: number[]) {
323 attributes: [ 'id' ],
325 ownerAccountId: accountId
329 attributes: [ 'videoId', 'startTimestamp', 'stopTimestamp' ],
330 model: VideoPlaylistElementModel.unscoped(),
333 [Sequelize.Op.any]: videoIds
341 return VideoPlaylistModel.findAll(query)
344 static doesPlaylistExist (url: string) {
352 return VideoPlaylistModel
357 static loadWithAccountAndChannelSummary (id: number | string, transaction: Sequelize.Transaction) {
358 const where = buildWhereIdOrUUID(id)
365 return VideoPlaylistModel
366 .scope([ ScopeNames.WITH_ACCOUNT_AND_CHANNEL_SUMMARY, ScopeNames.WITH_VIDEOS_LENGTH ])
370 static loadWithAccountAndChannel (id: number | string, transaction: Sequelize.Transaction) {
371 const where = buildWhereIdOrUUID(id)
378 return VideoPlaylistModel
379 .scope([ ScopeNames.WITH_ACCOUNT_AND_CHANNEL, ScopeNames.WITH_VIDEOS_LENGTH ])
383 static loadByUrlAndPopulateAccount (url: string) {
390 return VideoPlaylistModel.scope(ScopeNames.WITH_ACCOUNT).findOne(query)
393 static getPrivacyLabel (privacy: VideoPlaylistPrivacy) {
394 return VIDEO_PLAYLIST_PRIVACIES[privacy] || 'Unknown'
397 static getTypeLabel (type: VideoPlaylistType) {
398 return VIDEO_PLAYLIST_TYPES[type] || 'Unknown'
401 static resetPlaylistsOfChannel (videoChannelId: number, transaction: Sequelize.Transaction) {
409 return VideoPlaylistModel.update({ privacy: VideoPlaylistPrivacy.PRIVATE, videoChannelId: null }, query)
412 getThumbnailName () {
413 const extension = '.jpg'
415 return 'playlist-' + this.uuid + extension
419 return CONFIG.WEBSERVER.URL + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
422 getThumbnailStaticPath () {
423 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
427 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
428 return remove(thumbnailPath)
429 .catch(err => logger.warn('Cannot delete thumbnail %s.', thumbnailPath, { err }))
433 return this.OwnerAccount.isOwned()
436 toFormattedJSON (): VideoPlaylist {
440 isLocal: this.isOwned(),
442 displayName: this.name,
443 description: this.description,
446 label: VideoPlaylistModel.getPrivacyLabel(this.privacy)
449 thumbnailPath: this.getThumbnailStaticPath(),
453 label: VideoPlaylistModel.getTypeLabel(this.type)
456 videosLength: this.get('videosLength'),
458 createdAt: this.createdAt,
459 updatedAt: this.updatedAt,
461 ownerAccount: this.OwnerAccount.toFormattedSummaryJSON(),
462 videoChannel: this.VideoChannel ? this.VideoChannel.toFormattedSummaryJSON() : null
466 toActivityPubObject (page: number, t: Sequelize.Transaction): Promise<PlaylistObject> {
467 const handler = (start: number, count: number) => {
468 return VideoPlaylistElementModel.listUrlsOfForAP(this.id, start, count, t)
471 return activityPubCollectionPagination(this.url, handler, page)
473 return Object.assign(o, {
474 type: 'Playlist' as 'Playlist',
476 content: this.description,
478 published: this.createdAt.toISOString(),
479 updated: this.updatedAt.toISOString(),
480 attributedTo: this.VideoChannel ? [ this.VideoChannel.Actor.url ] : [],
482 type: 'Image' as 'Image',
483 url: this.getThumbnailUrl(),
484 mediaType: 'image/jpeg' as 'image/jpeg',
485 width: THUMBNAILS_SIZE.width,
486 height: THUMBNAILS_SIZE.height