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 { buildServerIdsFollowedBy, buildWhereIdOrUUID, getPlaylistSort, isOutdated, throwIfNotValid } from '../utils'
54 import { ThumbnailModel } from './thumbnail'
55 import { ScopeNames as VideoChannelScopeNames, VideoChannelModel } from './video-channel'
56 import { VideoPlaylistElementModel } from './video-playlist-element'
59 AVAILABLE_FOR_LIST = 'AVAILABLE_FOR_LIST',
60 WITH_VIDEOS_LENGTH = 'WITH_VIDEOS_LENGTH',
61 WITH_ACCOUNT_AND_CHANNEL_SUMMARY = 'WITH_ACCOUNT_AND_CHANNEL_SUMMARY',
62 WITH_ACCOUNT = 'WITH_ACCOUNT',
63 WITH_THUMBNAIL = 'WITH_THUMBNAIL',
64 WITH_ACCOUNT_AND_CHANNEL = 'WITH_ACCOUNT_AND_CHANNEL'
67 type AvailableForListOptions = {
68 followerActorId: number
69 type?: VideoPlaylistType
71 videoChannelId?: number
72 listMyPlaylists?: boolean
77 [ScopeNames.WITH_THUMBNAIL]: {
80 model: ThumbnailModel,
85 [ScopeNames.WITH_VIDEOS_LENGTH]: {
89 literal('(SELECT COUNT("id") FROM "videoPlaylistElement" WHERE "videoPlaylistId" = "VideoPlaylistModel"."id")'),
95 [ScopeNames.WITH_ACCOUNT]: {
103 [ScopeNames.WITH_ACCOUNT_AND_CHANNEL_SUMMARY]: {
106 model: AccountModel.scope(AccountScopeNames.SUMMARY),
110 model: VideoChannelModel.scope(VideoChannelScopeNames.SUMMARY),
115 [ScopeNames.WITH_ACCOUNT_AND_CHANNEL]: {
122 model: VideoChannelModel,
127 [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 + '%'
188 model: AccountModel.scope({
189 method: [ AccountScopeNames.SUMMARY, { whereActor } as SummaryOptions ]
194 model: VideoChannelModel.scope(VideoChannelScopeNames.SUMMARY),
203 tableName: 'videoPlaylist',
206 fields: [ 'ownerAccountId' ]
209 fields: [ 'videoChannelId' ]
217 export class VideoPlaylistModel extends Model {
225 @Is('VideoPlaylistName', value => throwIfNotValid(value, isVideoPlaylistNameValid, 'name'))
230 @Is('VideoPlaylistDescription', value => throwIfNotValid(value, isVideoPlaylistDescriptionValid, 'description', true))
231 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_PLAYLISTS.DESCRIPTION.max))
235 @Is('VideoPlaylistPrivacy', value => throwIfNotValid(value, isVideoPlaylistPrivacyValid, 'privacy'))
237 privacy: VideoPlaylistPrivacy
240 @Is('VideoPlaylistUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
241 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_PLAYLISTS.URL.max))
245 @Default(DataType.UUIDV4)
247 @Column(DataType.UUID)
251 @Default(VideoPlaylistType.REGULAR)
253 type: VideoPlaylistType
255 @ForeignKey(() => AccountModel)
257 ownerAccountId: number
259 @BelongsTo(() => AccountModel, {
265 OwnerAccount: AccountModel
267 @ForeignKey(() => VideoChannelModel)
269 videoChannelId: number
271 @BelongsTo(() => VideoChannelModel, {
277 VideoChannel: VideoChannelModel
279 @HasMany(() => VideoPlaylistElementModel, {
281 name: 'videoPlaylistId',
286 VideoPlaylistElements: VideoPlaylistElementModel[]
288 @HasOne(() => ThumbnailModel, {
290 name: 'videoPlaylistId',
296 Thumbnail: ThumbnailModel
298 static listForApi (options: {
299 followerActorId: number
303 type?: VideoPlaylistType
305 videoChannelId?: number
306 listMyPlaylists?: boolean
310 offset: options.start,
311 limit: options.count,
312 order: getPlaylistSort(options.sort)
315 const scopes: (string | ScopeOptions)[] = [
318 ScopeNames.AVAILABLE_FOR_LIST,
321 followerActorId: options.followerActorId,
322 accountId: options.accountId,
323 videoChannelId: options.videoChannelId,
324 listMyPlaylists: options.listMyPlaylists,
325 search: options.search
326 } as AvailableForListOptions
329 ScopeNames.WITH_VIDEOS_LENGTH,
330 ScopeNames.WITH_THUMBNAIL
333 return VideoPlaylistModel
335 .findAndCountAll(query)
336 .then(({ rows, count }) => {
337 return { total: count, data: rows }
341 static listPublicUrlsOfForAP (options: { account?: MAccountId, channel?: MChannelId }, start: number, count: number) {
343 privacy: VideoPlaylistPrivacy.PUBLIC
346 if (options.account) {
347 Object.assign(where, { ownerAccountId: options.account.id })
350 if (options.channel) {
351 Object.assign(where, { videoChannelId: options.channel.id })
355 attributes: [ 'url' ],
361 return VideoPlaylistModel.findAndCountAll(query)
362 .then(({ rows, count }) => {
363 return { total: count, data: rows.map(p => p.url) }
367 static listPlaylistIdsOf (accountId: number, videoIds: number[]): Promise<MVideoPlaylistIdWithElements[]> {
369 attributes: [ 'id' ],
371 ownerAccountId: accountId
375 attributes: [ 'id', 'videoId', 'startTimestamp', 'stopTimestamp' ],
376 model: VideoPlaylistElementModel.unscoped(),
387 return VideoPlaylistModel.findAll(query)
390 static doesPlaylistExist (url: string) {
392 attributes: [ 'id' ],
398 return VideoPlaylistModel
403 static loadWithAccountAndChannelSummary (id: number | string, transaction: Transaction): Promise<MVideoPlaylistFullSummary> {
404 const where = buildWhereIdOrUUID(id)
411 return VideoPlaylistModel
412 .scope([ ScopeNames.WITH_ACCOUNT_AND_CHANNEL_SUMMARY, ScopeNames.WITH_VIDEOS_LENGTH, ScopeNames.WITH_THUMBNAIL ])
416 static loadWithAccountAndChannel (id: number | string, transaction: Transaction): Promise<MVideoPlaylistFull> {
417 const where = buildWhereIdOrUUID(id)
424 return VideoPlaylistModel
425 .scope([ ScopeNames.WITH_ACCOUNT_AND_CHANNEL, ScopeNames.WITH_VIDEOS_LENGTH, ScopeNames.WITH_THUMBNAIL ])
429 static loadByUrlAndPopulateAccount (url: string): Promise<MVideoPlaylistAccountThumbnail> {
436 return VideoPlaylistModel.scope([ ScopeNames.WITH_ACCOUNT, ScopeNames.WITH_THUMBNAIL ]).findOne(query)
439 static getPrivacyLabel (privacy: VideoPlaylistPrivacy) {
440 return VIDEO_PLAYLIST_PRIVACIES[privacy] || 'Unknown'
443 static getTypeLabel (type: VideoPlaylistType) {
444 return VIDEO_PLAYLIST_TYPES[type] || 'Unknown'
447 static resetPlaylistsOfChannel (videoChannelId: number, transaction: Transaction) {
455 return VideoPlaylistModel.update({ privacy: VideoPlaylistPrivacy.PRIVATE, videoChannelId: null }, query)
458 async setAndSaveThumbnail (thumbnail: MThumbnail, t: Transaction) {
459 thumbnail.videoPlaylistId = this.id
461 this.Thumbnail = await thumbnail.save({ transaction: t })
465 return !!this.Thumbnail
468 hasGeneratedThumbnail () {
469 return this.hasThumbnail() && this.Thumbnail.automaticallyGenerated === true
472 generateThumbnailName () {
473 const extension = '.jpg'
475 return 'playlist-' + uuidv4() + extension
479 if (!this.hasThumbnail()) return null
481 return WEBSERVER.URL + STATIC_PATHS.THUMBNAILS + this.Thumbnail.filename
484 getThumbnailStaticPath () {
485 if (!this.hasThumbnail()) return null
487 return join(STATIC_PATHS.THUMBNAILS, this.Thumbnail.filename)
491 return WEBSERVER.URL + '/videos/watch/playlist/' + this.uuid
494 getEmbedStaticPath () {
495 return '/video-playlists/embed/' + this.uuid
499 this.changed('updatedAt', true)
505 return this.OwnerAccount.isOwned()
509 if (this.isOwned()) return false
511 return isOutdated(this, ACTIVITY_PUB.VIDEO_PLAYLIST_REFRESH_INTERVAL)
514 toFormattedJSON (this: MVideoPlaylistFormattable): VideoPlaylist {
518 isLocal: this.isOwned(),
520 displayName: this.name,
521 description: this.description,
524 label: VideoPlaylistModel.getPrivacyLabel(this.privacy)
527 thumbnailPath: this.getThumbnailStaticPath(),
528 embedPath: this.getEmbedStaticPath(),
532 label: VideoPlaylistModel.getTypeLabel(this.type)
535 videosLength: this.get('videosLength') as number,
537 createdAt: this.createdAt,
538 updatedAt: this.updatedAt,
540 ownerAccount: this.OwnerAccount.toFormattedSummaryJSON(),
541 videoChannel: this.VideoChannel
542 ? this.VideoChannel.toFormattedSummaryJSON()
547 toActivityPubObject (this: MVideoPlaylistAP, page: number, t: Transaction): Promise<PlaylistObject> {
548 const handler = (start: number, count: number) => {
549 return VideoPlaylistElementModel.listUrlsOfForAP(this.id, start, count, t)
552 let icon: ActivityIconObject
553 if (this.hasThumbnail()) {
555 type: 'Image' as 'Image',
556 url: this.getThumbnailUrl(),
557 mediaType: 'image/jpeg' as 'image/jpeg',
558 width: THUMBNAILS_SIZE.width,
559 height: THUMBNAILS_SIZE.height
563 return activityPubCollectionPagination(this.url, handler, page)
565 return Object.assign(o, {
566 type: 'Playlist' as 'Playlist',
568 content: this.description,
570 published: this.createdAt.toISOString(),
571 updated: this.updatedAt.toISOString(),
572 attributedTo: this.VideoChannel ? [ this.VideoChannel.Actor.url ] : [],