1 import { join } from 'path'
2 import { FindOptions, Includeable, literal, Op, ScopeOptions, Sequelize, Transaction, WhereOptions } from 'sequelize'
19 } from 'sequelize-typescript'
20 import { activityPubCollectionPagination } from '@server/lib/activitypub/collection'
21 import { MAccountId, MChannelId } from '@server/types/models'
22 import { buildPlaylistEmbedPath, buildPlaylistWatchPath, pick } from '@shared/core-utils'
23 import { buildUUID, uuidToShort } from '@shared/extra-utils'
24 import { ActivityIconObject, PlaylistObject, VideoPlaylist, VideoPlaylistPrivacy, VideoPlaylistType } from '@shared/models'
25 import { AttributesOnly } from '@shared/typescript-utils'
26 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
28 isVideoPlaylistDescriptionValid,
29 isVideoPlaylistNameValid,
30 isVideoPlaylistPrivacyValid
31 } from '../../helpers/custom-validators/video-playlists'
37 VIDEO_PLAYLIST_PRIVACIES,
40 } from '../../initializers/constants'
41 import { MThumbnail } from '../../types/models/video/thumbnail'
43 MVideoPlaylistAccountThumbnail,
45 MVideoPlaylistFormattable,
47 MVideoPlaylistFullSummary,
48 MVideoPlaylistSummaryWithElements
49 } from '../../types/models/video/video-playlist'
50 import { AccountModel, ScopeNames as AccountScopeNames, SummaryOptions } from '../account/account'
51 import { ActorModel } from '../actor/actor'
53 buildServerIdsFollowedBy,
54 buildTrigramSearchIndex,
56 createSimilarityAttribute,
62 import { ThumbnailModel } from './thumbnail'
63 import { ScopeNames as VideoChannelScopeNames, VideoChannelModel } from './video-channel'
64 import { VideoPlaylistElementModel } from './video-playlist-element'
67 AVAILABLE_FOR_LIST = 'AVAILABLE_FOR_LIST',
68 WITH_VIDEOS_LENGTH = 'WITH_VIDEOS_LENGTH',
69 WITH_ACCOUNT_AND_CHANNEL_SUMMARY = 'WITH_ACCOUNT_AND_CHANNEL_SUMMARY',
70 WITH_ACCOUNT = 'WITH_ACCOUNT',
71 WITH_THUMBNAIL = 'WITH_THUMBNAIL',
72 WITH_ACCOUNT_AND_CHANNEL = 'WITH_ACCOUNT_AND_CHANNEL'
75 type AvailableForListOptions = {
76 followerActorId?: number
77 type?: VideoPlaylistType
79 videoChannelId?: number
80 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 const whereAnd: WhereOptions[] = []
146 const whereServer = options.host && options.host !== WEBSERVER.HOST
147 ? { host: options.host }
150 let whereActor: WhereOptions = {}
152 if (options.host === WEBSERVER.HOST) {
154 [Op.and]: [ { serverId: null } ]
158 if (options.listMyPlaylists !== true) {
160 privacy: VideoPlaylistPrivacy.PUBLIC
163 // Only list local playlists
164 const whereActorOr: WhereOptions[] = [
170 // … OR playlists that are on an instance followed by actorId
171 if (options.followerActorId) {
172 const inQueryInstanceFollow = buildServerIdsFollowedBy(options.followerActorId)
176 [Op.in]: literal(inQueryInstanceFollow)
181 Object.assign(whereActor, { [Op.or]: whereActorOr })
184 if (options.accountId) {
186 ownerAccountId: options.accountId
190 if (options.videoChannelId) {
192 videoChannelId: options.videoChannelId
205 [Op.in]: options.uuids
210 if (options.withVideos === true) {
212 literal(`(${getVideoLengthSelect()}) != 0`)
216 let attributesInclude: any[] = [ literal('0 as similarity') ]
218 if (options.search) {
219 const escapedSearch = VideoPlaylistModel.sequelize.escape(options.search)
220 const escapedLikeSearch = VideoPlaylistModel.sequelize.escape('%' + options.search + '%')
221 attributesInclude = [ createSimilarityAttribute('VideoPlaylistModel.name', options.search) ]
226 'lower(immutable_unaccent("VideoPlaylistModel"."name")) % lower(immutable_unaccent(' + escapedSearch + '))'
229 'lower(immutable_unaccent("VideoPlaylistModel"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))'
239 const include: Includeable[] = [
241 model: AccountModel.scope({
242 method: [ AccountScopeNames.SUMMARY, { whereActor, whereServer, forCount: options.forCount } as SummaryOptions ]
248 if (options.forCount !== true) {
250 model: VideoChannelModel.scope(VideoChannelScopeNames.SUMMARY),
257 include: attributesInclude
266 tableName: 'videoPlaylist',
268 buildTrigramSearchIndex('video_playlist_name_trigram', 'name'),
271 fields: [ 'ownerAccountId' ]
274 fields: [ 'videoChannelId' ]
282 export class VideoPlaylistModel extends Model<Partial<AttributesOnly<VideoPlaylistModel>>> {
290 @Is('VideoPlaylistName', value => throwIfNotValid(value, isVideoPlaylistNameValid, 'name'))
295 @Is('VideoPlaylistDescription', value => throwIfNotValid(value, isVideoPlaylistDescriptionValid, 'description', true))
296 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_PLAYLISTS.DESCRIPTION.max))
300 @Is('VideoPlaylistPrivacy', value => throwIfNotValid(value, isVideoPlaylistPrivacyValid, 'privacy'))
302 privacy: VideoPlaylistPrivacy
305 @Is('VideoPlaylistUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
306 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_PLAYLISTS.URL.max))
310 @Default(DataType.UUIDV4)
312 @Column(DataType.UUID)
316 @Default(VideoPlaylistType.REGULAR)
318 type: VideoPlaylistType
320 @ForeignKey(() => AccountModel)
322 ownerAccountId: number
324 @BelongsTo(() => AccountModel, {
330 OwnerAccount: AccountModel
332 @ForeignKey(() => VideoChannelModel)
334 videoChannelId: number
336 @BelongsTo(() => VideoChannelModel, {
342 VideoChannel: VideoChannelModel
344 @HasMany(() => VideoPlaylistElementModel, {
346 name: 'videoPlaylistId',
351 VideoPlaylistElements: VideoPlaylistElementModel[]
353 @HasOne(() => ThumbnailModel, {
355 name: 'videoPlaylistId',
361 Thumbnail: ThumbnailModel
363 static listForApi (options: AvailableForListOptions & {
369 offset: options.start,
370 limit: options.count,
371 order: getPlaylistSort(options.sort)
374 const commonAvailableForListOptions = pick(options, [
385 const scopesFind: (string | ScopeOptions)[] = [
388 ScopeNames.AVAILABLE_FOR_LIST,
390 ...commonAvailableForListOptions,
392 withVideos: options.withVideos || false
393 } as AvailableForListOptions
396 ScopeNames.WITH_VIDEOS_LENGTH,
397 ScopeNames.WITH_THUMBNAIL
400 const scopesCount: (string | ScopeOptions)[] = [
403 ScopeNames.AVAILABLE_FOR_LIST,
406 ...commonAvailableForListOptions,
408 withVideos: options.withVideos || false,
410 } as AvailableForListOptions
413 ScopeNames.WITH_VIDEOS_LENGTH
417 VideoPlaylistModel.scope(scopesCount).count(),
418 VideoPlaylistModel.scope(scopesFind).findAll(query)
419 ]).then(([ count, rows ]) => ({ total: count, data: rows }))
422 static searchForApi (options: Pick<AvailableForListOptions, 'followerActorId' | 'search' | 'host' | 'uuids'> & {
427 return VideoPlaylistModel.listForApi({
430 type: VideoPlaylistType.REGULAR,
431 listMyPlaylists: false,
436 static listPublicUrlsOfForAP (options: { account?: MAccountId, channel?: MChannelId }, start: number, count: number) {
438 privacy: VideoPlaylistPrivacy.PUBLIC
441 if (options.account) {
442 Object.assign(where, { ownerAccountId: options.account.id })
445 if (options.channel) {
446 Object.assign(where, { videoChannelId: options.channel.id })
449 const getQuery = (forCount: boolean) => {
451 attributes: forCount === true
461 VideoPlaylistModel.count(getQuery(true)),
462 VideoPlaylistModel.findAll(getQuery(false))
463 ]).then(([ total, rows ]) => ({
465 data: rows.map(p => p.url)
469 static listPlaylistSummariesOf (accountId: number, videoIds: number[]): Promise<MVideoPlaylistSummaryWithElements[]> {
471 attributes: [ 'id', 'name', 'uuid' ],
473 ownerAccountId: accountId
477 attributes: [ 'id', 'videoId', 'startTimestamp', 'stopTimestamp' ],
478 model: VideoPlaylistElementModel.unscoped(),
489 return VideoPlaylistModel.findAll(query)
492 static doesPlaylistExist (url: string) {
494 attributes: [ 'id' ],
500 return VideoPlaylistModel
505 static loadWithAccountAndChannelSummary (id: number | string, transaction: Transaction): Promise<MVideoPlaylistFullSummary> {
506 const where = buildWhereIdOrUUID(id)
513 return VideoPlaylistModel
514 .scope([ ScopeNames.WITH_ACCOUNT_AND_CHANNEL_SUMMARY, ScopeNames.WITH_VIDEOS_LENGTH, ScopeNames.WITH_THUMBNAIL ])
518 static loadWithAccountAndChannel (id: number | string, transaction: Transaction): Promise<MVideoPlaylistFull> {
519 const where = buildWhereIdOrUUID(id)
526 return VideoPlaylistModel
527 .scope([ ScopeNames.WITH_ACCOUNT_AND_CHANNEL, ScopeNames.WITH_VIDEOS_LENGTH, ScopeNames.WITH_THUMBNAIL ])
531 static loadByUrlAndPopulateAccount (url: string): Promise<MVideoPlaylistAccountThumbnail> {
538 return VideoPlaylistModel.scope([ ScopeNames.WITH_ACCOUNT, ScopeNames.WITH_THUMBNAIL ]).findOne(query)
541 static loadByUrlWithAccountAndChannelSummary (url: string): Promise<MVideoPlaylistFullSummary> {
548 return VideoPlaylistModel
549 .scope([ ScopeNames.WITH_ACCOUNT_AND_CHANNEL_SUMMARY, ScopeNames.WITH_VIDEOS_LENGTH, ScopeNames.WITH_THUMBNAIL ])
553 static getPrivacyLabel (privacy: VideoPlaylistPrivacy) {
554 return VIDEO_PLAYLIST_PRIVACIES[privacy] || 'Unknown'
557 static getTypeLabel (type: VideoPlaylistType) {
558 return VIDEO_PLAYLIST_TYPES[type] || 'Unknown'
561 static resetPlaylistsOfChannel (videoChannelId: number, transaction: Transaction) {
569 return VideoPlaylistModel.update({ privacy: VideoPlaylistPrivacy.PRIVATE, videoChannelId: null }, query)
572 async setAndSaveThumbnail (thumbnail: MThumbnail, t: Transaction) {
573 thumbnail.videoPlaylistId = this.id
575 this.Thumbnail = await thumbnail.save({ transaction: t })
579 return !!this.Thumbnail
582 hasGeneratedThumbnail () {
583 return this.hasThumbnail() && this.Thumbnail.automaticallyGenerated === true
586 generateThumbnailName () {
587 const extension = '.jpg'
589 return 'playlist-' + buildUUID() + extension
593 if (!this.hasThumbnail()) return null
595 return WEBSERVER.URL + STATIC_PATHS.THUMBNAILS + this.Thumbnail.filename
598 getThumbnailStaticPath () {
599 if (!this.hasThumbnail()) return null
601 return join(STATIC_PATHS.THUMBNAILS, this.Thumbnail.filename)
604 getWatchStaticPath () {
605 return buildPlaylistWatchPath({ shortUUID: uuidToShort(this.uuid) })
608 getEmbedStaticPath () {
609 return buildPlaylistEmbedPath(this)
612 static async getStats () {
613 const totalLocalPlaylists = await VideoPlaylistModel.count({
616 model: AccountModel.unscoped(),
620 model: ActorModel.unscoped(),
630 privacy: VideoPlaylistPrivacy.PUBLIC
640 return setAsUpdated({ sequelize: this.sequelize, table: 'videoPlaylist', id: this.id })
643 setVideosLength (videosLength: number) {
644 this.set('videosLength' as any, videosLength, { raw: true })
648 return this.OwnerAccount.isOwned()
652 if (this.isOwned()) return false
654 return isOutdated(this, ACTIVITY_PUB.VIDEO_PLAYLIST_REFRESH_INTERVAL)
657 toFormattedJSON (this: MVideoPlaylistFormattable): VideoPlaylist {
661 shortUUID: uuidToShort(this.uuid),
663 isLocal: this.isOwned(),
667 displayName: this.name,
668 description: this.description,
671 label: VideoPlaylistModel.getPrivacyLabel(this.privacy)
674 thumbnailPath: this.getThumbnailStaticPath(),
675 embedPath: this.getEmbedStaticPath(),
679 label: VideoPlaylistModel.getTypeLabel(this.type)
682 videosLength: this.get('videosLength') as number,
684 createdAt: this.createdAt,
685 updatedAt: this.updatedAt,
687 ownerAccount: this.OwnerAccount.toFormattedSummaryJSON(),
688 videoChannel: this.VideoChannel
689 ? this.VideoChannel.toFormattedSummaryJSON()
694 toActivityPubObject (this: MVideoPlaylistAP, page: number, t: Transaction): Promise<PlaylistObject> {
695 const handler = (start: number, count: number) => {
696 return VideoPlaylistElementModel.listUrlsOfForAP(this.id, start, count, t)
699 let icon: ActivityIconObject
700 if (this.hasThumbnail()) {
702 type: 'Image' as 'Image',
703 url: this.getThumbnailUrl(),
704 mediaType: 'image/jpeg' as 'image/jpeg',
705 width: THUMBNAILS_SIZE.width,
706 height: THUMBNAILS_SIZE.height
710 return activityPubCollectionPagination(this.url, handler, page)
712 return Object.assign(o, {
713 type: 'Playlist' as 'Playlist',
715 content: this.description,
716 mediaType: 'text/markdown' as 'text/markdown',
718 published: this.createdAt.toISOString(),
719 updated: this.updatedAt.toISOString(),
720 attributedTo: this.VideoChannel ? [ this.VideoChannel.Actor.url ] : [],