fix some lints

Many of these were fixed automatically with eslint --fix.

Some of them (e.g. adding return types to functions) were done manually.
This commit is contained in:
Johann150 2022-08-11 00:09:29 +02:00
parent 961fb0d2df
commit 6ce4b3fe2f
Signed by untrusted user: Johann150
GPG key ID: 9EE6577A2A06F8F1
76 changed files with 142 additions and 143 deletions

View file

@ -10,7 +10,7 @@ const urlRegexFull = /^https?:\/\/[\w\/:%#@$&?!()\[\]~.,=+\-]+$/;
export function fromHtml(html: string, hashtagNames?: string[]): string { export function fromHtml(html: string, hashtagNames?: string[]): string {
const dom = parse5.parseFragment( const dom = parse5.parseFragment(
// some AP servers like Pixelfed use br tags as well as newlines // some AP servers like Pixelfed use br tags as well as newlines
html.replace(/<br\s?\/?>\r?\n/gi, '\n') html.replace(/<br\s?\/?>\r?\n/gi, '\n'),
); );
let text = ''; let text = '';

View file

@ -5,7 +5,7 @@ export type Acct = {
export function parse(acct: string): Acct { export function parse(acct: string): Acct {
const split = acct.split('@'); const split = acct.split('@');
if (split[0].length == 0) { if (split[0].length === 0) {
// there was an initial at // there was an initial at
split.shift(); split.shift();
} }

View file

@ -9,8 +9,8 @@ const retryDelay = 100;
const lock: (key: string, timeout?: number) => Promise<() => void> const lock: (key: string, timeout?: number) => Promise<() => void>
= redisClient = redisClient
? promisify(redisLock(redisClient, retryDelay)) ? promisify(redisLock(redisClient, retryDelay))
: async () => () => { }; : async () => () => { };
/** /**
* Get AP Object lock * Get AP Object lock

View file

@ -9,7 +9,7 @@ export async function verifyRecaptcha(secret: string, response: string) {
}); });
if (result.success !== true) { if (result.success !== true) {
const errorCodes = result['error-codes'] ? result['error-codes']?.join(', ') : ''; const errorCodes = result['error-codes'] ? result['error-codes'].join(', ') : '';
throw new Error(`recaptcha-failed: ${errorCodes}`); throw new Error(`recaptcha-failed: ${errorCodes}`);
} }
} }
@ -20,7 +20,7 @@ export async function verifyHcaptcha(secret: string, response: string) {
}); });
if (result.success !== true) { if (result.success !== true) {
const errorCodes = result['error-codes'] ? result['error-codes']?.join(', ') : ''; const errorCodes = result['error-codes'] ? result['error-codes'].join(', ') : '';
throw new Error(`hcaptcha-failed: ${errorCodes}`); throw new Error(`hcaptcha-failed: ${errorCodes}`);
} }
} }

View file

@ -65,7 +65,7 @@ export async function checkHitAntenna(antenna: Antenna, note: (Note | Packed<'No
and.every(keyword => and.every(keyword =>
antenna.caseSensitive antenna.caseSensitive
? note.text!.includes(keyword) ? note.text!.includes(keyword)
: note.text!.toLowerCase().includes(keyword.toLowerCase()) : note.text!.toLowerCase().includes(keyword.toLowerCase()),
)); ));
if (!matched) return false; if (!matched) return false;
@ -83,7 +83,7 @@ export async function checkHitAntenna(antenna: Antenna, note: (Note | Packed<'No
and.every(keyword => and.every(keyword =>
antenna.caseSensitive antenna.caseSensitive
? note.text!.includes(keyword) ? note.text!.includes(keyword)
: note.text!.toLowerCase().includes(keyword.toLowerCase()) : note.text!.toLowerCase().includes(keyword.toLowerCase()),
)); ));
if (matched) return false; if (matched) return false;

View file

@ -1,5 +1,5 @@
import { URL } from 'node:url';
import { toASCII } from 'punycode'; import { toASCII } from 'punycode';
import { URL } from 'node:url';
import config from '@/config/index.js'; import config from '@/config/index.js';
export function getFullApAccount(username: string, host: string | null): string { export function getFullApAccount(username: string, host: string | null): string {

View file

@ -18,7 +18,7 @@ export function createTempDir(): Promise<[string, () => void]> {
(e, path, cleanup) => { (e, path, cleanup) => {
if (e) return rej(e); if (e) return rej(e);
res([path, cleanup]); res([path, cleanup]);
} },
); );
}); });
} }

View file

@ -1,15 +1,15 @@
import { Packed } from './schema.js'; import { Packed } from './schema.js';
export function isInstanceMuted(note: Packed<'Note'>, mutedInstances: Set<string>): boolean { export function isInstanceMuted(note: Packed<'Note'>, mutedInstances: Set<string>): boolean {
if (mutedInstances.has(note?.user?.host ?? '')) return true; if (mutedInstances.has(note.user.host ?? '')) return true;
if (mutedInstances.has(note?.reply?.user?.host ?? '')) return true; if (mutedInstances.has(note.reply?.user.host ?? '')) return true;
if (mutedInstances.has(note?.renote?.user?.host ?? '')) return true; if (mutedInstances.has(note.renote?.user.host ?? '')) return true;
return false; return false;
} }
export function isUserFromMutedInstance(notif: Packed<'Notification'>, mutedInstances: Set<string>): boolean { export function isUserFromMutedInstance(notif: Packed<'Notification'>, mutedInstances: Set<string>): boolean {
if (mutedInstances.has(notif?.user?.host ?? '')) return true; if (mutedInstances.has(notif.user?.host ?? '')) return true;
return false; return false;
} }

View file

@ -1,7 +1,7 @@
export function isUserRelated(note: any, ids: Set<string>): boolean { export function isUserRelated(note: any, ids: Set<string>): boolean {
if (ids.has(note.userId)) return true; // note author is muted if (ids.has(note.userId)) return true; // note author is muted
if (note.mentions && note.mentions.some((user: string) => ids.has(user))) return true; // any of mentioned users are muted if (note.mentions && note.mentions.some((user: string) => ids.has(user))) return true; // any of mentioned users are muted
if (note.reply && isUserRelated(note.reply, ids)) return true; // also check reply target if (note.reply && isUserRelated(note.reply, ids)) return true; // also check reply target
if (note.renote && isUserRelated(note.renote, ids)) return true; // also check renote target if (note.renote && isUserRelated(note.renote, ids)) return true; // also check renote target
return false; return false;
} }

View file

@ -8,7 +8,7 @@ export function nyaize(text: string): string {
.replace(/(?<=every)one/gi, x => x === 'ONE' ? 'NYAN' : 'nyan') .replace(/(?<=every)one/gi, x => x === 'ONE' ? 'NYAN' : 'nyan')
// ko-KR // ko-KR
.replace(/[나-낳]/g, match => String.fromCharCode( .replace(/[나-낳]/g, match => String.fromCharCode(
match.charCodeAt(0)! + '냐'.charCodeAt(0) - '나'.charCodeAt(0) match.charCodeAt(0)! + '냐'.charCodeAt(0) - '나'.charCodeAt(0),
)) ))
.replace(/(다$)|(다(?=\.))|(다(?= ))|(다(?=!))|(다(?=\?))/gm, '다냥') .replace(/(다$)|(다(?=\.))|(다(?= ))|(다(?=!))|(다(?=\?))/gm, '다냥')
.replace(/(야(?=\?))|(야$)|(야(?= ))/gm, '냥'); .replace(/(야(?=\?))|(야$)|(야(?= ))/gm, '냥');

View file

@ -52,7 +52,7 @@ export class AbuseUserReport {
public resolved: boolean; public resolved: boolean;
@Column('boolean', { @Column('boolean', {
default: false default: false,
}) })
public forwarded: boolean; public forwarded: boolean;

View file

@ -12,7 +12,7 @@ export const AppRepository = db.getRepository(App).extend({
detail?: boolean, detail?: boolean,
includeSecret?: boolean, includeSecret?: boolean,
includeProfileImageIds?: boolean includeProfileImageIds?: boolean
} },
): Promise<Packed<'App'>> { ): Promise<Packed<'App'>> {
const opts = Object.assign({ const opts = Object.assign({
detail: false, detail: false,

View file

@ -7,7 +7,7 @@ import { Apps } from '../index.js';
export const AuthSessionRepository = db.getRepository(AuthSession).extend({ export const AuthSessionRepository = db.getRepository(AuthSession).extend({
async pack( async pack(
src: AuthSession['id'] | AuthSession, src: AuthSession['id'] | AuthSession,
me?: { id: User['id'] } | null | undefined me?: { id: User['id'] } | null | undefined,
) { ) {
const session = typeof src === 'object' ? src : await this.findOneByOrFail({ id: src }); const session = typeof src === 'object' ? src : await this.findOneByOrFail({ id: src });

View file

@ -8,7 +8,7 @@ import { Users } from '../index.js';
export const BlockingRepository = db.getRepository(Blocking).extend({ export const BlockingRepository = db.getRepository(Blocking).extend({
async pack( async pack(
src: Blocking['id'] | Blocking, src: Blocking['id'] | Blocking,
me?: { id: User['id'] } | null | undefined me?: { id: User['id'] } | null | undefined,
): Promise<Packed<'Blocking'>> { ): Promise<Packed<'Blocking'>> {
const blocking = typeof src === 'object' ? src : await this.findOneByOrFail({ id: src }); const blocking = typeof src === 'object' ? src : await this.findOneByOrFail({ id: src });
@ -24,7 +24,7 @@ export const BlockingRepository = db.getRepository(Blocking).extend({
packMany( packMany(
blockings: any[], blockings: any[],
me: { id: User['id'] } me: { id: User['id'] },
) { ) {
return Promise.all(blockings.map(x => this.pack(x, me))); return Promise.all(blockings.map(x => this.pack(x, me)));
}, },

View file

@ -9,7 +9,7 @@ export const DriveFolderRepository = db.getRepository(DriveFolder).extend({
src: DriveFolder['id'] | DriveFolder, src: DriveFolder['id'] | DriveFolder,
options?: { options?: {
detail: boolean detail: boolean
} },
): Promise<Packed<'DriveFolder'>> { ): Promise<Packed<'DriveFolder'>> {
const opts = Object.assign({ const opts = Object.assign({
detail: false, detail: false,

View file

@ -6,7 +6,7 @@ import { Users } from '../index.js';
export const FollowRequestRepository = db.getRepository(FollowRequest).extend({ export const FollowRequestRepository = db.getRepository(FollowRequest).extend({
async pack( async pack(
src: FollowRequest['id'] | FollowRequest, src: FollowRequest['id'] | FollowRequest,
me?: { id: User['id'] } | null | undefined me?: { id: User['id'] } | null | undefined,
) { ) {
const request = typeof src === 'object' ? src : await this.findOneByOrFail({ id: src }); const request = typeof src === 'object' ? src : await this.findOneByOrFail({ id: src });

View file

@ -76,7 +76,7 @@ export const FollowingRepository = db.getRepository(Following).extend({
opts?: { opts?: {
populateFollowee?: boolean; populateFollowee?: boolean;
populateFollower?: boolean; populateFollower?: boolean;
} },
) { ) {
return Promise.all(followings.map(x => this.pack(x, me, opts))); return Promise.all(followings.map(x => this.pack(x, me, opts)));
}, },

View file

@ -5,7 +5,7 @@ import { GalleryPosts } from '../index.js';
export const GalleryLikeRepository = db.getRepository(GalleryLike).extend({ export const GalleryLikeRepository = db.getRepository(GalleryLike).extend({
async pack( async pack(
src: GalleryLike['id'] | GalleryLike, src: GalleryLike['id'] | GalleryLike,
me?: any me?: any,
) { ) {
const like = typeof src === 'object' ? src : await this.findOneByOrFail({ id: src }); const like = typeof src === 'object' ? src : await this.findOneByOrFail({ id: src });
@ -17,7 +17,7 @@ export const GalleryLikeRepository = db.getRepository(GalleryLike).extend({
packMany( packMany(
likes: any[], likes: any[],
me: any me: any,
) { ) {
return Promise.all(likes.map(x => this.pack(x, me))); return Promise.all(likes.map(x => this.pack(x, me)));
}, },

View file

@ -11,7 +11,7 @@ export const MessagingMessageRepository = db.getRepository(MessagingMessage).ext
options?: { options?: {
populateRecipient?: boolean, populateRecipient?: boolean,
populateGroup?: boolean, populateGroup?: boolean,
} },
): Promise<Packed<'MessagingMessage'>> { ): Promise<Packed<'MessagingMessage'>> {
const opts = options || { const opts = options || {
populateRecipient: true, populateRecipient: true,

View file

@ -8,7 +8,7 @@ import { Users } from '../index.js';
export const MutingRepository = db.getRepository(Muting).extend({ export const MutingRepository = db.getRepository(Muting).extend({
async pack( async pack(
src: Muting['id'] | Muting, src: Muting['id'] | Muting,
me?: { id: User['id'] } | null | undefined me?: { id: User['id'] } | null | undefined,
): Promise<Packed<'Muting'>> { ): Promise<Packed<'Muting'>> {
const muting = typeof src === 'object' ? src : await this.findOneByOrFail({ id: src }); const muting = typeof src === 'object' ? src : await this.findOneByOrFail({ id: src });
@ -25,7 +25,7 @@ export const MutingRepository = db.getRepository(Muting).extend({
packMany( packMany(
mutings: any[], mutings: any[],
me: { id: User['id'] } me: { id: User['id'] },
) { ) {
return Promise.all(mutings.map(x => this.pack(x, me))); return Promise.all(mutings.map(x => this.pack(x, me)));
}, },

View file

@ -6,7 +6,7 @@ import { Notes } from '../index.js';
export const NoteFavoriteRepository = db.getRepository(NoteFavorite).extend({ export const NoteFavoriteRepository = db.getRepository(NoteFavorite).extend({
async pack( async pack(
src: NoteFavorite['id'] | NoteFavorite, src: NoteFavorite['id'] | NoteFavorite,
me?: { id: User['id'] } | null | undefined me?: { id: User['id'] } | null | undefined,
) { ) {
const favorite = typeof src === 'object' ? src : await this.findOneByOrFail({ id: src }); const favorite = typeof src === 'object' ? src : await this.findOneByOrFail({ id: src });
@ -21,7 +21,7 @@ export const NoteFavoriteRepository = db.getRepository(NoteFavorite).extend({
packMany( packMany(
favorites: any[], favorites: any[],
me: { id: User['id'] } me: { id: User['id'] },
) { ) {
return Promise.allSettled(favorites.map(x => this.pack(x, me))) return Promise.allSettled(favorites.map(x => this.pack(x, me)))
.then(promises => promises.flatMap(result => result.status === 'fulfilled' ? [result.value] : [])); .then(promises => promises.flatMap(result => result.status === 'fulfilled' ? [result.value] : []));

View file

@ -42,5 +42,5 @@ export const NoteReactionRepository = db.getRepository(NoteReaction).extend({
// filter out rejected promises, only keep fulfilled values // filter out rejected promises, only keep fulfilled values
return reactions.flatMap(result => result.status === 'fulfilled' ? [result.value] : []); return reactions.flatMap(result => result.status === 'fulfilled' ? [result.value] : []);
} },
}); });

View file

@ -137,7 +137,7 @@ export const NoteRepository = db.getRepository(Note).extend({
_hint_?: { _hint_?: {
myReactions: Map<Note['id'], NoteReaction | null>; myReactions: Map<Note['id'], NoteReaction | null>;
}; };
} },
): Promise<Packed<'Note'>> { ): Promise<Packed<'Note'>> {
const opts = Object.assign({ const opts = Object.assign({
detail: true, detail: true,
@ -163,7 +163,7 @@ export const NoteRepository = db.getRepository(Note).extend({
: await Channels.findOneBy({ id: note.channelId }) : await Channels.findOneBy({ id: note.channelId })
: null; : null;
const reactionEmojiNames = Object.keys(note.reactions).filter(x => x?.startsWith(':')).map(x => decodeReaction(x).reaction).map(x => x.replace(/:/g, '')); const reactionEmojiNames = Object.keys(note.reactions).filter(x => x.startsWith(':')).map(x => decodeReaction(x).reaction).map(x => x.replace(/:/g, ''));
const packed: Packed<'Note'> = await awaitAll({ const packed: Packed<'Note'> = await awaitAll({
id: note.id, id: note.id,
@ -233,7 +233,7 @@ export const NoteRepository = db.getRepository(Note).extend({
me?: { id: User['id'] } | null | undefined, me?: { id: User['id'] } | null | undefined,
options?: { options?: {
detail?: boolean; detail?: boolean;
} },
) { ) {
if (notes.length === 0) return []; if (notes.length === 0) return [];

View file

@ -16,7 +16,7 @@ export const NotificationRepository = db.getRepository(Notification).extend({
_hintForEachNotes_?: { _hintForEachNotes_?: {
myReactions: Map<Note['id'], NoteReaction | null>; myReactions: Map<Note['id'], NoteReaction | null>;
}; };
} },
): Promise<Packed<'Notification'>> { ): Promise<Packed<'Notification'>> {
const notification = typeof src === 'object' ? src : await this.findOneByOrFail({ id: src }); const notification = typeof src === 'object' ? src : await this.findOneByOrFail({ id: src });
const token = notification.appAccessTokenId ? await AccessTokens.findOneByOrFail({ id: notification.appAccessTokenId }) : null; const token = notification.appAccessTokenId ? await AccessTokens.findOneByOrFail({ id: notification.appAccessTokenId }) : null;
@ -85,7 +85,7 @@ export const NotificationRepository = db.getRepository(Notification).extend({
async packMany( async packMany(
notifications: Notification[], notifications: Notification[],
meId: User['id'] meId: User['id'],
) { ) {
if (notifications.length === 0) return []; if (notifications.length === 0) return [];

View file

@ -6,7 +6,7 @@ import { Pages } from '../index.js';
export const PageLikeRepository = db.getRepository(PageLike).extend({ export const PageLikeRepository = db.getRepository(PageLike).extend({
async pack( async pack(
src: PageLike['id'] | PageLike, src: PageLike['id'] | PageLike,
me?: { id: User['id'] } | null | undefined me?: { id: User['id'] } | null | undefined,
) { ) {
const like = typeof src === 'object' ? src : await this.findOneByOrFail({ id: src }); const like = typeof src === 'object' ? src : await this.findOneByOrFail({ id: src });
@ -18,7 +18,7 @@ export const PageLikeRepository = db.getRepository(PageLike).extend({
packMany( packMany(
likes: any[], likes: any[],
me: { id: User['id'] } me: { id: User['id'] },
) { ) {
return Promise.all(likes.map(x => this.pack(x, me))); return Promise.all(likes.map(x => this.pack(x, me)));
}, },

View file

@ -161,19 +161,19 @@ export const packedUserDetailedNotMeOnlySchema = {
type: 'array', type: 'array',
nullable: false, optional: false, nullable: false, optional: false,
items: { items: {
type: 'object', type: 'object',
nullable: false, optional: false, nullable: false, optional: false,
properties: { properties: {
name: { name: {
type: 'string', type: 'string',
nullable: false, optional: false, nullable: false, optional: false,
},
value: {
type: 'string',
nullable: false, optional: false,
},
}, },
maxLength: 4, value: {
type: 'string',
nullable: false, optional: false,
},
},
maxLength: 4,
}, },
}, },
followersCount: { followersCount: {

View file

@ -10,7 +10,7 @@ export async function awaitAll<T>(obj: Promiseable<T>): Promise<T> {
const resolvedValues = await Promise.all(values.map(value => const resolvedValues = await Promise.all(values.map(value =>
(!value || !value.constructor || value.constructor.name !== 'Object') (!value || !value.constructor || value.constructor.name !== 'Object')
? value ? value
: awaitAll(value) : awaitAll(value),
)); ));
for (let i = 0; i < keys.length; i++) { for (let i = 0; i < keys.length; i++) {

View file

@ -6,12 +6,12 @@ const dateTimeIntervals = {
export function dateUTC(time: number[]): Date { export function dateUTC(time: number[]): Date {
const d = time.length === 2 ? Date.UTC(time[0], time[1]) const d = time.length === 2 ? Date.UTC(time[0], time[1])
: time.length === 3 ? Date.UTC(time[0], time[1], time[2]) : time.length === 3 ? Date.UTC(time[0], time[1], time[2])
: time.length === 4 ? Date.UTC(time[0], time[1], time[2], time[3]) : time.length === 4 ? Date.UTC(time[0], time[1], time[2], time[3])
: time.length === 5 ? Date.UTC(time[0], time[1], time[2], time[3], time[4]) : time.length === 5 ? Date.UTC(time[0], time[1], time[2], time[3], time[4])
: time.length === 6 ? Date.UTC(time[0], time[1], time[2], time[3], time[4], time[5]) : time.length === 6 ? Date.UTC(time[0], time[1], time[2], time[3], time[4], time[5])
: time.length === 7 ? Date.UTC(time[0], time[1], time[2], time[3], time[4], time[5], time[6]) : time.length === 7 ? Date.UTC(time[0], time[1], time[2], time[3], time[4], time[5], time[6])
: null; : null;
if (!d) throw new Error('wrong number of arguments'); if (!d) throw new Error('wrong number of arguments');

View file

@ -21,9 +21,9 @@ import { ThinUser } from './types.js';
function renderError(e: Error): any { function renderError(e: Error): any {
return { return {
stack: e?.stack, stack: e.stack,
message: e?.message, message: e.message,
name: e?.name, name: e.name,
}; };
} }

View file

@ -21,7 +21,7 @@ export async function parseAudience(actor: CacheableRemoteUser, to?: ApObject, c
const limit = promiseLimit<CacheableUser | null>(2); const limit = promiseLimit<CacheableUser | null>(2);
const mentionedUsers = (await Promise.all( const mentionedUsers = (await Promise.all(
others.map(id => limit(() => resolvePerson(id, resolver).catch(() => null))) others.map(id => limit(() => resolvePerson(id, resolver).catch(() => null))),
)).filter((x): x is CacheableUser => x != null); )).filter((x): x is CacheableUser => x != null);
if (toGroups.public.length > 0) { if (toGroups.public.length > 0) {

View file

@ -35,7 +35,7 @@ export async function createImage(actor: CacheableRemoteUser, value: any): Promi
uri: image.url, uri: image.url,
sensitive: image.sensitive, sensitive: image.sensitive,
isLink: !instance.cacheRemoteFiles, isLink: !instance.cacheRemoteFiles,
comment: truncate(image.name, DB_MAX_IMAGE_COMMENT_LENGTH) comment: truncate(image.name, DB_MAX_IMAGE_COMMENT_LENGTH),
}); });
if (file.isLink) { if (file.isLink) {

View file

@ -196,7 +196,7 @@ export async function createNote(value: string | IObject, resolver?: Resolver =
// テキストのパース // テキストのパース
let text: string | null = null; let text: string | null = null;
if (note.source?.mediaType === 'text/x.misskeymarkdown' && typeof note.source?.content === 'string') { if (note.source?.mediaType === 'text/x.misskeymarkdown' && typeof note.source.content === 'string') {
text = note.source.content; text = note.source.content;
} else if (typeof note._misskey_content !== 'undefined') { } else if (typeof note._misskey_content !== 'undefined') {
text = note._misskey_content; text = note._misskey_content;

View file

@ -77,11 +77,11 @@ export async function renderPerson(user: ILocalUser) {
attachment: attachment.length ? attachment : undefined, attachment: attachment.length ? attachment : undefined,
} as any; } as any;
if (profile?.birthday) { if (profile.birthday) {
person['vcard:bday'] = profile.birthday; person['vcard:bday'] = profile.birthday;
} }
if (profile?.location) { if (profile.location) {
person['vcard:Address'] = profile.location; person['vcard:Address'] = profile.location;
} }

View file

@ -123,7 +123,7 @@ export default class Resolver {
if (parsed.rest == null || !/^\w+$/.test(parsed.rest)) throw new Error('resolveLocal: invalid follow URI'); if (parsed.rest == null || !/^\w+$/.test(parsed.rest)) throw new Error('resolveLocal: invalid follow URI');
return Promise.all( return Promise.all(
[parsed.id, parsed.rest].map(id => Users.findOneByOrFail({ id })) [parsed.id, parsed.rest].map(id => Users.findOneByOrFail({ id })),
) )
.then(([follower, followee]) => renderActivity(renderFollow(follower, followee, url))); .then(([follower, followee]) => renderActivity(renderFollow(follower, followee, url)));
default: default:

View file

@ -18,7 +18,7 @@ import orderedCollection from '@/remote/activitypub/renderer/ordered-collection.
export async function readUserMessagingMessage( export async function readUserMessagingMessage(
userId: User['id'], userId: User['id'],
otherpartyId: User['id'], otherpartyId: User['id'],
messageIds: MessagingMessage['id'][] messageIds: MessagingMessage['id'][],
) { ) {
if (messageIds.length === 0) return; if (messageIds.length === 0) return;
@ -58,7 +58,7 @@ export async function readUserMessagingMessage(
recipientId: userId, recipientId: userId,
isRead: false, isRead: false,
}, },
take: 1 take: 1,
}); });
if (!count) { if (!count) {
@ -73,7 +73,7 @@ export async function readUserMessagingMessage(
export async function readGroupMessagingMessage( export async function readGroupMessagingMessage(
userId: User['id'], userId: User['id'],
groupId: UserGroup['id'], groupId: UserGroup['id'],
messageIds: MessagingMessage['id'][] messageIds: MessagingMessage['id'][],
) { ) {
if (messageIds.length === 0) return; if (messageIds.length === 0) return;

View file

@ -7,7 +7,7 @@ import { Notifications, Users } from '@/models/index.js';
export async function readNotification( export async function readNotification(
userId: User['id'], userId: User['id'],
notificationIds: Notification['id'][] notificationIds: Notification['id'][],
) { ) {
if (notificationIds.length === 0) return; if (notificationIds.length === 0) return;
@ -27,7 +27,7 @@ export async function readNotification(
export async function readNotificationByQuery( export async function readNotificationByQuery(
userId: User['id'], userId: User['id'],
query: Record<string, any> query: Record<string, any>,
) { ) {
const notificationIds = await Notifications.findBy({ const notificationIds = await Notifications.findBy({
...query, ...query,

View file

@ -64,7 +64,7 @@ export async function signup(opts: {
passphrase: undefined, passphrase: undefined,
}, },
} as any, (err, publicKey, privateKey) => } as any, (err, publicKey, privateKey) =>
err ? rej(err) : res([publicKey, privateKey]) err ? rej(err) : res([publicKey, privateKey]),
)); ));
let account!: User; let account!: User;

View file

@ -28,7 +28,7 @@ export const paramDef = {
// eslint-disable-next-line import/no-default-export // eslint-disable-next-line import/no-default-export
export default define(meta, paramDef, async () => { export default define(meta, paramDef, async () => {
const sizes = await const sizes = await
db.query(` db.query(`
SELECT relname AS "table", reltuples as "count", pg_total_relation_size(C.oid) AS "size" SELECT relname AS "table", reltuples as "count", pg_total_relation_size(C.oid) AS "size"
FROM pg_class C LEFT JOIN pg_namespace N ON (N.oid = C.relnamespace) FROM pg_class C LEFT JOIN pg_namespace N ON (N.oid = C.relnamespace)
WHERE nspname NOT IN ('pg_catalog', 'information_schema') WHERE nspname NOT IN ('pg_catalog', 'information_schema')

View file

@ -25,7 +25,7 @@ export const paramDef = {
export default define(meta, paramDef, async (ps, me) => { export default define(meta, paramDef, async (ps, me) => {
const [user, profile] = await Promise.all([ const [user, profile] = await Promise.all([
Users.findOneBy({ id: ps.userId }), Users.findOneBy({ id: ps.userId }),
UserProfiles.findOneBy({ userId: ps.userId }) UserProfiles.findOneBy({ userId: ps.userId }),
]); ]);
if (user == null || profile == null) { if (user == null || profile == null) {

View file

@ -58,7 +58,7 @@ export default define(meta, paramDef, async (ps, user) => {
} }
const query = makePaginationQuery(Notes.createQueryBuilder('note'), const query = makePaginationQuery(Notes.createQueryBuilder('note'),
ps.sinceId, ps.untilId, ps.sinceDate, ps.untilDate) ps.sinceId, ps.untilId, ps.sinceDate, ps.untilDate)
.innerJoin(AntennaNotes.metadata.targetName, 'antennaNote', 'antennaNote.noteId = note.id') .innerJoin(AntennaNotes.metadata.targetName, 'antennaNote', 'antennaNote.noteId = note.id')
.innerJoinAndSelect('note.user', 'user') .innerJoinAndSelect('note.user', 'user')
.leftJoinAndSelect('user.avatar', 'avatar') .leftJoinAndSelect('user.avatar', 'avatar')

View file

@ -47,8 +47,8 @@ export const meta = {
type: 'object', type: 'object',
optional: false, nullable: false, optional: false, nullable: false,
ref: 'UserDetailedNotMe', ref: 'UserDetailedNotMe',
} },
} },
}, },
{ {
type: 'object', type: 'object',
@ -62,9 +62,9 @@ export const meta = {
type: 'object', type: 'object',
optional: false, nullable: false, optional: false, nullable: false,
ref: 'Note', ref: 'Note',
} },
} },
} },
], ],
}, },
} as const; } as const;

View file

@ -47,7 +47,7 @@ export default define(meta, paramDef, async (ps, user) => {
DriveFiles.findOneBy({ DriveFiles.findOneBy({
id: fileId, id: fileId,
userId: user.id, userId: user.id,
}) }),
))).filter((file): file is DriveFile => file != null); ))).filter((file): file is DriveFile => file != null);
if (files.length === 0) { if (files.length === 0) {

View file

@ -46,7 +46,7 @@ export default define(meta, paramDef, async (ps, user) => {
DriveFiles.findOneBy({ DriveFiles.findOneBy({
id: fileId, id: fileId,
userId: user.id, userId: user.id,
}) }),
))).filter((file): file is DriveFile => file != null); ))).filter((file): file is DriveFile => file != null);
if (files.length === 0) { if (files.length === 0) {

View file

@ -127,7 +127,7 @@ export default define(meta, paramDef, async () => {
.andWhere('note.createdAt > :gt', { gt: new Date(now.getTime() - (interval * (i + 1))) }) .andWhere('note.createdAt > :gt', { gt: new Date(now.getTime() - (interval * (i + 1))) })
.cache(60000) // 1 min .cache(60000) // 1 min
.getRawOne() .getRawOne()
.then(x => parseInt(x.count, 10)) .then(x => parseInt(x.count, 10)),
))); )));
} }
@ -140,7 +140,7 @@ export default define(meta, paramDef, async () => {
.andWhere('note.createdAt > :gt', { gt: new Date(now.getTime() - rangeA) }) .andWhere('note.createdAt > :gt', { gt: new Date(now.getTime() - rangeA) })
.cache(60000 * 60) // 60 min .cache(60000 * 60) // 60 min
.getRawOne() .getRawOne()
.then(x => parseInt(x.count, 10)) .then(x => parseInt(x.count, 10)),
)); ));
const stats = hots.map((tag, i) => ({ const stats = hots.map((tag, i) => ({

View file

@ -27,7 +27,7 @@ export const meta = {
ref: 'GalleryPost', ref: 'GalleryPost',
}, },
}, },
} },
}, },
} as const; } as const;

View file

@ -26,7 +26,7 @@ export const meta = {
ref: 'Page', ref: 'Page',
}, },
}, },
} },
}, },
} as const; } as const;

View file

@ -57,7 +57,7 @@ export const meta = {
message: 'Invalid Regular Expression.', message: 'Invalid Regular Expression.',
code: 'INVALID_REGEXP', code: 'INVALID_REGEXP',
id: '0d786918-10df-41cd-8f33-8dec7d9a89a5', id: '0d786918-10df-41cd-8f33-8dec7d9a89a5',
} },
}, },
res: { res: {
@ -77,7 +77,8 @@ export const paramDef = {
lang: { type: 'string', enum: [null, ...Object.keys(langmap)], nullable: true }, lang: { type: 'string', enum: [null, ...Object.keys(langmap)], nullable: true },
avatarId: { type: 'string', format: 'misskey:id', nullable: true }, avatarId: { type: 'string', format: 'misskey:id', nullable: true },
bannerId: { type: 'string', format: 'misskey:id', nullable: true }, bannerId: { type: 'string', format: 'misskey:id', nullable: true },
fields: { type: 'array', fields: {
type: 'array',
minItems: 0, minItems: 0,
maxItems: 16, maxItems: 16,
items: { items: {

View file

@ -1,4 +1,4 @@
import { IsNull, MoreThan } from 'typeorm'; import { IsNull } from 'typeorm';
import config from '@/config/index.js'; import config from '@/config/index.js';
import { fetchMeta } from '@/misc/fetch-meta.js'; import { fetchMeta } from '@/misc/fetch-meta.js';
import { Emojis, Users } from '@/models/index.js'; import { Emojis, Users } from '@/models/index.js';

View file

@ -1,4 +1,3 @@
import { Brackets } from 'typeorm';
import { Notes } from '@/models/index.js'; import { Notes } from '@/models/index.js';
import define from '../../define.js'; import define from '../../define.js';
import { makePaginationQuery } from '../../common/make-pagination-query.js'; import { makePaginationQuery } from '../../common/make-pagination-query.js';

View file

@ -16,7 +16,7 @@ export class ApiError extends Error {
kind: 'server', kind: 'server',
httpStatusCode: 500, httpStatusCode: 500,
}, },
info?: any | null | undefined info?: any | null | undefined,
) { ) {
super(e.message); super(e.message);
this.message = e.message; this.message = e.message;

View file

@ -37,7 +37,7 @@ export function genOpenapiSpec() {
Bearer: { Bearer: {
type: 'http', type: 'http',
scheme: 'bearer', scheme: 'bearer',
} },
}, },
}, },
}; };

View file

@ -55,6 +55,6 @@ export const schemas = {
}, },
...Object.fromEntries( ...Object.fromEntries(
Object.entries(refs).map(([key, schema]) => [key, convertSchemaToOpenApiSchema(schema)]) Object.entries(refs).map(([key, schema]) => [key, convertSchemaToOpenApiSchema(schema)]),
), ),
}; };

View file

@ -172,7 +172,7 @@ export default async (ctx: Koa.Context) => {
body.credentialId body.credentialId
.replace(/-/g, '+') .replace(/-/g, '+')
.replace(/_/g, '/'), .replace(/_/g, '/'),
'base64' 'base64',
).toString('hex'), ).toString('hex'),
}); });

View file

@ -1,6 +1,6 @@
import * as http from 'node:http';
import { EventEmitter } from 'events'; import { EventEmitter } from 'events';
import { ParsedUrlQuery } from 'querystring'; import { ParsedUrlQuery } from 'querystring';
import * as http from 'node:http';
import * as websocket from 'websocket'; import * as websocket from 'websocket';
import { subscriber as redisClient } from '@/db/redis.js'; import { subscriber as redisClient } from '@/db/redis.js';
@ -8,13 +8,13 @@ import { Users } from '@/models/index.js';
import MainStreamConnection from './stream/index.js'; import MainStreamConnection from './stream/index.js';
import authenticate from './authenticate.js'; import authenticate from './authenticate.js';
export const initializeStreamingServer = (server: http.Server) => { export const initializeStreamingServer = (server: http.Server): void => {
// Init websocket server // Init websocket server
const ws = new websocket.server({ const ws = new websocket.server({
httpServer: server, httpServer: server,
}); });
ws.on('request', async (request) => { ws.on('request', async (request): Promise<void> => {
const q = request.resourceURL.query as ParsedUrlQuery; const q = request.resourceURL.query as ParsedUrlQuery;
const [user, app] = await authenticate(request.httpRequest.headers.authorization, q.i) const [user, app] = await authenticate(request.httpRequest.headers.authorization, q.i)

View file

@ -13,7 +13,7 @@ const nodeinfo2_0path = '/nodeinfo/2.0';
export const links = [{ export const links = [{
rel: 'http://nodeinfo.diaspora.software/ns/schema/2.1', rel: 'http://nodeinfo.diaspora.software/ns/schema/2.1',
href: config.url + nodeinfo2_1path href: config.url + nodeinfo2_1path,
}, { }, {
rel: 'http://nodeinfo.diaspora.software/ns/schema/2.0', rel: 'http://nodeinfo.diaspora.software/ns/schema/2.0',
href: config.url + nodeinfo2_0path, href: config.url + nodeinfo2_0path,

View file

@ -2,7 +2,7 @@ import Koa from 'koa';
import { fetchMeta } from '@/misc/fetch-meta.js'; import { fetchMeta } from '@/misc/fetch-meta.js';
import manifest from './manifest.json' assert { type: 'json' }; import manifest from './manifest.json' assert { type: 'json' };
export const manifestHandler = async (ctx: Koa.Context) => { export const manifestHandler = async (ctx: Koa.Context): Promise<void> => {
// TODO // TODO
//const res = structuredClone(manifest); //const res = structuredClone(manifest);
const res = JSON.parse(JSON.stringify(manifest)); const res = JSON.parse(JSON.stringify(manifest));

View file

@ -8,7 +8,7 @@ import { getJson } from '@/misc/fetch.js';
const logger = new Logger('url-preview'); const logger = new Logger('url-preview');
export const urlPreviewHandler = async (ctx: Koa.Context) => { export const urlPreviewHandler = async (ctx: Koa.Context): Promise<void> => {
const url = ctx.query.url; const url = ctx.query.url;
if (typeof url !== 'string') { if (typeof url !== 'string') {
ctx.status = 400; ctx.status = 400;

View file

@ -13,11 +13,11 @@ const router = new Router();
const XRD = (...x: { element: string, value?: string, attributes?: Record<string, string> }[]) => const XRD = (...x: { element: string, value?: string, attributes?: Record<string, string> }[]) =>
`<?xml version="1.0" encoding="UTF-8"?><XRD xmlns="http://docs.oasis-open.org/ns/xri/xrd-1.0">${x.map(({ element, value, attributes }) => `<?xml version="1.0" encoding="UTF-8"?><XRD xmlns="http://docs.oasis-open.org/ns/xri/xrd-1.0">${x.map(({ element, value, attributes }) =>
`<${ `<${
Object.entries(typeof attributes === 'object' && attributes || {}).reduce((a, [k, v]) => `${a} ${k}="${escapeAttribute(v)}"`, element) Object.entries(typeof attributes === 'object' && attributes || {}).reduce((a, [k, v]) => `${a} ${k}="${escapeAttribute(v)}"`, element)
}${ }${
typeof value === 'string' ? `>${escapeValue(value)}</${element}` : '/' typeof value === 'string' ? `>${escapeValue(value)}</${element}` : '/'
}>`).reduce((a, c) => a + c, '')}</XRD>`; }>`).reduce((a, c) => a + c, '')}</XRD>`;
const allPath = '/.well-known/(.*)'; const allPath = '/.well-known/(.*)';
const webFingerPath = '/.well-known/webfinger'; const webFingerPath = '/.well-known/webfinger';

View file

@ -9,7 +9,7 @@ import { sendEmailNotification } from './send-email-notification.js';
export async function createNotification( export async function createNotification(
notifieeId: User['id'], notifieeId: User['id'],
type: Notification['type'], type: Notification['type'],
data: Partial<Notification> data: Partial<Notification>,
) { ) {
if (data.notifierId && (notifieeId === data.notifierId)) { if (data.notifierId && (notifieeId === data.notifierId)) {
return null; return null;

View file

@ -10,7 +10,7 @@ import { UsedUsername } from '@/models/entities/used-username.js';
import { db } from '@/db/postgre.js'; import { db } from '@/db/postgre.js';
import generateNativeUserToken from '../server/api/common/generate-native-user-token.js'; import generateNativeUserToken from '../server/api/common/generate-native-user-token.js';
export async function createSystemUser(username: string) { export async function createSystemUser(username: string): Promise<User> {
const password = uuid(); const password = uuid();
// Generate hash of password // Generate hash of password

View file

@ -8,7 +8,7 @@ export async function deleteAccount(user: {
host: string | null; host: string | null;
}): Promise<void> { }): Promise<void> {
// 物理削除する前にDelete activityを送信する // 物理削除する前にDelete activityを送信する
await doPostSuspend(user).catch(e => {}); await doPostSuspend(user).catch(() => {});
createDeleteAccountJob(user, { createDeleteAccountJob(user, {
soft: false, soft: false,

View file

@ -279,7 +279,7 @@ async function upload(key: string, stream: fs.ReadStream | Buffer, _type: string
const s3 = getS3(meta); const s3 = getS3(meta);
const upload = s3.upload(params, { const upload = s3.upload(params, {
partSize: s3.endpoint?.hostname === 'storage.googleapis.com' ? 500 * 1024 * 1024 : 8 * 1024 * 1024, partSize: s3.endpoint.hostname === 'storage.googleapis.com' ? 500 * 1024 * 1024 : 8 * 1024 * 1024,
}); });
const result = await upload.promise(); const result = await upload.promise();
@ -345,7 +345,7 @@ export async function addFile({
isLink = false, isLink = false,
url = null, url = null,
uri = null, uri = null,
sensitive = null sensitive = null,
}: AddFileArgs): Promise<DriveFile> { }: AddFileArgs): Promise<DriveFile> {
const info = await getFileInfo(path); const info = await getFileInfo(path);
logger.info(`${JSON.stringify(info)}`); logger.info(`${JSON.stringify(info)}`);
@ -431,10 +431,9 @@ export async function addFile({
file.blurhash = info.blurhash || null; file.blurhash = info.blurhash || null;
file.isLink = isLink; file.isLink = isLink;
file.isSensitive = user file.isSensitive = user
? Users.isLocalUser(user) && profile!.alwaysMarkNsfw ? true : ? Users.isLocalUser(user) && profile!.alwaysMarkNsfw
(sensitive !== null && sensitive !== undefined) ? true
? sensitive : sensitive ?? false
: false
: false; : false;
if (url !== null) { if (url !== null) {

View file

@ -38,11 +38,11 @@ export async function convertSharpToJpeg(sharp: sharp.Sharp, width: number, heig
* Convert to WebP * Convert to WebP
* with resize, remove metadata, resolve orientation, stop animation * with resize, remove metadata, resolve orientation, stop animation
*/ */
export async function convertToWebp(path: string, width: number, height: number, quality: number = 85): Promise<IImage> { export async function convertToWebp(path: string, width: number, height: number, quality = 85): Promise<IImage> {
return convertSharpToWebp(await sharp(path), width, height, quality); return convertSharpToWebp(await sharp(path), width, height, quality);
} }
export async function convertSharpToWebp(sharp: sharp.Sharp, width: number, height: number, quality: number = 85): Promise<IImage> { export async function convertSharpToWebp(sharp: sharp.Sharp, width: number, height: number, quality = 85): Promise<IImage> {
const data = await sharp const data = await sharp
.resize(width, height, { .resize(width, height, {
fit: 'inside', fit: 'inside',

View file

@ -235,7 +235,7 @@ async function getSiteName(info: NodeInfo | null, doc: DOMWindow['document'] | n
} }
if (manifest) { if (manifest) {
return manifest?.name || manifest?.short_name; return manifest.name || manifest.short_name;
} }
return null; return null;
@ -261,7 +261,7 @@ async function getDescription(info: NodeInfo | null, doc: DOMWindow['document']
} }
if (manifest) { if (manifest) {
return manifest?.name || manifest?.short_name; return manifest.name || manifest.short_name;
} }
return null; return null;

View file

@ -7,12 +7,12 @@ import renderDelete from '@/remote/activitypub/renderer/delete.js';
import renderTombstone from '@/remote/activitypub/renderer/tombstone.js'; import renderTombstone from '@/remote/activitypub/renderer/tombstone.js';
import { deliver } from '@/queue/index.js'; import { deliver } from '@/queue/index.js';
export async function deleteMessage(message: MessagingMessage) { export async function deleteMessage(message: MessagingMessage): Promise<void> {
await MessagingMessages.delete(message.id); await MessagingMessages.delete(message.id);
postDeleteMessage(message); await postDeleteMessage(message);
} }
async function postDeleteMessage(message: MessagingMessage) { async function postDeleteMessage(message: MessagingMessage): Promise<void> {
if (message.recipientId) { if (message.recipientId) {
const user = await Users.findOneByOrFail({ id: message.userId }); const user = await Users.findOneByOrFail({ id: message.userId });
const recipient = await Users.findOneByOrFail({ id: message.recipientId }); const recipient = await Users.findOneByOrFail({ id: message.recipientId });

View file

@ -679,12 +679,12 @@ async function extractMentionedUsers(user: { host: User['host']; }, tokens: mfm.
const mentions = extractMentions(tokens); const mentions = extractMentions(tokens);
let mentionedUsers = (await Promise.all(mentions.map(m => let mentionedUsers = (await Promise.all(mentions.map(m =>
resolveUser(m.username, m.host || user.host).catch(() => null) resolveUser(m.username, m.host || user.host).catch(() => null),
))).filter(x => x != null) as User[]; ))).filter(x => x != null) as User[];
// Drop duplicate users // Drop duplicate users
mentionedUsers = mentionedUsers.filter((u, i, self) => mentionedUsers = mentionedUsers.filter((u, i, self) =>
i === self.findIndex(u2 => u.id === u2.id) i === self.findIndex(u2 => u.id === u2.id),
); );
return mentionedUsers; return mentionedUsers;

View file

@ -21,7 +21,7 @@ import { deliverToRelays } from '../relay.js';
* @param user 稿 * @param user 稿
* @param note 稿 * @param note 稿
*/ */
export default async function(user: { id: User['id']; uri: User['uri']; host: User['host']; }, note: Note, quiet = false) { export default async function(user: { id: User['id']; uri: User['uri']; host: User['host']; }, note: Note, quiet = false): Promise<void> {
const deletedAt = new Date(); const deletedAt = new Date();
// この投稿を除く指定したユーザーによる指定したノートのリノートが存在しないとき // この投稿を除く指定したユーザーによる指定したノートのリノートが存在しないとき
@ -83,7 +83,7 @@ export default async function(user: { id: User['id']; uri: User['uri']; host: Us
}); });
} }
async function findCascadingNotes(note: Note) { async function findCascadingNotes(note: Note): Promise<Note[]> {
const cascadingNotes: Note[] = []; const cascadingNotes: Note[] = [];
const recursive = async (noteId: string) => { const recursive = async (noteId: string) => {
@ -105,7 +105,7 @@ async function findCascadingNotes(note: Note) {
return cascadingNotes.filter(note => note.userHost === null); // filter out non-local users return cascadingNotes.filter(note => note.userHost === null); // filter out non-local users
} }
async function getMentionedRemoteUsers(note: Note) { async function getMentionedRemoteUsers(note: Note): Promise<IRemoteUser[]> {
const where = [] as any[]; const where = [] as any[];
// mention / reply / dm // mention / reply / dm

View file

@ -6,7 +6,7 @@ import { Note } from '@/models/entities/note.js';
import { deliverToFollowers } from '@/remote/activitypub/deliver-manager.js'; import { deliverToFollowers } from '@/remote/activitypub/deliver-manager.js';
import { deliverToRelays } from '../../relay.js'; import { deliverToRelays } from '../../relay.js';
export async function deliverQuestionUpdate(noteId: Note['id']) { export async function deliverQuestionUpdate(noteId: Note['id']): Promise<void> {
const note = await Notes.findOneBy({ id: noteId }); const note = await Notes.findOneBy({ id: noteId });
if (note == null) throw new Error('note not found'); if (note == null) throw new Error('note not found');

View file

@ -18,7 +18,7 @@ export default async function(
info?: { info?: {
following: Set<User['id']>; following: Set<User['id']>;
followingChannels: Set<Channel['id']>; followingChannels: Set<Channel['id']>;
} },
) { ) {
const following = info?.following ? info.following : new Set<string>((await Followings.find({ const following = info?.following ? info.following : new Set<string>((await Followings.find({
where: { where: {

View file

@ -8,7 +8,7 @@ export async function insertNoteUnread(userId: User['id'], note: Note, params: {
// NOTE: isSpecifiedがtrueならisMentionedは必ずfalse // NOTE: isSpecifiedがtrueならisMentionedは必ずfalse
isSpecified: boolean; isSpecified: boolean;
isMentioned: boolean; isMentioned: boolean;
}) { }): Promise<void> {
//#region ミュートしているなら無視 //#region ミュートしているなら無視
// TODO: 現在の仕様ではChannelにミュートは適用されないのでよしなにケアする // TODO: 現在の仕様ではChannelにミュートは適用されないのでよしなにケアする
const mute = await Mutings.findBy({ const mute = await Mutings.findBy({

View file

@ -29,7 +29,7 @@ function truncateNotification(notification: Packed<'Notification'>): any {
reply: undefined, reply: undefined,
renote: undefined, renote: undefined,
user: undefined as any, // 通知を受け取ったユーザーである場合が多いのでこれも捨てる user: undefined as any, // 通知を受け取ったユーザーである場合が多いのでこれも捨てる
} },
}; };
} }

View file

@ -5,7 +5,7 @@ import Logger from './logger.js';
export const logger = new Logger('email'); export const logger = new Logger('email');
export async function sendEmail(to: string, subject: string, html: string, text: string) { export async function sendEmail(to: string, subject: string, html: string, text: string): Promise<void> {
const meta = await fetchMeta(true); const meta = await fetchMeta(true);
const iconUrl = `${config.url}/static-assets/mi-white.png`; const iconUrl = `${config.url}/static-assets/mi-white.png`;

View file

@ -7,7 +7,7 @@ import { User } from '@/models/entities/user.js';
import { Users, Followings } from '@/models/index.js'; import { Users, Followings } from '@/models/index.js';
import { publishInternalEvent } from '@/services/stream.js'; import { publishInternalEvent } from '@/services/stream.js';
export async function doPostSuspend(user: { id: User['id']; host: User['host'] }) { export async function doPostSuspend(user: { id: User['id']; host: User['host'] }): Promise<void> {
publishInternalEvent('userChangeSuspendedState', { id: user.id, isSuspended: true }); publishInternalEvent('userChangeSuspendedState', { id: user.id, isSuspended: true });
if (Users.isLocalUser(user)) { if (Users.isLocalUser(user)) {

View file

@ -5,13 +5,13 @@ import { genId } from '@/misc/gen-id.js';
import { Hashtag } from '@/models/entities/hashtag.js'; import { Hashtag } from '@/models/entities/hashtag.js';
import { normalizeForSearch } from '@/misc/normalize-for-search.js'; import { normalizeForSearch } from '@/misc/normalize-for-search.js';
export async function updateHashtags(user: { id: User['id']; host: User['host']; }, tags: string[]) { export async function updateHashtags(user: { id: User['id']; host: User['host']; }, tags: string[]): Promise<void> {
for (const tag of tags) { for (const tag of tags) {
await updateHashtag(user, tag); await updateHashtag(user, tag);
} }
} }
export async function updateUsertags(user: User, tags: string[]) { export async function updateUsertags(user: User, tags: string[]): Promise<void> {
for (const tag of tags) { for (const tag of tags) {
await updateHashtag(user, tag, true, true); await updateHashtag(user, tag, true, true);
} }
@ -21,7 +21,7 @@ export async function updateUsertags(user: User, tags: string[]) {
} }
} }
export async function updateHashtag(user: { id: User['id']; host: User['host']; }, _tag: string, isUserAttached = false, inc = true) { export async function updateHashtag(user: { id: User['id']; host: User['host']; }, _tag: string, isUserAttached = false, inc = true): Promise<void> {
const tag = normalizeForSearch(_tag); const tag = normalizeForSearch(_tag);
const index = await Hashtags.findOneBy({ name: tag }); const index = await Hashtags.findOneBy({ name: tag });

View file

@ -7,7 +7,7 @@ import { genId } from '@/misc/gen-id.js';
import { fetchProxyAccount } from '@/misc/fetch-proxy-account.js'; import { fetchProxyAccount } from '@/misc/fetch-proxy-account.js';
import createFollowing from '../following/create.js'; import createFollowing from '../following/create.js';
export async function pushUserToUserList(target: User, list: UserList) { export async function pushUserToUserList(target: User, list: UserList): Promise<void> {
await UserListJoinings.insert({ await UserListJoinings.insert({
id: genId(), id: genId(),
createdAt: new Date(), createdAt: new Date(),

View file

@ -24,11 +24,11 @@ export async function validateEmailForAccount(emailAddress: string): Promise<{
return { return {
available, available,
reason: available ? null : reason: available ? null :
exist !== 0 ? 'used' : exist !== 0 ? 'used' :
validated.reason === 'regex' ? 'format' : validated.reason === 'regex' ? 'format' :
validated.reason === 'disposable' ? 'disposable' : validated.reason === 'disposable' ? 'disposable' :
validated.reason === 'mx' ? 'mx' : validated.reason === 'mx' ? 'mx' :
validated.reason === 'smtp' ? 'smtp' : validated.reason === 'smtp' ? 'smtp' :
null, null,
}; };
} }