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
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: {
361 followerActorId: number
365 type?: VideoPlaylistType
367 videoChannelId?: number
368 listMyPlaylists?: boolean
372 withVideos?: boolean // false by default
375 offset: options.start,
376 limit: options.count,
377 order: getPlaylistSort(options.sort)
380 const scopes: (string | ScopeOptions)[] = [
383 ScopeNames.AVAILABLE_FOR_LIST,
386 followerActorId: options.followerActorId,
387 accountId: options.accountId,
388 videoChannelId: options.videoChannelId,
389 listMyPlaylists: options.listMyPlaylists,
390 search: options.search,
392 uuids: options.uuids,
393 withVideos: options.withVideos || false
394 } as AvailableForListOptions
397 ScopeNames.WITH_VIDEOS_LENGTH,
398 ScopeNames.WITH_THUMBNAIL
401 return VideoPlaylistModel
403 .findAndCountAll(query)
404 .then(({ rows, count }) => {
405 return { total: count, data: rows }
409 static searchForApi (options: {
410 followerActorId: number
418 return VideoPlaylistModel.listForApi({
420 type: VideoPlaylistType.REGULAR,
421 listMyPlaylists: false,
426 static listPublicUrlsOfForAP (options: { account?: MAccountId, channel?: MChannelId }, start: number, count: number) {
428 privacy: VideoPlaylistPrivacy.PUBLIC
431 if (options.account) {
432 Object.assign(where, { ownerAccountId: options.account.id })
435 if (options.channel) {
436 Object.assign(where, { videoChannelId: options.channel.id })
440 attributes: [ 'url' ],
446 return VideoPlaylistModel.findAndCountAll(query)
447 .then(({ rows, count }) => {
448 return { total: count, data: rows.map(p => p.url) }
452 static listPlaylistIdsOf (accountId: number, videoIds: number[]): Promise<MVideoPlaylistIdWithElements[]> {
454 attributes: [ 'id' ],
456 ownerAccountId: accountId
460 attributes: [ 'id', 'videoId', 'startTimestamp', 'stopTimestamp' ],
461 model: VideoPlaylistElementModel.unscoped(),
472 return VideoPlaylistModel.findAll(query)
475 static doesPlaylistExist (url: string) {
477 attributes: [ 'id' ],
483 return VideoPlaylistModel
488 static loadWithAccountAndChannelSummary (id: number | string, transaction: Transaction): Promise<MVideoPlaylistFullSummary> {
489 const where = buildWhereIdOrUUID(id)
496 return VideoPlaylistModel
497 .scope([ ScopeNames.WITH_ACCOUNT_AND_CHANNEL_SUMMARY, ScopeNames.WITH_VIDEOS_LENGTH, ScopeNames.WITH_THUMBNAIL ])
501 static loadWithAccountAndChannel (id: number | string, transaction: Transaction): Promise<MVideoPlaylistFull> {
502 const where = buildWhereIdOrUUID(id)
509 return VideoPlaylistModel
510 .scope([ ScopeNames.WITH_ACCOUNT_AND_CHANNEL, ScopeNames.WITH_VIDEOS_LENGTH, ScopeNames.WITH_THUMBNAIL ])
514 static loadByUrlAndPopulateAccount (url: string): Promise<MVideoPlaylistAccountThumbnail> {
521 return VideoPlaylistModel.scope([ ScopeNames.WITH_ACCOUNT, ScopeNames.WITH_THUMBNAIL ]).findOne(query)
524 static loadByUrlWithAccountAndChannelSummary (url: string): Promise<MVideoPlaylistFullSummary> {
531 return VideoPlaylistModel
532 .scope([ ScopeNames.WITH_ACCOUNT_AND_CHANNEL_SUMMARY, ScopeNames.WITH_VIDEOS_LENGTH, ScopeNames.WITH_THUMBNAIL ])
536 static getPrivacyLabel (privacy: VideoPlaylistPrivacy) {
537 return VIDEO_PLAYLIST_PRIVACIES[privacy] || 'Unknown'
540 static getTypeLabel (type: VideoPlaylistType) {
541 return VIDEO_PLAYLIST_TYPES[type] || 'Unknown'
544 static resetPlaylistsOfChannel (videoChannelId: number, transaction: Transaction) {
552 return VideoPlaylistModel.update({ privacy: VideoPlaylistPrivacy.PRIVATE, videoChannelId: null }, query)
555 async setAndSaveThumbnail (thumbnail: MThumbnail, t: Transaction) {
556 thumbnail.videoPlaylistId = this.id
558 this.Thumbnail = await thumbnail.save({ transaction: t })
562 return !!this.Thumbnail
565 hasGeneratedThumbnail () {
566 return this.hasThumbnail() && this.Thumbnail.automaticallyGenerated === true
569 generateThumbnailName () {
570 const extension = '.jpg'
572 return 'playlist-' + buildUUID() + extension
576 if (!this.hasThumbnail()) return null
578 return WEBSERVER.URL + STATIC_PATHS.THUMBNAILS + this.Thumbnail.filename
581 getThumbnailStaticPath () {
582 if (!this.hasThumbnail()) return null
584 return join(STATIC_PATHS.THUMBNAILS, this.Thumbnail.filename)
587 getWatchStaticPath () {
588 return buildPlaylistWatchPath({ shortUUID: uuidToShort(this.uuid) })
591 getEmbedStaticPath () {
592 return buildPlaylistEmbedPath(this)
595 static async getStats () {
596 const totalLocalPlaylists = await VideoPlaylistModel.count({
613 privacy: VideoPlaylistPrivacy.PUBLIC
623 return setAsUpdated('videoPlaylist', this.id)
626 setVideosLength (videosLength: number) {
627 this.set('videosLength' as any, videosLength, { raw: true })
631 return this.OwnerAccount.isOwned()
635 if (this.isOwned()) return false
637 return isOutdated(this, ACTIVITY_PUB.VIDEO_PLAYLIST_REFRESH_INTERVAL)
640 toFormattedJSON (this: MVideoPlaylistFormattable): VideoPlaylist {
644 shortUUID: uuidToShort(this.uuid),
646 isLocal: this.isOwned(),
650 displayName: this.name,
651 description: this.description,
654 label: VideoPlaylistModel.getPrivacyLabel(this.privacy)
657 thumbnailPath: this.getThumbnailStaticPath(),
658 embedPath: this.getEmbedStaticPath(),
662 label: VideoPlaylistModel.getTypeLabel(this.type)
665 videosLength: this.get('videosLength') as number,
667 createdAt: this.createdAt,
668 updatedAt: this.updatedAt,
670 ownerAccount: this.OwnerAccount.toFormattedSummaryJSON(),
671 videoChannel: this.VideoChannel
672 ? this.VideoChannel.toFormattedSummaryJSON()
677 toActivityPubObject (this: MVideoPlaylistAP, page: number, t: Transaction): Promise<PlaylistObject> {
678 const handler = (start: number, count: number) => {
679 return VideoPlaylistElementModel.listUrlsOfForAP(this.id, start, count, t)
682 let icon: ActivityIconObject
683 if (this.hasThumbnail()) {
685 type: 'Image' as 'Image',
686 url: this.getThumbnailUrl(),
687 mediaType: 'image/jpeg' as 'image/jpeg',
688 width: THUMBNAILS_SIZE.width,
689 height: THUMBNAILS_SIZE.height
693 return activityPubCollectionPagination(this.url, handler, page)
695 return Object.assign(o, {
696 type: 'Playlist' as 'Playlist',
698 content: this.description,
700 published: this.createdAt.toISOString(),
701 updated: this.updatedAt.toISOString(),
702 attributedTo: this.VideoChannel ? [ this.VideoChannel.Actor.url ] : [],