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