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