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 { AttributesOnly } from '@shared/core-utils'
23 import { ActivityIconObject } from '../../../shared/models/activitypub/objects'
24 import { PlaylistObject } from '../../../shared/models/activitypub/objects/playlist-object'
25 import { VideoPlaylistPrivacy } from '../../../shared/models/videos/playlist/video-playlist-privacy.model'
26 import { VideoPlaylistType } from '../../../shared/models/videos/playlist/video-playlist-type.model'
27 import { VideoPlaylist } from '../../../shared/models/videos/playlist/video-playlist.model'
28 import { activityPubCollectionPagination } from '../../helpers/activitypub'
29 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
31 isVideoPlaylistDescriptionValid,
32 isVideoPlaylistNameValid,
33 isVideoPlaylistPrivacyValid
34 } from '../../helpers/custom-validators/video-playlists'
40 VIDEO_PLAYLIST_PRIVACIES,
43 } from '../../initializers/constants'
44 import { MThumbnail } from '../../types/models/video/thumbnail'
46 MVideoPlaylistAccountThumbnail,
48 MVideoPlaylistFormattable,
50 MVideoPlaylistFullSummary,
51 MVideoPlaylistIdWithElements
52 } from '../../types/models/video/video-playlist'
53 import { AccountModel, ScopeNames as AccountScopeNames, SummaryOptions } from '../account/account'
54 import { ActorModel } from '../actor/actor'
55 import { buildServerIdsFollowedBy, buildWhereIdOrUUID, getPlaylistSort, isOutdated, throwIfNotValid } from '../utils'
56 import { ThumbnailModel } from './thumbnail'
57 import { ScopeNames as VideoChannelScopeNames, VideoChannelModel } from './video-channel'
58 import { VideoPlaylistElementModel } from './video-playlist-element'
61 AVAILABLE_FOR_LIST = 'AVAILABLE_FOR_LIST',
62 WITH_VIDEOS_LENGTH = 'WITH_VIDEOS_LENGTH',
63 WITH_ACCOUNT_AND_CHANNEL_SUMMARY = 'WITH_ACCOUNT_AND_CHANNEL_SUMMARY',
64 WITH_ACCOUNT = 'WITH_ACCOUNT',
65 WITH_THUMBNAIL = 'WITH_THUMBNAIL',
66 WITH_ACCOUNT_AND_CHANNEL = 'WITH_ACCOUNT_AND_CHANNEL'
69 type AvailableForListOptions = {
70 followerActorId?: number
71 type?: VideoPlaylistType
73 videoChannelId?: number
74 listMyPlaylists?: boolean
79 [ScopeNames.WITH_THUMBNAIL]: {
82 model: ThumbnailModel,
87 [ScopeNames.WITH_VIDEOS_LENGTH]: {
91 literal('(SELECT COUNT("id") FROM "videoPlaylistElement" WHERE "videoPlaylistId" = "VideoPlaylistModel"."id")'),
97 [ScopeNames.WITH_ACCOUNT]: {
105 [ScopeNames.WITH_ACCOUNT_AND_CHANNEL_SUMMARY]: {
108 model: AccountModel.scope(AccountScopeNames.SUMMARY),
112 model: VideoChannelModel.scope(VideoChannelScopeNames.SUMMARY),
117 [ScopeNames.WITH_ACCOUNT_AND_CHANNEL]: {
124 model: VideoChannelModel,
129 [ScopeNames.AVAILABLE_FOR_LIST]: (options: AvailableForListOptions) => {
130 let whereActor: WhereOptions = {}
132 const whereAnd: WhereOptions[] = []
134 if (options.listMyPlaylists !== true) {
136 privacy: VideoPlaylistPrivacy.PUBLIC
139 // Only list local playlists
140 const whereActorOr: WhereOptions[] = [
146 // … OR playlists that are on an instance followed by actorId
147 if (options.followerActorId) {
148 const inQueryInstanceFollow = buildServerIdsFollowedBy(options.followerActorId)
152 [Op.in]: literal(inQueryInstanceFollow)
158 [Op.or]: whereActorOr
162 if (options.accountId) {
164 ownerAccountId: options.accountId
168 if (options.videoChannelId) {
170 videoChannelId: options.videoChannelId
180 if (options.search) {
183 [Op.iLike]: '%' + options.search + '%'
196 model: AccountModel.scope({
197 method: [ AccountScopeNames.SUMMARY, { whereActor } as SummaryOptions ]
202 model: VideoChannelModel.scope(VideoChannelScopeNames.SUMMARY),
211 tableName: 'videoPlaylist',
214 fields: [ 'ownerAccountId' ]
217 fields: [ 'videoChannelId' ]
225 export class VideoPlaylistModel extends Model<Partial<AttributesOnly<VideoPlaylistModel>>> {
233 @Is('VideoPlaylistName', value => throwIfNotValid(value, isVideoPlaylistNameValid, 'name'))
238 @Is('VideoPlaylistDescription', value => throwIfNotValid(value, isVideoPlaylistDescriptionValid, 'description', true))
239 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_PLAYLISTS.DESCRIPTION.max))
243 @Is('VideoPlaylistPrivacy', value => throwIfNotValid(value, isVideoPlaylistPrivacyValid, 'privacy'))
245 privacy: VideoPlaylistPrivacy
248 @Is('VideoPlaylistUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
249 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_PLAYLISTS.URL.max))
253 @Default(DataType.UUIDV4)
255 @Column(DataType.UUID)
259 @Default(VideoPlaylistType.REGULAR)
261 type: VideoPlaylistType
263 @ForeignKey(() => AccountModel)
265 ownerAccountId: number
267 @BelongsTo(() => AccountModel, {
273 OwnerAccount: AccountModel
275 @ForeignKey(() => VideoChannelModel)
277 videoChannelId: number
279 @BelongsTo(() => VideoChannelModel, {
285 VideoChannel: VideoChannelModel
287 @HasMany(() => VideoPlaylistElementModel, {
289 name: 'videoPlaylistId',
294 VideoPlaylistElements: VideoPlaylistElementModel[]
296 @HasOne(() => ThumbnailModel, {
298 name: 'videoPlaylistId',
304 Thumbnail: ThumbnailModel
306 static listForApi (options: {
307 followerActorId: number
311 type?: VideoPlaylistType
313 videoChannelId?: number
314 listMyPlaylists?: boolean
318 offset: options.start,
319 limit: options.count,
320 order: getPlaylistSort(options.sort)
323 const scopes: (string | ScopeOptions)[] = [
326 ScopeNames.AVAILABLE_FOR_LIST,
329 followerActorId: options.followerActorId,
330 accountId: options.accountId,
331 videoChannelId: options.videoChannelId,
332 listMyPlaylists: options.listMyPlaylists,
333 search: options.search
334 } as AvailableForListOptions
337 ScopeNames.WITH_VIDEOS_LENGTH,
338 ScopeNames.WITH_THUMBNAIL
341 return VideoPlaylistModel
343 .findAndCountAll(query)
344 .then(({ rows, count }) => {
345 return { total: count, data: rows }
349 static listPublicUrlsOfForAP (options: { account?: MAccountId, channel?: MChannelId }, start: number, count: number) {
351 privacy: VideoPlaylistPrivacy.PUBLIC
354 if (options.account) {
355 Object.assign(where, { ownerAccountId: options.account.id })
358 if (options.channel) {
359 Object.assign(where, { videoChannelId: options.channel.id })
363 attributes: [ 'url' ],
369 return VideoPlaylistModel.findAndCountAll(query)
370 .then(({ rows, count }) => {
371 return { total: count, data: rows.map(p => p.url) }
375 static listPlaylistIdsOf (accountId: number, videoIds: number[]): Promise<MVideoPlaylistIdWithElements[]> {
377 attributes: [ 'id' ],
379 ownerAccountId: accountId
383 attributes: [ 'id', 'videoId', 'startTimestamp', 'stopTimestamp' ],
384 model: VideoPlaylistElementModel.unscoped(),
395 return VideoPlaylistModel.findAll(query)
398 static doesPlaylistExist (url: string) {
400 attributes: [ 'id' ],
406 return VideoPlaylistModel
411 static loadWithAccountAndChannelSummary (id: number | string, transaction: Transaction): Promise<MVideoPlaylistFullSummary> {
412 const where = buildWhereIdOrUUID(id)
419 return VideoPlaylistModel
420 .scope([ ScopeNames.WITH_ACCOUNT_AND_CHANNEL_SUMMARY, ScopeNames.WITH_VIDEOS_LENGTH, ScopeNames.WITH_THUMBNAIL ])
424 static loadWithAccountAndChannel (id: number | string, transaction: Transaction): Promise<MVideoPlaylistFull> {
425 const where = buildWhereIdOrUUID(id)
432 return VideoPlaylistModel
433 .scope([ ScopeNames.WITH_ACCOUNT_AND_CHANNEL, ScopeNames.WITH_VIDEOS_LENGTH, ScopeNames.WITH_THUMBNAIL ])
437 static loadByUrlAndPopulateAccount (url: string): Promise<MVideoPlaylistAccountThumbnail> {
444 return VideoPlaylistModel.scope([ ScopeNames.WITH_ACCOUNT, ScopeNames.WITH_THUMBNAIL ]).findOne(query)
447 static getPrivacyLabel (privacy: VideoPlaylistPrivacy) {
448 return VIDEO_PLAYLIST_PRIVACIES[privacy] || 'Unknown'
451 static getTypeLabel (type: VideoPlaylistType) {
452 return VIDEO_PLAYLIST_TYPES[type] || 'Unknown'
455 static resetPlaylistsOfChannel (videoChannelId: number, transaction: Transaction) {
463 return VideoPlaylistModel.update({ privacy: VideoPlaylistPrivacy.PRIVATE, videoChannelId: null }, query)
466 async setAndSaveThumbnail (thumbnail: MThumbnail, t: Transaction) {
467 thumbnail.videoPlaylistId = this.id
469 this.Thumbnail = await thumbnail.save({ transaction: t })
473 return !!this.Thumbnail
476 hasGeneratedThumbnail () {
477 return this.hasThumbnail() && this.Thumbnail.automaticallyGenerated === true
480 generateThumbnailName () {
481 const extension = '.jpg'
483 return 'playlist-' + uuidv4() + extension
487 if (!this.hasThumbnail()) return null
489 return WEBSERVER.URL + STATIC_PATHS.THUMBNAILS + this.Thumbnail.filename
492 getThumbnailStaticPath () {
493 if (!this.hasThumbnail()) return null
495 return join(STATIC_PATHS.THUMBNAILS, this.Thumbnail.filename)
499 return WEBSERVER.URL + '/w/p/' + this.uuid
502 getEmbedStaticPath () {
503 return '/video-playlists/embed/' + this.uuid
506 static async getStats () {
507 const totalLocalPlaylists = await VideoPlaylistModel.count({
524 privacy: VideoPlaylistPrivacy.PUBLIC
534 this.changed('updatedAt', true)
540 return this.OwnerAccount.isOwned()
544 if (this.isOwned()) return false
546 return isOutdated(this, ACTIVITY_PUB.VIDEO_PLAYLIST_REFRESH_INTERVAL)
549 toFormattedJSON (this: MVideoPlaylistFormattable): VideoPlaylist {
553 isLocal: this.isOwned(),
555 displayName: this.name,
556 description: this.description,
559 label: VideoPlaylistModel.getPrivacyLabel(this.privacy)
562 thumbnailPath: this.getThumbnailStaticPath(),
563 embedPath: this.getEmbedStaticPath(),
567 label: VideoPlaylistModel.getTypeLabel(this.type)
570 videosLength: this.get('videosLength') as number,
572 createdAt: this.createdAt,
573 updatedAt: this.updatedAt,
575 ownerAccount: this.OwnerAccount.toFormattedSummaryJSON(),
576 videoChannel: this.VideoChannel
577 ? this.VideoChannel.toFormattedSummaryJSON()
582 toActivityPubObject (this: MVideoPlaylistAP, page: number, t: Transaction): Promise<PlaylistObject> {
583 const handler = (start: number, count: number) => {
584 return VideoPlaylistElementModel.listUrlsOfForAP(this.id, start, count, t)
587 let icon: ActivityIconObject
588 if (this.hasThumbnail()) {
590 type: 'Image' as 'Image',
591 url: this.getThumbnailUrl(),
592 mediaType: 'image/jpeg' as 'image/jpeg',
593 width: THUMBNAILS_SIZE.width,
594 height: THUMBNAILS_SIZE.height
598 return activityPubCollectionPagination(this.url, handler, page)
600 return Object.assign(o, {
601 type: 'Playlist' as 'Playlist',
603 content: this.description,
605 published: this.createdAt.toISOString(),
606 updated: this.updatedAt.toISOString(),
607 attributedTo: this.VideoChannel ? [ this.VideoChannel.Actor.url ] : [],