1 import { join } from 'path'
2 import { FindOptions, literal, Op, ScopeOptions, Transaction, WhereOptions } from 'sequelize'
19 } from 'sequelize-typescript'
20 import { MAccountId, MChannelId } from '@server/types/models'
21 import { ActivityIconObject } from '../../../shared/models/activitypub/objects'
22 import { PlaylistObject } from '../../../shared/models/activitypub/objects/playlist-object'
23 import { VideoPlaylistPrivacy } from '../../../shared/models/videos/playlist/video-playlist-privacy.model'
24 import { VideoPlaylistType } from '../../../shared/models/videos/playlist/video-playlist-type.model'
25 import { VideoPlaylist } from '../../../shared/models/videos/playlist/video-playlist.model'
26 import { activityPubCollectionPagination } from '../../helpers/activitypub'
27 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
29 isVideoPlaylistDescriptionValid,
30 isVideoPlaylistNameValid,
31 isVideoPlaylistPrivacyValid
32 } from '../../helpers/custom-validators/video-playlists'
38 VIDEO_PLAYLIST_PRIVACIES,
41 } from '../../initializers/constants'
42 import { MThumbnail } from '../../types/models/video/thumbnail'
44 MVideoPlaylistAccountThumbnail,
46 MVideoPlaylistFormattable,
48 MVideoPlaylistFullSummary,
49 MVideoPlaylistIdWithElements
50 } from '../../types/models/video/video-playlist'
51 import { AccountModel, ScopeNames as AccountScopeNames, SummaryOptions } from '../account/account'
52 import { buildServerIdsFollowedBy, buildWhereIdOrUUID, getPlaylistSort, isOutdated, throwIfNotValid } from '../utils'
53 import { ThumbnailModel } from './thumbnail'
54 import { ScopeNames as VideoChannelScopeNames, VideoChannelModel } from './video-channel'
55 import { VideoPlaylistElementModel } from './video-playlist-element'
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 listMyPlaylists?: 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 let whereActor: WhereOptions = {}
129 const whereAnd: WhereOptions[] = []
131 if (options.listMyPlaylists !== true) {
133 privacy: VideoPlaylistPrivacy.PUBLIC
136 // Only list local playlists OR playlists that are on an instance followed by actorId
137 const inQueryInstanceFollow = buildServerIdsFollowedBy(options.followerActorId)
146 [Op.in]: literal(inQueryInstanceFollow)
153 if (options.accountId) {
155 ownerAccountId: options.accountId
159 if (options.videoChannelId) {
161 videoChannelId: options.videoChannelId
171 if (options.search) {
174 [Op.iLike]: '%' + options.search + '%'
187 model: AccountModel.scope({
188 method: [ AccountScopeNames.SUMMARY, { whereActor } as SummaryOptions ]
193 model: VideoChannelModel.scope(VideoChannelScopeNames.SUMMARY),
202 tableName: 'videoPlaylist',
205 fields: [ 'ownerAccountId' ]
208 fields: [ 'videoChannelId' ]
216 export class VideoPlaylistModel extends Model {
224 @Is('VideoPlaylistName', value => throwIfNotValid(value, isVideoPlaylistNameValid, 'name'))
229 @Is('VideoPlaylistDescription', value => throwIfNotValid(value, isVideoPlaylistDescriptionValid, 'description', true))
230 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_PLAYLISTS.DESCRIPTION.max))
234 @Is('VideoPlaylistPrivacy', value => throwIfNotValid(value, isVideoPlaylistPrivacyValid, 'privacy'))
236 privacy: VideoPlaylistPrivacy
239 @Is('VideoPlaylistUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
240 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_PLAYLISTS.URL.max))
244 @Default(DataType.UUIDV4)
246 @Column(DataType.UUID)
250 @Default(VideoPlaylistType.REGULAR)
252 type: VideoPlaylistType
254 @ForeignKey(() => AccountModel)
256 ownerAccountId: number
258 @BelongsTo(() => AccountModel, {
264 OwnerAccount: AccountModel
266 @ForeignKey(() => VideoChannelModel)
268 videoChannelId: number
270 @BelongsTo(() => VideoChannelModel, {
276 VideoChannel: VideoChannelModel
278 @HasMany(() => VideoPlaylistElementModel, {
280 name: 'videoPlaylistId',
285 VideoPlaylistElements: VideoPlaylistElementModel[]
287 @HasOne(() => ThumbnailModel, {
289 name: 'videoPlaylistId',
295 Thumbnail: ThumbnailModel
297 static listForApi (options: {
298 followerActorId: number
302 type?: VideoPlaylistType
304 videoChannelId?: number
305 listMyPlaylists?: boolean
309 offset: options.start,
310 limit: options.count,
311 order: getPlaylistSort(options.sort)
314 const scopes: (string | ScopeOptions)[] = [
317 ScopeNames.AVAILABLE_FOR_LIST,
320 followerActorId: options.followerActorId,
321 accountId: options.accountId,
322 videoChannelId: options.videoChannelId,
323 listMyPlaylists: options.listMyPlaylists,
324 search: options.search
325 } as AvailableForListOptions
328 ScopeNames.WITH_VIDEOS_LENGTH,
329 ScopeNames.WITH_THUMBNAIL
332 return VideoPlaylistModel
334 .findAndCountAll(query)
335 .then(({ rows, count }) => {
336 return { total: count, data: rows }
340 static listPublicUrlsOfForAP (options: { account?: MAccountId, channel?: MChannelId }, start: number, count: number) {
342 privacy: VideoPlaylistPrivacy.PUBLIC
345 if (options.account) {
346 Object.assign(where, { ownerAccountId: options.account.id })
349 if (options.channel) {
350 Object.assign(where, { videoChannelId: options.channel.id })
354 attributes: [ 'url' ],
360 return VideoPlaylistModel.findAndCountAll(query)
361 .then(({ rows, count }) => {
362 return { total: count, data: rows.map(p => p.url) }
366 static listPlaylistIdsOf (accountId: number, videoIds: number[]): Promise<MVideoPlaylistIdWithElements[]> {
368 attributes: [ 'id' ],
370 ownerAccountId: accountId
374 attributes: [ 'id', 'videoId', 'startTimestamp', 'stopTimestamp' ],
375 model: VideoPlaylistElementModel.unscoped(),
386 return VideoPlaylistModel.findAll(query)
389 static doesPlaylistExist (url: string) {
391 attributes: [ 'id' ],
397 return VideoPlaylistModel
402 static loadWithAccountAndChannelSummary (id: number | string, transaction: Transaction): Promise<MVideoPlaylistFullSummary> {
403 const where = buildWhereIdOrUUID(id)
410 return VideoPlaylistModel
411 .scope([ ScopeNames.WITH_ACCOUNT_AND_CHANNEL_SUMMARY, ScopeNames.WITH_VIDEOS_LENGTH, ScopeNames.WITH_THUMBNAIL ])
415 static loadWithAccountAndChannel (id: number | string, transaction: Transaction): Promise<MVideoPlaylistFull> {
416 const where = buildWhereIdOrUUID(id)
423 return VideoPlaylistModel
424 .scope([ ScopeNames.WITH_ACCOUNT_AND_CHANNEL, ScopeNames.WITH_VIDEOS_LENGTH, ScopeNames.WITH_THUMBNAIL ])
428 static loadByUrlAndPopulateAccount (url: string): Promise<MVideoPlaylistAccountThumbnail> {
435 return VideoPlaylistModel.scope([ ScopeNames.WITH_ACCOUNT, ScopeNames.WITH_THUMBNAIL ]).findOne(query)
438 static getPrivacyLabel (privacy: VideoPlaylistPrivacy) {
439 return VIDEO_PLAYLIST_PRIVACIES[privacy] || 'Unknown'
442 static getTypeLabel (type: VideoPlaylistType) {
443 return VIDEO_PLAYLIST_TYPES[type] || 'Unknown'
446 static resetPlaylistsOfChannel (videoChannelId: number, transaction: Transaction) {
454 return VideoPlaylistModel.update({ privacy: VideoPlaylistPrivacy.PRIVATE, videoChannelId: null }, query)
457 async setAndSaveThumbnail (thumbnail: MThumbnail, t: Transaction) {
458 thumbnail.videoPlaylistId = this.id
460 this.Thumbnail = await thumbnail.save({ transaction: t })
464 return !!this.Thumbnail
467 hasGeneratedThumbnail () {
468 return this.hasThumbnail() && this.Thumbnail.automaticallyGenerated === true
471 generateThumbnailName () {
472 const extension = '.jpg'
474 return 'playlist-' + this.uuid + extension
478 if (!this.hasThumbnail()) return null
480 return WEBSERVER.URL + STATIC_PATHS.THUMBNAILS + this.Thumbnail.filename
483 getThumbnailStaticPath () {
484 if (!this.hasThumbnail()) return null
486 return join(STATIC_PATHS.THUMBNAILS, this.Thumbnail.filename)
490 return WEBSERVER.URL + '/videos/watch/playlist/' + this.uuid
493 getEmbedStaticPath () {
494 return '/video-playlists/embed/' + this.uuid
498 this.changed('updatedAt', true)
504 return this.OwnerAccount.isOwned()
508 if (this.isOwned()) return false
510 return isOutdated(this, ACTIVITY_PUB.VIDEO_PLAYLIST_REFRESH_INTERVAL)
513 toFormattedJSON (this: MVideoPlaylistFormattable): VideoPlaylist {
517 isLocal: this.isOwned(),
519 displayName: this.name,
520 description: this.description,
523 label: VideoPlaylistModel.getPrivacyLabel(this.privacy)
526 thumbnailPath: this.getThumbnailStaticPath(),
527 embedPath: this.getEmbedStaticPath(),
531 label: VideoPlaylistModel.getTypeLabel(this.type)
534 videosLength: this.get('videosLength') as number,
536 createdAt: this.createdAt,
537 updatedAt: this.updatedAt,
539 ownerAccount: this.OwnerAccount.toFormattedSummaryJSON(),
540 videoChannel: this.VideoChannel
541 ? this.VideoChannel.toFormattedSummaryJSON()
546 toActivityPubObject (this: MVideoPlaylistAP, page: number, t: Transaction): Promise<PlaylistObject> {
547 const handler = (start: number, count: number) => {
548 return VideoPlaylistElementModel.listUrlsOfForAP(this.id, start, count, t)
551 let icon: ActivityIconObject
552 if (this.hasThumbnail()) {
554 type: 'Image' as 'Image',
555 url: this.getThumbnailUrl(),
556 mediaType: 'image/jpeg' as 'image/jpeg',
557 width: THUMBNAILS_SIZE.width,
558 height: THUMBNAILS_SIZE.height
562 return activityPubCollectionPagination(this.url, handler, page)
564 return Object.assign(o, {
565 type: 'Playlist' as 'Playlist',
567 content: this.description,
569 published: this.createdAt.toISOString(),
570 updated: this.updatedAt.toISOString(),
571 attributedTo: this.VideoChannel ? [ this.VideoChannel.Actor.url ] : [],