18 } from 'sequelize-typescript'
19 import { VideoPlaylistPrivacy } from '../../../shared/models/videos/playlist/video-playlist-privacy.model'
20 import { buildServerIdsFollowedBy, buildWhereIdOrUUID, getSort, isOutdated, throwIfNotValid, createSimilarityAttribute } 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,
35 } from '../../initializers/constants'
36 import { VideoPlaylist } from '../../../shared/models/videos/playlist/video-playlist.model'
37 import { AccountModel, ScopeNames as AccountScopeNames, SummaryOptions } 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 { VideoPlaylistType } from '../../../shared/models/videos/playlist/video-playlist-type.model'
44 import { ThumbnailModel } from './thumbnail'
45 import { ActivityIconObject } from '../../../shared/models/activitypub/objects'
46 import { FindOptions, literal, Op, ScopeOptions, Transaction, WhereOptions } from 'sequelize'
47 import * as Bluebird from 'bluebird'
49 MVideoPlaylistAccountThumbnail, MVideoPlaylistAP,
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 privateAndUnlisted?: 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) => {
127 // Only list local playlists OR playlists that are on an instance followed by actorId
128 const inQueryInstanceFollow = buildServerIdsFollowedBy(options.followerActorId)
136 [ Op.in ]: literal(inQueryInstanceFollow)
142 const whereAnd: WhereOptions[] = []
144 if (options.privateAndUnlisted !== true) {
146 privacy: VideoPlaylistPrivacy.PUBLIC
150 if (options.accountId) {
152 ownerAccountId: options.accountId
156 if (options.videoChannelId) {
158 videoChannelId: options.videoChannelId
168 if (options.search) {
169 const escapedSearch = VideoPlaylistModel.sequelize.escape(options.search)
170 const escapedLikeSearch = VideoPlaylistModel.sequelize.escape('%' + options.search + '%')
173 [ Op.in ]: Sequelize.literal(
175 'SELECT "videoPlaylist"."id" FROM "videoPlaylist" ' +
177 'lower(immutable_unaccent("videoPlaylist"."name")) % lower(immutable_unaccent(' + escapedSearch + ')) OR ' +
178 'lower(immutable_unaccent("videoPlaylist"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))' +
189 const accountScope = {
190 method: [ AccountScopeNames.SUMMARY, { whereActor } as SummaryOptions ]
197 model: AccountModel.scope(accountScope),
201 model: VideoChannelModel.scope(VideoChannelScopeNames.SUMMARY),
210 tableName: 'videoPlaylist',
213 fields: [ 'ownerAccountId' ]
216 fields: [ 'videoChannelId' ]
224 export class VideoPlaylistModel extends Model<VideoPlaylistModel> {
232 @Is('VideoPlaylistName', value => throwIfNotValid(value, isVideoPlaylistNameValid, 'name'))
237 @Is('VideoPlaylistDescription', value => throwIfNotValid(value, isVideoPlaylistDescriptionValid, 'description', true))
242 @Is('VideoPlaylistPrivacy', value => throwIfNotValid(value, isVideoPlaylistPrivacyValid, 'privacy'))
244 privacy: VideoPlaylistPrivacy
247 @Is('VideoPlaylistUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
248 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_PLAYLISTS.URL.max))
252 @Default(DataType.UUIDV4)
254 @Column(DataType.UUID)
258 @Default(VideoPlaylistType.REGULAR)
260 type: VideoPlaylistType
262 @ForeignKey(() => AccountModel)
264 ownerAccountId: number
266 @BelongsTo(() => AccountModel, {
272 OwnerAccount: AccountModel
274 @ForeignKey(() => VideoChannelModel)
276 videoChannelId: number
278 @BelongsTo(() => VideoChannelModel, {
284 VideoChannel: VideoChannelModel
286 @HasMany(() => VideoPlaylistElementModel, {
288 name: 'videoPlaylistId',
293 VideoPlaylistElements: VideoPlaylistElementModel[]
295 @HasOne(() => ThumbnailModel, {
297 name: 'videoPlaylistId',
303 Thumbnail: ThumbnailModel
305 static listForApi (options: {
306 followerActorId: number
310 type?: VideoPlaylistType,
312 videoChannelId?: number,
313 privateAndUnlisted?: boolean,
317 offset: options.start,
318 limit: options.count,
319 order: getSort(options.sort)
322 const scopes: (string | ScopeOptions)[] = [
325 ScopeNames.AVAILABLE_FOR_LIST,
328 followerActorId: options.followerActorId,
329 accountId: options.accountId,
330 videoChannelId: options.videoChannelId,
331 privateAndUnlisted: options.privateAndUnlisted,
332 search: options.search
333 } as AvailableForListOptions
336 ScopeNames.WITH_VIDEOS_LENGTH,
337 ScopeNames.WITH_THUMBNAIL
340 return VideoPlaylistModel
342 .findAndCountAll(query)
343 .then(({ rows, count }) => {
344 return { total: count, data: rows }
348 static listPublicUrlsOfForAP (accountId: number, start: number, count: number) {
350 attributes: [ 'url' ],
354 ownerAccountId: accountId,
355 privacy: VideoPlaylistPrivacy.PUBLIC
359 return VideoPlaylistModel.findAndCountAll(query)
360 .then(({ rows, count }) => {
361 return { total: count, data: rows.map(p => p.url) }
365 static listPlaylistIdsOf (accountId: number, videoIds: number[]): Bluebird<MVideoPlaylistIdWithElements[]> {
367 attributes: [ 'id' ],
369 ownerAccountId: accountId
373 attributes: [ 'id', 'videoId', 'startTimestamp', 'stopTimestamp' ],
374 model: VideoPlaylistElementModel.unscoped(),
377 [Op.in]: videoIds // FIXME: sequelize ANY seems broken
385 return VideoPlaylistModel.findAll(query)
388 static doesPlaylistExist (url: string) {
396 return VideoPlaylistModel
401 static loadWithAccountAndChannelSummary (id: number | string, transaction: Transaction): Bluebird<MVideoPlaylistFullSummary> {
402 const where = buildWhereIdOrUUID(id)
409 return VideoPlaylistModel
410 .scope([ ScopeNames.WITH_ACCOUNT_AND_CHANNEL_SUMMARY, ScopeNames.WITH_VIDEOS_LENGTH, ScopeNames.WITH_THUMBNAIL ])
414 static loadWithAccountAndChannel (id: number | string, transaction: Transaction): Bluebird<MVideoPlaylistFull> {
415 const where = buildWhereIdOrUUID(id)
422 return VideoPlaylistModel
423 .scope([ ScopeNames.WITH_ACCOUNT_AND_CHANNEL, ScopeNames.WITH_VIDEOS_LENGTH, ScopeNames.WITH_THUMBNAIL ])
427 static loadByUrlAndPopulateAccount (url: string): Bluebird<MVideoPlaylistAccountThumbnail> {
434 return VideoPlaylistModel.scope([ ScopeNames.WITH_ACCOUNT, ScopeNames.WITH_THUMBNAIL ]).findOne(query)
437 static getPrivacyLabel (privacy: VideoPlaylistPrivacy) {
438 return VIDEO_PLAYLIST_PRIVACIES[privacy] || 'Unknown'
441 static getTypeLabel (type: VideoPlaylistType) {
442 return VIDEO_PLAYLIST_TYPES[type] || 'Unknown'
445 static resetPlaylistsOfChannel (videoChannelId: number, transaction: Transaction) {
453 return VideoPlaylistModel.update({ privacy: VideoPlaylistPrivacy.PRIVATE, videoChannelId: null }, query)
456 async setAndSaveThumbnail (thumbnail: MThumbnail, t: Transaction) {
457 thumbnail.videoPlaylistId = this.id
459 this.Thumbnail = await thumbnail.save({ transaction: t })
463 return !!this.Thumbnail
466 hasGeneratedThumbnail () {
467 return this.hasThumbnail() && this.Thumbnail.automaticallyGenerated === true
470 generateThumbnailName () {
471 const extension = '.jpg'
473 return 'playlist-' + this.uuid + extension
477 if (!this.hasThumbnail()) return null
479 return WEBSERVER.URL + STATIC_PATHS.THUMBNAILS + this.Thumbnail.filename
482 getThumbnailStaticPath () {
483 if (!this.hasThumbnail()) return null
485 return join(STATIC_PATHS.THUMBNAILS, this.Thumbnail.filename)
489 this.changed('updatedAt', true)
495 return this.OwnerAccount.isOwned()
499 if (this.isOwned()) return false
501 return isOutdated(this, ACTIVITY_PUB.VIDEO_PLAYLIST_REFRESH_INTERVAL)
504 toFormattedJSON (this: MVideoPlaylistFormattable): VideoPlaylist {
508 isLocal: this.isOwned(),
510 displayName: this.name,
511 description: this.description,
514 label: VideoPlaylistModel.getPrivacyLabel(this.privacy)
517 thumbnailPath: this.getThumbnailStaticPath(),
521 label: VideoPlaylistModel.getTypeLabel(this.type)
524 videosLength: this.get('videosLength') as number,
526 createdAt: this.createdAt,
527 updatedAt: this.updatedAt,
529 ownerAccount: this.OwnerAccount.toFormattedSummaryJSON(),
530 videoChannel: this.VideoChannel ? this.VideoChannel.toFormattedSummaryJSON() : null
534 toActivityPubObject (this: MVideoPlaylistAP, page: number, t: Transaction): Promise<PlaylistObject> {
535 const handler = (start: number, count: number) => {
536 return VideoPlaylistElementModel.listUrlsOfForAP(this.id, start, count, t)
539 let icon: ActivityIconObject
540 if (this.hasThumbnail()) {
542 type: 'Image' as 'Image',
543 url: this.getThumbnailUrl(),
544 mediaType: 'image/jpeg' as 'image/jpeg',
545 width: THUMBNAILS_SIZE.width,
546 height: THUMBNAILS_SIZE.height
550 return activityPubCollectionPagination(this.url, handler, page)
552 return Object.assign(o, {
553 type: 'Playlist' as 'Playlist',
555 content: this.description,
557 published: this.createdAt.toISOString(),
558 updated: this.updatedAt.toISOString(),
559 attributedTo: this.VideoChannel ? [ this.VideoChannel.Actor.url ] : [],