]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/models/video/video-channel.ts
Fix lint
[github/Chocobozzz/PeerTube.git] / server / models / video / video-channel.ts
CommitLineData
fa47956e 1import { FindOptions, Includeable, literal, Op, QueryTypes, ScopeOptions, Transaction, WhereOptions } 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'
6b5f72be 20import { CONFIG } from '@server/initializers/config'
a59f210f 21import { MAccountActor } from '@server/types/models'
6b5f72be
C
22import { pick } from '@shared/core-utils'
23import { AttributesOnly } from '@shared/typescript-utils'
50d6de9c 24import { ActivityPubActor } from '../../../shared/models/activitypub'
418d092a 25import { VideoChannel, VideoChannelSummary } from '../../../shared/models/videos'
2422c46b 26import {
06a05d5f 27 isVideoChannelDescriptionValid,
27db7840 28 isVideoChannelDisplayNameValid,
2422c46b
C
29 isVideoChannelSupportValid
30} from '../../helpers/custom-validators/video-channels'
754b6f5f 31import { CONSTRAINTS_FIELDS, WEBSERVER } from '../../initializers/constants'
2af337c8 32import { sendDeleteActor } from '../../lib/activitypub/send'
453e83ea 33import {
d0800f76 34 MChannel,
453e83ea 35 MChannelActor,
b5fecbf4 36 MChannelAP,
2cb03dc1 37 MChannelBannerAccountDefault,
b5fecbf4
C
38 MChannelFormattable,
39 MChannelSummaryFormattable
26d6bf65 40} from '../../types/models/video'
2af337c8 41import { AccountModel, ScopeNames as AccountModelScopeNames, SummaryOptions as AccountSummaryOptions } from '../account/account'
7d9ba5c0
C
42import { ActorModel, unusedActorAttributesForAPI } from '../actor/actor'
43import { ActorFollowModel } from '../actor/actor-follow'
44import { ActorImageModel } from '../actor/actor-image'
2af337c8 45import { ServerModel } from '../server/server'
fa47956e 46import { setAsUpdated } from '../shared'
2af337c8
C
47import { buildServerIdsFollowedBy, buildTrigramSearchIndex, createSimilarityAttribute, getSort, throwIfNotValid } from '../utils'
48import { VideoModel } from './video'
49import { VideoPlaylistModel } from './video-playlist'
f37dc0dd 50
418d092a 51export enum ScopeNames {
453e83ea 52 FOR_API = 'FOR_API',
8165d00a 53 SUMMARY = 'SUMMARY',
d48ff09d 54 WITH_ACCOUNT = 'WITH_ACCOUNT',
50d6de9c 55 WITH_ACTOR = 'WITH_ACTOR',
2cb03dc1 56 WITH_ACTOR_BANNER = 'WITH_ACTOR_BANNER',
418d092a 57 WITH_VIDEOS = 'WITH_VIDEOS',
8165d00a 58 WITH_STATS = 'WITH_STATS'
d48ff09d
C
59}
60
f37dc0dd
C
61type AvailableForListOptions = {
62 actorId: number
bc99dfe5 63 search?: string
fa47956e 64 host?: string
b033851f 65 handles?: string[]
d0800f76 66 forCount?: boolean
f37dc0dd
C
67}
68
8165d00a
RK
69type AvailableWithStatsOptions = {
70 daysPrior: number
71}
72
bfbd9128 73export type SummaryOptions = {
4f32032f 74 actorRequired?: boolean // Default: true
bfbd9128
C
75 withAccount?: boolean // Default: false
76 withAccountBlockerIds?: number[]
77}
78
3acc5084 79@DefaultScope(() => ({
50d6de9c
C
80 include: [
81 {
3acc5084 82 model: ActorModel,
50d6de9c
C
83 required: true
84 }
85 ]
3acc5084
C
86}))
87@Scopes(() => ({
453e83ea 88 [ScopeNames.FOR_API]: (options: AvailableForListOptions) => {
f37dc0dd 89 // Only list local channels OR channels that are on an instance followed by actorId
418d092a 90 const inQueryInstanceFollow = buildServerIdsFollowedBy(options.actorId)
f37dc0dd 91
fbd67e7f
C
92 const whereActorAnd: WhereOptions[] = [
93 {
94 [Op.or]: [
95 {
96 serverId: null
97 },
98 {
99 serverId: {
100 [Op.in]: Sequelize.literal(inQueryInstanceFollow)
101 }
fa47956e 102 }
fbd67e7f
C
103 ]
104 }
105 ]
fa47956e
C
106
107 let serverRequired = false
108 let whereServer: WhereOptions
109
110 if (options.host && options.host !== WEBSERVER.HOST) {
111 serverRequired = true
112 whereServer = { host: options.host }
113 }
114
115 if (options.host === WEBSERVER.HOST) {
fbd67e7f
C
116 whereActorAnd.push({
117 serverId: null
118 })
119 }
120
d0800f76 121 if (Array.isArray(options.handles) && options.handles.length !== 0) {
122 const or: string[] = []
b033851f
C
123
124 for (const handle of options.handles || []) {
125 const [ preferredUsername, host ] = handle.split('@')
126
93a1e67f 127 if (!host || host === WEBSERVER.HOST) {
d0800f76 128 or.push(`("preferredUsername" = ${VideoChannelModel.sequelize.escape(preferredUsername)} AND "serverId" IS NULL)`)
b033851f 129 } else {
d0800f76 130 or.push(
131 `(` +
132 `"preferredUsername" = ${VideoChannelModel.sequelize.escape(preferredUsername)} ` +
133 `AND "host" = ${VideoChannelModel.sequelize.escape(host)}` +
134 `)`
135 )
fbd67e7f 136 }
b033851f
C
137 }
138
d0800f76 139 whereActorAnd.push({
140 id: {
141 [Op.in]: literal(`(SELECT "actor".id FROM actor LEFT JOIN server on server.id = actor."serverId" WHERE ${or.join(' OR ')})`)
142 }
143 })
144 }
145
43fc899a
C
146 const channelActorInclude: Includeable[] = []
147 const accountActorInclude: Includeable[] = []
d0800f76 148
149 if (options.forCount !== true) {
43fc899a 150 accountActorInclude.push({
d0800f76 151 model: ServerModel,
152 required: false
153 })
154
43fc899a 155 accountActorInclude.push({
d0800f76 156 model: ActorImageModel,
157 as: 'Avatars',
158 required: false
159 })
160
43fc899a 161 channelActorInclude.push({
d0800f76 162 model: ActorImageModel,
163 as: 'Avatars',
164 required: false
165 })
166
43fc899a 167 channelActorInclude.push({
d0800f76 168 model: ActorImageModel,
169 as: 'Banners',
170 required: false
171 })
172 }
173
174 if (options.forCount !== true || serverRequired) {
43fc899a 175 channelActorInclude.push({
d0800f76 176 model: ServerModel,
177 duplicating: false,
178 required: serverRequired,
179 where: whereServer
180 })
fa47956e
C
181 }
182
f37dc0dd
C
183 return {
184 include: [
185 {
186 attributes: {
187 exclude: unusedActorAttributesForAPI
188 },
d0800f76 189 model: ActorModel.unscoped(),
fbd67e7f
C
190 where: {
191 [Op.and]: whereActorAnd
192 },
43fc899a 193 include: channelActorInclude
f37dc0dd
C
194 },
195 {
d0800f76 196 model: AccountModel.unscoped(),
f37dc0dd
C
197 required: true,
198 include: [
199 {
200 attributes: {
201 exclude: unusedActorAttributesForAPI
202 },
d0800f76 203 model: ActorModel.unscoped(),
204 required: true,
43fc899a 205 include: accountActorInclude
f37dc0dd
C
206 }
207 ]
208 }
209 ]
210 }
211 },
8165d00a 212 [ScopeNames.SUMMARY]: (options: SummaryOptions = {}) => {
b49f22d8
C
213 const include: Includeable[] = [
214 {
d0800f76 215 attributes: [ 'id', 'preferredUsername', 'url', 'serverId' ],
b49f22d8
C
216 model: ActorModel.unscoped(),
217 required: options.actorRequired ?? true,
218 include: [
219 {
220 attributes: [ 'host' ],
221 model: ServerModel.unscoped(),
222 required: false
223 },
224 {
d0800f76 225 model: ActorImageModel,
226 as: 'Avatars',
b49f22d8
C
227 required: false
228 }
229 ]
230 }
231 ]
232
8165d00a 233 const base: FindOptions = {
b49f22d8 234 attributes: [ 'id', 'name', 'description', 'actorId' ]
8165d00a
RK
235 }
236
237 if (options.withAccount === true) {
b49f22d8 238 include.push({
8165d00a
RK
239 model: AccountModel.scope({
240 method: [ AccountModelScopeNames.SUMMARY, { withAccountBlockerIds: options.withAccountBlockerIds } as AccountSummaryOptions ]
241 }),
242 required: true
243 })
244 }
245
b49f22d8
C
246 base.include = include
247
8165d00a
RK
248 return base
249 },
f37dc0dd
C
250 [ScopeNames.WITH_ACCOUNT]: {
251 include: [
252 {
3acc5084 253 model: AccountModel,
f37dc0dd 254 required: true
d48ff09d
C
255 }
256 ]
257 },
8165d00a 258 [ScopeNames.WITH_ACTOR]: {
d48ff09d 259 include: [
8165d00a 260 ActorModel
d48ff09d 261 ]
50d6de9c 262 },
2cb03dc1
C
263 [ScopeNames.WITH_ACTOR_BANNER]: {
264 include: [
265 {
266 model: ActorModel,
267 include: [
268 {
269 model: ActorImageModel,
270 required: false,
d0800f76 271 as: 'Banners'
2cb03dc1
C
272 }
273 ]
274 }
275 ]
276 },
8165d00a 277 [ScopeNames.WITH_VIDEOS]: {
50d6de9c 278 include: [
8165d00a 279 VideoModel
50d6de9c 280 ]
8165d00a 281 },
3d527ba1
RK
282 [ScopeNames.WITH_STATS]: (options: AvailableWithStatsOptions = { daysPrior: 30 }) => {
283 const daysPrior = parseInt(options.daysPrior + '', 10)
284
285 return {
286 attributes: {
287 include: [
1ba471c5
C
288 [
289 literal('(SELECT COUNT(*) FROM "video" WHERE "channelId" = "VideoChannelModel"."id")'),
290 'videosCount'
291 ],
3d527ba1
RK
292 [
293 literal(
294 '(' +
295 `SELECT string_agg(concat_ws('|', t.day, t.views), ',') ` +
296 'FROM ( ' +
297 'WITH ' +
298 'days AS ( ' +
299 `SELECT generate_series(date_trunc('day', now()) - '${daysPrior} day'::interval, ` +
300 `date_trunc('day', now()), '1 day'::interval) AS day ` +
8165d00a 301 ') ' +
5a61ffbb
C
302 'SELECT days.day AS day, COALESCE(SUM("videoView".views), 0) AS views ' +
303 'FROM days ' +
304 'LEFT JOIN (' +
305 '"videoView" INNER JOIN "video" ON "videoView"."videoId" = "video"."id" ' +
306 'AND "video"."channelId" = "VideoChannelModel"."id"' +
307 `) ON date_trunc('day', "videoView"."startDate") = date_trunc('day', days.day) ` +
308 'GROUP BY day ' +
309 'ORDER BY day ' +
310 ') t' +
3d527ba1
RK
311 ')'
312 ),
313 'viewsPerDay'
c6f8ca4d
FC
314 ],
315 [
316 literal(
317 '(' +
318 'SELECT COALESCE(SUM("video".views), 0) AS totalViews ' +
319 'FROM "video" ' +
320 'WHERE "video"."channelId" = "VideoChannelModel"."id"' +
321 ')'
322 ),
323 'totalViews'
3d527ba1 324 ]
8165d00a 325 ]
3d527ba1 326 }
8165d00a 327 }
3d527ba1 328 }
3acc5084 329}))
3fd3ab2d
C
330@Table({
331 tableName: 'videoChannel',
0374b6b5
C
332 indexes: [
333 buildTrigramSearchIndex('video_channel_name_trigram', 'name'),
334
335 {
336 fields: [ 'accountId' ]
337 },
338 {
339 fields: [ 'actorId' ]
340 }
341 ]
3fd3ab2d 342})
16c016e8 343export class VideoChannelModel extends Model<Partial<AttributesOnly<VideoChannelModel>>> {
72c7248b 344
3fd3ab2d 345 @AllowNull(false)
27db7840 346 @Is('VideoChannelName', value => throwIfNotValid(value, isVideoChannelDisplayNameValid, 'name'))
3fd3ab2d
C
347 @Column
348 name: string
72c7248b 349
3fd3ab2d 350 @AllowNull(true)
2422c46b 351 @Default(null)
1735c825 352 @Is('VideoChannelDescription', value => throwIfNotValid(value, isVideoChannelDescriptionValid, 'description', true))
a10fc78b 353 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_CHANNELS.DESCRIPTION.max))
3fd3ab2d 354 description: string
72c7248b 355
2422c46b
C
356 @AllowNull(true)
357 @Default(null)
1735c825 358 @Is('VideoChannelSupport', value => throwIfNotValid(value, isVideoChannelSupportValid, 'support', true))
a10fc78b 359 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_CHANNELS.SUPPORT.max))
2422c46b
C
360 support: string
361
3fd3ab2d
C
362 @CreatedAt
363 createdAt: Date
72c7248b 364
3fd3ab2d
C
365 @UpdatedAt
366 updatedAt: Date
4e50b6a1 367
fadf619a
C
368 @ForeignKey(() => ActorModel)
369 @Column
370 actorId: number
371
372 @BelongsTo(() => ActorModel, {
373 foreignKey: {
374 allowNull: false
375 },
376 onDelete: 'cascade'
377 })
378 Actor: ActorModel
379
3fd3ab2d
C
380 @ForeignKey(() => AccountModel)
381 @Column
382 accountId: number
4e50b6a1 383
3fd3ab2d
C
384 @BelongsTo(() => AccountModel, {
385 foreignKey: {
386 allowNull: false
06c27593 387 }
3fd3ab2d
C
388 })
389 Account: AccountModel
72c7248b 390
3fd3ab2d 391 @HasMany(() => VideoModel, {
72c7248b 392 foreignKey: {
3fd3ab2d 393 name: 'channelId',
72c7248b
C
394 allowNull: false
395 },
f05a1c30
C
396 onDelete: 'CASCADE',
397 hooks: true
72c7248b 398 })
3fd3ab2d 399 Videos: VideoModel[]
72c7248b 400
418d092a
C
401 @HasMany(() => VideoPlaylistModel, {
402 foreignKey: {
07b1a18a 403 allowNull: true
418d092a 404 },
df0b219d 405 onDelete: 'CASCADE',
418d092a
C
406 hooks: true
407 })
408 VideoPlaylists: VideoPlaylistModel[]
409
f05a1c30
C
410 @BeforeDestroy
411 static async sendDeleteIfOwned (instance: VideoChannelModel, options) {
412 if (!instance.Actor) {
e6122097 413 instance.Actor = await instance.$get('Actor', { transaction: options.transaction })
f05a1c30
C
414 }
415
2af337c8
C
416 await ActorFollowModel.removeFollowsOf(instance.Actor.id, options.transaction)
417
c5a893d5 418 if (instance.Actor.isOwned()) {
c5a893d5
C
419 return sendDeleteActor(instance.Actor, options.transaction)
420 }
421
422 return undefined
3fd3ab2d 423 }
72c7248b 424
3fd3ab2d
C
425 static countByAccount (accountId: number) {
426 const query = {
427 where: {
428 accountId
429 }
72c7248b 430 }
3fd3ab2d 431
11d70211 432 return VideoChannelModel.unscoped().count(query)
72c7248b
C
433 }
434
fe19f600
RK
435 static async getStats () {
436
437 function getActiveVideoChannels (days: number) {
438 const options = {
439 type: QueryTypes.SELECT as QueryTypes.SELECT,
440 raw: true
441 }
442
443 const query = `
444SELECT COUNT(DISTINCT("VideoChannelModel"."id")) AS "count"
445FROM "videoChannel" AS "VideoChannelModel"
446INNER JOIN "video" AS "Videos"
447ON "VideoChannelModel"."id" = "Videos"."channelId"
448AND ("Videos"."publishedAt" > Now() - interval '${days}d')
449INNER JOIN "account" AS "Account"
450ON "VideoChannelModel"."accountId" = "Account"."id"
451INNER JOIN "actor" AS "Account->Actor"
452ON "Account"."actorId" = "Account->Actor"."id"
453AND "Account->Actor"."serverId" IS NULL
454LEFT OUTER JOIN "server" AS "Account->Actor->Server"
455ON "Account->Actor"."serverId" = "Account->Actor->Server"."id"`
456
457 return VideoChannelModel.sequelize.query<{ count: string }>(query, options)
458 .then(r => parseInt(r[0].count, 10))
459 }
460
461 const totalLocalVideoChannels = await VideoChannelModel.count()
462 const totalLocalDailyActiveVideoChannels = await getActiveVideoChannels(1)
463 const totalLocalWeeklyActiveVideoChannels = await getActiveVideoChannels(7)
464 const totalLocalMonthlyActiveVideoChannels = await getActiveVideoChannels(30)
465 const totalHalfYearActiveVideoChannels = await getActiveVideoChannels(180)
466
467 return {
468 totalLocalVideoChannels,
469 totalLocalDailyActiveVideoChannels,
470 totalLocalWeeklyActiveVideoChannels,
471 totalLocalMonthlyActiveVideoChannels,
472 totalHalfYearActiveVideoChannels
473 }
474 }
475
b49f22d8 476 static listLocalsForSitemap (sort: string): Promise<MChannelActor[]> {
2feebf3e
C
477 const query = {
478 attributes: [ ],
479 offset: 0,
480 order: getSort(sort),
481 include: [
482 {
483 attributes: [ 'preferredUsername', 'serverId' ],
484 model: ActorModel.unscoped(),
485 where: {
486 serverId: null
487 }
488 }
489 ]
490 }
491
492 return VideoChannelModel
493 .unscoped()
494 .findAll(query)
495 }
496
9c9a236b 497 static listForApi (parameters: Pick<AvailableForListOptions, 'actorId'> & {
f37dc0dd
C
498 start: number
499 count: number
500 sort: string
9c9a236b
C
501 }) {
502 const { actorId } = parameters
fa47956e 503
9c9a236b
C
504 const query = {
505 offset: parameters.start,
506 limit: parameters.count,
507 order: getSort(parameters.sort)
508 }
509
d0800f76 510 const getScope = (forCount: boolean) => {
511 return { method: [ ScopeNames.FOR_API, { actorId, forCount } as AvailableForListOptions ] }
512 }
513
514 return Promise.all([
515 VideoChannelModel.scope(getScope(true)).count(),
516 VideoChannelModel.scope(getScope(false)).findAll(query)
517 ]).then(([ total, data ]) => ({ total, data }))
9c9a236b
C
518 }
519
520 static searchForApi (options: Pick<AvailableForListOptions, 'actorId' | 'search' | 'host' | 'handles'> & {
521 start: number
522 count: number
523 sort: string
f37dc0dd 524 }) {
fbd67e7f
C
525 let attributesInclude: any[] = [ literal('0 as similarity') ]
526 let where: WhereOptions
f37dc0dd 527
fbd67e7f
C
528 if (options.search) {
529 const escapedSearch = VideoChannelModel.sequelize.escape(options.search)
530 const escapedLikeSearch = VideoChannelModel.sequelize.escape('%' + options.search + '%')
531 attributesInclude = [ createSimilarityAttribute('VideoChannelModel.name', options.search) ]
532
533 where = {
1735c825 534 [Op.or]: [
c3c2ab1c
C
535 Sequelize.literal(
536 'lower(immutable_unaccent("VideoChannelModel"."name")) % lower(immutable_unaccent(' + escapedSearch + '))'
537 ),
538 Sequelize.literal(
539 'lower(immutable_unaccent("VideoChannelModel"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))'
f37dc0dd 540 )
c3c2ab1c 541 ]
f37dc0dd
C
542 }
543 }
544
fbd67e7f
C
545 const query = {
546 attributes: {
547 include: attributesInclude
548 },
549 offset: options.start,
550 limit: options.count,
551 order: getSort(options.sort),
552 where
553 }
554
d0800f76 555 const getScope = (forCount: boolean) => {
556 return {
557 method: [
558 ScopeNames.FOR_API, {
559 ...pick(options, [ 'actorId', 'host', 'handles' ]),
560
561 forCount
562 } as AvailableForListOptions
563 ]
564 }
565 }
566
567 return Promise.all([
568 VideoChannelModel.scope(getScope(true)).count(query),
569 VideoChannelModel.scope(getScope(false)).findAll(query)
570 ]).then(([ total, data ]) => ({ total, data }))
72c7248b
C
571 }
572
4beda9e1 573 static listByAccountForAPI (options: {
a1587156
C
574 accountId: number
575 start: number
576 count: number
91b66319 577 sort: string
8165d00a 578 withStats?: boolean
4f5d0459 579 search?: string
91b66319 580 }) {
4f5d0459
RK
581 const escapedSearch = VideoModel.sequelize.escape(options.search)
582 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
583 const where = options.search
584 ? {
585 [Op.or]: [
586 Sequelize.literal(
587 'lower(immutable_unaccent("VideoChannelModel"."name")) % lower(immutable_unaccent(' + escapedSearch + '))'
588 ),
589 Sequelize.literal(
590 'lower(immutable_unaccent("VideoChannelModel"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))'
591 )
592 ]
593 }
594 : null
595
d0800f76 596 const getQuery = (forCount: boolean) => {
597 const accountModel = forCount
598 ? AccountModel.unscoped()
599 : AccountModel
600
601 return {
602 offset: options.start,
603 limit: options.count,
604 order: getSort(options.sort),
605 include: [
606 {
607 model: accountModel,
608 where: {
609 id: options.accountId
610 },
611 required: true
612 }
613 ],
614 where
615 }
3fd3ab2d 616 }
72c7248b 617
43fc899a 618 const findScopes: string | ScopeOptions | (string | ScopeOptions)[] = [ ScopeNames.WITH_ACTOR_BANNER ]
8165d00a 619
5a61ffbb 620 if (options.withStats === true) {
43fc899a 621 findScopes.push({
8165d00a
RK
622 method: [ ScopeNames.WITH_STATS, { daysPrior: 30 } as AvailableWithStatsOptions ]
623 })
624 }
625
d0800f76 626 return Promise.all([
43fc899a
C
627 VideoChannelModel.unscoped().count(getQuery(true)),
628 VideoChannelModel.scope(findScopes).findAll(getQuery(false))
d0800f76 629 ]).then(([ total, data ]) => ({ total, data }))
72c7248b
C
630 }
631
d0800f76 632 static listAllByAccount (accountId: number): Promise<MChannel[]> {
4beda9e1 633 const query = {
754b6f5f 634 limit: CONFIG.VIDEO_CHANNELS.MAX_PER_USER,
4beda9e1
C
635 include: [
636 {
637 attributes: [],
d0800f76 638 model: AccountModel.unscoped(),
4beda9e1
C
639 where: {
640 id: accountId
641 },
642 required: true
643 }
644 ]
645 }
646
647 return VideoChannelModel.findAll(query)
648 }
649
eae0365b 650 static loadAndPopulateAccount (id: number, transaction?: Transaction): Promise<MChannelBannerAccountDefault> {
5cf84858 651 return VideoChannelModel.unscoped()
2cb03dc1 652 .scope([ ScopeNames.WITH_ACTOR_BANNER, ScopeNames.WITH_ACCOUNT ])
eae0365b 653 .findByPk(id, { transaction })
3fd3ab2d 654 }
0d0e8dd0 655
2cb03dc1 656 static loadByUrlAndPopulateAccount (url: string): Promise<MChannelBannerAccountDefault> {
f37dc0dd
C
657 const query = {
658 include: [
659 {
660 model: ActorModel,
661 required: true,
662 where: {
663 url
2cb03dc1
C
664 },
665 include: [
666 {
667 model: ActorImageModel,
668 required: false,
d0800f76 669 as: 'Banners'
2cb03dc1
C
670 }
671 ]
f37dc0dd
C
672 }
673 ]
674 }
675
676 return VideoChannelModel
677 .scope([ ScopeNames.WITH_ACCOUNT ])
8a19bee1 678 .findOne(query)
72c7248b
C
679 }
680
92bf2f62
C
681 static loadByNameWithHostAndPopulateAccount (nameWithHost: string) {
682 const [ name, host ] = nameWithHost.split('@')
683
6dd9de95 684 if (!host || host === WEBSERVER.HOST) return VideoChannelModel.loadLocalByNameAndPopulateAccount(name)
92bf2f62
C
685
686 return VideoChannelModel.loadByNameAndHostAndPopulateAccount(name, host)
687 }
688
2cb03dc1 689 static loadLocalByNameAndPopulateAccount (name: string): Promise<MChannelBannerAccountDefault> {
8a19bee1 690 const query = {
3fd3ab2d 691 include: [
8a19bee1
C
692 {
693 model: ActorModel,
694 required: true,
695 where: {
696 preferredUsername: name,
697 serverId: null
2cb03dc1
C
698 },
699 include: [
700 {
701 model: ActorImageModel,
702 required: false,
d0800f76 703 as: 'Banners'
2cb03dc1
C
704 }
705 ]
8a19bee1 706 }
3fd3ab2d
C
707 ]
708 }
72c7248b 709
5cf84858 710 return VideoChannelModel.unscoped()
2cb03dc1 711 .scope([ ScopeNames.WITH_ACCOUNT ])
8a19bee1 712 .findOne(query)
72c7248b
C
713 }
714
2cb03dc1 715 static loadByNameAndHostAndPopulateAccount (name: string, host: string): Promise<MChannelBannerAccountDefault> {
06a05d5f
C
716 const query = {
717 include: [
718 {
719 model: ActorModel,
720 required: true,
721 where: {
8a19bee1
C
722 preferredUsername: name
723 },
724 include: [
725 {
726 model: ServerModel,
727 required: true,
728 where: { host }
2cb03dc1
C
729 },
730 {
731 model: ActorImageModel,
732 required: false,
d0800f76 733 as: 'Banners'
8a19bee1
C
734 }
735 ]
06a05d5f
C
736 }
737 ]
738 }
739
5cf84858 740 return VideoChannelModel.unscoped()
2cb03dc1 741 .scope([ ScopeNames.WITH_ACCOUNT ])
8a19bee1
C
742 .findOne(query)
743 }
744
1ca9f7c3
C
745 toFormattedSummaryJSON (this: MChannelSummaryFormattable): VideoChannelSummary {
746 const actor = this.Actor.toFormattedSummaryJSON()
747
748 return {
749 id: this.id,
750 name: actor.name,
751 displayName: this.getDisplayName(),
752 url: actor.url,
753 host: actor.host,
d0800f76 754 avatars: actor.avatars,
755
756 // TODO: remove, deprecated in 4.2
1ca9f7c3
C
757 avatar: actor.avatar
758 }
759 }
760
761 toFormattedJSON (this: MChannelFormattable): VideoChannel {
1ba471c5
C
762 const viewsPerDayString = this.get('viewsPerDay') as string
763 const videosCount = this.get('videosCount') as number
764
765 let viewsPerDay: { date: Date, views: number }[]
766
767 if (viewsPerDayString) {
768 viewsPerDay = viewsPerDayString.split(',')
769 .map(v => {
770 const [ dateString, amount ] = v.split('|')
771
772 return {
773 date: new Date(dateString),
774 views: +amount
775 }
776 })
777 }
8165d00a 778
c6f8ca4d
FC
779 const totalViews = this.get('totalViews') as number
780
50d6de9c 781 const actor = this.Actor.toFormattedJSON()
6b738c7a 782 const videoChannel = {
3fd3ab2d 783 id: this.id,
749c7247 784 displayName: this.getDisplayName(),
3fd3ab2d 785 description: this.description,
2422c46b 786 support: this.support,
50d6de9c 787 isLocal: this.Actor.isOwned(),
e024fd6a 788 updatedAt: this.updatedAt,
d0800f76 789
8165d00a 790 ownerAccount: undefined,
d0800f76 791
1ba471c5 792 videosCount,
d0800f76 793 viewsPerDay,
c6f8ca4d 794 totalViews,
d0800f76 795
796 avatars: actor.avatars,
797
798 // TODO: remove, deprecated in 4.2
799 avatar: actor.avatar
6b738c7a
C
800 }
801
a4f99a76 802 if (this.Account) videoChannel.ownerAccount = this.Account.toFormattedJSON()
72c7248b 803
6b738c7a 804 return Object.assign(actor, videoChannel)
72c7248b
C
805 }
806
b5fecbf4 807 toActivityPubObject (this: MChannelAP): ActivityPubActor {
8424c402 808 const obj = this.Actor.toActivityPubObject(this.name)
50d6de9c
C
809
810 return Object.assign(obj, {
811 summary: this.description,
2422c46b 812 support: this.support,
50d6de9c
C
813 attributedTo: [
814 {
815 type: 'Person' as 'Person',
816 id: this.Account.Actor.url
817 }
818 ]
819 })
72c7248b 820 }
749c7247 821
a59f210f
C
822 getLocalUrl (this: MAccountActor | MChannelActor) {
823 return WEBSERVER.URL + `/video-channels/` + this.Actor.preferredUsername
824 }
825
749c7247
C
826 getDisplayName () {
827 return this.name
828 }
744d0eca
C
829
830 isOutdated () {
831 return this.Actor.isOutdated()
832 }
e024fd6a 833
3419e0e1 834 setAsUpdated (transaction?: Transaction) {
e024fd6a
C
835 return setAsUpdated('videoChannel', this.id, transaction)
836 }
72c7248b 837}