Skip to content

Commit

Permalink
petit refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
vmaubert committed Dec 18, 2024
1 parent 18c7404 commit b501a48
Show file tree
Hide file tree
Showing 2 changed files with 92 additions and 55 deletions.
14 changes: 13 additions & 1 deletion .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,18 @@
"plugins": ["@typescript-eslint"],
"rules": {
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/no-var-requires": "off"
"@typescript-eslint/no-var-requires": "off",
"@typescript-eslint/no-unused-vars": [
"error",
{
"args": "all",
"argsIgnorePattern": "^_",
"caughtErrors": "all",
"caughtErrorsIgnorePattern": "^_",
"destructuredArrayIgnorePattern": "^_",
"varsIgnorePattern": "^_",
"ignoreRestSiblings": true
}
]
}
}
133 changes: 79 additions & 54 deletions server/services/imapService/index.ts
Original file line number Diff line number Diff line change
@@ -1,95 +1,120 @@
import {ImapFlow} from 'imapflow';
import { createWriteStream } from 'node:fs';
import { simpleParser } from 'mailparser';
import config from '../../utils/config';
import { ImapFlow } from 'imapflow';
import { isNull } from 'lodash';
import { ParsedMail, simpleParser } from 'mailparser';
import { LaboratoryName } from '../../../shared/referential/Laboratory';
import config from '../../utils/config';

const laboratoriesWithConf = ['GIR 49'] as const satisfies LaboratoryName[];
type LaboratoryWithConf = (typeof laboratoriesWithConf)[number];
const laboratoriesConf = {
'GIR 49': {
//FIXME
isSender: (_senderAddress) =>
true,
extractData: (email): null | unknown => email ?? null
}
} as const satisfies {
[name in LaboratoryWithConf]: {
isSender: (senderAddress: string) => boolean;
extractData: (email: ParsedMail) => void;
};
};

const run =async () => {
//FIXME test
export const getLaboratoryNameBySender = (
senderAddress: string
): null | LaboratoryWithConf => {
for (const laboratory of laboratoriesWithConf) {
if (laboratoriesConf[laboratory].isSender(senderAddress)) {
return laboratory;
}
}
return null;
};

const run = async () => {
if (
isNull(config.inbox.user) ||
isNull(config.inbox.host) ||
isNull(config.inbox.password)
) {
console.warn("Impossible d'accéder à la boite email car les variables INBOX ne sont pas définies")
return
console.warn(
"Impossible d'accéder à la boite email car les variables INBOX ne sont pas définies"
);
return;
}

const client = new ImapFlow({
host: config.inbox.host,
auth: {
user: config.inbox.user,
pass: config.inbox.password
pass: config.inbox.password
},
port: config.inbox.port,
secure: true,
logger: false
});
await client.connect()
// Select and lock a mailbox. Throws if mailbox does not exist
await client.connect();
// Select and lock a mailbox. Throws if mailbox does not exist
const lock = await client.getMailboxLock(config.inbox.mailboxName);
try {
// fetch latest message source
// client.mailbox includes information about currently selected mailbox
// "exists" value is also the largest sequence number available in the mailbox
if( typeof client.mailbox !== 'boolean' ) {
if (typeof client.mailbox !== 'boolean') {
// const message = await client.fetchOne(`${client.mailbox.exists}`, { source: true });
// console.log(message.source.toString());

const messagesToRead: {messageUid: number, laboratoryName: LaboratoryName}[] = []
const messagesToRead: {
messageUid: number;
laboratoryName: LaboratoryWithConf;
}[] = [];
// list subjects for all messages
// uid value is always included in FETCH response, envelope strings are in unicode.
for await (const message of client.fetch('1:*', { envelope: true, bodyStructure: true })) {

console.log('Email reçu', message.envelope.sender[0].address, message.envelope.subject)

let laboratoryName: LaboratoryName | null = null

//FIXME check sender email en plus de l'objet pour trouver le bon labo
//FIXME mettre le bon objet
//FIXME ajouter un test
if (message.envelope.subject === 'TEST LABO') {
laboratoryName = 'GIR 49'
}
for await (const message of client.fetch('1:*', {
envelope: true,
bodyStructure: true
})) {
console.log(
'Email reçu',
message.envelope.sender[0].address,
message.envelope.subject
);

const laboratoryName: LaboratoryWithConf | null =
getLaboratoryNameBySender(message.envelope.sender[0].address ?? '');

if (laboratoryName !== null) {
messagesToRead.push({messageUid: message.uid, laboratoryName})
console.log(' =====> ', laboratoryName)
}else {
console.log(' =====> IGNORÉ')
messagesToRead.push({ messageUid: message.uid, laboratoryName });
console.log(' =====> ', laboratoryName);
} else {
console.log(' =====> IGNORÉ');
}
// if (message.bodyStructure.childNodes.length) {
// for (const node of message.bodyStructure.childNodes){
//
// if( node.type === 'application/vnd.oasis.opendocument.text'){
// messageIdsToRead.push(message.uid)
// }
// }
}
for (const messagesToReadElement of messagesToRead) {
//null permet de récupérer tout l'email
//@ts-expect-error TS2345
const downloadObject = await client.download(messagesToReadElement.messageUid,null, {uid: true})

const parsed = await simpleParser(downloadObject.content)
// console.log(`Email reçu pour ${messagesToReadElement.laboratoryName}: ${parsed}`)

await client.messageMove(`${messagesToReadElement.messageUid}`, config.inbox.trashboxName, {uid: true})
// createWriteStream(parsed.attachments[2].filename ?? '').write(parsed.attachments[2].content)

for (const message of messagesToRead) {
const messageUid: string = `${message.messageUid}`
//undefined permet de récupérer tout l'email
const downloadObject = await client.download(messageUid, undefined, {
uid: true
});

const parsed = await simpleParser(downloadObject.content);
console.log(parsed);

}

//FIXME trash
// await client.messageMove(messageUid, config.inbox.trashboxName, {uid: true})

const data =

Check failure on line 107 in server/services/imapService/index.ts

View workflow job for this annotation

GitHub Actions / build_test (22.x)

'data' is declared but its value is never read.
laboratoriesConf[message.laboratoryName].extractData(
parsed
);

// createWriteStream(parsed.attachments[2].filename ?? '').write(parsed.attachments[2].content)
}
}
} catch(e){
console.error(e)
}
finally {
} catch (e) {
console.error(e);
} finally {
// Make sure lock is released, otherwise next `getMailboxLock()` never returns
lock.release();
}
Expand All @@ -98,4 +123,4 @@ const run =async () => {
await client.logout();
};

run().catch(err => console.error(err));
run().catch((err) => console.error(err));

0 comments on commit b501a48

Please sign in to comment.