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