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