17 } from 'sequelize-typescript'
18 import { VideoPlaylistPrivacy } from '../../../shared/models/videos/playlist/video-playlist-privacy.model'
19 import { buildServerIdsFollowedBy, buildWhereIdOrUUID, getSort, isOutdated, throwIfNotValid } from '../utils'
21 isVideoPlaylistDescriptionValid,
22 isVideoPlaylistNameValid,
23 isVideoPlaylistPrivacyValid
24 } from '../../helpers/custom-validators/video-playlists'
25 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
31 VIDEO_PLAYLIST_PRIVACIES,
34 } from '../../initializers/constants'
35 import { VideoPlaylist } from '../../../shared/models/videos/playlist/video-playlist.model'
36 import { AccountModel, ScopeNames as AccountScopeNames, SummaryOptions } 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 { VideoPlaylistType } from '../../../shared/models/videos/playlist/video-playlist-type.model'
43 import { ThumbnailModel } from './thumbnail'
44 import { ActivityIconObject } from '../../../shared/models/activitypub/objects'
45 import { FindOptions, literal, Op, ScopeOptions, Transaction, WhereOptions } from 'sequelize'
46 import * as Bluebird from 'bluebird'
48 MVideoPlaylistAccountThumbnail,
50 MVideoPlaylistFormattable,
52 MVideoPlaylistFullSummary,
53 MVideoPlaylistIdWithElements
54 } from '../../typings/models/video/video-playlist'
55 import { MThumbnail } from '../../typings/models/video/thumbnail'
58 AVAILABLE_FOR_LIST = 'AVAILABLE_FOR_LIST',
59 WITH_VIDEOS_LENGTH = 'WITH_VIDEOS_LENGTH',
60 WITH_ACCOUNT_AND_CHANNEL_SUMMARY = 'WITH_ACCOUNT_AND_CHANNEL_SUMMARY',
61 WITH_ACCOUNT = 'WITH_ACCOUNT',
62 WITH_THUMBNAIL = 'WITH_THUMBNAIL',
63 WITH_ACCOUNT_AND_CHANNEL = 'WITH_ACCOUNT_AND_CHANNEL'
66 type AvailableForListOptions = {
67 followerActorId: number
68 type?: VideoPlaylistType
70 videoChannelId?: number
71 listMyPlaylists?: boolean
76 [ScopeNames.WITH_THUMBNAIL]: {
79 model: ThumbnailModel,
84 [ScopeNames.WITH_VIDEOS_LENGTH]: {
88 literal('(SELECT COUNT("id") FROM "videoPlaylistElement" WHERE "videoPlaylistId" = "VideoPlaylistModel"."id")'),
94 [ScopeNames.WITH_ACCOUNT]: {
102 [ScopeNames.WITH_ACCOUNT_AND_CHANNEL_SUMMARY]: {
105 model: AccountModel.scope(AccountScopeNames.SUMMARY),
109 model: VideoChannelModel.scope(VideoChannelScopeNames.SUMMARY),
114 [ScopeNames.WITH_ACCOUNT_AND_CHANNEL]: {
121 model: VideoChannelModel,
126 [ScopeNames.AVAILABLE_FOR_LIST]: (options: AvailableForListOptions) => {
128 let whereActor: WhereOptions = {}
130 const whereAnd: WhereOptions[] = []
132 if (options.listMyPlaylists !== true) {
134 privacy: VideoPlaylistPrivacy.PUBLIC
137 // Only list local playlists OR playlists that are on an instance followed by actorId
138 const inQueryInstanceFollow = buildServerIdsFollowedBy(options.followerActorId)
147 [Op.in]: literal(inQueryInstanceFollow)
154 if (options.accountId) {
156 ownerAccountId: options.accountId
160 if (options.videoChannelId) {
162 videoChannelId: options.videoChannelId
172 if (options.search) {
175 [Op.iLike]: '%' + options.search + '%'
184 const accountScope = {
185 method: [ AccountScopeNames.SUMMARY, { whereActor } as SummaryOptions ]
192 model: AccountModel.scope(accountScope),
196 model: VideoChannelModel.scope(VideoChannelScopeNames.SUMMARY),
205 tableName: 'videoPlaylist',
208 fields: [ 'ownerAccountId' ]
211 fields: [ 'videoChannelId' ]
219 export class VideoPlaylistModel extends Model<VideoPlaylistModel> {
227 @Is('VideoPlaylistName', value => throwIfNotValid(value, isVideoPlaylistNameValid, 'name'))
232 @Is('VideoPlaylistDescription', value => throwIfNotValid(value, isVideoPlaylistDescriptionValid, 'description', true))
237 @Is('VideoPlaylistPrivacy', value => throwIfNotValid(value, isVideoPlaylistPrivacyValid, 'privacy'))
239 privacy: VideoPlaylistPrivacy
242 @Is('VideoPlaylistUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
243 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_PLAYLISTS.URL.max))
247 @Default(DataType.UUIDV4)
249 @Column(DataType.UUID)
253 @Default(VideoPlaylistType.REGULAR)
255 type: VideoPlaylistType
257 @ForeignKey(() => AccountModel)
259 ownerAccountId: number
261 @BelongsTo(() => AccountModel, {
267 OwnerAccount: AccountModel
269 @ForeignKey(() => VideoChannelModel)
271 videoChannelId: number
273 @BelongsTo(() => VideoChannelModel, {
279 VideoChannel: VideoChannelModel
281 @HasMany(() => VideoPlaylistElementModel, {
283 name: 'videoPlaylistId',
288 VideoPlaylistElements: VideoPlaylistElementModel[]
290 @HasOne(() => ThumbnailModel, {
292 name: 'videoPlaylistId',
298 Thumbnail: ThumbnailModel
300 static listForApi (options: {
301 followerActorId: number
305 type?: VideoPlaylistType
307 videoChannelId?: number
308 listMyPlaylists?: boolean
312 offset: options.start,
313 limit: options.count,
314 order: getSort(options.sort)
317 const scopes: (string | ScopeOptions)[] = [
320 ScopeNames.AVAILABLE_FOR_LIST,
323 followerActorId: options.followerActorId,
324 accountId: options.accountId,
325 videoChannelId: options.videoChannelId,
326 listMyPlaylists: options.listMyPlaylists,
327 search: options.search
328 } as AvailableForListOptions
331 ScopeNames.WITH_VIDEOS_LENGTH,
332 ScopeNames.WITH_THUMBNAIL
335 return VideoPlaylistModel
337 .findAndCountAll(query)
338 .then(({ rows, count }) => {
339 return { total: count, data: rows }
343 static listPublicUrlsOfForAP (accountId: number, start: number, count: number) {
345 attributes: [ 'url' ],
349 ownerAccountId: accountId,
350 privacy: VideoPlaylistPrivacy.PUBLIC
354 return VideoPlaylistModel.findAndCountAll(query)
355 .then(({ rows, count }) => {
356 return { total: count, data: rows.map(p => p.url) }
360 static listPlaylistIdsOf (accountId: number, videoIds: number[]): Bluebird<MVideoPlaylistIdWithElements[]> {
362 attributes: [ 'id' ],
364 ownerAccountId: accountId
368 attributes: [ 'id', 'videoId', 'startTimestamp', 'stopTimestamp' ],
369 model: VideoPlaylistElementModel.unscoped(),
380 return VideoPlaylistModel.findAll(query)
383 static doesPlaylistExist (url: string) {
391 return VideoPlaylistModel
396 static loadWithAccountAndChannelSummary (id: number | string, transaction: Transaction): Bluebird<MVideoPlaylistFullSummary> {
397 const where = buildWhereIdOrUUID(id)
404 return VideoPlaylistModel
405 .scope([ ScopeNames.WITH_ACCOUNT_AND_CHANNEL_SUMMARY, ScopeNames.WITH_VIDEOS_LENGTH, ScopeNames.WITH_THUMBNAIL ])
409 static loadWithAccountAndChannel (id: number | string, transaction: Transaction): Bluebird<MVideoPlaylistFull> {
410 const where = buildWhereIdOrUUID(id)
417 return VideoPlaylistModel
418 .scope([ ScopeNames.WITH_ACCOUNT_AND_CHANNEL, ScopeNames.WITH_VIDEOS_LENGTH, ScopeNames.WITH_THUMBNAIL ])
422 static loadByUrlAndPopulateAccount (url: string): Bluebird<MVideoPlaylistAccountThumbnail> {
429 return VideoPlaylistModel.scope([ ScopeNames.WITH_ACCOUNT, ScopeNames.WITH_THUMBNAIL ]).findOne(query)
432 static getPrivacyLabel (privacy: VideoPlaylistPrivacy) {
433 return VIDEO_PLAYLIST_PRIVACIES[privacy] || 'Unknown'
436 static getTypeLabel (type: VideoPlaylistType) {
437 return VIDEO_PLAYLIST_TYPES[type] || 'Unknown'
440 static resetPlaylistsOfChannel (videoChannelId: number, transaction: Transaction) {
448 return VideoPlaylistModel.update({ privacy: VideoPlaylistPrivacy.PRIVATE, videoChannelId: null }, query)
451 async setAndSaveThumbnail (thumbnail: MThumbnail, t: Transaction) {
452 thumbnail.videoPlaylistId = this.id
454 this.Thumbnail = await thumbnail.save({ transaction: t })
458 return !!this.Thumbnail
461 hasGeneratedThumbnail () {
462 return this.hasThumbnail() && this.Thumbnail.automaticallyGenerated === true
465 generateThumbnailName () {
466 const extension = '.jpg'
468 return 'playlist-' + this.uuid + extension
472 if (!this.hasThumbnail()) return null
474 return WEBSERVER.URL + STATIC_PATHS.THUMBNAILS + this.Thumbnail.filename
477 getThumbnailStaticPath () {
478 if (!this.hasThumbnail()) return null
480 return join(STATIC_PATHS.THUMBNAILS, this.Thumbnail.filename)
484 this.changed('updatedAt', true)
490 return this.OwnerAccount.isOwned()
494 if (this.isOwned()) return false
496 return isOutdated(this, ACTIVITY_PUB.VIDEO_PLAYLIST_REFRESH_INTERVAL)
499 toFormattedJSON (this: MVideoPlaylistFormattable): VideoPlaylist {
503 isLocal: this.isOwned(),
505 displayName: this.name,
506 description: this.description,
509 label: VideoPlaylistModel.getPrivacyLabel(this.privacy)
512 thumbnailPath: this.getThumbnailStaticPath(),
516 label: VideoPlaylistModel.getTypeLabel(this.type)
519 videosLength: this.get('videosLength') as number,
521 createdAt: this.createdAt,
522 updatedAt: this.updatedAt,
524 ownerAccount: this.OwnerAccount.toFormattedSummaryJSON(),
525 videoChannel: this.VideoChannel ? this.VideoChannel.toFormattedSummaryJSON() : null
529 toActivityPubObject (this: MVideoPlaylistAP, page: number, t: Transaction): Promise<PlaylistObject> {
530 const handler = (start: number, count: number) => {
531 return VideoPlaylistElementModel.listUrlsOfForAP(this.id, start, count, t)
534 let icon: ActivityIconObject
535 if (this.hasThumbnail()) {
537 type: 'Image' as 'Image',
538 url: this.getThumbnailUrl(),
539 mediaType: 'image/jpeg' as 'image/jpeg',
540 width: THUMBNAILS_SIZE.width,
541 height: THUMBNAILS_SIZE.height
545 return activityPubCollectionPagination(this.url, handler, page)
547 return Object.assign(o, {
548 type: 'Playlist' as 'Playlist',
550 content: this.description,
552 published: this.createdAt.toISOString(),
553 updated: this.updatedAt.toISOString(),
554 attributedTo: this.VideoChannel ? [ this.VideoChannel.Actor.url ] : [],