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