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 { setAsUpdated } from '@server/helpers/database-utils'
22 import { MAccountId, MChannelId } from '@server/types/models'
23 import { AttributesOnly } from '@shared/core-utils'
24 import { ActivityIconObject } from '../../../shared/models/activitypub/objects'
25 import { PlaylistObject } from '../../../shared/models/activitypub/objects/playlist-object'
26 import { VideoPlaylistPrivacy } from '../../../shared/models/videos/playlist/video-playlist-privacy.model'
27 import { VideoPlaylistType } from '../../../shared/models/videos/playlist/video-playlist-type.model'
28 import { VideoPlaylist } from '../../../shared/models/videos/playlist/video-playlist.model'
29 import { activityPubCollectionPagination } from '../../helpers/activitypub'
30 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
32 isVideoPlaylistDescriptionValid,
33 isVideoPlaylistNameValid,
34 isVideoPlaylistPrivacyValid
35 } from '../../helpers/custom-validators/video-playlists'
41 VIDEO_PLAYLIST_PRIVACIES,
44 } from '../../initializers/constants'
45 import { MThumbnail } from '../../types/models/video/thumbnail'
47 MVideoPlaylistAccountThumbnail,
49 MVideoPlaylistFormattable,
51 MVideoPlaylistFullSummary,
52 MVideoPlaylistIdWithElements
53 } from '../../types/models/video/video-playlist'
54 import { AccountModel, ScopeNames as AccountScopeNames, SummaryOptions } from '../account/account'
55 import { ActorModel } from '../actor/actor'
56 import { buildServerIdsFollowedBy, buildWhereIdOrUUID, getPlaylistSort, isOutdated, throwIfNotValid } from '../utils'
57 import { ThumbnailModel } from './thumbnail'
58 import { ScopeNames as VideoChannelScopeNames, VideoChannelModel } from './video-channel'
59 import { VideoPlaylistElementModel } from './video-playlist-element'
62 AVAILABLE_FOR_LIST = 'AVAILABLE_FOR_LIST',
63 WITH_VIDEOS_LENGTH = 'WITH_VIDEOS_LENGTH',
64 WITH_ACCOUNT_AND_CHANNEL_SUMMARY = 'WITH_ACCOUNT_AND_CHANNEL_SUMMARY',
65 WITH_ACCOUNT = 'WITH_ACCOUNT',
66 WITH_THUMBNAIL = 'WITH_THUMBNAIL',
67 WITH_ACCOUNT_AND_CHANNEL = 'WITH_ACCOUNT_AND_CHANNEL'
70 type AvailableForListOptions = {
71 followerActorId?: number
72 type?: VideoPlaylistType
74 videoChannelId?: number
75 listMyPlaylists?: boolean
80 [ScopeNames.WITH_THUMBNAIL]: {
83 model: ThumbnailModel,
88 [ScopeNames.WITH_VIDEOS_LENGTH]: {
92 literal('(SELECT COUNT("id") FROM "videoPlaylistElement" WHERE "videoPlaylistId" = "VideoPlaylistModel"."id")'),
98 [ScopeNames.WITH_ACCOUNT]: {
106 [ScopeNames.WITH_ACCOUNT_AND_CHANNEL_SUMMARY]: {
109 model: AccountModel.scope(AccountScopeNames.SUMMARY),
113 model: VideoChannelModel.scope(VideoChannelScopeNames.SUMMARY),
118 [ScopeNames.WITH_ACCOUNT_AND_CHANNEL]: {
125 model: VideoChannelModel,
130 [ScopeNames.AVAILABLE_FOR_LIST]: (options: AvailableForListOptions) => {
131 let whereActor: WhereOptions = {}
133 const whereAnd: WhereOptions[] = []
135 if (options.listMyPlaylists !== true) {
137 privacy: VideoPlaylistPrivacy.PUBLIC
140 // Only list local playlists
141 const whereActorOr: WhereOptions[] = [
147 // … OR playlists that are on an instance followed by actorId
148 if (options.followerActorId) {
149 const inQueryInstanceFollow = buildServerIdsFollowedBy(options.followerActorId)
153 [Op.in]: literal(inQueryInstanceFollow)
159 [Op.or]: whereActorOr
163 if (options.accountId) {
165 ownerAccountId: options.accountId
169 if (options.videoChannelId) {
171 videoChannelId: options.videoChannelId
181 if (options.search) {
184 [Op.iLike]: '%' + options.search + '%'
197 model: AccountModel.scope({
198 method: [ AccountScopeNames.SUMMARY, { whereActor } as SummaryOptions ]
203 model: VideoChannelModel.scope(VideoChannelScopeNames.SUMMARY),
212 tableName: 'videoPlaylist',
215 fields: [ 'ownerAccountId' ]
218 fields: [ 'videoChannelId' ]
226 export class VideoPlaylistModel extends Model<Partial<AttributesOnly<VideoPlaylistModel>>> {
234 @Is('VideoPlaylistName', value => throwIfNotValid(value, isVideoPlaylistNameValid, 'name'))
239 @Is('VideoPlaylistDescription', value => throwIfNotValid(value, isVideoPlaylistDescriptionValid, 'description', true))
240 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_PLAYLISTS.DESCRIPTION.max))
244 @Is('VideoPlaylistPrivacy', value => throwIfNotValid(value, isVideoPlaylistPrivacyValid, 'privacy'))
246 privacy: VideoPlaylistPrivacy
249 @Is('VideoPlaylistUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
250 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_PLAYLISTS.URL.max))
254 @Default(DataType.UUIDV4)
256 @Column(DataType.UUID)
260 @Default(VideoPlaylistType.REGULAR)
262 type: VideoPlaylistType
264 @ForeignKey(() => AccountModel)
266 ownerAccountId: number
268 @BelongsTo(() => AccountModel, {
274 OwnerAccount: AccountModel
276 @ForeignKey(() => VideoChannelModel)
278 videoChannelId: number
280 @BelongsTo(() => VideoChannelModel, {
286 VideoChannel: VideoChannelModel
288 @HasMany(() => VideoPlaylistElementModel, {
290 name: 'videoPlaylistId',
295 VideoPlaylistElements: VideoPlaylistElementModel[]
297 @HasOne(() => ThumbnailModel, {
299 name: 'videoPlaylistId',
305 Thumbnail: ThumbnailModel
307 static listForApi (options: {
308 followerActorId: number
312 type?: VideoPlaylistType
314 videoChannelId?: number
315 listMyPlaylists?: boolean
319 offset: options.start,
320 limit: options.count,
321 order: getPlaylistSort(options.sort)
324 const scopes: (string | ScopeOptions)[] = [
327 ScopeNames.AVAILABLE_FOR_LIST,
330 followerActorId: options.followerActorId,
331 accountId: options.accountId,
332 videoChannelId: options.videoChannelId,
333 listMyPlaylists: options.listMyPlaylists,
334 search: options.search
335 } as AvailableForListOptions
338 ScopeNames.WITH_VIDEOS_LENGTH,
339 ScopeNames.WITH_THUMBNAIL
342 return VideoPlaylistModel
344 .findAndCountAll(query)
345 .then(({ rows, count }) => {
346 return { total: count, data: rows }
350 static listPublicUrlsOfForAP (options: { account?: MAccountId, channel?: MChannelId }, start: number, count: number) {
352 privacy: VideoPlaylistPrivacy.PUBLIC
355 if (options.account) {
356 Object.assign(where, { ownerAccountId: options.account.id })
359 if (options.channel) {
360 Object.assign(where, { videoChannelId: options.channel.id })
364 attributes: [ 'url' ],
370 return VideoPlaylistModel.findAndCountAll(query)
371 .then(({ rows, count }) => {
372 return { total: count, data: rows.map(p => p.url) }
376 static listPlaylistIdsOf (accountId: number, videoIds: number[]): Promise<MVideoPlaylistIdWithElements[]> {
378 attributes: [ 'id' ],
380 ownerAccountId: accountId
384 attributes: [ 'id', 'videoId', 'startTimestamp', 'stopTimestamp' ],
385 model: VideoPlaylistElementModel.unscoped(),
396 return VideoPlaylistModel.findAll(query)
399 static doesPlaylistExist (url: string) {
401 attributes: [ 'id' ],
407 return VideoPlaylistModel
412 static loadWithAccountAndChannelSummary (id: number | string, transaction: Transaction): Promise<MVideoPlaylistFullSummary> {
413 const where = buildWhereIdOrUUID(id)
420 return VideoPlaylistModel
421 .scope([ ScopeNames.WITH_ACCOUNT_AND_CHANNEL_SUMMARY, ScopeNames.WITH_VIDEOS_LENGTH, ScopeNames.WITH_THUMBNAIL ])
425 static loadWithAccountAndChannel (id: number | string, transaction: Transaction): Promise<MVideoPlaylistFull> {
426 const where = buildWhereIdOrUUID(id)
433 return VideoPlaylistModel
434 .scope([ ScopeNames.WITH_ACCOUNT_AND_CHANNEL, ScopeNames.WITH_VIDEOS_LENGTH, ScopeNames.WITH_THUMBNAIL ])
438 static loadByUrlAndPopulateAccount (url: string): Promise<MVideoPlaylistAccountThumbnail> {
445 return VideoPlaylistModel.scope([ ScopeNames.WITH_ACCOUNT, ScopeNames.WITH_THUMBNAIL ]).findOne(query)
448 static getPrivacyLabel (privacy: VideoPlaylistPrivacy) {
449 return VIDEO_PLAYLIST_PRIVACIES[privacy] || 'Unknown'
452 static getTypeLabel (type: VideoPlaylistType) {
453 return VIDEO_PLAYLIST_TYPES[type] || 'Unknown'
456 static resetPlaylistsOfChannel (videoChannelId: number, transaction: Transaction) {
464 return VideoPlaylistModel.update({ privacy: VideoPlaylistPrivacy.PRIVATE, videoChannelId: null }, query)
467 async setAndSaveThumbnail (thumbnail: MThumbnail, t: Transaction) {
468 thumbnail.videoPlaylistId = this.id
470 this.Thumbnail = await thumbnail.save({ transaction: t })
474 return !!this.Thumbnail
477 hasGeneratedThumbnail () {
478 return this.hasThumbnail() && this.Thumbnail.automaticallyGenerated === true
481 generateThumbnailName () {
482 const extension = '.jpg'
484 return 'playlist-' + uuidv4() + extension
488 if (!this.hasThumbnail()) return null
490 return WEBSERVER.URL + STATIC_PATHS.THUMBNAILS + this.Thumbnail.filename
493 getThumbnailStaticPath () {
494 if (!this.hasThumbnail()) return null
496 return join(STATIC_PATHS.THUMBNAILS, this.Thumbnail.filename)
500 return WEBSERVER.URL + '/w/p/' + this.uuid
503 getEmbedStaticPath () {
504 return '/video-playlists/embed/' + this.uuid
507 static async getStats () {
508 const totalLocalPlaylists = await VideoPlaylistModel.count({
525 privacy: VideoPlaylistPrivacy.PUBLIC
535 return setAsUpdated('videoPlaylist', this.id)
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 ] : [],