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