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, pick } from '@shared/core-utils'
22 import { buildUUID, uuidToShort } from '@shared/extra-utils'
23 import { AttributesOnly } from '@shared/typescript-utils'
24 import { ActivityIconObject } from '../../../shared/models/activitypub/objects'
25 import { PlaylistObject } from '../../../shared/models/activitypub/objects/playlist-object'
26 import { VideoPlaylistPrivacy } from '../../../shared/models/videos/playlist/video-playlist-privacy.model'
27 import { VideoPlaylistType } from '../../../shared/models/videos/playlist/video-playlist-type.model'
28 import { VideoPlaylist } from '../../../shared/models/videos/playlist/video-playlist.model'
29 import { activityPubCollectionPagination } from '../../helpers/activitypub'
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
91 function getVideoLengthSelect () {
92 return 'SELECT COUNT("id") FROM "videoPlaylistElement" WHERE "videoPlaylistId" = "VideoPlaylistModel"."id"'
96 [ScopeNames.WITH_THUMBNAIL]: {
99 model: ThumbnailModel,
104 [ScopeNames.WITH_VIDEOS_LENGTH]: {
108 literal(`(${getVideoLengthSelect()})`),
114 [ScopeNames.WITH_ACCOUNT]: {
122 [ScopeNames.WITH_ACCOUNT_AND_CHANNEL_SUMMARY]: {
125 model: AccountModel.scope(AccountScopeNames.SUMMARY),
129 model: VideoChannelModel.scope(VideoChannelScopeNames.SUMMARY),
134 [ScopeNames.WITH_ACCOUNT_AND_CHANNEL]: {
141 model: VideoChannelModel,
146 [ScopeNames.AVAILABLE_FOR_LIST]: (options: AvailableForListOptions) => {
147 const whereAnd: WhereOptions[] = []
149 const whereServer = options.host && options.host !== WEBSERVER.HOST
150 ? { host: options.host }
153 let whereActor: WhereOptions = {}
155 if (options.host === WEBSERVER.HOST) {
157 [Op.and]: [ { serverId: null } ]
161 if (options.listMyPlaylists !== true) {
163 privacy: VideoPlaylistPrivacy.PUBLIC
166 // Only list local playlists
167 const whereActorOr: WhereOptions[] = [
173 // … OR playlists that are on an instance followed by actorId
174 if (options.followerActorId) {
175 const inQueryInstanceFollow = buildServerIdsFollowedBy(options.followerActorId)
179 [Op.in]: literal(inQueryInstanceFollow)
184 Object.assign(whereActor, { [Op.or]: whereActorOr })
187 if (options.accountId) {
189 ownerAccountId: options.accountId
193 if (options.videoChannelId) {
195 videoChannelId: options.videoChannelId
208 [Op.in]: options.uuids
213 if (options.withVideos === true) {
215 literal(`(${getVideoLengthSelect()}) != 0`)
219 let attributesInclude: any[] = [ literal('0 as similarity') ]
221 if (options.search) {
222 const escapedSearch = VideoPlaylistModel.sequelize.escape(options.search)
223 const escapedLikeSearch = VideoPlaylistModel.sequelize.escape('%' + options.search + '%')
224 attributesInclude = [ createSimilarityAttribute('VideoPlaylistModel.name', options.search) ]
229 'lower(immutable_unaccent("VideoPlaylistModel"."name")) % lower(immutable_unaccent(' + escapedSearch + '))'
232 'lower(immutable_unaccent("VideoPlaylistModel"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))'
244 include: attributesInclude
249 model: AccountModel.scope({
250 method: [ AccountScopeNames.SUMMARY, { whereActor, whereServer } as SummaryOptions ]
255 model: VideoChannelModel.scope(VideoChannelScopeNames.SUMMARY),
264 tableName: 'videoPlaylist',
266 buildTrigramSearchIndex('video_playlist_name_trigram', 'name'),
269 fields: [ 'ownerAccountId' ]
272 fields: [ 'videoChannelId' ]
280 export class VideoPlaylistModel extends Model<Partial<AttributesOnly<VideoPlaylistModel>>> {
288 @Is('VideoPlaylistName', value => throwIfNotValid(value, isVideoPlaylistNameValid, 'name'))
293 @Is('VideoPlaylistDescription', value => throwIfNotValid(value, isVideoPlaylistDescriptionValid, 'description', true))
294 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_PLAYLISTS.DESCRIPTION.max))
298 @Is('VideoPlaylistPrivacy', value => throwIfNotValid(value, isVideoPlaylistPrivacyValid, 'privacy'))
300 privacy: VideoPlaylistPrivacy
303 @Is('VideoPlaylistUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
304 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_PLAYLISTS.URL.max))
308 @Default(DataType.UUIDV4)
310 @Column(DataType.UUID)
314 @Default(VideoPlaylistType.REGULAR)
316 type: VideoPlaylistType
318 @ForeignKey(() => AccountModel)
320 ownerAccountId: number
322 @BelongsTo(() => AccountModel, {
328 OwnerAccount: AccountModel
330 @ForeignKey(() => VideoChannelModel)
332 videoChannelId: number
334 @BelongsTo(() => VideoChannelModel, {
340 VideoChannel: VideoChannelModel
342 @HasMany(() => VideoPlaylistElementModel, {
344 name: 'videoPlaylistId',
349 VideoPlaylistElements: VideoPlaylistElementModel[]
351 @HasOne(() => ThumbnailModel, {
353 name: 'videoPlaylistId',
359 Thumbnail: ThumbnailModel
361 static listForApi (options: AvailableForListOptions & {
367 offset: options.start,
368 limit: options.count,
369 order: getPlaylistSort(options.sort)
372 const scopes: (string | ScopeOptions)[] = [
375 ScopeNames.AVAILABLE_FOR_LIST,
377 ...pick(options, [ 'type', 'followerActorId', 'accountId', 'videoChannelId', 'listMyPlaylists', 'search', 'host', 'uuids' ]),
379 withVideos: options.withVideos || false
380 } as AvailableForListOptions
383 ScopeNames.WITH_VIDEOS_LENGTH,
384 ScopeNames.WITH_THUMBNAIL
387 return VideoPlaylistModel
389 .findAndCountAll(query)
390 .then(({ rows, count }) => {
391 return { total: count, data: rows }
395 static searchForApi (options: Pick<AvailableForListOptions, 'followerActorId' | 'search'| 'host'| 'uuids'> & {
400 return VideoPlaylistModel.listForApi({
403 type: VideoPlaylistType.REGULAR,
404 listMyPlaylists: false,
409 static listPublicUrlsOfForAP (options: { account?: MAccountId, channel?: MChannelId }, start: number, count: number) {
411 privacy: VideoPlaylistPrivacy.PUBLIC
414 if (options.account) {
415 Object.assign(where, { ownerAccountId: options.account.id })
418 if (options.channel) {
419 Object.assign(where, { videoChannelId: options.channel.id })
423 attributes: [ 'url' ],
429 return VideoPlaylistModel.findAndCountAll(query)
430 .then(({ rows, count }) => {
431 return { total: count, data: rows.map(p => p.url) }
435 static listPlaylistIdsOf (accountId: number, videoIds: number[]): Promise<MVideoPlaylistIdWithElements[]> {
437 attributes: [ 'id' ],
439 ownerAccountId: accountId
443 attributes: [ 'id', 'videoId', 'startTimestamp', 'stopTimestamp' ],
444 model: VideoPlaylistElementModel.unscoped(),
455 return VideoPlaylistModel.findAll(query)
458 static doesPlaylistExist (url: string) {
460 attributes: [ 'id' ],
466 return VideoPlaylistModel
471 static loadWithAccountAndChannelSummary (id: number | string, transaction: Transaction): Promise<MVideoPlaylistFullSummary> {
472 const where = buildWhereIdOrUUID(id)
479 return VideoPlaylistModel
480 .scope([ ScopeNames.WITH_ACCOUNT_AND_CHANNEL_SUMMARY, ScopeNames.WITH_VIDEOS_LENGTH, ScopeNames.WITH_THUMBNAIL ])
484 static loadWithAccountAndChannel (id: number | string, transaction: Transaction): Promise<MVideoPlaylistFull> {
485 const where = buildWhereIdOrUUID(id)
492 return VideoPlaylistModel
493 .scope([ ScopeNames.WITH_ACCOUNT_AND_CHANNEL, ScopeNames.WITH_VIDEOS_LENGTH, ScopeNames.WITH_THUMBNAIL ])
497 static loadByUrlAndPopulateAccount (url: string): Promise<MVideoPlaylistAccountThumbnail> {
504 return VideoPlaylistModel.scope([ ScopeNames.WITH_ACCOUNT, ScopeNames.WITH_THUMBNAIL ]).findOne(query)
507 static loadByUrlWithAccountAndChannelSummary (url: string): Promise<MVideoPlaylistFullSummary> {
514 return VideoPlaylistModel
515 .scope([ ScopeNames.WITH_ACCOUNT_AND_CHANNEL_SUMMARY, ScopeNames.WITH_VIDEOS_LENGTH, ScopeNames.WITH_THUMBNAIL ])
519 static getPrivacyLabel (privacy: VideoPlaylistPrivacy) {
520 return VIDEO_PLAYLIST_PRIVACIES[privacy] || 'Unknown'
523 static getTypeLabel (type: VideoPlaylistType) {
524 return VIDEO_PLAYLIST_TYPES[type] || 'Unknown'
527 static resetPlaylistsOfChannel (videoChannelId: number, transaction: Transaction) {
535 return VideoPlaylistModel.update({ privacy: VideoPlaylistPrivacy.PRIVATE, videoChannelId: null }, query)
538 async setAndSaveThumbnail (thumbnail: MThumbnail, t: Transaction) {
539 thumbnail.videoPlaylistId = this.id
541 this.Thumbnail = await thumbnail.save({ transaction: t })
545 return !!this.Thumbnail
548 hasGeneratedThumbnail () {
549 return this.hasThumbnail() && this.Thumbnail.automaticallyGenerated === true
552 generateThumbnailName () {
553 const extension = '.jpg'
555 return 'playlist-' + buildUUID() + extension
559 if (!this.hasThumbnail()) return null
561 return WEBSERVER.URL + STATIC_PATHS.THUMBNAILS + this.Thumbnail.filename
564 getThumbnailStaticPath () {
565 if (!this.hasThumbnail()) return null
567 return join(STATIC_PATHS.THUMBNAILS, this.Thumbnail.filename)
570 getWatchStaticPath () {
571 return buildPlaylistWatchPath({ shortUUID: uuidToShort(this.uuid) })
574 getEmbedStaticPath () {
575 return buildPlaylistEmbedPath(this)
578 static async getStats () {
579 const totalLocalPlaylists = await VideoPlaylistModel.count({
596 privacy: VideoPlaylistPrivacy.PUBLIC
606 return setAsUpdated('videoPlaylist', this.id)
609 setVideosLength (videosLength: number) {
610 this.set('videosLength' as any, videosLength, { raw: true })
614 return this.OwnerAccount.isOwned()
618 if (this.isOwned()) return false
620 return isOutdated(this, ACTIVITY_PUB.VIDEO_PLAYLIST_REFRESH_INTERVAL)
623 toFormattedJSON (this: MVideoPlaylistFormattable): VideoPlaylist {
627 shortUUID: uuidToShort(this.uuid),
629 isLocal: this.isOwned(),
633 displayName: this.name,
634 description: this.description,
637 label: VideoPlaylistModel.getPrivacyLabel(this.privacy)
640 thumbnailPath: this.getThumbnailStaticPath(),
641 embedPath: this.getEmbedStaticPath(),
645 label: VideoPlaylistModel.getTypeLabel(this.type)
648 videosLength: this.get('videosLength') as number,
650 createdAt: this.createdAt,
651 updatedAt: this.updatedAt,
653 ownerAccount: this.OwnerAccount.toFormattedSummaryJSON(),
654 videoChannel: this.VideoChannel
655 ? this.VideoChannel.toFormattedSummaryJSON()
660 toActivityPubObject (this: MVideoPlaylistAP, page: number, t: Transaction): Promise<PlaylistObject> {
661 const handler = (start: number, count: number) => {
662 return VideoPlaylistElementModel.listUrlsOfForAP(this.id, start, count, t)
665 let icon: ActivityIconObject
666 if (this.hasThumbnail()) {
668 type: 'Image' as 'Image',
669 url: this.getThumbnailUrl(),
670 mediaType: 'image/jpeg' as 'image/jpeg',
671 width: THUMBNAILS_SIZE.width,
672 height: THUMBNAILS_SIZE.height
676 return activityPubCollectionPagination(this.url, handler, page)
678 return Object.assign(o, {
679 type: 'Playlist' as 'Playlist',
681 content: this.description,
682 mediaType: 'text/markdown' as 'text/markdown',
684 published: this.createdAt.toISOString(),
685 updated: this.updatedAt.toISOString(),
686 attributedTo: this.VideoChannel ? [ this.VideoChannel.Actor.url ] : [],