Skip to content

Commit

Permalink
Add bayes score checks before and after training
Browse files Browse the repository at this point in the history
Perform sequential bayes score checks before and after training and display results to the user via system notifications.
  • Loading branch information
moisseev committed Aug 13, 2024
1 parent 7b87225 commit d056a44
Show file tree
Hide file tree
Showing 4 changed files with 83 additions and 26 deletions.
3 changes: 3 additions & 0 deletions _locales/en/messages.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,9 @@
"spamness.alertText.failedToSendRequestToRspamd": {
"message": "Failed to send request to Rspamd."
},
"spamness.alertText.failedToParseResponse": {
"message": "Failed to parse response."
},
"spamness.alertText.pleaseConfigure": {
"message": "Please configure"
},
Expand Down
3 changes: 3 additions & 0 deletions _locales/ru/messages.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@
"spamness.alertText.failedToSendRequestToRspamd": {
"message": "Не удалось отправить запрос к Rspamd."
},
"spamness.alertText.failedToParseResponse": {
"message": "Не удалось извлечь информацию из ответа."
},
"spamness.alertText.pleaseConfigure": {
"message": "Пожалуйста, настройте"
},
Expand Down
2 changes: 1 addition & 1 deletion eslint.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ export default [
"func-names": "off",
"func-style": ["error", "declaration"],
"id-length": ["error", {min: 1}],
"max-lines": ["error", 450],
"max-lines": ["error", 500],
"max-lines-per-function": ["warn", 250],
"max-params": ["warn", 6],
"max-statements": ["warn", 50],
Expand Down
101 changes: 76 additions & 25 deletions scripts/background.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@ async function sendMessageToRspamd(message, buttonId, action) {
}

const hamSpam = (buttonId === "rspamdSpamnessButtonHam") ? "Ham" : "Spam";

const headers = new Headers();

if (action === "fuzzy") {
Expand All @@ -63,47 +62,99 @@ async function sendMessageToRspamd(message, buttonId, action) {

if (localStorage.serverPassword) headers.append("Password", localStorage.serverPassword);

function parseSymbols(symbols) {
const regexp = action === "bayes" ? /BAYES_/ : /(BAYES_|FUZZY_)/;
return Object.keys(symbols)
.filter((s) => regexp.test(s))
.sort()
.map((k) => {
const s = symbols[k];
return `${s.name} (${s.score.toFixed(2)}) [${s.options[0]}]`;
})
.join("\n");
}

async function handleResponse(response) {
try {
const {symbols} = await response.json();
return [null, parseSymbols(symbols), "info"];
} catch (error) {
return ["spamness.alertText.failedToParseResponse", `${error.name}: ${error.message}`, "error"];
}
}

const endpoint = {
bayes: "/learn" + hamSpam.toLowerCase(),
check: "/checkv2",
fuzzy: "/fuzzyadd"
};
const file = await browser.messages.getRaw(message.id);

try {
const serverUrl = new URL(endpoint[action], localStorage.serverBaseUrl);
const file = await browser.messages.getRaw(message.id);

const response = await fetch(serverUrl, {
body: file,
headers: headers,
method: "POST",
});

if (response.ok) {
async function sendRequestToRspamd(endpointType) {
async function displayResponseNotification(response) {
if (response.status === 200) {
if (action === "check") {
const {symbols} = await response.json();
const filteredKeys = Object.keys(symbols).filter((s) => (/(BAYES_|FUZZY_)/).test(s)).sort();
const msg = filteredKeys.reduce((prev, k) => {
const s = symbols[k];
return prev + s.name + "(" + s.score.toFixed(2) + ")[" + s.options[0] + "]\n";
}, "");
libBackground.displayNotification(null, msg, "info");
} else {
const [messageName, string, logLevel] = await handleResponse(response);
libBackground.displayNotification(messageName, string, logLevel);
} else if (action !== "bayes") {
libBackground.displayNotification(
null,
browser.i18n.getMessage("spamness.alertText.messageTrainedAs") + hamSpam,
"info"
);
}
} else {
libBackground.displayNotification(null, `Status: ${response.status}\n${response.statusText}`, "info");
libBackground.displayNotification(
null,
`Status: ${response.status}\n${response.statusText}`,
"info"
);
}
}

const serverUrl = new URL(endpoint[endpointType], localStorage.serverBaseUrl);
try {
const response = await fetch(serverUrl, {
body: file,
headers: headers,
method: "POST",
});

if (response.ok) {
await displayResponseNotification(response);
} else {
libBackground.displayNotification(null, `Status: ${response.status}\n${response.statusText}`);
}

return response;
} catch (error) {
libBackground.displayNotification("spamness.alertText.failedToSendRequestToRspamd", error.message);
return null;
}
}

if (action === "bayes") {
const bayesRequestSequence = ["check", "bayes", "check"];
const responses = [];
for (const endpointType of bayesRequestSequence) {
// eslint-disable-next-line no-await-in-loop
const response = await sendRequestToRspamd(endpointType);
if (response && response.status === 200) {
responses.push(response);
} else {
break;
}
} else {
libBackground.displayNotification(null, `Status: ${response.status}\n${response.statusText}`);
}
} catch (e) {
libBackground.displayNotification("spamness.alertText.failedToSendRequestToRspamd", e.message);

if (responses.length < 2) return;

let msg = "1. " + (await handleResponse(responses[0]))[1] +
"\n2. " + browser.i18n.getMessage("spamness.alertText.messageTrainedAs") + hamSpam;
if (responses.length > 2) msg += "\n3. " + (await handleResponse(responses[2]))[1];

libBackground.displayNotification(null, msg, "info");
} else {
await sendRequestToRspamd(action);
}
}

Expand Down

0 comments on commit d056a44

Please sign in to comment.