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