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