buildRows scandiva fino a 2000 righe e si fermava quando mittente e oggetto erano vuoti, ma la riga successiva all'ultima non esiste: Ada sollevava CONSTRAINT_ERROR su mail_boxes.adb B.Order (Row + 1) a ogni lettura, due volte. Visto sul telefono: 234 occorrenze in 1273 righe di log. Ora il limite e' il conteggio che s_open restituisce.
1839 lines
68 KiB
C++
1839 lines
68 KiB
C++
#include "enginebridge.h"
|
|
#include "accountsettings.h"
|
|
|
|
#include <QCoreApplication>
|
|
#include <QDir>
|
|
#include <QRegularExpression>
|
|
#include <QFile>
|
|
#include <QFileInfo>
|
|
#include <QHash>
|
|
#include <QSettings>
|
|
#include <QSaveFile>
|
|
#include <QSet>
|
|
#include <QStandardPaths>
|
|
#include <QStringList>
|
|
#include <QVariantMap>
|
|
#include <QVector>
|
|
#include <algorithm>
|
|
#include <QTimer>
|
|
#include <QDebug>
|
|
|
|
EngineBridge *EngineBridge::s_instance = nullptr;
|
|
gd_folder_fn EngineBridge::s_folder = nullptr;
|
|
gd_open_fn EngineBridge::s_open = nullptr;
|
|
gd_cell_fn EngineBridge::s_cell = nullptr;
|
|
gd_body_fn EngineBridge::s_body = nullptr;
|
|
gd_can_hold_fn EngineBridge::s_unread = nullptr;
|
|
gd_text_fn EngineBridge::s_path = nullptr;
|
|
gd_make_folder_fn EngineBridge::s_make_folder = nullptr;
|
|
gd_set_fn EngineBridge::s_priority = nullptr;
|
|
gd_set_fn EngineBridge::s_label = nullptr;
|
|
gd_make_folder_fn EngineBridge::s_change = nullptr;
|
|
gd_can_hold_fn EngineBridge::s_forget = nullptr;
|
|
gd_read_fn EngineBridge::s_read = nullptr;
|
|
gd_id_of_fn EngineBridge::s_id_of = nullptr;
|
|
gd_move_fn EngineBridge::s_move = nullptr;
|
|
gd_commit_fn EngineBridge::s_commit = nullptr;
|
|
gd_find_start_fn EngineBridge::s_imap_start = nullptr;
|
|
gd_find_poll_fn EngineBridge::s_imap_poll = nullptr;
|
|
gd_rescan_fn EngineBridge::s_rescan = nullptr;
|
|
gd_text_fn EngineBridge::s_attachments = nullptr;
|
|
gd_sort_fn EngineBridge::s_sort = nullptr;
|
|
gd_absorb_fn EngineBridge::s_absorb = nullptr;
|
|
gd_text_fn EngineBridge::s_sender = nullptr;
|
|
gd_header_fn EngineBridge::s_header = nullptr;
|
|
gd_compose_fn EngineBridge::s_compose = nullptr;
|
|
gd_claim_fn EngineBridge::s_claim = nullptr;
|
|
gd_send_start_fn EngineBridge::s_send_start = nullptr;
|
|
gd_find_poll_fn EngineBridge::s_send_poll = nullptr;
|
|
gd_send_done_fn EngineBridge::s_send_done = nullptr;
|
|
gd_queue_sent_fn EngineBridge::s_queue_sent = nullptr;
|
|
gd_place_fn EngineBridge::s_place = nullptr;
|
|
gd_log_fn EngineBridge::s_log = nullptr;
|
|
gd_empty_fn EngineBridge::s_empty = nullptr;
|
|
gd_text_fn EngineBridge::s_plain = nullptr;
|
|
gd_text_fn EngineBridge::s_html = nullptr;
|
|
gd_find_start_fn EngineBridge::s_find_start = nullptr;
|
|
gd_find_poll_fn EngineBridge::s_find_poll = nullptr;
|
|
gd_find_cancel_fn EngineBridge::s_find_cancel = nullptr;
|
|
gd_id_named_fn EngineBridge::s_id_named = nullptr;
|
|
gd_row_of_fn EngineBridge::s_row_of = nullptr;
|
|
gd_find_start_fn EngineBridge::s_book_start = nullptr;
|
|
gd_find_poll_fn EngineBridge::s_book_poll = nullptr;
|
|
gd_place_fn EngineBridge::s_book_list = nullptr;
|
|
|
|
// Colonne del motore (enum Column di qt_shim.cpp)
|
|
enum Column { Status, Priority, Attachment, Label, Who, Date, Size, Subject, Junk };
|
|
|
|
EngineBridge::EngineBridge(QObject *parent)
|
|
: QObject(parent), m_settings(nullptr), m_checking(false),
|
|
m_attFolder(-1), m_attRow(-1)
|
|
{
|
|
// Il controllo della posta gira in una task del motore: si interroga a
|
|
// intervalli finché non ha finito.
|
|
m_poll = new QTimer(this);
|
|
m_poll->setInterval(250);
|
|
connect(m_poll, &QTimer::timeout, this, &EngineBridge::pollMail);
|
|
}
|
|
|
|
EngineBridge *EngineBridge::instance() { return s_instance; }
|
|
void EngineBridge::setInstance(EngineBridge *b) { s_instance = b; }
|
|
|
|
void EngineBridge::keepCallbacks(gd_folder_fn folder, gd_open_fn open, gd_cell_fn cell,
|
|
gd_body_fn body, gd_can_hold_fn unread,
|
|
gd_read_fn mark_read, gd_id_of_fn id_of,
|
|
gd_move_fn move, gd_commit_fn commit,
|
|
gd_find_start_fn imap_start, gd_find_poll_fn imap_poll,
|
|
gd_rescan_fn rescan, gd_text_fn attachments,
|
|
gd_sort_fn sort, gd_absorb_fn absorb,
|
|
gd_text_fn sender, gd_header_fn header,
|
|
gd_compose_fn compose, gd_claim_fn claim,
|
|
gd_send_start_fn send_start,
|
|
gd_find_poll_fn send_poll,
|
|
gd_send_done_fn send_done,
|
|
gd_queue_sent_fn queue_sent, gd_place_fn place,
|
|
gd_log_fn log, gd_empty_fn empty,
|
|
gd_text_fn plain, gd_text_fn html,
|
|
gd_find_start_fn find_start,
|
|
gd_find_poll_fn find_poll,
|
|
gd_find_cancel_fn find_cancel,
|
|
gd_id_named_fn id_named,
|
|
gd_row_of_fn row_of,
|
|
gd_find_start_fn book_start,
|
|
gd_find_poll_fn book_poll,
|
|
gd_place_fn book_list, gd_text_fn path,
|
|
gd_make_folder_fn make_folder,
|
|
gd_set_fn priority, gd_set_fn label,
|
|
gd_make_folder_fn change, gd_can_hold_fn forget)
|
|
{
|
|
s_folder = folder;
|
|
s_open = open;
|
|
s_cell = cell;
|
|
s_body = body;
|
|
s_unread = unread;
|
|
s_path = path;
|
|
s_make_folder = make_folder;
|
|
s_read = mark_read;
|
|
s_id_of = id_of;
|
|
s_move = move;
|
|
s_commit = commit;
|
|
s_imap_start = imap_start;
|
|
s_imap_poll = imap_poll;
|
|
s_rescan = rescan;
|
|
s_attachments = attachments;
|
|
s_sort = sort;
|
|
s_priority = priority;
|
|
s_label = label;
|
|
s_absorb = absorb;
|
|
s_sender = sender;
|
|
s_header = header;
|
|
s_compose = compose;
|
|
s_claim = claim;
|
|
s_send_start = send_start;
|
|
s_send_poll = send_poll;
|
|
s_send_done = send_done;
|
|
s_queue_sent = queue_sent;
|
|
s_place = place;
|
|
s_log = log;
|
|
s_empty = empty;
|
|
s_plain = plain;
|
|
s_html = html;
|
|
s_find_start = find_start;
|
|
s_find_poll = find_poll;
|
|
s_find_cancel = find_cancel;
|
|
s_id_named = id_named;
|
|
s_row_of = row_of;
|
|
s_book_start = book_start;
|
|
s_book_poll = book_poll;
|
|
s_book_list = book_list;
|
|
if (s_instance) {
|
|
emit s_instance->ready();
|
|
}
|
|
}
|
|
|
|
// "Scarica la posta": si passa al motore la riga dell'account (formato di
|
|
// Mail_Imap.Start) e si segue Poll fino a che non ha finito.
|
|
void EngineBridge::checkMail()
|
|
{
|
|
if (m_checking) return;
|
|
if (!m_settings) return;
|
|
const QString line = m_settings->imapLine();
|
|
if (line.isEmpty()) {
|
|
m_lastResult = tr("Configura l'account prima di scaricare la posta");
|
|
emit mailChecked();
|
|
return;
|
|
}
|
|
if (!s_imap_start || !s_imap_poll) {
|
|
m_lastResult = tr("Il motore non e' pronto");
|
|
emit mailChecked();
|
|
return;
|
|
}
|
|
const QByteArray bytes = line.toUtf8();
|
|
m_checking = true;
|
|
emit checkingChanged();
|
|
m_lastResult.clear();
|
|
s_imap_start(bytes.constData(), bytes.size());
|
|
m_poll->start();
|
|
}
|
|
|
|
void EngineBridge::pollMail()
|
|
{
|
|
char buf[8192];
|
|
int running = 1;
|
|
const int n = s_imap_poll ? s_imap_poll(buf, int(sizeof buf) - 1, &running) : 0;
|
|
|
|
if (n > 0) {
|
|
const QString text = QString::fromUtf8(buf, n);
|
|
const QStringList lines = text.split('\n', QString::SkipEmptyParts);
|
|
for (int i = 0; i < lines.size(); i++) {
|
|
const QString riga = lines.at(i);
|
|
// "! testo" = problema; "+ persona cartella quanti" = copiati;
|
|
// "* cartella" = cartella creata
|
|
if (riga.startsWith(QLatin1String("!"))) {
|
|
m_lastResult = riga.mid(2).trimmed();
|
|
} else if (riga.startsWith(QLatin1String("+"))) {
|
|
// persona, cartella, quanti: si mostra l'avanzamento invece di
|
|
// lasciare "controllo in corso" senza dire nulla
|
|
const QStringList campi = riga.mid(2).split('\t');
|
|
if (campi.size() >= 3)
|
|
m_lastResult = QString("%1: %2 messaggi").arg(campi.at(1), campi.at(2));
|
|
else
|
|
m_lastResult = tr("Posta scaricata");
|
|
} else if (riga.startsWith(QLatin1String("*"))) {
|
|
m_lastResult = QString("Cartella %1").arg(riga.mid(2).trimmed());
|
|
} else {
|
|
continue;
|
|
}
|
|
emit lastResultChanged();
|
|
}
|
|
}
|
|
|
|
if (!running) {
|
|
m_poll->stop();
|
|
m_checking = false;
|
|
if (m_lastResult.isEmpty()) m_lastResult = tr("Nessun messaggio nuovo");
|
|
if (s_rescan) s_rescan(); // le cartelle possono essere nuove
|
|
dropAllRows(); // e i messaggi sono cambiati
|
|
// I file appena copiati vanno presi nell'indice del motore: senza
|
|
// absorb, al controllo successivo non li vede e li riscarica da capo.
|
|
if (s_absorb && s_folder) {
|
|
char nome[512];
|
|
int depth = 0;
|
|
for (int i = 0; i < 200; i++) {
|
|
if (s_folder(i, &depth, nome, int(sizeof nome) - 1) < 0) break;
|
|
s_absorb(i);
|
|
}
|
|
}
|
|
emit checkingChanged();
|
|
emit lastResultChanged();
|
|
emit ready(); // la QML ricarica
|
|
emit mailChecked();
|
|
}
|
|
}
|
|
|
|
void EngineBridge::markRead(int folder, int row, bool read)
|
|
{
|
|
if (!s_read) return;
|
|
s_read(folder, row, read ? 1 : 0);
|
|
if (s_commit) s_commit(folder);
|
|
dropRows(folder); // il grassetto del non letto è cambiato
|
|
// Il conteggio viene dal motore, che lo ricava dai file: se il numero
|
|
// accanto alla cartella resta fermo, questa riga dice se il motore lo
|
|
// aggiorna o se è la vista a non richiederlo.
|
|
logInvio(QString("letto: cartella %1 riga %2 -> non letti %3")
|
|
.arg(folder).arg(row)
|
|
.arg(s_unread ? s_unread(folder) : -1));
|
|
// Le altre pagine (elenco, cartelle, copertina) mostrano lo stato: si
|
|
// avvisano fuori dalla chiamata, altrimenti chi legge la cella rientra
|
|
// qui dentro mentre la sta leggendo.
|
|
QTimer::singleShot(0, this, [this] { emit ready(); });
|
|
}
|
|
|
|
// Le cartelle in cui si può spostare un messaggio: tutte tranne gli account
|
|
// e quella da cui il messaggio parte.
|
|
QVariantList EngineBridge::cartellePer(int esclusa)
|
|
{
|
|
QVariantList out;
|
|
const QVariantList tutte = folders();
|
|
for (int i = 0; i < tutte.size(); i++) {
|
|
const QVariantMap m = tutte.at(i).toMap();
|
|
const int idx = m.value(QStringLiteral("folder")).toInt();
|
|
if (idx == esclusa) continue;
|
|
if (m.value(QStringLiteral("tipo")).toString() == QLatin1String("account"))
|
|
continue;
|
|
QVariantMap c;
|
|
c["folder"] = idx;
|
|
c["nome"] = m.value(QStringLiteral("nome"));
|
|
c["livello"] = m.value(QStringLiteral("livello"));
|
|
c["tipo"] = m.value(QStringLiteral("tipo"));
|
|
out.append(c);
|
|
}
|
|
return out;
|
|
}
|
|
|
|
bool EngineBridge::spostaIn(int da, int riga, int a)
|
|
{
|
|
if (!s_id_of || !s_move || da == a) return false;
|
|
const int id = s_id_of(da, riga);
|
|
if (id < 0) return false;
|
|
if (s_move(da, id, a) == 0) return false;
|
|
if (s_commit) s_commit(da);
|
|
dropRows(da); // la riga è uscita da qui
|
|
dropRows(a); // ed è entrata là
|
|
logInvio(QString("sposta: cartella %1 riga %2 -> %3").arg(da).arg(riga).arg(a));
|
|
emit ready();
|
|
return true;
|
|
}
|
|
|
|
// Creare una cartella vera (Maildir: tmp, new, cur) sotto l'account. Il
|
|
// motore dice 1 se l'ha creata, 0 se c'era già, negativo se non può.
|
|
QString EngineBridge::creaCartella(int parent, const QString &nome)
|
|
{
|
|
if (!s_make_folder) return tr("Il motore non sa creare cartelle");
|
|
const QString n = nome.trimmed();
|
|
if (n.isEmpty()) return tr("Scrivi il nome della cartella");
|
|
const QByteArray b = n.toUtf8();
|
|
const int r = s_make_folder(parent, b.constData(), b.size(), 1);
|
|
if (r < 0) return tr("Il motore non può creare una cartella lì");
|
|
if (r == 0) return tr("Esiste già una cartella con questo nome");
|
|
if (s_rescan) s_rescan();
|
|
logInvio(QString("cartella creata: %1 sotto %2").arg(n).arg(parent));
|
|
emit ready();
|
|
return QString();
|
|
}
|
|
|
|
// Ogni quanti minuti guardare la posta da soli. Si conserva nella
|
|
// configurazione dell'app; 0 vuol dire spento.
|
|
int EngineBridge::minutiControllo() const
|
|
{
|
|
QSettings s;
|
|
return s.value(QStringLiteral("posta/minuti"), 0).toInt();
|
|
}
|
|
|
|
void EngineBridge::setMinutiControllo(int minuti)
|
|
{
|
|
QSettings s;
|
|
s.setValue(QStringLiteral("posta/minuti"), qMax(0, minuti));
|
|
logInvio(QString("controllo automatico: %1 minuti").arg(qMax(0, minuti)));
|
|
}
|
|
|
|
// La Trash dell'account della cartella: il motore lavora per numeri di
|
|
// cartella, quindi si cerca la prima "Trash" che non sia un account.
|
|
static int trashIndex()
|
|
{
|
|
EngineBridge *b = EngineBridge::instance();
|
|
if (!b) return -1;
|
|
const QVariantList elenco = b->folders();
|
|
for (int i = 0; i < elenco.size(); i++) {
|
|
const QVariantMap m = elenco.at(i).toMap();
|
|
if (m.value("tipo").toString() == QLatin1String("trash"))
|
|
return m.value("folder").toInt();
|
|
}
|
|
return -1;
|
|
}
|
|
|
|
bool EngineBridge::moveToTrash(int folder, int row)
|
|
{
|
|
const int target = trashIndex();
|
|
if (!s_move || !s_id_of || target < 0 || target == folder) return false;
|
|
const int id = s_id_of(folder, row);
|
|
if (id < 0) return false;
|
|
const bool ok = s_move(folder, id, target) != 0;
|
|
if (ok) {
|
|
if (s_commit) s_commit(folder);
|
|
dropRows(folder); // la riga è uscita
|
|
dropRows(target); // ed è entrata nella Trash
|
|
}
|
|
return ok;
|
|
}
|
|
|
|
// Il motore restituisce la lunghezza del testo, non un terminatore: leggere
|
|
// il buffer fino al primo zero si porta dietro i residui del testo precedente
|
|
// ("In" che diventa "Incal"). Si legge sempre con la lunghezza.
|
|
static QString testoMotore(const char *buf, int n)
|
|
{
|
|
if (n <= 0) return QString();
|
|
return QString::fromUtf8(buf, n);
|
|
}
|
|
|
|
// L'indirizzo di chi ha scritto: il motore da' "Nome\tindirizzo".
|
|
QString EngineBridge::senderOf(int folder, int row)
|
|
{
|
|
if (!s_sender || !s_id_of) return QString();
|
|
const int id = s_id_of(folder, row);
|
|
if (id < 0) return QString();
|
|
char buf[1024];
|
|
const int n = s_sender(folder, id, buf, int(sizeof buf) - 1);
|
|
if (n <= 0) return QString();
|
|
const QString tutto = testoMotore(buf, qMin(n, int(sizeof buf) - 1));
|
|
const int tab = tutto.indexOf(QLatin1Char('\t'));
|
|
const QString indirizzo = tab >= 0 ? tutto.mid(tab + 1) : tutto;
|
|
return indirizzo.trimmed();
|
|
}
|
|
|
|
// Un header del messaggio, come lo da' il motore ("to", "cc", ...).
|
|
QString EngineBridge::headerOf(int folder, int row, const QString &name)
|
|
{
|
|
if (!s_header || !s_id_of) return QString();
|
|
const int id = s_id_of(folder, row);
|
|
if (id < 0) return QString();
|
|
char buf[4096];
|
|
const int n = s_header(folder, id, name.toUtf8().constData(), buf,
|
|
int(sizeof buf) - 1);
|
|
if (n <= 0) return QString();
|
|
return testoMotore(buf, qMin(n, int(sizeof buf) - 1)).trimmed();
|
|
}
|
|
|
|
int EngineBridge::idOf(int folder, int row)
|
|
{
|
|
if (!s_id_of) return -1;
|
|
return s_id_of(folder, row);
|
|
}
|
|
|
|
// Una cella, come stringa UTF-8 letta dal motore.
|
|
QString EngineBridge::cell(int folder, int row, int column)
|
|
{
|
|
if (!s_cell) return QString();
|
|
char buf[2048];
|
|
int n = s_cell(folder, row, column, buf, int(sizeof buf) - 1);
|
|
if (n <= 0) return QString();
|
|
if (n > int(sizeof buf) - 1) n = int(sizeof buf) - 1;
|
|
return QString::fromUtf8(buf, n);
|
|
}
|
|
|
|
// Una cartella ha messaggi? Serve solo per decidere se "Local" merita di
|
|
// comparire: nell'originale e' la posta senza server (importazioni e cartelle
|
|
// create a mano), e su un telefono che scarica da IMAP e' quasi sempre vuota.
|
|
static bool hasMessages(int folder)
|
|
{
|
|
EngineBridge *b = EngineBridge::instance();
|
|
return b && !b->messages(folder).isEmpty();
|
|
}
|
|
|
|
QVariantList EngineBridge::folders()
|
|
{
|
|
QVariantList out;
|
|
if (!s_folder) return out;
|
|
|
|
struct Entry { int index; QString nome; int depth; };
|
|
QVector<Entry> all;
|
|
char buf[512];
|
|
int depth = 0;
|
|
for (int i = 0; i < 200; i++) {
|
|
int n = s_folder(i, &depth, buf, int(sizeof buf) - 1);
|
|
if (n < 0) break;
|
|
if (n > int(sizeof buf) - 1) n = int(sizeof buf) - 1;
|
|
Entry e;
|
|
e.index = i;
|
|
e.nome = QString::fromUtf8(buf, n);
|
|
e.depth = depth;
|
|
all.append(e);
|
|
}
|
|
|
|
// "Local" e le sue cartelle si mostrano solo se qualcuna ha messaggi.
|
|
int localAt = -1;
|
|
for (int k = 0; k < all.size(); k++) {
|
|
if (all.at(k).depth == 0 && all.at(k).nome == QLatin1String("Local")) {
|
|
localAt = k;
|
|
break;
|
|
}
|
|
}
|
|
int localEnd = localAt; // ultimo indice del sottoalbero di Local
|
|
bool localHasMail = false;
|
|
if (localAt >= 0) {
|
|
for (int k = localAt + 1; k < all.size() && all.at(k).depth > 0; k++) {
|
|
localEnd = k;
|
|
if (hasMessages(all.at(k).index)) localHasMail = true;
|
|
}
|
|
}
|
|
|
|
for (int k = 0; k < all.size(); k++) {
|
|
if (localAt >= 0 && !localHasMail && k >= localAt && k <= localEnd)
|
|
continue;
|
|
const Entry &e = all.at(k);
|
|
|
|
// Il tipo serve solo a scegliere l'icona: il motore non lo dice.
|
|
// Le cartelle standard si chiamano INBOX, Sent, Junk, Trash.
|
|
QString tipo = "cartella";
|
|
if (e.depth == 0) tipo = "account";
|
|
else if (e.nome == QLatin1String("INBOX") || e.nome == QLatin1String("In")) tipo = "in";
|
|
else if (e.nome == QLatin1String("Sent") || e.nome == QLatin1String("Out")) tipo = "out";
|
|
else if (e.nome == QLatin1String("Junk")) tipo = "junk";
|
|
else if (e.nome == QLatin1String("Drafts")) tipo = "draft";
|
|
else if (e.nome == QLatin1String("Trash")) tipo = "trash";
|
|
|
|
QVariantMap m;
|
|
m["folder"] = e.index;
|
|
m["nome"] = e.nome;
|
|
m["livello"] = e.depth;
|
|
m["tipo"] = tipo;
|
|
m["nonLetti"] = s_unread ? s_unread(e.index) : 0;
|
|
out.append(m);
|
|
}
|
|
return out;
|
|
}
|
|
|
|
// La colonna Status non e' vuota quando il messaggio e' letto: e' uno spazio
|
|
// (vedi Mail_Boxes.Status_Of, che da' U per il non letto e ' ' per il resto,
|
|
// con Q/D/Z/S/R/F per gli altri casi). Confrontare con "" rendeva non letto
|
|
// qualunque messaggio.
|
|
static bool unreadMark(const QString &stato)
|
|
{
|
|
return stato.trimmed() == QLatin1String("U");
|
|
}
|
|
|
|
bool EngineBridge::isUnread(int folder, int row)
|
|
{
|
|
return unreadMark(cell(folder, row, Status));
|
|
}
|
|
|
|
QString EngineBridge::folderType(int folder)
|
|
{
|
|
const QVariantList elenco = folders();
|
|
for (int i = 0; i < elenco.size(); i++) {
|
|
const QVariantMap m = elenco.at(i).toMap();
|
|
if (m.value("folder").toInt() == folder)
|
|
return m.value("tipo").toString();
|
|
}
|
|
return QString();
|
|
}
|
|
|
|
// Una cartella per nome, chiesta direttamente al motore: folders() e' la
|
|
// vista, che nasconde le cartelle locali vuote — e la coda di invio e' una di
|
|
// quelle.
|
|
int EngineBridge::folderNamed(const QString &nome)
|
|
{
|
|
if (!s_folder) return -1;
|
|
char buf[512];
|
|
int depth = 0;
|
|
for (int i = 0; i < 500; i++) {
|
|
buf[0] = '\0';
|
|
const int n = s_folder(i, &depth, buf, int(sizeof buf) - 1);
|
|
if (n < 0) break;
|
|
if (testoMotore(buf, qMin(n, int(sizeof buf) - 1))
|
|
.compare(nome, Qt::CaseInsensitive) == 0)
|
|
return i;
|
|
}
|
|
return -1;
|
|
}
|
|
|
|
// La coda di invio. Il nome mostrato non basta ("Out" o "Sent" a seconda dei
|
|
// casi e delle lingue), quindi si chiede al motore la posizione: place da'
|
|
// "account<TAB>cartella" e la coda e' "Local<TAB>Sent".
|
|
int EngineBridge::folderOut()
|
|
{
|
|
if (!s_folder) return -1;
|
|
|
|
int perNome = -1;
|
|
int sentAltrove = -1;
|
|
char buf[512];
|
|
int depth = 0;
|
|
for (int i = 0; i < 500; i++) {
|
|
buf[0] = '\0';
|
|
const int n = s_folder(i, &depth, buf, int(sizeof buf) - 1);
|
|
if (n < 0) break;
|
|
const QString nome = testoMotore(buf, qMin(n, int(sizeof buf) - 1));
|
|
|
|
if (s_place) {
|
|
char dove[1024];
|
|
dove[0] = '\0';
|
|
const int m = s_place(i, dove, int(sizeof dove) - 1);
|
|
if (m > 0) {
|
|
const QString posto = testoMotore(dove, qMin(m, int(sizeof dove) - 1));
|
|
if (posto.compare(QLatin1String("Local\tSent"), Qt::CaseInsensitive) == 0)
|
|
return i; // la coda vera
|
|
if (posto.endsWith(QLatin1String("\tSent")))
|
|
sentAltrove = i;
|
|
}
|
|
}
|
|
if (nome.compare(QLatin1String("Out"), Qt::CaseInsensitive) == 0)
|
|
perNome = i;
|
|
}
|
|
if (perNome >= 0) return perNome; // il nome che usa la vista
|
|
return sentAltrove;
|
|
}
|
|
|
|
// Per il messaggio d'errore: cosa il motore dice di avere, senza indovinare.
|
|
QString EngineBridge::cartelleViste()
|
|
{
|
|
if (!s_folder) return QStringLiteral("(motore non pronto)");
|
|
QStringList nomi;
|
|
char buf[512];
|
|
int depth = 0;
|
|
for (int i = 0; i < 500; i++) {
|
|
buf[0] = '\0';
|
|
const int n = s_folder(i, &depth, buf, int(sizeof buf) - 1);
|
|
if (n < 0) break;
|
|
nomi << testoMotore(buf, qMin(n, int(sizeof buf) - 1));
|
|
}
|
|
return nomi.join(QStringLiteral(", "));
|
|
}
|
|
|
|
void EngineBridge::logInvio(const QString &riga)
|
|
{
|
|
if (s_log) s_log(riga.toUtf8().constData());
|
|
}
|
|
|
|
// Svuota il cestino, come fa la vista originale: la cartella "Trash" e la
|
|
// funzione Empty del motore. Restituisce quanti messaggi sono spariti.
|
|
int EngineBridge::emptyTrash(int folder)
|
|
{
|
|
if (!s_empty) return -1;
|
|
// Il cestino che si sta guardando, non "il primo chiamato Trash": con piu'
|
|
// account ce n'e' uno per account e si finiva su quello locale, vuoto.
|
|
const int cestino = folder >= 0 ? folder : folderNamed(QStringLiteral("Trash"));
|
|
if (cestino < 0) {
|
|
logInvio("ERR trash: nessun cestino");
|
|
return -1;
|
|
}
|
|
const int rimossi = s_empty(cestino);
|
|
if (s_commit) s_commit(cestino);
|
|
if (s_absorb) s_absorb(cestino);
|
|
dropRows(cestino);
|
|
if (s_rescan) s_rescan();
|
|
logInvio(QString("trash: cartella %1, %2 messaggi rimossi").arg(cestino).arg(rimossi));
|
|
QTimer::singleShot(0, this, [this] { emit ready(); });
|
|
return rimossi;
|
|
}
|
|
|
|
// Il nome di una cartella per indice, chiesto al motore.
|
|
QString EngineBridge::nomeCartella(int folder)
|
|
{
|
|
if (!s_folder || folder < 0) return QString();
|
|
char buf[512];
|
|
int depth = 0;
|
|
const int n = s_folder(folder, &depth, buf, int(sizeof buf) - 1);
|
|
if (n < 0) return QString();
|
|
return testoMotore(buf, qMin(n, int(sizeof buf) - 1));
|
|
}
|
|
|
|
// La ricerca: il motore lavora in background e riporta una riga per
|
|
// risultato ("+ <cartella> <file> <mittente> <data> <oggetto>"), "=" se il
|
|
// risultato e' stato tagliato, "!" per un problema. La query e' un foglio di
|
|
// campi separati da tab: cartelle, campo, confronto, testo, congiunzione,
|
|
// campo, confronto, testo, ricostruisci.
|
|
QString EngineBridge::avviaRicerca(const QString &testo)
|
|
{
|
|
if (!s_find_start || !s_find_poll)
|
|
return tr("La ricerca del motore non è disponibile");
|
|
const QString cercato = testo.trimmed();
|
|
if (cercato.isEmpty())
|
|
return tr("Scrivi qualcosa da cercare");
|
|
|
|
QStringList posti;
|
|
if (s_folder) {
|
|
char buf[512];
|
|
int depth = 0;
|
|
for (int i = 0; i < 500; i++) {
|
|
const int n = s_folder(i, &depth, buf, int(sizeof buf) - 1);
|
|
if (n < 0) break;
|
|
posti << QString::number(i);
|
|
}
|
|
}
|
|
if (posti.isEmpty())
|
|
return tr("Nessuna cartella dove cercare");
|
|
|
|
// Campo 0 = ovunque, confronto 0 = contiene; il secondo termine e' vuoto.
|
|
m_posti = posti.join(QLatin1Char(','));
|
|
m_ultimoCercato = cercato;
|
|
m_faseRicerca = 0;
|
|
lanciaRicerca(false);
|
|
|
|
if (!m_findTimer) {
|
|
m_findTimer = new QTimer(this);
|
|
m_findTimer->setInterval(150);
|
|
connect(m_findTimer, &QTimer::timeout, this, &EngineBridge::pollRicerca);
|
|
}
|
|
m_findTimer->start();
|
|
return QString();
|
|
}
|
|
|
|
// La query e' un foglio di nove campi separati da tab: cartelle, campo,
|
|
// confronto, testo, congiunzione, campo, confronto, testo, ricostruisci.
|
|
void EngineBridge::lanciaRicerca(bool ricostruisci)
|
|
{
|
|
if (!s_find_start) return;
|
|
QString q = m_posti;
|
|
q += QStringLiteral("\t0\t0\t");
|
|
q += m_ultimoCercato;
|
|
q += QStringLiteral("\t0\t0\t0\t\t");
|
|
q += ricostruisci ? QStringLiteral("1") : QStringLiteral("0");
|
|
|
|
m_hits.clear();
|
|
m_findErrore.clear();
|
|
const QByteArray bytes = q.toUtf8();
|
|
s_find_start(bytes.constData(), bytes.size());
|
|
logInvio(QString("find: %1 di \"%2\"")
|
|
.arg(ricostruisci ? QStringLiteral("ricostruzione indice")
|
|
: QStringLiteral("ricerca"))
|
|
.arg(m_ultimoCercato));
|
|
}
|
|
|
|
void EngineBridge::pollRicerca()
|
|
{
|
|
if (!s_find_poll) {
|
|
if (m_findTimer) m_findTimer->stop();
|
|
return;
|
|
}
|
|
QByteArray buffer(64 * 1024, '\0');
|
|
int ancora = 0;
|
|
const int letti = s_find_poll(buffer.data(), buffer.size(), &ancora);
|
|
const QList<QByteArray> righe = buffer.left(letti).split('\n');
|
|
for (int i = 0; i < righe.size(); i++) {
|
|
const QByteArray riga = righe.at(i);
|
|
if (riga.isEmpty()) continue;
|
|
if (riga.at(0) == '!') {
|
|
m_findErrore = QString::fromUtf8(riga.mid(2)).trimmed();
|
|
continue;
|
|
}
|
|
if (riga.at(0) != '+') continue; // "=" = risultati tagliati
|
|
const QList<QByteArray> celle = riga.split('\t');
|
|
if (celle.size() < 6) continue;
|
|
|
|
SearchHit h;
|
|
h.cartella = celle.at(1).toInt();
|
|
h.base = QString::fromUtf8(celle.at(2));
|
|
h.mittente = QString::fromUtf8(celle.at(3));
|
|
h.data = QString::fromUtf8(celle.at(4));
|
|
h.oggetto = QString::fromUtf8(celle.at(5));
|
|
h.dove = nomeCartella(h.cartella);
|
|
|
|
// La ricerca nomina il file: la riga nella cartella si ricava dall'id.
|
|
h.riga = -1;
|
|
if (s_id_named && s_row_of) {
|
|
const QByteArray nome = h.base.toUtf8();
|
|
const int id = s_id_named(h.cartella, nome.constData(), nome.size());
|
|
if (id >= 0) h.riga = s_row_of(h.cartella, id);
|
|
}
|
|
m_hits.append(h);
|
|
}
|
|
if (ancora) return;
|
|
|
|
m_findTimer->stop();
|
|
logInvio(QString("find: %1 risultati (fase %2)")
|
|
.arg(m_hits.size()).arg(m_faseRicerca));
|
|
|
|
// Nessun risultato: puo' essere che l'indice della cartella sia vecchio o
|
|
// non ci sia. Si ricostruisce (la ricostruzione non da' risultati) e si
|
|
// ripete la ricerca una volta sola: senza questo limite sarebbe un giro
|
|
// infinito su una parola che davvero non c'e'.
|
|
if (m_hits.isEmpty() && m_faseRicerca == 0) {
|
|
m_faseRicerca = 1;
|
|
lanciaRicerca(true);
|
|
m_findTimer->start();
|
|
return;
|
|
}
|
|
if (m_faseRicerca == 1) {
|
|
m_faseRicerca = 2;
|
|
lanciaRicerca(false);
|
|
m_findTimer->start();
|
|
return;
|
|
}
|
|
|
|
emit searchFinished(m_hits.size(), m_findErrore);
|
|
}
|
|
|
|
QVariantList EngineBridge::risultatiRicerca()
|
|
{
|
|
QVariantList out;
|
|
for (int i = 0; i < m_hits.size(); i++) {
|
|
const SearchHit &h = m_hits.at(i);
|
|
QVariantMap m;
|
|
m["cartella"] = h.cartella;
|
|
m["riga"] = h.riga;
|
|
m["dove"] = h.dove;
|
|
m["mittente"] = h.mittente;
|
|
m["data"] = h.data;
|
|
m["oggetto"] = h.oggetto;
|
|
out.append(m);
|
|
}
|
|
return out;
|
|
}
|
|
|
|
void EngineBridge::fermaRicerca()
|
|
{
|
|
if (s_find_cancel) s_find_cancel();
|
|
if (m_findTimer) m_findTimer->stop();
|
|
}
|
|
|
|
// La rubrica: il motore sincronizza il libro CardDAV e ne tiene i contatti in
|
|
// locale; qui si avvia, si segue e si leggono. La riga di configurazione la
|
|
// compone AccountSettings::bookLine.
|
|
QString EngineBridge::sincronizzaRubrica()
|
|
{
|
|
if (!s_book_start || !s_book_poll || !s_book_list)
|
|
return tr("La rubrica del motore non è disponibile");
|
|
const QString riga = m_settings ? m_settings->bookLine() : QString();
|
|
if (riga.isEmpty())
|
|
return tr("Rubrica non configurata: indirizzo del libro, utente e password");
|
|
|
|
m_contatti.clear();
|
|
m_bookErrore.clear();
|
|
const QByteArray config = riga.toUtf8();
|
|
s_book_start(config.constData(), config.size());
|
|
|
|
if (!m_bookTimer) {
|
|
m_bookTimer = new QTimer(this);
|
|
m_bookTimer->setInterval(250);
|
|
connect(m_bookTimer, &QTimer::timeout, this, &EngineBridge::pollRubrica);
|
|
}
|
|
m_bookTimer->start();
|
|
logInvio("rubrica: avviata la sincronizzazione");
|
|
return QString();
|
|
}
|
|
|
|
void EngineBridge::pollRubrica()
|
|
{
|
|
QByteArray buffer(64 * 1024, '\0');
|
|
int ancora = 0;
|
|
const int letti = s_book_poll ? s_book_poll(buffer.data(), buffer.size(), &ancora) : 0;
|
|
const QList<QByteArray> righe = buffer.left(letti).split('\n');
|
|
for (int i = 0; i < righe.size(); i++) {
|
|
const QByteArray riga = righe.at(i);
|
|
if (riga.isEmpty()) continue;
|
|
if (riga.at(0) == '!')
|
|
m_bookErrore = QString::fromUtf8(riga.mid(2)).trimmed();
|
|
}
|
|
if (ancora) return;
|
|
|
|
m_bookTimer->stop();
|
|
leggiContattiLocali();
|
|
|
|
logInvio(QString("rubrica: %1 contatti").arg(m_contatti.size()));
|
|
if (!m_bookErrore.isEmpty())
|
|
logInvio("rubrica: errore " + m_bookErrore);
|
|
emit rubricaPronta(m_contatti.size(), m_bookErrore);
|
|
}
|
|
|
|
QVariantList EngineBridge::contatti()
|
|
{
|
|
QVariantList out;
|
|
for (int i = 0; i < m_contatti.size(); i++) {
|
|
const Contact &c = m_contatti.at(i);
|
|
QVariantMap m;
|
|
m["libro"] = c.libro;
|
|
m["nome"] = c.nome;
|
|
m["indirizzo"] = c.indirizzo;
|
|
out.append(m);
|
|
}
|
|
return out;
|
|
}
|
|
|
|
// I contatti come li ha il motore su disco: libro, risorsa, nome, indirizzo.
|
|
void EngineBridge::leggiContattiLocali()
|
|
{
|
|
m_contatti.clear();
|
|
if (!s_book_list) return;
|
|
QByteArray elenco(1 << 24, '\0');
|
|
const int n = s_book_list(0, elenco.data(), elenco.size());
|
|
const QList<QByteArray> righe = elenco.left(n).split('\n');
|
|
for (int i = 0; i < righe.size(); i++) {
|
|
const QList<QByteArray> celle = righe.at(i).split('\t');
|
|
if (celle.size() < 4) continue;
|
|
Contact c;
|
|
c.libro = QString::fromUtf8(celle.at(0));
|
|
c.risorsa = QString::fromUtf8(celle.at(1));
|
|
c.nome = QString::fromUtf8(celle.at(2));
|
|
c.indirizzo = QString::fromUtf8(celle.at(3));
|
|
if (c.indirizzo.trimmed().isEmpty()) continue; // senza email non serve
|
|
m_contatti.append(c);
|
|
}
|
|
}
|
|
|
|
// Suggerimenti per il campo "A": si cerca nel nome e nell'indirizzo, senza
|
|
// badare alle maiuscole. Prima la rubrica, poi gli indirizzi gia' visti nei
|
|
// messaggi: con la rubrica quasi vuota il campo resterebbe muto, e chi si e'
|
|
// gia' scritto e' comunque un suggerimento utile.
|
|
void EngineBridge::annotaMittente(const QString &who)
|
|
{
|
|
if (who.isEmpty()) return;
|
|
// Il motore da' "Nome<TAB>indirizzo"; a volte c'e' solo l'indirizzo.
|
|
const QStringList pezzi = who.split('\t');
|
|
QString nome, indirizzo;
|
|
for (int i = 0; i < pezzi.size(); i++) {
|
|
const QString p = pezzi.at(i).trimmed();
|
|
if (p.contains('@')) { if (indirizzo.isEmpty()) indirizzo = p; }
|
|
else if (nome.isEmpty()) nome = p;
|
|
}
|
|
if (indirizzo.isEmpty()) return;
|
|
const QString chiave = indirizzo.toLower();
|
|
const QString mio = m_settings ? m_settings->mittente().trimmed() : QString();
|
|
if (!mio.isEmpty() && chiave == mio.toLower()) return; // non suggerire se stessi
|
|
if (!m_visti.contains(chiave))
|
|
m_visti.insert(chiave, nome);
|
|
}
|
|
|
|
// I mittenti delle cartelle non si conoscono finché non si apre una cartella:
|
|
// qui si legge l'In una volta sola, così il completamento funziona anche
|
|
// scrivendo subito un messaggio nuovo.
|
|
void EngineBridge::caricaVisti()
|
|
{
|
|
m_vistiCaricati = true;
|
|
const QVariantList tutte = folders();
|
|
for (int i = 0; i < tutte.size(); i++) {
|
|
const QVariantMap m = tutte.at(i).toMap();
|
|
if (m.value(QStringLiteral("tipo")).toString() != QLatin1String("in"))
|
|
continue;
|
|
messages(m.value(QStringLiteral("folder")).toInt()); // popola m_visti
|
|
break;
|
|
}
|
|
logInvio(QString("suggerisci: %1 mittenti visti").arg(m_visti.size()));
|
|
}
|
|
|
|
QVariantList EngineBridge::suggerisci(const QString &testo, int quanti)
|
|
{
|
|
QVariantList out;
|
|
const QString cerca = testo.trimmed().toLower();
|
|
if (cerca.isEmpty()) return out;
|
|
if (quanti <= 0) quanti = 6;
|
|
if (m_contatti.isEmpty()) leggiContattiLocali();
|
|
// Se in questa sessione non si e' ancora aperta una cartella, i mittenti
|
|
// visti non ci sono: si leggono ora, una volta sola.
|
|
if (m_visti.isEmpty() && !m_vistiCaricati) caricaVisti();
|
|
|
|
QSet<QString> gia; // un indirizzo non compare due volte
|
|
for (int i = 0; i < m_contatti.size() && out.size() < quanti; i++) {
|
|
const Contact &c = m_contatti.at(i);
|
|
if (!c.nome.toLower().contains(cerca)
|
|
&& !c.indirizzo.toLower().contains(cerca))
|
|
continue;
|
|
gia.insert(c.indirizzo.toLower());
|
|
QVariantMap m;
|
|
m["nome"] = c.nome;
|
|
m["indirizzo"] = c.indirizzo;
|
|
out.append(m);
|
|
}
|
|
|
|
for (QHash<QString, QString>::const_iterator it = m_visti.constBegin();
|
|
it != m_visti.constEnd() && out.size() < quanti; ++it) {
|
|
if (gia.contains(it.key())) continue;
|
|
if (!it.key().contains(cerca) && !it.value().toLower().contains(cerca))
|
|
continue;
|
|
QVariantMap m;
|
|
m["nome"] = it.value();
|
|
m["indirizzo"] = it.key();
|
|
out.append(m);
|
|
}
|
|
logInvio(QString("suggerisci \"%1\": %2 (rubrica %3, visti %4)")
|
|
.arg(cerca).arg(out.size())
|
|
.arg(m_contatti.size()).arg(m_visti.size()));
|
|
return out;
|
|
}
|
|
|
|
// I filtri stanno in un modulo che si esporta da sé (Mail_Filing), non
|
|
// nell'aggregato di gd_run: si chiamano come le altre funzioni C del motore.
|
|
extern "C" {
|
|
int gd_filing_start(const void *config, int len);
|
|
int gd_filing_poll(char *buf, int cap, int *running);
|
|
void gd_filing_cancel(void);
|
|
// Addestramento del junk: anche questo modulo si esporta da sé.
|
|
void gd_junk_train(const void *config, int len);
|
|
int gd_junk_poll(char *buf, int cap, int *running);
|
|
void gd_junk_cancel(void);
|
|
}
|
|
|
|
bool EngineBridge::filtriAttivi() const
|
|
{
|
|
QSettings s;
|
|
return s.value(QStringLiteral("filtri/attivi"), false).toBool();
|
|
}
|
|
|
|
void EngineBridge::setFiltriAttivi(bool attivi)
|
|
{
|
|
QSettings s;
|
|
s.setValue(QStringLiteral("filtri/attivi"), attivi);
|
|
logInvio(QString("filtri: %1").arg(attivi ? "attivi" : "spenti"));
|
|
}
|
|
|
|
// Due giri, come l'originale: prima il motore impara cosa c'e' nelle cartelle,
|
|
// poi gli si danno i messaggi da archiviare e lui risponde dove metterli.
|
|
QString EngineBridge::filtra(int folder)
|
|
{
|
|
if (m_filtriTimer && m_filtriTimer->isActive())
|
|
return tr("I filtri stanno già lavorando");
|
|
if (!s_folder || !s_id_of || !s_path)
|
|
return tr("Il motore non offre i filtri");
|
|
|
|
// Si archivia solo nelle cartelle normali: non negli account, non in In,
|
|
// Out, Sent, Junk e Trash (che il motore rifiuta comunque).
|
|
QString elenco;
|
|
int inbox = -1;
|
|
const QVariantList tutte = folders();
|
|
for (int i = 0; i < tutte.size(); i++) {
|
|
const QVariantMap m = tutte.at(i).toMap();
|
|
const QString tipo = m.value("tipo").toString();
|
|
const int idx = m.value("folder").toInt();
|
|
if (tipo == QLatin1String("in")) { inbox = idx; continue; }
|
|
if (tipo != QLatin1String("cartella")) continue;
|
|
elenco += QStringLiteral("F\t%1\n").arg(idx);
|
|
}
|
|
if (elenco.isEmpty())
|
|
return tr("Nessuna cartella in cui archiviare");
|
|
if (inbox < 0) inbox = folder;
|
|
|
|
// I messaggi della cartella, con il percorso del file: il motore li legge
|
|
// da lì per imparare e per decidere.
|
|
const QVariantList messaggi = messages(folder);
|
|
m_filtriArchivia.clear();
|
|
int quanti = 0;
|
|
for (int i = 0; i < messaggi.size() && quanti < 300; i++) {
|
|
const int riga = messaggi.at(i).toMap().value(QStringLiteral("riga")).toInt();
|
|
const int id = s_id_of(folder, riga);
|
|
if (id < 0) continue;
|
|
char buf[4096];
|
|
const int n = s_path(folder, id, buf, int(sizeof buf) - 1);
|
|
if (n <= 0) continue;
|
|
const QString percorso = QString::fromUtf8(buf, qMin(n, int(sizeof buf) - 1));
|
|
if (percorso.isEmpty()) continue;
|
|
m_filtriArchivia += QStringLiteral("C\t%1\t%2\t%3\n")
|
|
.arg(folder).arg(id).arg(percorso);
|
|
quanti++;
|
|
}
|
|
if (m_filtriArchivia.isEmpty())
|
|
return tr("Nessun messaggio da archiviare qui");
|
|
|
|
m_filtriImpara = QStringLiteral("A\n") + elenco
|
|
+ QStringLiteral("I\t%1\n").arg(inbox);
|
|
m_filtriSpostati = 0;
|
|
m_filtriRestano = 0;
|
|
m_filtriErrore.clear();
|
|
|
|
if (!m_filtriTimer) {
|
|
m_filtriTimer = new QTimer(this);
|
|
m_filtriTimer->setInterval(300);
|
|
connect(m_filtriTimer, &QTimer::timeout, this, &EngineBridge::pollFiltri);
|
|
}
|
|
logInvio(QString("filtri: %1 messaggi da archiviare, In %2")
|
|
.arg(quanti).arg(inbox));
|
|
avviaFiltri(true);
|
|
return QString();
|
|
}
|
|
|
|
void EngineBridge::avviaFiltri(bool apprendimento)
|
|
{
|
|
m_faseFiltri = apprendimento ? 1 : 2;
|
|
const QByteArray config =
|
|
(apprendimento ? m_filtriImpara : m_filtriArchivia).toUtf8();
|
|
gd_filing_start(config.data(), config.size());
|
|
if (m_filtriTimer) m_filtriTimer->start();
|
|
}
|
|
|
|
void EngineBridge::pollFiltri()
|
|
{
|
|
QByteArray buffer(64 * 1024, '\0');
|
|
int ancora = 0;
|
|
const int letti = gd_filing_poll(buffer.data(), buffer.size(), &ancora);
|
|
const QList<QByteArray> righe = buffer.left(letti).split('\n');
|
|
for (int i = 0; i < righe.size(); i++) {
|
|
const QByteArray riga = righe.at(i);
|
|
if (riga.isEmpty()) continue;
|
|
if (riga.at(0) == '!') {
|
|
m_filtriErrore = QString::fromUtf8(riga.mid(2)).trimmed();
|
|
continue;
|
|
}
|
|
if (riga.at(0) == '+') { // "+ quanti" imparati
|
|
m_filtriRestano = riga.mid(2).trimmed().toInt();
|
|
continue;
|
|
}
|
|
if (riga.at(0) != '=') continue; // "? folder id" = resta dov'e'
|
|
const QList<QByteArray> celle = riga.split('\t');
|
|
if (celle.size() < 4) continue;
|
|
const int da = celle.at(1).toInt();
|
|
const int id = celle.at(2).toInt();
|
|
const int a = celle.at(3).toInt();
|
|
if (s_move && s_move(da, id, a) != 0) {
|
|
m_filtriSpostati++;
|
|
dropRows(da);
|
|
dropRows(a);
|
|
}
|
|
}
|
|
if (ancora) return;
|
|
|
|
if (m_faseFiltri == 1) { avviaFiltri(false); return; }
|
|
|
|
if (m_filtriTimer) m_filtriTimer->stop();
|
|
QString esito;
|
|
if (!m_filtriErrore.isEmpty())
|
|
esito = tr("Filtri: %1").arg(m_filtriErrore);
|
|
else if (m_filtriSpostati == 0)
|
|
esito = tr("Filtri: nessun messaggio archiviato (imparati %1)")
|
|
.arg(m_filtriRestano);
|
|
else
|
|
esito = tr("Filtri: %1 messaggi archiviati").arg(m_filtriSpostati);
|
|
logInvio("filtri: " + esito);
|
|
emit filtrazione(esito);
|
|
emit ready();
|
|
}
|
|
|
|
// Il foglio di composizione, nell'unico formato che Mail_Compose.Parse
|
|
// conosce: campi "Nome: valore", riga vuota, corpo.
|
|
QString EngineBridge::foglioMessaggio(const QString &to, const QString &cc,
|
|
const QString &bcc, const QString &from,
|
|
const QString &oggetto, const QString &corpo,
|
|
const QStringList &allegati) const
|
|
{
|
|
QString foglio;
|
|
foglio += QLatin1String("From: ") + from + QLatin1Char('\n');
|
|
foglio += QLatin1String("To: ") + to.trimmed() + QLatin1Char('\n');
|
|
if (!cc.trimmed().isEmpty())
|
|
foglio += QLatin1String("Cc: ") + cc.trimmed() + QLatin1Char('\n');
|
|
if (!bcc.trimmed().isEmpty())
|
|
foglio += QLatin1String("Bcc: ") + bcc.trimmed() + QLatin1Char('\n');
|
|
// Gli allegati: percorsi separati da punto e virgola, come li legge
|
|
// Split_Paths di Mail_Compose. Un file che non si legge fa fallire la
|
|
// composizione, quindi si scartano i percorsi vuoti.
|
|
QStringList validi;
|
|
for (int i = 0; i < allegati.size(); i++) {
|
|
const QString p = allegati.at(i).trimmed();
|
|
if (!p.isEmpty()) validi << p;
|
|
}
|
|
if (!validi.isEmpty())
|
|
foglio += QLatin1String("Attached: ") + validi.join(QLatin1String("; "))
|
|
+ QLatin1Char('\n');
|
|
foglio += QLatin1String("Subject: ") + oggetto + QLatin1String("\n\n") + corpo;
|
|
return foglio;
|
|
}
|
|
|
|
// La cartella delle bozze: "Drafts" sul server; se non c'è, si ripiega su Out.
|
|
int EngineBridge::folderDrafts()
|
|
{
|
|
const QVariantList tutte = folders();
|
|
for (int i = 0; i < tutte.size(); i++) {
|
|
const QVariantMap m = tutte.at(i).toMap();
|
|
if (m.value(QStringLiteral("tipo")).toString() == QLatin1String("draft"))
|
|
return m.value(QStringLiteral("folder")).toInt();
|
|
}
|
|
return folderOut();
|
|
}
|
|
|
|
// Salvare una bozza: Queue = 0, così il messaggio non parte, e la cartella
|
|
// di destinazione è Drafts. bozzaId >= 0 sostituisce quella ripresa.
|
|
QString EngineBridge::salvaBozza(const QString &to, const QString &cc,
|
|
const QString &bcc, const QString &da,
|
|
const QString &oggetto, const QString &corpo,
|
|
const QStringList &allegati, int bozzaId)
|
|
{
|
|
if (!s_compose) return tr("Il motore non è pronto");
|
|
|
|
const int drafts = folderDrafts();
|
|
if (drafts < 0) {
|
|
const QString m = tr("Manca la cartella delle bozze");
|
|
logInvio("ERR bozza: " + m);
|
|
return m;
|
|
}
|
|
|
|
QString from = da.trimmed();
|
|
if (from.isEmpty() && m_settings) from = m_settings->mittente().trimmed();
|
|
|
|
const QString foglio = foglioMessaggio(to, cc, bcc, from, oggetto, corpo,
|
|
allegati);
|
|
const QByteArray testo = foglio.toUtf8();
|
|
const QByteArray nessunHtml;
|
|
char stato[1024];
|
|
stato[0] = '\0';
|
|
const int id = s_compose(drafts, testo.constData(), testo.size(),
|
|
nessunHtml.constData(), 0,
|
|
0 /* non in coda */, 0 /* cifra */, 0 /* firma */,
|
|
0 /* nuovo */, -1, -1, bozzaId, stato,
|
|
int(sizeof stato) - 1);
|
|
if (id < 0) {
|
|
const QString m = QString::fromUtf8(stato, qMin(-id, int(sizeof stato) - 1));
|
|
logInvio("ERR bozza: " + m);
|
|
return m;
|
|
}
|
|
dropRows(drafts);
|
|
logInvio(QString("bozza salvata: id %1 in %2").arg(id).arg(drafts));
|
|
emit ready();
|
|
return QString();
|
|
}
|
|
|
|
// Rileggere una bozza per riprenderla: i campi del foglio e gli allegati.
|
|
QVariantMap EngineBridge::bozza(int folder, int row)
|
|
{
|
|
QVariantMap m;
|
|
m["a"] = headerOf(folder, row, QStringLiteral("To"));
|
|
m["cc"] = headerOf(folder, row, QStringLiteral("Cc"));
|
|
m["bcc"] = headerOf(folder, row, QStringLiteral("Bcc"));
|
|
m["da"] = headerOf(folder, row, QStringLiteral("From"));
|
|
m["oggetto"] = headerOf(folder, row, QStringLiteral("Subject"));
|
|
m["corpo"] = body(folder, row);
|
|
// I percorsi degli allegati li scrive il motore in questo header quando
|
|
// il messaggio è una bozza (Mail_Compose.Draft_Attached).
|
|
QStringList allegati;
|
|
const QString attaccati =
|
|
headerOf(folder, row, QStringLiteral("X-Grumpydove-Attached"));
|
|
if (!attaccati.isEmpty())
|
|
allegati = attaccati.split(QRegExp(QStringLiteral("\\s*;\\s*")),
|
|
QString::SkipEmptyParts);
|
|
m["allegati"] = allegati;
|
|
return m;
|
|
}
|
|
|
|
// Ordinare per colonna: le colonne sono quelle del motore (4 mittente,
|
|
// 5 data, 6 dimensione, 7 oggetto). L'ordinamento lo fa lui, che conosce i
|
|
// minuti della data: la colonna a schermo è solo testo.
|
|
QString EngineBridge::ordina(int folder, int colonna, bool discendente)
|
|
{
|
|
if (!s_sort) return tr("Il motore non può ordinare");
|
|
m_ordine[folder] = qMakePair(colonna, discendente);
|
|
s_sort(folder, colonna, discendente ? 1 : 0);
|
|
dropRows(folder);
|
|
logInvio(QString("ordina: cartella %1 colonna %2 %3")
|
|
.arg(folder).arg(colonna).arg(discendente ? "discendente" : "crescente"));
|
|
emit ready();
|
|
return QString();
|
|
}
|
|
|
|
// Rileggere una cartella dal disco, senza passare dal server.
|
|
void EngineBridge::risincronizza(int folder)
|
|
{
|
|
if (s_rescan) s_rescan();
|
|
dropRows(folder);
|
|
if (s_open) {
|
|
long totale = 0;
|
|
s_open(folder, &totale);
|
|
}
|
|
logInvio(QString("risincronizza: cartella %1").arg(folder));
|
|
emit ready();
|
|
}
|
|
|
|
// Priorità 1 (massima) .. 5 (minima); 3 toglie l'indicazione.
|
|
void EngineBridge::impostaPriorita(int folder, int row, int valore)
|
|
{
|
|
if (!s_priority) return;
|
|
s_priority(folder, row, valore);
|
|
dropRows(folder);
|
|
emit ready();
|
|
}
|
|
|
|
// Etichette 0 .. 7; 0 toglie quella presente.
|
|
void EngineBridge::impostaEtichetta(int folder, int row, int valore)
|
|
{
|
|
if (!s_label) return;
|
|
s_label(folder, row, valore);
|
|
dropRows(folder);
|
|
emit ready();
|
|
}
|
|
|
|
// "Questo è junk" / "non è junk". Il motore non conosce un contrassegno per
|
|
// singolo messaggio: si sposta nella cartella giusta e si insegna al filtro
|
|
// (S = quella cartella è spam, H = i letti dell'In sono ham).
|
|
QString EngineBridge::segnalaJunk(int folder, int row, bool junk)
|
|
{
|
|
const int id = s_id_of ? s_id_of(folder, row) : -1;
|
|
if (id < 0) return tr("Messaggio non trovato");
|
|
|
|
int destinazione = -1;
|
|
const QVariantList tutte = folders();
|
|
for (int i = 0; i < tutte.size(); i++) {
|
|
const QVariantMap m = tutte.at(i).toMap();
|
|
const QString tipo = m.value(QStringLiteral("tipo")).toString();
|
|
if (junk && tipo == QLatin1String("junk"))
|
|
destinazione = m.value(QStringLiteral("folder")).toInt();
|
|
if (!junk && tipo == QLatin1String("in") && destinazione < 0)
|
|
destinazione = m.value(QStringLiteral("folder")).toInt();
|
|
}
|
|
if (destinazione < 0)
|
|
return junk ? tr("Non c'è una cartella Junk") : tr("Non c'è l'In");
|
|
|
|
if (s_move && s_move(folder, id, destinazione) != 0) {
|
|
if (s_commit) s_commit(folder);
|
|
dropRows(folder);
|
|
dropRows(destinazione);
|
|
}
|
|
addestraJunk();
|
|
emit ready();
|
|
return QString();
|
|
}
|
|
|
|
// Rinominare una cartella: Change_Folder con Length > 0 e Target -1.
|
|
QString EngineBridge::rinominaCartella(int folder, const QString &nome)
|
|
{
|
|
if (!s_change) return tr("Il motore non sa rinominare le cartelle");
|
|
const QString n = nome.trimmed();
|
|
if (n.isEmpty()) return tr("Scrivi il nome nuovo");
|
|
const QByteArray b = n.toUtf8();
|
|
const int r = s_change(folder, b.constData(), b.size(), -1);
|
|
if (r < 0) return tr("Non si può rinominare questa cartella");
|
|
if (r == 0) return tr("C'è già una cartella con questo nome");
|
|
if (s_forget) s_forget(folder);
|
|
if (s_rescan) s_rescan();
|
|
logInvio(QString("cartella %1 rinominata in %2").arg(folder).arg(n));
|
|
emit ready();
|
|
return QString();
|
|
}
|
|
|
|
// Eliminare una cartella: Change_Folder con Length 0 e Target -1 la toglie
|
|
// con quello che contiene. Il motore rifiuta le cartelle di servizio.
|
|
QString EngineBridge::eliminaCartella(int folder)
|
|
{
|
|
if (!s_change) return tr("Il motore non sa eliminare le cartelle");
|
|
const int r = s_change(folder, QByteArray().constData(), 0, -1);
|
|
if (r < 0) return tr("Non si può eliminare questa cartella");
|
|
if (s_forget) s_forget(folder);
|
|
if (s_rescan) s_rescan();
|
|
logInvio(QString("cartella %1 eliminata").arg(folder));
|
|
emit ready();
|
|
return QString();
|
|
}
|
|
|
|
// Il file del messaggio: serve ad allegarlo (inoltro come allegato).
|
|
QString EngineBridge::percorsoMessaggio(int folder, int row)
|
|
{
|
|
if (!s_path || !s_id_of) return QString();
|
|
const int id = s_id_of(folder, row);
|
|
if (id < 0) return QString();
|
|
char buf[4096];
|
|
const int n = s_path(folder, id, buf, int(sizeof buf) - 1);
|
|
if (n <= 0) return QString();
|
|
return QString::fromUtf8(buf, qMin(n, int(sizeof buf) - 1));
|
|
}
|
|
|
|
// Redirect: non è un inoltro, è la ricomposizione dell'originale con gli
|
|
// header Resent-*, e la fa il motore (Kind = 3). Il giro dopo il compose è
|
|
// lo stesso dell'invio normale.
|
|
QString EngineBridge::redirect(int folder, int row, const QString &a,
|
|
const QString &da)
|
|
{
|
|
if (!s_compose || !s_claim || !s_send_start || !s_send_poll)
|
|
return tr("Il motore non è pronto");
|
|
const int id = s_id_of ? s_id_of(folder, row) : -1;
|
|
if (id < 0) return tr("Messaggio non trovato");
|
|
if (a.trimmed().isEmpty()) return tr("Manca il destinatario");
|
|
|
|
const int out = folderOut();
|
|
if (out < 0) return tr("Manca la cartella di uscita");
|
|
const QString config = m_settings ? m_settings->smtpLine() : QString();
|
|
if (config.isEmpty()) return tr("SMTP non configurato: controlla l'account");
|
|
|
|
QString from = da.trimmed();
|
|
if (from.isEmpty() && m_settings) from = m_settings->mittente().trimmed();
|
|
if (from.indexOf(QLatin1Char('@')) < 1)
|
|
return tr("Manca l'indirizzo del mittente");
|
|
|
|
// Per il redirect il corpo non conta: il motore usa l'originale.
|
|
QString foglio;
|
|
foglio += QLatin1String("From: ") + from + QLatin1Char('\n');
|
|
foglio += QLatin1String("To: ") + a.trimmed() + QLatin1String("\nSubject: \n\n");
|
|
|
|
const QByteArray testo = foglio.toUtf8();
|
|
const QByteArray nessunHtml;
|
|
char stato[1024];
|
|
stato[0] = '\0';
|
|
const int salvato = s_compose(out, testo.constData(), testo.size(),
|
|
nessunHtml.constData(), 0,
|
|
1 /* in coda */, 0, 0,
|
|
3 /* redirect */, folder, id, -1,
|
|
stato, int(sizeof stato) - 1);
|
|
if (salvato < 0) {
|
|
const QString m = QString::fromUtf8(stato).trimmed();
|
|
logInvio("ERR redirect: " + m);
|
|
return m.isEmpty() ? tr("Il motore ha rifiutato il redirect") : m;
|
|
}
|
|
|
|
QByteArray coda(1 << 20, '\0');
|
|
const int usati = s_claim(out, coda.data(), coda.size());
|
|
if (usati <= 0) return tr("Niente in coda da mandare");
|
|
coda.truncate(usati);
|
|
|
|
QString persona = m_settings->persona().isEmpty() ? m_settings->user()
|
|
: m_settings->persona();
|
|
persona.replace(QRegularExpression(QStringLiteral("[^A-Za-z0-9._-]")),
|
|
QStringLiteral("-"));
|
|
m_sendFolder = out;
|
|
m_sendOk = 0;
|
|
m_sendKo = 0;
|
|
m_sendEsito.clear();
|
|
m_sendPersona = persona;
|
|
if (!m_sendTimer) {
|
|
m_sendTimer = new QTimer(this);
|
|
m_sendTimer->setInterval(200);
|
|
connect(m_sendTimer, &QTimer::timeout, this, &EngineBridge::pollSend);
|
|
}
|
|
const QByteArray cfg = config.toUtf8();
|
|
s_send_start(cfg.constData(), cfg.size(), coda.constData(), coda.size());
|
|
m_sendTimer->start();
|
|
logInvio(QString("redirect: cartella %1 riga %2 -> %3").arg(folder).arg(row).arg(a));
|
|
return QString();
|
|
}
|
|
|
|
// Spostare più messaggi in una volta. Gli id si leggono tutti prima: dopo il
|
|
// primo spostamento le righe non sono più quelle, e inseguirle porterebbe a
|
|
// muovere i messaggi sbagliati.
|
|
int EngineBridge::spostaMolti(int da, const QVariantList &righe, int a)
|
|
{
|
|
if (!s_id_of || !s_move || da == a) return 0;
|
|
QVector<int> ids;
|
|
for (int i = 0; i < righe.size(); i++) {
|
|
const int id = s_id_of(da, righe.at(i).toInt());
|
|
if (id >= 0) ids.append(id);
|
|
}
|
|
int fatti = 0;
|
|
for (int i = 0; i < ids.size(); i++)
|
|
if (s_move(da, ids.at(i), a) != 0) fatti++;
|
|
if (s_commit) s_commit(da);
|
|
dropRows(da);
|
|
dropRows(a);
|
|
logInvio(QString("sposta molti: %1 di %2 nella cartella %3")
|
|
.arg(fatti).arg(righe.size()).arg(a));
|
|
emit ready();
|
|
return fatti;
|
|
}
|
|
|
|
int EngineBridge::cestinaMolti(int da, const QVariantList &righe)
|
|
{
|
|
const int trash = trashIndex();
|
|
if (trash < 0) return 0;
|
|
return spostaMolti(da, righe, trash);
|
|
}
|
|
|
|
// Letto / non letto su più messaggi: si va dal fondo verso l'alto, così gli
|
|
// indici delle righe ancora da trattare non cambiano.
|
|
int EngineBridge::lettoMolti(int folder, const QVariantList &righe, bool letto)
|
|
{
|
|
if (!s_read) return 0;
|
|
QVector<int> ordinate;
|
|
for (int i = 0; i < righe.size(); i++) ordinate.append(righe.at(i).toInt());
|
|
std::sort(ordinate.begin(), ordinate.end(), std::greater<int>());
|
|
int fatti = 0;
|
|
for (int i = 0; i < ordinate.size(); i++) {
|
|
s_read(folder, ordinate.at(i), letto ? 1 : 0);
|
|
fatti++;
|
|
}
|
|
if (s_commit) s_commit(folder);
|
|
dropRows(folder);
|
|
emit ready();
|
|
return fatti;
|
|
}
|
|
|
|
// Addestramento del junk: una riga per cartella, come vuole Mail_Junk.Train.
|
|
void EngineBridge::addestraJunk()
|
|
{
|
|
int junk = -1, in = -1;
|
|
const QVariantList tutte = folders();
|
|
for (int i = 0; i < tutte.size(); i++) {
|
|
const QVariantMap m = tutte.at(i).toMap();
|
|
const QString tipo = m.value(QStringLiteral("tipo")).toString();
|
|
if (tipo == QLatin1String("junk")) junk = m.value(QStringLiteral("folder")).toInt();
|
|
if (tipo == QLatin1String("in")) in = m.value(QStringLiteral("folder")).toInt();
|
|
}
|
|
if (junk < 0 || in < 0) {
|
|
logInvio("junk: manca la cartella Junk o l'In");
|
|
return;
|
|
}
|
|
|
|
const QString config = QStringLiteral("S\t%1\nH\t%2\n").arg(junk).arg(in);
|
|
const QByteArray b = config.toUtf8();
|
|
m_junkImparati = 0;
|
|
m_junkErrore.clear();
|
|
gd_junk_train(b.constData(), b.size());
|
|
|
|
if (!m_junkTimer) {
|
|
m_junkTimer = new QTimer(this);
|
|
m_junkTimer->setInterval(250);
|
|
connect(m_junkTimer, &QTimer::timeout, this, &EngineBridge::pollJunk);
|
|
}
|
|
m_junkTimer->start();
|
|
}
|
|
|
|
void EngineBridge::pollJunk()
|
|
{
|
|
QByteArray buffer(64 * 1024, '\0');
|
|
int ancora = 0;
|
|
const int letti = gd_junk_poll(buffer.data(), buffer.size(), &ancora);
|
|
const QList<QByteArray> righe = buffer.left(letti).split('\n');
|
|
for (int i = 0; i < righe.size(); i++) {
|
|
const QByteArray riga = righe.at(i);
|
|
if (riga.isEmpty()) continue;
|
|
if (riga.at(0) == '!') {
|
|
m_junkErrore = QString::fromUtf8(riga.mid(2)).trimmed();
|
|
continue;
|
|
}
|
|
if (riga.at(0) == '+') // "+ spam ham"
|
|
m_junkImparati = riga.mid(2).trimmed().toInt();
|
|
}
|
|
if (ancora) return;
|
|
|
|
if (m_junkTimer) m_junkTimer->stop();
|
|
if (!m_junkErrore.isEmpty())
|
|
logInvio("junk: " + m_junkErrore);
|
|
else
|
|
logInvio(QString("junk: %1 messaggi imparati").arg(m_junkImparati));
|
|
}
|
|
|
|
// Il giro dell'invio, come nell'originale: compose scrive il messaggio in Out
|
|
// con il flag di coda, claim estrae quelli da mandare, send_start parla con il
|
|
// server SMTP e send_poll riporta un messaggio per volta.
|
|
QString EngineBridge::sendMessage(const QString &to, const QString &cc,
|
|
const QString &bcc, const QString &da,
|
|
const QString &oggetto, const QString &corpo,
|
|
const QStringList &allegati, const QString &html)
|
|
{
|
|
if (!s_compose || !s_claim || !s_send_start || !s_send_poll) {
|
|
const QString m = tr("Il motore non è pronto");
|
|
logInvio("ERR send: " + m);
|
|
return m;
|
|
}
|
|
|
|
const int out = folderOut();
|
|
if (out < 0) {
|
|
const QString m = tr("Manca la cartella di uscita. Il motore vede: %1")
|
|
.arg(cartelleViste());
|
|
logInvio("ERR send: " + m);
|
|
return m;
|
|
}
|
|
|
|
const QString config = m_settings ? m_settings->smtpLine() : QString();
|
|
if (config.isEmpty()) {
|
|
const QString m = tr("SMTP non configurato: controlla l'account");
|
|
logInvio("ERR send: " + m);
|
|
return m;
|
|
}
|
|
|
|
if (to.trimmed().isEmpty()) {
|
|
const QString m = tr("Manca il destinatario");
|
|
logInvio("ERR send: " + m);
|
|
return m;
|
|
}
|
|
|
|
// Il From: senza, il messaggio parte senza mittente e il motore non
|
|
// trova nemmeno la personalità a cui appartiene. Arriva dalla pagina di
|
|
// composizione, che lo mostra: cosi' non dipende dal fatto che il campo
|
|
// in Account sia stato salvato.
|
|
QString from = da.trimmed();
|
|
if (from.isEmpty() && m_settings)
|
|
from = m_settings->mittente().trimmed();
|
|
if (from.isEmpty() && m_settings && m_settings->persona().contains(QLatin1Char('@')))
|
|
from = m_settings->persona().trimmed();
|
|
if (from.isEmpty()) {
|
|
const QString m = tr("Manca l'indirizzo del mittente: scrivilo nel campo «Da»");
|
|
logInvio("ERR send: " + m);
|
|
return m;
|
|
}
|
|
if (from.indexOf(QLatin1Char('@')) < 1) {
|
|
const QString m = tr("«%1» non è un indirizzo: manca la parte dopo la @").arg(from);
|
|
logInvio("ERR send: " + m);
|
|
return m;
|
|
}
|
|
|
|
// Se l'hai scritto qui, vale anche per le prossime volte.
|
|
if (m_settings && m_settings->mittente().compare(from, Qt::CaseInsensitive) != 0) {
|
|
m_settings->setMittente(from);
|
|
m_settings->save();
|
|
}
|
|
|
|
// Il foglio che il motore sa leggere: campi "Nome: valore", riga vuota,
|
|
// poi il corpo (Mail_Compose.Parse).
|
|
const QString foglio = foglioMessaggio(to, cc, bcc, from, oggetto, corpo,
|
|
allegati);
|
|
|
|
const QByteArray testo = foglio.toUtf8();
|
|
// La parte HTML è facoltativa: se c'è, il motore fa un
|
|
// multipart/alternative (testo + HTML), se non c'è resta testo semplice.
|
|
const QByteArray parteHtml = html.toUtf8();
|
|
char stato[1024];
|
|
stato[0] = '\0';
|
|
const int salvato = s_compose(out, testo.constData(), testo.size(),
|
|
parteHtml.constData(), parteHtml.size(),
|
|
1 /* in coda */, 0 /* cifra */, 0 /* firma */,
|
|
0 /* nessun originale */, -1, -1, -1,
|
|
stato, int(sizeof stato) - 1);
|
|
if (salvato < 0) {
|
|
const QString motivo = QString::fromUtf8(stato).trimmed();
|
|
const QString m = motivo.isEmpty() ? tr("Il motore ha rifiutato il messaggio")
|
|
: motivo;
|
|
logInvio("ERR send: compose: " + m);
|
|
return m;
|
|
}
|
|
|
|
QByteArray coda(1 << 20, '\0');
|
|
const int usati = s_claim(out, coda.data(), coda.size());
|
|
if (usati <= 0) {
|
|
const QString m = tr("Niente in coda da mandare");
|
|
logInvio("ERR send: " + m);
|
|
return m;
|
|
}
|
|
coda.truncate(usati);
|
|
logInvio(QString("send: coda %1, %2 byte, da %3, a %4")
|
|
.arg(out).arg(usati).arg(from).arg(to.trimmed()));
|
|
|
|
// Il nome della personalità serve alla copia in Sent sul server.
|
|
QString persona = m_settings->persona().isEmpty() ? m_settings->user()
|
|
: m_settings->persona();
|
|
persona.replace(QRegularExpression(QStringLiteral("[^A-Za-z0-9._-]")),
|
|
QStringLiteral("-"));
|
|
|
|
m_sendFolder = out;
|
|
m_sendOk = 0;
|
|
m_sendKo = 0;
|
|
m_sendEsito.clear();
|
|
m_sendPersona = persona;
|
|
|
|
if (!m_sendTimer) {
|
|
m_sendTimer = new QTimer(this);
|
|
m_sendTimer->setInterval(200);
|
|
connect(m_sendTimer, &QTimer::timeout, this, &EngineBridge::pollSend);
|
|
}
|
|
const QByteArray cfg = config.toUtf8();
|
|
s_send_start(cfg.constData(), cfg.size(), coda.constData(), coda.size());
|
|
m_sendTimer->start();
|
|
return QString();
|
|
}
|
|
|
|
void EngineBridge::pollSend()
|
|
{
|
|
if (!s_send_poll) {
|
|
if (m_sendTimer) m_sendTimer->stop();
|
|
return;
|
|
}
|
|
|
|
QByteArray buffer(64 * 1024, '\0');
|
|
int ancora = 0;
|
|
const int letti = s_send_poll(buffer.data(), buffer.size(), &ancora);
|
|
const QList<QByteArray> righe = buffer.left(letti).split('\n');
|
|
for (int i = 0; i < righe.size(); i++) {
|
|
const QByteArray riga = righe.at(i);
|
|
if (riga.isEmpty()) continue;
|
|
if (riga.at(0) == '!') {
|
|
m_sendEsito = QString::fromUtf8(riga.mid(2)).trimmed();
|
|
continue;
|
|
}
|
|
const QList<QByteArray> celle = riga.split('\t');
|
|
if (celle.size() < 2) continue;
|
|
const int id = celle.at(1).toInt();
|
|
const bool inviato = riga.at(0) == '+';
|
|
if (inviato) {
|
|
++m_sendOk;
|
|
// La copia che resta sul server: la mette lui nel Sent della
|
|
// personalità, se la conosce.
|
|
if (s_queue_sent && !m_sendPersona.isEmpty()) {
|
|
const QByteArray p = m_sendPersona.toUtf8();
|
|
s_queue_sent(m_sendFolder, id, p.constData(), p.size());
|
|
}
|
|
} else {
|
|
++m_sendKo;
|
|
m_sendEsito = celle.size() > 2 ? QString::fromUtf8(celle.at(2)).trimmed()
|
|
: tr("invio non riuscito");
|
|
}
|
|
if (s_send_done) s_send_done(m_sendFolder, id, inviato ? 1 : 0);
|
|
}
|
|
|
|
if (ancora) return;
|
|
|
|
m_sendTimer->stop();
|
|
if (s_absorb) s_absorb(m_sendFolder);
|
|
dropAllRows(); // Out e Sent sono cambiate
|
|
if (s_rescan) s_rescan();
|
|
|
|
// La copia sul server (l'append di queue_sent) parte col controllo posta:
|
|
// l'originale lo fa subito dopo l'invio, altrimenti la posta inviata resta
|
|
// solo nella coda locale.
|
|
if (m_sendOk > 0 && m_settings && m_settings->configured()) {
|
|
logInvio("send: avvio il controllo per portare la copia sul server");
|
|
QTimer::singleShot(400, this, [this] { checkMail(); });
|
|
}
|
|
|
|
emit sendFinished(m_sendOk, m_sendKo, m_sendEsito);
|
|
QTimer::singleShot(0, this, [this] { emit ready(); });
|
|
}
|
|
|
|
// Legge una cartella dal motore una volta sola e la tiene: una chiamata per
|
|
// campo per riga, quindi rileggerla a ogni apertura era il costo vero.
|
|
void EngineBridge::buildRows(int folder)
|
|
{
|
|
QVector<Row> rows;
|
|
m_rows[folder] = rows; // svuota la voce precedente
|
|
m_rowsValid.insert(folder);
|
|
if (!s_open || !s_cell) return;
|
|
|
|
long total_k = 0;
|
|
if (s_open(folder, &total_k) == 0) return;
|
|
|
|
// Il numero di messaggi lo dice s_open: senza questo limite si chiede la
|
|
// riga successiva all'ultima, che nel motore non esiste, e Ada solleva
|
|
// un CONSTRAINT_ERROR (mail_boxes.adb, B.Order (Row + 1)) a ogni lettura.
|
|
const int quante = int(qBound<long>(0, total_k, 2000));
|
|
if (quante == 0) return;
|
|
|
|
// Dal più nuovo al più vecchio, salvo che l'utente abbia scelto un'altra
|
|
// colonna: l'ordinamento lo fa il motore (conosce i minuti della data, la
|
|
// colonna a schermo è solo testo).
|
|
if (s_sort) {
|
|
const QPair<int, bool> scelto = m_ordine.value(folder, qMakePair(int(Date), true));
|
|
s_sort(folder, scelto.first, scelto.second ? 1 : 0);
|
|
}
|
|
|
|
for (int row = 0; row < quante; row++) {
|
|
const QString who = cell(folder, row, Who);
|
|
const QString subject = cell(folder, row, Subject);
|
|
if (who.isEmpty() && subject.isEmpty()) break; // riga senza niente da mostrare
|
|
|
|
Row r;
|
|
r.riga = row;
|
|
r.mittente = who;
|
|
annotaMittente(who);
|
|
r.oggetto = subject;
|
|
r.data = cell(folder, row, Date);
|
|
r.dimensione = cell(folder, row, Size);
|
|
r.nonLetto = unreadMark(cell(folder, row, Status));
|
|
r.allegato = !cell(folder, row, Attachment).isEmpty();
|
|
r.junk = !cell(folder, row, Junk).isEmpty();
|
|
rows.append(r);
|
|
}
|
|
m_rows[folder] = rows;
|
|
}
|
|
|
|
QVariantList EngineBridge::messages(int folder)
|
|
{
|
|
if (!m_rowsValid.contains(folder)) buildRows(folder);
|
|
|
|
QVariantList out;
|
|
const QVector<Row> &rows = m_rows[folder];
|
|
out.reserve(rows.size());
|
|
for (int i = 0; i < rows.size(); i++) {
|
|
const Row &r = rows.at(i);
|
|
QVariantMap m;
|
|
m["riga"] = r.riga;
|
|
m["mittente"] = r.mittente;
|
|
m["oggetto"] = r.oggetto;
|
|
m["data"] = r.data;
|
|
m["dimensione"] = r.dimensione;
|
|
m["nonLetto"] = r.nonLetto;
|
|
m["allegato"] = r.allegato;
|
|
m["junk"] = r.junk;
|
|
out.append(m);
|
|
}
|
|
return out;
|
|
}
|
|
|
|
// La parte HTML del messaggio, così come l'ha scritta il mittente: la pagina
|
|
// la ripulisce e la disegna (qml/js/htmlpulito.js). Vuota se il messaggio non
|
|
// ha una parte HTML.
|
|
QString EngineBridge::corpoHtml(int folder, int row)
|
|
{
|
|
if (!s_html || !s_id_of) return QString();
|
|
const int id = s_id_of(folder, row);
|
|
if (id < 0) return QString();
|
|
QByteArray buf(1 << 20, '\0'); // 1 MiB: oltre, non vale la pena disegnarlo
|
|
const int n = s_html(folder, id, buf.data(), buf.size() - 1);
|
|
if (n <= 0) return QString();
|
|
return QString::fromUtf8(buf.constData(), qMin(n, buf.size() - 1));
|
|
}
|
|
|
|
QString EngineBridge::body(int folder, int row)
|
|
{
|
|
char buf[65536];
|
|
|
|
// Il testo che il motore prepara per la lettura. Se il messaggio e' solo
|
|
// HTML quel testo puo' mancare: allora la parte di testo del MIME e, in
|
|
// ultima istanza, l'HTML grezzo (che la pagina riduce a testo, vedi
|
|
// qml/js/htmltext.js).
|
|
if (s_body) {
|
|
const int n = s_body(folder, row, buf, int(sizeof buf) - 1);
|
|
if (n > 0) return QString::fromUtf8(buf, qMin(n, int(sizeof buf) - 1));
|
|
}
|
|
if (!s_id_of) return QString();
|
|
const int id = s_id_of(folder, row);
|
|
if (id < 0) return QString();
|
|
|
|
if (s_plain) {
|
|
const int n = s_plain(folder, id, buf, int(sizeof buf) - 1);
|
|
if (n > 0) return QString::fromUtf8(buf, qMin(n, int(sizeof buf) - 1));
|
|
}
|
|
if (s_html) {
|
|
const int n = s_html(folder, id, buf, int(sizeof buf) - 1);
|
|
if (n > 0) return QString::fromUtf8(buf, qMin(n, int(sizeof buf) - 1));
|
|
}
|
|
return QString();
|
|
}
|
|
|
|
// Gli allegati del messaggio, come li dà il motore: per ognuno nome (UTF-8),
|
|
// NUL, la lunghezza, NUL, i byte. Si leggono una volta sola e si tengono,
|
|
// perché ogni chiamata li ricostruisce da capo (fino a 80 MB).
|
|
QVariantList EngineBridge::attachments(int folder, int row)
|
|
{
|
|
QVariantList out;
|
|
if (!s_attachments || !s_id_of) return out;
|
|
const int id = s_id_of(folder, row);
|
|
if (id < 0) return out;
|
|
|
|
QByteArray blob(80 << 20, Qt::Uninitialized);
|
|
const int n = s_attachments(folder, id, blob.data(), blob.size());
|
|
if (n <= 0) return out;
|
|
blob.truncate(n);
|
|
|
|
m_attBytes.clear();
|
|
m_attNames.clear();
|
|
m_attFolder = folder;
|
|
m_attRow = row;
|
|
|
|
int at = 0;
|
|
while (at < blob.size()) {
|
|
const int a = blob.indexOf('\0', at);
|
|
if (a < 0) break;
|
|
const int b = blob.indexOf('\0', a + 1);
|
|
if (b < 0) break;
|
|
bool ok = false;
|
|
const int length = blob.mid(a + 1, b - a - 1).toInt(&ok);
|
|
if (!ok || length < 0 || b + 1 + length > blob.size()) break;
|
|
|
|
const QString nome = QString::fromUtf8(blob.mid(at, a - at));
|
|
const QByteArray bytes = blob.mid(b + 1, length);
|
|
m_attNames.append(nome);
|
|
m_attBytes.append(bytes);
|
|
|
|
QVariantMap m;
|
|
m["nome"] = nome;
|
|
m["dimensione"] = bytes.size();
|
|
m["indice"] = out.size();
|
|
out.append(m);
|
|
at = b + 1 + length;
|
|
}
|
|
return out;
|
|
}
|
|
|
|
// Salva un allegato in Download e restituisce il percorso ("" se non riesce).
|
|
QString EngineBridge::saveAttachment(int folder, int row, int index)
|
|
{
|
|
if (folder != m_attFolder || row != m_attRow)
|
|
attachments(folder, row);
|
|
if (index < 0 || index >= m_attBytes.size()) return QString();
|
|
|
|
QString dir = QStandardPaths::writableLocation(QStandardPaths::DownloadLocation);
|
|
if (dir.isEmpty()) dir = QDir::homePath() + QStringLiteral("/Downloads");
|
|
QDir().mkpath(dir);
|
|
|
|
// il nome arriva dal mittente: si tiene solo l'ultimo pezzo, senza percorsi
|
|
QString nome = QFileInfo(m_attNames.at(index)).fileName();
|
|
if (nome.isEmpty()) nome = QStringLiteral("allegato-%1").arg(index + 1);
|
|
QString path = dir + "/" + nome;
|
|
const QFileInfo fi(nome);
|
|
for (int k = 1; QFile::exists(path) && k < 1000; k++) {
|
|
path = fi.suffix().isEmpty()
|
|
? QString("%1/%2 (%3)").arg(dir, nome, QString::number(k))
|
|
: QString("%1/%2 (%3).%4").arg(dir, fi.completeBaseName(),
|
|
QString::number(k), fi.suffix());
|
|
}
|
|
|
|
QSaveFile f(path);
|
|
if (!f.open(QIODevice::WriteOnly)) return QString();
|
|
const QByteArray &bytes = m_attBytes.at(index);
|
|
if (f.write(bytes) != bytes.size()) { f.cancelWriting(); return QString(); }
|
|
if (!f.commit()) return QString();
|
|
return path;
|
|
}
|
|
|
|
int EngineBridge::totalUnread()
|
|
{
|
|
if (!s_folder || !s_unread) return 0;
|
|
char buf[512];
|
|
int depth = 0;
|
|
int total = 0;
|
|
for (int i = 0; i < 200; i++) {
|
|
int n = s_folder(i, &depth, buf, int(sizeof buf) - 1);
|
|
if (n < 0) break;
|
|
if (depth == 0) total += s_unread(i); // gli account sommano già le cartelle
|
|
}
|
|
return total;
|
|
}
|