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