1 import { join } from 'path'
2 import { FindOptions, literal, Op, ScopeOptions, Sequelize, Transaction, WhereOptions } from 'sequelize'
19 } from 'sequelize-typescript'
20 import { MAccountId, MChannelId } from '@server/types/models'
21 import { buildPlaylistEmbedPath, buildPlaylistWatchPath, buildUUID, pick, uuidToShort } from '@shared/core-utils'
22 import { AttributesOnly } from '@shared/typescript-utils'
23 import { ActivityIconObject } from '../../../shared/models/activitypub/objects'
24 import { PlaylistObject } from '../../../shared/models/activitypub/objects/playlist-object'
25 import { VideoPlaylistPrivacy } from '../../../shared/models/videos/playlist/video-playlist-privacy.model'
26 import { VideoPlaylistType } from '../../../shared/models/videos/playlist/video-playlist-type.model'
27 import { VideoPlaylist } from '../../../shared/models/videos/playlist/video-playlist.model'
28 import { activityPubCollectionPagination } from '../../helpers/activitypub'
29 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
31 isVideoPlaylistDescriptionValid,
32 isVideoPlaylistNameValid,
33 isVideoPlaylistPrivacyValid
34 } from '../../helpers/custom-validators/video-playlists'
40 VIDEO_PLAYLIST_PRIVACIES,
43 } from '../../initializers/constants'
44 import { MThumbnail } from '../../types/models/video/thumbnail'
46 MVideoPlaylistAccountThumbnail,
48 MVideoPlaylistFormattable,
50 MVideoPlaylistFullSummary,
51 MVideoPlaylistIdWithElements
52 } from '../../types/models/video/video-playlist'
53 import { AccountModel, ScopeNames as AccountScopeNames, SummaryOptions } from '../account/account'
54 import { ActorModel } from '../actor/actor'
55 import { setAsUpdated } from '../shared'
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
90 function getVideoLengthSelect () {
91 return 'SELECT COUNT("id") FROM "videoPlaylistElement" WHERE "videoPlaylistId" = "VideoPlaylistModel"."id"'
95 [ScopeNames.WITH_THUMBNAIL]: {
98 model: ThumbnailModel,
103 [ScopeNames.WITH_VIDEOS_LENGTH]: {
107 literal(`(${getVideoLengthSelect()})`),
113 [ScopeNames.WITH_ACCOUNT]: {
121 [ScopeNames.WITH_ACCOUNT_AND_CHANNEL_SUMMARY]: {
124 model: AccountModel.scope(AccountScopeNames.SUMMARY),
128 model: VideoChannelModel.scope(VideoChannelScopeNames.SUMMARY),
133 [ScopeNames.WITH_ACCOUNT_AND_CHANNEL]: {
140 model: VideoChannelModel,
145 [ScopeNames.AVAILABLE_FOR_LIST]: (options: AvailableForListOptions) => {
146 const whereAnd: WhereOptions[] = []
148 const whereServer = options.host && options.host !== WEBSERVER.HOST
149 ? { host: options.host }
152 let whereActor: WhereOptions = {}
154 if (options.host === WEBSERVER.HOST) {
156 [Op.and]: [ { serverId: null } ]
160 if (options.listMyPlaylists !== true) {
162 privacy: VideoPlaylistPrivacy.PUBLIC
165 // Only list local playlists
166 const whereActorOr: WhereOptions[] = [
172 // … OR playlists that are on an instance followed by actorId
173 if (options.followerActorId) {
174 const inQueryInstanceFollow = buildServerIdsFollowedBy(options.followerActorId)
178 [Op.in]: literal(inQueryInstanceFollow)
183 Object.assign(whereActor, { [Op.or]: whereActorOr })
186 if (options.accountId) {
188 ownerAccountId: options.accountId
192 if (options.videoChannelId) {
194 videoChannelId: options.videoChannelId
207 [Op.in]: options.uuids
212 if (options.withVideos === true) {
214 literal(`(${getVideoLengthSelect()}) != 0`)
218 let attributesInclude: any[] = [ literal('0 as similarity') ]
220 if (options.search) {
221 const escapedSearch = VideoPlaylistModel.sequelize.escape(options.search)
222 const escapedLikeSearch = VideoPlaylistModel.sequelize.escape('%' + options.search + '%')
223 attributesInclude = [ createSimilarityAttribute('VideoPlaylistModel.name', options.search) ]
228 'lower(immutable_unaccent("VideoPlaylistModel"."name")) % lower(immutable_unaccent(' + escapedSearch + '))'
231 'lower(immutable_unaccent("VideoPlaylistModel"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))'
243 include: attributesInclude
248 model: AccountModel.scope({
249 method: [ AccountScopeNames.SUMMARY, { whereActor, whereServer } as SummaryOptions ]
254 model: VideoChannelModel.scope(VideoChannelScopeNames.SUMMARY),
263 tableName: 'videoPlaylist',
265 buildTrigramSearchIndex('video_playlist_name_trigram', 'name'),
268 fields: [ 'ownerAccountId' ]
271 fields: [ 'videoChannelId' ]
279 export class VideoPlaylistModel extends Model<Partial<AttributesOnly<VideoPlaylistModel>>> {
287 @Is('VideoPlaylistName', value => throwIfNotValid(value, isVideoPlaylistNameValid, 'name'))
292 @Is('VideoPlaylistDescription', value => throwIfNotValid(value, isVideoPlaylistDescriptionValid, 'description', true))
293 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_PLAYLISTS.DESCRIPTION.max))
297 @Is('VideoPlaylistPrivacy', value => throwIfNotValid(value, isVideoPlaylistPrivacyValid, 'privacy'))
299 privacy: VideoPlaylistPrivacy
302 @Is('VideoPlaylistUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
303 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_PLAYLISTS.URL.max))
307 @Default(DataType.UUIDV4)
309 @Column(DataType.UUID)
313 @Default(VideoPlaylistType.REGULAR)
315 type: VideoPlaylistType
317 @ForeignKey(() => AccountModel)
319 ownerAccountId: number
321 @BelongsTo(() => AccountModel, {
327 OwnerAccount: AccountModel
329 @ForeignKey(() => VideoChannelModel)
331 videoChannelId: number
333 @BelongsTo(() => VideoChannelModel, {
339 VideoChannel: VideoChannelModel
341 @HasMany(() => VideoPlaylistElementModel, {
343 name: 'videoPlaylistId',
348 VideoPlaylistElements: VideoPlaylistElementModel[]
350 @HasOne(() => ThumbnailModel, {
352 name: 'videoPlaylistId',
358 Thumbnail: ThumbnailModel
360 static listForApi (options: AvailableForListOptions & {
366 offset: options.start,
367 limit: options.count,
368 order: getPlaylistSort(options.sort)
371 const scopes: (string | ScopeOptions)[] = [
374 ScopeNames.AVAILABLE_FOR_LIST,
376 ...pick(options, [ 'type', 'followerActorId', 'accountId', 'videoChannelId', 'listMyPlaylists', 'search', 'host', 'uuids' ]),
378 withVideos: options.withVideos || false
379 } as AvailableForListOptions
382 ScopeNames.WITH_VIDEOS_LENGTH,
383 ScopeNames.WITH_THUMBNAIL
386 return VideoPlaylistModel
388 .findAndCountAll(query)
389 .then(({ rows, count }) => {
390 return { total: count, data: rows }
394 static searchForApi (options: Pick<AvailableForListOptions, 'followerActorId' | 'search'| 'host'| 'uuids'> & {
399 return VideoPlaylistModel.listForApi({
402 type: VideoPlaylistType.REGULAR,
403 listMyPlaylists: false,
408 static listPublicUrlsOfForAP (options: { account?: MAccountId, channel?: MChannelId }, start: number, count: number) {
410 privacy: VideoPlaylistPrivacy.PUBLIC
413 if (options.account) {
414 Object.assign(where, { ownerAccountId: options.account.id })
417 if (options.channel) {
418 Object.assign(where, { videoChannelId: options.channel.id })
422 attributes: [ 'url' ],
428 return VideoPlaylistModel.findAndCountAll(query)
429 .then(({ rows, count }) => {
430 return { total: count, data: rows.map(p => p.url) }
434 static listPlaylistIdsOf (accountId: number, videoIds: number[]): Promise<MVideoPlaylistIdWithElements[]> {
436 attributes: [ 'id' ],
438 ownerAccountId: accountId
442 attributes: [ 'id', 'videoId', 'startTimestamp', 'stopTimestamp' ],
443 model: VideoPlaylistElementModel.unscoped(),
454 return VideoPlaylistModel.findAll(query)
457 static doesPlaylistExist (url: string) {
459 attributes: [ 'id' ],
465 return VideoPlaylistModel
470 static loadWithAccountAndChannelSummary (id: number | string, transaction: Transaction): Promise<MVideoPlaylistFullSummary> {
471 const where = buildWhereIdOrUUID(id)
478 return VideoPlaylistModel
479 .scope([ ScopeNames.WITH_ACCOUNT_AND_CHANNEL_SUMMARY, ScopeNames.WITH_VIDEOS_LENGTH, ScopeNames.WITH_THUMBNAIL ])
483 static loadWithAccountAndChannel (id: number | string, transaction: Transaction): Promise<MVideoPlaylistFull> {
484 const where = buildWhereIdOrUUID(id)
491 return VideoPlaylistModel
492 .scope([ ScopeNames.WITH_ACCOUNT_AND_CHANNEL, ScopeNames.WITH_VIDEOS_LENGTH, ScopeNames.WITH_THUMBNAIL ])
496 static loadByUrlAndPopulateAccount (url: string): Promise<MVideoPlaylistAccountThumbnail> {
503 return VideoPlaylistModel.scope([ ScopeNames.WITH_ACCOUNT, ScopeNames.WITH_THUMBNAIL ]).findOne(query)
506 static loadByUrlWithAccountAndChannelSummary (url: string): Promise<MVideoPlaylistFullSummary> {
513 return VideoPlaylistModel
514 .scope([ ScopeNames.WITH_ACCOUNT_AND_CHANNEL_SUMMARY, ScopeNames.WITH_VIDEOS_LENGTH, ScopeNames.WITH_THUMBNAIL ])
518 static getPrivacyLabel (privacy: VideoPlaylistPrivacy) {
519 return VIDEO_PLAYLIST_PRIVACIES[privacy] || 'Unknown'
522 static getTypeLabel (type: VideoPlaylistType) {
523 return VIDEO_PLAYLIST_TYPES[type] || 'Unknown'
526 static resetPlaylistsOfChannel (videoChannelId: number, transaction: Transaction) {
534 return VideoPlaylistModel.update({ privacy: VideoPlaylistPrivacy.PRIVATE, videoChannelId: null }, query)
537 async setAndSaveThumbnail (thumbnail: MThumbnail, t: Transaction) {
538 thumbnail.videoPlaylistId = this.id
540 this.Thumbnail = await thumbnail.save({ transaction: t })
544 return !!this.Thumbnail
547 hasGeneratedThumbnail () {
548 return this.hasThumbnail() && this.Thumbnail.automaticallyGenerated === true
551 generateThumbnailName () {
552 const extension = '.jpg'
554 return 'playlist-' + buildUUID() + extension
558 if (!this.hasThumbnail()) return null
560 return WEBSERVER.URL + STATIC_PATHS.THUMBNAILS + this.Thumbnail.filename
563 getThumbnailStaticPath () {
564 if (!this.hasThumbnail()) return null
566 return join(STATIC_PATHS.THUMBNAILS, this.Thumbnail.filename)
569 getWatchStaticPath () {
570 return buildPlaylistWatchPath({ shortUUID: uuidToShort(this.uuid) })
573 getEmbedStaticPath () {
574 return buildPlaylistEmbedPath(this)
577 static async getStats () {
578 const totalLocalPlaylists = await VideoPlaylistModel.count({
595 privacy: VideoPlaylistPrivacy.PUBLIC
605 return setAsUpdated('videoPlaylist', this.id)
608 setVideosLength (videosLength: number) {
609 this.set('videosLength' as any, videosLength, { raw: true })
613 return this.OwnerAccount.isOwned()
617 if (this.isOwned()) return false
619 return isOutdated(this, ACTIVITY_PUB.VIDEO_PLAYLIST_REFRESH_INTERVAL)
622 toFormattedJSON (this: MVideoPlaylistFormattable): VideoPlaylist {
626 shortUUID: uuidToShort(this.uuid),
628 isLocal: this.isOwned(),
632 displayName: this.name,
633 description: this.description,
636 label: VideoPlaylistModel.getPrivacyLabel(this.privacy)
639 thumbnailPath: this.getThumbnailStaticPath(),
640 embedPath: this.getEmbedStaticPath(),
644 label: VideoPlaylistModel.getTypeLabel(this.type)
647 videosLength: this.get('videosLength') as number,
649 createdAt: this.createdAt,
650 updatedAt: this.updatedAt,
652 ownerAccount: this.OwnerAccount.toFormattedSummaryJSON(),
653 videoChannel: this.VideoChannel
654 ? this.VideoChannel.toFormattedSummaryJSON()
659 toActivityPubObject (this: MVideoPlaylistAP, page: number, t: Transaction): Promise<PlaylistObject> {
660 const handler = (start: number, count: number) => {
661 return VideoPlaylistElementModel.listUrlsOfForAP(this.id, start, count, t)
664 let icon: ActivityIconObject
665 if (this.hasThumbnail()) {
667 type: 'Image' as 'Image',
668 url: this.getThumbnailUrl(),
669 mediaType: 'image/jpeg' as 'image/jpeg',
670 width: THUMBNAILS_SIZE.width,
671 height: THUMBNAILS_SIZE.height
675 return activityPubCollectionPagination(this.url, handler, page)
677 return Object.assign(o, {
678 type: 'Playlist' as 'Playlist',
680 content: this.description,
682 published: this.createdAt.toISOString(),
683 updated: this.updatedAt.toISOString(),
684 attributedTo: this.VideoChannel ? [ this.VideoChannel.Actor.url ] : [],