1 import { join } from 'path'
2 import { FindOptions, literal, Op, ScopeOptions, Sequelize, Transaction, WhereOptions } from 'sequelize'
19 } from 'sequelize-typescript'
20 import { buildUUID, uuidToShort } from '@server/helpers/uuid'
21 import { MAccountId, MChannelId } from '@server/types/models'
22 import { AttributesOnly, buildPlaylistEmbedPath, buildPlaylistWatchPath } from '@shared/core-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
89 function getVideoLengthSelect () {
90 return 'SELECT COUNT("id") FROM "videoPlaylistElement" WHERE "videoPlaylistId" = "VideoPlaylistModel"."id"'
94 [ScopeNames.WITH_THUMBNAIL]: {
97 model: ThumbnailModel,
102 [ScopeNames.WITH_VIDEOS_LENGTH]: {
106 literal(`(${getVideoLengthSelect()})`),
112 [ScopeNames.WITH_ACCOUNT]: {
120 [ScopeNames.WITH_ACCOUNT_AND_CHANNEL_SUMMARY]: {
123 model: AccountModel.scope(AccountScopeNames.SUMMARY),
127 model: VideoChannelModel.scope(VideoChannelScopeNames.SUMMARY),
132 [ScopeNames.WITH_ACCOUNT_AND_CHANNEL]: {
139 model: VideoChannelModel,
144 [ScopeNames.AVAILABLE_FOR_LIST]: (options: AvailableForListOptions) => {
145 const whereAnd: WhereOptions[] = []
147 const whereServer = options.host && options.host !== WEBSERVER.HOST
148 ? { host: options.host }
151 let whereActor: WhereOptions = {}
153 if (options.host === WEBSERVER.HOST) {
155 [Op.and]: [ { serverId: null } ]
159 if (options.listMyPlaylists !== true) {
161 privacy: VideoPlaylistPrivacy.PUBLIC
164 // Only list local playlists
165 const whereActorOr: WhereOptions[] = [
171 // … OR playlists that are on an instance followed by actorId
172 if (options.followerActorId) {
173 const inQueryInstanceFollow = buildServerIdsFollowedBy(options.followerActorId)
177 [Op.in]: literal(inQueryInstanceFollow)
182 Object.assign(whereActor, { [Op.or]: whereActorOr })
185 if (options.accountId) {
187 ownerAccountId: options.accountId
191 if (options.videoChannelId) {
193 videoChannelId: options.videoChannelId
203 if (options.withVideos === true) {
205 literal(`(${getVideoLengthSelect()}) != 0`)
209 const attributesInclude = []
211 if (options.search) {
212 const escapedSearch = VideoPlaylistModel.sequelize.escape(options.search)
213 const escapedLikeSearch = VideoPlaylistModel.sequelize.escape('%' + options.search + '%')
214 attributesInclude.push(createSimilarityAttribute('VideoPlaylistModel.name', options.search))
219 'lower(immutable_unaccent("VideoPlaylistModel"."name")) % lower(immutable_unaccent(' + escapedSearch + '))'
222 'lower(immutable_unaccent("VideoPlaylistModel"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))'
234 include: attributesInclude
239 model: AccountModel.scope({
240 method: [ AccountScopeNames.SUMMARY, { whereActor, whereServer } as SummaryOptions ]
245 model: VideoChannelModel.scope(VideoChannelScopeNames.SUMMARY),
254 tableName: 'videoPlaylist',
256 buildTrigramSearchIndex('video_playlist_name_trigram', 'name'),
259 fields: [ 'ownerAccountId' ]
262 fields: [ 'videoChannelId' ]
270 export class VideoPlaylistModel extends Model<Partial<AttributesOnly<VideoPlaylistModel>>> {
278 @Is('VideoPlaylistName', value => throwIfNotValid(value, isVideoPlaylistNameValid, 'name'))
283 @Is('VideoPlaylistDescription', value => throwIfNotValid(value, isVideoPlaylistDescriptionValid, 'description', true))
284 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_PLAYLISTS.DESCRIPTION.max))
288 @Is('VideoPlaylistPrivacy', value => throwIfNotValid(value, isVideoPlaylistPrivacyValid, 'privacy'))
290 privacy: VideoPlaylistPrivacy
293 @Is('VideoPlaylistUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
294 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_PLAYLISTS.URL.max))
298 @Default(DataType.UUIDV4)
300 @Column(DataType.UUID)
304 @Default(VideoPlaylistType.REGULAR)
306 type: VideoPlaylistType
308 @ForeignKey(() => AccountModel)
310 ownerAccountId: number
312 @BelongsTo(() => AccountModel, {
318 OwnerAccount: AccountModel
320 @ForeignKey(() => VideoChannelModel)
322 videoChannelId: number
324 @BelongsTo(() => VideoChannelModel, {
330 VideoChannel: VideoChannelModel
332 @HasMany(() => VideoPlaylistElementModel, {
334 name: 'videoPlaylistId',
339 VideoPlaylistElements: VideoPlaylistElementModel[]
341 @HasOne(() => ThumbnailModel, {
343 name: 'videoPlaylistId',
349 Thumbnail: ThumbnailModel
351 static listForApi (options: {
352 followerActorId: number
356 type?: VideoPlaylistType
358 videoChannelId?: number
359 listMyPlaylists?: boolean
362 withVideos?: boolean // false by default
365 offset: options.start,
366 limit: options.count,
367 order: getPlaylistSort(options.sort)
370 const scopes: (string | ScopeOptions)[] = [
373 ScopeNames.AVAILABLE_FOR_LIST,
376 followerActorId: options.followerActorId,
377 accountId: options.accountId,
378 videoChannelId: options.videoChannelId,
379 listMyPlaylists: options.listMyPlaylists,
380 search: options.search,
382 withVideos: options.withVideos || false
383 } as AvailableForListOptions
386 ScopeNames.WITH_VIDEOS_LENGTH,
387 ScopeNames.WITH_THUMBNAIL
390 return VideoPlaylistModel
392 .findAndCountAll(query)
393 .then(({ rows, count }) => {
394 return { total: count, data: rows }
398 static searchForApi (options: {
399 followerActorId: number
406 return VideoPlaylistModel.listForApi({
408 type: VideoPlaylistType.REGULAR,
409 listMyPlaylists: false,
414 static listPublicUrlsOfForAP (options: { account?: MAccountId, channel?: MChannelId }, start: number, count: number) {
416 privacy: VideoPlaylistPrivacy.PUBLIC
419 if (options.account) {
420 Object.assign(where, { ownerAccountId: options.account.id })
423 if (options.channel) {
424 Object.assign(where, { videoChannelId: options.channel.id })
428 attributes: [ 'url' ],
434 return VideoPlaylistModel.findAndCountAll(query)
435 .then(({ rows, count }) => {
436 return { total: count, data: rows.map(p => p.url) }
440 static listPlaylistIdsOf (accountId: number, videoIds: number[]): Promise<MVideoPlaylistIdWithElements[]> {
442 attributes: [ 'id' ],
444 ownerAccountId: accountId
448 attributes: [ 'id', 'videoId', 'startTimestamp', 'stopTimestamp' ],
449 model: VideoPlaylistElementModel.unscoped(),
460 return VideoPlaylistModel.findAll(query)
463 static doesPlaylistExist (url: string) {
465 attributes: [ 'id' ],
471 return VideoPlaylistModel
476 static loadWithAccountAndChannelSummary (id: number | string, transaction: Transaction): Promise<MVideoPlaylistFullSummary> {
477 const where = buildWhereIdOrUUID(id)
484 return VideoPlaylistModel
485 .scope([ ScopeNames.WITH_ACCOUNT_AND_CHANNEL_SUMMARY, ScopeNames.WITH_VIDEOS_LENGTH, ScopeNames.WITH_THUMBNAIL ])
489 static loadWithAccountAndChannel (id: number | string, transaction: Transaction): Promise<MVideoPlaylistFull> {
490 const where = buildWhereIdOrUUID(id)
497 return VideoPlaylistModel
498 .scope([ ScopeNames.WITH_ACCOUNT_AND_CHANNEL, ScopeNames.WITH_VIDEOS_LENGTH, ScopeNames.WITH_THUMBNAIL ])
502 static loadByUrlAndPopulateAccount (url: string): Promise<MVideoPlaylistAccountThumbnail> {
509 return VideoPlaylistModel.scope([ ScopeNames.WITH_ACCOUNT, ScopeNames.WITH_THUMBNAIL ]).findOne(query)
512 static loadByUrlWithAccountAndChannelSummary (url: string): Promise<MVideoPlaylistFullSummary> {
519 return VideoPlaylistModel
520 .scope([ ScopeNames.WITH_ACCOUNT_AND_CHANNEL_SUMMARY, ScopeNames.WITH_VIDEOS_LENGTH, ScopeNames.WITH_THUMBNAIL ])
524 static getPrivacyLabel (privacy: VideoPlaylistPrivacy) {
525 return VIDEO_PLAYLIST_PRIVACIES[privacy] || 'Unknown'
528 static getTypeLabel (type: VideoPlaylistType) {
529 return VIDEO_PLAYLIST_TYPES[type] || 'Unknown'
532 static resetPlaylistsOfChannel (videoChannelId: number, transaction: Transaction) {
540 return VideoPlaylistModel.update({ privacy: VideoPlaylistPrivacy.PRIVATE, videoChannelId: null }, query)
543 async setAndSaveThumbnail (thumbnail: MThumbnail, t: Transaction) {
544 thumbnail.videoPlaylistId = this.id
546 this.Thumbnail = await thumbnail.save({ transaction: t })
550 return !!this.Thumbnail
553 hasGeneratedThumbnail () {
554 return this.hasThumbnail() && this.Thumbnail.automaticallyGenerated === true
557 generateThumbnailName () {
558 const extension = '.jpg'
560 return 'playlist-' + buildUUID() + extension
564 if (!this.hasThumbnail()) return null
566 return WEBSERVER.URL + STATIC_PATHS.THUMBNAILS + this.Thumbnail.filename
569 getThumbnailStaticPath () {
570 if (!this.hasThumbnail()) return null
572 return join(STATIC_PATHS.THUMBNAILS, this.Thumbnail.filename)
575 getWatchStaticPath () {
576 return buildPlaylistWatchPath({ shortUUID: uuidToShort(this.uuid) })
579 getEmbedStaticPath () {
580 return buildPlaylistEmbedPath(this)
583 static async getStats () {
584 const totalLocalPlaylists = await VideoPlaylistModel.count({
601 privacy: VideoPlaylistPrivacy.PUBLIC
611 return setAsUpdated('videoPlaylist', this.id)
614 setVideosLength (videosLength: number) {
615 this.set('videosLength' as any, videosLength, { raw: true })
619 return this.OwnerAccount.isOwned()
623 if (this.isOwned()) return false
625 return isOutdated(this, ACTIVITY_PUB.VIDEO_PLAYLIST_REFRESH_INTERVAL)
628 toFormattedJSON (this: MVideoPlaylistFormattable): VideoPlaylist {
632 shortUUID: uuidToShort(this.uuid),
634 isLocal: this.isOwned(),
638 displayName: this.name,
639 description: this.description,
642 label: VideoPlaylistModel.getPrivacyLabel(this.privacy)
645 thumbnailPath: this.getThumbnailStaticPath(),
646 embedPath: this.getEmbedStaticPath(),
650 label: VideoPlaylistModel.getTypeLabel(this.type)
653 videosLength: this.get('videosLength') as number,
655 createdAt: this.createdAt,
656 updatedAt: this.updatedAt,
658 ownerAccount: this.OwnerAccount.toFormattedSummaryJSON(),
659 videoChannel: this.VideoChannel
660 ? this.VideoChannel.toFormattedSummaryJSON()
665 toActivityPubObject (this: MVideoPlaylistAP, page: number, t: Transaction): Promise<PlaylistObject> {
666 const handler = (start: number, count: number) => {
667 return VideoPlaylistElementModel.listUrlsOfForAP(this.id, start, count, t)
670 let icon: ActivityIconObject
671 if (this.hasThumbnail()) {
673 type: 'Image' as 'Image',
674 url: this.getThumbnailUrl(),
675 mediaType: 'image/jpeg' as 'image/jpeg',
676 width: THUMBNAILS_SIZE.width,
677 height: THUMBNAILS_SIZE.height
681 return activityPubCollectionPagination(this.url, handler, page)
683 return Object.assign(o, {
684 type: 'Playlist' as 'Playlist',
686 content: this.description,
688 published: this.createdAt.toISOString(),
689 updated: this.updatedAt.toISOString(),
690 attributedTo: this.VideoChannel ? [ this.VideoChannel.Actor.url ] : [],