]>
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 { forceNumber, 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 = forceNumber(options.daysPrior) | |
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 getLocalVideoChannelStats (days?: number) { | |
438 | const options = { | |
439 | type: QueryTypes.SELECT as QueryTypes.SELECT, | |
440 | raw: true | |
441 | } | |
442 | ||
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 | ||
448 | const query = ` | |
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` | |
455 | ||
456 | return VideoChannelModel.sequelize.query<{ count: string }>(query, options) | |
457 | .then(r => parseInt(r[0].count, 10)) | |
458 | } | |
459 | ||
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) | |
465 | ||
466 | return { | |
467 | totalLocalVideoChannels, | |
468 | totalLocalDailyActiveVideoChannels, | |
469 | totalLocalWeeklyActiveVideoChannels, | |
470 | totalLocalMonthlyActiveVideoChannels, | |
471 | totalLocalHalfYearActiveVideoChannels | |
472 | } | |
473 | } | |
474 | ||
475 | static listLocalsForSitemap (sort: string): Promise<MChannelActor[]> { | |
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 | ||
496 | static listForApi (parameters: Pick<AvailableForListOptions, 'actorId'> & { | |
497 | start: number | |
498 | count: number | |
499 | sort: string | |
500 | }) { | |
501 | const { actorId } = parameters | |
502 | ||
503 | const query = { | |
504 | offset: parameters.start, | |
505 | limit: parameters.count, | |
506 | order: getSort(parameters.sort) | |
507 | } | |
508 | ||
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 })) | |
517 | } | |
518 | ||
519 | static searchForApi (options: Pick<AvailableForListOptions, 'actorId' | 'search' | 'host' | 'handles'> & { | |
520 | start: number | |
521 | count: number | |
522 | sort: string | |
523 | }) { | |
524 | let attributesInclude: any[] = [ literal('0 as similarity') ] | |
525 | let where: WhereOptions | |
526 | ||
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 = { | |
533 | [Op.or]: [ | |
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 + '))' | |
539 | ) | |
540 | ] | |
541 | } | |
542 | } | |
543 | ||
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 | ||
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 })) | |
570 | } | |
571 | ||
572 | static listByAccountForAPI (options: { | |
573 | accountId: number | |
574 | start: number | |
575 | count: number | |
576 | sort: string | |
577 | withStats?: boolean | |
578 | search?: string | |
579 | }) { | |
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 | ||
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 | } | |
615 | } | |
616 | ||
617 | const findScopes: string | ScopeOptions | (string | ScopeOptions)[] = [ ScopeNames.WITH_ACTOR_BANNER ] | |
618 | ||
619 | if (options.withStats === true) { | |
620 | findScopes.push({ | |
621 | method: [ ScopeNames.WITH_STATS, { daysPrior: 30 } as AvailableWithStatsOptions ] | |
622 | }) | |
623 | } | |
624 | ||
625 | return Promise.all([ | |
626 | VideoChannelModel.unscoped().count(getQuery(true)), | |
627 | VideoChannelModel.scope(findScopes).findAll(getQuery(false)) | |
628 | ]).then(([ total, data ]) => ({ total, data })) | |
629 | } | |
630 | ||
631 | static listAllByAccount (accountId: number): Promise<MChannel[]> { | |
632 | const query = { | |
633 | limit: CONFIG.VIDEO_CHANNELS.MAX_PER_USER, | |
634 | include: [ | |
635 | { | |
636 | attributes: [], | |
637 | model: AccountModel.unscoped(), | |
638 | where: { | |
639 | id: accountId | |
640 | }, | |
641 | required: true | |
642 | } | |
643 | ] | |
644 | } | |
645 | ||
646 | return VideoChannelModel.findAll(query) | |
647 | } | |
648 | ||
649 | static loadAndPopulateAccount (id: number, transaction?: Transaction): Promise<MChannelBannerAccountDefault> { | |
650 | return VideoChannelModel.unscoped() | |
651 | .scope([ ScopeNames.WITH_ACTOR_BANNER, ScopeNames.WITH_ACCOUNT ]) | |
652 | .findByPk(id, { transaction }) | |
653 | } | |
654 | ||
655 | static loadByUrlAndPopulateAccount (url: string): Promise<MChannelBannerAccountDefault> { | |
656 | const query = { | |
657 | include: [ | |
658 | { | |
659 | model: ActorModel, | |
660 | required: true, | |
661 | where: { | |
662 | url | |
663 | }, | |
664 | include: [ | |
665 | { | |
666 | model: ActorImageModel, | |
667 | required: false, | |
668 | as: 'Banners' | |
669 | } | |
670 | ] | |
671 | } | |
672 | ] | |
673 | } | |
674 | ||
675 | return VideoChannelModel | |
676 | .scope([ ScopeNames.WITH_ACCOUNT ]) | |
677 | .findOne(query) | |
678 | } | |
679 | ||
680 | static loadByNameWithHostAndPopulateAccount (nameWithHost: string) { | |
681 | const [ name, host ] = nameWithHost.split('@') | |
682 | ||
683 | if (!host || host === WEBSERVER.HOST) return VideoChannelModel.loadLocalByNameAndPopulateAccount(name) | |
684 | ||
685 | return VideoChannelModel.loadByNameAndHostAndPopulateAccount(name, host) | |
686 | } | |
687 | ||
688 | static loadLocalByNameAndPopulateAccount (name: string): Promise<MChannelBannerAccountDefault> { | |
689 | const query = { | |
690 | include: [ | |
691 | { | |
692 | model: ActorModel, | |
693 | required: true, | |
694 | where: { | |
695 | preferredUsername: name, | |
696 | serverId: null | |
697 | }, | |
698 | include: [ | |
699 | { | |
700 | model: ActorImageModel, | |
701 | required: false, | |
702 | as: 'Banners' | |
703 | } | |
704 | ] | |
705 | } | |
706 | ] | |
707 | } | |
708 | ||
709 | return VideoChannelModel.unscoped() | |
710 | .scope([ ScopeNames.WITH_ACCOUNT ]) | |
711 | .findOne(query) | |
712 | } | |
713 | ||
714 | static loadByNameAndHostAndPopulateAccount (name: string, host: string): Promise<MChannelBannerAccountDefault> { | |
715 | const query = { | |
716 | include: [ | |
717 | { | |
718 | model: ActorModel, | |
719 | required: true, | |
720 | where: { | |
721 | preferredUsername: name | |
722 | }, | |
723 | include: [ | |
724 | { | |
725 | model: ServerModel, | |
726 | required: true, | |
727 | where: { host } | |
728 | }, | |
729 | { | |
730 | model: ActorImageModel, | |
731 | required: false, | |
732 | as: 'Banners' | |
733 | } | |
734 | ] | |
735 | } | |
736 | ] | |
737 | } | |
738 | ||
739 | return VideoChannelModel.unscoped() | |
740 | .scope([ ScopeNames.WITH_ACCOUNT ]) | |
741 | .findOne(query) | |
742 | } | |
743 | ||
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, | |
753 | avatars: actor.avatars, | |
754 | ||
755 | // TODO: remove, deprecated in 4.2 | |
756 | avatar: actor.avatar | |
757 | } | |
758 | } | |
759 | ||
760 | toFormattedJSON (this: MChannelFormattable): VideoChannel { | |
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 | } | |
777 | ||
778 | const totalViews = this.get('totalViews') as number | |
779 | ||
780 | const actor = this.Actor.toFormattedJSON() | |
781 | const videoChannel = { | |
782 | id: this.id, | |
783 | displayName: this.getDisplayName(), | |
784 | description: this.description, | |
785 | support: this.support, | |
786 | isLocal: this.Actor.isOwned(), | |
787 | updatedAt: this.updatedAt, | |
788 | ||
789 | ownerAccount: undefined, | |
790 | ||
791 | videosCount, | |
792 | viewsPerDay, | |
793 | totalViews, | |
794 | ||
795 | avatars: actor.avatars, | |
796 | ||
797 | // TODO: remove, deprecated in 4.2 | |
798 | avatar: actor.avatar | |
799 | } | |
800 | ||
801 | if (this.Account) videoChannel.ownerAccount = this.Account.toFormattedJSON() | |
802 | ||
803 | return Object.assign(actor, videoChannel) | |
804 | } | |
805 | ||
806 | toActivityPubObject (this: MChannelAP): ActivityPubActor { | |
807 | const obj = this.Actor.toActivityPubObject(this.name) | |
808 | ||
809 | return Object.assign(obj, { | |
810 | summary: this.description, | |
811 | support: this.support, | |
812 | attributedTo: [ | |
813 | { | |
814 | type: 'Person' as 'Person', | |
815 | id: this.Account.Actor.url | |
816 | } | |
817 | ] | |
818 | }) | |
819 | } | |
820 | ||
821 | getLocalUrl (this: MAccountActor | MChannelActor) { | |
822 | return WEBSERVER.URL + `/video-channels/` + this.Actor.preferredUsername | |
823 | } | |
824 | ||
825 | getDisplayName () { | |
826 | return this.name | |
827 | } | |
828 | ||
829 | isOutdated () { | |
830 | return this.Actor.isOutdated() | |
831 | } | |
832 | ||
833 | setAsUpdated (transaction?: Transaction) { | |
834 | return setAsUpdated('videoChannel', this.id, transaction) | |
835 | } | |
836 | } |