Lint + formatting

This commit is contained in:
PrivateGER 2023-05-26 03:06:41 +02:00 committed by PrivateGER
parent 43813d12b5
commit 274bfcd898
7 changed files with 144 additions and 127 deletions

View File

@ -41,7 +41,7 @@ export default function () {
r: round(Math.max(0, fsStats.rIO_sec ?? 0)), r: round(Math.max(0, fsStats.rIO_sec ?? 0)),
w: round(Math.max(0, fsStats.wIO_sec ?? 0)), w: round(Math.max(0, fsStats.wIO_sec ?? 0)),
}, },
meilisearch: meilisearchStats meilisearch: meilisearchStats,
}; };
ev.emit("serverStats", stats); ev.emit("serverStats", stats);
log.unshift(stats); log.unshift(stats);

View File

@ -1,4 +1,4 @@
import {Health, MeiliSearch, Stats} from 'meilisearch'; import {Health, MeiliSearch, Stats} from "meilisearch";
import {dbLogger} from "./logger.js"; import {dbLogger} from "./logger.js";
import config from "@/config/index.js"; import config from "@/config/index.js";
@ -7,13 +7,15 @@ import * as url from "url";
import {User} from "@/models/entities/user.js"; import {User} from "@/models/entities/user.js";
import {Users} from "@/models/index.js"; import {Users} from "@/models/index.js";
const logger = dbLogger.createSubLogger("meilisearch", "gray", false); const logger = dbLogger.createSubLogger("meilisearch", "gray", false);
logger.info("Connecting to MeiliSearch"); logger.info("Connecting to MeiliSearch");
const hasConfig = const hasConfig =
config.meilisearch && (config.meilisearch.host || config.meilisearch.port || config.meilisearch.apiKey); config.meilisearch &&
(config.meilisearch.host ||
config.meilisearch.port ||
config.meilisearch.apiKey);
const host = hasConfig ? config.meilisearch.host ?? "localhost" : ""; const host = hasConfig ? config.meilisearch.host ?? "localhost" : "";
const port = hasConfig ? config.meilisearch.port ?? 7700 : 0; const port = hasConfig ? config.meilisearch.port ?? 7700 : 0;
@ -22,13 +24,28 @@ const auth = hasConfig ? config.meilisearch.apiKey ?? "" : "";
const client: MeiliSearch = new MeiliSearch({ const client: MeiliSearch = new MeiliSearch({
host: `http://${host}:${port}`, host: `http://${host}:${port}`,
apiKey: auth, apiKey: auth,
}) });
const posts = client.index('posts'); const posts = client.index("posts");
posts.updateSearchableAttributes(['text']).catch((e) => logger.error(`Setting searchable attr failed, searches won't work: ${e}`)); posts
.updateSearchableAttributes(["text"])
.catch((e) =>
logger.error(`Setting searchable attr failed, searches won't work: ${e}`),
);
posts.updateFilterableAttributes(["userName", "userHost", "mediaAttachment", "createdAt"]).catch((e) => logger.error(`Setting filterable attr failed, advanced searches won't work: ${e}`)); posts
.updateFilterableAttributes([
"userName",
"userHost",
"mediaAttachment",
"createdAt",
])
.catch((e) =>
logger.error(
`Setting filterable attr failed, advanced searches won't work: ${e}`,
),
);
logger.info("Connected to MeiliSearch"); logger.info("Connected to MeiliSearch");
@ -40,12 +57,12 @@ export type MeilisearchNote = {
userName: string; userName: string;
channelId: string; channelId: string;
mediaAttachment: string; mediaAttachment: string;
createdAt: number createdAt: number;
} };
export default hasConfig ? { export default hasConfig
? {
search: (query: string, limit: number, offset: number) => { search: (query: string, limit: number, offset: number) => {
/// Advanced search syntax /// Advanced search syntax
/// from:user => filter by user + optional domain /// from:user => filter by user + optional domain
/// has:image/video/audio/text/file => filter by attachment types /// has:image/video/audio/text/file => filter by attachment types
@ -53,54 +70,52 @@ export default hasConfig ? {
/// before:Date => show posts made before Date /// before:Date => show posts made before Date
/// after: Date => show posts made after Date /// after: Date => show posts made after Date
let constructedFilters: string[] = []; let constructedFilters: string[] = [];
let splitSearch = query.split(" "); let splitSearch = query.split(" ");
// Detect search operators and remove them from the actual query // Detect search operators and remove them from the actual query
splitSearch = splitSearch.filter(term => { splitSearch = splitSearch.filter((term) => {
if (term.startsWith("has:")) { if (term.startsWith("has:")) {
let fileType = term.slice(4); let fileType = term.slice(4);
constructedFilters.push(`mediaAttachment = "${fileType}"`) constructedFilters.push(`mediaAttachment = "${fileType}"`);
return false; return false;
} else if (term.startsWith("from:")) { } else if (term.startsWith("from:")) {
let user = term.slice(5); let user = term.slice(5);
constructedFilters.push(`userName = ${user}`) constructedFilters.push(`userName = ${user}`);
return false; return false;
} else if (term.startsWith("domain:")) { } else if (term.startsWith("domain:")) {
let domain = term.slice(7); let domain = term.slice(7);
constructedFilters.push(`userHost = ${domain}`) constructedFilters.push(`userHost = ${domain}`);
return false; return false;
} else if (term.startsWith("after:")) { } else if (term.startsWith("after:")) {
let timestamp = term.slice(6); let timestamp = term.slice(6);
// Try to parse the timestamp as JavaScript Date // Try to parse the timestamp as JavaScript Date
let date = Date.parse(timestamp); let date = Date.parse(timestamp);
if (isNaN(date)) return false; if (isNaN(date)) return false;
constructedFilters.push(`createdAt > ${date}`) constructedFilters.push(`createdAt > ${date}`);
return false; return false;
} else if (term.startsWith("before:")) { } else if (term.startsWith("before:")) {
let timestamp = term.slice(7); let timestamp = term.slice(7);
// Try to parse the timestamp as JavaScript Date // Try to parse the timestamp as JavaScript Date
let date = Date.parse(timestamp); let date = Date.parse(timestamp);
if (isNaN(date)) return false; if (isNaN(date)) return false;
constructedFilters.push(`createdAt < ${date}`) constructedFilters.push(`createdAt < ${date}`);
return false; return false;
} }
return true; return true;
}) });
logger.info(`Searching for ${splitSearch.join(" ")}`); logger.info(`Searching for ${splitSearch.join(" ")}`);
logger.info(`Limit: ${limit}`); logger.info(`Limit: ${limit}`);
logger.info(`Offset: ${offset}`); logger.info(`Offset: ${offset}`);
logger.info(`Filters: ${constructedFilters}`) logger.info(`Filters: ${constructedFilters}`);
return posts.search(splitSearch.join(" "), { return posts.search(splitSearch.join(" "), {
limit: limit, limit: limit,
offset: offset, offset: offset,
filter: constructedFilters filter: constructedFilters,
}); });
}, },
ingestNote: async (ingestNotes: Note | Note[]) => { ingestNote: async (ingestNotes: Note | Note[]) => {
@ -114,8 +129,8 @@ export default hasConfig ? {
if (note.user === undefined) { if (note.user === undefined) {
let user = await Users.findOne({ let user = await Users.findOne({
where: { where: {
id: note.userId id: note.userId,
} },
}); });
note.user = user; note.user = user;
} }
@ -130,8 +145,8 @@ export default hasConfig ? {
case "text": case "text":
break; break;
default: default:
attachmentType = "file" attachmentType = "file";
break break;
} }
} }
@ -139,19 +154,21 @@ export default hasConfig ? {
id: note.id.toString(), id: note.id.toString(),
text: note.text ? note.text : "", text: note.text ? note.text : "",
userId: note.userId, userId: note.userId,
userHost: note.userHost !== "" ? note.userHost : url.parse(config.host).host, userHost:
note.userHost !== ""
? note.userHost
: url.parse(config.host).host,
channelId: note.channelId ? note.channelId : "", channelId: note.channelId ? note.channelId : "",
mediaAttachment: attachmentType, mediaAttachment: attachmentType,
userName: note.user?.username ?? "UNKNOWN", userName: note.user?.username ?? "UNKNOWN",
createdAt: note.createdAt.getTime() / 1000 // division by 1000 is necessary because Node returns in ms-accuracy createdAt: note.createdAt.getTime() / 1000, // division by 1000 is necessary because Node returns in ms-accuracy
} });
)
} }
let indexingIDs = indexingBatch.map(note => note.id); let indexingIDs = indexingBatch.map((note) => note.id);
return posts.addDocuments(indexingBatch, { return posts.addDocuments(indexingBatch, {
primaryKey: "id" primaryKey: "id",
}); });
}, },
serverStats: async () => { serverStats: async () => {
@ -161,7 +178,8 @@ export default hasConfig ? {
return { return {
health: health.status, health: health.status,
size: stats.databaseSize, size: stats.databaseSize,
indexed_count: stats.indexes["posts"].numberOfDocuments indexed_count: stats.indexes["posts"].numberOfDocuments,
};
},
} }
} : null;
} : null;

