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