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