View File

@ -39,7 +39,7 @@ export default async function indexAllNotes(
order: { order: {
id: 1, id: 1,
}, },
relations: ["user"] relations: ["user"],
}); });
} catch (e) { } catch (e) {
logger.error(`Failed to query notes ${e}`); logger.error(`Failed to query notes ${e}`);
@ -62,7 +62,7 @@ export default async function indexAllNotes(
const chunk = notes.slice(i, i + batch); const chunk = notes.slice(i, i + batch);
if (meilisearch) { if (meilisearch) {
await meilisearch.ingestNote(chunk) await meilisearch.ingestNote(chunk);
} }
await Promise.all(chunk.map((note) => index(note, true))); await Promise.all(chunk.map((note) => index(note, true)));

View File

@ -236,7 +236,6 @@ export default define(meta, paramDef, async (ps, me) => {
} }
return found; return found;
} else { } else {
const userQuery = const userQuery =
ps.userId != null ps.userId != null

View File

@ -34,8 +34,7 @@ export default define(meta, paramDef, async () => {
total: fsStats[0].size, total: fsStats[0].size,
used: fsStats[0].used, used: fsStats[0].used,
}, },
meilisearch: meilisearchStats meilisearch: meilisearchStats,
}; };
}); });

View File

@ -6,12 +6,13 @@ export async function search() {
const { canceled, result: query } = await os.inputText({ const { canceled, result: query } = await os.inputText({
title: i18n.ts.search, title: i18n.ts.search,
placeholder: "Enter search terms...", placeholder: "Enter search terms...",
text: "Advanced search operators\n" + text:
"Advanced search operators\n" +
"from:user => filter by user\n" + "from:user => filter by user\n" +
"has:image/video/audio/text/file => filter by attachment types\n" + "has:image/video/audio/text/file => filter by attachment types\n" +
"domain:domain.com => filter by domain\n" + "domain:domain.com => filter by domain\n" +
"before:Date => show posts made before Date\n" + "before:Date => show posts made before Date\n" +
"after:Date => show posts made after Date" "after:Date => show posts made after Date",
}); });
if (canceled || query == null || query === "") return; if (canceled || query == null || query === "") return;

View File

@ -61,7 +61,7 @@ import XNet from "./net.vue";
import XCpu from "./cpu.vue"; import XCpu from "./cpu.vue";
import XMemory from "./mem.vue"; import XMemory from "./mem.vue";
import XDisk from "./disk.vue"; import XDisk from "./disk.vue";
import XMeili from "./meilisearch.vue" import XMeili from "./meilisearch.vue";
import MkContainer from "@/components/MkContainer.vue"; import MkContainer from "@/components/MkContainer.vue";
import { GetFormResultType } from "@/scripts/form"; import { GetFormResultType } from "@/scripts/form";
import * as os from "@/os"; import * as os from "@/os";