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