]>
Commit | Line | Data |
---|---|---|
1 | import { FindOptions, Includeable, literal, Op, QueryTypes, ScopeOptions, Transaction, WhereOptions } from 'sequelize' | |
2 | import { | |
3 | AllowNull, | |
4 | BeforeDestroy, | |
5 | BelongsTo, | |
6 | Column, | |
7 | CreatedAt, | |
8 | DataType, | |
9 | Default, | |
10 | DefaultScope, | |
11 | ForeignKey, | |
12 | HasMany, | |
13 | Is, | |
14 | Model, | |
15 | Scopes, | |
16 | Sequelize, | |
17 | Table, | |
18 | UpdatedAt | |
19 | } from 'sequelize-typescript' | |
20 | import { CONFIG } from '@server/initializers/config' | |
21 | import { MAccountActor } from '@server/types/models' | |
22 | import { pick } from '@shared/core-utils' | |
23 | import { AttributesOnly } from '@shared/typescript-utils' | |
24 | import { ActivityPubActor } from '../../../shared/models/activitypub' | |
25 | import { VideoChannel, VideoChannelSummary } from '../../../shared/models/videos' | |
26 | import { | |
27 | isVideoChannelDescriptionValid, | |
28 | isVideoChannelDisplayNameValid, | |
29 | isVideoChannelSupportValid | |
30 | } from '../../helpers/custom-validators/video-channels' | |
31 | import { CONSTRAINTS_FIELDS, WEBSERVER } from '../../initializers/constants' | |
32 | import { sendDeleteActor } from '../../lib/activitypub/send' | |
33 | import { | |
34 | MChannel, | |
35 | MChannelActor, | |
36 | MChannelAP, | |
37 | MChannelBannerAccountDefault, | |
38 | MChannelFormattable, | |
39 | MChannelSummaryFormattable | |
40 | } from '../../types/models/video' | |
41 | import { AccountModel, ScopeNames as AccountModelScopeNames, SummaryOptions as AccountSummaryOptions } from '../account/account' | |
42 | import { ActorModel, unusedActorAttributesForAPI } from '../actor/actor' | |
43 | import { ActorFollowModel } from '../actor/actor-follow' | |
44 | import { ActorImageModel } from '../actor/actor-image' | |
45 | import { ServerModel } from '../server/server' | |
46 | import { setAsUpdated } from '../shared' | |
47 | import { buildServerIdsFollowedBy, buildTrigramSearchIndex, createSimilarityAttribute, getSort, throwIfNotValid } from '../utils' | |
48 | import { VideoModel } from './video' | |
49 | import { VideoPlaylistModel } from './video-playlist' | |
50 | ||
51 | export enum ScopeNames { | |
52 | FOR_API = 'FOR_API', | |
53 | SUMMARY = 'SUMMARY', | |
54 | WITH_ACCOUNT = 'WITH_ACCOUNT', | |
55 | WITH_ACTOR = 'WITH_ACTOR', | |
56 | WITH_ACTOR_BANNER = 'WITH_ACTOR_BANNER', | |
57 | WITH_VIDEOS = 'WITH_VIDEOS', | |
58 | WITH_STATS = 'WITH_STATS' | |
59 | } | |
60 | ||
61 | type AvailableForListOptions = { | |
62 | actorId: number | |
63 | search?: string | |
64 | host?: string | |
65 | handles?: string[] | |
66 | forCount?: boolean | |
67 | } | |
68 | ||
69 | type AvailableWithStatsOptions = { | |
70 | daysPrior: number | |
71 | } | |
72 | ||
73 | export type SummaryOptions = { | |
74 | actorRequired?: boolean // Default: true | |
75 | withAccount?: boolean // Default: false | |
76 | withAccountBlockerIds?: number[] | |
77 | } | |
78 | ||
79 | @DefaultScope(() => ({ | |
80 | include: [ | |
81 | { | |
82 | model: ActorModel, | |
83 | required: true | |
84 | } | |
85 | ] | |
86 | })) | |
87 | @Scopes(() => ({ | |
88 | [ScopeNames.FOR_API]: (options: AvailableForListOptions) => { | |
89 | // Only list local channels OR channels that are on an instance followed by actorId | |
90 | const inQueryInstanceFollow = buildServerIdsFollowedBy(options.actorId) | |
91 | ||
92 | const whereActorAnd: WhereOptions[] = [ | |
93 | { | |
94 | [Op.or]: [ | |
95 | { | |
96 | serverId: null | |
97 | }, | |
98 | { | |
99 | serverId: { | |
100 | [Op.in]: Sequelize.literal(inQueryInstanceFollow) | |
101 | } | |
102 | } | |
103 | ] | |
104 | } | |
105 | ] | |
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) { | |
116 | whereActorAnd.push({ | |
117 | serverId: null | |
118 | }) | |
119 | } | |
120 | ||
121 | if (Array.isArray(options.handles) && options.handles.length !== 0) { | |
122 | const or: string[] = [] | |
123 | ||
124 | for (const handle of options.handles || []) { | |
125 | const [ preferredUsername, host ] = handle.split('@') | |
126 | ||
127 | if (!host || host === WEBSERVER.HOST) { | |
128 | or.push(`("preferredUsername" = ${VideoChannelModel.sequelize.escape(preferredUsername)} AND "serverId" IS NULL)`) | |
129 | } else { | |
130 | or.push( | |
131 | `(` + | |
132 | `"preferredUsername" = ${VideoChannelModel.sequelize.escape(preferredUsername)} ` + | |
133 | `AND "host" = ${VideoChannelModel.sequelize.escape(host)}` + | |
134 | `)` | |
135 | ) | |
136 | } | |
137 | } | |
138 | ||
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 | ||
146 | const channelActorInclude: Includeable[] = [] | |
147 | const accountActorInclude: Includeable[] = [] | |
148 | ||
149 | if (options.forCount !== true) { | |
150 | accountActorInclude.push({ | |
151 | model: ServerModel, | |
152 | required: false | |
153 | }) | |
154 | ||
155 | accountActorInclude.push({ | |
156 | model: ActorImageModel, | |
157 | as: 'Avatars', | |
158 | required: false | |
159 | }) | |
160 | ||
161 | channelActorInclude.push({ | |
162 | model: ActorImageModel, | |
163 | as: 'Avatars', | |
164 | required: false | |
165 | }) | |
166 | ||
167 | channelActorInclude.push({ | |
168 | model: ActorImageModel, | |
169 | as: 'Banners', | |
170 | required: false | |
171 | }) | |
172 | } | |
173 | ||
174 | if (options.forCount !== true || serverRequired) { | |
175 | channelActorInclude.push({ | |
176 | model: ServerModel, | |
177 | duplicating: false, | |
178 | required: serverRequired, | |
179 | where: whereServer | |
180 | }) | |
181 | } | |
182 | ||
183 | return { | |
184 | include: [ | |
185 | { | |
186 | attributes: { | |
187 | exclude: unusedActorAttributesForAPI | |
188 | }, | |
189 | model: ActorModel.unscoped(), | |
190 | where: { | |
191 | [Op.and]: whereActorAnd | |
192 | }, | |
193 | include: channelActorInclude | |
194 | }, | |
195 | { | |
196 | model: AccountModel.unscoped(), | |
197 | required: true, | |
198 | include: [ | |
199 | { | |
200 | attributes: { | |
201 | exclude: unusedActorAttributesForAPI | |
202 | }, | |
203 | model: ActorModel.unscoped(), | |
204 | required: true, | |
205 | include: accountActorInclude | |
206 | } | |
207 | ] | |
208 | } | |
209 | ] | |
210 | } | |
211 | }, | |
212 | [ScopeNames.SUMMARY]: (options: SummaryOptions = {}) => { | |
213 | const include: Includeable[] = [ | |
214 | { | |
215 | attributes: [ 'id', 'preferredUsername', 'url', 'serverId' ], | |
216 | model: ActorModel.unscoped(), | |
217 | required: options.actorRequired ?? true, | |
218 | include: [ | |
219 | { | |
220 | attributes: [ 'host' ], | |
221 | model: ServerModel.unscoped(), | |
222 | required: false | |
223 | }, | |
224 | { | |
225 | model: ActorImageModel, | |
226 | as: 'Avatars', | |
227 | required: false | |
228 | } | |
229 | ] | |
230 | } | |
231 | ] | |
232 | ||
233 | const base: FindOptions = { | |
234 | attributes: [ 'id', 'name', 'description', 'actorId' ] | |
235 | } | |
236 | ||
237 | if (options.withAccount === true) { | |
238 | include.push({ | |
239 | model: AccountModel.scope({ | |
240 | method: [ AccountModelScopeNames.SUMMARY, { withAccountBlockerIds: options.withAccountBlockerIds } as AccountSummaryOptions ] | |
241 | }), | |
242 | required: true | |
243 | }) | |
244 | } | |
245 | ||
246 | base.include = include | |
247 | ||
248 | return base | |
249 | }, | |
250 | [ScopeNames.WITH_ACCOUNT]: { | |
251 | include: [ | |
252 | { | |
253 | model: AccountModel, | |
254 | required: true | |
255 | } | |
256 | ] | |
257 | }, | |
258 | [ScopeNames.WITH_ACTOR]: { | |
259 | include: [ | |
260 | ActorModel | |
261 | ] | |
262 | }, | |
263 | [ScopeNames.WITH_ACTOR_BANNER]: { | |
264 | include: [ | |
265 | { | |
266 | model: ActorModel, | |
267 | include: [ | |
268 | { | |
269 | model: ActorImageModel, | |
270 | required: false, | |
271 | as: 'Banners' | |
272 | } | |
273 | ] | |
274 | } | |
275 | ] | |
276 | }, | |
277 | [ScopeNames.WITH_VIDEOS]: { | |
278 | include: [ | |
279 | VideoModel | |
280 | ] | |
281 | }, | |
282 | [ScopeNames.WITH_STATS]: (options: AvailableWithStatsOptions = { daysPrior: 30 }) => { | |
283 | const daysPrior = parseInt(options.daysPrior + '', 10) | |
284 | ||
285 | return { | |
286 | attributes: { | |
287 | include: [ | |
288 | [ | |
289 | literal('(SELECT COUNT(*) FROM "video" WHERE "channelId" = "VideoChannelModel"."id")'), | |
290 | 'videosCount' | |
291 | ], | |
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 ` + | |
301 | ') ' + | |
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' + | |
311 | ')' | |
312 | ), | |
313 | 'viewsPerDay' | |
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' | |
324 | ] | |
325 | ] | |
326 | } | |
327 | } | |
328 | } | |
329 | })) | |
330 | @Table({ | |
331 | tableName: 'videoChannel', | |
332 | indexes: [ | |
333 | buildTrigramSearchIndex('video_channel_name_trigram', 'name'), | |
334 | ||
335 | { | |
336 | fields: [ 'accountId' ] | |
337 | }, | |
338 | { | |
339 | fields: [ 'actorId' ] | |
340 | } | |
341 | ] | |
342 | }) | |
343 | export class VideoChannelModel extends Model<Partial<AttributesOnly<VideoChannelModel>>> { | |
344 | ||
345 | @AllowNull(false) | |
346 | @Is('VideoChannelName', value => throwIfNotValid(value, isVideoChannelDisplayNameValid, 'name')) | |
347 | @Column | |
348 | name: string | |
349 | ||
350 | @AllowNull(true) | |
351 | @Default(null) | |
352 | @Is('VideoChannelDescription', value => throwIfNotValid(value, isVideoChannelDescriptionValid, 'description', true)) | |
353 | @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_CHANNELS.DESCRIPTION.max)) | |
354 | description: string | |
355 | ||
356 | @AllowNull(true) | |
357 | @Default(null) | |
358 | @Is('VideoChannelSupport', value => throwIfNotValid(value, isVideoChannelSupportValid, 'support', true)) | |
359 | @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_CHANNELS.SUPPORT.max)) | |
360 | support: string | |
361 | ||
362 | @CreatedAt | |
363 | createdAt: Date | |
364 | ||
365 | @UpdatedAt | |
366 | updatedAt: Date | |
367 | ||
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 | ||
380 | @ForeignKey(() => AccountModel) | |
381 | @Column | |
382 | accountId: number | |
383 | ||
384 | @BelongsTo(() => AccountModel, { | |
385 | foreignKey: { | |
386 | allowNull: false | |
387 | } | |
388 | }) | |
389 | Account: AccountModel | |
390 | ||
391 | @HasMany(() => VideoModel, { | |
392 | foreignKey: { | |
393 | name: 'channelId', | |
394 | allowNull: false | |
395 | }, | |
396 | onDelete: 'CASCADE', | |
397 | hooks: true | |
398 | }) | |
399 | Videos: VideoModel[] | |
400 | ||
401 | @HasMany(() => VideoPlaylistModel, { | |
402 | foreignKey: { | |
403 | allowNull: true | |
404 | }, | |
405 | onDelete: 'CASCADE', | |
406 | hooks: true | |
407 | }) | |
408 | VideoPlaylists: VideoPlaylistModel[] | |
409 | ||
410 | @BeforeDestroy | |
411 | static async sendDeleteIfOwned (instance: VideoChannelModel, options) { | |
412 | if (!instance.Actor) { | |
413 | instance.Actor = await instance.$get('Actor', { transaction: options.transaction }) | |
414 | } | |
415 | ||
416 | await ActorFollowModel.removeFollowsOf(instance.Actor.id, options.transaction) | |
417 | ||
418 | if (instance.Actor.isOwned()) { | |
419 | return sendDeleteActor(instance.Actor, options.transaction) | |
420 | } | |
421 | ||
422 | return undefined | |
423 | } | |
424 | ||
425 | static countByAccount (accountId: number) { | |
426 | const query = { | |
427 | where: { | |
428 | accountId | |
429 | } | |
430 | } | |
431 | ||
432 | return VideoChannelModel.unscoped().count(query) | |
433 | } | |
434 | ||
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 = ` | |
444 | SELECT COUNT(DISTINCT("VideoChannelModel"."id")) AS "count" | |
445 | FROM "videoChannel" AS "VideoChannelModel" | |
446 | INNER JOIN "video" AS "Videos" | |
447 | ON "VideoChannelModel"."id" = "Videos"."channelId" | |
448 | AND ("Videos"."publishedAt" > Now() - interval '${days}d') | |
449 | INNER JOIN "account" AS "Account" | |
450 | ON "VideoChannelModel"."accountId" = "Account"."id" | |
451 | INNER JOIN "actor" AS "Account->Actor" | |
452 | ON "Account"."actorId" = "Account->Actor"."id" | |
453 | AND "Account->Actor"."serverId" IS NULL | |
454 | LEFT OUTER JOIN "server" AS "Account->Actor->Server" | |
455 | ON "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 | ||
476 | static listLocalsForSitemap (sort: string): Promise<MChannelActor[]> { | |
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 | ||
497 | static listForApi (parameters: Pick<AvailableForListOptions, 'actorId'> & { | |
498 | start: number | |
499 | count: number | |
500 | sort: string | |
501 | }) { | |
502 | const { actorId } = parameters | |
503 | ||
504 | const query = { | |
505 | offset: parameters.start, | |
506 | limit: parameters.count, | |
507 | order: getSort(parameters.sort) | |
508 | } | |
509 | ||
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 })) | |
518 | } | |
519 | ||
520 | static searchForApi (options: Pick<AvailableForListOptions, 'actorId' | 'search' | 'host' | 'handles'> & { | |
521 | start: number | |
522 | count: number | |
523 | sort: string | |
524 | }) { | |
525 | let attributesInclude: any[] = [ literal('0 as similarity') ] | |
526 | let where: WhereOptions | |
527 | ||
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 = { | |
534 | [Op.or]: [ | |
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 + '))' | |
540 | ) | |
541 | ] | |
542 | } | |
543 | } | |
544 | ||
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 | ||
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 })) | |
571 | } | |
572 | ||
573 | static listByAccountForAPI (options: { | |
574 | accountId: number | |
575 | start: number | |
576 | count: number | |
577 | sort: string | |
578 | withStats?: boolean | |
579 | search?: string | |
580 | }) { | |
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 | ||
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 | } | |
616 | } | |
617 | ||
618 | const findScopes: string | ScopeOptions | (string | ScopeOptions)[] = [ ScopeNames.WITH_ACTOR_BANNER ] | |
619 | ||
620 | if (options.withStats === true) { | |
621 | findScopes.push({ | |
622 | method: [ ScopeNames.WITH_STATS, { daysPrior: 30 } as AvailableWithStatsOptions ] | |
623 | }) | |
624 | } | |
625 | ||
626 | return Promise.all([ | |
627 | VideoChannelModel.unscoped().count(getQuery(true)), | |
628 | VideoChannelModel.scope(findScopes).findAll(getQuery(false)) | |
629 | ]).then(([ total, data ]) => ({ total, data })) | |
630 | } | |
631 | ||
632 | static listAllByAccount (accountId: number): Promise<MChannel[]> { | |
633 | const query = { | |
634 | limit: CONFIG.VIDEO_CHANNELS.MAX_PER_USER, | |
635 | include: [ | |
636 | { | |
637 | attributes: [], | |
638 | model: AccountModel.unscoped(), | |
639 | where: { | |
640 | id: accountId | |
641 | }, | |
642 | required: true | |
643 | } | |
644 | ] | |
645 | } | |
646 | ||
647 | return VideoChannelModel.findAll(query) | |
648 | } | |
649 | ||
650 | static loadAndPopulateAccount (id: number, transaction?: Transaction): Promise<MChannelBannerAccountDefault> { | |
651 | return VideoChannelModel.unscoped() | |
652 | .scope([ ScopeNames.WITH_ACTOR_BANNER, ScopeNames.WITH_ACCOUNT ]) | |
653 | .findByPk(id, { transaction }) | |
654 | } | |
655 | ||
656 | static loadByUrlAndPopulateAccount (url: string): Promise<MChannelBannerAccountDefault> { | |
657 | const query = { | |
658 | include: [ | |
659 | { | |
660 | model: ActorModel, | |
661 | required: true, | |
662 | where: { | |
663 | url | |
664 | }, | |
665 | include: [ | |
666 | { | |
667 | model: ActorImageModel, | |
668 | required: false, | |
669 | as: 'Banners' | |
670 | } | |
671 | ] | |
672 | } | |
673 | ] | |
674 | } | |
675 | ||
676 | return VideoChannelModel | |
677 | .scope([ ScopeNames.WITH_ACCOUNT ]) | |
678 | .findOne(query) | |
679 | } | |
680 | ||
681 | static loadByNameWithHostAndPopulateAccount (nameWithHost: string) { | |
682 | const [ name, host ] = nameWithHost.split('@') | |
683 | ||
684 | if (!host || host === WEBSERVER.HOST) return VideoChannelModel.loadLocalByNameAndPopulateAccount(name) | |
685 | ||
686 | return VideoChannelModel.loadByNameAndHostAndPopulateAccount(name, host) | |
687 | } | |
688 | ||
689 | static loadLocalByNameAndPopulateAccount (name: string): Promise<MChannelBannerAccountDefault> { | |
690 | const query = { | |
691 | include: [ | |
692 | { | |
693 | model: ActorModel, | |
694 | required: true, | |
695 | where: { | |
696 | preferredUsername: name, | |
697 | serverId: null | |
698 | }, | |
699 | include: [ | |
700 | { | |
701 | model: ActorImageModel, | |
702 | required: false, | |
703 | as: 'Banners' | |
704 | } | |
705 | ] | |
706 | } | |
707 | ] | |
708 | } | |
709 | ||
710 | return VideoChannelModel.unscoped() | |
711 | .scope([ ScopeNames.WITH_ACCOUNT ]) | |
712 | .findOne(query) | |
713 | } | |
714 | ||
715 | static loadByNameAndHostAndPopulateAccount (name: string, host: string): Promise<MChannelBannerAccountDefault> { | |
716 | const query = { | |
717 | include: [ | |
718 | { | |
719 | model: ActorModel, | |
720 | required: true, | |
721 | where: { | |
722 | preferredUsername: name | |
723 | }, | |
724 | include: [ | |
725 | { | |
726 | model: ServerModel, | |
727 | required: true, | |
728 | where: { host } | |
729 | }, | |
730 | { | |
731 | model: ActorImageModel, | |
732 | required: false, | |
733 | as: 'Banners' | |
734 | } | |
735 | ] | |
736 | } | |
737 | ] | |
738 | } | |
739 | ||
740 | return VideoChannelModel.unscoped() | |
741 | .scope([ ScopeNames.WITH_ACCOUNT ]) | |
742 | .findOne(query) | |
743 | } | |
744 | ||
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, | |
754 | avatars: actor.avatars, | |
755 | ||
756 | // TODO: remove, deprecated in 4.2 | |
757 | avatar: actor.avatar | |
758 | } | |
759 | } | |
760 | ||
761 | toFormattedJSON (this: MChannelFormattable): VideoChannel { | |
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 | } | |
778 | ||
779 | const totalViews = this.get('totalViews') as number | |
780 | ||
781 | const actor = this.Actor.toFormattedJSON() | |
782 | const videoChannel = { | |
783 | id: this.id, | |
784 | displayName: this.getDisplayName(), | |
785 | description: this.description, | |
786 | support: this.support, | |
787 | isLocal: this.Actor.isOwned(), | |
788 | updatedAt: this.updatedAt, | |
789 | ||
790 | ownerAccount: undefined, | |
791 | ||
792 | videosCount, | |
793 | viewsPerDay, | |
794 | totalViews, | |
795 | ||
796 | avatars: actor.avatars, | |
797 | ||
798 | // TODO: remove, deprecated in 4.2 | |
799 | avatar: actor.avatar | |
800 | } | |
801 | ||
802 | if (this.Account) videoChannel.ownerAccount = this.Account.toFormattedJSON() | |
803 | ||
804 | return Object.assign(actor, videoChannel) | |
805 | } | |
806 | ||
807 | toActivityPubObject (this: MChannelAP): ActivityPubActor { | |
808 | const obj = this.Actor.toActivityPubObject(this.name) | |
809 | ||
810 | return Object.assign(obj, { | |
811 | summary: this.description, | |
812 | support: this.support, | |
813 | attributedTo: [ | |
814 | { | |
815 | type: 'Person' as 'Person', | |
816 | id: this.Account.Actor.url | |
817 | } | |
818 | ] | |
819 | }) | |
820 | } | |
821 | ||
822 | getLocalUrl (this: MAccountActor | MChannelActor) { | |
823 | return WEBSERVER.URL + `/video-channels/` + this.Actor.preferredUsername | |
824 | } | |
825 | ||
826 | getDisplayName () { | |
827 | return this.name | |
828 | } | |
829 | ||
830 | isOutdated () { | |
831 | return this.Actor.isOutdated() | |
832 | } | |
833 | ||
834 | setAsUpdated (transaction?: Transaction) { | |
835 | return setAsUpdated('videoChannel', this.id, transaction) | |
836 | } | |
837 | } |