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