place da' 'account<TAB>cartella': la coda e' Local<TAB>Sent. Cercarla per nome mostrato falliva. Se non si trova, l'errore elenca le cartelle viste.
722 lines
26 KiB
C++
722 lines
26 KiB
C++
#include "enginebridge.h"
|
|
#include "accountsettings.h"
|
|
|
|
#include <QCoreApplication>
|
|
#include <QDir>
|
|
#include <QRegularExpression>
|
|
#include <QFile>
|
|
#include <QFileInfo>
|
|
#include <QHash>
|
|
#include <QSaveFile>
|
|
#include <QSet>
|
|
#include <QStandardPaths>
|
|
#include <QStringList>
|
|
#include <QVariantMap>
|
|
#include <QVector>
|
|
#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_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;
|
|
|
|
// 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)
|
|
{
|
|
s_folder = folder;
|
|
s_open = open;
|
|
s_cell = cell;
|
|
s_body = body;
|
|
s_unread = unread;
|
|
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_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;
|
|
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
|
|
// 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(); });
|
|
}
|
|
|
|
// 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;
|
|
}
|
|
|
|
// 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();
|
|
buf[qMin(n, int(sizeof buf) - 1)] = '\0';
|
|
const QString tutto = QString::fromUtf8(buf);
|
|
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();
|
|
buf[qMin(n, int(sizeof buf) - 1)] = '\0';
|
|
return QString::fromUtf8(buf).trimmed();
|
|
}
|
|
|
|
// 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("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';
|
|
if (s_folder(i, &depth, buf, int(sizeof buf) - 1) < 0) break;
|
|
buf[sizeof buf - 1] = '\0';
|
|
if (QString::fromUtf8(buf).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';
|
|
if (s_folder(i, &depth, buf, int(sizeof buf) - 1) < 0) break;
|
|
buf[sizeof buf - 1] = '\0';
|
|
const QString nome = QString::fromUtf8(buf);
|
|
|
|
if (s_place) {
|
|
char dove[1024];
|
|
dove[0] = '\0';
|
|
if (s_place(i, dove, int(sizeof dove) - 1) > 0) {
|
|
dove[sizeof dove - 1] = '\0';
|
|
const QString posto = QString::fromUtf8(dove);
|
|
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';
|
|
if (s_folder(i, &depth, buf, int(sizeof buf) - 1) < 0) break;
|
|
buf[sizeof buf - 1] = '\0';
|
|
nomi << QString::fromUtf8(buf);
|
|
}
|
|
return nomi.join(QStringLiteral(", "));
|
|
}
|
|
|
|
// 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 &oggetto,
|
|
const QString &corpo)
|
|
{
|
|
if (!s_compose || !s_claim || !s_send_start || !s_send_poll)
|
|
return tr("Il motore non è pronto");
|
|
|
|
const int out = folderOut();
|
|
if (out < 0)
|
|
return tr("Manca la cartella di uscita. Il motore vede: %1").arg(cartelleViste());
|
|
|
|
const QString config = m_settings ? m_settings->smtpLine() : QString();
|
|
if (config.isEmpty())
|
|
return tr("SMTP non configurato: controlla l'account");
|
|
|
|
if (to.trimmed().isEmpty())
|
|
return tr("Manca il destinatario");
|
|
|
|
// Il From: senza, il messaggio parte senza mittente e il motore non
|
|
// trova nemmeno la personalità a cui appartiene.
|
|
QString from = m_settings ? m_settings->mittente().trimmed() : QString();
|
|
if (from.isEmpty() && m_settings && m_settings->persona().contains(QLatin1Char('@')))
|
|
from = m_settings->persona().trimmed();
|
|
if (from.isEmpty())
|
|
return tr("Manca l'indirizzo del mittente: Impostazioni → Account");
|
|
|
|
// Il foglio che il motore sa leggere: campi "Nome: valore", riga vuota,
|
|
// poi il corpo (Mail_Compose.Parse).
|
|
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');
|
|
foglio += QLatin1String("Subject: ") + oggetto + QLatin1String("\n\n") + corpo;
|
|
|
|
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 /* cifra */, 0 /* firma */,
|
|
0 /* nessun originale */, -1, -1, -1,
|
|
stato, int(sizeof stato) - 1);
|
|
if (salvato < 0) {
|
|
const QString motivo = QString::fromUtf8(stato).trimmed();
|
|
return motivo.isEmpty() ? tr("Il motore ha rifiutato il messaggio") : motivo;
|
|
}
|
|
|
|
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);
|
|
|
|
// 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();
|
|
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;
|
|
|
|
// Dal più nuovo al più vecchio: l'ordinamento lo fa il motore (conosce i
|
|
// minuti della data, la colonna a schermo è solo testo).
|
|
if (s_sort) s_sort(folder, Date, 1);
|
|
|
|
for (int row = 0; row < 2000; row++) {
|
|
const QString who = cell(folder, row, Who);
|
|
const QString subject = cell(folder, row, Subject);
|
|
if (who.isEmpty() && subject.isEmpty()) break; // fine della cartella
|
|
|
|
Row r;
|
|
r.riga = row;
|
|
r.mittente = 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;
|
|
}
|
|
|
|
QString EngineBridge::body(int folder, int row)
|
|
{
|
|
if (!s_body) return QString();
|
|
char buf[65536];
|
|
int n = s_body(folder, row, 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);
|
|
}
|
|
|
|
// 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;
|
|
}
|