X-Git-Url: https://git.immae.eu/?a=blobdiff_plain;f=server%2Fmodels%2Fvideo%2Fvideo-channel.ts;h=410fd6d3f777c4e15c2bb0f509eb2012eb0210de;hb=d0800f7661f13fabe7bb6f4aa0ea50764f106405;hp=d2a055f5b0884362f3d581a5c11775d01b37081c;hpb=dc48fdbe68e9dd3a3a6028181e61d8595d98e654;p=github%2FChocobozzz%2FPeerTube.git diff --git a/server/models/video/video-channel.ts b/server/models/video/video-channel.ts index d2a055f5b..410fd6d3f 100644 --- a/server/models/video/video-channel.ts +++ b/server/models/video/video-channel.ts @@ -1,4 +1,4 @@ -import { FindOptions, Includeable, literal, Op, ScopeOptions } from 'sequelize' +import { FindOptions, Includeable, literal, Op, QueryTypes, ScopeOptions, Transaction, WhereOptions } from 'sequelize' import { AllowNull, BeforeDestroy, @@ -17,17 +17,21 @@ import { Table, UpdatedAt } from 'sequelize-typescript' +import { CONFIG } from '@server/initializers/config' import { MAccountActor } from '@server/types/models' +import { pick } from '@shared/core-utils' +import { AttributesOnly } from '@shared/typescript-utils' import { ActivityPubActor } from '../../../shared/models/activitypub' import { VideoChannel, VideoChannelSummary } from '../../../shared/models/videos' import { isVideoChannelDescriptionValid, - isVideoChannelNameValid, + isVideoChannelDisplayNameValid, isVideoChannelSupportValid } from '../../helpers/custom-validators/video-channels' import { CONSTRAINTS_FIELDS, WEBSERVER } from '../../initializers/constants' import { sendDeleteActor } from '../../lib/activitypub/send' import { + MChannel, MChannelActor, MChannelAP, MChannelBannerAccountDefault, @@ -35,10 +39,11 @@ import { MChannelSummaryFormattable } from '../../types/models/video' import { AccountModel, ScopeNames as AccountModelScopeNames, SummaryOptions as AccountSummaryOptions } from '../account/account' -import { ActorImageModel } from '../account/actor-image' -import { ActorModel, unusedActorAttributesForAPI } from '../activitypub/actor' -import { ActorFollowModel } from '../activitypub/actor-follow' +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' @@ -56,6 +61,9 @@ export enum ScopeNames { type AvailableForListOptions = { actorId: number search?: string + host?: string + handles?: string[] + forCount?: boolean } type AvailableWithStatsOptions = { @@ -81,43 +89,120 @@ export type SummaryOptions = { // 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 + }) + } + + if (Array.isArray(options.handles) && options.handles.length !== 0) { + const or: string[] = [] + + for (const handle of options.handles || []) { + const [ preferredUsername, host ] = handle.split('@') + + if (!host || host === WEBSERVER.HOST) { + or.push(`("preferredUsername" = ${VideoChannelModel.sequelize.escape(preferredUsername)} AND "serverId" IS NULL)`) + } else { + or.push( + `(` + + `"preferredUsername" = ${VideoChannelModel.sequelize.escape(preferredUsername)} ` + + `AND "host" = ${VideoChannelModel.sequelize.escape(host)}` + + `)` + ) + } + } + + whereActorAnd.push({ + id: { + [Op.in]: literal(`(SELECT "actor".id FROM actor LEFT JOIN server on server.id = actor."serverId" WHERE ${or.join(' OR ')})`) + } + }) + } + + const channelInclude: Includeable[] = [] + const accountInclude: Includeable[] = [] + + if (options.forCount !== true) { + accountInclude.push({ + model: ServerModel, + required: false + }) + + accountInclude.push({ + model: ActorImageModel, + as: 'Avatars', + required: false + }) + + channelInclude.push({ + model: ActorImageModel, + as: 'Avatars', + required: false + }) + + channelInclude.push({ + model: ActorImageModel, + as: 'Banners', + required: false + }) + } + + if (options.forCount !== true || serverRequired) { + channelInclude.push({ + model: ServerModel, + duplicating: false, + required: serverRequired, + where: whereServer + }) + } + return { include: [ { attributes: { exclude: unusedActorAttributesForAPI }, - model: ActorModel, + model: ActorModel.unscoped(), where: { - [Op.or]: [ - { - serverId: null - }, - { - serverId: { - [Op.in]: Sequelize.literal(inQueryInstanceFollow) - } - } - ] + [Op.and]: whereActorAnd }, - include: [ - { - model: ActorImageModel, - as: 'Banner', - required: false - } - ] + include: channelInclude }, { - model: AccountModel, + model: AccountModel.unscoped(), required: true, include: [ { attributes: { exclude: unusedActorAttributesForAPI }, - model: ActorModel, // Default scope includes avatar and server - required: true + model: ActorModel.unscoped(), + required: true, + include: accountInclude } ] } @@ -127,7 +212,7 @@ export type SummaryOptions = { [ScopeNames.SUMMARY]: (options: SummaryOptions = {}) => { const include: Includeable[] = [ { - attributes: [ 'id', 'preferredUsername', 'url', 'serverId', 'avatarId' ], + attributes: [ 'id', 'preferredUsername', 'url', 'serverId' ], model: ActorModel.unscoped(), required: options.actorRequired ?? true, include: [ @@ -137,8 +222,8 @@ export type SummaryOptions = { required: false }, { - model: ActorImageModel.unscoped(), - as: 'Avatar', + model: ActorImageModel, + as: 'Avatars', required: false } ] @@ -183,7 +268,7 @@ export type SummaryOptions = { { model: ActorImageModel, required: false, - as: 'Banner' + as: 'Banners' } ] } @@ -245,10 +330,10 @@ export type SummaryOptions = { } ] }) -export class VideoChannelModel extends Model { +export class VideoChannelModel extends Model>> { @AllowNull(false) - @Is('VideoChannelName', value => throwIfNotValid(value, isVideoChannelNameValid, 'name')) + @Is('VideoChannelName', value => throwIfNotValid(value, isVideoChannelDisplayNameValid, 'name')) @Column name: string @@ -289,8 +374,7 @@ export class VideoChannelModel extends Model { @BelongsTo(() => AccountModel, { foreignKey: { allowNull: false - }, - hooks: true + } }) Account: AccountModel @@ -338,28 +422,45 @@ export class VideoChannelModel extends Model { return VideoChannelModel.count(query) } - static listForApi (parameters: { - actorId: number - start: number - count: number - sort: string - }) { - const { actorId } = parameters + static async getStats () { - const query = { - offset: parameters.start, - limit: parameters.count, - order: getSort(parameters.sort) + 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)) } - return VideoChannelModel - .scope({ - method: [ ScopeNames.FOR_API, { actorId } as AvailableForListOptions ] - }) - .findAndCountAll(query) - .then(({ rows, count }) => { - return { total: count, data: rows } - }) + 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 { @@ -383,26 +484,43 @@ export class VideoChannelModel extends Model { .findAll(query) } - static searchForApi (options: { - actorId: number - search: string + static listForApi (parameters: Pick & { start: number count: number sort: string }) { - const attributesInclude = [] - const escapedSearch = VideoModel.sequelize.escape(options.search) - const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%') - attributesInclude.push(createSimilarityAttribute('VideoChannelModel.name', options.search)) + const { actorId } = parameters const query = { - attributes: { - include: attributesInclude - }, - offset: options.start, - limit: options.count, - order: getSort(options.sort), - where: { + offset: parameters.start, + limit: parameters.count, + order: getSort(parameters.sort) + } + + const getScope = (forCount: boolean) => { + return { method: [ ScopeNames.FOR_API, { actorId, forCount } as AvailableForListOptions ] } + } + + return Promise.all([ + VideoChannelModel.scope(getScope(true)).count(), + VideoChannelModel.scope(getScope(false)).findAll(query) + ]).then(([ total, data ]) => ({ total, data })) + } + + static searchForApi (options: Pick & { + 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 + '))' @@ -414,17 +532,35 @@ export class VideoChannelModel extends Model { } } - return VideoChannelModel - .scope({ - method: [ ScopeNames.FOR_API, { actorId: options.actorId } as AvailableForListOptions ] - }) - .findAndCountAll(query) - .then(({ rows, count }) => { - return { total: count, data: rows } - }) + const query = { + attributes: { + include: attributesInclude + }, + offset: options.start, + limit: options.count, + order: getSort(options.sort), + where + } + + const getScope = (forCount: boolean) => { + return { + method: [ + ScopeNames.FOR_API, { + ...pick(options, [ 'actorId', 'host', 'handles' ]), + + forCount + } as AvailableForListOptions + ] + } + } + + return Promise.all([ + VideoChannelModel.scope(getScope(true)).count(query), + VideoChannelModel.scope(getScope(false)).findAll(query) + ]).then(([ total, data ]) => ({ total, data })) } - static listByAccount (options: { + static listByAccountForAPI (options: { accountId: number start: number count: number @@ -447,20 +583,26 @@ export class VideoChannelModel extends Model { } : null - const query = { - offset: options.start, - limit: options.count, - order: getSort(options.sort), - include: [ - { - model: AccountModel, - where: { - id: options.accountId - }, - required: true - } - ], - where + const getQuery = (forCount: boolean) => { + const accountModel = forCount + ? AccountModel.unscoped() + : AccountModel + + return { + 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 ] @@ -471,18 +613,34 @@ export class VideoChannelModel extends Model { }) } - return VideoChannelModel - .scope(scopes) - .findAndCountAll(query) - .then(({ rows, count }) => { - return { total: count, data: rows } - }) + return Promise.all([ + VideoChannelModel.scope(scopes).count(getQuery(true)), + VideoChannelModel.scope(scopes).findAll(getQuery(false)) + ]).then(([ total, data ]) => ({ total, data })) + } + + static listAllByAccount (accountId: number): Promise { + const query = { + limit: CONFIG.VIDEO_CHANNELS.MAX_PER_USER, + include: [ + { + attributes: [], + model: AccountModel.unscoped(), + where: { + id: accountId + }, + required: true + } + ] + } + + return VideoChannelModel.findAll(query) } - static loadAndPopulateAccount (id: number): Promise { + static loadAndPopulateAccount (id: number, transaction?: Transaction): Promise { return VideoChannelModel.unscoped() .scope([ ScopeNames.WITH_ACTOR_BANNER, ScopeNames.WITH_ACCOUNT ]) - .findByPk(id) + .findByPk(id, { transaction }) } static loadByUrlAndPopulateAccount (url: string): Promise { @@ -498,7 +656,7 @@ export class VideoChannelModel extends Model { { model: ActorImageModel, required: false, - as: 'Banner' + as: 'Banners' } ] } @@ -532,7 +690,7 @@ export class VideoChannelModel extends Model { { model: ActorImageModel, required: false, - as: 'Banner' + as: 'Banners' } ] } @@ -562,7 +720,7 @@ export class VideoChannelModel extends Model { { model: ActorImageModel, required: false, - as: 'Banner' + as: 'Banners' } ] } @@ -583,6 +741,9 @@ export class VideoChannelModel extends Model { displayName: this.getDisplayName(), url: actor.url, host: actor.host, + avatars: actor.avatars, + + // TODO: remove, deprecated in 4.2 avatar: actor.avatar } } @@ -612,11 +773,17 @@ export class VideoChannelModel extends Model { description: this.description, support: this.support, isLocal: this.Actor.isOwned(), - createdAt: this.createdAt, updatedAt: this.updatedAt, + ownerAccount: undefined, + videosCount, - viewsPerDay + viewsPerDay, + + avatars: actor.avatars, + + // TODO: remove, deprecated in 4.2 + avatar: actor.avatar } if (this.Account) videoChannel.ownerAccount = this.Account.toFormattedJSON() @@ -650,4 +817,8 @@ export class VideoChannelModel extends Model { isOutdated () { return this.Actor.isOutdated() } + + setAsUpdated (transaction?: Transaction) { + return setAsUpdated('videoChannel', this.id, transaction) + } }