]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/models/video/video-channel.ts
Merge branch 'release/5.0.0' into develop
[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'
4638cd71 22import { forceNumber, pick } from '@shared/core-utils'
6b5f72be 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 282 [ScopeNames.WITH_STATS]: (options: AvailableWithStatsOptions = { daysPrior: 30 }) => {
4638cd71 283 const daysPrior = forceNumber(options.daysPrior)
3d527ba1
RK
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
dfa4944f 437 function getLocalVideoChannelStats (days?: number) {
fe19f600
RK
438 const options = {
439 type: QueryTypes.SELECT as QueryTypes.SELECT,
440 raw: true
441 }
442
dfa4944f
C
443 const videoJoin = days
444 ? `INNER JOIN "video" AS "Videos" ON "VideoChannelModel"."id" = "Videos"."channelId" ` +
445 `AND ("Videos"."publishedAt" > Now() - interval '${days}d')`
446 : ''
447
fe19f600 448 const query = `
dfa4944f
C
449 SELECT COUNT(DISTINCT("VideoChannelModel"."id")) AS "count"
450 FROM "videoChannel" AS "VideoChannelModel"
451 ${videoJoin}
452 INNER JOIN "account" AS "Account" ON "VideoChannelModel"."accountId" = "Account"."id"
453 INNER JOIN "actor" AS "Account->Actor" ON "Account"."actorId" = "Account->Actor"."id"
454 AND "Account->Actor"."serverId" IS NULL`
fe19f600
RK
455
456 return VideoChannelModel.sequelize.query<{ count: string }>(query, options)
457 .then(r => parseInt(r[0].count, 10))
458 }
459
dfa4944f
C
460 const totalLocalVideoChannels = await getLocalVideoChannelStats()
461 const totalLocalDailyActiveVideoChannels = await getLocalVideoChannelStats(1)
462 const totalLocalWeeklyActiveVideoChannels = await getLocalVideoChannelStats(7)
463 const totalLocalMonthlyActiveVideoChannels = await getLocalVideoChannelStats(30)
464 const totalLocalHalfYearActiveVideoChannels = await getLocalVideoChannelStats(180)
fe19f600
RK
465
466 return {
467 totalLocalVideoChannels,
468 totalLocalDailyActiveVideoChannels,
469 totalLocalWeeklyActiveVideoChannels,
470 totalLocalMonthlyActiveVideoChannels,
dfa4944f 471 totalLocalHalfYearActiveVideoChannels
fe19f600
RK
472 }
473 }
474
b49f22d8 475 static listLocalsForSitemap (sort: string): Promise<MChannelActor[]> {
2feebf3e
C
476 const query = {
477 attributes: [ ],
478 offset: 0,
479 order: getSort(sort),
480 include: [
481 {
482 attributes: [ 'preferredUsername', 'serverId' ],
483 model: ActorModel.unscoped(),
484 where: {
485 serverId: null
486 }
487 }
488 ]
489 }
490
491 return VideoChannelModel
492 .unscoped()
493 .findAll(query)
494 }
495
9c9a236b 496 static listForApi (parameters: Pick<AvailableForListOptions, 'actorId'> & {
f37dc0dd
C
497 start: number
498 count: number
499 sort: string
9c9a236b
C
500 }) {
501 const { actorId } = parameters
fa47956e 502
9c9a236b
C
503 const query = {
504 offset: parameters.start,
505 limit: parameters.count,
506 order: getSort(parameters.sort)
507 }
508
d0800f76 509 const getScope = (forCount: boolean) => {
510 return { method: [ ScopeNames.FOR_API, { actorId, forCount } as AvailableForListOptions ] }
511 }
512
513 return Promise.all([
514 VideoChannelModel.scope(getScope(true)).count(),
515 VideoChannelModel.scope(getScope(false)).findAll(query)
516 ]).then(([ total, data ]) => ({ total, data }))
9c9a236b
C
517 }
518
519 static searchForApi (options: Pick<AvailableForListOptions, 'actorId' | 'search' | 'host' | 'handles'> & {
520 start: number
521 count: number
522 sort: string
f37dc0dd 523 }) {
fbd67e7f
C
524 let attributesInclude: any[] = [ literal('0 as similarity') ]
525 let where: WhereOptions
f37dc0dd 526
fbd67e7f
C
527 if (options.search) {
528 const escapedSearch = VideoChannelModel.sequelize.escape(options.search)
529 const escapedLikeSearch = VideoChannelModel.sequelize.escape('%' + options.search + '%')
530 attributesInclude = [ createSimilarityAttribute('VideoChannelModel.name', options.search) ]
531
532 where = {
1735c825 533 [Op.or]: [
c3c2ab1c
C
534 Sequelize.literal(
535 'lower(immutable_unaccent("VideoChannelModel"."name")) % lower(immutable_unaccent(' + escapedSearch + '))'
536 ),
537 Sequelize.literal(
538 'lower(immutable_unaccent("VideoChannelModel"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))'
f37dc0dd 539 )
c3c2ab1c 540 ]
f37dc0dd
C
541 }
542 }
543
fbd67e7f
C
544 const query = {
545 attributes: {
546 include: attributesInclude
547 },
548 offset: options.start,
549 limit: options.count,
550 order: getSort(options.sort),
551 where
552 }
553
d0800f76 554 const getScope = (forCount: boolean) => {
555 return {
556 method: [
557 ScopeNames.FOR_API, {
558 ...pick(options, [ 'actorId', 'host', 'handles' ]),
559
560 forCount
561 } as AvailableForListOptions
562 ]
563 }
564 }
565
566 return Promise.all([
567 VideoChannelModel.scope(getScope(true)).count(query),
568 VideoChannelModel.scope(getScope(false)).findAll(query)
569 ]).then(([ total, data ]) => ({ total, data }))
72c7248b
C
570 }
571
4beda9e1 572 static listByAccountForAPI (options: {
a1587156
C
573 accountId: number
574 start: number
575 count: number
91b66319 576 sort: string
8165d00a 577 withStats?: boolean
4f5d0459 578 search?: string
91b66319 579 }) {
4f5d0459
RK
580 const escapedSearch = VideoModel.sequelize.escape(options.search)
581 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
582 const where = options.search
583 ? {
584 [Op.or]: [
585 Sequelize.literal(
586 'lower(immutable_unaccent("VideoChannelModel"."name")) % lower(immutable_unaccent(' + escapedSearch + '))'
587 ),
588 Sequelize.literal(
589 'lower(immutable_unaccent("VideoChannelModel"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))'
590 )
591 ]
592 }
593 : null
594
d0800f76 595 const getQuery = (forCount: boolean) => {
596 const accountModel = forCount
597 ? AccountModel.unscoped()
598 : AccountModel
599
600 return {
601 offset: options.start,
602 limit: options.count,
603 order: getSort(options.sort),
604 include: [
605 {
606 model: accountModel,
607 where: {
608 id: options.accountId
609 },
610 required: true
611 }
612 ],
613 where
614 }
3fd3ab2d 615 }
72c7248b 616
43fc899a 617 const findScopes: string | ScopeOptions | (string | ScopeOptions)[] = [ ScopeNames.WITH_ACTOR_BANNER ]
8165d00a 618
5a61ffbb 619 if (options.withStats === true) {
43fc899a 620 findScopes.push({
8165d00a
RK
621 method: [ ScopeNames.WITH_STATS, { daysPrior: 30 } as AvailableWithStatsOptions ]
622 })
623 }
624
d0800f76 625 return Promise.all([
43fc899a
C
626 VideoChannelModel.unscoped().count(getQuery(true)),
627 VideoChannelModel.scope(findScopes).findAll(getQuery(false))
d0800f76 628 ]).then(([ total, data ]) => ({ total, data }))
72c7248b
C
629 }
630
d0800f76 631 static listAllByAccount (accountId: number): Promise<MChannel[]> {
4beda9e1 632 const query = {
754b6f5f 633 limit: CONFIG.VIDEO_CHANNELS.MAX_PER_USER,
4beda9e1
C
634 include: [
635 {
636 attributes: [],
d0800f76 637 model: AccountModel.unscoped(),
4beda9e1
C
638 where: {
639 id: accountId
640 },
641 required: true
642 }
643 ]
644 }
645
646 return VideoChannelModel.findAll(query)
647 }
648
eae0365b 649 static loadAndPopulateAccount (id: number, transaction?: Transaction): Promise<MChannelBannerAccountDefault> {
5cf84858 650 return VideoChannelModel.unscoped()
2cb03dc1 651 .scope([ ScopeNames.WITH_ACTOR_BANNER, ScopeNames.WITH_ACCOUNT ])
eae0365b 652 .findByPk(id, { transaction })
3fd3ab2d 653 }
0d0e8dd0 654
2cb03dc1 655 static loadByUrlAndPopulateAccount (url: string): Promise<MChannelBannerAccountDefault> {
f37dc0dd
C
656 const query = {
657 include: [
658 {
659 model: ActorModel,
660 required: true,
661 where: {
662 url
2cb03dc1
C
663 },
664 include: [
665 {
666 model: ActorImageModel,
667 required: false,
d0800f76 668 as: 'Banners'
2cb03dc1
C
669 }
670 ]
f37dc0dd
C
671 }
672 ]
673 }
674
675 return VideoChannelModel
676 .scope([ ScopeNames.WITH_ACCOUNT ])
8a19bee1 677 .findOne(query)
72c7248b
C
678 }
679
92bf2f62
C
680 static loadByNameWithHostAndPopulateAccount (nameWithHost: string) {
681 const [ name, host ] = nameWithHost.split('@')
682
6dd9de95 683 if (!host || host === WEBSERVER.HOST) return VideoChannelModel.loadLocalByNameAndPopulateAccount(name)
92bf2f62
C
684
685 return VideoChannelModel.loadByNameAndHostAndPopulateAccount(name, host)
686 }
687
2cb03dc1 688 static loadLocalByNameAndPopulateAccount (name: string): Promise<MChannelBannerAccountDefault> {
8a19bee1 689 const query = {
3fd3ab2d 690 include: [
8a19bee1
C
691 {
692 model: ActorModel,
693 required: true,
694 where: {
695 preferredUsername: name,
696 serverId: null
2cb03dc1
C
697 },
698 include: [
699 {
700 model: ActorImageModel,
701 required: false,
d0800f76 702 as: 'Banners'
2cb03dc1
C
703 }
704 ]
8a19bee1 705 }
3fd3ab2d
C
706 ]
707 }
72c7248b 708
5cf84858 709 return VideoChannelModel.unscoped()
2cb03dc1 710 .scope([ ScopeNames.WITH_ACCOUNT ])
8a19bee1 711 .findOne(query)
72c7248b
C
712 }
713
2cb03dc1 714 static loadByNameAndHostAndPopulateAccount (name: string, host: string): Promise<MChannelBannerAccountDefault> {
06a05d5f
C
715 const query = {
716 include: [
717 {
718 model: ActorModel,
719 required: true,
720 where: {
8a19bee1
C
721 preferredUsername: name
722 },
723 include: [
724 {
725 model: ServerModel,
726 required: true,
727 where: { host }
2cb03dc1
C
728 },
729 {
730 model: ActorImageModel,
731 required: false,
d0800f76 732 as: 'Banners'
8a19bee1
C
733 }
734 ]
06a05d5f
C
735 }
736 ]
737 }
738
5cf84858 739 return VideoChannelModel.unscoped()
2cb03dc1 740 .scope([ ScopeNames.WITH_ACCOUNT ])
8a19bee1
C
741 .findOne(query)
742 }
743
1ca9f7c3
C
744 toFormattedSummaryJSON (this: MChannelSummaryFormattable): VideoChannelSummary {
745 const actor = this.Actor.toFormattedSummaryJSON()
746
747 return {
748 id: this.id,
749 name: actor.name,
750 displayName: this.getDisplayName(),
751 url: actor.url,
752 host: actor.host,
d0800f76 753 avatars: actor.avatars,
754
755 // TODO: remove, deprecated in 4.2
1ca9f7c3
C
756 avatar: actor.avatar
757 }
758 }
759
760 toFormattedJSON (this: MChannelFormattable): VideoChannel {
1ba471c5
C
761 const viewsPerDayString = this.get('viewsPerDay') as string
762 const videosCount = this.get('videosCount') as number
763
764 let viewsPerDay: { date: Date, views: number }[]
765
766 if (viewsPerDayString) {
767 viewsPerDay = viewsPerDayString.split(',')
768 .map(v => {
769 const [ dateString, amount ] = v.split('|')
770
771 return {
772 date: new Date(dateString),
773 views: +amount
774 }
775 })
776 }
8165d00a 777
c6f8ca4d
FC
778 const totalViews = this.get('totalViews') as number
779
50d6de9c 780 const actor = this.Actor.toFormattedJSON()
6b738c7a 781 const videoChannel = {
3fd3ab2d 782 id: this.id,
749c7247 783 displayName: this.getDisplayName(),
3fd3ab2d 784 description: this.description,
2422c46b 785 support: this.support,
50d6de9c 786 isLocal: this.Actor.isOwned(),
e024fd6a 787 updatedAt: this.updatedAt,
d0800f76 788
8165d00a 789 ownerAccount: undefined,
d0800f76 790
1ba471c5 791 videosCount,
d0800f76 792 viewsPerDay,
c6f8ca4d 793 totalViews,
d0800f76 794
795 avatars: actor.avatars,
796
797 // TODO: remove, deprecated in 4.2
798 avatar: actor.avatar
6b738c7a
C
799 }
800
a4f99a76 801 if (this.Account) videoChannel.ownerAccount = this.Account.toFormattedJSON()
72c7248b 802
6b738c7a 803 return Object.assign(actor, videoChannel)
72c7248b
C
804 }
805
b5fecbf4 806 toActivityPubObject (this: MChannelAP): ActivityPubActor {
8424c402 807 const obj = this.Actor.toActivityPubObject(this.name)
50d6de9c
C
808
809 return Object.assign(obj, {
810 summary: this.description,
2422c46b 811 support: this.support,
50d6de9c
C
812 attributedTo: [
813 {
814 type: 'Person' as 'Person',
815 id: this.Account.Actor.url
816 }
817 ]
818 })
72c7248b 819 }
749c7247 820
a59f210f
C
821 getLocalUrl (this: MAccountActor | MChannelActor) {
822 return WEBSERVER.URL + `/video-channels/` + this.Actor.preferredUsername
823 }
824
749c7247
C
825 getDisplayName () {
826 return this.name
827 }
744d0eca
C
828
829 isOutdated () {
830 return this.Actor.isOutdated()
831 }
e024fd6a 832
3419e0e1 833 setAsUpdated (transaction?: Transaction) {
e024fd6a
C
834 return setAsUpdated('videoChannel', this.id, transaction)
835 }
72c7248b 836}