]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/models/video/video-playlist.ts
Fix subscriptions
[github/Chocobozzz/PeerTube.git] / server / models / video / video-playlist.ts
1 import { join } from 'path'
2 import { FindOptions, literal, Op, ScopeOptions, Sequelize, Transaction, WhereOptions } from 'sequelize'
3 import {
4 AllowNull,
5 BelongsTo,
6 Column,
7 CreatedAt,
8 DataType,
9 Default,
10 ForeignKey,
11 HasMany,
12 HasOne,
13 Is,
14 IsUUID,
15 Model,
16 Scopes,
17 Table,
18 UpdatedAt
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'
30 import {
31 isVideoPlaylistDescriptionValid,
32 isVideoPlaylistNameValid,
33 isVideoPlaylistPrivacyValid
34 } from '../../helpers/custom-validators/video-playlists'
35 import {
36 ACTIVITY_PUB,
37 CONSTRAINTS_FIELDS,
38 STATIC_PATHS,
39 THUMBNAILS_SIZE,
40 VIDEO_PLAYLIST_PRIVACIES,
41 VIDEO_PLAYLIST_TYPES,
42 WEBSERVER
43 } from '../../initializers/constants'
44 import { MThumbnail } from '../../types/models/video/thumbnail'
45 import {
46 MVideoPlaylistAccountThumbnail,
47 MVideoPlaylistAP,
48 MVideoPlaylistFormattable,
49 MVideoPlaylistFull,
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'
56 import {
57 buildServerIdsFollowedBy,
58 buildTrigramSearchIndex,
59 buildWhereIdOrUUID,
60 createSimilarityAttribute,
61 getPlaylistSort,
62 isOutdated,
63 throwIfNotValid
64 } from '../utils'
65 import { ThumbnailModel } from './thumbnail'
66 import { ScopeNames as VideoChannelScopeNames, VideoChannelModel } from './video-channel'
67 import { VideoPlaylistElementModel } from './video-playlist-element'
68
69 enum ScopeNames {
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'
76 }
77
78 type AvailableForListOptions = {
79 followerActorId?: number
80 type?: VideoPlaylistType
81 accountId?: number
82 videoChannelId?: number
83 listMyPlaylists?: boolean
84 search?: string
85 host?: string
86 uuids?: string[]
87 withVideos?: boolean
88 }
89
90 function getVideoLengthSelect () {
91 return 'SELECT COUNT("id") FROM "videoPlaylistElement" WHERE "videoPlaylistId" = "VideoPlaylistModel"."id"'
92 }
93
94 @Scopes(() => ({
95 [ScopeNames.WITH_THUMBNAIL]: {
96 include: [
97 {
98 model: ThumbnailModel,
99 required: false
100 }
101 ]
102 },
103 [ScopeNames.WITH_VIDEOS_LENGTH]: {
104 attributes: {
105 include: [
106 [
107 literal(`(${getVideoLengthSelect()})`),
108 'videosLength'
109 ]
110 ]
111 }
112 } as FindOptions,
113 [ScopeNames.WITH_ACCOUNT]: {
114 include: [
115 {
116 model: AccountModel,
117 required: true
118 }
119 ]
120 },
121 [ScopeNames.WITH_ACCOUNT_AND_CHANNEL_SUMMARY]: {
122 include: [
123 {
124 model: AccountModel.scope(AccountScopeNames.SUMMARY),
125 required: true
126 },
127 {
128 model: VideoChannelModel.scope(VideoChannelScopeNames.SUMMARY),
129 required: false
130 }
131 ]
132 },
133 [ScopeNames.WITH_ACCOUNT_AND_CHANNEL]: {
134 include: [
135 {
136 model: AccountModel,
137 required: true
138 },
139 {
140 model: VideoChannelModel,
141 required: false
142 }
143 ]
144 },
145 [ScopeNames.AVAILABLE_FOR_LIST]: (options: AvailableForListOptions) => {
146 const whereAnd: WhereOptions[] = []
147
148 const whereServer = options.host && options.host !== WEBSERVER.HOST
149 ? { host: options.host }
150 : undefined
151
152 let whereActor: WhereOptions = {}
153
154 if (options.host === WEBSERVER.HOST) {
155 whereActor = {
156 [Op.and]: [ { serverId: null } ]
157 }
158 }
159
160 if (options.listMyPlaylists !== true) {
161 whereAnd.push({
162 privacy: VideoPlaylistPrivacy.PUBLIC
163 })
164
165 // Only list local playlists
166 const whereActorOr: WhereOptions[] = [
167 {
168 serverId: null
169 }
170 ]
171
172 // … OR playlists that are on an instance followed by actorId
173 if (options.followerActorId) {
174 const inQueryInstanceFollow = buildServerIdsFollowedBy(options.followerActorId)
175
176 whereActorOr.push({
177 serverId: {
178 [Op.in]: literal(inQueryInstanceFollow)
179 }
180 })
181 }
182
183 Object.assign(whereActor, { [Op.or]: whereActorOr })
184 }
185
186 if (options.accountId) {
187 whereAnd.push({
188 ownerAccountId: options.accountId
189 })
190 }
191
192 if (options.videoChannelId) {
193 whereAnd.push({
194 videoChannelId: options.videoChannelId
195 })
196 }
197
198 if (options.type) {
199 whereAnd.push({
200 type: options.type
201 })
202 }
203
204 if (options.uuids) {
205 whereAnd.push({
206 uuid: {
207 [Op.in]: options.uuids
208 }
209 })
210 }
211
212 if (options.withVideos === true) {
213 whereAnd.push(
214 literal(`(${getVideoLengthSelect()}) != 0`)
215 )
216 }
217
218 let attributesInclude: any[] = [ literal('0 as similarity') ]
219
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) ]
224
225 whereAnd.push({
226 [Op.or]: [
227 Sequelize.literal(
228 'lower(immutable_unaccent("VideoPlaylistModel"."name")) % lower(immutable_unaccent(' + escapedSearch + '))'
229 ),
230 Sequelize.literal(
231 'lower(immutable_unaccent("VideoPlaylistModel"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))'
232 )
233 ]
234 })
235 }
236
237 const where = {
238 [Op.and]: whereAnd
239 }
240
241 return {
242 attributes: {
243 include: attributesInclude
244 },
245 where,
246 include: [
247 {
248 model: AccountModel.scope({
249 method: [ AccountScopeNames.SUMMARY, { whereActor, whereServer } as SummaryOptions ]
250 }),
251 required: true
252 },
253 {
254 model: VideoChannelModel.scope(VideoChannelScopeNames.SUMMARY),
255 required: false
256 }
257 ]
258 } as FindOptions
259 }
260 }))
261
262 @Table({
263 tableName: 'videoPlaylist',
264 indexes: [
265 buildTrigramSearchIndex('video_playlist_name_trigram', 'name'),
266
267 {
268 fields: [ 'ownerAccountId' ]
269 },
270 {
271 fields: [ 'videoChannelId' ]
272 },
273 {
274 fields: [ 'url' ],
275 unique: true
276 }
277 ]
278 })
279 export class VideoPlaylistModel extends Model<Partial<AttributesOnly<VideoPlaylistModel>>> {
280 @CreatedAt
281 createdAt: Date
282
283 @UpdatedAt
284 updatedAt: Date
285
286 @AllowNull(false)
287 @Is('VideoPlaylistName', value => throwIfNotValid(value, isVideoPlaylistNameValid, 'name'))
288 @Column
289 name: string
290
291 @AllowNull(true)
292 @Is('VideoPlaylistDescription', value => throwIfNotValid(value, isVideoPlaylistDescriptionValid, 'description', true))
293 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_PLAYLISTS.DESCRIPTION.max))
294 description: string
295
296 @AllowNull(false)
297 @Is('VideoPlaylistPrivacy', value => throwIfNotValid(value, isVideoPlaylistPrivacyValid, 'privacy'))
298 @Column
299 privacy: VideoPlaylistPrivacy
300
301 @AllowNull(false)
302 @Is('VideoPlaylistUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
303 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_PLAYLISTS.URL.max))
304 url: string
305
306 @AllowNull(false)
307 @Default(DataType.UUIDV4)
308 @IsUUID(4)
309 @Column(DataType.UUID)
310 uuid: string
311
312 @AllowNull(false)
313 @Default(VideoPlaylistType.REGULAR)
314 @Column
315 type: VideoPlaylistType
316
317 @ForeignKey(() => AccountModel)
318 @Column
319 ownerAccountId: number
320
321 @BelongsTo(() => AccountModel, {
322 foreignKey: {
323 allowNull: false
324 },
325 onDelete: 'CASCADE'
326 })
327 OwnerAccount: AccountModel
328
329 @ForeignKey(() => VideoChannelModel)
330 @Column
331 videoChannelId: number
332
333 @BelongsTo(() => VideoChannelModel, {
334 foreignKey: {
335 allowNull: true
336 },
337 onDelete: 'CASCADE'
338 })
339 VideoChannel: VideoChannelModel
340
341 @HasMany(() => VideoPlaylistElementModel, {
342 foreignKey: {
343 name: 'videoPlaylistId',
344 allowNull: false
345 },
346 onDelete: 'CASCADE'
347 })
348 VideoPlaylistElements: VideoPlaylistElementModel[]
349
350 @HasOne(() => ThumbnailModel, {
351 foreignKey: {
352 name: 'videoPlaylistId',
353 allowNull: true
354 },
355 onDelete: 'CASCADE',
356 hooks: true
357 })
358 Thumbnail: ThumbnailModel
359
360 static listForApi (options: AvailableForListOptions & {
361 start: number
362 count: number
363 sort: string
364 }) {
365 const query = {
366 offset: options.start,
367 limit: options.count,
368 order: getPlaylistSort(options.sort)
369 }
370
371 const scopes: (string | ScopeOptions)[] = [
372 {
373 method: [
374 ScopeNames.AVAILABLE_FOR_LIST,
375 {
376 ...pick(options, [ 'type', 'followerActorId', 'accountId', 'videoChannelId', 'listMyPlaylists', 'search', 'host', 'uuids' ]),
377
378 withVideos: options.withVideos || false
379 } as AvailableForListOptions
380 ]
381 },
382 ScopeNames.WITH_VIDEOS_LENGTH,
383 ScopeNames.WITH_THUMBNAIL
384 ]
385
386 return VideoPlaylistModel
387 .scope(scopes)
388 .findAndCountAll(query)
389 .then(({ rows, count }) => {
390 return { total: count, data: rows }
391 })
392 }
393
394 static searchForApi (options: Pick<AvailableForListOptions, 'followerActorId' | 'search'| 'host'| 'uuids'> & {
395 start: number
396 count: number
397 sort: string
398 }) {
399 return VideoPlaylistModel.listForApi({
400 ...options,
401
402 type: VideoPlaylistType.REGULAR,
403 listMyPlaylists: false,
404 withVideos: true
405 })
406 }
407
408 static listPublicUrlsOfForAP (options: { account?: MAccountId, channel?: MChannelId }, start: number, count: number) {
409 const where = {
410 privacy: VideoPlaylistPrivacy.PUBLIC
411 }
412
413 if (options.account) {
414 Object.assign(where, { ownerAccountId: options.account.id })
415 }
416
417 if (options.channel) {
418 Object.assign(where, { videoChannelId: options.channel.id })
419 }
420
421 const query = {
422 attributes: [ 'url' ],
423 offset: start,
424 limit: count,
425 where
426 }
427
428 return VideoPlaylistModel.findAndCountAll(query)
429 .then(({ rows, count }) => {
430 return { total: count, data: rows.map(p => p.url) }
431 })
432 }
433
434 static listPlaylistIdsOf (accountId: number, videoIds: number[]): Promise<MVideoPlaylistIdWithElements[]> {
435 const query = {
436 attributes: [ 'id' ],
437 where: {
438 ownerAccountId: accountId
439 },
440 include: [
441 {
442 attributes: [ 'id', 'videoId', 'startTimestamp', 'stopTimestamp' ],
443 model: VideoPlaylistElementModel.unscoped(),
444 where: {
445 videoId: {
446 [Op.in]: videoIds
447 }
448 },
449 required: true
450 }
451 ]
452 }
453
454 return VideoPlaylistModel.findAll(query)
455 }
456
457 static doesPlaylistExist (url: string) {
458 const query = {
459 attributes: [ 'id' ],
460 where: {
461 url
462 }
463 }
464
465 return VideoPlaylistModel
466 .findOne(query)
467 .then(e => !!e)
468 }
469
470 static loadWithAccountAndChannelSummary (id: number | string, transaction: Transaction): Promise<MVideoPlaylistFullSummary> {
471 const where = buildWhereIdOrUUID(id)
472
473 const query = {
474 where,
475 transaction
476 }
477
478 return VideoPlaylistModel
479 .scope([ ScopeNames.WITH_ACCOUNT_AND_CHANNEL_SUMMARY, ScopeNames.WITH_VIDEOS_LENGTH, ScopeNames.WITH_THUMBNAIL ])
480 .findOne(query)
481 }
482
483 static loadWithAccountAndChannel (id: number | string, transaction: Transaction): Promise<MVideoPlaylistFull> {
484 const where = buildWhereIdOrUUID(id)
485
486 const query = {
487 where,
488 transaction
489 }
490
491 return VideoPlaylistModel
492 .scope([ ScopeNames.WITH_ACCOUNT_AND_CHANNEL, ScopeNames.WITH_VIDEOS_LENGTH, ScopeNames.WITH_THUMBNAIL ])
493 .findOne(query)
494 }
495
496 static loadByUrlAndPopulateAccount (url: string): Promise<MVideoPlaylistAccountThumbnail> {
497 const query = {
498 where: {
499 url
500 }
501 }
502
503 return VideoPlaylistModel.scope([ ScopeNames.WITH_ACCOUNT, ScopeNames.WITH_THUMBNAIL ]).findOne(query)
504 }
505
506 static loadByUrlWithAccountAndChannelSummary (url: string): Promise<MVideoPlaylistFullSummary> {
507 const query = {
508 where: {
509 url
510 }
511 }
512
513 return VideoPlaylistModel
514 .scope([ ScopeNames.WITH_ACCOUNT_AND_CHANNEL_SUMMARY, ScopeNames.WITH_VIDEOS_LENGTH, ScopeNames.WITH_THUMBNAIL ])
515 .findOne(query)
516 }
517
518 static getPrivacyLabel (privacy: VideoPlaylistPrivacy) {
519 return VIDEO_PLAYLIST_PRIVACIES[privacy] || 'Unknown'
520 }
521
522 static getTypeLabel (type: VideoPlaylistType) {
523 return VIDEO_PLAYLIST_TYPES[type] || 'Unknown'
524 }
525
526 static resetPlaylistsOfChannel (videoChannelId: number, transaction: Transaction) {
527 const query = {
528 where: {
529 videoChannelId
530 },
531 transaction
532 }
533
534 return VideoPlaylistModel.update({ privacy: VideoPlaylistPrivacy.PRIVATE, videoChannelId: null }, query)
535 }
536
537 async setAndSaveThumbnail (thumbnail: MThumbnail, t: Transaction) {
538 thumbnail.videoPlaylistId = this.id
539
540 this.Thumbnail = await thumbnail.save({ transaction: t })
541 }
542
543 hasThumbnail () {
544 return !!this.Thumbnail
545 }
546
547 hasGeneratedThumbnail () {
548 return this.hasThumbnail() && this.Thumbnail.automaticallyGenerated === true
549 }
550
551 generateThumbnailName () {
552 const extension = '.jpg'
553
554 return 'playlist-' + buildUUID() + extension
555 }
556
557 getThumbnailUrl () {
558 if (!this.hasThumbnail()) return null
559
560 return WEBSERVER.URL + STATIC_PATHS.THUMBNAILS + this.Thumbnail.filename
561 }
562
563 getThumbnailStaticPath () {
564 if (!this.hasThumbnail()) return null
565
566 return join(STATIC_PATHS.THUMBNAILS, this.Thumbnail.filename)
567 }
568
569 getWatchStaticPath () {
570 return buildPlaylistWatchPath({ shortUUID: uuidToShort(this.uuid) })
571 }
572
573 getEmbedStaticPath () {
574 return buildPlaylistEmbedPath(this)
575 }
576
577 static async getStats () {
578 const totalLocalPlaylists = await VideoPlaylistModel.count({
579 include: [
580 {
581 model: AccountModel,
582 required: true,
583 include: [
584 {
585 model: ActorModel,
586 required: true,
587 where: {
588 serverId: null
589 }
590 }
591 ]
592 }
593 ],
594 where: {
595 privacy: VideoPlaylistPrivacy.PUBLIC
596 }
597 })
598
599 return {
600 totalLocalPlaylists
601 }
602 }
603
604 setAsRefreshed () {
605 return setAsUpdated('videoPlaylist', this.id)
606 }
607
608 setVideosLength (videosLength: number) {
609 this.set('videosLength' as any, videosLength, { raw: true })
610 }
611
612 isOwned () {
613 return this.OwnerAccount.isOwned()
614 }
615
616 isOutdated () {
617 if (this.isOwned()) return false
618
619 return isOutdated(this, ACTIVITY_PUB.VIDEO_PLAYLIST_REFRESH_INTERVAL)
620 }
621
622 toFormattedJSON (this: MVideoPlaylistFormattable): VideoPlaylist {
623 return {
624 id: this.id,
625 uuid: this.uuid,
626 shortUUID: uuidToShort(this.uuid),
627
628 isLocal: this.isOwned(),
629
630 url: this.url,
631
632 displayName: this.name,
633 description: this.description,
634 privacy: {
635 id: this.privacy,
636 label: VideoPlaylistModel.getPrivacyLabel(this.privacy)
637 },
638
639 thumbnailPath: this.getThumbnailStaticPath(),
640 embedPath: this.getEmbedStaticPath(),
641
642 type: {
643 id: this.type,
644 label: VideoPlaylistModel.getTypeLabel(this.type)
645 },
646
647 videosLength: this.get('videosLength') as number,
648
649 createdAt: this.createdAt,
650 updatedAt: this.updatedAt,
651
652 ownerAccount: this.OwnerAccount.toFormattedSummaryJSON(),
653 videoChannel: this.VideoChannel
654 ? this.VideoChannel.toFormattedSummaryJSON()
655 : null
656 }
657 }
658
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)
662 }
663
664 let icon: ActivityIconObject
665 if (this.hasThumbnail()) {
666 icon = {
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
672 }
673 }
674
675 return activityPubCollectionPagination(this.url, handler, page)
676 .then(o => {
677 return Object.assign(o, {
678 type: 'Playlist' as 'Playlist',
679 name: this.name,
680 content: this.description,
681 uuid: this.uuid,
682 published: this.createdAt.toISOString(),
683 updated: this.updatedAt.toISOString(),
684 attributedTo: this.VideoChannel ? [ this.VideoChannel.Actor.url ] : [],
685 icon
686 })
687 })
688 }
689 }