Merge tag 'tags/upstream/2024.8.1'
This commit is contained in:
commit
91ec6c3a14
1105 changed files with 55244 additions and 26173 deletions
|
@ -33,7 +33,7 @@ import { UtilityService } from '@/core/UtilityService.js';
|
|||
import { UserEntityService } from '@/core/entities/UserEntityService.js';
|
||||
import { bindThis } from '@/decorators.js';
|
||||
import { IActivity } from '@/core/activitypub/type.js';
|
||||
import { isPureRenote } from '@/misc/is-pure-renote.js';
|
||||
import { isQuote, isRenote } from '@/misc/is-renote.js';
|
||||
import type { FastifyInstance, FastifyRequest, FastifyReply, FastifyPluginOptions, FastifyBodyParser } from 'fastify';
|
||||
import type { FindOptionsWhere } from 'typeorm';
|
||||
import type Logger from '@/logger.js';
|
||||
|
@ -107,7 +107,7 @@ export class ActivityPubServerService {
|
|||
*/
|
||||
@bindThis
|
||||
private async packActivity(note: MiNote): Promise<any> {
|
||||
if (isPureRenote(note)) {
|
||||
if (isRenote(note) && !isQuote(note)) {
|
||||
const renote = await this.notesRepository.findOneByOrFail({ id: note.renoteId });
|
||||
return this.apRendererService.renderAnnounce(renote.uri ? renote.uri : `${this.config.url}/notes/${renote.id}`, note);
|
||||
}
|
||||
|
|
|
@ -53,7 +53,7 @@ export class FileServerService {
|
|||
private internalStorageService: InternalStorageService,
|
||||
private loggerService: LoggerService,
|
||||
) {
|
||||
this.logger = this.loggerService.getLogger('server', 'gray', false);
|
||||
this.logger = this.loggerService.getLogger('server', 'gray');
|
||||
|
||||
//this.createServer = this.createServer.bind(this);
|
||||
}
|
||||
|
@ -212,6 +212,8 @@ export class FileServerService {
|
|||
}
|
||||
|
||||
reply.header('Content-Type', FILE_TYPE_BROWSERSAFE.includes(image.type) ? image.type : 'application/octet-stream');
|
||||
reply.header('Content-Length', file.file.size);
|
||||
reply.header('Cache-Control', 'max-age=31536000, immutable');
|
||||
reply.header('Content-Disposition',
|
||||
contentDisposition(
|
||||
'inline',
|
||||
|
@ -254,6 +256,7 @@ export class FileServerService {
|
|||
return fs.createReadStream(file.path);
|
||||
} else {
|
||||
reply.header('Content-Type', FILE_TYPE_BROWSERSAFE.includes(file.file.type) ? file.file.type : 'application/octet-stream');
|
||||
reply.header('Content-Length', file.file.size);
|
||||
reply.header('Cache-Control', 'max-age=31536000, immutable');
|
||||
reply.header('Content-Disposition', contentDisposition('inline', file.filename));
|
||||
|
||||
|
@ -528,9 +531,7 @@ export class FileServerService {
|
|||
if (!file.storedInternal) {
|
||||
if (!(file.isLink && file.uri)) return '204';
|
||||
const result = await this.downloadAndDetectTypeFromUrl(file.uri);
|
||||
if (!file.size) {
|
||||
file.size = (await fs.promises.stat(result.path)).size;
|
||||
}
|
||||
file.size = (await fs.promises.stat(result.path)).size; // DB file.sizeは正確とは限らないので
|
||||
return {
|
||||
...result,
|
||||
url: file.uri,
|
||||
|
|
54
packages/backend/src/server/HealthServerService.ts
Normal file
54
packages/backend/src/server/HealthServerService.ts
Normal file
|
@ -0,0 +1,54 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: syuilo and misskey-project
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import * as Redis from 'ioredis';
|
||||
import { DataSource } from 'typeorm';
|
||||
import { bindThis } from '@/decorators.js';
|
||||
import { DI } from '@/di-symbols.js';
|
||||
import { readyRef } from '@/boot/ready.js';
|
||||
import type { FastifyInstance, FastifyPluginOptions } from 'fastify';
|
||||
import type { MeiliSearch } from 'meilisearch';
|
||||
|
||||
@Injectable()
|
||||
export class HealthServerService {
|
||||
constructor(
|
||||
@Inject(DI.redis)
|
||||
private redis: Redis.Redis,
|
||||
|
||||
@Inject(DI.redisForPub)
|
||||
private redisForPub: Redis.Redis,
|
||||
|
||||
@Inject(DI.redisForSub)
|
||||
private redisForSub: Redis.Redis,
|
||||
|
||||
@Inject(DI.redisForTimelines)
|
||||
private redisForTimelines: Redis.Redis,
|
||||
|
||||
@Inject(DI.db)
|
||||
private db: DataSource,
|
||||
|
||||
@Inject(DI.meilisearch)
|
||||
private meilisearch: MeiliSearch | null,
|
||||
) {}
|
||||
|
||||
@bindThis
|
||||
public createServer(fastify: FastifyInstance, options: FastifyPluginOptions, done: (err?: Error) => void) {
|
||||
fastify.get('/', async (request, reply) => {
|
||||
reply.code(await Promise.all([
|
||||
new Promise<void>((resolve, reject) => readyRef.value ? resolve() : reject()),
|
||||
this.redis.ping(),
|
||||
this.redisForPub.ping(),
|
||||
this.redisForSub.ping(),
|
||||
this.redisForTimelines.ping(),
|
||||
this.db.query('SELECT 1'),
|
||||
...(this.meilisearch ? [this.meilisearch.health()] : []),
|
||||
]).then(() => 200, () => 503));
|
||||
reply.header('Cache-Control', 'no-store');
|
||||
});
|
||||
|
||||
done();
|
||||
}
|
||||
}
|
|
@ -36,12 +36,12 @@ export class NodeinfoServerService {
|
|||
@bindThis
|
||||
public getLinks() {
|
||||
return [{
|
||||
rel: 'http://nodeinfo.diaspora.software/ns/schema/2.1',
|
||||
href: this.config.url + nodeinfo2_1path
|
||||
}, {
|
||||
rel: 'http://nodeinfo.diaspora.software/ns/schema/2.0',
|
||||
href: this.config.url + nodeinfo2_0path,
|
||||
}];
|
||||
rel: 'http://nodeinfo.diaspora.software/ns/schema/2.1',
|
||||
href: this.config.url + nodeinfo2_1path,
|
||||
}, {
|
||||
rel: 'http://nodeinfo.diaspora.software/ns/schema/2.0',
|
||||
href: this.config.url + nodeinfo2_0path,
|
||||
}];
|
||||
}
|
||||
|
||||
@bindThis
|
||||
|
@ -107,6 +107,7 @@ export class NodeinfoServerService {
|
|||
langs: meta.langs,
|
||||
tosUrl: meta.termsOfServiceUrl,
|
||||
privacyPolicyUrl: meta.privacyPolicyUrl,
|
||||
inquiryUrl: meta.inquiryUrl,
|
||||
impressumUrl: meta.impressumUrl,
|
||||
donationUrl: meta.donationUrl,
|
||||
repositoryUrl: meta.repositoryUrl,
|
||||
|
@ -134,7 +135,7 @@ export class NodeinfoServerService {
|
|||
return document;
|
||||
};
|
||||
|
||||
const cache = new MemorySingleCache<Awaited<ReturnType<typeof nodeinfo2>>>(1000 * 60 * 10);
|
||||
const cache = new MemorySingleCache<Awaited<ReturnType<typeof nodeinfo2>>>(1000 * 60 * 10); // 10m
|
||||
|
||||
fastify.get(nodeinfo2_1path, async (request, reply) => {
|
||||
const base = await cache.fetch(() => nodeinfo2(21));
|
||||
|
|
|
@ -8,6 +8,7 @@ import { EndpointsModule } from '@/server/api/EndpointsModule.js';
|
|||
import { CoreModule } from '@/core/CoreModule.js';
|
||||
import { ApiCallService } from './api/ApiCallService.js';
|
||||
import { FileServerService } from './FileServerService.js';
|
||||
import { HealthServerService } from './HealthServerService.js';
|
||||
import { NodeinfoServerService } from './NodeinfoServerService.js';
|
||||
import { ServerService } from './ServerService.js';
|
||||
import { WellKnownServerService } from './WellKnownServerService.js';
|
||||
|
@ -58,6 +59,7 @@ import { ReversiGameChannelService } from './api/stream/channels/reversi-game.js
|
|||
ClientServerService,
|
||||
ClientLoggerService,
|
||||
FeedService,
|
||||
HealthServerService,
|
||||
UrlPreviewService,
|
||||
ActivityPubServerService,
|
||||
FileServerService,
|
||||
|
|
|
@ -18,7 +18,6 @@ import { DI } from '@/di-symbols.js';
|
|||
import type Logger from '@/logger.js';
|
||||
import * as Acct from '@/misc/acct.js';
|
||||
import { genIdenticon } from '@/misc/gen-identicon.js';
|
||||
import { createTemp } from '@/misc/create-temp.js';
|
||||
import { UserEntityService } from '@/core/entities/UserEntityService.js';
|
||||
import { LoggerService } from '@/core/LoggerService.js';
|
||||
import { bindThis } from '@/decorators.js';
|
||||
|
@ -29,6 +28,7 @@ import { ApiServerService } from './api/ApiServerService.js';
|
|||
import { StreamingApiServerService } from './api/StreamingApiServerService.js';
|
||||
import { WellKnownServerService } from './WellKnownServerService.js';
|
||||
import { FileServerService } from './FileServerService.js';
|
||||
import { HealthServerService } from './HealthServerService.js';
|
||||
import { ClientServerService } from './web/ClientServerService.js';
|
||||
import { OpenApiServerService } from './api/openapi/OpenApiServerService.js';
|
||||
import { MastodonApiServerService } from './api/mastodon/MastodonApiServerService.js';
|
||||
|
@ -64,12 +64,13 @@ export class ServerService implements OnApplicationShutdown {
|
|||
private wellKnownServerService: WellKnownServerService,
|
||||
private nodeinfoServerService: NodeinfoServerService,
|
||||
private fileServerService: FileServerService,
|
||||
private healthServerService: HealthServerService,
|
||||
private clientServerService: ClientServerService,
|
||||
private globalEventService: GlobalEventService,
|
||||
private loggerService: LoggerService,
|
||||
private oauth2ProviderService: OAuth2ProviderService,
|
||||
) {
|
||||
this.logger = this.loggerService.getLogger('server', 'gray', false);
|
||||
this.logger = this.loggerService.getLogger('server', 'gray');
|
||||
}
|
||||
|
||||
@bindThis
|
||||
|
@ -111,6 +112,7 @@ export class ServerService implements OnApplicationShutdown {
|
|||
fastify.register(this.nodeinfoServerService.createServer);
|
||||
fastify.register(this.wellKnownServerService.createServer);
|
||||
fastify.register(this.oauth2ProviderService.createServer, { prefix: '/oauth' });
|
||||
fastify.register(this.healthServerService.createServer, { prefix: '/healthz' });
|
||||
|
||||
fastify.get<{ Params: { path: string }; Querystring: { static?: any; badge?: any; }; }>('/emoji/:path(.*)', async (request, reply) => {
|
||||
const path = request.params.path;
|
||||
|
@ -122,12 +124,20 @@ export class ServerService implements OnApplicationShutdown {
|
|||
return;
|
||||
}
|
||||
|
||||
const name = path.split('@')[0].replace(/\.webp$/i, '');
|
||||
const host = path.split('@')[1]?.replace(/\.webp$/i, '');
|
||||
const emojiPath = path.replace(/\.webp$/i, '');
|
||||
const pathChunks = emojiPath.split('@');
|
||||
|
||||
if (pathChunks.length > 2) {
|
||||
reply.code(400);
|
||||
return;
|
||||
}
|
||||
|
||||
const name = pathChunks.shift();
|
||||
const host = pathChunks.pop();
|
||||
|
||||
const emoji = await this.emojisRepository.findOneBy({
|
||||
// `@.` is the spec of ReactionService.decodeReaction
|
||||
host: (host == null || host === '.') ? IsNull() : host,
|
||||
host: (host === undefined || host === '.') ? IsNull() : host,
|
||||
name: name,
|
||||
});
|
||||
|
||||
|
@ -186,9 +196,7 @@ export class ServerService implements OnApplicationShutdown {
|
|||
reply.header('Cache-Control', 'public, max-age=86400');
|
||||
|
||||
if ((await this.metaService.fetch()).enableIdenticonGeneration) {
|
||||
const [temp, cleanup] = await createTemp();
|
||||
await genIdenticon(request.params.x, fs.createWriteStream(temp));
|
||||
return fs.createReadStream(temp).on('close', () => cleanup());
|
||||
return await genIdenticon(request.params.x);
|
||||
} else {
|
||||
return reply.redirect('/static-assets/avatar.png');
|
||||
}
|
||||
|
|
|
@ -7,6 +7,7 @@ import { randomUUID } from 'node:crypto';
|
|||
import * as fs from 'node:fs';
|
||||
import * as stream from 'node:stream/promises';
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import * as Sentry from '@sentry/node';
|
||||
import { DI } from '@/di-symbols.js';
|
||||
import { getIpHash } from '@/misc/get-ip-hash.js';
|
||||
import type { MiLocalUser, MiUser } from '@/models/User.js';
|
||||
|
@ -17,6 +18,7 @@ import { MetaService } from '@/core/MetaService.js';
|
|||
import { createTemp } from '@/misc/create-temp.js';
|
||||
import { bindThis } from '@/decorators.js';
|
||||
import { RoleService } from '@/core/RoleService.js';
|
||||
import type { Config } from '@/config.js';
|
||||
import { ApiError } from './error.js';
|
||||
import { RateLimiterService } from './RateLimiterService.js';
|
||||
import { ApiLoggerService } from './ApiLoggerService.js';
|
||||
|
@ -72,6 +74,16 @@ export class ApiCallService implements OnApplicationShutdown {
|
|||
reply.header('WWW-Authenticate', `Bearer realm="Misskey", error="insufficient_scope", error_description="${err.message}"`);
|
||||
}
|
||||
statusCode = statusCode ?? 403;
|
||||
} else if (err.code === 'RATE_LIMIT_EXCEEDED') {
|
||||
const info: unknown = err.info;
|
||||
const unixEpochInSeconds = Date.now();
|
||||
if (typeof(info) === 'object' && info && 'resetMs' in info && typeof(info.resetMs) === 'number') {
|
||||
const cooldownInSeconds = Math.ceil((info.resetMs - unixEpochInSeconds) / 1000);
|
||||
// もしかするとマイナスになる可能性がなくはないのでマイナスだったら0にしておく
|
||||
reply.header('Retry-After', Math.max(cooldownInSeconds, 0).toString(10));
|
||||
} else {
|
||||
this.logger.warn(`rate limit information has unexpected type ${typeof(err.info?.reset)}`);
|
||||
}
|
||||
} else if (!statusCode) {
|
||||
statusCode = 500;
|
||||
}
|
||||
|
@ -92,6 +104,51 @@ export class ApiCallService implements OnApplicationShutdown {
|
|||
}
|
||||
}
|
||||
|
||||
#onExecError(ep: IEndpoint, data: any, err: Error, userId?: MiUser['id']): void {
|
||||
if (err instanceof ApiError || err instanceof AuthenticationError) {
|
||||
throw err;
|
||||
} else {
|
||||
const errId = randomUUID();
|
||||
this.logger.error(`Internal error occurred in ${ep.name}: ${err.message}`, {
|
||||
ep: ep.name,
|
||||
ps: data,
|
||||
e: {
|
||||
message: err.message,
|
||||
code: err.name,
|
||||
stack: err.stack,
|
||||
id: errId,
|
||||
},
|
||||
});
|
||||
|
||||
if (this.config.sentryForBackend) {
|
||||
Sentry.captureMessage(`Internal error occurred in ${ep.name}: ${err.message}`, {
|
||||
level: 'error',
|
||||
user: {
|
||||
id: userId,
|
||||
},
|
||||
extra: {
|
||||
ep: ep.name,
|
||||
ps: data,
|
||||
e: {
|
||||
message: err.message,
|
||||
code: err.name,
|
||||
stack: err.stack,
|
||||
id: errId,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
throw new ApiError(null, {
|
||||
e: {
|
||||
message: err.message,
|
||||
code: err.name,
|
||||
id: errId,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@bindThis
|
||||
public handleRequest(
|
||||
endpoint: IEndpoint & { exec: any },
|
||||
|
@ -262,12 +319,17 @@ export class ApiCallService implements OnApplicationShutdown {
|
|||
if (factor > 0) {
|
||||
// Rate limit
|
||||
await this.rateLimiterService.limit(limit as IEndpointMeta['limit'] & { key: NonNullable<string> }, limitActor, factor).catch(err => {
|
||||
throw new ApiError({
|
||||
message: 'Rate limit exceeded. Please try again later.',
|
||||
code: 'RATE_LIMIT_EXCEEDED',
|
||||
id: 'd5826d14-3982-4d2e-8011-b9e9f02499ef',
|
||||
httpStatusCode: 429,
|
||||
});
|
||||
if ('info' in err) {
|
||||
// errはLimiter.LimiterInfoであることが期待される
|
||||
throw new ApiError({
|
||||
message: 'Rate limit exceeded. Please try again later.',
|
||||
code: 'RATE_LIMIT_EXCEEDED',
|
||||
id: 'd5826d14-3982-4d2e-8011-b9e9f02499ef',
|
||||
httpStatusCode: 429,
|
||||
}, err.info);
|
||||
} else {
|
||||
throw new TypeError('information must be a rate-limiter information.');
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
@ -367,31 +429,15 @@ export class ApiCallService implements OnApplicationShutdown {
|
|||
}
|
||||
|
||||
// API invoking
|
||||
return await ep.exec(data, user, token, file, request.ip, request.headers).catch((err: Error) => {
|
||||
if (err instanceof ApiError || err instanceof AuthenticationError) {
|
||||
throw err;
|
||||
} else {
|
||||
const errId = randomUUID();
|
||||
this.logger.error(`Internal error occurred in ${ep.name}: ${err.message}`, {
|
||||
ep: ep.name,
|
||||
ps: data,
|
||||
e: {
|
||||
message: err.message,
|
||||
code: err.name,
|
||||
stack: err.stack,
|
||||
id: errId,
|
||||
},
|
||||
});
|
||||
console.error(err, errId);
|
||||
throw new ApiError(null, {
|
||||
e: {
|
||||
message: err.message,
|
||||
code: err.name,
|
||||
id: errId,
|
||||
},
|
||||
});
|
||||
}
|
||||
});
|
||||
if (this.config.sentryForBackend) {
|
||||
return await Sentry.startSpan({
|
||||
name: 'API: ' + ep.name,
|
||||
}, () => ep.exec(data, user, token, file, request.ip, request.headers)
|
||||
.catch((err: Error) => this.#onExecError(ep, data, err, user?.id)));
|
||||
} else {
|
||||
return await ep.exec(data, user, token, file, request.ip, request.headers)
|
||||
.catch((err: Error) => this.#onExecError(ep, data, err, user?.id));
|
||||
}
|
||||
}
|
||||
|
||||
@bindThis
|
||||
|
|
|
@ -137,7 +137,7 @@ export class ApiServerService {
|
|||
const instances = await this.instancesRepository.find({
|
||||
select: ['host'],
|
||||
where: {
|
||||
isSuspended: false,
|
||||
suspensionState: 'none',
|
||||
},
|
||||
});
|
||||
|
||||
|
|
|
@ -37,7 +37,7 @@ export class AuthenticateService implements OnApplicationShutdown {
|
|||
|
||||
private cacheService: CacheService,
|
||||
) {
|
||||
this.appCache = new MemoryKVCache<MiApp>(Infinity);
|
||||
this.appCache = new MemoryKVCache<MiApp>(1000 * 60 * 60 * 24 * 7); // 1w
|
||||
}
|
||||
|
||||
@bindThis
|
||||
|
|
|
@ -6,8 +6,13 @@
|
|||
import { Module } from '@nestjs/common';
|
||||
|
||||
import { CoreModule } from '@/core/CoreModule.js';
|
||||
import * as ep___admin_meta from './endpoints/admin/meta.js';
|
||||
import * as ep___admin_abuseReport_notificationRecipient_list from '@/server/api/endpoints/admin/abuse-report/notification-recipient/list.js';
|
||||
import * as ep___admin_abuseReport_notificationRecipient_show from '@/server/api/endpoints/admin/abuse-report/notification-recipient/show.js';
|
||||
import * as ep___admin_abuseReport_notificationRecipient_create from '@/server/api/endpoints/admin/abuse-report/notification-recipient/create.js';
|
||||
import * as ep___admin_abuseReport_notificationRecipient_update from '@/server/api/endpoints/admin/abuse-report/notification-recipient/update.js';
|
||||
import * as ep___admin_abuseReport_notificationRecipient_delete from '@/server/api/endpoints/admin/abuse-report/notification-recipient/delete.js';
|
||||
import * as ep___admin_abuseUserReports from './endpoints/admin/abuse-user-reports.js';
|
||||
import * as ep___admin_meta from './endpoints/admin/meta.js';
|
||||
import * as ep___admin_accounts_create from './endpoints/admin/accounts/create.js';
|
||||
import * as ep___admin_accounts_delete from './endpoints/admin/accounts/delete.js';
|
||||
import * as ep___admin_accounts_findByEmail from './endpoints/admin/accounts/find-by-email.js';
|
||||
|
@ -87,7 +92,13 @@ import * as ep___admin_roles_assign from './endpoints/admin/roles/assign.js';
|
|||
import * as ep___admin_roles_unassign from './endpoints/admin/roles/unassign.js';
|
||||
import * as ep___admin_roles_updateDefaultPolicies from './endpoints/admin/roles/update-default-policies.js';
|
||||
import * as ep___admin_roles_users from './endpoints/admin/roles/users.js';
|
||||
import * as ep___admin_systemWebhook_create from './endpoints/admin/system-webhook/create.js';
|
||||
import * as ep___admin_systemWebhook_delete from './endpoints/admin/system-webhook/delete.js';
|
||||
import * as ep___admin_systemWebhook_list from './endpoints/admin/system-webhook/list.js';
|
||||
import * as ep___admin_systemWebhook_show from './endpoints/admin/system-webhook/show.js';
|
||||
import * as ep___admin_systemWebhook_update from './endpoints/admin/system-webhook/update.js';
|
||||
import * as ep___announcements from './endpoints/announcements.js';
|
||||
import * as ep___announcements_show from './endpoints/announcements/show.js';
|
||||
import * as ep___antennas_create from './endpoints/antennas/create.js';
|
||||
import * as ep___antennas_delete from './endpoints/antennas/delete.js';
|
||||
import * as ep___antennas_list from './endpoints/antennas/list.js';
|
||||
|
@ -393,6 +404,11 @@ import type { Provider } from '@nestjs/common';
|
|||
|
||||
const $admin_meta: Provider = { provide: 'ep:admin/meta', useClass: ep___admin_meta.default };
|
||||
const $admin_abuseUserReports: Provider = { provide: 'ep:admin/abuse-user-reports', useClass: ep___admin_abuseUserReports.default };
|
||||
const $admin_abuseReport_notificationRecipient_list: Provider = { provide: 'ep:admin/abuse-report/notification-recipient/list', useClass: ep___admin_abuseReport_notificationRecipient_list.default };
|
||||
const $admin_abuseReport_notificationRecipient_show: Provider = { provide: 'ep:admin/abuse-report/notification-recipient/show', useClass: ep___admin_abuseReport_notificationRecipient_show.default };
|
||||
const $admin_abuseReport_notificationRecipient_create: Provider = { provide: 'ep:admin/abuse-report/notification-recipient/create', useClass: ep___admin_abuseReport_notificationRecipient_create.default };
|
||||
const $admin_abuseReport_notificationRecipient_update: Provider = { provide: 'ep:admin/abuse-report/notification-recipient/update', useClass: ep___admin_abuseReport_notificationRecipient_update.default };
|
||||
const $admin_abuseReport_notificationRecipient_delete: Provider = { provide: 'ep:admin/abuse-report/notification-recipient/delete', useClass: ep___admin_abuseReport_notificationRecipient_delete.default };
|
||||
const $admin_accounts_create: Provider = { provide: 'ep:admin/accounts/create', useClass: ep___admin_accounts_create.default };
|
||||
const $admin_accounts_delete: Provider = { provide: 'ep:admin/accounts/delete', useClass: ep___admin_accounts_delete.default };
|
||||
const $admin_accounts_findByEmail: Provider = { provide: 'ep:admin/accounts/find-by-email', useClass: ep___admin_accounts_findByEmail.default };
|
||||
|
@ -472,7 +488,13 @@ const $admin_roles_assign: Provider = { provide: 'ep:admin/roles/assign', useCla
|
|||
const $admin_roles_unassign: Provider = { provide: 'ep:admin/roles/unassign', useClass: ep___admin_roles_unassign.default };
|
||||
const $admin_roles_updateDefaultPolicies: Provider = { provide: 'ep:admin/roles/update-default-policies', useClass: ep___admin_roles_updateDefaultPolicies.default };
|
||||
const $admin_roles_users: Provider = { provide: 'ep:admin/roles/users', useClass: ep___admin_roles_users.default };
|
||||
const $admin_systemWebhook_create: Provider = { provide: 'ep:admin/system-webhook/create', useClass: ep___admin_systemWebhook_create.default };
|
||||
const $admin_systemWebhook_delete: Provider = { provide: 'ep:admin/system-webhook/delete', useClass: ep___admin_systemWebhook_delete.default };
|
||||
const $admin_systemWebhook_list: Provider = { provide: 'ep:admin/system-webhook/list', useClass: ep___admin_systemWebhook_list.default };
|
||||
const $admin_systemWebhook_show: Provider = { provide: 'ep:admin/system-webhook/show', useClass: ep___admin_systemWebhook_show.default };
|
||||
const $admin_systemWebhook_update: Provider = { provide: 'ep:admin/system-webhook/update', useClass: ep___admin_systemWebhook_update.default };
|
||||
const $announcements: Provider = { provide: 'ep:announcements', useClass: ep___announcements.default };
|
||||
const $announcements_show: Provider = { provide: 'ep:announcements/show', useClass: ep___announcements_show.default };
|
||||
const $antennas_create: Provider = { provide: 'ep:antennas/create', useClass: ep___antennas_create.default };
|
||||
const $antennas_delete: Provider = { provide: 'ep:antennas/delete', useClass: ep___antennas_delete.default };
|
||||
const $antennas_list: Provider = { provide: 'ep:antennas/list', useClass: ep___antennas_list.default };
|
||||
|
@ -782,6 +804,11 @@ const $reversi_verify: Provider = { provide: 'ep:reversi/verify', useClass: ep__
|
|||
ApiLoggerService,
|
||||
$admin_meta,
|
||||
$admin_abuseUserReports,
|
||||
$admin_abuseReport_notificationRecipient_list,
|
||||
$admin_abuseReport_notificationRecipient_show,
|
||||
$admin_abuseReport_notificationRecipient_create,
|
||||
$admin_abuseReport_notificationRecipient_update,
|
||||
$admin_abuseReport_notificationRecipient_delete,
|
||||
$admin_accounts_create,
|
||||
$admin_accounts_delete,
|
||||
$admin_accounts_findByEmail,
|
||||
|
@ -861,7 +888,13 @@ const $reversi_verify: Provider = { provide: 'ep:reversi/verify', useClass: ep__
|
|||
$admin_roles_unassign,
|
||||
$admin_roles_updateDefaultPolicies,
|
||||
$admin_roles_users,
|
||||
$admin_systemWebhook_create,
|
||||
$admin_systemWebhook_delete,
|
||||
$admin_systemWebhook_list,
|
||||
$admin_systemWebhook_show,
|
||||
$admin_systemWebhook_update,
|
||||
$announcements,
|
||||
$announcements_show,
|
||||
$antennas_create,
|
||||
$antennas_delete,
|
||||
$antennas_list,
|
||||
|
@ -1165,6 +1198,11 @@ const $reversi_verify: Provider = { provide: 'ep:reversi/verify', useClass: ep__
|
|||
exports: [
|
||||
$admin_meta,
|
||||
$admin_abuseUserReports,
|
||||
$admin_abuseReport_notificationRecipient_list,
|
||||
$admin_abuseReport_notificationRecipient_show,
|
||||
$admin_abuseReport_notificationRecipient_create,
|
||||
$admin_abuseReport_notificationRecipient_update,
|
||||
$admin_abuseReport_notificationRecipient_delete,
|
||||
$admin_accounts_create,
|
||||
$admin_accounts_delete,
|
||||
$admin_accounts_findByEmail,
|
||||
|
@ -1244,7 +1282,13 @@ const $reversi_verify: Provider = { provide: 'ep:reversi/verify', useClass: ep__
|
|||
$admin_roles_unassign,
|
||||
$admin_roles_updateDefaultPolicies,
|
||||
$admin_roles_users,
|
||||
$admin_systemWebhook_create,
|
||||
$admin_systemWebhook_delete,
|
||||
$admin_systemWebhook_list,
|
||||
$admin_systemWebhook_show,
|
||||
$admin_systemWebhook_update,
|
||||
$announcements,
|
||||
$announcements_show,
|
||||
$antennas_create,
|
||||
$antennas_delete,
|
||||
$antennas_list,
|
||||
|
|
|
@ -32,11 +32,18 @@ export class RateLimiterService {
|
|||
|
||||
@bindThis
|
||||
public limit(limitation: IEndpointMeta['limit'] & { key: NonNullable<string> }, actor: string, factor = 1) {
|
||||
return new Promise<void>((ok, reject) => {
|
||||
if (this.disabled) ok();
|
||||
{
|
||||
if (this.disabled) {
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
// those lines with the "wrong" brace style / indentation are
|
||||
// done that way so that the *other* lines stay identical to
|
||||
// Misskey, simplifying merges
|
||||
|
||||
// Short-term limit
|
||||
const min = (): void => {
|
||||
// eslint-disable-next-line brace-style
|
||||
const minP = () => { return new Promise<void>((ok, reject) => {
|
||||
const minIntervalLimiter = new Limiter({
|
||||
id: `${actor}:${limitation.key}:min`,
|
||||
duration: limitation.minInterval! * factor,
|
||||
|
@ -46,25 +53,27 @@ export class RateLimiterService {
|
|||
|
||||
minIntervalLimiter.get((err, info) => {
|
||||
if (err) {
|
||||
return reject('ERR');
|
||||
return reject({ code: 'ERR', info });
|
||||
}
|
||||
|
||||
this.logger.debug(`${actor} ${limitation.key} min remaining: ${info.remaining}`);
|
||||
|
||||
if (info.remaining === 0) {
|
||||
reject('BRIEF_REQUEST_INTERVAL');
|
||||
return reject({ code: 'BRIEF_REQUEST_INTERVAL', info });
|
||||
} else {
|
||||
if (hasLongTermLimit) {
|
||||
max();
|
||||
return maxP().then(ok, reject);
|
||||
} else {
|
||||
ok();
|
||||
return ok();
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
// eslint-disable-next-line brace-style
|
||||
}); };
|
||||
|
||||
// Long term limit
|
||||
const max = (): void => {
|
||||
// eslint-disable-next-line brace-style
|
||||
const maxP = () => { return new Promise<void>((ok, reject) => {
|
||||
const limiter = new Limiter({
|
||||
id: `${actor}:${limitation.key}`,
|
||||
duration: limitation.duration! * factor,
|
||||
|
@ -74,18 +83,19 @@ export class RateLimiterService {
|
|||
|
||||
limiter.get((err, info) => {
|
||||
if (err) {
|
||||
return reject('ERR');
|
||||
return reject({ code: 'ERR', info });
|
||||
}
|
||||
|
||||
this.logger.debug(`${actor} ${limitation.key} max remaining: ${info.remaining}`);
|
||||
|
||||
if (info.remaining === 0) {
|
||||
reject('RATE_LIMIT_EXCEEDED');
|
||||
return reject({ code: 'RATE_LIMIT_EXCEEDED', info });
|
||||
} else {
|
||||
ok();
|
||||
return ok();
|
||||
}
|
||||
});
|
||||
};
|
||||
// eslint-disable-next-line brace-style
|
||||
}); };
|
||||
|
||||
const hasShortTermLimit = typeof limitation.minInterval === 'number';
|
||||
|
||||
|
@ -94,12 +104,12 @@ export class RateLimiterService {
|
|||
typeof limitation.max === 'number';
|
||||
|
||||
if (hasShortTermLimit) {
|
||||
min();
|
||||
return minP();
|
||||
} else if (hasLongTermLimit) {
|
||||
max();
|
||||
return maxP();
|
||||
} else {
|
||||
ok();
|
||||
return Promise.resolve();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -29,13 +29,13 @@ export class SigninService {
|
|||
public signin(request: FastifyRequest, reply: FastifyReply, user: MiLocalUser) {
|
||||
setImmediate(async () => {
|
||||
// Append signin history
|
||||
const record = await this.signinsRepository.insert({
|
||||
const record = await this.signinsRepository.insertOne({
|
||||
id: this.idService.gen(),
|
||||
userId: user.id,
|
||||
ip: request.ip,
|
||||
headers: request.headers as any,
|
||||
success: true,
|
||||
}).then(x => this.signinsRepository.findOneByOrFail(x.identifiers[0]));
|
||||
});
|
||||
|
||||
// Publish signin event
|
||||
this.globalEventService.publishMainStream(user.id, 'signin', await this.signinEntityService.pack(record));
|
||||
|
|
|
@ -196,14 +196,14 @@ export class SignupApiService {
|
|||
//const salt = await bcrypt.genSalt(8);
|
||||
const hash = await argon2.hash(password);
|
||||
|
||||
const pendingUser = await this.userPendingsRepository.insert({
|
||||
const pendingUser = await this.userPendingsRepository.insertOne({
|
||||
id: this.idService.gen(),
|
||||
code,
|
||||
email: emailAddress!,
|
||||
username: username,
|
||||
password: hash,
|
||||
reason: reason,
|
||||
}).then(x => this.userPendingsRepository.findOneByOrFail(x.identifiers[0]));
|
||||
});
|
||||
|
||||
const link = `${this.config.url}/signup-complete/${code}`;
|
||||
|
||||
|
|
|
@ -19,7 +19,15 @@ import { ChannelFollowingService } from '@/core/ChannelFollowingService.js';
|
|||
import { AuthenticateService, AuthenticationError } from './AuthenticateService.js';
|
||||
import MainStreamConnection from './stream/Connection.js';
|
||||
import { ChannelsService } from './stream/ChannelsService.js';
|
||||
import { RateLimiterService } from './RateLimiterService.js';
|
||||
import { RoleService } from '@/core/RoleService.js';
|
||||
import { getIpHash } from '@/misc/get-ip-hash.js';
|
||||
import proxyAddr from 'proxy-addr';
|
||||
import ms from 'ms';
|
||||
import type * as http from 'node:http';
|
||||
import type { IEndpointMeta } from './endpoints.js';
|
||||
import { LoggerService } from '@/core/LoggerService.js';
|
||||
import type Logger from '@/logger.js';
|
||||
|
||||
@Injectable()
|
||||
export class StreamingApiServerService {
|
||||
|
@ -41,9 +49,35 @@ export class StreamingApiServerService {
|
|||
private notificationService: NotificationService,
|
||||
private usersService: UserService,
|
||||
private channelFollowingService: ChannelFollowingService,
|
||||
private rateLimiterService: RateLimiterService,
|
||||
private roleService: RoleService,
|
||||
private loggerService: LoggerService,
|
||||
) {
|
||||
}
|
||||
|
||||
@bindThis
|
||||
private async rateLimitThis(
|
||||
user: MiLocalUser | null | undefined,
|
||||
requestIp: string | undefined,
|
||||
limit: IEndpointMeta['limit'] & { key: NonNullable<string> },
|
||||
) : Promise<boolean> {
|
||||
let limitActor: string;
|
||||
if (user) {
|
||||
limitActor = user.id;
|
||||
} else {
|
||||
limitActor = getIpHash(requestIp || 'wtf');
|
||||
}
|
||||
|
||||
const factor = user ? (await this.roleService.getUserPolicies(user.id)).rateLimitFactor : 1;
|
||||
|
||||
if (factor <= 0) return false;
|
||||
|
||||
// Rate limit
|
||||
return await this.rateLimiterService.limit(limit, limitActor, factor)
|
||||
.then(() => { return false; })
|
||||
.catch(err => { return true; });
|
||||
}
|
||||
|
||||
@bindThis
|
||||
public attach(server: http.Server): void {
|
||||
this.#wss = new WebSocket.WebSocketServer({
|
||||
|
@ -57,6 +91,21 @@ export class StreamingApiServerService {
|
|||
return;
|
||||
}
|
||||
|
||||
// ServerServices sets `trustProxy: true`, which inside
|
||||
// fastify/request.js ends up calling `proxyAddr` in this way,
|
||||
// so we do the same
|
||||
const requestIp = proxyAddr(request, () => { return true; } );
|
||||
|
||||
if (await this.rateLimitThis(null, requestIp, {
|
||||
key: 'wsconnect',
|
||||
duration: ms('5min'),
|
||||
max: 32,
|
||||
})) {
|
||||
socket.write('HTTP/1.1 429 Rate Limit Exceeded\r\n\r\n');
|
||||
socket.destroy();
|
||||
return;
|
||||
}
|
||||
|
||||
const q = new URL(request.url, `http://${request.headers.host}`).searchParams;
|
||||
|
||||
let user: MiLocalUser | null = null;
|
||||
|
@ -94,13 +143,27 @@ export class StreamingApiServerService {
|
|||
return;
|
||||
}
|
||||
|
||||
const rateLimiter = () => {
|
||||
// rather high limit, because when catching up at the top of a
|
||||
// timeline, the frontend may render many many notes, each of
|
||||
// which causes a message via `useNoteCapture` to ask for
|
||||
// realtime updates of that note
|
||||
return this.rateLimitThis(user, requestIp, {
|
||||
key: 'wsmessage',
|
||||
duration: ms('2sec'),
|
||||
max: 4096,
|
||||
});
|
||||
};
|
||||
|
||||
const stream = new MainStreamConnection(
|
||||
this.channelsService,
|
||||
this.noteReadService,
|
||||
this.notificationService,
|
||||
this.cacheService,
|
||||
this.channelFollowingService,
|
||||
user, app,
|
||||
this.loggerService,
|
||||
user, app, requestIp,
|
||||
rateLimiter,
|
||||
);
|
||||
|
||||
await stream.init();
|
||||
|
|
|
@ -6,8 +6,18 @@
|
|||
import { permissions } from 'misskey-js';
|
||||
import type { KeyOf, Schema } from '@/misc/json-schema.js';
|
||||
|
||||
import * as ep___admin_meta from './endpoints/admin/meta.js';
|
||||
import * as ep___admin_abuseReport_notificationRecipient_list
|
||||
from '@/server/api/endpoints/admin/abuse-report/notification-recipient/list.js';
|
||||
import * as ep___admin_abuseReport_notificationRecipient_show
|
||||
from '@/server/api/endpoints/admin/abuse-report/notification-recipient/show.js';
|
||||
import * as ep___admin_abuseReport_notificationRecipient_create
|
||||
from '@/server/api/endpoints/admin/abuse-report/notification-recipient/create.js';
|
||||
import * as ep___admin_abuseReport_notificationRecipient_update
|
||||
from '@/server/api/endpoints/admin/abuse-report/notification-recipient/update.js';
|
||||
import * as ep___admin_abuseReport_notificationRecipient_delete
|
||||
from '@/server/api/endpoints/admin/abuse-report/notification-recipient/delete.js';
|
||||
import * as ep___admin_abuseUserReports from './endpoints/admin/abuse-user-reports.js';
|
||||
import * as ep___admin_meta from './endpoints/admin/meta.js';
|
||||
import * as ep___admin_accounts_create from './endpoints/admin/accounts/create.js';
|
||||
import * as ep___admin_accounts_delete from './endpoints/admin/accounts/delete.js';
|
||||
import * as ep___admin_accounts_findByEmail from './endpoints/admin/accounts/find-by-email.js';
|
||||
|
@ -44,7 +54,8 @@ import * as ep___admin_emoji_setCategoryBulk from './endpoints/admin/emoji/set-c
|
|||
import * as ep___admin_emoji_setLicenseBulk from './endpoints/admin/emoji/set-license-bulk.js';
|
||||
import * as ep___admin_emoji_update from './endpoints/admin/emoji/update.js';
|
||||
import * as ep___admin_federation_deleteAllFiles from './endpoints/admin/federation/delete-all-files.js';
|
||||
import * as ep___admin_federation_refreshRemoteInstanceMetadata from './endpoints/admin/federation/refresh-remote-instance-metadata.js';
|
||||
import * as ep___admin_federation_refreshRemoteInstanceMetadata
|
||||
from './endpoints/admin/federation/refresh-remote-instance-metadata.js';
|
||||
import * as ep___admin_federation_removeAllFollowing from './endpoints/admin/federation/remove-all-following.js';
|
||||
import * as ep___admin_federation_updateInstance from './endpoints/admin/federation/update-instance.js';
|
||||
import * as ep___admin_getIndexStats from './endpoints/admin/get-index-stats.js';
|
||||
|
@ -87,7 +98,13 @@ import * as ep___admin_roles_assign from './endpoints/admin/roles/assign.js';
|
|||
import * as ep___admin_roles_unassign from './endpoints/admin/roles/unassign.js';
|
||||
import * as ep___admin_roles_updateDefaultPolicies from './endpoints/admin/roles/update-default-policies.js';
|
||||
import * as ep___admin_roles_users from './endpoints/admin/roles/users.js';
|
||||
import * as ep___admin_systemWebhook_create from './endpoints/admin/system-webhook/create.js';
|
||||
import * as ep___admin_systemWebhook_delete from './endpoints/admin/system-webhook/delete.js';
|
||||
import * as ep___admin_systemWebhook_list from './endpoints/admin/system-webhook/list.js';
|
||||
import * as ep___admin_systemWebhook_show from './endpoints/admin/system-webhook/show.js';
|
||||
import * as ep___admin_systemWebhook_update from './endpoints/admin/system-webhook/update.js';
|
||||
import * as ep___announcements from './endpoints/announcements.js';
|
||||
import * as ep___announcements_show from './endpoints/announcements/show.js';
|
||||
import * as ep___antennas_create from './endpoints/antennas/create.js';
|
||||
import * as ep___antennas_delete from './endpoints/antennas/delete.js';
|
||||
import * as ep___antennas_list from './endpoints/antennas/list.js';
|
||||
|
@ -391,6 +408,11 @@ import * as ep___reversi_verify from './endpoints/reversi/verify.js';
|
|||
const eps = [
|
||||
['admin/meta', ep___admin_meta],
|
||||
['admin/abuse-user-reports', ep___admin_abuseUserReports],
|
||||
['admin/abuse-report/notification-recipient/list', ep___admin_abuseReport_notificationRecipient_list],
|
||||
['admin/abuse-report/notification-recipient/show', ep___admin_abuseReport_notificationRecipient_show],
|
||||
['admin/abuse-report/notification-recipient/create', ep___admin_abuseReport_notificationRecipient_create],
|
||||
['admin/abuse-report/notification-recipient/update', ep___admin_abuseReport_notificationRecipient_update],
|
||||
['admin/abuse-report/notification-recipient/delete', ep___admin_abuseReport_notificationRecipient_delete],
|
||||
['admin/accounts/create', ep___admin_accounts_create],
|
||||
['admin/accounts/delete', ep___admin_accounts_delete],
|
||||
['admin/accounts/find-by-email', ep___admin_accounts_findByEmail],
|
||||
|
@ -470,7 +492,13 @@ const eps = [
|
|||
['admin/roles/unassign', ep___admin_roles_unassign],
|
||||
['admin/roles/update-default-policies', ep___admin_roles_updateDefaultPolicies],
|
||||
['admin/roles/users', ep___admin_roles_users],
|
||||
['admin/system-webhook/create', ep___admin_systemWebhook_create],
|
||||
['admin/system-webhook/delete', ep___admin_systemWebhook_delete],
|
||||
['admin/system-webhook/list', ep___admin_systemWebhook_list],
|
||||
['admin/system-webhook/show', ep___admin_systemWebhook_show],
|
||||
['admin/system-webhook/update', ep___admin_systemWebhook_update],
|
||||
['announcements', ep___announcements],
|
||||
['announcements/show', ep___announcements_show],
|
||||
['antennas/create', ep___antennas_create],
|
||||
['antennas/delete', ep___antennas_delete],
|
||||
['antennas/list', ep___antennas_list],
|
||||
|
@ -902,8 +930,12 @@ export interface IEndpoint {
|
|||
const endpoints: IEndpoint[] = (eps as [string, any]).map(([name, ep]) => {
|
||||
return {
|
||||
name: name,
|
||||
get meta() { return ep.meta ?? {}; },
|
||||
get params() { return ep.paramDef; },
|
||||
get meta() {
|
||||
return ep.meta ?? {};
|
||||
},
|
||||
get params() {
|
||||
return ep.paramDef;
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
|
|
|
@ -0,0 +1,122 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: syuilo and misskey-project
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import { Endpoint } from '@/server/api/endpoint-base.js';
|
||||
import { ApiError } from '@/server/api/error.js';
|
||||
import {
|
||||
AbuseReportNotificationRecipientEntityService,
|
||||
} from '@/core/entities/AbuseReportNotificationRecipientEntityService.js';
|
||||
import { AbuseReportNotificationService } from '@/core/AbuseReportNotificationService.js';
|
||||
import { DI } from '@/di-symbols.js';
|
||||
import type { UserProfilesRepository } from '@/models/_.js';
|
||||
|
||||
export const meta = {
|
||||
tags: ['admin', 'abuse-report', 'notification-recipient'],
|
||||
|
||||
requireCredential: true,
|
||||
requireModerator: true,
|
||||
secure: true,
|
||||
kind: 'write:admin:abuse-report:notification-recipient',
|
||||
|
||||
res: {
|
||||
type: 'object',
|
||||
ref: 'AbuseReportNotificationRecipient',
|
||||
},
|
||||
|
||||
errors: {
|
||||
correlationCheckEmail: {
|
||||
message: 'If "method" is email, "userId" must be set.',
|
||||
code: 'CORRELATION_CHECK_EMAIL',
|
||||
id: '348bb8ae-575a-6fe9-4327-5811999def8f',
|
||||
httpStatusCode: 400,
|
||||
},
|
||||
correlationCheckWebhook: {
|
||||
message: 'If "method" is webhook, "systemWebhookId" must be set.',
|
||||
code: 'CORRELATION_CHECK_WEBHOOK',
|
||||
id: 'b0c15051-de2d-29ef-260c-9585cddd701a',
|
||||
httpStatusCode: 400,
|
||||
},
|
||||
emailAddressNotSet: {
|
||||
message: 'Email address is not set.',
|
||||
code: 'EMAIL_ADDRESS_NOT_SET',
|
||||
id: '7cc1d85e-2f58-fc31-b644-3de8d0d3421f',
|
||||
httpStatusCode: 400,
|
||||
},
|
||||
},
|
||||
} as const;
|
||||
|
||||
export const paramDef = {
|
||||
type: 'object',
|
||||
properties: {
|
||||
isActive: {
|
||||
type: 'boolean',
|
||||
},
|
||||
name: {
|
||||
type: 'string',
|
||||
minLength: 1,
|
||||
maxLength: 255,
|
||||
},
|
||||
method: {
|
||||
type: 'string',
|
||||
enum: ['email', 'webhook'],
|
||||
},
|
||||
userId: {
|
||||
type: 'string',
|
||||
format: 'misskey:id',
|
||||
},
|
||||
systemWebhookId: {
|
||||
type: 'string',
|
||||
format: 'misskey:id',
|
||||
},
|
||||
},
|
||||
required: [
|
||||
'isActive',
|
||||
'name',
|
||||
'method',
|
||||
],
|
||||
} as const;
|
||||
|
||||
@Injectable()
|
||||
export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-disable-line import/no-default-export
|
||||
constructor(
|
||||
@Inject(DI.userProfilesRepository)
|
||||
private userProfilesRepository: UserProfilesRepository,
|
||||
private abuseReportNotificationService: AbuseReportNotificationService,
|
||||
private abuseReportNotificationRecipientEntityService: AbuseReportNotificationRecipientEntityService,
|
||||
) {
|
||||
super(meta, paramDef, async (ps, me) => {
|
||||
if (ps.method === 'email') {
|
||||
const userProfile = await this.userProfilesRepository.findOneBy({ userId: ps.userId });
|
||||
if (!ps.userId || !userProfile) {
|
||||
throw new ApiError(meta.errors.correlationCheckEmail);
|
||||
}
|
||||
|
||||
if (!userProfile.email || !userProfile.emailVerified) {
|
||||
throw new ApiError(meta.errors.emailAddressNotSet);
|
||||
}
|
||||
}
|
||||
|
||||
if (ps.method === 'webhook' && !ps.systemWebhookId) {
|
||||
throw new ApiError(meta.errors.correlationCheckWebhook);
|
||||
}
|
||||
|
||||
const userId = ps.method === 'email' ? ps.userId : null;
|
||||
const systemWebhookId = ps.method === 'webhook' ? ps.systemWebhookId : null;
|
||||
const result = await this.abuseReportNotificationService.createRecipient(
|
||||
{
|
||||
isActive: ps.isActive,
|
||||
name: ps.name,
|
||||
method: ps.method,
|
||||
userId: userId ?? null,
|
||||
systemWebhookId: systemWebhookId ?? null,
|
||||
},
|
||||
me,
|
||||
);
|
||||
|
||||
return this.abuseReportNotificationRecipientEntityService.pack(result);
|
||||
});
|
||||
}
|
||||
}
|
|
@ -0,0 +1,44 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: syuilo and misskey-project
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { Endpoint } from '@/server/api/endpoint-base.js';
|
||||
import { AbuseReportNotificationService } from '@/core/AbuseReportNotificationService.js';
|
||||
|
||||
export const meta = {
|
||||
tags: ['admin', 'abuse-report', 'notification-recipient'],
|
||||
|
||||
requireCredential: true,
|
||||
requireModerator: true,
|
||||
secure: true,
|
||||
kind: 'write:admin:abuse-report:notification-recipient',
|
||||
} as const;
|
||||
|
||||
export const paramDef = {
|
||||
type: 'object',
|
||||
properties: {
|
||||
id: {
|
||||
type: 'string',
|
||||
format: 'misskey:id',
|
||||
},
|
||||
},
|
||||
required: [
|
||||
'id',
|
||||
],
|
||||
} as const;
|
||||
|
||||
@Injectable()
|
||||
export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-disable-line import/no-default-export
|
||||
constructor(
|
||||
private abuseReportNotificationService: AbuseReportNotificationService,
|
||||
) {
|
||||
super(meta, paramDef, async (ps, me) => {
|
||||
await this.abuseReportNotificationService.deleteRecipient(
|
||||
ps.id,
|
||||
me,
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
|
@ -0,0 +1,55 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: syuilo and misskey-project
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { Endpoint } from '@/server/api/endpoint-base.js';
|
||||
import {
|
||||
AbuseReportNotificationRecipientEntityService,
|
||||
} from '@/core/entities/AbuseReportNotificationRecipientEntityService.js';
|
||||
import { AbuseReportNotificationService } from '@/core/AbuseReportNotificationService.js';
|
||||
|
||||
export const meta = {
|
||||
tags: ['admin', 'abuse-report', 'notification-recipient'],
|
||||
|
||||
requireCredential: true,
|
||||
requireModerator: true,
|
||||
secure: true,
|
||||
kind: 'read:admin:abuse-report:notification-recipient',
|
||||
|
||||
res: {
|
||||
type: 'array',
|
||||
items: {
|
||||
type: 'object',
|
||||
ref: 'AbuseReportNotificationRecipient',
|
||||
},
|
||||
},
|
||||
} as const;
|
||||
|
||||
export const paramDef = {
|
||||
type: 'object',
|
||||
properties: {
|
||||
method: {
|
||||
type: 'array',
|
||||
items: {
|
||||
type: 'string',
|
||||
enum: ['email', 'webhook'],
|
||||
},
|
||||
},
|
||||
},
|
||||
required: [],
|
||||
} as const;
|
||||
|
||||
@Injectable()
|
||||
export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-disable-line import/no-default-export
|
||||
constructor(
|
||||
private abuseReportNotificationService: AbuseReportNotificationService,
|
||||
private abuseReportNotificationRecipientEntityService: AbuseReportNotificationRecipientEntityService,
|
||||
) {
|
||||
super(meta, paramDef, async (ps) => {
|
||||
const recipients = await this.abuseReportNotificationService.fetchRecipients({ method: ps.method });
|
||||
return this.abuseReportNotificationRecipientEntityService.packMany(recipients);
|
||||
});
|
||||
}
|
||||
}
|
|
@ -0,0 +1,64 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: syuilo and misskey-project
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { Endpoint } from '@/server/api/endpoint-base.js';
|
||||
import {
|
||||
AbuseReportNotificationRecipientEntityService,
|
||||
} from '@/core/entities/AbuseReportNotificationRecipientEntityService.js';
|
||||
import { AbuseReportNotificationService } from '@/core/AbuseReportNotificationService.js';
|
||||
import { ApiError } from '@/server/api/error.js';
|
||||
|
||||
export const meta = {
|
||||
tags: ['admin', 'abuse-report', 'notification-recipient'],
|
||||
|
||||
requireCredential: true,
|
||||
requireModerator: true,
|
||||
secure: true,
|
||||
kind: 'read:admin:abuse-report:notification-recipient',
|
||||
|
||||
res: {
|
||||
type: 'object',
|
||||
ref: 'AbuseReportNotificationRecipient',
|
||||
},
|
||||
|
||||
errors: {
|
||||
noSuchRecipient: {
|
||||
message: 'No such recipient.',
|
||||
code: 'NO_SUCH_RECIPIENT',
|
||||
id: '013de6a8-f757-04cb-4d73-cc2a7e3368e4',
|
||||
kind: 'server',
|
||||
httpStatusCode: 404,
|
||||
},
|
||||
},
|
||||
} as const;
|
||||
|
||||
export const paramDef = {
|
||||
type: 'object',
|
||||
properties: {
|
||||
id: {
|
||||
type: 'string',
|
||||
format: 'misskey:id',
|
||||
},
|
||||
},
|
||||
required: ['id'],
|
||||
} as const;
|
||||
|
||||
@Injectable()
|
||||
export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-disable-line import/no-default-export
|
||||
constructor(
|
||||
private abuseReportNotificationService: AbuseReportNotificationService,
|
||||
private abuseReportNotificationRecipientEntityService: AbuseReportNotificationRecipientEntityService,
|
||||
) {
|
||||
super(meta, paramDef, async (ps) => {
|
||||
const recipients = await this.abuseReportNotificationService.fetchRecipients({ ids: [ps.id] });
|
||||
if (recipients.length === 0) {
|
||||
throw new ApiError(meta.errors.noSuchRecipient);
|
||||
}
|
||||
|
||||
return this.abuseReportNotificationRecipientEntityService.pack(recipients[0]);
|
||||
});
|
||||
}
|
||||
}
|
|
@ -0,0 +1,128 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: syuilo and misskey-project
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import { Endpoint } from '@/server/api/endpoint-base.js';
|
||||
import { ApiError } from '@/server/api/error.js';
|
||||
import {
|
||||
AbuseReportNotificationRecipientEntityService,
|
||||
} from '@/core/entities/AbuseReportNotificationRecipientEntityService.js';
|
||||
import { AbuseReportNotificationService } from '@/core/AbuseReportNotificationService.js';
|
||||
import { DI } from '@/di-symbols.js';
|
||||
import type { UserProfilesRepository } from '@/models/_.js';
|
||||
|
||||
export const meta = {
|
||||
tags: ['admin', 'abuse-report', 'notification-recipient'],
|
||||
|
||||
requireCredential: true,
|
||||
requireModerator: true,
|
||||
secure: true,
|
||||
kind: 'write:admin:abuse-report:notification-recipient',
|
||||
|
||||
res: {
|
||||
type: 'object',
|
||||
ref: 'AbuseReportNotificationRecipient',
|
||||
},
|
||||
|
||||
errors: {
|
||||
correlationCheckEmail: {
|
||||
message: 'If "method" is email, "userId" must be set.',
|
||||
code: 'CORRELATION_CHECK_EMAIL',
|
||||
id: '348bb8ae-575a-6fe9-4327-5811999def8f',
|
||||
httpStatusCode: 400,
|
||||
},
|
||||
correlationCheckWebhook: {
|
||||
message: 'If "method" is webhook, "systemWebhookId" must be set.',
|
||||
code: 'CORRELATION_CHECK_WEBHOOK',
|
||||
id: 'b0c15051-de2d-29ef-260c-9585cddd701a',
|
||||
httpStatusCode: 400,
|
||||
},
|
||||
emailAddressNotSet: {
|
||||
message: 'Email address is not set.',
|
||||
code: 'EMAIL_ADDRESS_NOT_SET',
|
||||
id: '7cc1d85e-2f58-fc31-b644-3de8d0d3421f',
|
||||
httpStatusCode: 400,
|
||||
},
|
||||
},
|
||||
} as const;
|
||||
|
||||
export const paramDef = {
|
||||
type: 'object',
|
||||
properties: {
|
||||
id: {
|
||||
type: 'string',
|
||||
format: 'misskey:id',
|
||||
},
|
||||
isActive: {
|
||||
type: 'boolean',
|
||||
},
|
||||
name: {
|
||||
type: 'string',
|
||||
minLength: 1,
|
||||
maxLength: 255,
|
||||
},
|
||||
method: {
|
||||
type: 'string',
|
||||
enum: ['email', 'webhook'],
|
||||
},
|
||||
userId: {
|
||||
type: 'string',
|
||||
format: 'misskey:id',
|
||||
},
|
||||
systemWebhookId: {
|
||||
type: 'string',
|
||||
format: 'misskey:id',
|
||||
},
|
||||
},
|
||||
required: [
|
||||
'id',
|
||||
'isActive',
|
||||
'name',
|
||||
'method',
|
||||
],
|
||||
} as const;
|
||||
|
||||
@Injectable()
|
||||
export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-disable-line import/no-default-export
|
||||
constructor(
|
||||
@Inject(DI.userProfilesRepository)
|
||||
private userProfilesRepository: UserProfilesRepository,
|
||||
private abuseReportNotificationService: AbuseReportNotificationService,
|
||||
private abuseReportNotificationRecipientEntityService: AbuseReportNotificationRecipientEntityService,
|
||||
) {
|
||||
super(meta, paramDef, async (ps, me) => {
|
||||
if (ps.method === 'email') {
|
||||
const userProfile = await this.userProfilesRepository.findOneBy({ userId: ps.userId });
|
||||
if (!ps.userId || !userProfile) {
|
||||
throw new ApiError(meta.errors.correlationCheckEmail);
|
||||
}
|
||||
|
||||
if (!userProfile.email || !userProfile.emailVerified) {
|
||||
throw new ApiError(meta.errors.emailAddressNotSet);
|
||||
}
|
||||
}
|
||||
|
||||
if (ps.method === 'webhook' && !ps.systemWebhookId) {
|
||||
throw new ApiError(meta.errors.correlationCheckWebhook);
|
||||
}
|
||||
|
||||
const userId = ps.method === 'email' ? ps.userId : null;
|
||||
const systemWebhookId = ps.method === 'webhook' ? ps.systemWebhookId : null;
|
||||
const result = await this.abuseReportNotificationService.updateRecipient(
|
||||
{
|
||||
id: ps.id,
|
||||
isActive: ps.isActive,
|
||||
name: ps.name,
|
||||
method: ps.method,
|
||||
userId: userId ?? null,
|
||||
systemWebhookId: systemWebhookId ?? null,
|
||||
},
|
||||
me,
|
||||
);
|
||||
|
||||
return this.abuseReportNotificationRecipientEntityService.pack(result);
|
||||
});
|
||||
}
|
||||
}
|
|
@ -7,9 +7,9 @@ import { Inject, Injectable } from '@nestjs/common';
|
|||
import { Endpoint } from '@/server/api/endpoint-base.js';
|
||||
import type { UsersRepository } from '@/models/_.js';
|
||||
import { QueueService } from '@/core/QueueService.js';
|
||||
import { UserSuspendService } from '@/core/UserSuspendService.js';
|
||||
import { DI } from '@/di-symbols.js';
|
||||
import { UserEntityService } from '@/core/entities/UserEntityService.js';
|
||||
import { DeleteAccountService } from '@/core/DeleteAccountService.js';
|
||||
|
||||
export const meta = {
|
||||
tags: ['admin'],
|
||||
|
@ -34,9 +34,7 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
@Inject(DI.usersRepository)
|
||||
private usersRepository: UsersRepository,
|
||||
|
||||
private userEntityService: UserEntityService,
|
||||
private queueService: QueueService,
|
||||
private userSuspendService: UserSuspendService,
|
||||
private deleteAccoountService: DeleteAccountService,
|
||||
) {
|
||||
super(meta, paramDef, async (ps, me) => {
|
||||
const user = await this.usersRepository.findOneBy({ id: ps.userId });
|
||||
|
@ -49,22 +47,7 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
throw new Error('cannot delete a root account');
|
||||
}
|
||||
|
||||
if (this.userEntityService.isLocalUser(user)) {
|
||||
// 物理削除する前にDelete activityを送信する
|
||||
await this.userSuspendService.doPostSuspend(user).catch(err => {});
|
||||
|
||||
this.queueService.createDeleteAccountJob(user, {
|
||||
soft: false,
|
||||
});
|
||||
} else {
|
||||
this.queueService.createDeleteAccountJob(user, {
|
||||
soft: true, // リモートユーザーの削除は、完全にDBから物理削除してしまうと再度連合してきてアカウントが復活する可能性があるため、soft指定する
|
||||
});
|
||||
}
|
||||
|
||||
await this.usersRepository.update(user.id, {
|
||||
isDeleted: true,
|
||||
});
|
||||
await this.deleteAccoountService.deleteAccount(user);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
|
@ -51,7 +51,7 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
private moderationLogService: ModerationLogService,
|
||||
) {
|
||||
super(meta, paramDef, async (ps, me) => {
|
||||
const ad = await this.adsRepository.insert({
|
||||
const ad = await this.adsRepository.insertOne({
|
||||
id: this.idService.gen(),
|
||||
expiresAt: new Date(ps.expiresAt),
|
||||
startsAt: new Date(ps.startsAt),
|
||||
|
@ -62,7 +62,7 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
ratio: ps.ratio,
|
||||
place: ps.place,
|
||||
memo: ps.memo,
|
||||
}).then(r => this.adsRepository.findOneByOrFail({ id: r.identifiers[0].id }));
|
||||
});
|
||||
|
||||
this.moderationLogService.log(me, 'createAd', {
|
||||
adId: ad.id,
|
||||
|
|
|
@ -41,7 +41,7 @@ export const paramDef = {
|
|||
startsAt: { type: 'integer' },
|
||||
dayOfWeek: { type: 'integer' },
|
||||
},
|
||||
required: ['id', 'memo', 'url', 'imageUrl', 'place', 'priority', 'ratio', 'expiresAt', 'startsAt', 'dayOfWeek'],
|
||||
required: ['id'],
|
||||
} as const;
|
||||
|
||||
@Injectable()
|
||||
|
@ -64,8 +64,8 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
ratio: ps.ratio,
|
||||
memo: ps.memo,
|
||||
imageUrl: ps.imageUrl,
|
||||
expiresAt: new Date(ps.expiresAt),
|
||||
startsAt: new Date(ps.startsAt),
|
||||
expiresAt: ps.expiresAt ? new Date(ps.expiresAt) : undefined,
|
||||
startsAt: ps.startsAt ? new Date(ps.startsAt) : undefined,
|
||||
dayOfWeek: ps.dayOfWeek,
|
||||
});
|
||||
|
||||
|
|
|
@ -70,6 +70,7 @@ export const paramDef = {
|
|||
sinceId: { type: 'string', format: 'misskey:id' },
|
||||
untilId: { type: 'string', format: 'misskey:id' },
|
||||
userId: { type: 'string', format: 'misskey:id', nullable: true },
|
||||
status: { type: 'string', enum: ['all', 'active', 'archived'], default: 'active' },
|
||||
},
|
||||
required: [],
|
||||
} as const;
|
||||
|
@ -88,7 +89,13 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
) {
|
||||
super(meta, paramDef, async (ps, me) => {
|
||||
const query = this.queryService.makePaginationQuery(this.announcementsRepository.createQueryBuilder('announcement'), ps.sinceId, ps.untilId);
|
||||
query.andWhere('announcement.isActive = true');
|
||||
|
||||
if (ps.status === 'archived') {
|
||||
query.andWhere('announcement.isActive = false');
|
||||
} else if (ps.status === 'active') {
|
||||
query.andWhere('announcement.isActive = true');
|
||||
}
|
||||
|
||||
if (ps.userId) {
|
||||
query.andWhere('announcement.userId = :userId', { userId: ps.userId });
|
||||
} else {
|
||||
|
|
|
@ -40,7 +40,7 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
});
|
||||
|
||||
for (const file of files) {
|
||||
this.driveService.deleteFile(file);
|
||||
this.driveService.deleteFile(file, false, me);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
|
|
@ -62,7 +62,7 @@ export const meta = {
|
|||
name: {
|
||||
type: 'string',
|
||||
optional: false, nullable: false,
|
||||
example: 'lenna.jpg',
|
||||
example: '192.jpg',
|
||||
},
|
||||
type: {
|
||||
type: 'string',
|
||||
|
|
|
@ -91,7 +91,7 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
const addedEmoji = await this.customEmojiService.add({
|
||||
driveFile,
|
||||
name: nameNfc,
|
||||
category: emoji.category?.normalize('NFC'),
|
||||
category: emoji.category?.normalize('NFC') ?? null,
|
||||
aliases: emoji.aliases?.map(a => a.normalize('NFC')),
|
||||
host: null,
|
||||
license: emoji.license,
|
||||
|
|
|
@ -67,6 +67,7 @@ export const paramDef = {
|
|||
properties: {
|
||||
query: { type: 'string', nullable: true, default: null },
|
||||
limit: { type: 'integer', minimum: 1, maximum: 100, default: 10 },
|
||||
offset: { type: 'integer', minimum: 1, nullable: true, default: null },
|
||||
sinceId: { type: 'string', format: 'misskey:id' },
|
||||
untilId: { type: 'string', format: 'misskey:id' },
|
||||
},
|
||||
|
@ -92,7 +93,7 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
//q.andWhere('emoji.name ILIKE :q', { q: `%${ sqlLikeEscape(ps.query) }%` });
|
||||
//const emojis = await q.limit(ps.limit).getMany();
|
||||
|
||||
emojis = await q.orderBy('length(emoji.name)', 'ASC').getMany();
|
||||
emojis = await q.orderBy('length(emoji.name)', 'ASC').addOrderBy('id', 'DESC').getMany();
|
||||
const queryarry = ps.query.match(/:([\p{Letter}\p{Number}\p{Mark}_+-]*):/ug);
|
||||
|
||||
if (queryarry) {
|
||||
|
@ -106,9 +107,9 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
emoji.aliases.some(a => a.includes(queryNfc)) ||
|
||||
emoji.category?.includes(queryNfc));
|
||||
}
|
||||
emojis.splice(ps.limit + 1);
|
||||
emojis = emojis.slice((ps.offset ?? 0), ((ps.offset ?? 0) + ps.limit));
|
||||
} else {
|
||||
emojis = await q.limit(ps.limit).getMany();
|
||||
emojis = await q.take(ps.limit).skip(ps.offset ?? 0).getMany();
|
||||
}
|
||||
|
||||
return this.emojiEntityService.packDetailedMany(emojis);
|
||||
|
|
|
@ -48,13 +48,20 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
throw new Error('instance not found');
|
||||
}
|
||||
|
||||
const isSuspendedBefore = instance.suspensionState !== 'none';
|
||||
let suspensionState: undefined | 'manuallySuspended' | 'none';
|
||||
|
||||
if (ps.isSuspended != null && isSuspendedBefore !== ps.isSuspended) {
|
||||
suspensionState = ps.isSuspended ? 'manuallySuspended' : 'none';
|
||||
}
|
||||
|
||||
await this.federatedInstanceService.update(instance.id, {
|
||||
isSuspended: ps.isSuspended,
|
||||
suspensionState,
|
||||
isNSFW: ps.isNSFW,
|
||||
moderationNote: ps.moderationNote,
|
||||
});
|
||||
|
||||
if (ps.isSuspended != null && instance.isSuspended !== ps.isSuspended) {
|
||||
if (ps.isSuspended != null && isSuspendedBefore !== ps.isSuspended) {
|
||||
if (ps.isSuspended) {
|
||||
this.moderationLogService.log(me, 'suspendRemoteInstance', {
|
||||
id: instance.id,
|
||||
|
|
|
@ -67,11 +67,11 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
const ticketsPromises = [];
|
||||
|
||||
for (let i = 0; i < ps.count; i++) {
|
||||
ticketsPromises.push(this.registrationTicketsRepository.insert({
|
||||
ticketsPromises.push(this.registrationTicketsRepository.insertOne({
|
||||
id: this.idService.gen(),
|
||||
expiresAt: ps.expiresAt ? new Date(ps.expiresAt) : null,
|
||||
code: generateInviteCode(),
|
||||
}).then(x => this.registrationTicketsRepository.findOneByOrFail(x.identifiers[0])));
|
||||
}));
|
||||
}
|
||||
|
||||
const tickets = await Promise.all(ticketsPromises);
|
||||
|
|
|
@ -133,6 +133,16 @@ export const meta = {
|
|||
nullable: false,
|
||||
},
|
||||
},
|
||||
mediaSilencedHosts: {
|
||||
type: 'array',
|
||||
optional: false,
|
||||
nullable: false,
|
||||
items: {
|
||||
type: 'string',
|
||||
optional: false,
|
||||
nullable: false,
|
||||
},
|
||||
},
|
||||
pinnedUsers: {
|
||||
type: 'array',
|
||||
optional: false, nullable: false,
|
||||
|
@ -470,6 +480,10 @@ export const meta = {
|
|||
type: 'string',
|
||||
optional: false, nullable: true,
|
||||
},
|
||||
inquiryUrl: {
|
||||
type: 'string',
|
||||
optional: false, nullable: true,
|
||||
},
|
||||
repositoryUrl: {
|
||||
type: 'string',
|
||||
optional: false, nullable: true,
|
||||
|
@ -477,6 +491,8 @@ export const meta = {
|
|||
summalyProxy: {
|
||||
type: 'string',
|
||||
optional: false, nullable: true,
|
||||
deprecated: true,
|
||||
description: '[Deprecated] Use "urlPreviewSummaryProxyUrl" instead.',
|
||||
},
|
||||
themeColor: {
|
||||
type: 'string',
|
||||
|
@ -494,6 +510,30 @@ export const meta = {
|
|||
type: 'string',
|
||||
optional: false, nullable: false,
|
||||
},
|
||||
urlPreviewEnabled: {
|
||||
type: 'boolean',
|
||||
optional: false, nullable: false,
|
||||
},
|
||||
urlPreviewTimeout: {
|
||||
type: 'number',
|
||||
optional: false, nullable: false,
|
||||
},
|
||||
urlPreviewMaximumContentLength: {
|
||||
type: 'number',
|
||||
optional: false, nullable: false,
|
||||
},
|
||||
urlPreviewRequireContentLength: {
|
||||
type: 'boolean',
|
||||
optional: false, nullable: false,
|
||||
},
|
||||
urlPreviewUserAgent: {
|
||||
type: 'string',
|
||||
optional: false, nullable: true,
|
||||
},
|
||||
urlPreviewSummaryProxyUrl: {
|
||||
type: 'string',
|
||||
optional: false, nullable: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
} as const;
|
||||
|
@ -531,6 +571,7 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
impressumUrl: instance.impressumUrl,
|
||||
donationUrl: instance.donationUrl,
|
||||
privacyPolicyUrl: instance.privacyPolicyUrl,
|
||||
inquiryUrl: instance.inquiryUrl,
|
||||
disableRegistration: instance.disableRegistration,
|
||||
emailRequiredForSignup: instance.emailRequiredForSignup,
|
||||
approvalRequiredForSignup: instance.approvalRequiredForSignup,
|
||||
|
@ -569,6 +610,7 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
allowedHosts: instance.allowedHosts,
|
||||
allowlistMode: instance.allowlistMode,
|
||||
silencedHosts: instance.silencedHosts,
|
||||
mediaSilencedHosts: instance.mediaSilencedHosts,
|
||||
sensitiveWords: instance.sensitiveWords,
|
||||
prohibitedWords: instance.prohibitedWords,
|
||||
preservedUsernames: instance.preservedUsernames,
|
||||
|
@ -583,7 +625,6 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
enableSensitiveMediaDetectionForVideos: instance.enableSensitiveMediaDetectionForVideos,
|
||||
enableBotTrending: instance.enableBotTrending,
|
||||
proxyAccountId: instance.proxyAccountId,
|
||||
summalyProxy: instance.summalyProxy,
|
||||
email: instance.email,
|
||||
smtpSecure: instance.smtpSecure,
|
||||
smtpHost: instance.smtpHost,
|
||||
|
@ -630,6 +671,13 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
perUserHomeTimelineCacheMax: instance.perUserHomeTimelineCacheMax,
|
||||
perUserListTimelineCacheMax: instance.perUserListTimelineCacheMax,
|
||||
notesPerOneAd: instance.notesPerOneAd,
|
||||
summalyProxy: instance.urlPreviewSummaryProxyUrl,
|
||||
urlPreviewEnabled: instance.urlPreviewEnabled,
|
||||
urlPreviewTimeout: instance.urlPreviewTimeout,
|
||||
urlPreviewMaximumContentLength: instance.urlPreviewMaximumContentLength,
|
||||
urlPreviewRequireContentLength: instance.urlPreviewRequireContentLength,
|
||||
urlPreviewUserAgent: instance.urlPreviewUserAgent,
|
||||
urlPreviewSummaryProxyUrl: instance.urlPreviewSummaryProxyUrl,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
|
|
@ -1,3 +1,8 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: marie and other Sharkey contributors
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import { Endpoint } from '@/server/api/endpoint-base.js';
|
||||
import type { UsersRepository, UserProfilesRepository } from '@/models/_.js';
|
||||
|
|
|
@ -5,7 +5,7 @@
|
|||
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import { Endpoint } from '@/server/api/endpoint-base.js';
|
||||
import type { DbQueue, DeliverQueue, EndedPollNotificationQueue, InboxQueue, ObjectStorageQueue, SystemQueue, WebhookDeliverQueue } from '@/core/QueueModule.js';
|
||||
import type { DbQueue, DeliverQueue, EndedPollNotificationQueue, InboxQueue, ObjectStorageQueue, SystemQueue, UserWebhookDeliverQueue, SystemWebhookDeliverQueue } from '@/core/QueueModule.js';
|
||||
|
||||
export const meta = {
|
||||
tags: ['admin'],
|
||||
|
@ -54,7 +54,8 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
@Inject('queue:inbox') public inboxQueue: InboxQueue,
|
||||
@Inject('queue:db') public dbQueue: DbQueue,
|
||||
@Inject('queue:objectStorage') public objectStorageQueue: ObjectStorageQueue,
|
||||
@Inject('queue:webhookDeliver') public webhookDeliverQueue: WebhookDeliverQueue,
|
||||
@Inject('queue:userWebhookDeliver') public userWebhookDeliverQueue: UserWebhookDeliverQueue,
|
||||
@Inject('queue:systemWebhookDeliver') public systemWebhookDeliverQueue: SystemWebhookDeliverQueue,
|
||||
) {
|
||||
super(meta, paramDef, async (ps, me) => {
|
||||
const deliverJobCounts = await this.deliverQueue.getJobCounts();
|
||||
|
|
|
@ -5,12 +5,10 @@
|
|||
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import { Endpoint } from '@/server/api/endpoint-base.js';
|
||||
import type { UsersRepository, AbuseUserReportsRepository } from '@/models/_.js';
|
||||
import { InstanceActorService } from '@/core/InstanceActorService.js';
|
||||
import { QueueService } from '@/core/QueueService.js';
|
||||
import { ApRendererService } from '@/core/activitypub/ApRendererService.js';
|
||||
import type { AbuseUserReportsRepository } from '@/models/_.js';
|
||||
import { DI } from '@/di-symbols.js';
|
||||
import { ModerationLogService } from '@/core/ModerationLogService.js';
|
||||
import { ApiError } from '@/server/api/error.js';
|
||||
import { AbuseReportService } from '@/core/AbuseReportService.js';
|
||||
|
||||
export const meta = {
|
||||
tags: ['admin'],
|
||||
|
@ -19,6 +17,16 @@ export const meta = {
|
|||
requireCredentialSecureMode: true,
|
||||
requireModerator: true,
|
||||
kind: 'write:admin:resolve-abuse-user-report',
|
||||
|
||||
errors: {
|
||||
noSuchAbuseReport: {
|
||||
message: 'No such abuse report.',
|
||||
code: 'NO_SUCH_ABUSE_REPORT',
|
||||
id: 'ac3794dd-2ce4-d878-e546-73c60c06b398',
|
||||
kind: 'server',
|
||||
httpStatusCode: 404,
|
||||
},
|
||||
},
|
||||
} as const;
|
||||
|
||||
export const paramDef = {
|
||||
|
@ -30,47 +38,20 @@ export const paramDef = {
|
|||
required: ['reportId'],
|
||||
} as const;
|
||||
|
||||
// TODO: ロジックをサービスに切り出す
|
||||
|
||||
@Injectable()
|
||||
export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-disable-line import/no-default-export
|
||||
constructor(
|
||||
@Inject(DI.usersRepository)
|
||||
private usersRepository: UsersRepository,
|
||||
|
||||
@Inject(DI.abuseUserReportsRepository)
|
||||
private abuseUserReportsRepository: AbuseUserReportsRepository,
|
||||
|
||||
private queueService: QueueService,
|
||||
private instanceActorService: InstanceActorService,
|
||||
private apRendererService: ApRendererService,
|
||||
private moderationLogService: ModerationLogService,
|
||||
private abuseReportService: AbuseReportService,
|
||||
) {
|
||||
super(meta, paramDef, async (ps, me) => {
|
||||
const report = await this.abuseUserReportsRepository.findOneBy({ id: ps.reportId });
|
||||
|
||||
if (report == null) {
|
||||
throw new Error('report not found');
|
||||
if (!report) {
|
||||
throw new ApiError(meta.errors.noSuchAbuseReport);
|
||||
}
|
||||
|
||||
if (ps.forward && report.targetUserHost != null) {
|
||||
const actor = await this.instanceActorService.getInstanceActor();
|
||||
const targetUser = await this.usersRepository.findOneByOrFail({ id: report.targetUserId });
|
||||
|
||||
this.queueService.deliver(actor, this.apRendererService.addContext(this.apRendererService.renderFlag(actor, targetUser.uri!, report.comment)), targetUser.inbox, false);
|
||||
}
|
||||
|
||||
await this.abuseUserReportsRepository.update(report.id, {
|
||||
resolved: true,
|
||||
assigneeId: me.id,
|
||||
forwarded: ps.forward && report.targetUserHost != null,
|
||||
});
|
||||
|
||||
this.moderationLogService.log(me, 'resolveAbuseReport', {
|
||||
reportId: report.id,
|
||||
report: report,
|
||||
forwarded: ps.forward && report.targetUserHost != null,
|
||||
});
|
||||
await this.abuseReportService.resolve([{ reportId: report.id, forward: ps.forward }], me);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
|
@ -7,6 +7,7 @@ import { Injectable } from '@nestjs/common';
|
|||
import { Endpoint } from '@/server/api/endpoint-base.js';
|
||||
import { GlobalEventService } from '@/core/GlobalEventService.js';
|
||||
import { MetaService } from '@/core/MetaService.js';
|
||||
import { ModerationLogService } from '@/core/ModerationLogService.js';
|
||||
|
||||
export const meta = {
|
||||
tags: ['admin', 'role'],
|
||||
|
@ -34,12 +35,22 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
constructor(
|
||||
private metaService: MetaService,
|
||||
private globalEventService: GlobalEventService,
|
||||
private moderationLogService: ModerationLogService,
|
||||
) {
|
||||
super(meta, paramDef, async (ps) => {
|
||||
super(meta, paramDef, async (ps, me) => {
|
||||
const before = await this.metaService.fetch(true);
|
||||
|
||||
await this.metaService.update({
|
||||
policies: ps.policies,
|
||||
});
|
||||
this.globalEventService.publishInternalEvent('policiesUpdated', ps.policies);
|
||||
|
||||
const after = await this.metaService.fetch(true);
|
||||
|
||||
this.globalEventService.publishInternalEvent('policiesUpdated', after.policies);
|
||||
this.moderationLogService.log(me, 'updateServerSettings', {
|
||||
before: before.policies,
|
||||
after: after.policies,
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
|
@ -6,7 +6,6 @@
|
|||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import { Endpoint } from '@/server/api/endpoint-base.js';
|
||||
import type { RolesRepository } from '@/models/_.js';
|
||||
import { GlobalEventService } from '@/core/GlobalEventService.js';
|
||||
import { DI } from '@/di-symbols.js';
|
||||
import { ApiError } from '@/server/api/error.js';
|
||||
import { RoleService } from '@/core/RoleService.js';
|
||||
|
@ -51,19 +50,6 @@ export const paramDef = {
|
|||
},
|
||||
required: [
|
||||
'roleId',
|
||||
'name',
|
||||
'description',
|
||||
'color',
|
||||
'iconUrl',
|
||||
'target',
|
||||
'condFormula',
|
||||
'isPublic',
|
||||
'isModerator',
|
||||
'isAdministrator',
|
||||
'asBadge',
|
||||
'canEditMembersByModerator',
|
||||
'displayOrder',
|
||||
'policies',
|
||||
],
|
||||
} as const;
|
||||
|
||||
|
|
|
@ -90,10 +90,13 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
.limit(ps.limit)
|
||||
.getMany();
|
||||
|
||||
const _users = assigns.map(({ user, userId }) => user ?? userId);
|
||||
const _userMap = await this.userEntityService.packMany(_users, me, { schema: 'UserDetailed' })
|
||||
.then(users => new Map(users.map(u => [u.id, u])));
|
||||
return await Promise.all(assigns.map(async assign => ({
|
||||
id: assign.id,
|
||||
createdAt: this.idService.parse(assign.id).date.toISOString(),
|
||||
user: await this.userEntityService.pack(assign.user!, me, { schema: 'UserDetailed' }),
|
||||
user: _userMap.get(assign.userId) ?? await this.userEntityService.pack(assign.user!, me, { schema: 'UserDetailed' }),
|
||||
expiresAt: assign.expiresAt?.toISOString() ?? null,
|
||||
})));
|
||||
});
|
||||
|
|
|
@ -17,7 +17,7 @@ export const meta = {
|
|||
requireCredential: true,
|
||||
requireCredentialSecureMode: true,
|
||||
requireModerator: true,
|
||||
kind: 'read:admin:show-users',
|
||||
kind: 'read:admin:show-user',
|
||||
|
||||
res: {
|
||||
type: 'array',
|
||||
|
|
|
@ -1,3 +1,8 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: marie and other Sharkey contributors
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import { Endpoint } from '@/server/api/endpoint-base.js';
|
||||
import type { UsersRepository } from '@/models/_.js';
|
||||
|
|
|
@ -3,18 +3,12 @@
|
|||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
import { IsNull, Not } from 'typeorm';
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import { Endpoint } from '@/server/api/endpoint-base.js';
|
||||
import type { UsersRepository, FollowingsRepository } from '@/models/_.js';
|
||||
import type { MiUser } from '@/models/User.js';
|
||||
import type { RelationshipJobData } from '@/queue/types.js';
|
||||
import { ModerationLogService } from '@/core/ModerationLogService.js';
|
||||
import type { UsersRepository } from '@/models/_.js';
|
||||
import { UserSuspendService } from '@/core/UserSuspendService.js';
|
||||
import { DI } from '@/di-symbols.js';
|
||||
import { bindThis } from '@/decorators.js';
|
||||
import { RoleService } from '@/core/RoleService.js';
|
||||
import { QueueService } from '@/core/QueueService.js';
|
||||
|
||||
export const meta = {
|
||||
tags: ['admin'],
|
||||
|
@ -39,13 +33,8 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
@Inject(DI.usersRepository)
|
||||
private usersRepository: UsersRepository,
|
||||
|
||||
@Inject(DI.followingsRepository)
|
||||
private followingsRepository: FollowingsRepository,
|
||||
|
||||
private userSuspendService: UserSuspendService,
|
||||
private roleService: RoleService,
|
||||
private moderationLogService: ModerationLogService,
|
||||
private queueService: QueueService,
|
||||
) {
|
||||
super(meta, paramDef, async (ps, me) => {
|
||||
const user = await this.usersRepository.findOneBy({ id: ps.userId });
|
||||
|
@ -58,42 +47,7 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
throw new Error('cannot suspend moderator account');
|
||||
}
|
||||
|
||||
await this.usersRepository.update(user.id, {
|
||||
isSuspended: true,
|
||||
});
|
||||
|
||||
this.moderationLogService.log(me, 'suspend', {
|
||||
userId: user.id,
|
||||
userUsername: user.username,
|
||||
userHost: user.host,
|
||||
});
|
||||
|
||||
(async () => {
|
||||
await this.userSuspendService.doPostSuspend(user).catch(e => {});
|
||||
await this.unFollowAll(user).catch(e => {});
|
||||
})();
|
||||
await this.userSuspendService.suspend(user, me);
|
||||
});
|
||||
}
|
||||
|
||||
@bindThis
|
||||
private async unFollowAll(follower: MiUser) {
|
||||
const followings = await this.followingsRepository.find({
|
||||
where: {
|
||||
followerId: follower.id,
|
||||
followeeId: Not(IsNull()),
|
||||
},
|
||||
});
|
||||
|
||||
const jobs: RelationshipJobData[] = [];
|
||||
for (const following of followings) {
|
||||
if (following.followeeId && following.followerId) {
|
||||
jobs.push({
|
||||
from: { id: following.followerId },
|
||||
to: { id: following.followeeId },
|
||||
silent: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
this.queueService.createUnfollowJob(jobs);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,85 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: syuilo and misskey-project
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { Endpoint } from '@/server/api/endpoint-base.js';
|
||||
import { SystemWebhookEntityService } from '@/core/entities/SystemWebhookEntityService.js';
|
||||
import { systemWebhookEventTypes } from '@/models/SystemWebhook.js';
|
||||
import { SystemWebhookService } from '@/core/SystemWebhookService.js';
|
||||
|
||||
export const meta = {
|
||||
tags: ['admin', 'system-webhook'],
|
||||
|
||||
requireCredential: true,
|
||||
requireModerator: true,
|
||||
secure: true,
|
||||
kind: 'write:admin:system-webhook',
|
||||
|
||||
res: {
|
||||
type: 'object',
|
||||
ref: 'SystemWebhook',
|
||||
},
|
||||
} as const;
|
||||
|
||||
export const paramDef = {
|
||||
type: 'object',
|
||||
properties: {
|
||||
isActive: {
|
||||
type: 'boolean',
|
||||
},
|
||||
name: {
|
||||
type: 'string',
|
||||
minLength: 1,
|
||||
maxLength: 255,
|
||||
},
|
||||
on: {
|
||||
type: 'array',
|
||||
items: {
|
||||
type: 'string',
|
||||
enum: systemWebhookEventTypes,
|
||||
},
|
||||
},
|
||||
url: {
|
||||
type: 'string',
|
||||
minLength: 1,
|
||||
maxLength: 1024,
|
||||
},
|
||||
secret: {
|
||||
type: 'string',
|
||||
minLength: 1,
|
||||
maxLength: 1024,
|
||||
},
|
||||
},
|
||||
required: [
|
||||
'isActive',
|
||||
'name',
|
||||
'on',
|
||||
'url',
|
||||
'secret',
|
||||
],
|
||||
} as const;
|
||||
|
||||
@Injectable()
|
||||
export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-disable-line import/no-default-export
|
||||
constructor(
|
||||
private systemWebhookService: SystemWebhookService,
|
||||
private systemWebhookEntityService: SystemWebhookEntityService,
|
||||
) {
|
||||
super(meta, paramDef, async (ps, me) => {
|
||||
const result = await this.systemWebhookService.createSystemWebhook(
|
||||
{
|
||||
isActive: ps.isActive,
|
||||
name: ps.name,
|
||||
on: ps.on,
|
||||
url: ps.url,
|
||||
secret: ps.secret,
|
||||
},
|
||||
me,
|
||||
);
|
||||
|
||||
return this.systemWebhookEntityService.pack(result);
|
||||
});
|
||||
}
|
||||
}
|
|
@ -0,0 +1,44 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: syuilo and misskey-project
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { Endpoint } from '@/server/api/endpoint-base.js';
|
||||
import { SystemWebhookService } from '@/core/SystemWebhookService.js';
|
||||
|
||||
export const meta = {
|
||||
tags: ['admin', 'system-webhook'],
|
||||
|
||||
requireCredential: true,
|
||||
requireModerator: true,
|
||||
secure: true,
|
||||
kind: 'write:admin:system-webhook',
|
||||
} as const;
|
||||
|
||||
export const paramDef = {
|
||||
type: 'object',
|
||||
properties: {
|
||||
id: {
|
||||
type: 'string',
|
||||
format: 'misskey:id',
|
||||
},
|
||||
},
|
||||
required: [
|
||||
'id',
|
||||
],
|
||||
} as const;
|
||||
|
||||
@Injectable()
|
||||
export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-disable-line import/no-default-export
|
||||
constructor(
|
||||
private systemWebhookService: SystemWebhookService,
|
||||
) {
|
||||
super(meta, paramDef, async (ps, me) => {
|
||||
await this.systemWebhookService.deleteSystemWebhook(
|
||||
ps.id,
|
||||
me,
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
|
@ -0,0 +1,60 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: syuilo and misskey-project
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { Endpoint } from '@/server/api/endpoint-base.js';
|
||||
import { SystemWebhookEntityService } from '@/core/entities/SystemWebhookEntityService.js';
|
||||
import { systemWebhookEventTypes } from '@/models/SystemWebhook.js';
|
||||
import { SystemWebhookService } from '@/core/SystemWebhookService.js';
|
||||
|
||||
export const meta = {
|
||||
tags: ['admin', 'system-webhook'],
|
||||
|
||||
requireCredential: true,
|
||||
requireModerator: true,
|
||||
secure: true,
|
||||
kind: 'write:admin:system-webhook',
|
||||
|
||||
res: {
|
||||
type: 'array',
|
||||
items: {
|
||||
type: 'object',
|
||||
ref: 'SystemWebhook',
|
||||
},
|
||||
},
|
||||
} as const;
|
||||
|
||||
export const paramDef = {
|
||||
type: 'object',
|
||||
properties: {
|
||||
isActive: {
|
||||
type: 'boolean',
|
||||
},
|
||||
on: {
|
||||
type: 'array',
|
||||
items: {
|
||||
type: 'string',
|
||||
enum: systemWebhookEventTypes,
|
||||
},
|
||||
},
|
||||
},
|
||||
required: [],
|
||||
} as const;
|
||||
|
||||
@Injectable()
|
||||
export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-disable-line import/no-default-export
|
||||
constructor(
|
||||
private systemWebhookService: SystemWebhookService,
|
||||
private systemWebhookEntityService: SystemWebhookEntityService,
|
||||
) {
|
||||
super(meta, paramDef, async (ps) => {
|
||||
const webhooks = await this.systemWebhookService.fetchSystemWebhooks({
|
||||
isActive: ps.isActive,
|
||||
on: ps.on,
|
||||
});
|
||||
return this.systemWebhookEntityService.packMany(webhooks);
|
||||
});
|
||||
}
|
||||
}
|
|
@ -0,0 +1,62 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: syuilo and misskey-project
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { Endpoint } from '@/server/api/endpoint-base.js';
|
||||
import { SystemWebhookEntityService } from '@/core/entities/SystemWebhookEntityService.js';
|
||||
import { ApiError } from '@/server/api/error.js';
|
||||
import { SystemWebhookService } from '@/core/SystemWebhookService.js';
|
||||
|
||||
export const meta = {
|
||||
tags: ['admin', 'system-webhook'],
|
||||
|
||||
requireCredential: true,
|
||||
requireModerator: true,
|
||||
secure: true,
|
||||
kind: 'write:admin:system-webhook',
|
||||
|
||||
res: {
|
||||
type: 'object',
|
||||
ref: 'SystemWebhook',
|
||||
},
|
||||
|
||||
errors: {
|
||||
noSuchSystemWebhook: {
|
||||
message: 'No such SystemWebhook.',
|
||||
code: 'NO_SUCH_SYSTEM_WEBHOOK',
|
||||
id: '38dd1ffe-04b4-6ff5-d8ba-4e6a6ae22c9d',
|
||||
kind: 'server',
|
||||
httpStatusCode: 404,
|
||||
},
|
||||
},
|
||||
} as const;
|
||||
|
||||
export const paramDef = {
|
||||
type: 'object',
|
||||
properties: {
|
||||
id: {
|
||||
type: 'string',
|
||||
format: 'misskey:id',
|
||||
},
|
||||
},
|
||||
required: ['id'],
|
||||
} as const;
|
||||
|
||||
@Injectable()
|
||||
export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-disable-line import/no-default-export
|
||||
constructor(
|
||||
private systemWebhookService: SystemWebhookService,
|
||||
private systemWebhookEntityService: SystemWebhookEntityService,
|
||||
) {
|
||||
super(meta, paramDef, async (ps) => {
|
||||
const webhooks = await this.systemWebhookService.fetchSystemWebhooks({ ids: [ps.id] });
|
||||
if (webhooks.length === 0) {
|
||||
throw new ApiError(meta.errors.noSuchSystemWebhook);
|
||||
}
|
||||
|
||||
return this.systemWebhookEntityService.pack(webhooks[0]);
|
||||
});
|
||||
}
|
||||
}
|
|
@ -0,0 +1,91 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: syuilo and misskey-project
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { Endpoint } from '@/server/api/endpoint-base.js';
|
||||
import { SystemWebhookEntityService } from '@/core/entities/SystemWebhookEntityService.js';
|
||||
import { systemWebhookEventTypes } from '@/models/SystemWebhook.js';
|
||||
import { SystemWebhookService } from '@/core/SystemWebhookService.js';
|
||||
|
||||
export const meta = {
|
||||
tags: ['admin', 'system-webhook'],
|
||||
|
||||
requireCredential: true,
|
||||
requireModerator: true,
|
||||
secure: true,
|
||||
kind: 'write:admin:system-webhook',
|
||||
|
||||
res: {
|
||||
type: 'object',
|
||||
ref: 'SystemWebhook',
|
||||
},
|
||||
} as const;
|
||||
|
||||
export const paramDef = {
|
||||
type: 'object',
|
||||
properties: {
|
||||
id: {
|
||||
type: 'string',
|
||||
format: 'misskey:id',
|
||||
},
|
||||
isActive: {
|
||||
type: 'boolean',
|
||||
},
|
||||
name: {
|
||||
type: 'string',
|
||||
minLength: 1,
|
||||
maxLength: 255,
|
||||
},
|
||||
on: {
|
||||
type: 'array',
|
||||
items: {
|
||||
type: 'string',
|
||||
enum: systemWebhookEventTypes,
|
||||
},
|
||||
},
|
||||
url: {
|
||||
type: 'string',
|
||||
minLength: 1,
|
||||
maxLength: 1024,
|
||||
},
|
||||
secret: {
|
||||
type: 'string',
|
||||
minLength: 1,
|
||||
maxLength: 1024,
|
||||
},
|
||||
},
|
||||
required: [
|
||||
'id',
|
||||
'isActive',
|
||||
'name',
|
||||
'on',
|
||||
'url',
|
||||
'secret',
|
||||
],
|
||||
} as const;
|
||||
|
||||
@Injectable()
|
||||
export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-disable-line import/no-default-export
|
||||
constructor(
|
||||
private systemWebhookService: SystemWebhookService,
|
||||
private systemWebhookEntityService: SystemWebhookEntityService,
|
||||
) {
|
||||
super(meta, paramDef, async (ps, me) => {
|
||||
const result = await this.systemWebhookService.updateSystemWebhook(
|
||||
{
|
||||
id: ps.id,
|
||||
isActive: ps.isActive,
|
||||
name: ps.name,
|
||||
on: ps.on,
|
||||
url: ps.url,
|
||||
secret: ps.secret,
|
||||
},
|
||||
me,
|
||||
);
|
||||
|
||||
return this.systemWebhookEntityService.pack(result);
|
||||
});
|
||||
}
|
||||
}
|
|
@ -1,3 +1,8 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: marie and other Sharkey contributors
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import { Endpoint } from '@/server/api/endpoint-base.js';
|
||||
import type { UsersRepository, UserProfilesRepository } from '@/models/_.js';
|
||||
|
|
|
@ -1,3 +1,8 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: marie and other Sharkey contributors
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import { Endpoint } from '@/server/api/endpoint-base.js';
|
||||
import type { UsersRepository } from '@/models/_.js';
|
||||
|
|
|
@ -6,7 +6,6 @@
|
|||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import { Endpoint } from '@/server/api/endpoint-base.js';
|
||||
import type { UsersRepository } from '@/models/_.js';
|
||||
import { ModerationLogService } from '@/core/ModerationLogService.js';
|
||||
import { UserSuspendService } from '@/core/UserSuspendService.js';
|
||||
import { DI } from '@/di-symbols.js';
|
||||
|
||||
|
@ -34,7 +33,6 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
private usersRepository: UsersRepository,
|
||||
|
||||
private userSuspendService: UserSuspendService,
|
||||
private moderationLogService: ModerationLogService,
|
||||
) {
|
||||
super(meta, paramDef, async (ps, me) => {
|
||||
const user = await this.usersRepository.findOneBy({ id: ps.userId });
|
||||
|
@ -43,17 +41,7 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
throw new Error('user not found');
|
||||
}
|
||||
|
||||
await this.usersRepository.update(user.id, {
|
||||
isSuspended: false,
|
||||
});
|
||||
|
||||
this.moderationLogService.log(me, 'unsuspend', {
|
||||
userId: user.id,
|
||||
userUsername: user.username,
|
||||
userHost: user.host,
|
||||
});
|
||||
|
||||
this.userSuspendService.doPostUnsuspend(user);
|
||||
await this.userSuspendService.unsuspend(user, me);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
|
@ -100,7 +100,6 @@ export const paramDef = {
|
|||
type: 'string',
|
||||
},
|
||||
},
|
||||
summalyProxy: { type: 'string', nullable: true },
|
||||
deeplAuthKey: { type: 'string', nullable: true },
|
||||
deeplIsPro: { type: 'boolean' },
|
||||
deeplFreeMode: { type: 'boolean' },
|
||||
|
@ -121,6 +120,7 @@ export const paramDef = {
|
|||
impressumUrl: { type: 'string', nullable: true },
|
||||
donationUrl: { type: 'string', nullable: true },
|
||||
privacyPolicyUrl: { type: 'string', nullable: true },
|
||||
inquiryUrl: { type: 'string', nullable: true },
|
||||
useObjectStorage: { type: 'boolean' },
|
||||
objectStorageBaseUrl: { type: 'string', nullable: true },
|
||||
objectStorageBucket: { type: 'string', nullable: true },
|
||||
|
@ -165,6 +165,23 @@ export const paramDef = {
|
|||
type: 'string',
|
||||
},
|
||||
},
|
||||
mediaSilencedHosts: {
|
||||
type: 'array',
|
||||
nullable: true,
|
||||
items: {
|
||||
type: 'string',
|
||||
},
|
||||
},
|
||||
summalyProxy: {
|
||||
type: 'string', nullable: true,
|
||||
description: '[Deprecated] Use "urlPreviewSummaryProxyUrl" instead.',
|
||||
},
|
||||
urlPreviewEnabled: { type: 'boolean' },
|
||||
urlPreviewTimeout: { type: 'integer' },
|
||||
urlPreviewMaximumContentLength: { type: 'integer' },
|
||||
urlPreviewRequireContentLength: { type: 'boolean' },
|
||||
urlPreviewUserAgent: { type: 'string', nullable: true },
|
||||
urlPreviewSummaryProxyUrl: { type: 'string', nullable: true },
|
||||
},
|
||||
required: [],
|
||||
} as const;
|
||||
|
@ -216,6 +233,14 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
return h !== '' && h !== lv && !set.blockedHosts?.includes(h);
|
||||
});
|
||||
}
|
||||
if (Array.isArray(ps.mediaSilencedHosts)) {
|
||||
let lastValue = '';
|
||||
set.mediaSilencedHosts = ps.mediaSilencedHosts.sort().filter((h) => {
|
||||
const lv = lastValue;
|
||||
lastValue = h;
|
||||
return h !== '' && h !== lv && !set.blockedHosts?.includes(h);
|
||||
});
|
||||
}
|
||||
if (ps.themeColor !== undefined) {
|
||||
set.themeColor = ps.themeColor;
|
||||
}
|
||||
|
@ -372,10 +397,6 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
set.langs = ps.langs.filter(Boolean);
|
||||
}
|
||||
|
||||
if (ps.summalyProxy !== undefined) {
|
||||
set.summalyProxy = ps.summalyProxy;
|
||||
}
|
||||
|
||||
if (ps.enableEmail !== undefined) {
|
||||
set.enableEmail = ps.enableEmail;
|
||||
}
|
||||
|
@ -440,6 +461,10 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
set.privacyPolicyUrl = ps.privacyPolicyUrl;
|
||||
}
|
||||
|
||||
if (ps.inquiryUrl !== undefined) {
|
||||
set.inquiryUrl = ps.inquiryUrl;
|
||||
}
|
||||
|
||||
if (ps.useObjectStorage !== undefined) {
|
||||
set.useObjectStorage = ps.useObjectStorage;
|
||||
}
|
||||
|
@ -624,6 +649,32 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
set.bannedEmailDomains = ps.bannedEmailDomains;
|
||||
}
|
||||
|
||||
if (ps.urlPreviewEnabled !== undefined) {
|
||||
set.urlPreviewEnabled = ps.urlPreviewEnabled;
|
||||
}
|
||||
|
||||
if (ps.urlPreviewTimeout !== undefined) {
|
||||
set.urlPreviewTimeout = ps.urlPreviewTimeout;
|
||||
}
|
||||
|
||||
if (ps.urlPreviewMaximumContentLength !== undefined) {
|
||||
set.urlPreviewMaximumContentLength = ps.urlPreviewMaximumContentLength;
|
||||
}
|
||||
|
||||
if (ps.urlPreviewRequireContentLength !== undefined) {
|
||||
set.urlPreviewRequireContentLength = ps.urlPreviewRequireContentLength;
|
||||
}
|
||||
|
||||
if (ps.urlPreviewUserAgent !== undefined) {
|
||||
const value = (ps.urlPreviewUserAgent ?? '').trim();
|
||||
set.urlPreviewUserAgent = value === '' ? null : ps.urlPreviewUserAgent;
|
||||
}
|
||||
|
||||
if (ps.summalyProxy !== undefined || ps.urlPreviewSummaryProxyUrl !== undefined) {
|
||||
const value = ((ps.urlPreviewSummaryProxyUrl ?? ps.summalyProxy) ?? '').trim();
|
||||
set.urlPreviewSummaryProxyUrl = value === '' ? null : value;
|
||||
}
|
||||
|
||||
const before = await this.metaService.fetch(true);
|
||||
|
||||
await this.metaService.update(set);
|
||||
|
|
|
@ -7,9 +7,9 @@ import { Inject, Injectable } from '@nestjs/common';
|
|||
import { Brackets } from 'typeorm';
|
||||
import { Endpoint } from '@/server/api/endpoint-base.js';
|
||||
import { QueryService } from '@/core/QueryService.js';
|
||||
import { AnnouncementService } from '@/core/AnnouncementService.js';
|
||||
import { AnnouncementEntityService } from '@/core/entities/AnnouncementEntityService.js';
|
||||
import { DI } from '@/di-symbols.js';
|
||||
import type { AnnouncementReadsRepository, AnnouncementsRepository } from '@/models/_.js';
|
||||
import type { AnnouncementsRepository } from '@/models/_.js';
|
||||
|
||||
export const meta = {
|
||||
tags: ['meta'],
|
||||
|
@ -45,11 +45,8 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
@Inject(DI.announcementsRepository)
|
||||
private announcementsRepository: AnnouncementsRepository,
|
||||
|
||||
@Inject(DI.announcementReadsRepository)
|
||||
private announcementReadsRepository: AnnouncementReadsRepository,
|
||||
|
||||
private queryService: QueryService,
|
||||
private announcementService: AnnouncementService,
|
||||
private announcementEntityService: AnnouncementEntityService,
|
||||
) {
|
||||
super(meta, paramDef, async (ps, me) => {
|
||||
const query = this.queryService.makePaginationQuery(this.announcementsRepository.createQueryBuilder('announcement'), ps.sinceId, ps.untilId)
|
||||
|
@ -61,7 +58,7 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
|
||||
const announcements = await query.limit(ps.limit).getMany();
|
||||
|
||||
return this.announcementService.packMany(announcements, me);
|
||||
return this.announcementEntityService.packMany(announcements, me);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,54 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: syuilo and misskey-project
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { EntityNotFoundError } from 'typeorm';
|
||||
import { Endpoint } from '@/server/api/endpoint-base.js';
|
||||
import { AnnouncementService } from '@/core/AnnouncementService.js';
|
||||
import { ApiError } from '../../error.js';
|
||||
|
||||
export const meta = {
|
||||
tags: ['meta'],
|
||||
|
||||
requireCredential: false,
|
||||
|
||||
res: {
|
||||
type: 'object',
|
||||
optional: false, nullable: false,
|
||||
ref: 'Announcement',
|
||||
},
|
||||
|
||||
errors: {
|
||||
noSuchAnnouncement: {
|
||||
message: 'No such announcement.',
|
||||
code: 'NO_SUCH_ANNOUNCEMENT',
|
||||
id: 'b57b5e1d-4f49-404a-9edb-46b00268f121',
|
||||
},
|
||||
},
|
||||
} as const;
|
||||
|
||||
export const paramDef = {
|
||||
type: 'object',
|
||||
properties: {
|
||||
announcementId: { type: 'string', format: 'misskey:id' },
|
||||
},
|
||||
required: ['announcementId'],
|
||||
} as const;
|
||||
|
||||
@Injectable()
|
||||
export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-disable-line import/no-default-export
|
||||
constructor(
|
||||
private announcementService: AnnouncementService,
|
||||
) {
|
||||
super(meta, paramDef, async (ps, me) => {
|
||||
try {
|
||||
return await this.announcementService.getAnnouncement(ps.announcementId, me);
|
||||
} catch (err) {
|
||||
if (err instanceof EntityNotFoundError) throw new ApiError(meta.errors.noSuchAnnouncement);
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
|
@ -65,11 +65,11 @@ export const paramDef = {
|
|||
} },
|
||||
caseSensitive: { type: 'boolean' },
|
||||
localOnly: { type: 'boolean' },
|
||||
excludeBots: { type: 'boolean' },
|
||||
withReplies: { type: 'boolean' },
|
||||
withFile: { type: 'boolean' },
|
||||
notify: { type: 'boolean' },
|
||||
},
|
||||
required: ['name', 'src', 'keywords', 'excludeKeywords', 'users', 'caseSensitive', 'withReplies', 'withFile', 'notify'],
|
||||
required: ['name', 'src', 'keywords', 'excludeKeywords', 'users', 'caseSensitive', 'withReplies', 'withFile'],
|
||||
} as const;
|
||||
|
||||
@Injectable()
|
||||
|
@ -94,7 +94,7 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
const currentAntennasCount = await this.antennasRepository.countBy({
|
||||
userId: me.id,
|
||||
});
|
||||
if (currentAntennasCount > (await this.roleService.getUserPolicies(me.id)).antennaLimit) {
|
||||
if (currentAntennasCount >= (await this.roleService.getUserPolicies(me.id)).antennaLimit) {
|
||||
throw new ApiError(meta.errors.tooManyAntennas);
|
||||
}
|
||||
|
||||
|
@ -113,7 +113,7 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
|
||||
const now = new Date();
|
||||
|
||||
const antenna = await this.antennasRepository.insert({
|
||||
const antenna = await this.antennasRepository.insertOne({
|
||||
id: this.idService.gen(now.getTime()),
|
||||
lastUsedAt: now,
|
||||
userId: me.id,
|
||||
|
@ -125,10 +125,10 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
users: ps.users,
|
||||
caseSensitive: ps.caseSensitive,
|
||||
localOnly: ps.localOnly,
|
||||
excludeBots: ps.excludeBots,
|
||||
withReplies: ps.withReplies,
|
||||
withFile: ps.withFile,
|
||||
notify: ps.notify,
|
||||
}).then(x => this.antennasRepository.findOneByOrFail(x.identifiers[0]));
|
||||
});
|
||||
|
||||
this.globalEventService.publishInternalEvent('antennaCreated', antenna);
|
||||
|
||||
|
|
|
@ -64,11 +64,11 @@ export const paramDef = {
|
|||
} },
|
||||
caseSensitive: { type: 'boolean' },
|
||||
localOnly: { type: 'boolean' },
|
||||
excludeBots: { type: 'boolean' },
|
||||
withReplies: { type: 'boolean' },
|
||||
withFile: { type: 'boolean' },
|
||||
notify: { type: 'boolean' },
|
||||
},
|
||||
required: ['antennaId', 'name', 'src', 'keywords', 'excludeKeywords', 'users', 'caseSensitive', 'withReplies', 'withFile', 'notify'],
|
||||
required: ['antennaId'],
|
||||
} as const;
|
||||
|
||||
@Injectable()
|
||||
|
@ -84,8 +84,10 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
private globalEventService: GlobalEventService,
|
||||
) {
|
||||
super(meta, paramDef, async (ps, me) => {
|
||||
if (ps.keywords.flat().every(x => x === '') && ps.excludeKeywords.flat().every(x => x === '')) {
|
||||
throw new Error('either keywords or excludeKeywords is required.');
|
||||
if (ps.keywords && ps.excludeKeywords) {
|
||||
if (ps.keywords.flat().every(x => x === '') && ps.excludeKeywords.flat().every(x => x === '')) {
|
||||
throw new Error('either keywords or excludeKeywords is required.');
|
||||
}
|
||||
}
|
||||
// Fetch the antenna
|
||||
const antenna = await this.antennasRepository.findOneBy({
|
||||
|
@ -99,7 +101,7 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
|
||||
let userList;
|
||||
|
||||
if (ps.src === 'list' && ps.userListId) {
|
||||
if ((ps.src === 'list' || antenna.src === 'list') && ps.userListId) {
|
||||
userList = await this.userListsRepository.findOneBy({
|
||||
id: ps.userListId,
|
||||
userId: me.id,
|
||||
|
@ -113,15 +115,15 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
await this.antennasRepository.update(antenna.id, {
|
||||
name: ps.name,
|
||||
src: ps.src,
|
||||
userListId: userList ? userList.id : null,
|
||||
userListId: ps.userListId !== undefined ? userList ? userList.id : null : undefined,
|
||||
keywords: ps.keywords,
|
||||
excludeKeywords: ps.excludeKeywords,
|
||||
users: ps.users,
|
||||
caseSensitive: ps.caseSensitive,
|
||||
localOnly: ps.localOnly,
|
||||
excludeBots: ps.excludeBots,
|
||||
withReplies: ps.withReplies,
|
||||
withFile: ps.withFile,
|
||||
notify: ps.notify,
|
||||
isActive: true,
|
||||
lastUsedAt: new Date(),
|
||||
});
|
||||
|
|
|
@ -55,7 +55,7 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
const permission = unique(ps.permission.map(v => v.replace(/^(.+)(\/|-)(read|write)$/, '$3:$1')));
|
||||
|
||||
// Create account
|
||||
const app = await this.appsRepository.insert({
|
||||
const app = await this.appsRepository.insertOne({
|
||||
id: this.idService.gen(),
|
||||
userId: me ? me.id : null,
|
||||
name: ps.name,
|
||||
|
@ -63,7 +63,7 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
permission,
|
||||
callbackUrl: ps.callbackUrl,
|
||||
secret: secret,
|
||||
}).then(x => this.appsRepository.findOneByOrFail(x.identifiers[0]));
|
||||
});
|
||||
|
||||
return await this.appEntityService.pack(app, null, {
|
||||
detail: true,
|
||||
|
|
|
@ -79,11 +79,11 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
const token = randomUUID();
|
||||
|
||||
// Create session token document
|
||||
const doc = await this.authSessionsRepository.insert({
|
||||
const doc = await this.authSessionsRepository.insertOne({
|
||||
id: this.idService.gen(),
|
||||
appId: app.id,
|
||||
token: token,
|
||||
}).then(x => this.authSessionsRepository.findOneByOrFail(x.identifiers[0]));
|
||||
});
|
||||
|
||||
return {
|
||||
token: doc.token,
|
||||
|
|
|
@ -6,9 +6,10 @@
|
|||
import ms from 'ms';
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import { Endpoint } from '@/server/api/endpoint-base.js';
|
||||
import type { UsersRepository, BlockingsRepository } from '@/models/_.js';
|
||||
import type { UsersRepository, BlockingsRepository, MutingsRepository } from '@/models/_.js';
|
||||
import { UserEntityService } from '@/core/entities/UserEntityService.js';
|
||||
import { UserBlockingService } from '@/core/UserBlockingService.js';
|
||||
import { UserMutingService } from '@/core/UserMutingService.js';
|
||||
import { DI } from '@/di-symbols.js';
|
||||
import { GetterService } from '@/server/api/GetterService.js';
|
||||
import { ApiError } from '../../error.js';
|
||||
|
@ -70,9 +71,13 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
@Inject(DI.blockingsRepository)
|
||||
private blockingsRepository: BlockingsRepository,
|
||||
|
||||
@Inject(DI.mutingsRepository)
|
||||
private mutingsRepository: MutingsRepository,
|
||||
|
||||
private userEntityService: UserEntityService,
|
||||
private getterService: GetterService,
|
||||
private userBlockingService: UserBlockingService,
|
||||
private userMutingService: UserMutingService,
|
||||
) {
|
||||
super(meta, paramDef, async (ps, me) => {
|
||||
const blocker = await this.usersRepository.findOneByOrFail({ id: me.id });
|
||||
|
@ -100,7 +105,19 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
throw new ApiError(meta.errors.alreadyBlocking);
|
||||
}
|
||||
|
||||
await this.userBlockingService.block(blocker, blockee);
|
||||
await Promise.all([
|
||||
this.userBlockingService.block(blocker, blockee),
|
||||
this.mutingsRepository.exists({
|
||||
where: {
|
||||
muterId: blocker.id,
|
||||
muteeId: blockee.id,
|
||||
},
|
||||
}).then(exists => {
|
||||
if (!exists) {
|
||||
this.userMutingService.mute(blocker, blockee, null);
|
||||
}
|
||||
}),
|
||||
]);
|
||||
|
||||
return await this.userEntityService.pack(blockee.id, blocker, {
|
||||
schema: 'UserDetailedNotMe',
|
||||
|
|
|
@ -6,9 +6,10 @@
|
|||
import ms from 'ms';
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import { Endpoint } from '@/server/api/endpoint-base.js';
|
||||
import type { UsersRepository, BlockingsRepository } from '@/models/_.js';
|
||||
import type { UsersRepository, BlockingsRepository, MutingsRepository } from '@/models/_.js';
|
||||
import { UserEntityService } from '@/core/entities/UserEntityService.js';
|
||||
import { UserBlockingService } from '@/core/UserBlockingService.js';
|
||||
import { UserMutingService } from '@/core/UserMutingService.js';
|
||||
import { DI } from '@/di-symbols.js';
|
||||
import { GetterService } from '@/server/api/GetterService.js';
|
||||
import { ApiError } from '../../error.js';
|
||||
|
@ -70,9 +71,13 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
@Inject(DI.blockingsRepository)
|
||||
private blockingsRepository: BlockingsRepository,
|
||||
|
||||
@Inject(DI.mutingsRepository)
|
||||
private mutingsRepository: MutingsRepository,
|
||||
|
||||
private userEntityService: UserEntityService,
|
||||
private getterService: GetterService,
|
||||
private userBlockingService: UserBlockingService,
|
||||
private userMutingService: UserMutingService,
|
||||
) {
|
||||
super(meta, paramDef, async (ps, me) => {
|
||||
const blocker = await this.usersRepository.findOneByOrFail({ id: me.id });
|
||||
|
@ -101,7 +106,17 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
}
|
||||
|
||||
// Delete blocking
|
||||
await this.userBlockingService.unblock(blocker, blockee);
|
||||
await Promise.all([
|
||||
this.userBlockingService.unblock(blocker, blockee),
|
||||
this.mutingsRepository.findOneBy({
|
||||
muterId: blocker.id,
|
||||
muteeId: blockee.id,
|
||||
}).then(exists => {
|
||||
if (exists) {
|
||||
this.userMutingService.unmute([exists]);
|
||||
}
|
||||
}),
|
||||
]);
|
||||
|
||||
return await this.userEntityService.pack(blockee.id, blocker, {
|
||||
schema: 'UserDetailedNotMe',
|
||||
|
|
|
@ -81,7 +81,7 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
}
|
||||
}
|
||||
|
||||
const channel = await this.channelsRepository.insert({
|
||||
const channel = await this.channelsRepository.insertOne({
|
||||
id: this.idService.gen(),
|
||||
userId: me.id,
|
||||
name: ps.name,
|
||||
|
@ -90,7 +90,7 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
isSensitive: ps.isSensitive ?? false,
|
||||
...(ps.color !== undefined ? { color: ps.color } : {}),
|
||||
allowRenoteToExternal: ps.allowRenoteToExternal ?? true,
|
||||
} as MiChannel).then(x => this.channelsRepository.findOneByOrFail(x.identifiers[0]));
|
||||
} as MiChannel);
|
||||
|
||||
return await this.channelEntityService.pack(channel, me);
|
||||
});
|
||||
|
|
|
@ -16,6 +16,7 @@ import { MetaService } from '@/core/MetaService.js';
|
|||
import { FanoutTimelineEndpointService } from '@/core/FanoutTimelineEndpointService.js';
|
||||
import { MiLocalUser } from '@/models/User.js';
|
||||
import { ApiError } from '../../error.js';
|
||||
import { Brackets } from 'typeorm';
|
||||
|
||||
export const meta = {
|
||||
tags: ['notes', 'channels'],
|
||||
|
@ -52,6 +53,12 @@ export const paramDef = {
|
|||
sinceDate: { type: 'integer' },
|
||||
untilDate: { type: 'integer' },
|
||||
allowPartial: { type: 'boolean', default: false }, // true is recommended but for compatibility false by default
|
||||
withRenotes: { type: 'boolean', default: true },
|
||||
withFiles: {
|
||||
type: 'boolean',
|
||||
default: false,
|
||||
description: 'Only show notes that have attached files.',
|
||||
},
|
||||
},
|
||||
required: ['channelId'],
|
||||
} as const;
|
||||
|
@ -90,7 +97,7 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
if (me) this.activeUsersChart.read(me);
|
||||
|
||||
if (!serverSettings.enableFanoutTimeline) {
|
||||
return await this.noteEntityService.packMany(await this.getFromDb({ untilId, sinceId, limit: ps.limit, channelId: channel.id }, me), me);
|
||||
return await this.noteEntityService.packMany(await this.getFromDb({ untilId, sinceId, limit: ps.limit, channelId: channel.id, withFiles: ps.withFiles, withRenotes: ps.withRenotes }, me), me);
|
||||
}
|
||||
|
||||
return await this.fanoutTimelineEndpointService.timeline({
|
||||
|
@ -101,9 +108,10 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
me,
|
||||
useDbFallback: true,
|
||||
redisTimelines: [`channelTimeline:${channel.id}`],
|
||||
excludePureRenotes: false,
|
||||
excludePureRenotes: !ps.withRenotes,
|
||||
excludeNoFiles: ps.withFiles,
|
||||
dbFallback: async (untilId, sinceId, limit) => {
|
||||
return await this.getFromDb({ untilId, sinceId, limit, channelId: channel.id }, me);
|
||||
return await this.getFromDb({ untilId, sinceId, limit, channelId: channel.id, withFiles: ps.withFiles, withRenotes: ps.withRenotes }, me);
|
||||
},
|
||||
});
|
||||
});
|
||||
|
@ -113,7 +121,9 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
untilId: string | null,
|
||||
sinceId: string | null,
|
||||
limit: number,
|
||||
channelId: string
|
||||
channelId: string,
|
||||
withFiles: boolean,
|
||||
withRenotes: boolean,
|
||||
}, me: MiLocalUser | null) {
|
||||
//#region fallback to database
|
||||
const query = this.queryService.makePaginationQuery(this.notesRepository.createQueryBuilder('note'), ps.sinceId, ps.untilId)
|
||||
|
@ -129,6 +139,20 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
this.queryService.generateMutedUserQuery(query, me);
|
||||
this.queryService.generateBlockedUserQuery(query, me);
|
||||
}
|
||||
|
||||
if (ps.withRenotes === false) {
|
||||
query.andWhere(new Brackets(qb => {
|
||||
qb.orWhere('note.renoteId IS NULL');
|
||||
qb.orWhere(new Brackets(qb => {
|
||||
qb.orWhere('note.text IS NOT NULL');
|
||||
qb.orWhere('note.fileIds != \'{}\'');
|
||||
}));
|
||||
}));
|
||||
}
|
||||
|
||||
if (ps.withFiles) {
|
||||
query.andWhere('note.fileIds != \'{}\'');
|
||||
}
|
||||
//#endregion
|
||||
|
||||
return await query.limit(ps.limit).getMany();
|
||||
|
|
|
@ -3,7 +3,7 @@
|
|||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { Endpoint } from '@/server/api/endpoint-base.js';
|
||||
import { ClipEntityService } from '@/core/entities/ClipEntityService.js';
|
||||
import { ClipService } from '@/core/ClipService.js';
|
||||
|
@ -42,7 +42,7 @@ export const paramDef = {
|
|||
isPublic: { type: 'boolean' },
|
||||
description: { type: 'string', nullable: true, minLength: 1, maxLength: 2048 },
|
||||
},
|
||||
required: ['clipId', 'name'],
|
||||
required: ['clipId'],
|
||||
} as const;
|
||||
|
||||
@Injectable()
|
||||
|
|
|
@ -9,6 +9,8 @@ import type { DriveFilesRepository } from '@/models/_.js';
|
|||
import { QueryService } from '@/core/QueryService.js';
|
||||
import { DriveFileEntityService } from '@/core/entities/DriveFileEntityService.js';
|
||||
import { DI } from '@/di-symbols.js';
|
||||
import { sqlLikeEscape } from '@/misc/sql-like-escape.js';
|
||||
import { Brackets } from 'typeorm';
|
||||
|
||||
export const meta = {
|
||||
tags: ['drive'],
|
||||
|
@ -38,6 +40,7 @@ export const paramDef = {
|
|||
folderId: { type: 'string', format: 'misskey:id', nullable: true, default: null },
|
||||
type: { type: 'string', nullable: true, pattern: /^[a-zA-Z\/\-*]+$/.toString().slice(1, -1) },
|
||||
sort: { type: 'string', nullable: true, enum: ['+createdAt', '-createdAt', '+name', '-name', '+size', '-size', null] },
|
||||
searchQuery: { type: 'string', default: '' }
|
||||
},
|
||||
required: [],
|
||||
} as const;
|
||||
|
@ -61,6 +64,15 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
query.andWhere('file.folderId IS NULL');
|
||||
}
|
||||
|
||||
if (ps.searchQuery.length > 0) {
|
||||
const args = { searchQuery: `%${sqlLikeEscape(ps.searchQuery)}%` };
|
||||
query.andWhere(new Brackets((qb) => {
|
||||
qb
|
||||
.where('file.name ILIKE :searchQuery', args)
|
||||
.orWhere('file.comment ILIKE :searchQuery', args);
|
||||
}));
|
||||
}
|
||||
|
||||
if (ps.type) {
|
||||
if (ps.type.endsWith('/*')) {
|
||||
query.andWhere('file.type like :type', { type: ps.type.replace('/*', '/') + '%' });
|
||||
|
|
|
@ -55,7 +55,7 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
folderId: ps.folderId ?? IsNull(),
|
||||
});
|
||||
|
||||
return await Promise.all(files.map(file => this.driveFileEntityService.pack(file, { self: true })));
|
||||
return await this.driveFileEntityService.packMany(files, { self: true });
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
|
@ -9,6 +9,7 @@ import type { DriveFoldersRepository } from '@/models/_.js';
|
|||
import { QueryService } from '@/core/QueryService.js';
|
||||
import { DriveFolderEntityService } from '@/core/entities/DriveFolderEntityService.js';
|
||||
import { DI } from '@/di-symbols.js';
|
||||
import { sqlLikeEscape } from '@/misc/sql-like-escape.js';
|
||||
|
||||
export const meta = {
|
||||
tags: ['drive'],
|
||||
|
@ -36,6 +37,7 @@ export const paramDef = {
|
|||
sinceId: { type: 'string', format: 'misskey:id' },
|
||||
untilId: { type: 'string', format: 'misskey:id' },
|
||||
folderId: { type: 'string', format: 'misskey:id', nullable: true, default: null },
|
||||
searchQuery: { type: 'string', default: '' }
|
||||
},
|
||||
required: [],
|
||||
} as const;
|
||||
|
@ -59,6 +61,9 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
query.andWhere('folder.parentId IS NULL');
|
||||
}
|
||||
|
||||
if (ps.searchQuery.length > 0) {
|
||||
query.andWhere('folder.name ILIKE :searchQuery', { searchQuery: `%${sqlLikeEscape(ps.searchQuery)}%` });
|
||||
}
|
||||
const folders = await query.limit(ps.limit).getMany();
|
||||
|
||||
return await Promise.all(folders.map(folder => this.driveFolderEntityService.pack(folder)));
|
||||
|
|
|
@ -76,12 +76,12 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
}
|
||||
|
||||
// Create folder
|
||||
const folder = await this.driveFoldersRepository.insert({
|
||||
const folder = await this.driveFoldersRepository.insertOne({
|
||||
id: this.idService.gen(),
|
||||
name: ps.name,
|
||||
parentId: parent !== null ? parent.id : null,
|
||||
userId: me.id,
|
||||
}).then(x => this.driveFoldersRepository.findOneByOrFail(x.identifiers[0]));
|
||||
});
|
||||
|
||||
const folderObj = await this.driveFolderEntityService.pack(folder);
|
||||
|
||||
|
|
|
@ -96,15 +96,14 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
|
||||
// Check if the circular reference will occur
|
||||
const checkCircle = async (folderId: string): Promise<boolean> => {
|
||||
// Fetch folder
|
||||
const folder2 = await this.driveFoldersRepository.findOneBy({
|
||||
const folder2 = await this.driveFoldersRepository.findOneByOrFail({
|
||||
id: folderId,
|
||||
});
|
||||
|
||||
if (folder2!.id === folder!.id) {
|
||||
if (folder2.id === folder.id) {
|
||||
return true;
|
||||
} else if (folder2!.parentId) {
|
||||
return await checkCircle(folder2!.parentId);
|
||||
} else if (folder2.parentId) {
|
||||
return await checkCircle(folder2.parentId);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
|
|
|
@ -136,9 +136,9 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
|
||||
if (typeof ps.suspended === 'boolean') {
|
||||
if (ps.suspended) {
|
||||
query.andWhere('instance.isSuspended = TRUE');
|
||||
query.andWhere('instance.suspensionState != \'none\'');
|
||||
} else {
|
||||
query.andWhere('instance.isSuspended = FALSE');
|
||||
query.andWhere('instance.suspensionState = \'none\'');
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -214,7 +214,7 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
|
||||
const instances = await query.limit(ps.limit).offset(ps.offset).getMany();
|
||||
|
||||
return await this.instanceEntityService.packMany(instances);
|
||||
return await this.instanceEntityService.packMany(instances, me);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
|
@ -108,9 +108,9 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
const gotPubCount = topPubInstances.map(x => x.followingCount).reduce((a, b) => a + b, 0);
|
||||
|
||||
return await awaitAll({
|
||||
topSubInstances: this.instanceEntityService.packMany(topSubInstances),
|
||||
topSubInstances: this.instanceEntityService.packMany(topSubInstances, me),
|
||||
otherFollowersCount: Math.max(0, allSubCount - gotSubCount),
|
||||
topPubInstances: this.instanceEntityService.packMany(topPubInstances),
|
||||
topPubInstances: this.instanceEntityService.packMany(topPubInstances, me),
|
||||
otherFollowingCount: Math.max(0, allPubCount - gotPubCount),
|
||||
});
|
||||
});
|
||||
|
|
|
@ -21,13 +21,188 @@ export const meta = {
|
|||
res: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
image: {
|
||||
type: 'object',
|
||||
optional: true,
|
||||
properties: {
|
||||
link: {
|
||||
type: 'string',
|
||||
optional: true,
|
||||
},
|
||||
url: {
|
||||
type: 'string',
|
||||
optional: false,
|
||||
},
|
||||
title: {
|
||||
type: 'string',
|
||||
optional: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
paginationLinks: {
|
||||
type: 'object',
|
||||
optional: true,
|
||||
properties: {
|
||||
self: {
|
||||
type: 'string',
|
||||
optional: true,
|
||||
},
|
||||
first: {
|
||||
type: 'string',
|
||||
optional: true,
|
||||
},
|
||||
next: {
|
||||
type: 'string',
|
||||
optional: true,
|
||||
},
|
||||
last: {
|
||||
type: 'string',
|
||||
optional: true,
|
||||
},
|
||||
prev: {
|
||||
type: 'string',
|
||||
optional: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
link: {
|
||||
type: 'string',
|
||||
optional: true,
|
||||
},
|
||||
title: {
|
||||
type: 'string',
|
||||
optional: true,
|
||||
},
|
||||
items: {
|
||||
type: 'array',
|
||||
optional: false,
|
||||
items: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
link: {
|
||||
type: 'string',
|
||||
optional: true,
|
||||
},
|
||||
guid: {
|
||||
type: 'string',
|
||||
optional: true,
|
||||
},
|
||||
title: {
|
||||
type: 'string',
|
||||
optional: true,
|
||||
},
|
||||
pubDate: {
|
||||
type: 'string',
|
||||
optional: true,
|
||||
},
|
||||
creator: {
|
||||
type: 'string',
|
||||
optional: true,
|
||||
},
|
||||
summary: {
|
||||
type: 'string',
|
||||
optional: true,
|
||||
},
|
||||
content: {
|
||||
type: 'string',
|
||||
optional: true,
|
||||
},
|
||||
isoDate: {
|
||||
type: 'string',
|
||||
optional: true,
|
||||
},
|
||||
categories: {
|
||||
type: 'array',
|
||||
optional: true,
|
||||
items: {
|
||||
type: 'string',
|
||||
},
|
||||
},
|
||||
contentSnippet: {
|
||||
type: 'string',
|
||||
optional: true,
|
||||
},
|
||||
enclosure: {
|
||||
type: 'object',
|
||||
optional: true,
|
||||
properties: {
|
||||
url: {
|
||||
type: 'string',
|
||||
optional: false,
|
||||
},
|
||||
length: {
|
||||
type: 'number',
|
||||
optional: true,
|
||||
},
|
||||
type: {
|
||||
type: 'string',
|
||||
optional: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
},
|
||||
feedUrl: {
|
||||
type: 'string',
|
||||
optional: true,
|
||||
},
|
||||
description: {
|
||||
type: 'string',
|
||||
optional: true,
|
||||
},
|
||||
itunes: {
|
||||
type: 'object',
|
||||
optional: true,
|
||||
additionalProperties: true,
|
||||
properties: {
|
||||
image: {
|
||||
type: 'string',
|
||||
optional: true,
|
||||
},
|
||||
owner: {
|
||||
type: 'object',
|
||||
optional: true,
|
||||
properties: {
|
||||
name: {
|
||||
type: 'string',
|
||||
optional: true,
|
||||
},
|
||||
email: {
|
||||
type: 'string',
|
||||
optional: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
author: {
|
||||
type: 'string',
|
||||
optional: true,
|
||||
},
|
||||
summary: {
|
||||
type: 'string',
|
||||
optional: true,
|
||||
},
|
||||
explicit: {
|
||||
type: 'string',
|
||||
optional: true,
|
||||
},
|
||||
categories: {
|
||||
type: 'array',
|
||||
optional: true,
|
||||
items: {
|
||||
type: 'string',
|
||||
},
|
||||
},
|
||||
keywords: {
|
||||
type: 'array',
|
||||
optional: true,
|
||||
items: {
|
||||
type: 'string',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
} as const;
|
||||
|
||||
|
|
|
@ -45,6 +45,7 @@ export const paramDef = {
|
|||
permissions: { type: 'array', items: {
|
||||
type: 'string',
|
||||
} },
|
||||
visibility: { type: 'string', enum: ['public', 'private'], default: 'public' },
|
||||
},
|
||||
required: ['title', 'summary', 'script', 'permissions'],
|
||||
} as const;
|
||||
|
@ -59,7 +60,7 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
private idService: IdService,
|
||||
) {
|
||||
super(meta, paramDef, async (ps, me) => {
|
||||
const flash = await this.flashsRepository.insert({
|
||||
const flash = await this.flashsRepository.insertOne({
|
||||
id: this.idService.gen(),
|
||||
userId: me.id,
|
||||
updatedAt: new Date(),
|
||||
|
@ -67,7 +68,8 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
summary: ps.summary,
|
||||
script: ps.script,
|
||||
permissions: ps.permissions,
|
||||
}).then(x => this.flashsRepository.findOneByOrFail(x.identifiers[0]));
|
||||
visibility: ps.visibility,
|
||||
});
|
||||
|
||||
return await this.flashEntityService.pack(flash);
|
||||
});
|
||||
|
|
|
@ -4,9 +4,11 @@
|
|||
*/
|
||||
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import type { FlashsRepository } from '@/models/_.js';
|
||||
import type { FlashsRepository, UsersRepository } from '@/models/_.js';
|
||||
import { Endpoint } from '@/server/api/endpoint-base.js';
|
||||
import { DI } from '@/di-symbols.js';
|
||||
import { ModerationLogService } from '@/core/ModerationLogService.js';
|
||||
import { RoleService } from '@/core/RoleService.js';
|
||||
import { ApiError } from '../../error.js';
|
||||
|
||||
export const meta = {
|
||||
|
@ -45,17 +47,35 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
constructor(
|
||||
@Inject(DI.flashsRepository)
|
||||
private flashsRepository: FlashsRepository,
|
||||
|
||||
@Inject(DI.usersRepository)
|
||||
private usersRepository: UsersRepository,
|
||||
|
||||
private moderationLogService: ModerationLogService,
|
||||
private roleService: RoleService,
|
||||
) {
|
||||
super(meta, paramDef, async (ps, me) => {
|
||||
const flash = await this.flashsRepository.findOneBy({ id: ps.flashId });
|
||||
|
||||
if (flash == null) {
|
||||
throw new ApiError(meta.errors.noSuchFlash);
|
||||
}
|
||||
if (flash.userId !== me.id) {
|
||||
|
||||
if (!await this.roleService.isModerator(me) && flash.userId !== me.id) {
|
||||
throw new ApiError(meta.errors.accessDenied);
|
||||
}
|
||||
|
||||
await this.flashsRepository.delete(flash.id);
|
||||
|
||||
if (flash.userId !== me.id) {
|
||||
const user = await this.usersRepository.findOneByOrFail({ id: flash.userId });
|
||||
this.moderationLogService.log(me, 'deleteFlash', {
|
||||
flashId: flash.id,
|
||||
flashUserId: flash.userId,
|
||||
flashUserUsername: user.username,
|
||||
flash,
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
|
@ -72,7 +72,7 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
.limit(ps.limit)
|
||||
.getMany();
|
||||
|
||||
return await Promise.all(requests.map(req => this.followRequestEntityService.pack(req)));
|
||||
return await this.followRequestEntityService.packMany(requests, me);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
|
@ -12,7 +12,6 @@ import type { MiDriveFile } from '@/models/DriveFile.js';
|
|||
import { IdService } from '@/core/IdService.js';
|
||||
import { GalleryPostEntityService } from '@/core/entities/GalleryPostEntityService.js';
|
||||
import { DI } from '@/di-symbols.js';
|
||||
import { isNotNull } from '@/misc/is-not-null.js';
|
||||
|
||||
export const meta = {
|
||||
tags: ['gallery'],
|
||||
|
@ -71,13 +70,13 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
id: fileId,
|
||||
userId: me.id,
|
||||
}),
|
||||
))).filter(isNotNull);
|
||||
))).filter(x => x != null);
|
||||
|
||||
if (files.length === 0) {
|
||||
throw new Error();
|
||||
}
|
||||
|
||||
const post = await this.galleryPostsRepository.insert(new MiGalleryPost({
|
||||
const post = await this.galleryPostsRepository.insertOne(new MiGalleryPost({
|
||||
id: this.idService.gen(),
|
||||
updatedAt: new Date(),
|
||||
title: ps.title,
|
||||
|
@ -85,7 +84,7 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
userId: me.id,
|
||||
isSensitive: ps.isSensitive,
|
||||
fileIds: files.map(file => file.id),
|
||||
})).then(x => this.galleryPostsRepository.findOneByOrFail(x.identifiers[0]));
|
||||
}));
|
||||
|
||||
return await this.galleryPostEntityService.pack(post, me);
|
||||
});
|
||||
|
|
|
@ -5,8 +5,10 @@
|
|||
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import { Endpoint } from '@/server/api/endpoint-base.js';
|
||||
import type { GalleryPostsRepository } from '@/models/_.js';
|
||||
import type { GalleryPostsRepository, UsersRepository } from '@/models/_.js';
|
||||
import { DI } from '@/di-symbols.js';
|
||||
import { ModerationLogService } from '@/core/ModerationLogService.js';
|
||||
import { RoleService } from '@/core/RoleService.js';
|
||||
import { ApiError } from '../../../error.js';
|
||||
|
||||
export const meta = {
|
||||
|
@ -23,6 +25,12 @@ export const meta = {
|
|||
code: 'NO_SUCH_POST',
|
||||
id: 'ae52f367-4bd7-4ecd-afc6-5672fff427f5',
|
||||
},
|
||||
|
||||
accessDenied: {
|
||||
message: 'Access denied.',
|
||||
code: 'ACCESS_DENIED',
|
||||
id: 'c86e09de-1c48-43ac-a435-1c7e42ed4496',
|
||||
},
|
||||
},
|
||||
} as const;
|
||||
|
||||
|
@ -39,18 +47,35 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
constructor(
|
||||
@Inject(DI.galleryPostsRepository)
|
||||
private galleryPostsRepository: GalleryPostsRepository,
|
||||
|
||||
@Inject(DI.usersRepository)
|
||||
private usersRepository: UsersRepository,
|
||||
|
||||
private moderationLogService: ModerationLogService,
|
||||
private roleService: RoleService,
|
||||
) {
|
||||
super(meta, paramDef, async (ps, me) => {
|
||||
const post = await this.galleryPostsRepository.findOneBy({
|
||||
id: ps.postId,
|
||||
userId: me.id,
|
||||
});
|
||||
const post = await this.galleryPostsRepository.findOneBy({ id: ps.postId });
|
||||
|
||||
if (post == null) {
|
||||
throw new ApiError(meta.errors.noSuchPost);
|
||||
}
|
||||
|
||||
if (!await this.roleService.isModerator(me) && post.userId !== me.id) {
|
||||
throw new ApiError(meta.errors.accessDenied);
|
||||
}
|
||||
|
||||
await this.galleryPostsRepository.delete(post.id);
|
||||
|
||||
if (post.userId !== me.id) {
|
||||
const user = await this.usersRepository.findOneByOrFail({ id: post.userId });
|
||||
this.moderationLogService.log(me, 'deleteGalleryPost', {
|
||||
postId: post.id,
|
||||
postUserId: post.userId,
|
||||
postUserUsername: user.username,
|
||||
post,
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
|
@ -10,7 +10,6 @@ import type { DriveFilesRepository, GalleryPostsRepository } from '@/models/_.js
|
|||
import type { MiDriveFile } from '@/models/DriveFile.js';
|
||||
import { GalleryPostEntityService } from '@/core/entities/GalleryPostEntityService.js';
|
||||
import { DI } from '@/di-symbols.js';
|
||||
import { isNotNull } from '@/misc/is-not-null.js';
|
||||
|
||||
export const meta = {
|
||||
tags: ['gallery'],
|
||||
|
@ -49,7 +48,7 @@ export const paramDef = {
|
|||
} },
|
||||
isSensitive: { type: 'boolean', default: false },
|
||||
},
|
||||
required: ['postId', 'title', 'fileIds'],
|
||||
required: ['postId'],
|
||||
} as const;
|
||||
|
||||
@Injectable()
|
||||
|
@ -64,15 +63,19 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
private galleryPostEntityService: GalleryPostEntityService,
|
||||
) {
|
||||
super(meta, paramDef, async (ps, me) => {
|
||||
const files = (await Promise.all(ps.fileIds.map(fileId =>
|
||||
this.driveFilesRepository.findOneBy({
|
||||
id: fileId,
|
||||
userId: me.id,
|
||||
}),
|
||||
))).filter(isNotNull);
|
||||
let files: Array<MiDriveFile> | undefined;
|
||||
|
||||
if (files.length === 0) {
|
||||
throw new Error();
|
||||
if (ps.fileIds) {
|
||||
files = (await Promise.all(ps.fileIds.map(fileId =>
|
||||
this.driveFilesRepository.findOneBy({
|
||||
id: fileId,
|
||||
userId: me.id,
|
||||
}),
|
||||
))).filter(x => x != null);
|
||||
|
||||
if (files.length === 0) {
|
||||
throw new Error();
|
||||
}
|
||||
}
|
||||
|
||||
await this.galleryPostsRepository.update({
|
||||
|
@ -83,7 +86,7 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
title: ps.title,
|
||||
description: ps.description,
|
||||
isSensitive: ps.isSensitive,
|
||||
fileIds: files.map(file => file.id),
|
||||
fileIds: files ? files.map(file => file.id) : undefined,
|
||||
});
|
||||
|
||||
const post = await this.galleryPostsRepository.findOneByOrFail({ id: ps.postId });
|
||||
|
|
|
@ -14,6 +14,7 @@ import type { UserProfilesRepository, UserSecurityKeysRepository } from '@/model
|
|||
import { WebAuthnService } from '@/core/WebAuthnService.js';
|
||||
import { ApiError } from '@/server/api/error.js';
|
||||
import { UserAuthService } from '@/core/UserAuthService.js';
|
||||
import ms from 'ms';
|
||||
|
||||
export const meta = {
|
||||
requireCredential: true,
|
||||
|
@ -21,6 +22,12 @@ export const meta = {
|
|||
|
||||
secure: true,
|
||||
|
||||
limit: {
|
||||
duration: ms('1hour'),
|
||||
max: 10,
|
||||
minInterval: ms('1sec'),
|
||||
},
|
||||
|
||||
errors: {
|
||||
incorrectPassword: {
|
||||
message: 'Incorrect password.',
|
||||
|
@ -98,10 +105,10 @@ export default class extends Endpoint<typeof meta, typeof paramDef> {
|
|||
}
|
||||
|
||||
const keyInfo = await this.webAuthnService.verifyRegistration(me.id, ps.credential);
|
||||
const keyId = keyInfo.credentialID;
|
||||
|
||||
const credentialId = Buffer.from(keyInfo.credentialID).toString('base64url');
|
||||
await this.userSecurityKeysRepository.insert({
|
||||
id: credentialId,
|
||||
id: keyId,
|
||||
userId: me.id,
|
||||
name: ps.name,
|
||||
publicKey: Buffer.from(keyInfo.credentialPublicKey).toString('base64url'),
|
||||
|
@ -118,7 +125,7 @@ export default class extends Endpoint<typeof meta, typeof paramDef> {
|
|||
}));
|
||||
|
||||
return {
|
||||
id: credentialId,
|
||||
id: keyId,
|
||||
name: ps.name,
|
||||
};
|
||||
});
|
||||
|
|
|
@ -12,6 +12,7 @@ import { DI } from '@/di-symbols.js';
|
|||
import { WebAuthnService } from '@/core/WebAuthnService.js';
|
||||
import { ApiError } from '@/server/api/error.js';
|
||||
import { UserAuthService } from '@/core/UserAuthService.js';
|
||||
import ms from 'ms';
|
||||
|
||||
export const meta = {
|
||||
requireCredential: true,
|
||||
|
@ -19,6 +20,12 @@ export const meta = {
|
|||
|
||||
secure: true,
|
||||
|
||||
limit: {
|
||||
duration: ms('1hour'),
|
||||
max: 10,
|
||||
minInterval: ms('1sec'),
|
||||
},
|
||||
|
||||
errors: {
|
||||
userNotFound: {
|
||||
message: 'User not found.',
|
||||
|
|
|
@ -14,6 +14,7 @@ import { DI } from '@/di-symbols.js';
|
|||
import type { Config } from '@/config.js';
|
||||
import { ApiError } from '@/server/api/error.js';
|
||||
import { UserAuthService } from '@/core/UserAuthService.js';
|
||||
import ms from 'ms';
|
||||
|
||||
export const meta = {
|
||||
requireCredential: true,
|
||||
|
@ -21,6 +22,12 @@ export const meta = {
|
|||
|
||||
secure: true,
|
||||
|
||||
limit: {
|
||||
duration: ms('1hour'),
|
||||
max: 10,
|
||||
minInterval: ms('1sec'),
|
||||
},
|
||||
|
||||
errors: {
|
||||
incorrectPassword: {
|
||||
message: 'Incorrect password.',
|
||||
|
|
|
@ -13,11 +13,18 @@ import { GlobalEventService } from '@/core/GlobalEventService.js';
|
|||
import { DI } from '@/di-symbols.js';
|
||||
import { ApiError } from '@/server/api/error.js';
|
||||
import { UserAuthService } from '@/core/UserAuthService.js';
|
||||
import ms from 'ms';
|
||||
|
||||
export const meta = {
|
||||
requireCredential: true,
|
||||
requireCredentialSecureMode: true,
|
||||
|
||||
limit: {
|
||||
duration: ms('1hour'),
|
||||
max: 10,
|
||||
minInterval: ms('1sec'),
|
||||
},
|
||||
|
||||
secure: true,
|
||||
|
||||
errors: {
|
||||
|
|
|
@ -13,6 +13,7 @@ import { GlobalEventService } from '@/core/GlobalEventService.js';
|
|||
import { DI } from '@/di-symbols.js';
|
||||
import { ApiError } from '@/server/api/error.js';
|
||||
import { UserAuthService } from '@/core/UserAuthService.js';
|
||||
import ms from 'ms';
|
||||
|
||||
export const meta = {
|
||||
requireCredential: true,
|
||||
|
@ -20,6 +21,12 @@ export const meta = {
|
|||
|
||||
secure: true,
|
||||
|
||||
limit: {
|
||||
duration: ms('1hour'),
|
||||
max: 10,
|
||||
minInterval: ms('1sec'),
|
||||
},
|
||||
|
||||
errors: {
|
||||
incorrectPassword: {
|
||||
message: 'Incorrect password.',
|
||||
|
|
|
@ -10,11 +10,18 @@ import { Endpoint } from '@/server/api/endpoint-base.js';
|
|||
import type { UserProfilesRepository } from '@/models/_.js';
|
||||
import { DI } from '@/di-symbols.js';
|
||||
import { UserAuthService } from '@/core/UserAuthService.js';
|
||||
import ms from 'ms';
|
||||
|
||||
export const meta = {
|
||||
requireCredential: true,
|
||||
requireCredentialSecureMode: true,
|
||||
|
||||
limit: {
|
||||
duration: ms('1hour'),
|
||||
max: 10,
|
||||
minInterval: ms('1sec'),
|
||||
},
|
||||
|
||||
secure: true,
|
||||
} as const;
|
||||
|
||||
|
|
|
@ -11,11 +11,18 @@ import { Endpoint } from '@/server/api/endpoint-base.js';
|
|||
import { DeleteAccountService } from '@/core/DeleteAccountService.js';
|
||||
import { DI } from '@/di-symbols.js';
|
||||
import { UserAuthService } from '@/core/UserAuthService.js';
|
||||
import ms from 'ms';
|
||||
|
||||
export const meta = {
|
||||
requireCredential: true,
|
||||
requireCredentialSecureMode: true,
|
||||
|
||||
limit: {
|
||||
duration: ms('1hour'),
|
||||
max: 10,
|
||||
minInterval: ms('1sec'),
|
||||
},
|
||||
|
||||
secure: true,
|
||||
} as const;
|
||||
|
||||
|
|
|
@ -79,7 +79,7 @@ export default class extends Endpoint<typeof meta, typeof paramDef> {
|
|||
if (file.size === 0) throw new ApiError(meta.errors.emptyFile);
|
||||
const antennas: (_Antenna & { userListAccts: string[] | null })[] = JSON.parse(await this.downloadService.downloadTextFile(file.url));
|
||||
const currentAntennasCount = await this.antennasRepository.countBy({ userId: me.id });
|
||||
if (currentAntennasCount + antennas.length > (await this.roleService.getUserPolicies(me.id)).antennaLimit) {
|
||||
if (currentAntennasCount + antennas.length >= (await this.roleService.getUserPolicies(me.id)).antennaLimit) {
|
||||
throw new ApiError(meta.errors.tooManyAntennas);
|
||||
}
|
||||
this.queueService.createImportAntennasJob(me, antennas);
|
||||
|
|
|
@ -76,7 +76,7 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
|
||||
const checkMoving = await this.accountMoveService.validateAlsoKnownAs(
|
||||
me,
|
||||
(old, src) => !!src.movedAt && src.movedAt.getTime() + 1000 * 60 * 60 * 2 > (new Date()).getTime(),
|
||||
(old, src) => !!src.movedAt && src.movedAt.getTime() + 1000 * 60 * 60 * 2 > Date.now(),
|
||||
true,
|
||||
);
|
||||
if (checkMoving ? file.size > 32 * 1024 * 1024 : file.size > 64 * 1024) throw new ApiError(meta.errors.tooBigFile);
|
||||
|
|
|
@ -76,7 +76,7 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
|
||||
const checkMoving = await this.accountMoveService.validateAlsoKnownAs(
|
||||
me,
|
||||
(old, src) => !!src.movedAt && src.movedAt.getTime() + 1000 * 60 * 60 * 2 > (new Date()).getTime(),
|
||||
(old, src) => !!src.movedAt && src.movedAt.getTime() + 1000 * 60 * 60 * 2 > Date.now(),
|
||||
true,
|
||||
);
|
||||
if (checkMoving ? file.size > 32 * 1024 * 1024 : file.size > 64 * 1024) throw new ApiError(meta.errors.tooBigFile);
|
||||
|
|
|
@ -76,7 +76,7 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
|
||||
const checkMoving = await this.accountMoveService.validateAlsoKnownAs(
|
||||
me,
|
||||
(old, src) => !!src.movedAt && src.movedAt.getTime() + 1000 * 60 * 60 * 2 > (new Date()).getTime(),
|
||||
(old, src) => !!src.movedAt && src.movedAt.getTime() + 1000 * 60 * 60 * 2 > Date.now(),
|
||||
true,
|
||||
);
|
||||
if (checkMoving ? file.size > 32 * 1024 * 1024 : file.size > 64 * 1024) throw new ApiError(meta.errors.tooBigFile);
|
||||
|
|
|
@ -1,3 +1,8 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: marie and other Sharkey contributors
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import ms from 'ms';
|
||||
import { Endpoint } from '@/server/api/endpoint-base.js';
|
||||
|
@ -60,7 +65,7 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
const file = await this.driveFilesRepository.findOneBy({ id: ps.fileId });
|
||||
|
||||
if (file == null) throw new ApiError(meta.errors.noSuchFile);
|
||||
|
||||
|
||||
if (file.size === 0) throw new ApiError(meta.errors.emptyFile);
|
||||
|
||||
if ((await this.roleService.getUserPolicies(me.id)).canImportNotes === false) {
|
||||
|
|
|
@ -75,7 +75,7 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
|
||||
const checkMoving = await this.accountMoveService.validateAlsoKnownAs(
|
||||
me,
|
||||
(old, src) => !!src.movedAt && src.movedAt.getTime() + 1000 * 60 * 60 * 2 > (new Date()).getTime(),
|
||||
(old, src) => !!src.movedAt && src.movedAt.getTime() + 1000 * 60 * 60 * 2 > Date.now(),
|
||||
true,
|
||||
);
|
||||
if (checkMoving ? file.size > 32 * 1024 * 1024 : file.size > 64 * 1024) throw new ApiError(meta.errors.tooBigFile);
|
||||
|
|
|
@ -7,7 +7,7 @@ import { In } from 'typeorm';
|
|||
import * as Redis from 'ioredis';
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import type { NotesRepository } from '@/models/_.js';
|
||||
import { obsoleteNotificationTypes, notificationTypes, FilterUnionByProperty } from '@/types.js';
|
||||
import { FilterUnionByProperty, notificationTypes, obsoleteNotificationTypes } from '@/types.js';
|
||||
import { Endpoint } from '@/server/api/endpoint-base.js';
|
||||
import { NoteReadService } from '@/core/NoteReadService.js';
|
||||
import { NotificationEntityService } from '@/core/entities/NotificationEntityService.js';
|
||||
|
@ -85,27 +85,51 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
const includeTypes = ps.includeTypes && ps.includeTypes.filter(type => !(obsoleteNotificationTypes).includes(type as any)) as typeof notificationTypes[number][];
|
||||
const excludeTypes = ps.excludeTypes && ps.excludeTypes.filter(type => !(obsoleteNotificationTypes).includes(type as any)) as typeof notificationTypes[number][];
|
||||
|
||||
const limit = ps.limit + (ps.untilId ? 1 : 0) + (ps.sinceId ? 1 : 0); // untilIdに指定したものも含まれるため+1
|
||||
const notificationsRes = await this.redisClient.xrevrange(
|
||||
`notificationTimeline:${me.id}`,
|
||||
ps.untilId ? this.idService.parse(ps.untilId).date.getTime() : '+',
|
||||
ps.sinceId ? this.idService.parse(ps.sinceId).date.getTime() : '-',
|
||||
'COUNT', limit);
|
||||
let sinceTime = ps.sinceId ? this.idService.parse(ps.sinceId).date.getTime().toString() : null;
|
||||
let untilTime = ps.untilId ? this.idService.parse(ps.untilId).date.getTime().toString() : null;
|
||||
|
||||
if (notificationsRes.length === 0) {
|
||||
return [];
|
||||
}
|
||||
let notifications: MiNotification[];
|
||||
for (;;) {
|
||||
let notificationsRes: [id: string, fields: string[]][];
|
||||
|
||||
let notifications = notificationsRes.map(x => JSON.parse(x[1][1])).filter(x => x.id !== ps.untilId && x !== ps.sinceId) as MiNotification[];
|
||||
// sinceidのみの場合は古い順、そうでない場合は新しい順。 QueryService.makePaginationQueryも参照
|
||||
if (sinceTime && !untilTime) {
|
||||
notificationsRes = await this.redisClient.xrange(
|
||||
`notificationTimeline:${me.id}`,
|
||||
'(' + sinceTime,
|
||||
'+',
|
||||
'COUNT', ps.limit);
|
||||
} else {
|
||||
notificationsRes = await this.redisClient.xrevrange(
|
||||
`notificationTimeline:${me.id}`,
|
||||
untilTime ? '(' + untilTime : '+',
|
||||
sinceTime ? '(' + sinceTime : '-',
|
||||
'COUNT', ps.limit);
|
||||
}
|
||||
|
||||
if (includeTypes && includeTypes.length > 0) {
|
||||
notifications = notifications.filter(notification => includeTypes.includes(notification.type));
|
||||
} else if (excludeTypes && excludeTypes.length > 0) {
|
||||
notifications = notifications.filter(notification => !excludeTypes.includes(notification.type));
|
||||
}
|
||||
if (notificationsRes.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
if (notifications.length === 0) {
|
||||
return [];
|
||||
notifications = notificationsRes.map(x => JSON.parse(x[1][1])) as MiNotification[];
|
||||
|
||||
if (includeTypes && includeTypes.length > 0) {
|
||||
notifications = notifications.filter(notification => includeTypes.includes(notification.type));
|
||||
} else if (excludeTypes && excludeTypes.length > 0) {
|
||||
notifications = notifications.filter(notification => !excludeTypes.includes(notification.type));
|
||||
}
|
||||
|
||||
if (notifications.length !== 0) {
|
||||
// 通知が1件以上ある場合は返す
|
||||
break;
|
||||
}
|
||||
|
||||
// フィルタしたことで通知が0件になった場合、次のページを取得する
|
||||
if (ps.sinceId && !ps.untilId) {
|
||||
sinceTime = notificationsRes[notificationsRes.length - 1][0];
|
||||
} else {
|
||||
untilTime = notificationsRes[notificationsRes.length - 1][0];
|
||||
}
|
||||
}
|
||||
|
||||
// Mark all as read
|
||||
|
|
|
@ -11,11 +11,18 @@ import type { UsersRepository, UserProfilesRepository } from '@/models/_.js';
|
|||
import generateUserToken from '@/misc/generate-native-user-token.js';
|
||||
import { GlobalEventService } from '@/core/GlobalEventService.js';
|
||||
import { DI } from '@/di-symbols.js';
|
||||
import ms from 'ms';
|
||||
|
||||
export const meta = {
|
||||
requireCredential: true,
|
||||
requireCredentialSecureMode: true,
|
||||
|
||||
limit: {
|
||||
duration: ms('1hour'),
|
||||
max: 10,
|
||||
minInterval: ms('1sec'),
|
||||
},
|
||||
|
||||
secure: true,
|
||||
} as const;
|
||||
|
||||
|
|
|
@ -1,3 +1,8 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: marie and other Sharkey contributors
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import { Endpoint } from '@/server/api/endpoint-base.js';
|
||||
import type { RegistryItemsRepository } from '@/models/_.js';
|
||||
|
|
|
@ -16,6 +16,7 @@ import { DI } from '@/di-symbols.js';
|
|||
import { GlobalEventService } from '@/core/GlobalEventService.js';
|
||||
import { L_CHARS, secureRndstr } from '@/misc/secure-rndstr.js';
|
||||
import { UserAuthService } from '@/core/UserAuthService.js';
|
||||
import { MetaService } from '@/core/MetaService.js';
|
||||
import { ApiError } from '../../error.js';
|
||||
|
||||
export const meta = {
|
||||
|
@ -41,6 +42,12 @@ export const meta = {
|
|||
code: 'UNAVAILABLE',
|
||||
id: 'a2defefb-f220-8849-0af6-17f816099323',
|
||||
},
|
||||
|
||||
emailRequired: {
|
||||
message: 'Email address is required.',
|
||||
code: 'EMAIL_REQUIRED',
|
||||
id: '324c7a88-59f2-492f-903f-89134f93e47e',
|
||||
},
|
||||
},
|
||||
|
||||
res: {
|
||||
|
@ -68,6 +75,7 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
@Inject(DI.userProfilesRepository)
|
||||
private userProfilesRepository: UserProfilesRepository,
|
||||
|
||||
private metaService: MetaService,
|
||||
private userEntityService: UserEntityService,
|
||||
private emailService: EmailService,
|
||||
private userAuthService: UserAuthService,
|
||||
|
@ -99,6 +107,8 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
if (!res.available) {
|
||||
throw new ApiError(meta.errors.unavailable);
|
||||
}
|
||||
} else if ((await this.metaService.fetch()).emailRequiredForSignup) {
|
||||
throw new ApiError(meta.errors.emailRequired);
|
||||
}
|
||||
|
||||
await this.userProfilesRepository.update(me.id, {
|
||||
|
|
|
@ -25,7 +25,7 @@ import { UserFollowingService } from '@/core/UserFollowingService.js';
|
|||
import { AccountUpdateService } from '@/core/AccountUpdateService.js';
|
||||
import { HashtagService } from '@/core/HashtagService.js';
|
||||
import { DI } from '@/di-symbols.js';
|
||||
import { RoleService } from '@/core/RoleService.js';
|
||||
import { RolePolicies, RoleService } from '@/core/RoleService.js';
|
||||
import { CacheService } from '@/core/CacheService.js';
|
||||
import { RemoteUserResolveService } from '@/core/RemoteUserResolveService.js';
|
||||
import { DriveFileEntityService } from '@/core/entities/DriveFileEntityService.js';
|
||||
|
@ -275,8 +275,16 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
const profileUpdates = {} as Partial<MiUserProfile>;
|
||||
|
||||
const profile = await this.userProfilesRepository.findOneByOrFail({ userId: user.id });
|
||||
let policies: RolePolicies | null = null;
|
||||
|
||||
if (ps.name !== undefined) updates.name = ps.name;
|
||||
if (ps.name !== undefined) {
|
||||
if (ps.name === null) {
|
||||
updates.name = null;
|
||||
} else {
|
||||
const trimmedName = ps.name.trim();
|
||||
updates.name = trimmedName === '' ? null : trimmedName;
|
||||
}
|
||||
}
|
||||
if (ps.description !== undefined) profileUpdates.description = ps.description;
|
||||
if (ps.lang !== undefined) profileUpdates.lang = ps.lang;
|
||||
if (ps.location !== undefined) profileUpdates.location = ps.location;
|
||||
|
@ -309,14 +317,16 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
}
|
||||
|
||||
if (ps.mutedWords !== undefined) {
|
||||
checkMuteWordCount(ps.mutedWords, (await this.roleService.getUserPolicies(user.id)).wordMuteLimit);
|
||||
policies ??= await this.roleService.getUserPolicies(user.id);
|
||||
checkMuteWordCount(ps.mutedWords, policies.wordMuteLimit);
|
||||
validateMuteWordRegex(ps.mutedWords);
|
||||
|
||||
profileUpdates.mutedWords = ps.mutedWords;
|
||||
profileUpdates.enableWordMute = ps.mutedWords.length > 0;
|
||||
}
|
||||
if (ps.hardMutedWords !== undefined) {
|
||||
checkMuteWordCount(ps.hardMutedWords, (await this.roleService.getUserPolicies(user.id)).wordMuteLimit);
|
||||
policies ??= await this.roleService.getUserPolicies(user.id);
|
||||
checkMuteWordCount(ps.hardMutedWords, policies.wordMuteLimit);
|
||||
validateMuteWordRegex(ps.hardMutedWords);
|
||||
profileUpdates.hardMutedWords = ps.hardMutedWords;
|
||||
}
|
||||
|
@ -338,12 +348,16 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
if (typeof ps.injectFeaturedNote === 'boolean') profileUpdates.injectFeaturedNote = ps.injectFeaturedNote;
|
||||
if (typeof ps.receiveAnnouncementEmail === 'boolean') profileUpdates.receiveAnnouncementEmail = ps.receiveAnnouncementEmail;
|
||||
if (typeof ps.alwaysMarkNsfw === 'boolean') {
|
||||
if ((await roleService.getUserPolicies(user.id)).alwaysMarkNsfw) throw new ApiError(meta.errors.restrictedByRole);
|
||||
policies ??= await this.roleService.getUserPolicies(user.id);
|
||||
if (policies.alwaysMarkNsfw) throw new ApiError(meta.errors.restrictedByRole);
|
||||
profileUpdates.alwaysMarkNsfw = ps.alwaysMarkNsfw;
|
||||
}
|
||||
if (ps.emailNotificationTypes !== undefined) profileUpdates.emailNotificationTypes = ps.emailNotificationTypes;
|
||||
|
||||
if (ps.avatarId) {
|
||||
policies ??= await this.roleService.getUserPolicies(user.id);
|
||||
if (!policies.canUpdateBioMedia) throw new ApiError(meta.errors.restrictedByRole);
|
||||
|
||||
const avatar = await this.driveFilesRepository.findOneBy({ id: ps.avatarId });
|
||||
|
||||
if (avatar == null || avatar.userId !== user.id) throw new ApiError(meta.errors.noSuchAvatar);
|
||||
|
@ -359,6 +373,9 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
}
|
||||
|
||||
if (ps.bannerId) {
|
||||
policies ??= await this.roleService.getUserPolicies(user.id);
|
||||
if (!policies.canUpdateBioMedia) throw new ApiError(meta.errors.restrictedByRole);
|
||||
|
||||
const banner = await this.driveFilesRepository.findOneBy({ id: ps.bannerId });
|
||||
|
||||
if (banner == null || banner.userId !== user.id) throw new ApiError(meta.errors.noSuchBanner);
|
||||
|
@ -389,14 +406,15 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
}
|
||||
|
||||
if (ps.avatarDecorations) {
|
||||
policies ??= await this.roleService.getUserPolicies(user.id);
|
||||
const decorations = await this.avatarDecorationService.getAll(true);
|
||||
const [myRoles, myPolicies] = await Promise.all([this.roleService.getUserRoles(user.id), this.roleService.getUserPolicies(user.id)]);
|
||||
const myRoles = await this.roleService.getUserRoles(user.id);
|
||||
const allRoles = await this.roleService.getRoles();
|
||||
const decorationIds = decorations
|
||||
.filter(d => d.roleIdsThatCanBeUsedThisDecoration.filter(roleId => allRoles.some(r => r.id === roleId)).length === 0 || myRoles.some(r => d.roleIdsThatCanBeUsedThisDecoration.includes(r.id)))
|
||||
.map(d => d.id);
|
||||
|
||||
if (ps.avatarDecorations.length > myPolicies.avatarDecorationLimit) throw new ApiError(meta.errors.restrictedByRole);
|
||||
if (ps.avatarDecorations.length > policies.avatarDecorationLimit) throw new ApiError(meta.errors.restrictedByRole);
|
||||
|
||||
updates.avatarDecorations = ps.avatarDecorations.filter(d => decorationIds.includes(d.id)).map(d => ({
|
||||
id: d.id,
|
||||
|
@ -535,26 +553,32 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
private async verifyLink(url: string, user: MiLocalUser) {
|
||||
if (!safeForSql(url)) return;
|
||||
|
||||
const html = await this.httpRequestService.getHtml(url);
|
||||
try {
|
||||
const html = await this.httpRequestService.getHtml(url);
|
||||
|
||||
const { window } = new JSDOM(html);
|
||||
const doc = window.document;
|
||||
const { window } = new JSDOM(html);
|
||||
const doc = window.document;
|
||||
|
||||
const myLink = `${this.config.url}/@${user.username}`;
|
||||
const myLink = `${this.config.url}/@${user.username}`;
|
||||
|
||||
const aEls = Array.from(doc.getElementsByTagName('a'));
|
||||
const linkEls = Array.from(doc.getElementsByTagName('link'));
|
||||
const aEls = Array.from(doc.getElementsByTagName('a'));
|
||||
const linkEls = Array.from(doc.getElementsByTagName('link'));
|
||||
|
||||
const includesMyLink = aEls.some(a => a.href === myLink);
|
||||
const includesRelMeLinks = [...aEls, ...linkEls].some(link => link.rel === 'me' && link.href === myLink);
|
||||
const includesMyLink = aEls.some(a => a.href === myLink);
|
||||
const includesRelMeLinks = [...aEls, ...linkEls].some(link => link.rel === 'me' && link.href === myLink);
|
||||
|
||||
if (includesMyLink || includesRelMeLinks) {
|
||||
await this.userProfilesRepository.createQueryBuilder('profile').update()
|
||||
.where('userId = :userId', { userId: user.id })
|
||||
.set({
|
||||
verifiedLinks: () => `array_append("verifiedLinks", '${url}')`, // ここでSQLインジェクションされそうなのでとりあえず safeForSql で弾いている
|
||||
})
|
||||
.execute();
|
||||
if (includesMyLink || includesRelMeLinks) {
|
||||
await this.userProfilesRepository.createQueryBuilder('profile').update()
|
||||
.where('userId = :userId', { userId: user.id })
|
||||
.set({
|
||||
verifiedLinks: () => `array_append("verifiedLinks", '${url}')`, // ここでSQLインジェクションされそうなのでとりあえず safeForSql で弾いている
|
||||
})
|
||||
.execute();
|
||||
}
|
||||
|
||||
window.close();
|
||||
} catch (err) {
|
||||
// なにもしない
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -86,18 +86,18 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
const currentWebhooksCount = await this.webhooksRepository.countBy({
|
||||
userId: me.id,
|
||||
});
|
||||
if (currentWebhooksCount > (await this.roleService.getUserPolicies(me.id)).webhookLimit) {
|
||||
if (currentWebhooksCount >= (await this.roleService.getUserPolicies(me.id)).webhookLimit) {
|
||||
throw new ApiError(meta.errors.tooManyWebhooks);
|
||||
}
|
||||
|
||||
const webhook = await this.webhooksRepository.insert({
|
||||
const webhook = await this.webhooksRepository.insertOne({
|
||||
id: this.idService.gen(),
|
||||
userId: me.id,
|
||||
name: ps.name,
|
||||
url: ps.url,
|
||||
secret: ps.secret,
|
||||
on: ps.on,
|
||||
}).then(x => this.webhooksRepository.findOneByOrFail(x.identifiers[0]));
|
||||
});
|
||||
|
||||
this.globalEventService.publishInternalEvent('webhookCreated', webhook);
|
||||
|
||||
|
|
|
@ -35,13 +35,13 @@ export const paramDef = {
|
|||
webhookId: { type: 'string', format: 'misskey:id' },
|
||||
name: { type: 'string', minLength: 1, maxLength: 100 },
|
||||
url: { type: 'string', minLength: 1, maxLength: 1024 },
|
||||
secret: { type: 'string', maxLength: 1024, default: '' },
|
||||
secret: { type: 'string', nullable: true, maxLength: 1024 },
|
||||
on: { type: 'array', items: {
|
||||
type: 'string', enum: webhookEventTypes,
|
||||
} },
|
||||
active: { type: 'boolean' },
|
||||
},
|
||||
required: ['webhookId', 'name', 'url', 'on', 'active'],
|
||||
required: ['webhookId'],
|
||||
} as const;
|
||||
|
||||
// TODO: ロジックをサービスに切り出す
|
||||
|
@ -67,7 +67,7 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
await this.webhooksRepository.update(webhook.id, {
|
||||
name: ps.name,
|
||||
url: ps.url,
|
||||
secret: ps.secret,
|
||||
secret: ps.secret === null ? '' : ps.secret,
|
||||
on: ps.on,
|
||||
active: ps.active,
|
||||
});
|
||||
|
|
|
@ -67,13 +67,13 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
}
|
||||
}
|
||||
|
||||
const ticket = await this.registrationTicketsRepository.insert({
|
||||
const ticket = await this.registrationTicketsRepository.insertOne({
|
||||
id: this.idService.gen(),
|
||||
createdBy: me,
|
||||
createdById: me.id,
|
||||
expiresAt: policies.inviteExpirationTime ? new Date(Date.now() + (policies.inviteExpirationTime * 1000 * 60)) : null,
|
||||
code: generateInviteCode(),
|
||||
}).then(x => this.registrationTicketsRepository.findOneByOrFail(x.identifiers[0]));
|
||||
});
|
||||
|
||||
return await this.inviteCodeEntityService.pack(ticket, me);
|
||||
});
|
||||
|
|
|
@ -16,7 +16,7 @@ import { Endpoint } from '@/server/api/endpoint-base.js';
|
|||
import { NoteEntityService } from '@/core/entities/NoteEntityService.js';
|
||||
import { NoteCreateService } from '@/core/NoteCreateService.js';
|
||||
import { DI } from '@/di-symbols.js';
|
||||
import { isPureRenote } from '@/misc/is-pure-renote.js';
|
||||
import { isQuote, isRenote } from '@/misc/is-renote.js';
|
||||
import { MetaService } from '@/core/MetaService.js';
|
||||
import { UtilityService } from '@/core/UtilityService.js';
|
||||
import { IdentifiableError } from '@/misc/identifiable-error.js';
|
||||
|
@ -33,6 +33,7 @@ export const meta = {
|
|||
limit: {
|
||||
duration: ms('1hour'),
|
||||
max: 300,
|
||||
minInterval: ms('1sec'),
|
||||
},
|
||||
|
||||
kind: 'write:notes',
|
||||
|
@ -293,7 +294,7 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
|
||||
if (renote == null) {
|
||||
throw new ApiError(meta.errors.noSuchRenoteTarget);
|
||||
} else if (isPureRenote(renote)) {
|
||||
} else if (isRenote(renote) && !isQuote(renote)) {
|
||||
throw new ApiError(meta.errors.cannotReRenote);
|
||||
}
|
||||
|
||||
|
@ -339,7 +340,7 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
|
||||
if (reply == null) {
|
||||
throw new ApiError(meta.errors.noSuchReplyTarget);
|
||||
} else if (isPureRenote(reply)) {
|
||||
} else if (isRenote(reply) && !isQuote(reply)) {
|
||||
throw new ApiError(meta.errors.cannotReplyToPureRenote);
|
||||
} else if (!await this.noteEntityService.isVisibleForMe(reply, me.id)) {
|
||||
throw new ApiError(meta.errors.cannotReplyToInvisibleNote);
|
||||
|
|
|
@ -11,7 +11,7 @@ import { Endpoint } from '@/server/api/endpoint-base.js';
|
|||
import { NoteEntityService } from '@/core/entities/NoteEntityService.js';
|
||||
import { NoteEditService } from '@/core/NoteEditService.js';
|
||||
import { DI } from '@/di-symbols.js';
|
||||
import { isPureRenote } from '@/misc/is-pure-renote.js';
|
||||
import { isQuote, isRenote } from '@/misc/is-renote.js';
|
||||
import { IdentifiableError } from '@/misc/identifiable-error.js';
|
||||
import { ApiError } from '../../error.js';
|
||||
|
||||
|
@ -337,7 +337,7 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
|
||||
if (renote == null) {
|
||||
throw new ApiError(meta.errors.noSuchRenoteTarget);
|
||||
} else if (isPureRenote(renote)) {
|
||||
} else if (isRenote(renote) && !isQuote(renote)) {
|
||||
throw new ApiError(meta.errors.cannotReRenote);
|
||||
}
|
||||
|
||||
|
@ -387,7 +387,7 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
|
||||
if (reply == null) {
|
||||
throw new ApiError(meta.errors.noSuchReplyTarget);
|
||||
} else if (isPureRenote(reply)) {
|
||||
} else if (isRenote(reply) && !isQuote(reply)) {
|
||||
throw new ApiError(meta.errors.cannotReplyToPureRenote);
|
||||
} else if (!await this.noteEntityService.isVisibleForMe(reply, me.id)) {
|
||||
throw new ApiError(meta.errors.cannotReplyToInvisibleNote);
|
||||
|
|
|
@ -142,9 +142,16 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
timelineConfig = [
|
||||
`homeTimeline:${me.id}`,
|
||||
'localTimeline',
|
||||
`localTimelineWithReplyTo:${me.id}`,
|
||||
];
|
||||
}
|
||||
|
||||
const [
|
||||
followings,
|
||||
] = await Promise.all([
|
||||
this.cacheService.userFollowingsCache.fetch(me.id),
|
||||
]);
|
||||
|
||||
const redisTimeline = await this.fanoutTimelineEndpointService.timeline({
|
||||
untilId,
|
||||
sinceId,
|
||||
|
@ -156,6 +163,13 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
alwaysIncludeMyNotes: true,
|
||||
excludePureRenotes: !ps.withRenotes,
|
||||
excludeBots: !ps.withBots,
|
||||
noteFilter: note => {
|
||||
if (note.reply && note.reply.visibility === 'followers') {
|
||||
if (!Object.hasOwn(followings, note.reply.userId) && note.reply.userId !== me.id) return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
},
|
||||
dbFallback: async (untilId, sinceId, limit) => await this.getFromDb({
|
||||
untilId,
|
||||
sinceId,
|
||||
|
|
|
@ -33,6 +33,7 @@ export const paramDef = {
|
|||
properties: {
|
||||
limit: { type: 'integer', minimum: 1, maximum: 100, default: 10 },
|
||||
offset: { type: 'integer', default: 0 },
|
||||
excludeChannels: { type: 'boolean', default: false },
|
||||
},
|
||||
required: [],
|
||||
} as const;
|
||||
|
@ -87,6 +88,12 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
query.setParameters(mutingQuery.getParameters());
|
||||
//#endregion
|
||||
|
||||
//#region exclude channels
|
||||
if (ps.excludeChannels) {
|
||||
query.andWhere('poll.channelId IS NULL');
|
||||
}
|
||||
//#endregion
|
||||
|
||||
const polls = await query
|
||||
.orderBy('poll.noteId', 'DESC')
|
||||
.limit(ps.limit)
|
||||
|
|
|
@ -145,12 +145,12 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
|
|||
}
|
||||
|
||||
// Create vote
|
||||
const vote = await this.pollVotesRepository.insert({
|
||||
const vote = await this.pollVotesRepository.insertOne({
|
||||
id: this.idService.gen(createdAt.getTime()),
|
||||
noteId: note.id,
|
||||
userId: me.id,
|
||||
choice: ps.choice,
|
||||
}).then(x => this.pollVotesRepository.findOneByOrFail(x.identifiers[0]));
|
||||
});
|
||||
|
||||
// Increment votes count
|
||||
const index = ps.choice + 1; // In SQL, array index is 1 based
|
||||
|
|
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue