1 import { join } from 'path'
2 import { FindOptions, literal, Op, ScopeOptions, Sequelize, Transaction, WhereOptions } from 'sequelize'
19 } from 'sequelize-typescript'
20 import { setAsUpdated } from '@server/helpers/database-utils'
21 import { buildUUID, uuidToShort } from '@server/helpers/uuid'
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'
57 buildServerIdsFollowedBy,
58 buildTrigramSearchIndex,
60 createSimilarityAttribute,
65 import { ThumbnailModel } from './thumbnail'
66 import { ScopeNames as VideoChannelScopeNames, VideoChannelModel } from './video-channel'
67 import { VideoPlaylistElementModel } from './video-playlist-element'
70 AVAILABLE_FOR_LIST = 'AVAILABLE_FOR_LIST',
71 WITH_VIDEOS_LENGTH = 'WITH_VIDEOS_LENGTH',
72 WITH_ACCOUNT_AND_CHANNEL_SUMMARY = 'WITH_ACCOUNT_AND_CHANNEL_SUMMARY',
73 WITH_ACCOUNT = 'WITH_ACCOUNT',
74 WITH_THUMBNAIL = 'WITH_THUMBNAIL',
75 WITH_ACCOUNT_AND_CHANNEL = 'WITH_ACCOUNT_AND_CHANNEL'
78 type AvailableForListOptions = {
79 followerActorId?: number
80 type?: VideoPlaylistType
82 videoChannelId?: number
83 listMyPlaylists?: boolean
88 function getVideoLengthSelect () {
89 return 'SELECT COUNT("id") FROM "videoPlaylistElement" WHERE "videoPlaylistId" = "VideoPlaylistModel"."id"'
93 [ScopeNames.WITH_THUMBNAIL]: {
96 model: ThumbnailModel,
101 [ScopeNames.WITH_VIDEOS_LENGTH]: {
105 literal(`(${getVideoLengthSelect()})`),
111 [ScopeNames.WITH_ACCOUNT]: {
119 [ScopeNames.WITH_ACCOUNT_AND_CHANNEL_SUMMARY]: {
122 model: AccountModel.scope(AccountScopeNames.SUMMARY),
126 model: VideoChannelModel.scope(VideoChannelScopeNames.SUMMARY),
131 [ScopeNames.WITH_ACCOUNT_AND_CHANNEL]: {
138 model: VideoChannelModel,
143 [ScopeNames.AVAILABLE_FOR_LIST]: (options: AvailableForListOptions) => {
144 let whereActor: WhereOptions = {}
146 const whereAnd: WhereOptions[] = []
148 if (options.listMyPlaylists !== true) {
150 privacy: VideoPlaylistPrivacy.PUBLIC
153 // Only list local playlists
154 const whereActorOr: WhereOptions[] = [
160 // … OR playlists that are on an instance followed by actorId
161 if (options.followerActorId) {
162 const inQueryInstanceFollow = buildServerIdsFollowedBy(options.followerActorId)
166 [Op.in]: literal(inQueryInstanceFollow)
172 [Op.or]: whereActorOr
176 if (options.accountId) {
178 ownerAccountId: options.accountId
182 if (options.videoChannelId) {
184 videoChannelId: options.videoChannelId
194 if (options.withVideos === true) {
196 literal(`(${getVideoLengthSelect()}) != 0`)
200 const attributesInclude = []
202 if (options.search) {
203 const escapedSearch = VideoPlaylistModel.sequelize.escape(options.search)
204 const escapedLikeSearch = VideoPlaylistModel.sequelize.escape('%' + options.search + '%')
205 attributesInclude.push(createSimilarityAttribute('VideoPlaylistModel.name', options.search))
210 'lower(immutable_unaccent("VideoPlaylistModel"."name")) % lower(immutable_unaccent(' + escapedSearch + '))'
213 'lower(immutable_unaccent("VideoPlaylistModel"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))'
225 include: attributesInclude
230 model: AccountModel.scope({
231 method: [ AccountScopeNames.SUMMARY, { whereActor } as SummaryOptions ]
236 model: VideoChannelModel.scope(VideoChannelScopeNames.SUMMARY),
245 tableName: 'videoPlaylist',
247 buildTrigramSearchIndex('video_playlist_name_trigram', 'name'),
250 fields: [ 'ownerAccountId' ]
253 fields: [ 'videoChannelId' ]
261 export class VideoPlaylistModel extends Model<Partial<AttributesOnly<VideoPlaylistModel>>> {
269 @Is('VideoPlaylistName', value => throwIfNotValid(value, isVideoPlaylistNameValid, 'name'))
274 @Is('VideoPlaylistDescription', value => throwIfNotValid(value, isVideoPlaylistDescriptionValid, 'description', true))
275 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_PLAYLISTS.DESCRIPTION.max))
279 @Is('VideoPlaylistPrivacy', value => throwIfNotValid(value, isVideoPlaylistPrivacyValid, 'privacy'))
281 privacy: VideoPlaylistPrivacy
284 @Is('VideoPlaylistUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
285 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_PLAYLISTS.URL.max))
289 @Default(DataType.UUIDV4)
291 @Column(DataType.UUID)
295 @Default(VideoPlaylistType.REGULAR)
297 type: VideoPlaylistType
299 @ForeignKey(() => AccountModel)
301 ownerAccountId: number
303 @BelongsTo(() => AccountModel, {
309 OwnerAccount: AccountModel
311 @ForeignKey(() => VideoChannelModel)
313 videoChannelId: number
315 @BelongsTo(() => VideoChannelModel, {
321 VideoChannel: VideoChannelModel
323 @HasMany(() => VideoPlaylistElementModel, {
325 name: 'videoPlaylistId',
330 VideoPlaylistElements: VideoPlaylistElementModel[]
332 @HasOne(() => ThumbnailModel, {
334 name: 'videoPlaylistId',
340 Thumbnail: ThumbnailModel
342 static listForApi (options: {
343 followerActorId: number
347 type?: VideoPlaylistType
349 videoChannelId?: number
350 listMyPlaylists?: boolean
352 withVideos?: boolean // false by default
355 offset: options.start,
356 limit: options.count,
357 order: getPlaylistSort(options.sort)
360 const scopes: (string | ScopeOptions)[] = [
363 ScopeNames.AVAILABLE_FOR_LIST,
366 followerActorId: options.followerActorId,
367 accountId: options.accountId,
368 videoChannelId: options.videoChannelId,
369 listMyPlaylists: options.listMyPlaylists,
370 search: options.search,
371 withVideos: options.withVideos || false
372 } as AvailableForListOptions
375 ScopeNames.WITH_VIDEOS_LENGTH,
376 ScopeNames.WITH_THUMBNAIL
379 return VideoPlaylistModel
381 .findAndCountAll(query)
382 .then(({ rows, count }) => {
383 return { total: count, data: rows }
387 static searchForApi (options: {
388 followerActorId: number
394 return VideoPlaylistModel.listForApi({
396 type: VideoPlaylistType.REGULAR,
397 listMyPlaylists: false,
402 static listPublicUrlsOfForAP (options: { account?: MAccountId, channel?: MChannelId }, start: number, count: number) {
404 privacy: VideoPlaylistPrivacy.PUBLIC
407 if (options.account) {
408 Object.assign(where, { ownerAccountId: options.account.id })
411 if (options.channel) {
412 Object.assign(where, { videoChannelId: options.channel.id })
416 attributes: [ 'url' ],
422 return VideoPlaylistModel.findAndCountAll(query)
423 .then(({ rows, count }) => {
424 return { total: count, data: rows.map(p => p.url) }
428 static listPlaylistIdsOf (accountId: number, videoIds: number[]): Promise<MVideoPlaylistIdWithElements[]> {
430 attributes: [ 'id' ],
432 ownerAccountId: accountId
436 attributes: [ 'id', 'videoId', 'startTimestamp', 'stopTimestamp' ],
437 model: VideoPlaylistElementModel.unscoped(),
448 return VideoPlaylistModel.findAll(query)
451 static doesPlaylistExist (url: string) {
453 attributes: [ 'id' ],
459 return VideoPlaylistModel
464 static loadWithAccountAndChannelSummary (id: number | string, transaction: Transaction): Promise<MVideoPlaylistFullSummary> {
465 const where = buildWhereIdOrUUID(id)
472 return VideoPlaylistModel
473 .scope([ ScopeNames.WITH_ACCOUNT_AND_CHANNEL_SUMMARY, ScopeNames.WITH_VIDEOS_LENGTH, ScopeNames.WITH_THUMBNAIL ])
477 static loadWithAccountAndChannel (id: number | string, transaction: Transaction): Promise<MVideoPlaylistFull> {
478 const where = buildWhereIdOrUUID(id)
485 return VideoPlaylistModel
486 .scope([ ScopeNames.WITH_ACCOUNT_AND_CHANNEL, ScopeNames.WITH_VIDEOS_LENGTH, ScopeNames.WITH_THUMBNAIL ])
490 static loadByUrlAndPopulateAccount (url: string): Promise<MVideoPlaylistAccountThumbnail> {
497 return VideoPlaylistModel.scope([ ScopeNames.WITH_ACCOUNT, ScopeNames.WITH_THUMBNAIL ]).findOne(query)
500 static loadByUrlWithAccountAndChannelSummary (url: string): Promise<MVideoPlaylistFullSummary> {
507 return VideoPlaylistModel
508 .scope([ ScopeNames.WITH_ACCOUNT_AND_CHANNEL_SUMMARY, ScopeNames.WITH_VIDEOS_LENGTH, ScopeNames.WITH_THUMBNAIL ])
512 static getPrivacyLabel (privacy: VideoPlaylistPrivacy) {
513 return VIDEO_PLAYLIST_PRIVACIES[privacy] || 'Unknown'
516 static getTypeLabel (type: VideoPlaylistType) {
517 return VIDEO_PLAYLIST_TYPES[type] || 'Unknown'
520 static resetPlaylistsOfChannel (videoChannelId: number, transaction: Transaction) {
528 return VideoPlaylistModel.update({ privacy: VideoPlaylistPrivacy.PRIVATE, videoChannelId: null }, query)
531 async setAndSaveThumbnail (thumbnail: MThumbnail, t: Transaction) {
532 thumbnail.videoPlaylistId = this.id
534 this.Thumbnail = await thumbnail.save({ transaction: t })
538 return !!this.Thumbnail
541 hasGeneratedThumbnail () {
542 return this.hasThumbnail() && this.Thumbnail.automaticallyGenerated === true
545 generateThumbnailName () {
546 const extension = '.jpg'
548 return 'playlist-' + buildUUID() + extension
552 if (!this.hasThumbnail()) return null
554 return WEBSERVER.URL + STATIC_PATHS.THUMBNAILS + this.Thumbnail.filename
557 getThumbnailStaticPath () {
558 if (!this.hasThumbnail()) return null
560 return join(STATIC_PATHS.THUMBNAILS, this.Thumbnail.filename)
564 return WEBSERVER.URL + '/w/p/' + this.uuid
567 getEmbedStaticPath () {
568 return '/video-playlists/embed/' + this.uuid
571 static async getStats () {
572 const totalLocalPlaylists = await VideoPlaylistModel.count({
589 privacy: VideoPlaylistPrivacy.PUBLIC
599 return setAsUpdated('videoPlaylist', this.id)
602 setVideosLength (videosLength: number) {
603 this.set('videosLength' as any, videosLength, { raw: true })
607 return this.OwnerAccount.isOwned()
611 if (this.isOwned()) return false
613 return isOutdated(this, ACTIVITY_PUB.VIDEO_PLAYLIST_REFRESH_INTERVAL)
616 toFormattedJSON (this: MVideoPlaylistFormattable): VideoPlaylist {
620 shortUUID: uuidToShort(this.uuid),
622 isLocal: this.isOwned(),
626 displayName: this.name,
627 description: this.description,
630 label: VideoPlaylistModel.getPrivacyLabel(this.privacy)
633 thumbnailPath: this.getThumbnailStaticPath(),
634 embedPath: this.getEmbedStaticPath(),
638 label: VideoPlaylistModel.getTypeLabel(this.type)
641 videosLength: this.get('videosLength') as number,
643 createdAt: this.createdAt,
644 updatedAt: this.updatedAt,
646 ownerAccount: this.OwnerAccount.toFormattedSummaryJSON(),
647 videoChannel: this.VideoChannel
648 ? this.VideoChannel.toFormattedSummaryJSON()
653 toActivityPubObject (this: MVideoPlaylistAP, page: number, t: Transaction): Promise<PlaylistObject> {
654 const handler = (start: number, count: number) => {
655 return VideoPlaylistElementModel.listUrlsOfForAP(this.id, start, count, t)
658 let icon: ActivityIconObject
659 if (this.hasThumbnail()) {
661 type: 'Image' as 'Image',
662 url: this.getThumbnailUrl(),
663 mediaType: 'image/jpeg' as 'image/jpeg',
664 width: THUMBNAILS_SIZE.width,
665 height: THUMBNAILS_SIZE.height
669 return activityPubCollectionPagination(this.url, handler, page)
671 return Object.assign(o, {
672 type: 'Playlist' as 'Playlist',
674 content: this.description,
676 published: this.createdAt.toISOString(),
677 updated: this.updatedAt.toISOString(),
678 attributedTo: this.VideoChannel ? [ this.VideoChannel.Actor.url ] : [],