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 { AttributesOnly } from '@shared/typescript-utils'
25 import { ActivityIconObject } from '../../../shared/models/activitypub/objects'
26 import { PlaylistObject } from '../../../shared/models/activitypub/objects/playlist-object'
27 import { VideoPlaylistPrivacy } from '../../../shared/models/videos/playlist/video-playlist-privacy.model'
28 import { VideoPlaylistType } from '../../../shared/models/videos/playlist/video-playlist-type.model'
29 import { VideoPlaylist } from '../../../shared/models/videos/playlist/video-playlist.model'
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 { setAsUpdated } from '../shared'
58 buildServerIdsFollowedBy,
59 buildTrigramSearchIndex,
61 createSimilarityAttribute,
66 import { ThumbnailModel } from './thumbnail'
67 import { ScopeNames as VideoChannelScopeNames, VideoChannelModel } from './video-channel'
68 import { VideoPlaylistElementModel } from './video-playlist-element'
71 AVAILABLE_FOR_LIST = 'AVAILABLE_FOR_LIST',
72 WITH_VIDEOS_LENGTH = 'WITH_VIDEOS_LENGTH',
73 WITH_ACCOUNT_AND_CHANNEL_SUMMARY = 'WITH_ACCOUNT_AND_CHANNEL_SUMMARY',
74 WITH_ACCOUNT = 'WITH_ACCOUNT',
75 WITH_THUMBNAIL = 'WITH_THUMBNAIL',
76 WITH_ACCOUNT_AND_CHANNEL = 'WITH_ACCOUNT_AND_CHANNEL'
79 type AvailableForListOptions = {
80 followerActorId?: number
81 type?: VideoPlaylistType
83 videoChannelId?: number
84 listMyPlaylists?: boolean
92 function getVideoLengthSelect () {
93 return 'SELECT COUNT("id") FROM "videoPlaylistElement" WHERE "videoPlaylistId" = "VideoPlaylistModel"."id"'
97 [ScopeNames.WITH_THUMBNAIL]: {
100 model: ThumbnailModel,
105 [ScopeNames.WITH_VIDEOS_LENGTH]: {
109 literal(`(${getVideoLengthSelect()})`),
115 [ScopeNames.WITH_ACCOUNT]: {
123 [ScopeNames.WITH_ACCOUNT_AND_CHANNEL_SUMMARY]: {
126 model: AccountModel.scope(AccountScopeNames.SUMMARY),
130 model: VideoChannelModel.scope(VideoChannelScopeNames.SUMMARY),
135 [ScopeNames.WITH_ACCOUNT_AND_CHANNEL]: {
142 model: VideoChannelModel,
147 [ScopeNames.AVAILABLE_FOR_LIST]: (options: AvailableForListOptions) => {
148 const whereAnd: WhereOptions[] = []
150 const whereServer = options.host && options.host !== WEBSERVER.HOST
151 ? { host: options.host }
154 let whereActor: WhereOptions = {}
156 if (options.host === WEBSERVER.HOST) {
158 [Op.and]: [ { serverId: null } ]
162 if (options.listMyPlaylists !== true) {
164 privacy: VideoPlaylistPrivacy.PUBLIC
167 // Only list local playlists
168 const whereActorOr: WhereOptions[] = [
174 // … OR playlists that are on an instance followed by actorId
175 if (options.followerActorId) {
176 const inQueryInstanceFollow = buildServerIdsFollowedBy(options.followerActorId)
180 [Op.in]: literal(inQueryInstanceFollow)
185 Object.assign(whereActor, { [Op.or]: whereActorOr })
188 if (options.accountId) {
190 ownerAccountId: options.accountId
194 if (options.videoChannelId) {
196 videoChannelId: options.videoChannelId
209 [Op.in]: options.uuids
214 if (options.withVideos === true) {
216 literal(`(${getVideoLengthSelect()}) != 0`)
220 let attributesInclude: any[] = [ literal('0 as similarity') ]
222 if (options.search) {
223 const escapedSearch = VideoPlaylistModel.sequelize.escape(options.search)
224 const escapedLikeSearch = VideoPlaylistModel.sequelize.escape('%' + options.search + '%')
225 attributesInclude = [ createSimilarityAttribute('VideoPlaylistModel.name', options.search) ]
230 'lower(immutable_unaccent("VideoPlaylistModel"."name")) % lower(immutable_unaccent(' + escapedSearch + '))'
233 'lower(immutable_unaccent("VideoPlaylistModel"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))'
243 const include: Includeable[] = [
245 model: AccountModel.scope({
246 method: [ AccountScopeNames.SUMMARY, { whereActor, whereServer, forCount: options.forCount } as SummaryOptions ]
252 if (options.forCount !== true) {
254 model: VideoChannelModel.scope(VideoChannelScopeNames.SUMMARY),
261 include: attributesInclude
270 tableName: 'videoPlaylist',
272 buildTrigramSearchIndex('video_playlist_name_trigram', 'name'),
275 fields: [ 'ownerAccountId' ]
278 fields: [ 'videoChannelId' ]
286 export class VideoPlaylistModel extends Model<Partial<AttributesOnly<VideoPlaylistModel>>> {
294 @Is('VideoPlaylistName', value => throwIfNotValid(value, isVideoPlaylistNameValid, 'name'))
299 @Is('VideoPlaylistDescription', value => throwIfNotValid(value, isVideoPlaylistDescriptionValid, 'description', true))
300 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_PLAYLISTS.DESCRIPTION.max))
304 @Is('VideoPlaylistPrivacy', value => throwIfNotValid(value, isVideoPlaylistPrivacyValid, 'privacy'))
306 privacy: VideoPlaylistPrivacy
309 @Is('VideoPlaylistUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
310 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_PLAYLISTS.URL.max))
314 @Default(DataType.UUIDV4)
316 @Column(DataType.UUID)
320 @Default(VideoPlaylistType.REGULAR)
322 type: VideoPlaylistType
324 @ForeignKey(() => AccountModel)
326 ownerAccountId: number
328 @BelongsTo(() => AccountModel, {
334 OwnerAccount: AccountModel
336 @ForeignKey(() => VideoChannelModel)
338 videoChannelId: number
340 @BelongsTo(() => VideoChannelModel, {
346 VideoChannel: VideoChannelModel
348 @HasMany(() => VideoPlaylistElementModel, {
350 name: 'videoPlaylistId',
355 VideoPlaylistElements: VideoPlaylistElementModel[]
357 @HasOne(() => ThumbnailModel, {
359 name: 'videoPlaylistId',
365 Thumbnail: ThumbnailModel
367 static listForApi (options: AvailableForListOptions & {
373 offset: options.start,
374 limit: options.count,
375 order: getPlaylistSort(options.sort)
378 const commonAvailableForListOptions = pick(options, [
389 const scopesFind: (string | ScopeOptions)[] = [
392 ScopeNames.AVAILABLE_FOR_LIST,
394 ...commonAvailableForListOptions,
396 withVideos: options.withVideos || false
397 } as AvailableForListOptions
400 ScopeNames.WITH_VIDEOS_LENGTH,
401 ScopeNames.WITH_THUMBNAIL
404 const scopesCount: (string | ScopeOptions)[] = [
407 ScopeNames.AVAILABLE_FOR_LIST,
410 ...commonAvailableForListOptions,
412 withVideos: options.withVideos || false,
414 } as AvailableForListOptions
417 ScopeNames.WITH_VIDEOS_LENGTH
421 VideoPlaylistModel.scope(scopesCount).count(),
422 VideoPlaylistModel.scope(scopesFind).findAll(query)
423 ]).then(([ count, rows ]) => ({ total: count, data: rows }))
426 static searchForApi (options: Pick<AvailableForListOptions, 'followerActorId' | 'search'| 'host'| 'uuids'> & {
431 return VideoPlaylistModel.listForApi({
434 type: VideoPlaylistType.REGULAR,
435 listMyPlaylists: false,
440 static listPublicUrlsOfForAP (options: { account?: MAccountId, channel?: MChannelId }, start: number, count: number) {
442 privacy: VideoPlaylistPrivacy.PUBLIC
445 if (options.account) {
446 Object.assign(where, { ownerAccountId: options.account.id })
449 if (options.channel) {
450 Object.assign(where, { videoChannelId: options.channel.id })
453 const getQuery = (forCount: boolean) => {
455 attributes: forCount === true
465 VideoPlaylistModel.count(getQuery(true)),
466 VideoPlaylistModel.findAll(getQuery(false))
467 ]).then(([ total, rows ]) => ({
469 data: rows.map(p => p.url)
473 static listPlaylistIdsOf (accountId: number, videoIds: number[]): Promise<MVideoPlaylistIdWithElements[]> {
475 attributes: [ 'id' ],
477 ownerAccountId: accountId
481 attributes: [ 'id', 'videoId', 'startTimestamp', 'stopTimestamp' ],
482 model: VideoPlaylistElementModel.unscoped(),
493 return VideoPlaylistModel.findAll(query)
496 static doesPlaylistExist (url: string) {
498 attributes: [ 'id' ],
504 return VideoPlaylistModel
509 static loadWithAccountAndChannelSummary (id: number | string, transaction: Transaction): Promise<MVideoPlaylistFullSummary> {
510 const where = buildWhereIdOrUUID(id)
517 return VideoPlaylistModel
518 .scope([ ScopeNames.WITH_ACCOUNT_AND_CHANNEL_SUMMARY, ScopeNames.WITH_VIDEOS_LENGTH, ScopeNames.WITH_THUMBNAIL ])
522 static loadWithAccountAndChannel (id: number | string, transaction: Transaction): Promise<MVideoPlaylistFull> {
523 const where = buildWhereIdOrUUID(id)
530 return VideoPlaylistModel
531 .scope([ ScopeNames.WITH_ACCOUNT_AND_CHANNEL, ScopeNames.WITH_VIDEOS_LENGTH, ScopeNames.WITH_THUMBNAIL ])
535 static loadByUrlAndPopulateAccount (url: string): Promise<MVideoPlaylistAccountThumbnail> {
542 return VideoPlaylistModel.scope([ ScopeNames.WITH_ACCOUNT, ScopeNames.WITH_THUMBNAIL ]).findOne(query)
545 static loadByUrlWithAccountAndChannelSummary (url: string): Promise<MVideoPlaylistFullSummary> {
552 return VideoPlaylistModel
553 .scope([ ScopeNames.WITH_ACCOUNT_AND_CHANNEL_SUMMARY, ScopeNames.WITH_VIDEOS_LENGTH, ScopeNames.WITH_THUMBNAIL ])
557 static getPrivacyLabel (privacy: VideoPlaylistPrivacy) {
558 return VIDEO_PLAYLIST_PRIVACIES[privacy] || 'Unknown'
561 static getTypeLabel (type: VideoPlaylistType) {
562 return VIDEO_PLAYLIST_TYPES[type] || 'Unknown'
565 static resetPlaylistsOfChannel (videoChannelId: number, transaction: Transaction) {
573 return VideoPlaylistModel.update({ privacy: VideoPlaylistPrivacy.PRIVATE, videoChannelId: null }, query)
576 async setAndSaveThumbnail (thumbnail: MThumbnail, t: Transaction) {
577 thumbnail.videoPlaylistId = this.id
579 this.Thumbnail = await thumbnail.save({ transaction: t })
583 return !!this.Thumbnail
586 hasGeneratedThumbnail () {
587 return this.hasThumbnail() && this.Thumbnail.automaticallyGenerated === true
590 generateThumbnailName () {
591 const extension = '.jpg'
593 return 'playlist-' + buildUUID() + extension
597 if (!this.hasThumbnail()) return null
599 return WEBSERVER.URL + STATIC_PATHS.THUMBNAILS + this.Thumbnail.filename
602 getThumbnailStaticPath () {
603 if (!this.hasThumbnail()) return null
605 return join(STATIC_PATHS.THUMBNAILS, this.Thumbnail.filename)
608 getWatchStaticPath () {
609 return buildPlaylistWatchPath({ shortUUID: uuidToShort(this.uuid) })
612 getEmbedStaticPath () {
613 return buildPlaylistEmbedPath(this)
616 static async getStats () {
617 const totalLocalPlaylists = await VideoPlaylistModel.count({
620 model: AccountModel.unscoped(),
624 model: ActorModel.unscoped(),
634 privacy: VideoPlaylistPrivacy.PUBLIC
644 return setAsUpdated('videoPlaylist', this.id)
647 setVideosLength (videosLength: number) {
648 this.set('videosLength' as any, videosLength, { raw: true })
652 return this.OwnerAccount.isOwned()
656 if (this.isOwned()) return false
658 return isOutdated(this, ACTIVITY_PUB.VIDEO_PLAYLIST_REFRESH_INTERVAL)
661 toFormattedJSON (this: MVideoPlaylistFormattable): VideoPlaylist {
665 shortUUID: uuidToShort(this.uuid),
667 isLocal: this.isOwned(),
671 displayName: this.name,
672 description: this.description,
675 label: VideoPlaylistModel.getPrivacyLabel(this.privacy)
678 thumbnailPath: this.getThumbnailStaticPath(),
679 embedPath: this.getEmbedStaticPath(),
683 label: VideoPlaylistModel.getTypeLabel(this.type)
686 videosLength: this.get('videosLength') as number,
688 createdAt: this.createdAt,
689 updatedAt: this.updatedAt,
691 ownerAccount: this.OwnerAccount.toFormattedSummaryJSON(),
692 videoChannel: this.VideoChannel
693 ? this.VideoChannel.toFormattedSummaryJSON()
698 toActivityPubObject (this: MVideoPlaylistAP, page: number, t: Transaction): Promise<PlaylistObject> {
699 const handler = (start: number, count: number) => {
700 return VideoPlaylistElementModel.listUrlsOfForAP(this.id, start, count, t)
703 let icon: ActivityIconObject
704 if (this.hasThumbnail()) {
706 type: 'Image' as 'Image',
707 url: this.getThumbnailUrl(),
708 mediaType: 'image/jpeg' as 'image/jpeg',
709 width: THUMBNAILS_SIZE.width,
710 height: THUMBNAILS_SIZE.height
714 return activityPubCollectionPagination(this.url, handler, page)
716 return Object.assign(o, {
717 type: 'Playlist' as 'Playlist',
719 content: this.description,
720 mediaType: 'text/markdown' as 'text/markdown',
722 published: this.createdAt.toISOString(),
723 updated: this.updatedAt.toISOString(),
724 attributedTo: this.VideoChannel ? [ this.VideoChannel.Actor.url ] : [],