]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/models/video/video-channel.ts
Split ffmpeg utils with ffprobe utils
[github/Chocobozzz/PeerTube.git] / server / models / video / video-channel.ts
CommitLineData
2af337c8
C
1import * as Bluebird from 'bluebird'
2import { FindOptions, literal, Op, ScopeOptions } from 'sequelize'
3fd3ab2d 3import {
06a05d5f
C
4 AllowNull,
5 BeforeDestroy,
6 BelongsTo,
7 Column,
8 CreatedAt,
9 DataType,
10 Default,
11 DefaultScope,
12 ForeignKey,
6dd9de95 13 HasMany,
06a05d5f
C
14 Is,
15 Model,
16 Scopes,
f37dc0dd 17 Sequelize,
06a05d5f
C
18 Table,
19 UpdatedAt
3fd3ab2d 20} from 'sequelize-typescript'
50d6de9c 21import { ActivityPubActor } from '../../../shared/models/activitypub'
418d092a 22import { VideoChannel, VideoChannelSummary } from '../../../shared/models/videos'
2422c46b 23import {
06a05d5f
C
24 isVideoChannelDescriptionValid,
25 isVideoChannelNameValid,
2422c46b
C
26 isVideoChannelSupportValid
27} from '../../helpers/custom-validators/video-channels'
74dc3bca 28import { CONSTRAINTS_FIELDS, WEBSERVER } from '../../initializers/constants'
2af337c8 29import { sendDeleteActor } from '../../lib/activitypub/send'
453e83ea
C
30import {
31 MChannelAccountDefault,
32 MChannelActor,
b5fecbf4
C
33 MChannelActorAccountDefaultVideos,
34 MChannelAP,
35 MChannelFormattable,
36 MChannelSummaryFormattable
26d6bf65 37} from '../../types/models/video'
2af337c8
C
38import { AccountModel, ScopeNames as AccountModelScopeNames, SummaryOptions as AccountSummaryOptions } from '../account/account'
39import { ActorModel, unusedActorAttributesForAPI } from '../activitypub/actor'
40import { ActorFollowModel } from '../activitypub/actor-follow'
41import { AvatarModel } from '../avatar/avatar'
42import { ServerModel } from '../server/server'
43import { buildServerIdsFollowedBy, buildTrigramSearchIndex, createSimilarityAttribute, getSort, throwIfNotValid } from '../utils'
44import { VideoModel } from './video'
45import { VideoPlaylistModel } from './video-playlist'
f37dc0dd 46
418d092a 47export enum ScopeNames {
453e83ea 48 FOR_API = 'FOR_API',
8165d00a 49 SUMMARY = 'SUMMARY',
d48ff09d 50 WITH_ACCOUNT = 'WITH_ACCOUNT',
50d6de9c 51 WITH_ACTOR = 'WITH_ACTOR',
418d092a 52 WITH_VIDEOS = 'WITH_VIDEOS',
8165d00a 53 WITH_STATS = 'WITH_STATS'
d48ff09d
C
54}
55
f37dc0dd
C
56type AvailableForListOptions = {
57 actorId: number
bc99dfe5 58 search?: string
f37dc0dd
C
59}
60
8165d00a
RK
61type AvailableWithStatsOptions = {
62 daysPrior: number
63}
64
bfbd9128 65export type SummaryOptions = {
4f32032f 66 actorRequired?: boolean // Default: true
bfbd9128
C
67 withAccount?: boolean // Default: false
68 withAccountBlockerIds?: number[]
69}
70
3acc5084 71@DefaultScope(() => ({
50d6de9c
C
72 include: [
73 {
3acc5084 74 model: ActorModel,
50d6de9c
C
75 required: true
76 }
77 ]
3acc5084
C
78}))
79@Scopes(() => ({
453e83ea 80 [ScopeNames.FOR_API]: (options: AvailableForListOptions) => {
f37dc0dd 81 // Only list local channels OR channels that are on an instance followed by actorId
418d092a 82 const inQueryInstanceFollow = buildServerIdsFollowedBy(options.actorId)
f37dc0dd
C
83
84 return {
85 include: [
86 {
87 attributes: {
88 exclude: unusedActorAttributesForAPI
89 },
90 model: ActorModel,
91 where: {
1735c825 92 [Op.or]: [
c305467c 93 {
f37dc0dd
C
94 serverId: null
95 },
96 {
97 serverId: {
a1587156 98 [Op.in]: Sequelize.literal(inQueryInstanceFollow)
f37dc0dd 99 }
c305467c
C
100 }
101 ]
50d6de9c 102 }
f37dc0dd
C
103 },
104 {
105 model: AccountModel,
106 required: true,
107 include: [
108 {
109 attributes: {
110 exclude: unusedActorAttributesForAPI
111 },
112 model: ActorModel, // Default scope includes avatar and server
113 required: true
114 }
115 ]
116 }
117 ]
118 }
119 },
8165d00a
RK
120 [ScopeNames.SUMMARY]: (options: SummaryOptions = {}) => {
121 const base: FindOptions = {
122 attributes: [ 'id', 'name', 'description', 'actorId' ],
123 include: [
124 {
125 attributes: [ 'id', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
126 model: ActorModel.unscoped(),
4f32032f 127 required: options.actorRequired ?? true,
8165d00a
RK
128 include: [
129 {
130 attributes: [ 'host' ],
131 model: ServerModel.unscoped(),
132 required: false
133 },
134 {
135 model: AvatarModel.unscoped(),
136 required: false
137 }
138 ]
139 }
140 ]
141 }
142
143 if (options.withAccount === true) {
144 base.include.push({
145 model: AccountModel.scope({
146 method: [ AccountModelScopeNames.SUMMARY, { withAccountBlockerIds: options.withAccountBlockerIds } as AccountSummaryOptions ]
147 }),
148 required: true
149 })
150 }
151
152 return base
153 },
f37dc0dd
C
154 [ScopeNames.WITH_ACCOUNT]: {
155 include: [
156 {
3acc5084 157 model: AccountModel,
f37dc0dd 158 required: true
d48ff09d
C
159 }
160 ]
161 },
8165d00a 162 [ScopeNames.WITH_ACTOR]: {
d48ff09d 163 include: [
8165d00a 164 ActorModel
d48ff09d 165 ]
50d6de9c 166 },
8165d00a 167 [ScopeNames.WITH_VIDEOS]: {
50d6de9c 168 include: [
8165d00a 169 VideoModel
50d6de9c 170 ]
8165d00a 171 },
3d527ba1
RK
172 [ScopeNames.WITH_STATS]: (options: AvailableWithStatsOptions = { daysPrior: 30 }) => {
173 const daysPrior = parseInt(options.daysPrior + '', 10)
174
175 return {
176 attributes: {
177 include: [
1ba471c5
C
178 [
179 literal('(SELECT COUNT(*) FROM "video" WHERE "channelId" = "VideoChannelModel"."id")'),
180 'videosCount'
181 ],
3d527ba1
RK
182 [
183 literal(
184 '(' +
185 `SELECT string_agg(concat_ws('|', t.day, t.views), ',') ` +
186 'FROM ( ' +
187 'WITH ' +
188 'days AS ( ' +
189 `SELECT generate_series(date_trunc('day', now()) - '${daysPrior} day'::interval, ` +
190 `date_trunc('day', now()), '1 day'::interval) AS day ` +
8165d00a 191 ') ' +
5a61ffbb
C
192 'SELECT days.day AS day, COALESCE(SUM("videoView".views), 0) AS views ' +
193 'FROM days ' +
194 'LEFT JOIN (' +
195 '"videoView" INNER JOIN "video" ON "videoView"."videoId" = "video"."id" ' +
196 'AND "video"."channelId" = "VideoChannelModel"."id"' +
197 `) ON date_trunc('day', "videoView"."startDate") = date_trunc('day', days.day) ` +
198 'GROUP BY day ' +
199 'ORDER BY day ' +
200 ') t' +
3d527ba1
RK
201 ')'
202 ),
203 'viewsPerDay'
204 ]
8165d00a 205 ]
3d527ba1 206 }
8165d00a 207 }
3d527ba1 208 }
3acc5084 209}))
3fd3ab2d
C
210@Table({
211 tableName: 'videoChannel',
0374b6b5
C
212 indexes: [
213 buildTrigramSearchIndex('video_channel_name_trigram', 'name'),
214
215 {
216 fields: [ 'accountId' ]
217 },
218 {
219 fields: [ 'actorId' ]
220 }
221 ]
3fd3ab2d
C
222})
223export class VideoChannelModel extends Model<VideoChannelModel> {
72c7248b 224
3fd3ab2d
C
225 @AllowNull(false)
226 @Is('VideoChannelName', value => throwIfNotValid(value, isVideoChannelNameValid, 'name'))
227 @Column
228 name: string
72c7248b 229
3fd3ab2d 230 @AllowNull(true)
2422c46b 231 @Default(null)
1735c825 232 @Is('VideoChannelDescription', value => throwIfNotValid(value, isVideoChannelDescriptionValid, 'description', true))
a10fc78b 233 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_CHANNELS.DESCRIPTION.max))
3fd3ab2d 234 description: string
72c7248b 235
2422c46b
C
236 @AllowNull(true)
237 @Default(null)
1735c825 238 @Is('VideoChannelSupport', value => throwIfNotValid(value, isVideoChannelSupportValid, 'support', true))
a10fc78b 239 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_CHANNELS.SUPPORT.max))
2422c46b
C
240 support: string
241
3fd3ab2d
C
242 @CreatedAt
243 createdAt: Date
72c7248b 244
3fd3ab2d
C
245 @UpdatedAt
246 updatedAt: Date
4e50b6a1 247
fadf619a
C
248 @ForeignKey(() => ActorModel)
249 @Column
250 actorId: number
251
252 @BelongsTo(() => ActorModel, {
253 foreignKey: {
254 allowNull: false
255 },
256 onDelete: 'cascade'
257 })
258 Actor: ActorModel
259
3fd3ab2d
C
260 @ForeignKey(() => AccountModel)
261 @Column
262 accountId: number
4e50b6a1 263
3fd3ab2d
C
264 @BelongsTo(() => AccountModel, {
265 foreignKey: {
266 allowNull: false
267 },
6b738c7a 268 hooks: true
3fd3ab2d
C
269 })
270 Account: AccountModel
72c7248b 271
3fd3ab2d 272 @HasMany(() => VideoModel, {
72c7248b 273 foreignKey: {
3fd3ab2d 274 name: 'channelId',
72c7248b
C
275 allowNull: false
276 },
f05a1c30
C
277 onDelete: 'CASCADE',
278 hooks: true
72c7248b 279 })
3fd3ab2d 280 Videos: VideoModel[]
72c7248b 281
418d092a
C
282 @HasMany(() => VideoPlaylistModel, {
283 foreignKey: {
07b1a18a 284 allowNull: true
418d092a 285 },
df0b219d 286 onDelete: 'CASCADE',
418d092a
C
287 hooks: true
288 })
289 VideoPlaylists: VideoPlaylistModel[]
290
f05a1c30
C
291 @BeforeDestroy
292 static async sendDeleteIfOwned (instance: VideoChannelModel, options) {
293 if (!instance.Actor) {
e6122097 294 instance.Actor = await instance.$get('Actor', { transaction: options.transaction })
f05a1c30
C
295 }
296
2af337c8
C
297 await ActorFollowModel.removeFollowsOf(instance.Actor.id, options.transaction)
298
c5a893d5 299 if (instance.Actor.isOwned()) {
c5a893d5
C
300 return sendDeleteActor(instance.Actor, options.transaction)
301 }
302
303 return undefined
3fd3ab2d 304 }
72c7248b 305
3fd3ab2d
C
306 static countByAccount (accountId: number) {
307 const query = {
308 where: {
309 accountId
310 }
72c7248b 311 }
3fd3ab2d
C
312
313 return VideoChannelModel.count(query)
72c7248b
C
314 }
315
bc99dfe5
RK
316 static listForApi (parameters: {
317 actorId: number
318 start: number
319 count: number
320 sort: string
bc99dfe5 321 }) {
4f5d0459 322 const { actorId } = parameters
bc99dfe5 323
3fd3ab2d 324 const query = {
bc99dfe5
RK
325 offset: parameters.start,
326 limit: parameters.count,
327 order: getSort(parameters.sort)
3fd3ab2d 328 }
72c7248b 329
f37dc0dd 330 const scopes = {
4f5d0459 331 method: [ ScopeNames.FOR_API, { actorId } as AvailableForListOptions ]
f37dc0dd 332 }
50d6de9c 333 return VideoChannelModel
f37dc0dd
C
334 .scope(scopes)
335 .findAndCountAll(query)
336 .then(({ rows, count }) => {
337 return { total: count, data: rows }
338 })
339 }
340
453e83ea 341 static listLocalsForSitemap (sort: string): Bluebird<MChannelActor[]> {
2feebf3e
C
342 const query = {
343 attributes: [ ],
344 offset: 0,
345 order: getSort(sort),
346 include: [
347 {
348 attributes: [ 'preferredUsername', 'serverId' ],
349 model: ActorModel.unscoped(),
350 where: {
351 serverId: null
352 }
353 }
354 ]
355 }
356
357 return VideoChannelModel
358 .unscoped()
359 .findAll(query)
360 }
361
f37dc0dd
C
362 static searchForApi (options: {
363 actorId: number
364 search: string
365 start: number
366 count: number
367 sort: string
368 }) {
369 const attributesInclude = []
370 const escapedSearch = VideoModel.sequelize.escape(options.search)
371 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
372 attributesInclude.push(createSimilarityAttribute('VideoChannelModel.name', options.search))
373
374 const query = {
375 attributes: {
376 include: attributesInclude
377 },
378 offset: options.start,
379 limit: options.count,
380 order: getSort(options.sort),
381 where: {
1735c825 382 [Op.or]: [
c3c2ab1c
C
383 Sequelize.literal(
384 'lower(immutable_unaccent("VideoChannelModel"."name")) % lower(immutable_unaccent(' + escapedSearch + '))'
385 ),
386 Sequelize.literal(
387 'lower(immutable_unaccent("VideoChannelModel"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))'
f37dc0dd 388 )
c3c2ab1c 389 ]
f37dc0dd
C
390 }
391 }
392
393 const scopes = {
453e83ea 394 method: [ ScopeNames.FOR_API, { actorId: options.actorId } as AvailableForListOptions ]
f37dc0dd
C
395 }
396 return VideoChannelModel
397 .scope(scopes)
50d6de9c 398 .findAndCountAll(query)
3fd3ab2d
C
399 .then(({ rows, count }) => {
400 return { total: count, data: rows }
401 })
72c7248b
C
402 }
403
91b66319 404 static listByAccount (options: {
a1587156
C
405 accountId: number
406 start: number
407 count: number
91b66319 408 sort: string
8165d00a 409 withStats?: boolean
4f5d0459 410 search?: string
91b66319 411 }) {
4f5d0459
RK
412 const escapedSearch = VideoModel.sequelize.escape(options.search)
413 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
414 const where = options.search
415 ? {
416 [Op.or]: [
417 Sequelize.literal(
418 'lower(immutable_unaccent("VideoChannelModel"."name")) % lower(immutable_unaccent(' + escapedSearch + '))'
419 ),
420 Sequelize.literal(
421 'lower(immutable_unaccent("VideoChannelModel"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))'
422 )
423 ]
424 }
425 : null
426
3fd3ab2d 427 const query = {
91b66319
C
428 offset: options.start,
429 limit: options.count,
430 order: getSort(options.sort),
3fd3ab2d
C
431 include: [
432 {
433 model: AccountModel,
434 where: {
91b66319 435 id: options.accountId
3fd3ab2d 436 },
50d6de9c 437 required: true
3fd3ab2d 438 }
4f5d0459
RK
439 ],
440 where
3fd3ab2d 441 }
72c7248b 442
8165d00a
RK
443 const scopes: string | ScopeOptions | (string | ScopeOptions)[] = [ ScopeNames.WITH_ACTOR ]
444
5a61ffbb 445 if (options.withStats === true) {
8165d00a
RK
446 scopes.push({
447 method: [ ScopeNames.WITH_STATS, { daysPrior: 30 } as AvailableWithStatsOptions ]
448 })
449 }
450
50d6de9c 451 return VideoChannelModel
8165d00a 452 .scope(scopes)
50d6de9c 453 .findAndCountAll(query)
3fd3ab2d
C
454 .then(({ rows, count }) => {
455 return { total: count, data: rows }
456 })
72c7248b
C
457 }
458
0283eaac 459 static loadByIdAndPopulateAccount (id: number): Bluebird<MChannelAccountDefault> {
5cf84858
C
460 return VideoChannelModel.unscoped()
461 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
9b39106d 462 .findByPk(id)
5cf84858
C
463 }
464
0283eaac 465 static loadByIdAndAccount (id: number, accountId: number): Bluebird<MChannelAccountDefault> {
8a19bee1 466 const query = {
3fd3ab2d
C
467 where: {
468 id,
469 accountId
d48ff09d 470 }
571389d4 471 }
3fd3ab2d 472
5cf84858 473 return VideoChannelModel.unscoped()
50d6de9c 474 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
8a19bee1 475 .findOne(query)
0d0e8dd0
C
476 }
477
0283eaac 478 static loadAndPopulateAccount (id: number): Bluebird<MChannelAccountDefault> {
5cf84858 479 return VideoChannelModel.unscoped()
50d6de9c 480 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
9b39106d 481 .findByPk(id)
3fd3ab2d 482 }
0d0e8dd0 483
453e83ea 484 static loadByUrlAndPopulateAccount (url: string): Bluebird<MChannelAccountDefault> {
f37dc0dd
C
485 const query = {
486 include: [
487 {
488 model: ActorModel,
489 required: true,
490 where: {
491 url
492 }
493 }
494 ]
495 }
496
497 return VideoChannelModel
498 .scope([ ScopeNames.WITH_ACCOUNT ])
8a19bee1 499 .findOne(query)
72c7248b
C
500 }
501
92bf2f62
C
502 static loadByNameWithHostAndPopulateAccount (nameWithHost: string) {
503 const [ name, host ] = nameWithHost.split('@')
504
6dd9de95 505 if (!host || host === WEBSERVER.HOST) return VideoChannelModel.loadLocalByNameAndPopulateAccount(name)
92bf2f62
C
506
507 return VideoChannelModel.loadByNameAndHostAndPopulateAccount(name, host)
508 }
509
0283eaac 510 static loadLocalByNameAndPopulateAccount (name: string): Bluebird<MChannelAccountDefault> {
8a19bee1 511 const query = {
3fd3ab2d 512 include: [
8a19bee1
C
513 {
514 model: ActorModel,
515 required: true,
516 where: {
517 preferredUsername: name,
518 serverId: null
519 }
520 }
3fd3ab2d
C
521 ]
522 }
72c7248b 523
5cf84858 524 return VideoChannelModel.unscoped()
8a19bee1
C
525 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
526 .findOne(query)
72c7248b
C
527 }
528
0283eaac 529 static loadByNameAndHostAndPopulateAccount (name: string, host: string): Bluebird<MChannelAccountDefault> {
06a05d5f
C
530 const query = {
531 include: [
532 {
533 model: ActorModel,
534 required: true,
535 where: {
8a19bee1
C
536 preferredUsername: name
537 },
538 include: [
539 {
540 model: ServerModel,
541 required: true,
542 where: { host }
543 }
544 ]
06a05d5f
C
545 }
546 ]
547 }
548
5cf84858 549 return VideoChannelModel.unscoped()
8a19bee1
C
550 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
551 .findOne(query)
552 }
553
453e83ea 554 static loadAndPopulateAccountAndVideos (id: number): Bluebird<MChannelActorAccountDefaultVideos> {
8a19bee1
C
555 const options = {
556 include: [
557 VideoModel
558 ]
559 }
560
5cf84858 561 return VideoChannelModel.unscoped()
8a19bee1 562 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT, ScopeNames.WITH_VIDEOS ])
9b39106d 563 .findByPk(id, options)
06a05d5f
C
564 }
565
1ca9f7c3
C
566 toFormattedSummaryJSON (this: MChannelSummaryFormattable): VideoChannelSummary {
567 const actor = this.Actor.toFormattedSummaryJSON()
568
569 return {
570 id: this.id,
571 name: actor.name,
572 displayName: this.getDisplayName(),
573 url: actor.url,
574 host: actor.host,
575 avatar: actor.avatar
576 }
577 }
578
579 toFormattedJSON (this: MChannelFormattable): VideoChannel {
1ba471c5
C
580 const viewsPerDayString = this.get('viewsPerDay') as string
581 const videosCount = this.get('videosCount') as number
582
583 let viewsPerDay: { date: Date, views: number }[]
584
585 if (viewsPerDayString) {
586 viewsPerDay = viewsPerDayString.split(',')
587 .map(v => {
588 const [ dateString, amount ] = v.split('|')
589
590 return {
591 date: new Date(dateString),
592 views: +amount
593 }
594 })
595 }
8165d00a 596
50d6de9c 597 const actor = this.Actor.toFormattedJSON()
6b738c7a 598 const videoChannel = {
3fd3ab2d 599 id: this.id,
749c7247 600 displayName: this.getDisplayName(),
3fd3ab2d 601 description: this.description,
2422c46b 602 support: this.support,
50d6de9c 603 isLocal: this.Actor.isOwned(),
3fd3ab2d 604 createdAt: this.createdAt,
6b738c7a 605 updatedAt: this.updatedAt,
8165d00a 606 ownerAccount: undefined,
1ba471c5
C
607 videosCount,
608 viewsPerDay
6b738c7a
C
609 }
610
a4f99a76 611 if (this.Account) videoChannel.ownerAccount = this.Account.toFormattedJSON()
72c7248b 612
6b738c7a 613 return Object.assign(actor, videoChannel)
72c7248b
C
614 }
615
b5fecbf4 616 toActivityPubObject (this: MChannelAP): ActivityPubActor {
8424c402 617 const obj = this.Actor.toActivityPubObject(this.name)
50d6de9c
C
618
619 return Object.assign(obj, {
620 summary: this.description,
2422c46b 621 support: this.support,
50d6de9c
C
622 attributedTo: [
623 {
624 type: 'Person' as 'Person',
625 id: this.Account.Actor.url
626 }
627 ]
628 })
72c7248b 629 }
749c7247
C
630
631 getDisplayName () {
632 return this.name
633 }
744d0eca
C
634
635 isOutdated () {
636 return this.Actor.isOutdated()
637 }
72c7248b 638}