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