1 import { join } from 'path'
2 import { FindOptions, literal, Op, ScopeOptions, Transaction, WhereOptions } from 'sequelize'
19 } from 'sequelize-typescript'
20 import { v4 as uuidv4 } from 'uuid'
21 import { MAccountId, MChannelId } from '@server/types/models'
22 import { ActivityIconObject } from '../../../shared/models/activitypub/objects'
23 import { PlaylistObject } from '../../../shared/models/activitypub/objects/playlist-object'
24 import { VideoPlaylistPrivacy } from '../../../shared/models/videos/playlist/video-playlist-privacy.model'
25 import { VideoPlaylistType } from '../../../shared/models/videos/playlist/video-playlist-type.model'
26 import { VideoPlaylist } from '../../../shared/models/videos/playlist/video-playlist.model'
27 import { activityPubCollectionPagination } from '../../helpers/activitypub'
28 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
30 isVideoPlaylistDescriptionValid,
31 isVideoPlaylistNameValid,
32 isVideoPlaylistPrivacyValid
33 } from '../../helpers/custom-validators/video-playlists'
39 VIDEO_PLAYLIST_PRIVACIES,
42 } from '../../initializers/constants'
43 import { MThumbnail } from '../../types/models/video/thumbnail'
45 MVideoPlaylistAccountThumbnail,
47 MVideoPlaylistFormattable,
49 MVideoPlaylistFullSummary,
50 MVideoPlaylistIdWithElements
51 } from '../../types/models/video/video-playlist'
52 import { AccountModel, ScopeNames as AccountScopeNames, SummaryOptions } from '../account/account'
53 import { ActorModel } from '../actor/actor'
54 import { buildServerIdsFollowedBy, buildWhereIdOrUUID, getPlaylistSort, isOutdated, throwIfNotValid } from '../utils'
55 import { ThumbnailModel } from './thumbnail'
56 import { ScopeNames as VideoChannelScopeNames, VideoChannelModel } from './video-channel'
57 import { VideoPlaylistElementModel } from './video-playlist-element'
60 AVAILABLE_FOR_LIST = 'AVAILABLE_FOR_LIST',
61 WITH_VIDEOS_LENGTH = 'WITH_VIDEOS_LENGTH',
62 WITH_ACCOUNT_AND_CHANNEL_SUMMARY = 'WITH_ACCOUNT_AND_CHANNEL_SUMMARY',
63 WITH_ACCOUNT = 'WITH_ACCOUNT',
64 WITH_THUMBNAIL = 'WITH_THUMBNAIL',
65 WITH_ACCOUNT_AND_CHANNEL = 'WITH_ACCOUNT_AND_CHANNEL'
68 type AvailableForListOptions = {
69 followerActorId?: number
70 type?: VideoPlaylistType
72 videoChannelId?: number
73 listMyPlaylists?: boolean
78 [ScopeNames.WITH_THUMBNAIL]: {
81 model: ThumbnailModel,
86 [ScopeNames.WITH_VIDEOS_LENGTH]: {
90 literal('(SELECT COUNT("id") FROM "videoPlaylistElement" WHERE "videoPlaylistId" = "VideoPlaylistModel"."id")'),
96 [ScopeNames.WITH_ACCOUNT]: {
104 [ScopeNames.WITH_ACCOUNT_AND_CHANNEL_SUMMARY]: {
107 model: AccountModel.scope(AccountScopeNames.SUMMARY),
111 model: VideoChannelModel.scope(VideoChannelScopeNames.SUMMARY),
116 [ScopeNames.WITH_ACCOUNT_AND_CHANNEL]: {
123 model: VideoChannelModel,
128 [ScopeNames.AVAILABLE_FOR_LIST]: (options: AvailableForListOptions) => {
129 let whereActor: WhereOptions = {}
131 const whereAnd: WhereOptions[] = []
133 if (options.listMyPlaylists !== true) {
135 privacy: VideoPlaylistPrivacy.PUBLIC
138 // Only list local playlists
139 const whereActorOr: WhereOptions[] = [
145 // … OR playlists that are on an instance followed by actorId
146 if (options.followerActorId) {
147 const inQueryInstanceFollow = buildServerIdsFollowedBy(options.followerActorId)
151 [Op.in]: literal(inQueryInstanceFollow)
157 [Op.or]: whereActorOr
161 if (options.accountId) {
163 ownerAccountId: options.accountId
167 if (options.videoChannelId) {
169 videoChannelId: options.videoChannelId
179 if (options.search) {
182 [Op.iLike]: '%' + options.search + '%'
195 model: AccountModel.scope({
196 method: [ AccountScopeNames.SUMMARY, { whereActor } as SummaryOptions ]
201 model: VideoChannelModel.scope(VideoChannelScopeNames.SUMMARY),
210 tableName: 'videoPlaylist',
213 fields: [ 'ownerAccountId' ]
216 fields: [ 'videoChannelId' ]
224 export class VideoPlaylistModel extends Model {
232 @Is('VideoPlaylistName', value => throwIfNotValid(value, isVideoPlaylistNameValid, 'name'))
237 @Is('VideoPlaylistDescription', value => throwIfNotValid(value, isVideoPlaylistDescriptionValid, 'description', true))
238 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_PLAYLISTS.DESCRIPTION.max))
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 listMyPlaylists?: boolean
317 offset: options.start,
318 limit: options.count,
319 order: getPlaylistSort(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 listMyPlaylists: options.listMyPlaylists,
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 (options: { account?: MAccountId, channel?: MChannelId }, start: number, count: number) {
350 privacy: VideoPlaylistPrivacy.PUBLIC
353 if (options.account) {
354 Object.assign(where, { ownerAccountId: options.account.id })
357 if (options.channel) {
358 Object.assign(where, { videoChannelId: options.channel.id })
362 attributes: [ 'url' ],
368 return VideoPlaylistModel.findAndCountAll(query)
369 .then(({ rows, count }) => {
370 return { total: count, data: rows.map(p => p.url) }
374 static listPlaylistIdsOf (accountId: number, videoIds: number[]): Promise<MVideoPlaylistIdWithElements[]> {
376 attributes: [ 'id' ],
378 ownerAccountId: accountId
382 attributes: [ 'id', 'videoId', 'startTimestamp', 'stopTimestamp' ],
383 model: VideoPlaylistElementModel.unscoped(),
394 return VideoPlaylistModel.findAll(query)
397 static doesPlaylistExist (url: string) {
399 attributes: [ 'id' ],
405 return VideoPlaylistModel
410 static loadWithAccountAndChannelSummary (id: number | string, transaction: Transaction): Promise<MVideoPlaylistFullSummary> {
411 const where = buildWhereIdOrUUID(id)
418 return VideoPlaylistModel
419 .scope([ ScopeNames.WITH_ACCOUNT_AND_CHANNEL_SUMMARY, ScopeNames.WITH_VIDEOS_LENGTH, ScopeNames.WITH_THUMBNAIL ])
423 static loadWithAccountAndChannel (id: number | string, transaction: Transaction): Promise<MVideoPlaylistFull> {
424 const where = buildWhereIdOrUUID(id)
431 return VideoPlaylistModel
432 .scope([ ScopeNames.WITH_ACCOUNT_AND_CHANNEL, ScopeNames.WITH_VIDEOS_LENGTH, ScopeNames.WITH_THUMBNAIL ])
436 static loadByUrlAndPopulateAccount (url: string): Promise<MVideoPlaylistAccountThumbnail> {
443 return VideoPlaylistModel.scope([ ScopeNames.WITH_ACCOUNT, ScopeNames.WITH_THUMBNAIL ]).findOne(query)
446 static getPrivacyLabel (privacy: VideoPlaylistPrivacy) {
447 return VIDEO_PLAYLIST_PRIVACIES[privacy] || 'Unknown'
450 static getTypeLabel (type: VideoPlaylistType) {
451 return VIDEO_PLAYLIST_TYPES[type] || 'Unknown'
454 static resetPlaylistsOfChannel (videoChannelId: number, transaction: Transaction) {
462 return VideoPlaylistModel.update({ privacy: VideoPlaylistPrivacy.PRIVATE, videoChannelId: null }, query)
465 async setAndSaveThumbnail (thumbnail: MThumbnail, t: Transaction) {
466 thumbnail.videoPlaylistId = this.id
468 this.Thumbnail = await thumbnail.save({ transaction: t })
472 return !!this.Thumbnail
475 hasGeneratedThumbnail () {
476 return this.hasThumbnail() && this.Thumbnail.automaticallyGenerated === true
479 generateThumbnailName () {
480 const extension = '.jpg'
482 return 'playlist-' + uuidv4() + extension
486 if (!this.hasThumbnail()) return null
488 return WEBSERVER.URL + STATIC_PATHS.THUMBNAILS + this.Thumbnail.filename
491 getThumbnailStaticPath () {
492 if (!this.hasThumbnail()) return null
494 return join(STATIC_PATHS.THUMBNAILS, this.Thumbnail.filename)
498 return WEBSERVER.URL + '/videos/watch/playlist/' + this.uuid
501 getEmbedStaticPath () {
502 return '/video-playlists/embed/' + this.uuid
505 static async getStats () {
506 const totalLocalPlaylists = await VideoPlaylistModel.count({
523 privacy: VideoPlaylistPrivacy.PUBLIC
533 this.changed('updatedAt', true)
539 return this.OwnerAccount.isOwned()
543 if (this.isOwned()) return false
545 return isOutdated(this, ACTIVITY_PUB.VIDEO_PLAYLIST_REFRESH_INTERVAL)
548 toFormattedJSON (this: MVideoPlaylistFormattable): VideoPlaylist {
552 isLocal: this.isOwned(),
554 displayName: this.name,
555 description: this.description,
558 label: VideoPlaylistModel.getPrivacyLabel(this.privacy)
561 thumbnailPath: this.getThumbnailStaticPath(),
562 embedPath: this.getEmbedStaticPath(),
566 label: VideoPlaylistModel.getTypeLabel(this.type)
569 videosLength: this.get('videosLength') as number,
571 createdAt: this.createdAt,
572 updatedAt: this.updatedAt,
574 ownerAccount: this.OwnerAccount.toFormattedSummaryJSON(),
575 videoChannel: this.VideoChannel
576 ? this.VideoChannel.toFormattedSummaryJSON()
581 toActivityPubObject (this: MVideoPlaylistAP, page: number, t: Transaction): Promise<PlaylistObject> {
582 const handler = (start: number, count: number) => {
583 return VideoPlaylistElementModel.listUrlsOfForAP(this.id, start, count, t)
586 let icon: ActivityIconObject
587 if (this.hasThumbnail()) {
589 type: 'Image' as 'Image',
590 url: this.getThumbnailUrl(),
591 mediaType: 'image/jpeg' as 'image/jpeg',
592 width: THUMBNAILS_SIZE.width,
593 height: THUMBNAILS_SIZE.height
597 return activityPubCollectionPagination(this.url, handler, page)
599 return Object.assign(o, {
600 type: 'Playlist' as 'Playlist',
602 content: this.description,
604 published: this.createdAt.toISOString(),
605 updated: this.updatedAt.toISOString(),
606 attributedTo: this.VideoChannel ? [ this.VideoChannel.Actor.url ] : [],