diff --git a/desktop/README.md b/desktop/README.md index 17552ea..a0594f6 100644 --- a/desktop/README.md +++ b/desktop/README.md @@ -10,7 +10,9 @@ It reads RSS, Atom, and JSON Feed, and Nostr long-form articles (NIP-23) and videos (NIP-71) by the authors you follow. The window has three panes (sources, articles, reader) driven from the keyboard, and the same engine (SQLite library, fetcher, feed parser, discovery, OPML, Nostr relays) runs -headless from the command line. Sync comes in a later phase. +headless from the command line. It pulls your subscriptions, read articles, +and saved views from the Readstr web app over Nostr (read-only for now; +publishing comes in a later phase). ## Build, test, install @@ -35,7 +37,7 @@ the articles of the selected source in the middle, newest first, and the article itself on the right. Selecting an article marks it read. Right-click a feed to refresh it or unsubscribe (and, for a Nostr author, to open their profile on njump.me or copy their npub); the `⋮` menu has refresh, mark the -view read, and OPML import and export. +view read, OPML import and export, and Sync with Nostr. Feeds refresh when the window opens and then about every 30 minutes (give or take 10%, so many readers don't all ask at once) for as long as it stays open; @@ -93,6 +95,47 @@ asked for, of the kind you asked for, and its id and signature check out (BIP-340, through libsecp256k1). When an author edits an article, the newer version replaces the older one in place, keeping its read and starred marks. +## Sync with the web app + +Give Readstr your npub (or an nprofile, whose relay hints are asked too) +with "Sync with Nostr…" in the `⋮` menu or `readstr sync login npub1…`, and +it pulls what the Readstr web app publishes for it: the subscription list +(kind 30404), the read articles (kind 30405, once the web app publishes it; +it does not yet), and the saved views (kind 30406). Only the public key is kept; nothing is ever signed or published, +which is why no signer is needed: the web app publishes these events in +cleartext, so anyone can read them. The window pulls right after you log in +and after every refresh of all feeds, so read marks find the articles it +brought; `readstr sync` pulls now. A pull that fails says so in the status +bar (and on stderr), or on stderr with exit code 1 from the command line. + +Merging is close to the web app's and never removes anything here: + +- Subscriptions are only added, never removed, and the list's `deleted` + entries are ignored, as the web app ignores them. Unlike the web app, + Readstr adds them without asking first. Only http(s) feed URLs and valid + npubs are taken, as for OPML import, except that a feed on this machine or + the local network (localhost, a private address, a name without a dot) is + left out and counted as unsupported, since whoever holds the npub's key + picks these; OPML import still takes them. A category becomes the feed's + category. New feeds are fetched by the next refresh (the window fetches + them at once). +- Read GUIDs mark the matching articles read in every feed, and are kept for + articles that arrive later, which come in read. An article is never + marked unread by a sync. +- Saved views are imported and stored for a later phase to show. A view's + mute words (`keywords.exclude`) never come from a relay, which never + carries them, and stay as they are here. + +Each event applies only when it is newer than the last one applied of its +kind (in the same second, when its id is lower, as NIP-01 has relays keep), +so an old or replayed one never rolls anything back, and unsubscribing here +is not undone by pulling the same list again. Readstr does not publish +yet, though, so a feed unsubscribed here comes back with the next newer +subscription list the web app publishes, which still has it. (Like the web app, an empty library +takes the subscription list whatever its age.) `readstr sync logout` or +"Stop syncing" forgets the npub and what was pulled for it; your +subscriptions, read marks, and saved views stay. + ## Command line Anything other than `open` runs headless, with no display needed. Every @@ -110,6 +153,9 @@ those that take `--json` print one line of JSON whose shape is stable (below). | `readstr star ID...`, `unstar ID...` | Star or unstar articles | | `readstr import FILE.opml [--json]` | Add the feeds in an OPML file; folders become categories | | `readstr export [FILE]` | Write the subscriptions as OPML to FILE, or to stdout | +| `readstr sync login NPUB` | Sync with an npub or nprofile from now on (public key only) | +| `readstr sync logout` | Stop syncing and forget what was pulled for the npub | +| `readstr sync [--json]` | Pull and merge the web app's sync events now; exits 1 if anything failed or was refused | | `readstr version [--json]`, `readstr --version` | Print the version | ```sh @@ -155,6 +201,15 @@ ISO 8601 (`2026-11-19T20:57:14Z`), and anything unknown is `null`. // an http(s) feed nor a valid npub) {"added": 12, "skipped": 2, "unsupported": 1} +// readstr sync --json ("added", "skipped", and "unsupported" count the remote +// subscriptions added, already here, and left out (neither an http(s) feed nor a +// valid npub, or a feed on this machine or the local network); +// "markedRead" the articles marked read, "pendingRead" the read GUIDs no article +// has yet, "views" the saved views now stored; "errors" says what failed or was +// refused, empty on success) +{"npub": "npub1…", "added": 2, "skipped": 40, "unsupported": 0, "markedRead": 12, + "pendingRead": 300, "views": 3, "syncedAt": "2026-11-19T21:30:00Z", "errors": []} + // readstr version --json {"name": "readstr", "version": "0.1.0", "qt": "6.12.0"} ``` @@ -193,6 +248,19 @@ asks for at most 100, and only for what is newer than a day before the last complete refresh (one where every relay answered both and no cap cut off). A relay that fails or stays silent is skipped, and a refresh fails only when none answers. +Sync events are taken only from the npub you gave, of their own kind with +their own d tag, and with a valid id and signature, like an author's; one +dated more than a day ahead is ignored. Their content must fit the web app's +format and caps (8 Mi characters, 5000 subscriptions, 100,000 read GUIDs of +at most 256 characters, URLs of at most 2048, 100 saved views, of which the +first 50 are kept), or that event is refused whole and the pull says so. As +on the web app, the merged views are cut to 50 with the remote ones first, +so 50 remote views leave no room for views only here. A newer event past the +size cap is passed over for the newest one that fits, or refused when none +does, and relay messages may be up to about 24 MiB for these. A pull cut +short by the pool's size cap, or with an event refused, says so and is not +recorded as the last sync; the events that fit still apply. + ## Files The library lives in `$XDG_DATA_HOME/readstr/readstr.db` (SQLite, in a 0700 diff --git a/desktop/src/Main.qml b/desktop/src/Main.qml index 28f6896..2e93ffc 100644 --- a/desktop/src/Main.qml +++ b/desktop/src/Main.qml @@ -26,7 +26,8 @@ ApplicationWindow { readonly property color errorColor: Material.color(Material.Red, Material.theme === Material.Light ? Material.Shade700 : Material.Shade300) // Single keys must not fire while a dialog or menu has the keyboard, or // typing an address would star articles. - readonly property bool dialogsClosed: !addDialog.visible && !unsubscribeDialog.visible && !sourcePane.menuOpen + readonly property bool dialogsClosed: !addDialog.visible && !unsubscribeDialog.visible && !syncDialog.visible + && !sourcePane.menuOpen // Nor behind the shortcuts overlay, which only ? and Esc close. readonly property bool keysFree: dialogsClosed && !helpVisible @@ -115,6 +116,7 @@ ApplicationWindow { onAddRequested: addDialog.open() onUnsubscribeRequested: (feedId, feedTitle) => win.askUnsubscribe(feedId, feedTitle) onHelpRequested: win.helpVisible = true + onSyncRequested: syncDialog.open() } Rectangle { Layout.fillHeight: true; Layout.preferredWidth: 1; color: Qt.alpha(theme.foreground, 0.1) } @@ -194,4 +196,5 @@ ApplicationWindow { AddFeedDialog { id: addDialog } UnsubscribeDialog { id: unsubscribeDialog } + SyncDialog { id: syncDialog } } diff --git a/desktop/src/SourcePane.qml b/desktop/src/SourcePane.qml index d5731e4..6132e4f 100644 --- a/desktop/src/SourcePane.qml +++ b/desktop/src/SourcePane.qml @@ -17,6 +17,7 @@ Rectangle { signal addRequested() signal unsubscribeRequested(var feedId, string feedTitle) signal helpRequested() + signal syncRequested() color: Qt.tint(theme.background, Qt.alpha(theme.foreground, 0.03)) @@ -74,6 +75,7 @@ Rectangle { MenuSeparator {} MenuItem { text: qsTr("Import OPML…"); onTriggered: backend.importOpml() } MenuItem { text: qsTr("Export OPML…"); onTriggered: backend.exportOpml() } + MenuItem { text: qsTr("Sync with Nostr…"); onTriggered: pane.syncRequested() } MenuSeparator {} MenuItem { text: qsTr("Keyboard shortcuts"); onTriggered: pane.helpRequested() } } diff --git a/desktop/src/SyncDialog.qml b/desktop/src/SyncDialog.qml new file mode 100644 index 0000000..0636a4f --- /dev/null +++ b/desktop/src/SyncDialog.qml @@ -0,0 +1,128 @@ +import QtQuick +import QtQuick.Controls +import QtQuick.Controls.Material +import QtQuick.Layouts + +// Sets or clears the npub whose subscriptions, read articles, and saved +// views come from the Readstr web app. Only the public key is kept: the +// events are public, so reading them needs no signer. +Dialog { + id: dialog + + readonly property color errorColor: Material.color(Material.Red, Material.theme === Material.Light ? Material.Shade700 : Material.Shade300) + property bool invalid: false + + function submit() { + if (field.text.trim() === "") + return + if (backend.setSyncNpub(field.text)) + close() + else + invalid = true + } + + parent: Overlay.overlay + anchors.centerIn: parent + width: Math.min(parent.width - 64, 520) + modal: true + title: qsTr("Sync with Nostr") + Material.roundedScale: theme.radius + + // Drawn plainly rather than through Material's elevation layer, which + // the software scene graph leaves out. + background: Rectangle { + radius: theme.radius + color: Qt.tint(theme.background, Qt.alpha(theme.foreground, 0.06)) + border.color: Qt.alpha(theme.foreground, 0.15) + border.width: 1 + } + + header: Label { + text: dialog.title + textFormat: Text.PlainText + elide: Text.ElideRight + padding: 24 + bottomPadding: 0 + font.pixelSize: 20 + } + + onOpened: { + field.text = backend.syncNpub + invalid = false + field.forceActiveFocus() + } + + contentItem: ColumnLayout { + spacing: 12 + + Label { + Layout.fillWidth: true + text: qsTr("After every refresh, Readstr reads the subscriptions and saved views the Readstr web app publishes for this npub, and its read articles once it publishes them. It never signs or publishes anything.") + textFormat: Text.PlainText + wrapMode: Text.Wrap + opacity: 0.7 + } + + TextField { + id: field + Layout.fillWidth: true + placeholderText: qsTr("npub or nprofile") + inputMethodHints: Qt.ImhNoAutoUppercase | Qt.ImhNoPredictiveText + Material.roundedScale: theme.radius + onAccepted: dialog.submit() + onTextEdited: dialog.invalid = false + } + + Label { + Layout.fillWidth: true + visible: backend.syncNpub !== "" && !!backend.syncedAt + text: { + translator.language + const date = backend.syncedAt + return date ? qsTr("Last synced %1").arg(date.toLocaleString(Qt.locale(), Locale.ShortFormat)) : "" + } + textFormat: Text.PlainText + elide: Text.ElideRight + opacity: 0.7 + } + + Label { + Layout.fillWidth: true + visible: dialog.invalid + text: qsTr("That is not an npub or nprofile") + textFormat: Text.PlainText + wrapMode: Text.Wrap + color: dialog.errorColor + } + } + + footer: DialogButtonBox { + background: null + Button { + text: qsTr("Stop syncing") + flat: true + focusPolicy: Qt.NoFocus + visible: backend.syncNpub !== "" + Material.roundedScale: theme.radius + onClicked: { + backend.stopSync() + dialog.close() + } + } + Button { + text: qsTr("Cancel") + flat: true + focusPolicy: Qt.NoFocus + Material.roundedScale: theme.radius + onClicked: dialog.close() + } + Button { + text: qsTr("Sync") + flat: true + focusPolicy: Qt.NoFocus + enabled: field.text.trim() !== "" && !backend.syncing + Material.roundedScale: theme.radius + onClicked: dialog.submit() + } + } +} diff --git a/desktop/src/backend.cpp b/desktop/src/backend.cpp index 42a29b1..b2769b2 100644 --- a/desktop/src/backend.cpp +++ b/desktop/src/backend.cpp @@ -52,7 +52,7 @@ QString richText(const Article &article) { Backend::Backend(FilePicker *picker, QObject *parent) : QObject(parent), m_fetcher(std::make_unique()), m_relays(std::make_unique()), - m_thumbnails(std::make_unique()), m_picker(picker) { + m_syncRelays(std::make_unique()), m_thumbnails(std::make_unique()), m_picker(picker) { m_openUrl = [](const QUrl &url) { return QDesktopServices::openUrl(url); }; m_writeClipboard = [](const QString &text) { QGuiApplication::clipboard()->setText(text, QClipboard::Clipboard); }; m_launch = &Backend::launchDetached; @@ -65,6 +65,7 @@ Backend::Backend(FilePicker *picker, QObject *parent) m_thread.setObjectName(QStringLiteral("readstr-library")); m_thread.start(); + m_syncRelays->setLimits(Sync::limits()); m_autoRefresh.setSingleShot(true); connect(&m_autoRefresh, &QTimer::timeout, this, &Backend::refreshAll); @@ -94,6 +95,7 @@ Backend::Backend(FilePicker *picker, QObject *parent) if (!m_storeOpen) setStatus(tr("Cannot open the library: %1").arg(m_store.lastError()), true); reloadLibrary(); + reloadSyncAccount(); } Backend::~Backend() { @@ -104,6 +106,7 @@ Backend::~Backend() { m_autoRefresh.stop(); m_fetcher.reset(); m_relays.reset(); + m_syncRelays.reset(); m_thumbnails.reset(); m_thread.quit(); m_thread.wait(); @@ -702,8 +705,11 @@ void Backend::refreshAll() { } if (feeds.isEmpty()) { scheduleAutoRefresh(); + // A new library may get its feeds from the sync. + sync(); return; } + m_syncAfterRefresh = true; refresh(feeds); } @@ -812,14 +818,11 @@ void Backend::refreshApplied(const Feed &feed, const Library::Refresh &outcome) emit refreshFinished(); // Feeds imported while this refresh ran have never been fetched. - if (m_fetchNewFeeds) { - m_fetchNewFeeds = false; - QList fresh; - for (const Feed &candidate : m_store.feeds()) - if (!candidate.lastFetchedAt.isValid()) - fresh << candidate; - if (!fresh.isEmpty()) - refresh(fresh); + if (std::exchange(m_fetchNewFeeds, false) && refreshUnfetched()) + return; + if (std::exchange(m_syncAfterRefresh, false)) { + m_refreshStatus = {m_status, m_statusError}; + sync(); } } @@ -838,6 +841,155 @@ void Backend::scheduleAutoRefresh() { m_autoRefresh.start(autoRefreshDelayMs(QRandomGenerator::global()->generateDouble())); } +QVariant Backend::syncedAt() const { + return m_syncAccount.syncedAt.isValid() ? QVariant(m_syncAccount.syncedAt.toLocalTime()) : QVariant(); +} + +void Backend::reloadSyncAccount() { + if (!m_storeOpen) + return; + const SyncAccount account = m_store.syncAccount(); + if (!m_store.lastError().isEmpty()) { + setStatus(tr("Cannot read the library: %1").arg(m_store.lastError()), true); + return; + } + m_syncAccount = account; + emit syncChanged(); +} + +bool Backend::setSyncNpub(const QString &text) { + const auto account = Sync::account(text); + if (!account || !m_storeOpen) + return false; + writeOnWorker( + [account = *account](Store &store) { + return store.setSyncAccount(account.npub, account.pubkey, account.relays) ? 1 : -1; + }, + tr("Cannot sync with %1: %2").arg(Nip19::shortNpub(account->npub, account->npub)), + [this, npub = account->npub](const WriteResult &result) { + if (!result.error.isEmpty()) { + setStatus(tr("Cannot sync with %1: %2").arg(Nip19::shortNpub(npub, npub), result.error), true); + return; + } + reloadSyncAccount(); + sync(); + }); + return true; +} + +void Backend::stopSync() { + if (!m_storeOpen || m_syncAccount.npub.isEmpty()) + return; + const QString npub = m_syncAccount.npub; + writeOnWorker([](Store &store) { return store.clearSyncAccount() ? 1 : -1; }, + tr("Cannot stop syncing: %1"), [this, npub](const WriteResult &result) { + if (!result.error.isEmpty()) { + setStatus(tr("Cannot stop syncing: %1").arg(result.error), true); + return; + } + reloadSyncAccount(); + setStatus(tr("Stopped syncing with %1").arg(Nip19::shortNpub(npub, npub))); + }); +} + +void Backend::sync() { + if (m_syncing) { + m_syncAgain = true; + return; + } + if (!m_storeOpen || m_syncAccount.pubkey.isEmpty()) { + m_refreshStatus.reset(); + return; + } + m_syncing = true; + emit syncChanged(); + setStatus(tr("Syncing with Nostr…")); + const SyncAccount account = m_syncAccount; + m_syncRelays->queryEachHeld({Sync::query(account)}, [this, account](qsizetype, const NostrResult &found, + const RelayPool::Release &release) { + if (m_closing) + return; + onWorker([account, found](Store &store) { return Sync::apply(store, account, found); }, + [this, release, pubkey = account.pubkey](const Sync::Outcome &outcome) { + release(); + syncApplied(outcome, pubkey); + }); + }); +} + +void Backend::syncApplied(const Sync::Outcome &outcome, const QString &pubkey) { + m_syncing = false; + emit syncChanged(); + reloadSyncAccount(); + const bool again = std::exchange(m_syncAgain, false); + if (outcome.added > 0) + m_syncFeedsAdded = true; + // An npub set while the pull was out is pulled for now. + if (!m_syncAccount.pubkey.isEmpty() && m_syncAccount.pubkey != pubkey) { + m_syncAddedBefore = m_syncMarkedBefore = 0; + sync(); + return; + } + reloadLibrary(); + QStringList errors = outcome.problems; + if (!outcome.error.isEmpty()) + errors.prepend(outcome.error); + const int added = std::exchange(m_syncAddedBefore, 0) + outcome.added; + const int markedRead = std::exchange(m_syncMarkedBefore, 0) + outcome.markedRead; + if (again && !m_syncAccount.pubkey.isEmpty()) { + // The follow-up says what both changed, and keeps the status of a + // refresh that finished while this one was out, which it was asked + // for. Its own problems are said there, if they persist. + for (const QString &error : std::as_const(errors)) + qWarning("readstr: sync: %s", qPrintable(error)); + m_syncAddedBefore = added; + m_syncMarkedBefore = markedRead; + sync(); + return; + } + const std::optional> refreshStatus = std::exchange(m_refreshStatus, std::nullopt); + // Anything said while the relays were asked is newer than the refresh's + // message, so that comes back only over the syncing one. + const bool stillSyncing = m_status == tr("Syncing with Nostr…"); + if (m_syncAccount.pubkey.isEmpty()) { + // Syncing was stopped while the pull was out, which is no failure. + // The window's own stop says so; a stop from elsewhere (`readstr + // sync logout`) must not leave "Syncing" up. + if (stillSyncing) + setStatus(refreshStatus ? refreshStatus->first : QString(), refreshStatus && refreshStatus->second); + } else if (!errors.isEmpty()) { + // Said on stderr too, since the status bar keeps only the latest. + for (const QString &error : std::as_const(errors)) + qWarning("readstr: sync: %s", qPrintable(error)); + setStatus(tr("Cannot sync with Nostr: %1").arg(errors.join("; ")), true); + } else if (refreshStatus && stillSyncing && added == 0 && markedRead == 0) { + // A sync that changed nothing would only hide what the refresh + // before it said, such as a feed that cannot be refreshed. + setStatus(refreshStatus->first, refreshStatus->second); + } else { + setStatus(tr("Synced with Nostr: %n feeds added, %1 articles marked read", nullptr, added).arg(markedRead)); + } + emit syncFinished(); + if (!std::exchange(m_syncFeedsAdded, false)) + return; + // The feeds the sync added have never been fetched. + if (m_refreshing) + m_fetchNewFeeds = true; + else + refreshUnfetched(); +} + +bool Backend::refreshUnfetched() { + QList fresh; + for (const Feed &candidate : m_store.feeds()) + if (!candidate.lastFetchedAt.isValid()) + fresh << candidate; + if (fresh.isEmpty()) + return false; + refresh(fresh); + return true; +} + void Backend::importOpml() { if (!m_picker) { setStatus(tr("No file chooser is available"), true); diff --git a/desktop/src/backend.h b/desktop/src/backend.h index e095c62..02e8cda 100644 --- a/desktop/src/backend.h +++ b/desktop/src/backend.h @@ -10,6 +10,8 @@ #include #include #include +#include +#include #include "articlemodel.h" #include "feedparser.h" @@ -19,6 +21,7 @@ #include "relaypool.h" #include "sourcemodel.h" #include "store.h" +#include "sync.h" #include "thumbnails.h" class FilePicker; @@ -73,6 +76,12 @@ class Backend : public QObject { Q_PROPERTY(bool adding READ adding NOTIFY addChanged) Q_PROPERTY(QString addError READ addError NOTIFY addChanged) + // The npub whose Nostr sync events are pulled after each refresh, empty + // for none, and when a pull last succeeded (null until one has). + Q_PROPERTY(QString syncNpub READ syncNpub NOTIFY syncChanged) + Q_PROPERTY(QVariant syncedAt READ syncedAt NOTIFY syncChanged) + Q_PROPERTY(bool syncing READ syncing NOTIFY syncChanged) + Q_PROPERTY(QString status READ status NOTIFY statusChanged) Q_PROPERTY(bool statusError READ statusError NOTIFY statusChanged) @@ -116,6 +125,10 @@ class Backend : public QObject { bool adding() const { return m_adding; } QString addError() const { return m_addError; } + QString syncNpub() const { return m_syncAccount.npub; } + QVariant syncedAt() const; + bool syncing() const { return m_syncing; } + QString status() const { return m_status; } bool statusError() const { return m_statusError; } @@ -138,6 +151,10 @@ class Backend : public QObject { Q_INVOKABLE bool unsubscribe(qint64 feedId); Q_INVOKABLE void refreshAll(); Q_INVOKABLE void refreshFeed(qint64 feedId); + // Syncs with the npub or nprofile `text` from now on and pulls at once; + // false, changing nothing, when it is neither. + Q_INVOKABLE bool setSyncNpub(const QString &text); + Q_INVOKABLE void stopSync(); Q_INVOKABLE void importOpml(); Q_INVOKABLE void exportOpml(); // Puts text selected in the reader on the clipboard (and the primary @@ -176,7 +193,10 @@ class Backend : public QObject { void setThumbnailLimits(const Thumbnails::Limits &limits) { m_thumbnails->setLimits(limits); } void setFetchLimits(const Fetcher::Limits &limits) { m_fetcher->setLimits(limits); } void setRelayLimits(const RelayPool::Limits &limits) { m_relays->setLimits(limits); } - void setRelays(const QStringList &relays) { m_relays->setRelays(relays); } + void setRelays(const QStringList &relays) { + m_relays->setRelays(relays); + m_syncRelays->setRelays(relays); + } signals: void libraryChanged(); @@ -188,6 +208,8 @@ class Backend : public QObject { void addChanged(); void subscribed(qint64 feedId); void imported(); + void syncChanged(); + void syncFinished(); void statusChanged(); private: @@ -242,14 +264,24 @@ class Backend : public QObject { QString npubOf(qint64 feedId) const; void refresh(const QList &targets); void refreshApplied(const Feed &feed, const Library::Refresh &outcome); + // Refreshes the feeds never fetched yet; false when there are none. + bool refreshUnfetched(); void searchRound(const std::shared_ptr &search); void subscribeFinished(const Library::Subscription &subscription); void scheduleAutoRefresh(); + void reloadSyncAccount(); + // Pulls the sync events, when there is an account and no pull is out. + void sync(); + // `pubkey` is the account the pull was for. + void syncApplied(const Sync::Outcome &outcome, const QString &pubkey); Store m_store; bool m_storeOpen = false; std::unique_ptr m_fetcher; std::unique_ptr m_relays; + // Its own pool, as the sync events are allowed to be far larger than + // an author's. + std::unique_ptr m_syncRelays; std::unique_ptr m_thumbnails; QThread m_thread; LibraryWorker *m_worker = nullptr; @@ -288,6 +320,23 @@ class Backend : public QObject { // Feeds whose delete the worker has not done yet, hidden meanwhile. QSet m_removing; bool m_fetchNewFeeds = false; + // A refresh of every feed pulls the sync events once it is done, so + // their read GUIDs find the articles it brought. + bool m_syncAfterRefresh = false; + // What that refresh said, kept when the sync after it changes nothing. + std::optional> m_refreshStatus; + SyncAccount m_syncAccount; + bool m_syncing = false; + // A pull asked for while one was out, which the relays may already have + // answered without what changed since, so one more runs after it. + bool m_syncAgain = false; + // What the pulls a follow-up replaced changed, said with its own. + int m_syncAddedBefore = 0; + int m_syncMarkedBefore = 0; + // Some pull added feeds that have not been fetched yet. Kept apart from + // the counts above, which a switch of account resets, so the feeds an + // earlier account's pull added are still fetched. + bool m_syncFeedsAdded = false; bool m_autoRefreshOn = false; QTimer m_autoRefresh; diff --git a/desktop/src/cli.cpp b/desktop/src/cli.cpp index d45561f..fcd5ea1 100644 --- a/desktop/src/cli.cpp +++ b/desktop/src/cli.cpp @@ -10,6 +10,7 @@ #include "fetcher.h" #include "library.h" #include "store.h" +#include "sync.h" namespace { using Handler = int (*)(const QString &, const QStringList &, QTextStream &, QTextStream &); @@ -29,6 +30,9 @@ void usage(QTextStream &stream) { " readstr read|unread|star|unstar ID...\n" " readstr import FILE.opml [--json]\n" " readstr export [FILE]\n" + " readstr sync [--json]\n" + " readstr sync login NPUB\n" + " readstr sync logout\n" " readstr version [--json]\n" " readstr --version\n"; } @@ -454,6 +458,83 @@ int exportOpml(const QString &command, const QStringList &arguments, QTextStream return 0; } +int sync(const QString &command, const QStringList &arguments, QTextStream &out, QTextStream &err) { + Options options; + if (!parseOptions(command, arguments, {"--json"}, {}, options, err)) + return 1; + const QString action = options.positional.value(0); + if (action == QLatin1String("login")) { + if (options.json || options.positional.size() != 2) + return fail(command, "login needs one npub or nprofile", err); + const auto account = Sync::account(options.positional.at(1)); + if (!account) + return fail(command, "give an npub or nprofile", err); + Store store; + if (!openStore(command, store, err)) + return 1; + if (!store.setSyncAccount(account->npub, account->pubkey, account->relays)) + return fail(command, store.lastError(), err); + out << "Syncing with " << account->npub << ". Run 'readstr sync' to pull now.\n"; + return 0; + } + if (action == QLatin1String("logout")) { + if (options.json || options.positional.size() != 1) + return fail(command, "logout takes no arguments", err); + Store store; + if (!openStore(command, store, err)) + return 1; + const SyncAccount account = store.syncAccount(); + if (!store.lastError().isEmpty() || !store.clearSyncAccount()) + return fail(command, store.lastError(), err); + if (account.npub.isEmpty()) + out << "Not syncing with any npub\n"; + else + out << "Stopped syncing with " << account.npub << "\n"; + return 0; + } + if (!options.positional.isEmpty()) + return fail(command, "unknown action '" + action + "' (login, logout, or none to pull)", err); + + Store store; + if (!openStore(command, store, err)) + return 1; + const SyncAccount account = store.syncAccount(); + if (!store.lastError().isEmpty()) + return fail(command, store.lastError(), err); + if (account.pubkey.isEmpty()) + return fail(command, "not syncing with any npub; run 'readstr sync login NPUB' first", err); + RelayPool relays; + relays.setLimits(Sync::limits()); + const Sync::Outcome outcome = Sync::apply(store, account, relays.query(Sync::query(account))); + QStringList errors = outcome.problems; + if (!outcome.error.isEmpty()) + errors.prepend(outcome.error); + for (const QString &error : std::as_const(errors)) + err << "readstr " << command << ": " << printable(error) << "\n"; + + if (options.json) { + const SyncAccount after = store.syncAccount(); + printJson(QJsonObject{{"npub", account.npub}, + {"added", outcome.added}, + {"skipped", outcome.skipped}, + {"unsupported", outcome.unsupported}, + {"markedRead", outcome.markedRead}, + {"pendingRead", outcome.pendingRead}, + {"views", outcome.views}, + {"syncedAt", nullable(after.syncedAt)}, + {"errors", QJsonArray::fromStringList(errors)}}, + out); + } else if (outcome.error.isEmpty()) { + out << "Synced with " << account.npub << ": " << outcome.added << " feeds added (" << outcome.skipped + << " already subscribed, " << outcome.unsupported << " unsupported), " << outcome.markedRead + << " articles marked read, " << outcome.pendingRead << " read GUIDs waiting for their articles, " + << outcome.views << " saved views\n"; + if (outcome.added > 0) + out << "Run 'readstr refresh' to fetch the new feeds.\n"; + } + return errors.isEmpty() ? 0 : 1; +} + int version(const QString &command, const QStringList &arguments, QTextStream &out, QTextStream &err) { Options options; if (!parseOptions(command, arguments, {"--json"}, {}, options, err)) @@ -487,6 +568,7 @@ constexpr Command commands[] = { {"unstar", setFlag}, {"import", importOpml}, {"export", exportOpml}, + {"sync", sync}, {"version", version}, {"--version", version}, {"help", help}, diff --git a/desktop/src/i18n/da.json b/desktop/src/i18n/da.json index a22524a..9365ef9 100644 --- a/desktop/src/i18n/da.json +++ b/desktop/src/i18n/da.json @@ -117,5 +117,27 @@ "The last refresh did not hear from every relay, or stopped at a limit, so some articles may be missing. The next refresh asks for them again.": "Den seneste opdatering hørte ikke fra alle relæer eller stoppede ved en grænse, så nogle artikler kan mangle. Den næste opdatering beder om dem igen.", "Open profile": "Åbn profil", "Copy npub": "Kopiér npub", - "Copied %1 to the clipboard": "Kopierede %1 til udklipsholderen" + "Copied %1 to the clipboard": "Kopierede %1 til udklipsholderen", + "Sync with Nostr…": "Synkronisér med Nostr…", + "Sync with Nostr": "Synkronisér med Nostr", + "After every refresh, Readstr reads the subscriptions and saved views the Readstr web app publishes for this npub, and its read articles once it publishes them. It never signs or publishes anything.": "Efter hver opdatering læser Readstr de abonnementer og gemte visninger, som Readstr-webappen offentliggør for denne npub, og dens læste artikler, når den offentliggør dem. Den signerer og offentliggør aldrig noget.", + "npub or nprofile": "npub eller nprofile", + "Last synced %1": "Sidst synkroniseret %1", + "That is not an npub or nprofile": "Det er ikke en npub eller nprofile", + "Stop syncing": "Stop synkronisering", + "Sync": "Synkronisér", + "Cannot sync with %1: %2": "Kan ikke synkronisere med %1: %2", + "Cannot stop syncing: %1": "Kan ikke stoppe synkroniseringen: %1", + "Stopped syncing with %1": "Synkroniserer ikke længere med %1", + "Syncing with Nostr…": "Synkroniserer med Nostr…", + "Cannot sync with Nostr: %1": "Kan ikke synkronisere med Nostr: %1", + "Synced with Nostr: %n feeds added, %1 articles marked read": { + "one": "Synkroniseret med Nostr: %n feed tilføjet, %1 artikler markeret som læst", + "other": "Synkroniseret med Nostr: %n feeds tilføjet, %1 artikler markeret som læst" + }, + "the npub changed during the pull": "npub'en blev ændret under hentningen", + "the subscription list does not fit the web app's format": "abonnementslisten passer ikke til webappens format", + "the read status does not fit the web app's format": "læsestatussen passer ikke til webappens format", + "the saved views do not fit the web app's format": "de gemte visninger passer ikke til webappens format", + "the relays sent more than fits, so some sync events may be missing": "relæerne sendte mere, end der er plads til, så nogle synkroniseringshændelser kan mangle" } diff --git a/desktop/src/i18n/en.json b/desktop/src/i18n/en.json index 1eef09c..1cde571 100644 --- a/desktop/src/i18n/en.json +++ b/desktop/src/i18n/en.json @@ -26,5 +26,9 @@ "Exported %n feeds to %1": { "one": "Exported %n feed to %1", "other": "Exported %n feeds to %1" + }, + "Synced with Nostr: %n feeds added, %1 articles marked read": { + "one": "Synced with Nostr: %n feed added, %1 articles marked read", + "other": "Synced with Nostr: %n feeds added, %1 articles marked read" } } diff --git a/desktop/src/i18n/pt-BR.json b/desktop/src/i18n/pt-BR.json index f472708..96a9e23 100644 --- a/desktop/src/i18n/pt-BR.json +++ b/desktop/src/i18n/pt-BR.json @@ -52,5 +52,28 @@ "The last refresh did not hear from every relay, or stopped at a limit, so some articles may be missing. The next refresh asks for them again.": "A última atualização não teve resposta de todos os relays, ou parou em um limite, então alguns artigos podem estar faltando. A próxima atualização pede por eles de novo.", "Open profile": "Abrir perfil", "Copy npub": "Copiar npub", - "Copied %1 to the clipboard": "%1 copiado para a área de transferência" + "Copied %1 to the clipboard": "%1 copiado para a área de transferência", + "Sync with Nostr…": "Sincronizar com o Nostr…", + "Sync with Nostr": "Sincronizar com o Nostr", + "After every refresh, Readstr reads the subscriptions and saved views the Readstr web app publishes for this npub, and its read articles once it publishes them. It never signs or publishes anything.": "Depois de cada atualização, o Readstr lê as assinaturas e as visualizações salvas que o app web do Readstr publica para esta npub, e os artigos lidos quando ele os publicar. Ele nunca assina nem publica nada.", + "npub or nprofile": "npub ou nprofile", + "Last synced %1": "Última sincronização: %1", + "That is not an npub or nprofile": "Isso não é uma npub nem um nprofile", + "Stop syncing": "Parar de sincronizar", + "Sync": "Sincronizar", + "Cannot sync with %1: %2": "Não foi possível sincronizar com %1: %2", + "Cannot stop syncing: %1": "Não foi possível parar de sincronizar: %1", + "Stopped syncing with %1": "Parou de sincronizar com %1", + "Syncing with Nostr…": "Sincronizando com o Nostr…", + "Cannot sync with Nostr: %1": "Não foi possível sincronizar com o Nostr: %1", + "Synced with Nostr: %n feeds added, %1 articles marked read": { + "one": "Sincronizado com o Nostr: %n feed adicionado, %1 artigos marcados como lidos", + "many": "Sincronizado com o Nostr: %n de feeds adicionados, %1 artigos marcados como lidos", + "other": "Sincronizado com o Nostr: %n feeds adicionados, %1 artigos marcados como lidos" + }, + "the npub changed during the pull": "a npub mudou durante a busca", + "the subscription list does not fit the web app's format": "a lista de assinaturas não segue o formato do app web", + "the read status does not fit the web app's format": "o status de leitura não segue o formato do app web", + "the saved views do not fit the web app's format": "as visualizações salvas não seguem o formato do app web", + "the relays sent more than fits, so some sync events may be missing": "os relays enviaram mais do que cabe, então alguns eventos de sincronização podem estar faltando" } diff --git a/desktop/src/i18n/pt.json b/desktop/src/i18n/pt.json index 7fe5977..fad89a9 100644 --- a/desktop/src/i18n/pt.json +++ b/desktop/src/i18n/pt.json @@ -124,5 +124,28 @@ "The last refresh did not hear from every relay, or stopped at a limit, so some articles may be missing. The next refresh asks for them again.": "A última atualização não obteve resposta de todos os relays, ou parou num limite, pelo que podem faltar alguns artigos. A próxima atualização volta a pedi-los.", "Open profile": "Abrir perfil", "Copy npub": "Copiar npub", - "Copied %1 to the clipboard": "%1 copiado para a área de transferência" + "Copied %1 to the clipboard": "%1 copiado para a área de transferência", + "Sync with Nostr…": "Sincronizar com o Nostr…", + "Sync with Nostr": "Sincronizar com o Nostr", + "After every refresh, Readstr reads the subscriptions and saved views the Readstr web app publishes for this npub, and its read articles once it publishes them. It never signs or publishes anything.": "Após cada atualização, o Readstr lê as subscrições e as vistas guardadas que a aplicação web do Readstr publica para esta npub, e os artigos lidos quando ela os publicar. Nunca assina nem publica nada.", + "npub or nprofile": "npub ou nprofile", + "Last synced %1": "Última sincronização: %1", + "That is not an npub or nprofile": "Isto não é uma npub nem um nprofile", + "Stop syncing": "Parar a sincronização", + "Sync": "Sincronizar", + "Cannot sync with %1: %2": "Não é possível sincronizar com %1: %2", + "Cannot stop syncing: %1": "Não é possível parar a sincronização: %1", + "Stopped syncing with %1": "Deixou de sincronizar com %1", + "Syncing with Nostr…": "A sincronizar com o Nostr…", + "Cannot sync with Nostr: %1": "Não é possível sincronizar com o Nostr: %1", + "Synced with Nostr: %n feeds added, %1 articles marked read": { + "one": "Sincronizado com o Nostr: %n feed adicionado, %1 artigos marcados como lidos", + "many": "Sincronizado com o Nostr: %n de feeds adicionados, %1 artigos marcados como lidos", + "other": "Sincronizado com o Nostr: %n feeds adicionados, %1 artigos marcados como lidos" + }, + "the npub changed during the pull": "a npub mudou durante a obtenção", + "the subscription list does not fit the web app's format": "a lista de subscrições não segue o formato da aplicação web", + "the read status does not fit the web app's format": "o estado de leitura não segue o formato da aplicação web", + "the saved views do not fit the web app's format": "as vistas guardadas não seguem o formato da aplicação web", + "the relays sent more than fits, so some sync events may be missing": "os relays enviaram mais do que cabe, por isso podem faltar alguns eventos de sincronização" } diff --git a/desktop/src/i18n/ru.json b/desktop/src/i18n/ru.json index 2b92ae9..b0acfaa 100644 --- a/desktop/src/i18n/ru.json +++ b/desktop/src/i18n/ru.json @@ -131,5 +131,29 @@ "The last refresh did not hear from every relay, or stopped at a limit, so some articles may be missing. The next refresh asks for them again.": "Последнее обновление получило ответ не от всех релеев или остановилось на ограничении, поэтому некоторых статей может не хватать. Следующее обновление запросит их снова.", "Open profile": "Открыть профиль", "Copy npub": "Копировать npub", - "Copied %1 to the clipboard": "%1 скопирован в буфер обмена" + "Copied %1 to the clipboard": "%1 скопирован в буфер обмена", + "Sync with Nostr…": "Синхронизация с Nostr…", + "Sync with Nostr": "Синхронизация с Nostr", + "After every refresh, Readstr reads the subscriptions and saved views the Readstr web app publishes for this npub, and its read articles once it publishes them. It never signs or publishes anything.": "После каждого обновления Readstr читает подписки и сохранённые представления, которые веб-приложение Readstr публикует для этого npub, а прочитанные статьи — когда оно начнёт их публиковать. Он никогда ничего не подписывает и не публикует.", + "npub or nprofile": "npub или nprofile", + "Last synced %1": "Последняя синхронизация: %1", + "That is not an npub or nprofile": "Это не npub и не nprofile", + "Stop syncing": "Остановить синхронизацию", + "Sync": "Синхронизировать", + "Cannot sync with %1: %2": "Не удаётся синхронизироваться с %1: %2", + "Cannot stop syncing: %1": "Не удаётся остановить синхронизацию: %1", + "Stopped syncing with %1": "Синхронизация с %1 остановлена", + "Syncing with Nostr…": "Синхронизация с Nostr…", + "Cannot sync with Nostr: %1": "Не удаётся синхронизироваться с Nostr: %1", + "Synced with Nostr: %n feeds added, %1 articles marked read": { + "one": "Синхронизировано с Nostr: добавлена %n лента, статей отмечено прочитанными: %1", + "few": "Синхронизировано с Nostr: добавлено %n ленты, статей отмечено прочитанными: %1", + "many": "Синхронизировано с Nostr: добавлено %n лент, статей отмечено прочитанными: %1", + "other": "Синхронизировано с Nostr: добавлено %n ленты, статей отмечено прочитанными: %1" + }, + "the npub changed during the pull": "npub изменился во время загрузки", + "the subscription list does not fit the web app's format": "список подписок не соответствует формату веб-приложения", + "the read status does not fit the web app's format": "статус прочтения не соответствует формату веб-приложения", + "the saved views do not fit the web app's format": "сохранённые представления не соответствуют формату веб-приложения", + "the relays sent more than fits, so some sync events may be missing": "релеи прислали больше, чем помещается, поэтому некоторые события синхронизации могут отсутствовать" } diff --git a/desktop/src/library.cpp b/desktop/src/library.cpp index dce6a75..3e98f94 100644 --- a/desktop/src/library.cpp +++ b/desktop/src/library.cpp @@ -215,7 +215,8 @@ Import importFile(Store &store, const QString &path) { return outlines ? importOutlines(store, *outlines) : result; } -Import importOutlines(Store &store, const QList &outlines) { +Import importOutlines(Store &store, const QList &outlines, + const std::function &gate) { Import result; // Unsupported outlines are set aside before de-duplication, so one // cannot shadow a supported one with the same key. An nprofile or a @@ -247,6 +248,16 @@ Import importOutlines(Store &store, const QList &outlines) { // nothing would fetch, and the subscriptions it reads cannot change // before it writes. const bool saved = store.transaction([&] { + if (gate) { + bool proceed = true; + if (!gate(&proceed)) + return false; + if (!proceed) { + result = Import{}; + result.stopped = true; + return true; + } + } const QList feeds = store.feeds(); if (!store.lastError().isEmpty()) return false; diff --git a/desktop/src/library.h b/desktop/src/library.h index cc197b3..f35b29e 100644 --- a/desktop/src/library.h +++ b/desktop/src/library.h @@ -4,6 +4,7 @@ #include #include #include +#include #include #include @@ -86,6 +87,8 @@ struct Import { int skipped = 0; // Outlines that are neither a web feed nor an npub. int unsupported = 0; + // The gate said to add nothing, so nothing was. + bool stopped = false; QString error; }; // Reads and parses an OPML file (a regular file of at most Opml::maxBytes) @@ -93,8 +96,13 @@ struct Import { // opened. Null with the reason in `error` when it cannot. std::optional> readOpml(const QString &path, QString *error); // Adds the feeds the outlines list that are not subscribed yet, all of them -// or, when one cannot be saved, none; folders become categories. -Import importOutlines(Store &store, const QList &outlines); +// or, when one cannot be saved, none; folders become categories. `gate`, +// when set, runs first inside the same transaction, so what it reads cannot +// change before the feeds are added and what it writes commits with them: +// it returns false on a store failure, which rolls everything back, and +// sets *proceed to false to add nothing. +Import importOutlines(Store &store, const QList &outlines, + const std::function &gate = {}); // readOpml() and then importOutlines(). Import importFile(Store &store, const QString &path); // The subscriptions as OPML, or null with the reason in `error`. diff --git a/desktop/src/relaypool.cpp b/desktop/src/relaypool.cpp index 41f531f..1ea0f78 100644 --- a/desktop/src/relaypool.cpp +++ b/desktop/src/relaypool.cpp @@ -15,14 +15,25 @@ #include "feedparser.h" #include "fetcher.h" -QJsonObject NostrQuery::filter() const { +QList NostrQuery::filters() const { QJsonArray kindArray; for (int kind : kinds) kindArray << kind; QJsonObject object{{"authors", QJsonArray{author}}, {"kinds", kindArray}, {"limit", limit}}; if (since > 0) object.insert("since", since); - return object; + if (dTags.isEmpty()) + return {object}; + // One filter per pair, each with its own limit, so the old versions a + // relay keeps of one pair cannot use up the limit of another. + QList perPair; + for (const auto &[kind, dTag] : dTags) { + QJsonObject pair = object; + pair.insert("kinds", QJsonArray{kind}); + pair.insert("#d", QJsonArray{dTag}); + perPair << pair; + } + return perPair; } namespace { @@ -48,6 +59,9 @@ struct RelayPool::Batch { // By id, or for a replaceable event by its address, holding only // the newest version. QHash events; + // By address, the newest verified event passed over for being past + // the query's maxContentLength, without its content. + QHash oversized; qint64 bytes = 0; bool truncated = false; // A relay hint was left out at the connection cap. @@ -191,7 +205,10 @@ class RelayPool::Connection : public QObject { }); timer->start(m_limits.subscriptionTimeoutMs); m_subscriptions.insert(id, {query, timer}); - send(QJsonArray{"REQ", id, m_batch->queries.at(query).query.filter()}); + QJsonArray request{"REQ", id}; + for (const QJsonObject &filter : m_batch->queries.at(query).query.filters()) + request << filter; + send(request); } void send(const QJsonArray &message) { @@ -468,9 +485,34 @@ bool RelayPool::accept(const std::shared_ptr &batch, int queryIndex, cons // Dropped before anything costly. if (state.delivered || event.pubkey != state.query.author || !state.query.kinds.contains(event.kind) || event.createdAt < state.query.since - || event.createdAt > QDateTime::currentSecsSinceEpoch() + maxClockSkew) + || event.createdAt > QDateTime::currentSecsSinceEpoch() + maxClockSkew + || (!state.query.dTags.isEmpty() + && !state.query.dTags.contains(std::pair(event.kind, event.tag(QStringLiteral("d")))))) return true; const QString address = replaceableKey(event); + if (state.query.maxContentLength > 0 && event.content.size() > state.query.maxContentLength) { + // Noted so the result can say it was refused, should no version of + // its address that fits come. Only the newest one per address is + // kept, since the sync judges it against its watermark, and only a + // version newer than the one held is verified, which keeps a relay + // from claiming a refusal with a forged event without hashing every + // oversized copy. + if (address.isEmpty() || state.events.contains(address)) + return true; + const auto held = state.oversized.constFind(address); + if (held != state.oversized.cend() && (held->id == event.id || !event.isNewerThan(*held))) + return true; + if (!event.verify()) + return false; + NostrEvent stripped; + stripped.id = event.id; + stripped.pubkey = event.pubkey; + stripped.createdAt = event.createdAt; + stripped.kind = event.kind; + stripped.tags = {{QStringLiteral("d"), event.tag(QStringLiteral("d"))}}; + state.oversized.insert(address, stripped); + return true; + } const QString key = address.isEmpty() ? event.id : address; const auto existing = state.events.constFind(key); if (existing != state.events.cend() && (existing->id == event.id || !event.isNewerThan(*existing))) @@ -534,6 +576,9 @@ void RelayPool::deliver(const std::shared_ptr &batch, int queryIndex, con result.answered = state.answered; result.truncated = state.truncated; result.deferred = state.deferred; + for (auto it = state.oversized.cbegin(); it != state.oversized.cend(); ++it) + if (!state.events.contains(it.key())) + result.oversized << it.value(); if (!error.isEmpty()) result.error = error; else if (!state.answered) diff --git a/desktop/src/relaypool.h b/desktop/src/relaypool.h index 05f8da1..749b7bc 100644 --- a/desktop/src/relaypool.h +++ b/desktop/src/relaypool.h @@ -9,6 +9,7 @@ #include #include #include +#include #include "nostrevent.h" @@ -22,8 +23,17 @@ struct NostrQuery { qint64 since = 0; // Relays to ask besides the pool's own, such as an nprofile's hints. QStringList extraRelays; + // When set, only events whose kind and d tag are one of these pairs, + // asked for with one filter per pair. A careless relay may still send a + // kind carrying another kind's d tag, which would take up the query's + // byte cap, so that is dropped here. + QList> dTags; + // When set, events whose content is longer are passed over rather than + // kept, so a huge newer version cannot hide a smaller older one. + qsizetype maxContentLength = 0; - QJsonObject filter() const; + // The NIP-01 filters of its REQ: one, or one per pair of dTags. + QList filters() const; }; struct NostrResult { @@ -40,6 +50,11 @@ struct NostrResult { QString error; // The events were cut off at the query's count or size cap. bool truncated = false; + // The newest version of each replaceable event a relay sent only past + // the query's maxContentLength, so no version of it was kept. Only its + // id, author, date, kind and d tag are kept, so it can be judged against + // a watermark without holding the content that did not fit. + QList oversized; // A relay hint was not asked, past the batch's connection cap. bool deferred = false; // When the query went out. diff --git a/desktop/src/resources.qrc b/desktop/src/resources.qrc index abadc36..9f9b257 100644 --- a/desktop/src/resources.qrc +++ b/desktop/src/resources.qrc @@ -6,6 +6,7 @@ ReaderPane.qml AddFeedDialog.qml UnsubscribeDialog.qml + SyncDialog.qml ShortcutsOverlay.qml i18n/en.json i18n/da.json diff --git a/desktop/src/sources.pri b/desktop/src/sources.pri index 2e4f342..3d24094 100644 --- a/desktop/src/sources.pri +++ b/desktop/src/sources.pri @@ -31,6 +31,7 @@ HEADERS += \ $$PWD/smallfile.h \ $$PWD/sourcemodel.h \ $$PWD/store.h \ + $$PWD/sync.h \ $$PWD/theme.h \ $$PWD/thumbnails.h \ $$PWD/translator.h @@ -55,6 +56,7 @@ SOURCES += \ $$PWD/sanitizer.cpp \ $$PWD/sourcemodel.cpp \ $$PWD/store.cpp \ + $$PWD/sync.cpp \ $$PWD/theme.cpp \ $$PWD/thumbnails.cpp \ $$PWD/translator.cpp diff --git a/desktop/src/store.cpp b/desktop/src/store.cpp index 836b690..9a1dc0a 100644 --- a/desktop/src/store.cpp +++ b/desktop/src/store.cpp @@ -99,6 +99,38 @@ const QList migrations = { // after it. "ALTER TABLE feeds ADD COLUMN incomplete INTEGER NOT NULL DEFAULT 0", }, + { + // The npub whose sync events are pulled (a public key only, as + // Readstr never signs), its nprofile's relay hints, and when a pull + // last succeeded. One row at most. + "CREATE TABLE sync_account (" + " id INTEGER PRIMARY KEY CHECK (id = 1)," + " npub TEXT NOT NULL," + " pubkey TEXT NOT NULL," + " relay_hints TEXT," + " synced_at INTEGER)", + // The created_at and id of the last event applied per d tag, so an + // older or repeated one is never applied again, as the web app keeps + // it. The id breaks a tie in created_at the way NIP-01 does. + "CREATE TABLE sync_applied (" + " d_tag TEXT PRIMARY KEY," + " created_at INTEGER NOT NULL," + " event_id TEXT NOT NULL)", + // The read GUIDs of the last kind 30405 event applied (when the web + // app publishes one; it does not yet), so articles that arrive later + // are marked read too. + "CREATE TABLE sync_read (guid TEXT PRIMARY KEY) WITHOUT ROWID", + // Read GUIDs are matched across feeds, as the web app keys them. + "CREATE INDEX items_by_guid ON items(guid)", + // Saved views from kind 30406, in order: the view as the web app + // publishes it (without keywords.exclude) as JSON, and the mute words + // (a JSON array), which are local only and never come from a relay. + "CREATE TABLE saved_views (" + " id TEXT PRIMARY KEY," + " position INTEGER NOT NULL," + " view TEXT NOT NULL," + " exclude TEXT)", + }, }; std::atomic connectionCounter{0}; @@ -140,6 +172,13 @@ QVariant timestamp(const QDateTime &time) { QVariant text(const QString &value) { return value.isEmpty() ? QVariant(QMetaType::fromType()) : QVariant(value); } + +// NULL for none, otherwise a JSON array. +QVariant jsonList(const QStringList &values) { + if (values.isEmpty()) + return QVariant(QMetaType::fromType()); + return QString::fromUtf8(QJsonDocument(QJsonArray::fromStringList(values)).toJson(QJsonDocument::Compact)); +} } Store::Store() : m_connection(QStringLiteral("readstr-store-%1").arg(connectionCounter++)) {} @@ -545,7 +584,8 @@ int Store::saveItems(qint64 feedId, const QList &items) { exists.prepare(QStringLiteral("SELECT 1 FROM items WHERE feed_id = ? AND guid = ?")); upsert.prepare(QStringLiteral( "INSERT INTO items (feed_id, guid, title, url, author, summary, content, published_at, created_at, address," - " revision, media_url, thumbnail_url, duration) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)" + " revision, media_url, thumbnail_url, duration, is_read) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?," + " EXISTS (SELECT 1 FROM sync_read WHERE guid = ?))" " ON CONFLICT(feed_id, guid) DO UPDATE SET title = excluded.title, url = excluded.url," " author = excluded.author, summary = excluded.summary, content = excluded.content," " published_at = COALESCE(excluded.published_at, items.published_at), media_url = excluded.media_url," @@ -616,6 +656,7 @@ int Store::saveItems(qint64 feedId, const QList &items) { upsert.addBindValue(text(item.mediaUrl)); upsert.addBindValue(text(item.thumbnailUrl)); upsert.addBindValue(item.duration >= 0 ? QVariant(item.duration) : QVariant(QMetaType::fromType())); + upsert.addBindValue(item.guid); if (!upsert.exec()) return failed(upsert); added += isNew; @@ -771,3 +812,146 @@ bool Store::setFlag(const char *column, qint64 articleId, bool value) { bool Store::setRead(qint64 articleId, bool read) { return setFlag("is_read", articleId, read); } bool Store::setStarred(qint64 articleId, bool starred) { return setFlag("is_starred", articleId, starred); } + +SyncAccount Store::syncAccount() { + m_error.clear(); + SyncAccount account; + QSqlQuery query(m_db); + if (!query.exec(QStringLiteral("SELECT npub, pubkey, relay_hints, synced_at FROM sync_account WHERE id = 1"))) { + fail(query.lastError().text()); + return account; + } + if (query.next()) { + account.npub = query.value(0).toString(); + account.pubkey = query.value(1).toString(); + account.relays = QJsonDocument::fromJson(query.value(2).toString().toUtf8()).toVariant().toStringList(); + if (!query.value(3).isNull()) + account.syncedAt = QDateTime::fromSecsSinceEpoch(query.value(3).toLongLong(), QTimeZone::UTC); + } + query.finish(); + if (account.pubkey.isEmpty()) + return account; + if (!query.exec(QStringLiteral("SELECT d_tag, created_at, event_id FROM sync_applied"))) { + fail(query.lastError().text()); + return {}; + } + while (query.next()) { + account.applied.insert(query.value(0).toString(), query.value(1).toLongLong()); + account.appliedIds.insert(query.value(0).toString(), query.value(2).toString()); + } + return account; +} + +bool Store::setSyncAccount(const QString &npub, const QString &pubkey, const QStringList &relays) { + return transaction([&] { + QSqlQuery query(m_db); + query.prepare(QStringLiteral("SELECT 1 FROM sync_account WHERE pubkey = ?")); + query.addBindValue(pubkey); + if (!query.exec()) + return fail(query.lastError().text()); + const bool same = query.next(); + query.finish(); + // Another account's watermarks and read GUIDs say nothing about this + // one's events. + if (!same && !clearSyncState()) + return false; + query.prepare(QStringLiteral("INSERT INTO sync_account (id, npub, pubkey, relay_hints) VALUES (1, ?, ?, ?)" + " ON CONFLICT(id) DO UPDATE SET npub = excluded.npub, pubkey = excluded.pubkey," + " relay_hints = excluded.relay_hints")); + query.addBindValue(npub); + query.addBindValue(pubkey); + query.addBindValue(jsonList(relays)); + return query.exec() || fail(query.lastError().text()); + }); +} + +bool Store::clearSyncState() { + QSqlQuery query(m_db); + for (const char *statement : {"DELETE FROM sync_account", "DELETE FROM sync_applied", "DELETE FROM sync_read"}) + if (!query.exec(QString::fromLatin1(statement))) + return fail(query.lastError().text()); + return true; +} + +bool Store::clearSyncAccount() { + return transaction([this] { return clearSyncState(); }); +} + +bool Store::setSyncApplied(const QString &dTag, qint64 createdAt, const QString &eventId) { + QSqlQuery query(m_db); + query.prepare(QStringLiteral( + "INSERT INTO sync_applied (d_tag, created_at, event_id) VALUES (?, ?, ?) ON CONFLICT(d_tag)" + " DO UPDATE SET created_at = excluded.created_at, event_id = excluded.event_id" + " WHERE excluded.created_at > sync_applied.created_at OR (excluded.created_at = sync_applied.created_at" + " AND excluded.event_id < sync_applied.event_id)")); + query.addBindValue(dTag); + query.addBindValue(createdAt); + query.addBindValue(eventId); + return query.exec() || fail(query.lastError().text()); +} + +bool Store::recordSynced(const QDateTime &time) { + QSqlQuery query(m_db); + query.prepare(QStringLiteral("UPDATE sync_account SET synced_at = ?")); + query.addBindValue(time.toSecsSinceEpoch()); + return query.exec() || fail(query.lastError().text()); +} + +int Store::applyReadGuids(const QStringList &guids) { + QSqlQuery query(m_db); + if (!query.exec(QStringLiteral("DELETE FROM sync_read"))) + return fail(query.lastError().text()), -1; + query.prepare(QStringLiteral("INSERT INTO sync_read (guid) VALUES (?) ON CONFLICT DO NOTHING")); + for (const QString &guid : guids) { + query.addBindValue(guid); + if (!query.exec()) + return fail(query.lastError().text()), -1; + } + // Only ever from unread to read: a GUID missing from the list says + // nothing about an article read here. + if (!query.exec(QStringLiteral( + "UPDATE items SET is_read = 1 WHERE is_read = 0 AND guid IN (SELECT guid FROM sync_read)"))) + return fail(query.lastError().text()), -1; + return query.numRowsAffected(); +} + +int Store::pendingReadCount() { + QSqlQuery query(m_db); + if (!query.exec(QStringLiteral("SELECT COUNT(*) FROM sync_read s" + " WHERE NOT EXISTS (SELECT 1 FROM items i WHERE i.guid = s.guid)")) + || !query.next()) + return fail(query.lastError().text()), -1; + return query.value(0).toInt(); +} + +QList Store::savedViews() { + m_error.clear(); + QList result; + QSqlQuery query(m_db); + if (!query.exec(QStringLiteral("SELECT id, view, exclude FROM saved_views ORDER BY position, id"))) { + fail(query.lastError().text()); + return result; + } + while (query.next()) + result << SavedView{query.value(0).toString(), + QJsonDocument::fromJson(query.value(1).toString().toUtf8()).object(), + QJsonDocument::fromJson(query.value(2).toString().toUtf8()).toVariant().toStringList()}; + return result; +} + +bool Store::replaceSavedViews(const QList &views) { + QSqlQuery query(m_db); + if (!query.exec(QStringLiteral("DELETE FROM saved_views"))) + return fail(query.lastError().text()); + query.prepare(QStringLiteral("INSERT INTO saved_views (id, position, view, exclude) VALUES (?, ?, ?, ?)")); + for (qsizetype i = 0; i < views.size(); ++i) { + const SavedView &view = views.at(i); + query.addBindValue(view.id); + query.addBindValue(i); + query.addBindValue(QString::fromUtf8(QJsonDocument(view.view).toJson(QJsonDocument::Compact))); + query.addBindValue(jsonList(view.exclude)); + if (!query.exec()) + return fail(query.lastError().text()); + } + return true; +} diff --git a/desktop/src/store.h b/desktop/src/store.h index b037106..0f9b376 100644 --- a/desktop/src/store.h +++ b/desktop/src/store.h @@ -1,6 +1,8 @@ #pragma once #include +#include +#include #include #include #include @@ -57,6 +59,29 @@ struct Article { QString feedUrl; }; +// The npub the library pulls sync events for: a public key only, since +// Readstr reads them and never signs. Empty when none is set. +struct SyncAccount { + QString npub; + // 64 lowercase hex characters. + QString pubkey; + // The nprofile's relay hints, asked besides the configured relays. + QStringList relays; + // When a pull last reached a relay and was merged, invalid until one has. + QDateTime syncedAt; + // The created_at and the id of the last event applied, by d tag. + QHash applied; + QHash appliedIds; +}; + +// A saved view as kind 30406 carries it, without keywords.exclude, and the +// mute words that stay on this machine. +struct SavedView { + QString id; + QJsonObject view; + QStringList exclude; +}; + struct ArticleFilter { qint64 feedId = 0; bool unreadOnly = false; @@ -118,8 +143,9 @@ class Store { // Records a fetch attempt: validators on success, the reason on failure. bool recordFetch(qint64 id, const QString &etag, const QString &lastModified, const QString &error); // Adds new items and refreshes existing ones (same guid in the same feed) - // without touching their read and starred flags. Returns how many are new, - // or -1 on failure. + // without touching their read and starred flags. A new one is read when + // its guid is among the last synced read GUIDs. Returns how many are + // new, or -1 on failure. int saveItems(qint64 feedId, const QList &items); QList
articles(const ArticleFilter &filter); @@ -132,6 +158,29 @@ class Store { int markRead(const ArticleFilter &filter, qint64 upToId); bool setStarred(qint64 articleId, bool starred); + // Empty, with lastError() set, when it cannot be read. + SyncAccount syncAccount(); + // Sets the sync account. Another npub than the current one starts + // afresh, forgetting what was applied for the last. + bool setSyncAccount(const QString &npub, const QString &pubkey, const QStringList &relays); + // Forgets the account and what was pulled for it; subscriptions, read + // marks, and saved views stay. + bool clearSyncAccount(); + // Moves the d tag's watermark up to the event `createdAt` and + // `eventId`, never down, in NostrEvent::isNewerThan's order. + bool setSyncApplied(const QString &dTag, qint64 createdAt, const QString &eventId); + bool recordSynced(const QDateTime &time); + // Remembers `guids` in place of the last list and marks the unread + // articles with any of them read, as saveItems() does for articles that + // come later. Returns how many changed, or -1 on failure. + int applyReadGuids(const QStringList &guids); + // The remembered read GUIDs no article has yet, or -1 on failure. + int pendingReadCount(); + QList savedViews(); + // Meant for inside transaction(), like applyReadGuids(), so a failure + // part way rolls the delete back with the rest. + bool replaceSavedViews(const QList &views); + // Runs `work` in one transaction that commits when it returns true and // rolls back when it returns false, keeping its lastError(), or throws, // passing the exception on. `work` must @@ -149,6 +198,7 @@ class Store { bool fail(const QString &message); bool setFlag(const char *column, qint64 articleId, bool value); qint64 categoryId(const QString &name); + bool clearSyncState(); QString m_connection; QSqlDatabase m_db; diff --git a/desktop/src/sync.cpp b/desktop/src/sync.cpp new file mode 100644 index 0000000..f25188d --- /dev/null +++ b/desktop/src/sync.cpp @@ -0,0 +1,583 @@ +#include "sync.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "feedparser.h" +#include "fetcher.h" +#include "library.h" +#include "nip19.h" + +namespace Sync { +std::optional account(const QString &text) { + const auto profile = Nip19::decodeProfile(text.trimmed()); + if (!profile) + return std::nullopt; + SyncAccount account; + account.pubkey = profile->pubkey; + account.npub = Nip19::npub(profile->pubkey); + account.relays = profile->relays; + return account; +} + +NostrQuery query(const SyncAccount &account) { + NostrQuery query; + query.author = account.pubkey; + query.kinds = {subscriptionsKind, readStatusKind, viewsKind}; + // Only the pairs the web app publishes, so an event of one kind with + // another's d tag cannot fill the byte cap and push the real one out. + query.dTags = {{subscriptionsKind, QString::fromLatin1(subscriptionsTag)}, + {readStatusKind, QString::fromLatin1(readStatusTag)}, + {viewsKind, QString::fromLatin1(viewsTag)}}; + // No small limit: a relay that keeps old versions sends them too, newest + // first, and the pool keeps only the newest of each. + query.limit = 100; + query.extraRelays = account.relays; + query.maxContentLength = maxContentLength; + return query; +} + +RelayPool::Limits limits() { + RelayPool::Limits limits; + // UTF-8 takes at most three bytes per UTF-16 unit of content. + limits.maxMessageBytes = 3 * maxContentLength + 256 * 1024; + limits.maxBytesPerQuery = 3 * 2 * (maxContentLength + NostrEvent::maxTagCharacters + 4096); + return limits; +} + +namespace { +// Schema checks in the web app's zod terms: a field that is present must +// have the right type and fit its caps, or the whole payload is refused. +bool isString(const QJsonValue &value, int maxLength) { + return value.isString() && value.toString().size() <= maxLength; +} + +bool optionalString(const QJsonObject &object, const char *key, int maxLength) { + return !object.contains(QLatin1String(key)) || isString(object.value(QLatin1String(key)), maxLength); +} + +bool stringArray(const QJsonValue &value, int maxCount, int maxLength, QStringList *out = nullptr) { + if (!value.isArray()) + return false; + const QJsonArray array = value.toArray(); + if (array.size() > maxCount) + return false; + for (const QJsonValue &item : array) { + if (!isString(item, maxLength)) + return false; + if (out) + *out << item.toString(); + } + return true; +} + +bool optionalStringArray(const QJsonObject &object, const char *key, int maxCount, int maxLength) { + return !object.contains(QLatin1String(key)) || stringArray(object.value(QLatin1String(key)), maxCount, maxLength); +} + +bool lastUpdatedFits(const QJsonObject &object) { + if (!object.contains(QLatin1String("lastUpdated"))) + return true; + const QJsonValue value = object.value(QLatin1String("lastUpdated")); + // zod's int() is a safe integer, and checking that first keeps the cast + // defined, which it is not for a double past qint64's range. + const double number = value.toDouble(); + return value.isDouble() && number >= 0 && number <= 9007199254740991.0 && std::trunc(number) == number; +} + +std::optional parseObject(const QString &content) { + QJsonParseError error; + const QJsonDocument document = QJsonDocument::fromJson(content.toUtf8(), &error); + if (error.error != QJsonParseError::NoError || !document.isObject()) + return std::nullopt; + return document.object(); +} + +struct SubscriptionList { + QStringList rss; + QStringList nostr; + // Feed (as listed) to category name. + QHash categories; +}; + +std::optional parseSubscriptions(const QString &content) { + const auto object = parseObject(content); + if (!object) + return std::nullopt; + SubscriptionList list; + if (!stringArray(object->value("rss"), maxFeeds, maxUrlLength, &list.rss) + || !stringArray(object->value("nostr"), maxFeeds, maxUrlLength, &list.nostr) + || !optionalStringArray(*object, "deleted", maxFeeds, maxUrlLength) || !lastUpdatedFits(*object)) + return std::nullopt; + if (object->contains("tags")) { + const QJsonValue tags = object->value("tags"); + if (!tags.isObject() || tags.toObject().size() > maxFeeds) + return std::nullopt; + const QJsonObject map = tags.toObject(); + for (auto it = map.begin(); it != map.end(); ++it) + if (it.key().size() > maxUrlLength || !stringArray(it.value(), maxTagsPerFeed, 256)) + return std::nullopt; + } + if (object->contains("categories")) { + const QJsonValue categories = object->value("categories"); + if (!categories.isObject() || categories.toObject().size() > maxFeeds) + return std::nullopt; + const QJsonObject map = categories.toObject(); + for (auto it = map.begin(); it != map.end(); ++it) { + if (it.key().size() > maxUrlLength || !it.value().isObject()) + return std::nullopt; + const QJsonObject category = it.value().toObject(); + if (!isString(category.value("name"), 256) || !optionalString(category, "color", 64) + || !optionalString(category, "icon", 256)) + return std::nullopt; + list.categories.insert(it.key(), category.value("name").toString()); + } + } + return list; +} + +std::optional parseReadStatus(const QString &content) { + const auto object = parseObject(content); + QStringList guids; + if (!object || !stringArray(object->value("itemGuids"), maxReadGuids, maxGuidLength, &guids) + || !lastUpdatedFits(*object)) + return std::nullopt; + return guids; +} + +// The web app's syncViewSchema, which lets unknown fields through. +bool viewFits(const QJsonValue &value) { + if (!value.isObject()) + return false; + const QJsonObject view = value.toObject(); + if (!isString(view.value("name"), 64) || !optionalString(view, "id", 256) || !optionalString(view, "icon", 8) + || !optionalString(view, "readState", 16) || !optionalString(view, "sort", 16) + || !optionalString(view, "organizationMode", 16)) + return false; + if (view.contains("order") && !view.value("order").isDouble()) + return false; + if (view.contains("source")) { + if (!view.value("source").isObject()) + return false; + const QJsonObject source = view.value("source").toObject(); + if (!isString(source.value("kind"), 32) || !optionalString(source, "feedId", 256) + || !optionalString(source, "categoryId", 256) || !optionalStringArray(source, "tags", maxFeeds, 256)) + return false; + } + if (view.contains("keywords")) { + if (!view.value("keywords").isObject()) + return false; + const QJsonObject keywords = view.value("keywords").toObject(); + if (!optionalStringArray(keywords, "include", maxFeeds, 256) + || !optionalStringArray(keywords, "exclude", maxFeeds, 256)) + return false; + } + return true; +} + +// sanitizeStrings in src/lib/saved-views.ts: strings only, each cut to 200 +// characters, empty ones dropped, at most 50. +QJsonArray sanitizeStrings(const QJsonValue &value) { + QJsonArray out; + for (const QJsonValue &item : value.toArray()) { + if (out.size() >= 50) + break; + const QString text = item.toString().left(200); + if (!text.isEmpty()) + out << text; + } + return out; +} + +QJsonObject sanitizeSource(const QJsonValue &value) { + const QJsonObject source = value.toObject(); + const QString kind = source.value("kind").toString(); + const QJsonObject all{{"kind", "all"}}; + if (kind == QLatin1String("feed")) { + const QString feedId = source.value("feedId").toString(); + return feedId.isEmpty() ? all : QJsonObject{{"kind", kind}, {"feedId", feedId}}; + } + if (kind == QLatin1String("tags")) { + const QJsonArray tags = sanitizeStrings(source.value("tags")); + return tags.isEmpty() ? all : QJsonObject{{"kind", kind}, {"tags", tags}}; + } + if (kind == QLatin1String("category")) { + const QString categoryId = source.value("categoryId").toString(); + return categoryId.isEmpty() ? all : QJsonObject{{"kind", kind}, {"categoryId", categoryId}}; + } + if (kind == QLatin1String("favorites")) + return QJsonObject{{"kind", kind}}; + return all; +} + +// The web app's sanitizeView gives a view without an id a random one, which +// it then publishes, so its next event carries it. The desktop never +// publishes, so a random id here would be new on every newer event and the +// view would pile up as copies; one derived from the view's place and name +// stays the same while the event does not change them. +QString derivedViewId(qsizetype index, const QString &name) { + const QByteArray hash = QCryptographicHash::hash(QString::number(index).toUtf8() + '\n' + name.toUtf8(), + QCryptographicHash::Sha256); + return QStringLiteral("synced-") + QString::fromLatin1(hash.toHex().left(16)); +} + +// sanitizeView in src/lib/saved-views.ts, less keywords.exclude, which a +// relay never gets to set here. `index` is the view's place in the event. +std::optional sanitizeView(const QJsonObject &raw, qsizetype index) { + const QString name = raw.value("name").toString().left(60).trimmed(); + if (name.isEmpty()) + return std::nullopt; + QString id = raw.value("id").toString(); + if (id.isEmpty()) + id = derivedViewId(index, name); + static const QStringList readStates{"all", "unread", "read"}, sorts{"newest", "oldest"}, + organizationModes{"tags", "categories"}; + const QString readState = raw.value("readState").toString(), sort = raw.value("sort").toString(); + const double order = raw.value("order").toDouble(); + QJsonObject view{{"id", id}, + {"name", name}, + {"order", order}, + {"source", sanitizeSource(raw.value("source"))}, + {"readState", readStates.contains(readState) ? readState : QStringLiteral("all")}, + {"sort", sorts.contains(sort) ? sort : QStringLiteral("newest")}}; + const QString icon = raw.value("icon").toString(); + if (!icon.isEmpty()) + view.insert("icon", icon.left(8)); + const QJsonArray include = sanitizeStrings(raw.value("keywords").toObject().value("include")); + if (!include.isEmpty()) + view.insert("keywords", QJsonObject{{"include", include}}); + const QString organizationMode = raw.value("organizationMode").toString(); + if (organizationModes.contains(organizationMode)) + view.insert("organizationMode", organizationMode); + return SavedView{id, view, {}}; +} + +// normalizeViews: the first maxViews, in order, numbered again from 0. +QList normalize(QList views) { + if (views.size() > maxViews) + views.resize(maxViews); + std::stable_sort(views.begin(), views.end(), [](const SavedView &a, const SavedView &b) { + return a.view.value("order").toDouble() < b.view.value("order").toDouble(); + }); + for (qsizetype i = 0; i < views.size(); ++i) + views[i].view.insert("order", int(i)); + return views; +} + +std::optional> parseViews(const QString &content) { + const auto object = parseObject(content); + if (!object || !object->value("views").isArray() || !lastUpdatedFits(*object)) + return std::nullopt; + const QJsonArray array = object->value("views").toArray(); + if (array.size() > maxRemoteViews) + return std::nullopt; + for (const QJsonValue &value : array) + if (!viewFits(value)) + return std::nullopt; + QList views; + for (qsizetype i = 0; i < qMin(array.size(), maxViews); ++i) + if (const auto view = sanitizeView(array.at(i).toObject(), i)) + views << *view; + return normalize(views); +} + +// mergeViewLists: the remote views first, keeping each one's local mute +// words, then the local ones the remote lacks, since deletions do not sync. +QList mergeViews(const QList &local, const QList &remote) { + QHash excludes; + for (const SavedView &view : local) + excludes.insert(view.id, view.exclude); + QSet seen; + QList merged; + for (SavedView view : remote) { + if (seen.contains(view.id)) + continue; + seen.insert(view.id); + view.exclude = excludes.value(view.id); + merged << view; + } + for (const SavedView &view : local) { + if (seen.contains(view.id)) + continue; + seen.insert(view.id); + merged << view; + } + return normalize(merged); +} + +// Newer than the last event applied in the order the pool picks versions +// by, so a tie in created_at goes to the lower id, and the same event +// replayed is never newer than itself. +bool isFresh(const SyncAccount &account, const char *dTag, const NostrEvent &event) { + const QString key = QString::fromLatin1(dTag); + const auto applied = account.applied.constFind(key); + if (applied == account.applied.cend()) + return true; + NostrEvent last; + last.createdAt = *applied; + last.id = account.appliedIds.value(key); + return event.isNewerThan(last); +} + +QString tr(const char *text) { return QCoreApplication::translate("Sync", text); } +} + +Outcome apply(Store &store, const SyncAccount &account, const NostrResult &result, + const std::function &beforeWrites) { + Outcome outcome; + if (!result.ok()) { + outcome.error = result.error; + return outcome; + } + // The account may have changed (in the window or from the command + // line) while the relays were asked, and what came is not the new one's. + const SyncAccount current = store.syncAccount(); + if (!store.lastError().isEmpty()) { + outcome.error = store.lastError(); + return outcome; + } + const auto npubChanged = [&] { + outcome.error = tr("the npub changed during the pull"); + return outcome; + }; + if (current.pubkey != account.pubkey) + return npubChanged(); + // The pool kept the newest version per kind and d tag; each kind must + // come with its own d tag, as the web app asks for them in pairs. + const NostrEvent *subscriptions = nullptr, *readStatus = nullptr, *views = nullptr; + for (const NostrEvent &event : result.events) { + if (event.pubkey != account.pubkey) + continue; + const QString dTag = event.tag(QStringLiteral("d")); + if (event.kind == subscriptionsKind && dTag == QLatin1String(subscriptionsTag)) + subscriptions = &event; + else if (event.kind == readStatusKind && dTag == QLatin1String(readStatusTag)) + readStatus = &event; + else if (event.kind == viewsKind && dTag == QLatin1String(viewsTag)) + views = &event; + } + + if (beforeWrites) + beforeWrites(); + + bool refused = false; + const auto refuse = [&](int kind) { + refused = true; + if (kind == subscriptionsKind) + outcome.problems << tr("the subscription list does not fit the web app's format"); + else if (kind == readStatusKind) + outcome.problems << tr("the read status does not fit the web app's format"); + else + outcome.problems << tr("the saved views do not fit the web app's format"); + }; + + const auto storeFailed = [&] { + outcome.error = store.lastError(); + return outcome; + }; + // Another writer (the window and `readstr sync` on one library) may + // apply a newer event, or the account be stopped and set again, while + // this pull runs, so each kind is judged against the account as it is + // now: once before its event is parsed, which also decides whether a + // payload that does not fit is reported, and again inside the write's + // own transaction. False on a store failure. + bool changed = false; + const auto stillFresh = [&](const char *dTag, const NostrEvent &event, bool emptyLibrary, bool *fresh) { + const SyncAccount now = store.syncAccount(); + if (!store.lastError().isEmpty()) + return false; + changed = now.pubkey != account.pubkey; + *fresh = !changed && (emptyLibrary || isFresh(now, dTag, event)); + return true; + }; + + if (subscriptions) { + const QList feeds = store.feeds(); + if (!store.lastError().isEmpty()) + return storeFailed(); + // An empty library has nothing for an old list to roll back, so it + // takes the list whatever the watermark says, as the web app does. + bool fresh = false; + if (!stillFresh(subscriptionsTag, *subscriptions, feeds.isEmpty(), &fresh)) + return storeFailed(); + if (changed) + return npubChanged(); + if (fresh) { + if (const auto list = parseSubscriptions(subscriptions->content)) { + // The web app adds what is missing and never applies the + // `deleted` list, so neither does this. + QList outlines; + int local = 0; + for (const QString &url : list->rss) { + // Whoever holds the npub's key picks these URLs, and the + // window fetches a new feed at once, so one on this + // machine or the local network would let them send + // requests there. OPML import keeps them, since the user + // picked that file. + if (Fetcher::isLocalHost(QUrl(url, QUrl::StrictMode).host())) { + ++local; + continue; + } + outlines << Opml::Outline{{}, url, {}, FeedParser::cleanText(list->categories.value(url)), {}}; + } + for (const QString &npub : list->nostr) + outlines << Opml::Outline{{}, {}, npub, FeedParser::cleanText(list->categories.value(npub)), {}}; + const Library::Import imported = Library::importOutlines(store, outlines, [&](bool *proceed) { + const QList now = store.feeds(); + if (!store.lastError().isEmpty() + || !stillFresh(subscriptionsTag, *subscriptions, now.isEmpty(), proceed)) + return false; + return !*proceed + || store.setSyncApplied(QString::fromLatin1(subscriptionsTag), subscriptions->createdAt, + subscriptions->id); + }); + if (!imported.error.isEmpty()) { + outcome.error = imported.error; + return outcome; + } + if (changed) + return npubChanged(); + if (!imported.stopped) { + outcome.added = imported.added; + outcome.skipped = imported.skipped; + outcome.unsupported = imported.unsupported + local; + } + } else { + // Not marked applied, as on the web, so every sync says so + // until a list that fits replaces it. + refuse(subscriptionsKind); + } + } + } + + const auto freshNow = [&](const char *dTag, const NostrEvent *event, bool *fresh) { + *fresh = false; + return !event || stillFresh(dTag, *event, false, fresh); + }; + bool readStatusFresh = false; + if (!freshNow(readStatusTag, readStatus, &readStatusFresh)) + return storeFailed(); + if (changed) + return npubChanged(); + if (readStatusFresh) { + if (const auto guids = parseReadStatus(readStatus->content)) { + const bool saved = store.transaction([&] { + bool fresh = false; + if (!stillFresh(readStatusTag, *readStatus, false, &fresh)) + return false; + if (!fresh) + return true; + outcome.markedRead = store.applyReadGuids(*guids); + return outcome.markedRead >= 0 + && store.setSyncApplied(QString::fromLatin1(readStatusTag), readStatus->createdAt, readStatus->id); + }); + if (!saved) { + outcome.markedRead = 0; + return storeFailed(); + } + if (changed) + return npubChanged(); + } else { + refuse(readStatusKind); + } + } + + bool viewsFresh = false; + if (!freshNow(viewsTag, views, &viewsFresh)) + return storeFailed(); + if (changed) + return npubChanged(); + if (viewsFresh) { + if (const auto remote = parseViews(views->content)) { + const bool saved = store.transaction([&] { + bool fresh = false; + if (!stillFresh(viewsTag, *views, false, &fresh)) + return false; + if (!fresh) + return true; + const QList local = store.savedViews(); + return store.lastError().isEmpty() && store.replaceSavedViews(mergeViews(local, *remote)) + && store.setSyncApplied(QString::fromLatin1(viewsTag), views->createdAt, views->id); + }); + if (!saved) + return storeFailed(); + if (changed) + return npubChanged(); + } else { + refuse(viewsKind); + } + } + + // A kind whose only versions were past the size cap is refused as one + // that does not fit, since the web app refuses it the same way, but only + // when the newest of them would have been applied had it fit: one no + // newer than what is already applied is obsolete, as it is for a payload + // that fits, and must not fail every pull. + for (const NostrEvent &event : result.oversized) { + if (event.pubkey != account.pubkey) + continue; + const QString dTag = event.tag(QStringLiteral("d")); + const char *tag = nullptr; + if (event.kind == subscriptionsKind && dTag == QLatin1String(subscriptionsTag)) + tag = subscriptionsTag; + else if (event.kind == readStatusKind && dTag == QLatin1String(readStatusTag)) + tag = readStatusTag; + else if (event.kind == viewsKind && dTag == QLatin1String(viewsTag)) + tag = viewsTag; + if (!tag) + continue; + bool emptyLibrary = false; + if (event.kind == subscriptionsKind) { + emptyLibrary = store.feeds().isEmpty(); + if (!store.lastError().isEmpty()) + return storeFailed(); + } + bool fresh = false; + if (!stillFresh(tag, event, emptyLibrary, &fresh)) + return storeFailed(); + if (changed) + return npubChanged(); + if (fresh) + refuse(event.kind); + } + + // The pool stopped keeping events at its size cap, so a newer one may + // be missing. What came is still applied, as the watermarks keep it from + // rolling anything back, but the pull is not recorded as the last sync, + // so "Last synced" never claims one that missed something. + if (result.truncated) + outcome.problems << tr("the relays sent more than fits, so some sync events may be missing"); + + outcome.pendingRead = store.pendingReadCount(); + if (outcome.pendingRead < 0) + return storeFailed(); + const QList saved = store.savedViews(); + if (!store.lastError().isEmpty()) + return storeFailed(); + outcome.views = int(saved.size()); + // A refused payload leaves its kind as it was, so the pull is not + // recorded as the last sync either, though what did fit stays applied. + if (!result.truncated && !refused) { + // Under the same check, so a pull for an account stopped meanwhile + // never dates the next one's. + const bool recorded = store.transaction([&] { + const SyncAccount now = store.syncAccount(); + if (!store.lastError().isEmpty()) + return false; + changed = now.pubkey != account.pubkey; + return changed || store.recordSynced(QDateTime::currentDateTimeUtc()); + }); + if (!recorded) + return storeFailed(); + if (changed) + return npubChanged(); + } + return outcome; +} +} diff --git a/desktop/src/sync.h b/desktop/src/sync.h new file mode 100644 index 0000000..d60fc2f --- /dev/null +++ b/desktop/src/sync.h @@ -0,0 +1,78 @@ +#pragma once + +#include +#include +#include +#include + +#include "relaypool.h" +#include "store.h" + +// Read-only Nostr sync with the Readstr web app (src/lib/nostr-sync.ts): +// the replaceable events it publishes in cleartext for an npub, pulled and +// merged into the library the way the web app merges them. Nothing here +// signs or publishes. Every event is untrusted: RelayPool has checked its +// id, signature, author, kind, d tag, and date, and its content must also +// fit the web app's schema and caps, or that kind is refused whole, as the +// web app refuses it. +namespace Sync { +inline constexpr int subscriptionsKind = 30404; +inline constexpr int readStatusKind = 30405; +inline constexpr int viewsKind = 30406; +inline constexpr char subscriptionsTag[] = "readstr-subscriptions"; +inline constexpr char readStatusTag[] = "readstr-read-status"; +inline constexpr char viewsTag[] = "readstr-views"; + +// The web app's caps. Content past maxContentLength is passed over while +// the newest version is picked, so it never hides an older one that fits. +inline constexpr qsizetype maxContentLength = 8 * 1024 * 1024; +inline constexpr int maxFeeds = 5000; +inline constexpr int maxReadGuids = 100000; +inline constexpr int maxUrlLength = 2048; +inline constexpr int maxGuidLength = 256; +inline constexpr int maxTagsPerFeed = 100; +inline constexpr int maxRemoteViews = 100; +// How many saved views are kept, as the web app's normalizeViews keeps them. +inline constexpr int maxViews = 50; + +// The account for an npub or nprofile (with or without "nostr:"), with the +// nprofile's relay hints, or null. +std::optional account(const QString &text); +// One request for the account's three events. +NostrQuery query(const SyncAccount &account); +// RelayPool's limits, raised so the three events at their caps fit. +RelayPool::Limits limits(); + +struct Outcome { + // Subscriptions added, already there, and dropped for being neither an + // http(s) feed nor a valid npub, or for being on this machine or the + // local network. + int added = 0; + int skipped = 0; + int unsupported = 0; + // Articles marked read now, and read GUIDs kept for articles not here yet. + int markedRead = 0; + int pendingRead = 0; + // Saved views in the library after the merge. + int views = 0; + // The kinds refused, and why; the others still applied. + QStringList problems; + // Set when nothing could be pulled or saved. + QString error; +}; +// Merges what the relays returned for query(account) into the library. +// Each kind applies only when its event is newer than the last one applied +// (the subscription list also when there are no feeds yet, as on the web), +// and never removes a subscription or a read mark: subscriptions are only +// added, articles only marked read, and saved views added or updated, +// keeping their mute words (keywords.exclude), which never come from a +// relay. Like the web app's mergeViewLists, the merged views are cut to +// maxViews with the remote ones first, so a full remote list drops the +// views only here, and their mute words with them. A truncated result still +// applies, but counts as a problem and is not recorded as the last sync, and +// neither is one with a payload refused, though the kinds that fit apply. +// beforeWrites runs after the first freshness check and before any write; +// tests use it to commit a competing write in between. +Outcome apply(Store &store, const SyncAccount &account, const NostrResult &result, + const std::function &beforeWrites = {}); +} diff --git a/desktop/tests/fakerelay.h b/desktop/tests/fakerelay.h index 7c490b4..34c49dc 100644 --- a/desktop/tests/fakerelay.h +++ b/desktop/tests/fakerelay.h @@ -5,6 +5,9 @@ #include #include #include +#include +#include +#include #include #include #include @@ -33,14 +36,19 @@ class FakeRelay : public QWebSocketServer { QList events; bool silent = false; QString closeWith; - // Answers as an honest relay does instead: only the events of the - // filter's kinds, newest first, and no more than its limit. + // Answers as an honest relay does instead: for each filter, only the + // events of its kinds (and d tags, when it names them), newest first, + // and no more than its limit. bool honourFilters = false; + // Answers each REQ after this long, to keep a query out. + int delayMs = 0; // Closes the connection after answering this many REQs on it, once. int dropAfter = 0; // Closes the connection after the events of a REQ, before its EOSE. bool dropBeforeEose = false; + // The first filter of each REQ, and every filter of each. QList filters; + QList requests; QStringList closed; int connections = 0; @@ -56,13 +64,40 @@ class FakeRelay : public QWebSocketServer { if (type != QLatin1String("REQ")) return; filters << message.at(2).toObject(); + requests << QJsonArray(message); + requests.last().removeFirst(); + requests.last().removeFirst(); if (silent) return; + if (delayMs > 0) { + QTimer::singleShot(delayMs, this, [this, socket = QPointer(socket), message] { + if (socket) + respond(socket, message); + }); + return; + } + respond(socket, message); + } + + void respond(QWebSocket *socket, const QJsonArray &message) { + const QString id = message.at(1).toString(); if (!closeWith.isEmpty()) { send(socket, {"CLOSED", id, closeWith}); return; } - for (const QJsonValue &event : answer(message.at(2).toObject())) + QList answered; + if (!honourFilters) { + answered = events; + } else { + QSet sent; + for (qsizetype i = 2; i < message.size(); ++i) + for (const QJsonValue &event : answer(message.at(i).toObject())) + if (!sent.contains(event.toObject().value(QStringLiteral("id")).toString())) { + sent.insert(event.toObject().value(QStringLiteral("id")).toString()); + answered << event; + } + } + for (const QJsonValue &event : std::as_const(answered)) send(socket, {"EVENT", id, event}); if (dropBeforeEose) { socket->close(); @@ -76,8 +111,6 @@ class FakeRelay : public QWebSocketServer { } QList answer(const QJsonObject &filter) const { - if (!honourFilters) - return events; QList matching; const QJsonArray kinds = filter.value(QStringLiteral("kinds")).toArray(); // Authors and since as NIP-01 has them, before the limit, so an event @@ -85,12 +118,16 @@ class FakeRelay : public QWebSocketServer { const bool anyAuthor = !filter.contains(QStringLiteral("authors")); const QJsonArray authors = filter.value(QStringLiteral("authors")).toArray(); const qint64 since = filter.value(QStringLiteral("since")).toInteger(0); + const bool anyD = !filter.contains(QStringLiteral("#d")); + const QJsonArray dTags = filter.value(QStringLiteral("#d")).toArray(); for (const QJsonValue &event : events) { const QJsonObject object = event.toObject(); if (!anyAuthor && !authors.contains(object.value(QStringLiteral("pubkey")))) continue; if (object.value(QStringLiteral("created_at")).toInteger() < since) continue; + if (!anyD && !dTags.contains(dTag(object))) + continue; for (const QJsonValue &kind : kinds) if (kind.toInt() == object.value(QStringLiteral("kind")).toInt(-1)) { matching << event; @@ -107,6 +144,13 @@ class FakeRelay : public QWebSocketServer { return matching; } + static QJsonValue dTag(const QJsonObject &event) { + for (const QJsonValue &tag : event.value(QStringLiteral("tags")).toArray()) + if (tag.toArray().at(0).toString() == QLatin1String("d")) + return tag.toArray().at(1); + return QString(); + } + static void send(QWebSocket *socket, const QJsonArray &message) { socket->sendTextMessage(QString::fromUtf8(QJsonDocument(message).toJson(QJsonDocument::Compact))); } diff --git a/desktop/tests/readstr_tests.cpp b/desktop/tests/readstr_tests.cpp index ff9cf81..b8a41c7 100644 --- a/desktop/tests/readstr_tests.cpp +++ b/desktop/tests/readstr_tests.cpp @@ -60,6 +60,7 @@ #include "sanitizer.h" #include "sourcemodel.h" #include "store.h" +#include "sync.h" #include "theme.h" #include "thumbnails.h" #include "translator.h" @@ -376,12 +377,12 @@ private slots: { Store store; QVERIFY2(store.open(path), qPrintable(store.lastError())); - QCOMPARE(store.schemaVersion(), 4); + QCOMPARE(store.schemaVersion(), 5); QVERIFY(store.addFeed("https://a.example.com/feed", "A")); } Store again; QVERIFY2(again.open(path), qPrintable(again.lastError())); - QCOMPARE(again.schemaVersion(), 4); + QCOMPARE(again.schemaVersion(), 5); QCOMPARE(again.feeds().size(), 1); QSqlDatabase raw = QSqlDatabase::addDatabase("QSQLITE", "raw"); @@ -551,7 +552,7 @@ private slots: for (int i = 0; i < 8; ++i) threads << QThread::create([&failures, path] { Store store; - if (!store.open(path) || store.schemaVersion() != 4) { + if (!store.open(path) || store.schemaVersion() != 5) { qWarning("%s", qPrintable(store.lastError())); ++failures; } @@ -606,7 +607,7 @@ private slots: Store writer; QVERIFY2(writer.open(path), qPrintable(writer.lastError())); - QCOMPARE(writer.schemaVersion(), 4); + QCOMPARE(writer.schemaVersion(), 5); QCOMPARE(writer.articles({0, false, false, 0}).size(), workers * perRound); // A reader in the middle of a transaction neither blocks a writer @@ -1690,7 +1691,7 @@ private slots: strings << match.captured(1); } const QString source = QFileInfo(QFINDTESTDATA("../src/backend.cpp")).absolutePath(); - for (const char *name : {"backend.cpp", "sanitizer.cpp", "portalfilepicker.cpp"}) { + for (const char *name : {"backend.cpp", "sanitizer.cpp", "portalfilepicker.cpp", "sync.cpp"}) { QFile file(source + "/" + name); QVERIFY(file.open(QIODevice::ReadOnly)); for (const auto &match : cppString.globalMatch(QString::fromUtf8(file.readAll()))) @@ -4088,6 +4089,919 @@ private slots: QVERIFY2(backend.status().startsWith("1 new article"), qPrintable(backend.status())); } + // Sync + + void syncLogsInAndOutWithAnNpubOnly() + { + QTemporaryDir dir; + const EnvironmentGuard guard({"READSTR_HOME"}); + qputenv("READSTR_HOME", dir.path().toUtf8()); + const QString npub = syncNpub(); + QString out, err; + QCOMPARE(run({"sync"}, out, err), 1); + QVERIFY2(err.contains("sync login NPUB"), qPrintable(err)); + err.clear(); + QCOMPARE(run({"sync", "login", "npub1notreal"}, out, err), 1); + QVERIFY(err.contains("npub or nprofile")); + QCOMPARE(run({"sync", "login"}, out, err), 1); + QCOMPARE(run({"sync", "pull"}, out, err), 1); + QVERIFY(err.contains("unknown action")); + + // An nprofile is kept as its npub, with its public relay hints. + const QByteArray key = QByteArray::fromHex(Nip19::decodeProfile(npub)->pubkey.toLatin1()); + const QByteArray relay = "wss://relay.example.com"; + const QString nprofile = + bech32("nprofile", QByteArray(1, 0) + char(32) + key + char(1) + char(relay.size()) + relay); + out.clear(); + QCOMPARE(run({"sync", "login", "nostr:" + nprofile}, out, err), 0); + QVERIFY2(out.startsWith("Syncing with " + npub), qPrintable(out)); + { + Store store; + QVERIFY(store.open()); + const SyncAccount account = store.syncAccount(); + QCOMPARE(account.npub, npub); + QCOMPARE(account.pubkey, Nip19::decodeProfile(npub)->pubkey); + QCOMPARE(account.relays, QStringList{QString::fromLatin1(relay)}); + QVERIFY(!account.syncedAt.isValid()); + QCOMPARE(Sync::query(account).extraRelays, account.relays); + + // Another npub starts afresh; the same one keeps its watermarks. + QVERIFY(store.setSyncApplied(Sync::readStatusTag, 100, QString(64, '5'))); + QVERIFY(store.setSyncApplied(Sync::readStatusTag, 50, QString(64, '1'))); + // A tie in created_at goes to the lower id, never the higher. + QVERIFY(store.setSyncApplied(Sync::readStatusTag, 100, QString(64, '9'))); + QCOMPARE(store.syncAccount().appliedIds.value(Sync::readStatusTag), QString(64, '5')); + QVERIFY(store.setSyncApplied(Sync::readStatusTag, 100, QString(64, '3'))); + QCOMPARE(store.syncAccount().appliedIds.value(Sync::readStatusTag), QString(64, '3')); + QVERIFY(store.setSyncAccount(npub, account.pubkey, {})); + QCOMPARE(store.syncAccount().applied.value(Sync::readStatusTag), 100); + const QString other = Nip19::npub(QString(64, 'b')); + QVERIFY(store.setSyncAccount(other, QString(64, 'b'), {})); + QVERIFY(store.syncAccount().applied.isEmpty()); + // A pull for the account before is not merged into this one's. + QCOMPARE(Sync::apply(store, account, NostrResult()).error, QString("the npub changed during the pull")); + } + out.clear(); + QCOMPARE(run({"sync", "logout"}, out, err), 0); + QCOMPARE(out, "Stopped syncing with " + Nip19::npub(QString(64, 'b')) + "\n"); + out.clear(); + QCOMPARE(run({"sync", "logout"}, out, err), 0); + QCOMPARE(out, QString("Not syncing with any npub\n")); + Store store; + QVERIFY(store.open()); + QVERIFY(store.syncAccount().npub.isEmpty()); + } + + // The web app's three events, pulled and merged into a library that + // already has some of it: subscriptions only added (its `deleted` list + // ignored), articles only marked read, views kept with local mute words. + void syncPullsAndMergesEachKind() + { + const qint64 now = QDateTime::currentSecsSinceEpoch() - 3600; + QTemporaryDir dir; + FakeRelay relay; + const EnvironmentGuard guard({"READSTR_HOME", "READSTR_RELAYS"}); + qputenv("READSTR_HOME", dir.path().toUtf8()); + qputenv("READSTR_RELAYS", relay.url().toUtf8()); + const QString author = Nip19::npub(QString(64, 'c')); + qint64 existing = 0; + { + Store store; + QVERIFY(store.open()); + existing = store.addFeed("https://a.example.com/feed", "A"); + ParsedItem one, two, three; + one.guid = one.title = "g1"; + two.guid = two.title = "g2"; + three.guid = three.title = "g3"; + QCOMPARE(store.saveItems(existing, {one, two, three}), 3); + for (const Article &article : store.articles({})) + if (article.guid == "g3") + QVERIFY(store.setRead(article.id, true)); + } + relay.events = { + syncEvent(Sync::subscriptionsKind, Sync::subscriptionsTag, + {{"rss", QJsonArray{"https://A.example.com/feed/", "https://b.example.com/rss", + "javascript:alert(1)", "file:///etc/passwd"}}, + {"nostr", QJsonArray{author, "npub1bad"}}, + {"categories", QJsonObject{{"https://b.example.com/rss", QJsonObject{{"name", "News"}}}}}, + {"tags", QJsonObject{{author, QJsonArray{"nostr"}}}}, + {"deleted", QJsonArray{"https://a.example.com/feed"}}, + {"lastUpdated", now}}, + now), + syncEvent(Sync::readStatusKind, Sync::readStatusTag, {{"itemGuids", QJsonArray{"g1", "later"}}}, now), + syncEvent(Sync::viewsKind, Sync::viewsTag, + {{"views", QJsonArray{QJsonObject{{"id", "v1"}, + {"name", "Morning"}, + {"order", 3}, + {"source", QJsonObject{{"kind", "feed"}, {"feedId", "x"}}}, + {"keywords", QJsonObject{{"include", QJsonArray{"ai"}}, + {"exclude", QJsonArray{"leak"}}}}}, + QJsonObject{{"name", " "}}}}}, + now)}; + + QString out, err; + QCOMPARE(run({"sync", "login", syncNpub()}, out, err), 0); + out.clear(); + QCOMPARE(run({"sync", "--json"}, out, err), 0); + QVERIFY2(err.isEmpty(), qPrintable(err)); + QVERIFY(out.endsWith("}\n") && out.count('\n') == 1); + const QJsonObject json = QJsonDocument::fromJson(out.toUtf8()).object(); + QCOMPARE(json.keys(), (QStringList{"added", "errors", "markedRead", "npub", "pendingRead", "skipped", "syncedAt", + "unsupported", "views"})); + QCOMPARE(json.value("npub").toString(), syncNpub()); + QCOMPARE(json.value("added").toInt(), 2); + QCOMPARE(json.value("skipped").toInt(), 1); + QCOMPARE(json.value("unsupported").toInt(), 3); + QCOMPARE(json.value("markedRead").toInt(), 1); + QCOMPARE(json.value("pendingRead").toInt(), 1); + QCOMPARE(json.value("views").toInt(), 1); + QVERIFY(json.value("syncedAt").toString().endsWith('Z')); + QCOMPARE(json.value("errors").toArray(), QJsonArray()); + // One request for the three events, a filter for each kind and d tag. + QCOMPARE(relay.requests.size(), 1); + QCOMPARE(relay.requests.first().size(), 3); + const QList> pairs{ + {30404, "readstr-subscriptions"}, {30405, "readstr-read-status"}, {30406, "readstr-views"}}; + for (qsizetype i = 0; i < pairs.size(); ++i) { + const QJsonObject filter = relay.requests.first().at(i).toObject(); + QCOMPARE(filter.value("kinds").toArray(), QJsonArray{pairs.at(i).first}); + QCOMPARE(filter.value("#d").toArray(), QJsonArray{pairs.at(i).second}); + QCOMPARE(filter.value("limit").toInt(), 100); + } + + Store store; + QVERIFY(store.open()); + QHash feeds; + for (const Feed &feed : store.feeds()) + feeds.insert(feed.url, feed); + QCOMPARE(feeds.size(), 3); + QVERIFY(feeds.contains("https://a.example.com/feed")); + QCOMPARE(feeds.value("https://b.example.com/rss").category, QString("News")); + QVERIFY(feeds.contains(author)); + QHash read; + for (const Article &article : store.articles({})) + read.insert(article.guid, article.read); + QCOMPARE(read, (QHash{{"g1", true}, {"g2", false}, {"g3", true}})); + // A read article that arrives later comes in read. + ParsedItem later, other; + later.guid = later.title = "later"; + other.guid = other.title = "other"; + QCOMPARE(store.saveItems(feeds.value("https://b.example.com/rss").id, {later, other}), 2); + for (const Article &article : store.articles({})) + if (article.guid == "later" || article.guid == "other") + QCOMPARE(article.read, article.guid == "later"); + QCOMPARE(store.pendingReadCount(), 0); + + QList views = store.savedViews(); + QCOMPARE(views.size(), 1); + QCOMPARE(views.first().id, QString("v1")); + QCOMPARE(views.first().view.value("name").toString(), QString("Morning")); + QCOMPARE(views.first().view.value("order").toInt(), 0); + QCOMPARE(views.first().view.value("keywords").toObject(), (QJsonObject{{"include", QJsonArray{"ai"}}})); + QVERIFY(views.first().exclude.isEmpty()); + + // The same events again change nothing, so a feed unsubscribed here + // stays gone and an article marked unread here stays unread. + QVERIFY(store.removeFeed(feeds.value("https://b.example.com/rss").id)); + for (const Article &article : store.articles({})) + if (article.guid == "g1") + QVERIFY(store.setRead(article.id, false)); + views.first().exclude = QStringList{"mute"}; + QVERIFY(store.replaceSavedViews(views)); + out.clear(); + QCOMPARE(run({"sync", "--json"}, out, err), 0); + const QJsonObject again = QJsonDocument::fromJson(out.toUtf8()).object(); + QCOMPARE(again.value("added").toInt(), 0); + QCOMPARE(again.value("markedRead").toInt(), 0); + QCOMPARE(store.feeds().size(), 2); + + // Newer ones apply: a view renamed keeps its local mute words, and a + // local view the remote lacks stays. + views << SavedView{"local", QJsonObject{{"id", "local"}, {"name", "Mine"}, {"order", 1}}, {}}; + QVERIFY(store.replaceSavedViews(views)); + relay.events = { + syncEvent(Sync::readStatusKind, Sync::readStatusTag, {{"itemGuids", QJsonArray{"g2"}}}, now + 10), + syncEvent(Sync::viewsKind, Sync::viewsTag, + {{"views", QJsonArray{QJsonObject{{"id", "v1"}, {"name", "Evening"}, + {"keywords", QJsonObject{{"exclude", QJsonArray{"remote"}}}}}}}}, + now + 10)}; + out.clear(); + QCOMPARE(run({"sync"}, out, err), 0); + QVERIFY2(out.startsWith("Synced with " + syncNpub() + ": 0 feeds added"), qPrintable(out)); + read.clear(); + for (const Article &article : store.articles({})) + read.insert(article.guid, article.read); + QCOMPARE(read, (QHash{{"g1", false}, {"g2", true}, {"g3", true}})); + views = store.savedViews(); + QCOMPARE(views.size(), 2); + QCOMPARE(views.first().view.value("name").toString(), QString("Evening")); + QVERIFY(!views.first().view.contains("keywords")); + QCOMPARE(views.first().exclude, QStringList{"mute"}); + QCOMPARE(views.last().id, QString("local")); + } + + // RelayPool's checks hold for sync events: another author's, another + // kind's, another d tag's, and a forged one are never applied. + void syncRejectsEventsItDidNotAskFor() + { + const qint64 now = QDateTime::currentSecsSinceEpoch() - 3600; + QTemporaryDir dir; + FakeRelay relay, forger; + const EnvironmentGuard guard({"READSTR_HOME", "READSTR_RELAYS"}); + qputenv("READSTR_HOME", dir.path().toUtf8()); + qputenv("READSTR_RELAYS", (relay.url() + "," + forger.url()).toUtf8()); + const QJsonObject list{{"rss", QJsonArray{"https://evil.example.com/feed"}}, {"nostr", QJsonArray()}}; + const QString content = QString::fromUtf8(QJsonDocument(list).toJson(QJsonDocument::Compact)); + relay.events = {signedEvent(Sync::subscriptionsKind, content, {{"d", Sync::subscriptionsTag}}, now, 2), + signedEvent(30023, content, {{"d", Sync::subscriptionsTag}}, now), + signedEvent(Sync::subscriptionsKind, content, {{"d", "other"}}, now), + signedEvent(Sync::readStatusKind, content, {{"d", Sync::subscriptionsTag}}, now), + syncEvent(Sync::readStatusKind, Sync::readStatusTag, {{"itemGuids", QJsonArray{"g1"}}}, now)}; + QJsonObject forged = syncEvent(Sync::subscriptionsKind, Sync::subscriptionsTag, + {{"rss", QJsonArray()}, {"nostr", QJsonArray()}}, now + 5); + forged.insert("content", content); + forger.events = {forged}; + + QString out, err; + QCOMPARE(run({"sync", "login", syncNpub()}, out, err), 0); + out.clear(); + QCOMPARE(run({"sync", "--json"}, out, err), 0); + QVERIFY2(err.isEmpty(), qPrintable(err)); + const QJsonObject json = QJsonDocument::fromJson(out.toUtf8()).object(); + QCOMPARE(json.value("added").toInt(), 0); + QCOMPARE(json.value("pendingRead").toInt(), 1); + Store store; + QVERIFY(store.open()); + QVERIFY(store.feeds().isEmpty()); + QVERIFY(!store.syncAccount().applied.contains(Sync::subscriptionsTag)); + + // No relay answering is a failure, said on stderr. + relay.closeWith = "blocked: no"; + forger.closeWith = "blocked: no"; + out.clear(); + err.clear(); + QCOMPARE(run({"sync", "--json"}, out, err), 1); + QVERIFY2(err.contains("blocked: no"), qPrintable(err)); + QVERIFY(QJsonDocument::fromJson(out.toUtf8()).object().value("errors").toArray().first().toString().contains( + "blocked: no")); + } + + // Payloads past the web app's caps are refused whole and said so; an + // event dated days ahead, or too large, is passed over for the newest + // one that fits; and a list with nothing applied is tried again. + void syncEnforcesCapsAndDates() + { + const qint64 now = QDateTime::currentSecsSinceEpoch() - 3600; + QTemporaryDir dir; + FakeRelay relay; + const EnvironmentGuard guard({"READSTR_HOME", "READSTR_RELAYS"}); + qputenv("READSTR_HOME", dir.path().toUtf8()); + qputenv("READSTR_RELAYS", relay.url().toUtf8()); + QJsonArray tooMany; + for (int i = 0; i <= Sync::maxFeeds; ++i) + tooMany << QStringLiteral("https://f%1.example.com/feed").arg(i); + QJsonArray views; + for (int i = 0; i <= Sync::maxRemoteViews; ++i) + views << QJsonObject{{"name", QString::number(i)}}; + relay.events = { + syncEvent(Sync::subscriptionsKind, Sync::subscriptionsTag, {{"rss", tooMany}, {"nostr", QJsonArray()}}, now), + syncEvent(Sync::readStatusKind, Sync::readStatusTag, + {{"itemGuids", QJsonArray{QString(Sync::maxGuidLength + 1, 'g')}}}, now), + syncEvent(Sync::viewsKind, Sync::viewsTag, {{"views", views}}, now)}; + + QString out, err; + QCOMPARE(run({"sync", "login", syncNpub()}, out, err), 0); + out.clear(); + QCOMPARE(run({"sync", "--json"}, out, err), 1); + for (const char *problem : {"subscription list", "read status", "saved views"}) + QVERIFY2(err.contains(problem), qPrintable(err)); + QCOMPARE(QJsonDocument::fromJson(out.toUtf8()).object().value("errors").toArray().size(), 3); + { + Store store; + QVERIFY(store.open()); + QVERIFY(store.feeds().isEmpty()); + QVERIFY(store.syncAccount().applied.isEmpty()); + } + + // Older events that fit, beside a newer one too large and one dated + // three days ahead. + relay.events = { + syncEvent(Sync::subscriptionsKind, Sync::subscriptionsTag, + {{"rss", QJsonArray{"https://ok.example.com/feed", "ftp://x.example.com/feed"}}, + {"nostr", QJsonArray()}}, + now), + syncEvent(Sync::subscriptionsKind, Sync::subscriptionsTag, + {{"rss", QJsonArray{"https://future.example.com/feed"}}, {"nostr", QJsonArray()}}, + QDateTime::currentSecsSinceEpoch() + 3 * 24 * 3600), + syncEvent(Sync::readStatusKind, Sync::readStatusTag, {{"itemGuids", QJsonArray{"small"}}}, now), + syncEvent(Sync::readStatusKind, Sync::readStatusTag, + {{"itemGuids", QJsonArray{"big"}}, {"padding", QString(Sync::maxContentLength, 'x')}}, now + 5)}; + out.clear(); + err.clear(); + QCOMPARE(run({"sync", "--json"}, out, err), 0); + QVERIFY2(err.isEmpty(), qPrintable(err)); + const QJsonObject json = QJsonDocument::fromJson(out.toUtf8()).object(); + QCOMPARE(json.value("added").toInt(), 1); + QCOMPARE(json.value("unsupported").toInt(), 1); + Store store; + QVERIFY(store.open()); + QCOMPARE(store.feeds().size(), 1); + QCOMPARE(store.feeds().first().url, QString("https://ok.example.com/feed")); + QCOMPARE(store.syncAccount().applied.value(Sync::readStatusTag), now); + } + + // Another writer on the same library (the window and `readstr sync`) + // may apply a newer event while a pull is out, or the npub be stopped + // and set again; the pull's events are judged against the library as it + // is when the pull writes, not as it was when the pull began. + void syncJudgesFreshnessWhenItWrites() + { + const qint64 now = QDateTime::currentSecsSinceEpoch() - 3600; + QTemporaryDir dir; + const QString path = dir.path() + "/readstr.db"; + Store store, other; + QVERIFY2(store.open(path), qPrintable(store.lastError())); + QVERIFY2(other.open(path), qPrintable(other.lastError())); + const SyncAccount login = *Sync::account(syncNpub()); + QVERIFY(store.setSyncAccount(login.npub, login.pubkey, {})); + // A library with feeds, so the subscription list's watermark counts. + QVERIFY(store.addFeed("https://a.invalid/feed", "A")); + const auto subscriptions = [](const char *url, qint64 at) { + return syncEvent(Sync::subscriptionsKind, Sync::subscriptionsTag, + {{"rss", QJsonArray{url}}, {"nostr", QJsonArray()}}, at); + }; + const auto read = [](const char *guid, qint64 at) { + return syncEvent(Sync::readStatusKind, Sync::readStatusTag, {{"itemGuids", QJsonArray{guid}}}, at); + }; + const auto views = [](const char *name, qint64 at) { + return syncEvent(Sync::viewsKind, Sync::viewsTag, + {{"views", QJsonArray{QJsonObject{{"id", "v"}, {"name", name}}}}}, at); + }; + + const SyncAccount stale = store.syncAccount(); + Sync::Outcome outcome = Sync::apply( + other, other.syncAccount(), + syncResult({subscriptions("https://new.invalid/feed", now + 20), read("new", now + 20), views("New", now + 20)})); + QVERIFY2(outcome.error.isEmpty() && outcome.problems.isEmpty(), qPrintable(outcome.error)); + QCOMPARE(outcome.added, 1); + // The pull that began before holds older versions and applies none. + outcome = Sync::apply( + store, stale, + syncResult({subscriptions("https://old.invalid/feed", now + 15), read("old", now + 15), views("Old", now + 15)})); + QVERIFY2(outcome.error.isEmpty() && outcome.problems.isEmpty(), qPrintable(outcome.error)); + QCOMPARE(outcome.added, 0); + QCOMPARE(outcome.markedRead, 0); + QCOMPARE(store.feeds().size(), 2); + QCOMPARE(store.savedViews().first().view.value("name").toString(), QString("New")); + QCOMPARE(store.syncAccount().applied.value(Sync::readStatusTag), now + 20); + ParsedItem oldItem, newItem; + oldItem.guid = oldItem.title = "old"; + newItem.guid = newItem.title = "new"; + QCOMPARE(store.saveItems(store.feeds().first().id, {oldItem, newItem}), 2); + for (const Article &article : store.articles({})) + QCOMPARE(article.read, article.guid == "new"); + + // Stopped and set again while a pull was out: what was applied for + // the npub before is forgotten, so the pull's events apply rather + // than being held to the old watermarks. + const SyncAccount before = store.syncAccount(); + QVERIFY(other.clearSyncAccount()); + QVERIFY(other.setSyncAccount(login.npub, login.pubkey, {})); + outcome = Sync::apply(store, before, syncResult({read("old", now + 10), views("Again", now + 10)})); + QVERIFY2(outcome.error.isEmpty() && outcome.problems.isEmpty(), qPrintable(outcome.error)); + QCOMPARE(outcome.markedRead, 1); + QCOMPARE(store.syncAccount().applied.value(Sync::readStatusTag), now + 10); + QCOMPARE(store.savedViews().first().view.value("name").toString(), QString("Again")); + QVERIFY(store.syncAccount().syncedAt.isValid()); + + // Stopped while a pull was out: nothing is applied or dated. + const SyncAccount gone = store.syncAccount(); + QVERIFY(other.clearSyncAccount()); + outcome = Sync::apply(store, gone, syncResult({views("Late", now + 30)})); + QCOMPARE(outcome.error, QString("the npub changed during the pull")); + QCOMPARE(store.savedViews().first().view.value("name").toString(), QString("Again")); + QVERIFY(store.syncAccount().npub.isEmpty()); + + // A newer event committed by the other writer after this pull's first + // check, but before it writes: the check inside each write refuses + // the pull's older events. + QVERIFY(store.setSyncAccount(login.npub, login.pubkey, {})); + QVERIFY(store.addFeed("https://b.invalid/feed", "B")); + const SyncAccount racing = store.syncAccount(); + const qsizetype feedsBefore = store.feeds().size(); + outcome = Sync::apply( + store, racing, + syncResult({subscriptions("https://race.invalid/feed", now + 50), read("race", now + 50), + views("Race", now + 50)}), + [&] { + const Sync::Outcome won = Sync::apply( + other, other.syncAccount(), + syncResult({subscriptions("https://won.invalid/feed", now + 60), read("won", now + 60), + views("Won", now + 60)})); + QVERIFY2(won.error.isEmpty() && won.problems.isEmpty(), qPrintable(won.error)); + }); + QVERIFY2(outcome.error.isEmpty() && outcome.problems.isEmpty(), qPrintable(outcome.error)); + QCOMPARE(outcome.added, 0); + QCOMPARE(store.feeds().size(), feedsBefore + 1); + for (const Feed &feed : store.feeds()) + QVERIFY(feed.url != "https://race.invalid/feed"); + QCOMPARE(store.savedViews().first().view.value("name").toString(), QString("Won")); + QCOMPARE(store.syncAccount().applied.value(Sync::readStatusTag), now + 60); + QCOMPARE(store.syncAccount().applied.value(Sync::subscriptionsTag), now + 60); + + // Stopped by the other writer between the first check and the writes: + // the import's gate sees it and nothing is added. + const SyncAccount stopping = store.syncAccount(); + outcome = Sync::apply(store, stopping, syncResult({subscriptions("https://late.invalid/feed", now + 70)}), + [&] { QVERIFY(other.clearSyncAccount()); }); + QCOMPARE(outcome.error, QString("the npub changed during the pull")); + for (const Feed &feed : store.feeds()) + QVERIFY(feed.url != "https://late.invalid/feed"); + + // Each kind is judged against the watermarks as they are when it is + // reached: while one newer is there, an older event and an older + // payload that does not fit are passed over unread, and once the + // account is stopped and set again after the pull's first check, + // both count, the payload being said not to fit. + QVERIFY(store.setSyncAccount(login.npub, login.pubkey, {})); + QVERIFY(store.setSyncApplied(Sync::readStatusTag, now + 20, QString(64, '0'))); + QVERIFY(store.setSyncApplied(Sync::viewsTag, now + 20, QString(64, '0'))); + const QJsonObject badViews = syncEvent(Sync::viewsKind, Sync::viewsTag, {{"views", "none"}}, now + 10); + outcome = Sync::apply(store, store.syncAccount(), syncResult({read("reset", now + 10), badViews})); + QVERIFY2(outcome.error.isEmpty() && outcome.problems.isEmpty(), qPrintable(outcome.problems.join("; "))); + QCOMPARE(store.syncAccount().applied.value(Sync::readStatusTag), now + 20); + outcome = Sync::apply(store, store.syncAccount(), syncResult({read("reset", now + 10), badViews}), [&] { + QVERIFY(other.clearSyncAccount()); + QVERIFY(other.setSyncAccount(login.npub, login.pubkey, {})); + }); + QVERIFY2(outcome.error.isEmpty(), qPrintable(outcome.error)); + QCOMPARE(outcome.problems, QStringList{"the saved views do not fit the web app's format"}); + QCOMPARE(store.syncAccount().applied.value(Sync::readStatusTag), now + 10); + } + + // Two versions in the same second are ordered by id, as the pool and + // NIP-01 order them: the lower id applies after the higher, and neither + // the higher nor the same event again applies after it. + void syncBreaksATieInCreatedAtById() + { + const qint64 now = QDateTime::currentSecsSinceEpoch() - 3600; + QTemporaryDir dir; + Store store; + QVERIFY2(store.open(dir.path() + "/readstr.db"), qPrintable(store.lastError())); + const SyncAccount account = *Sync::account(syncNpub()); + QVERIFY(store.setSyncAccount(account.npub, account.pubkey, {})); + QJsonObject low = syncEvent(Sync::readStatusKind, Sync::readStatusTag, {{"itemGuids", QJsonArray{"a"}}}, now); + QJsonObject high = syncEvent(Sync::readStatusKind, Sync::readStatusTag, {{"itemGuids", QJsonArray{"b"}}}, now); + if (high.value("id").toString() < low.value("id").toString()) + std::swap(low, high); + const auto applies = [&](const QJsonObject &event) { + const QString before = store.syncAccount().appliedIds.value(Sync::readStatusTag); + const Sync::Outcome outcome = Sync::apply(store, store.syncAccount(), syncResult({event})); + return outcome.error.isEmpty() && outcome.problems.isEmpty() + && store.syncAccount().appliedIds.value(Sync::readStatusTag) != before; + }; + QVERIFY(applies(high)); + QVERIFY(applies(low)); + QVERIFY(!applies(high)); + QVERIFY(!applies(low)); + QCOMPARE(store.syncAccount().appliedIds.value(Sync::readStatusTag), low.value("id").toString()); + QCOMPARE(store.syncAccount().applied.value(Sync::readStatusTag), now); + } + + // A payload refused for not fitting keeps the last sync's date, though + // the kinds beside it that fit apply; a pull with nothing refused, even + // one that finds no events, is dated as before. + void syncDoesNotDateAPullWithARefusal() + { + const qint64 now = QDateTime::currentSecsSinceEpoch() - 3600; + QTemporaryDir dir; + Store store; + QVERIFY2(store.open(dir.path() + "/readstr.db"), qPrintable(store.lastError())); + const SyncAccount account = *Sync::account(syncNpub()); + QVERIFY(store.setSyncAccount(account.npub, account.pubkey, {})); + Sync::Outcome outcome = Sync::apply( + store, store.syncAccount(), + syncResult({syncEvent(Sync::readStatusKind, Sync::readStatusTag, {{"itemGuids", QJsonArray{"g"}}}, now), + syncEvent(Sync::viewsKind, Sync::viewsTag, {{"views", "none"}}, now)})); + QVERIFY(outcome.error.isEmpty()); + QCOMPARE(outcome.problems, QStringList{"the saved views do not fit the web app's format"}); + QCOMPARE(outcome.pendingRead, 1); + QCOMPARE(store.syncAccount().applied.value(Sync::readStatusTag), now); + QVERIFY(!store.syncAccount().syncedAt.isValid()); + + outcome = Sync::apply(store, store.syncAccount(), syncResult({})); + QVERIFY(outcome.error.isEmpty() && outcome.problems.isEmpty()); + QVERIFY(store.syncAccount().syncedAt.isValid()); + } + + // An event past the size cap is passed over for an older one that fits, + // and refused, and said so, only when no version that fits came; author + // queries, which set no cap, keep events of any size. + void syncRefusesAnEventWithNoVersionThatFits() + { + const qint64 now = QDateTime::currentSecsSinceEpoch() - 3600; + FakeRelay relay; + const SyncAccount account = *Sync::account(syncNpub()); + const QString padding(200, 'x'); + relay.events = { + syncEvent(Sync::readStatusKind, Sync::readStatusTag, {{"itemGuids", QJsonArray{"small"}}}, now), + syncEvent(Sync::readStatusKind, Sync::readStatusTag, {{"itemGuids", QJsonArray{"big"}}, {"padding", padding}}, + now + 5), + syncEvent(Sync::viewsKind, Sync::viewsTag, {{"views", QJsonArray()}, {"padding", padding}}, now), + syncEvent(Sync::viewsKind, Sync::viewsTag, {{"views", QJsonArray()}, {"padding", padding}}, now + 5)}; + RelayPool pool; + pool.setLimits(Sync::limits()); + pool.setRelays({relay.url()}); + NostrQuery query = Sync::query(account); + query.maxContentLength = 150; + const NostrResult result = pool.query(query); + QVERIFY2(result.ok(), qPrintable(result.error)); + QCOMPARE(result.events.size(), 1); + QCOMPARE(result.events.first().createdAt, now); + QCOMPARE(result.oversized.size(), 1); + QCOMPARE(result.oversized.first().kind, Sync::viewsKind); + QCOMPARE(result.oversized.first().tag("d"), QString(Sync::viewsTag)); + QCOMPARE(result.oversized.first().id, relay.events.last().toObject().value("id").toString()); + QVERIFY(result.oversized.first().content.isEmpty()); + + query.maxContentLength = 0; + const NostrResult uncapped = pool.query(query); + QCOMPARE(uncapped.events.size(), 2); + QVERIFY(uncapped.oversized.isEmpty()); + + QTemporaryDir dir; + Store store; + QVERIFY2(store.open(dir.path() + "/readstr.db"), qPrintable(store.lastError())); + QVERIFY(store.setSyncAccount(account.npub, account.pubkey, {})); + const Sync::Outcome outcome = Sync::apply(store, store.syncAccount(), result); + QVERIFY(outcome.error.isEmpty()); + QCOMPARE(outcome.problems, QStringList{"the saved views do not fit the web app's format"}); + QCOMPARE(outcome.pendingRead, 1); + QVERIFY(!store.syncAccount().syncedAt.isValid()); + } + + // An oversized event no newer than what was already applied for its + // kind is obsolete, as one that fits would be, so it fails no pull; one + // newer than that, or any after the account starts afresh, is refused. + void syncRefusesOnlyAFreshOversizedEvent() + { + const qint64 now = QDateTime::currentSecsSinceEpoch() - 3600; + FakeRelay relay; + const SyncAccount account = *Sync::account(syncNpub()); + relay.events = {syncEvent(Sync::viewsKind, Sync::viewsTag, + {{"views", QJsonArray()}, {"padding", QString(200, 'x')}}, now)}; + RelayPool pool; + pool.setLimits(Sync::limits()); + pool.setRelays({relay.url()}); + NostrQuery query = Sync::query(account); + query.maxContentLength = 150; + const NostrResult result = pool.query(query); + QVERIFY2(result.ok(), qPrintable(result.error)); + QVERIFY(result.events.isEmpty()); + QCOMPARE(result.oversized.size(), 1); + QCOMPARE(result.oversized.first().createdAt, now); + + QTemporaryDir dir; + Store store; + QVERIFY2(store.open(dir.path() + "/readstr.db"), qPrintable(store.lastError())); + QVERIFY(store.setSyncAccount(account.npub, account.pubkey, {})); + QVERIFY(store.setSyncApplied(Sync::viewsTag, now + 100, QString(64, 'f'))); + Sync::Outcome outcome = Sync::apply(store, store.syncAccount(), result); + QVERIFY(outcome.error.isEmpty()); + QVERIFY2(outcome.problems.isEmpty(), qPrintable(outcome.problems.join("; "))); + QVERIFY(store.syncAccount().syncedAt.isValid()); + + QVERIFY(store.clearSyncAccount()); + QVERIFY(store.setSyncAccount(account.npub, account.pubkey, {})); + QVERIFY(store.setSyncApplied(Sync::viewsTag, now - 100, QString(64, 'f'))); + outcome = Sync::apply(store, store.syncAccount(), result); + QVERIFY(outcome.error.isEmpty()); + QCOMPARE(outcome.problems, QStringList{"the saved views do not fit the web app's format"}); + QVERIFY(!store.syncAccount().syncedAt.isValid()); + + QVERIFY(store.clearSyncAccount()); + QVERIFY(store.setSyncAccount(account.npub, account.pubkey, {})); + outcome = Sync::apply(store, store.syncAccount(), result); + QCOMPARE(outcome.problems, QStringList{"the saved views do not fit the web app's format"}); + QVERIFY(!store.syncAccount().syncedAt.isValid()); + } + + // Each kind and d tag pair is asked for with its own limit, so the old + // versions a relay keeps of one cannot crowd another out. + void syncGivesEachPairItsOwnLimit() + { + const qint64 now = QDateTime::currentSecsSinceEpoch() - 3600; + FakeRelay relay; + relay.honourFilters = true; + const SyncAccount account = *Sync::account(syncNpub()); + relay.events = { + syncEvent(Sync::subscriptionsKind, Sync::subscriptionsTag, {{"rss", QJsonArray()}, {"nostr", QJsonArray()}}, now)}; + for (int i = 1; i <= 3; ++i) + relay.events << syncEvent(Sync::readStatusKind, Sync::readStatusTag, + {{"itemGuids", QJsonArray{QString::number(i)}}}, now + i); + RelayPool pool; + pool.setLimits(Sync::limits()); + pool.setRelays({relay.url()}); + NostrQuery query = Sync::query(account); + query.limit = 2; + const NostrResult result = pool.query(query); + QVERIFY2(result.ok(), qPrintable(result.error)); + QHash kinds; + for (const NostrEvent &event : result.events) + kinds.insert(event.kind, event.createdAt); + QCOMPARE(kinds, (QHash{{Sync::subscriptionsKind, now}, {Sync::readStatusKind, now + 3}})); + } + + // Whoever holds the npub's key picks the synced feeds, which the window + // fetches at once, so none on this machine or the local network is + // added; OPML import, from a file the user picked, still takes them. + void syncLeavesOutLocalFeeds() + { + const qint64 now = QDateTime::currentSecsSinceEpoch() - 3600; + QTemporaryDir dir; + Store store; + QVERIFY2(store.open(dir.path() + "/readstr.db"), qPrintable(store.lastError())); + const SyncAccount account = *Sync::account(syncNpub()); + QVERIFY(store.setSyncAccount(account.npub, account.pubkey, {})); + const Sync::Outcome outcome = Sync::apply( + store, store.syncAccount(), + syncResult({syncEvent(Sync::subscriptionsKind, Sync::subscriptionsTag, + {{"rss", QJsonArray{"http://127.0.0.1:8080/feed", "http://192.168.1.2/rss", + "http://localhost/feed", "http://[::1]/feed", + "http://router/feed", "https://ok.invalid/feed"}}, + {"nostr", QJsonArray()}}, + now)})); + QVERIFY2(outcome.error.isEmpty() && outcome.problems.isEmpty(), qPrintable(outcome.error)); + QCOMPARE(outcome.added, 1); + QCOMPARE(outcome.unsupported, 5); + QCOMPARE(store.feeds().size(), 1); + QCOMPARE(store.feeds().first().url, QString("https://ok.invalid/feed")); + + const Library::Import imported = + Library::importOutlines(store, {Opml::Outline{{}, "http://127.0.0.1:8080/feed", {}, {}, {}}}); + QCOMPARE(imported.added, 1); + } + + // A lastUpdated past the safe integers, or with a fraction, is refused + // as zod refuses it, rather than cast (undefined for 1e300). + void syncRefusesAnUnsafeLastUpdated() + { + const qint64 now = QDateTime::currentSecsSinceEpoch() - 3600; + QTemporaryDir dir; + Store store; + QVERIFY2(store.open(dir.path() + "/readstr.db"), qPrintable(store.lastError())); + const SyncAccount account = *Sync::account(syncNpub()); + QVERIFY(store.setSyncAccount(account.npub, account.pubkey, {})); + for (const double lastUpdated : {1e300, 9007199254740992.0, 1.5, -1.0}) { + const Sync::Outcome outcome = Sync::apply( + store, store.syncAccount(), + syncResult({syncEvent(Sync::readStatusKind, Sync::readStatusTag, + {{"itemGuids", QJsonArray{"g"}}, {"lastUpdated", lastUpdated}}, now)})); + QVERIFY(outcome.error.isEmpty()); + QCOMPARE(outcome.problems, QStringList{"the read status does not fit the web app's format"}); + } + const Sync::Outcome outcome = Sync::apply( + store, store.syncAccount(), + syncResult({syncEvent(Sync::readStatusKind, Sync::readStatusTag, + {{"itemGuids", QJsonArray{"g"}}, {"lastUpdated", 9007199254740991.0}}, now)})); + QVERIFY(outcome.problems.isEmpty()); + QCOMPARE(outcome.pendingRead, 1); + } + + // A view without an id gets the same one from every newer event, so it + // is updated in place rather than piling up as copies. + void syncKeepsOneCopyOfAViewWithoutAnId() + { + const qint64 now = QDateTime::currentSecsSinceEpoch() - 3600; + QTemporaryDir dir; + Store store; + QVERIFY2(store.open(dir.path() + "/readstr.db"), qPrintable(store.lastError())); + const SyncAccount account = *Sync::account(syncNpub()); + QVERIFY(store.setSyncAccount(account.npub, account.pubkey, {})); + for (qint64 at : {now, now + 1, now + 2}) { + const Sync::Outcome outcome = Sync::apply( + store, store.syncAccount(), + syncResult({syncEvent(Sync::viewsKind, Sync::viewsTag, + {{"views", QJsonArray{QJsonObject{{"name", "Morning"}}}}}, at)})); + QVERIFY2(outcome.error.isEmpty() && outcome.problems.isEmpty(), qPrintable(outcome.error)); + QCOMPARE(outcome.views, 1); + } + QVERIFY(store.savedViews().first().id.startsWith("synced-")); + } + + // Only the kind and d tag pairs asked for are kept, so an event of one + // kind carrying another's d tag cannot fill the byte cap and push the + // real one out; a pull cut short anyway says so and is not dated. + void syncKeepsOnlyThePairsItAsksFor() + { + const qint64 now = QDateTime::currentSecsSinceEpoch() - 3600; + FakeRelay relay; + const SyncAccount account = *Sync::account(syncNpub()); + const QJsonObject real = + syncEvent(Sync::subscriptionsKind, Sync::subscriptionsTag, {{"rss", QJsonArray()}, {"nostr", QJsonArray()}}, now); + relay.events = {signedEvent(Sync::readStatusKind, QString(100000, 'x'), {{"d", Sync::subscriptionsTag}}, now + 5), + signedEvent(Sync::viewsKind, QString(100000, 'x'), {{"d", Sync::readStatusTag}}, now + 5), + real}; + RelayPool pool; + RelayPool::Limits limits = Sync::limits(); + limits.maxBytesPerQuery = 50000; + pool.setLimits(limits); + pool.setRelays({relay.url()}); + const NostrResult result = pool.query(Sync::query(account)); + QVERIFY2(result.ok(), qPrintable(result.error)); + QVERIFY(!result.truncated); + QCOMPARE(result.events.size(), 1); + QCOMPARE(result.events.first().id, real.value("id").toString()); + + QTemporaryDir dir; + Store store; + QVERIFY2(store.open(dir.path() + "/readstr.db"), qPrintable(store.lastError())); + QVERIFY(store.setSyncAccount(account.npub, account.pubkey, {})); + NostrResult truncated = syncResult({syncEvent(Sync::readStatusKind, Sync::readStatusTag, + {{"itemGuids", QJsonArray{"g"}}}, now)}); + truncated.truncated = true; + const Sync::Outcome outcome = Sync::apply(store, store.syncAccount(), truncated); + QVERIFY(outcome.error.isEmpty()); + QCOMPARE(outcome.problems, QStringList{"the relays sent more than fits, so some sync events may be missing"}); + QCOMPARE(outcome.pendingRead, 1); + QVERIFY(!store.syncAccount().syncedAt.isValid()); + } + + void syncMigratesALibraryFromVersionFour() + { + QTemporaryDir dir; + const QString path = dir.path() + "/readstr.db"; + { + QSqlDatabase raw = QSqlDatabase::addDatabase("QSQLITE", "v4"); + raw.setDatabaseName(path); + QVERIFY(raw.open()); + QSqlQuery query(raw); + QStringList statements = versionOneSchema(); + statements << "ALTER TABLE items ADD COLUMN address TEXT" + << "ALTER TABLE items ADD COLUMN revision INTEGER" + << "CREATE INDEX items_by_address ON items(feed_id, address) WHERE address IS NOT NULL" + << "ALTER TABLE feeds ADD COLUMN relay_hints TEXT" + << "ALTER TABLE feeds ADD COLUMN profile_revision INTEGER" + << "ALTER TABLE feeds ADD COLUMN profile_event_id TEXT" + << "ALTER TABLE feeds ADD COLUMN profile_title TEXT" + << "ALTER TABLE feeds ADD COLUMN complete_at INTEGER" + << "ALTER TABLE items ADD COLUMN media_url TEXT" + << "ALTER TABLE items ADD COLUMN thumbnail_url TEXT" + << "ALTER TABLE items ADD COLUMN duration REAL" + << "ALTER TABLE feeds ADD COLUMN incomplete INTEGER NOT NULL DEFAULT 0" + << "INSERT INTO feeds (url, url_key, title, created_at) VALUES ('https://a.example.com/feed'," + " 'a.example.com/feed', 'A', 1)" + << "INSERT INTO items (feed_id, guid, title, created_at, is_starred) VALUES (1, 'old', 'Old', 1, 1)" + << "PRAGMA user_version = 4"; + for (const QString &statement : statements) + QVERIFY2(query.exec(statement), qPrintable(query.lastError().text())); + query = QSqlQuery(); + raw.close(); + raw = QSqlDatabase(); + QSqlDatabase::removeDatabase("v4"); + } + Store store; + QVERIFY2(store.open(path), qPrintable(store.lastError())); + QCOMPARE(store.schemaVersion(), 5); + QCOMPARE(store.articles({}).first().title, QString("Old")); + QVERIFY(store.articles({}).first().starred); + const SyncAccount none = store.syncAccount(); + QVERIFY(store.lastError().isEmpty()); + QVERIFY(none.npub.isEmpty()); + QVERIFY(store.savedViews().isEmpty()); + QCOMPARE(store.applyReadGuids({"old", "new"}), 1); + QCOMPARE(store.pendingReadCount(), 1); + QVERIFY(store.articles({}).first().read); + QVERIFY(store.setSyncAccount(Nip19::npub(QString(64, 'a')), QString(64, 'a'), {})); + QVERIFY(store.recordSynced(QDateTime::currentDateTimeUtc())); + QVERIFY(store.syncAccount().syncedAt.isValid()); + } + + // The window pulls once the dialog sets an npub, and after a refresh of + // every feed, and says in the status bar what came of it. + void backendSyncsAfterLoginAndRefresh() + { + const qint64 now = QDateTime::currentSecsSinceEpoch() - 3600; + QTemporaryDir dir; + FakeRelay relay; + const EnvironmentGuard guard({"READSTR_HOME"}); + qputenv("READSTR_HOME", dir.path().toUtf8()); + // The account follows its own author, whose profile names the feed. + const QString author = syncNpub(); + relay.events = {syncEvent(Sync::subscriptionsKind, Sync::subscriptionsTag, + {{"rss", QJsonArray()}, {"nostr", QJsonArray{author}}}, now), + signedEvent(0, R"({"name":"me"})", {}, now)}; + + Backend backend; + backend.setRelays({relay.url()}); + QSignalSpy synced(&backend, &Backend::syncFinished); + QVERIFY(!backend.setSyncNpub("not an npub")); + QVERIFY(backend.syncNpub().isEmpty()); + QVERIFY(backend.setSyncNpub(syncNpub())); + QVERIFY(synced.wait(10000)); + QVERIFY2(backend.status().startsWith("Synced with Nostr: 1 feed"), qPrintable(backend.status())); + QVERIFY(!backend.statusError()); + QCOMPARE(backend.syncNpub(), syncNpub()); + QVERIFY(backend.syncedAt().isValid()); + // The feed it added is fetched at once. + QSignalSpy finished(&backend, &Backend::refreshFinished); + QVERIFY(finished.wait(10000)); + QCOMPARE(backend.feedCount(), 1); + + relay.closeWith = "blocked: no"; + backend.refreshAll(); + QVERIFY(synced.wait(10000)); + QVERIFY2(backend.status().startsWith("Cannot sync with Nostr: "), qPrintable(backend.status())); + QVERIFY(backend.statusError()); + + backend.stopSync(); + QTRY_VERIFY(backend.syncNpub().isEmpty()); + QVERIFY(backend.status().startsWith("Stopped syncing with npub1")); + } + + // A pull asked for while one is out runs once that one is done, rather + // than being dropped, and a refresh that ends during the first pull, + // with a feed that failed, keeps saying so when neither pull changes + // anything. + void backendPullsAgainForARequestDuringAPull() + { + QTemporaryDir dir; + FakeRelay relay; + FakeHttpServer server; + server.route("/feed", [](const FakeHttpServer::Request &) { return FakeHttpServer::Response{404, {}, {}}; }); + const EnvironmentGuard guard({"READSTR_HOME"}); + qputenv("READSTR_HOME", dir.path().toUtf8()); + { + Store store; + QVERIFY(store.open()); + QVERIFY(store.addFeed(server.url("/feed").toString(), "Broken")); + } + // Slow enough that the refresh ends while the first pull is out. + relay.delayMs = 500; + Backend backend; + backend.setRelays({relay.url()}); + QSignalSpy synced(&backend, &Backend::syncFinished); + bool asked = false; + connect(&backend, &Backend::syncChanged, &backend, [&] { + if (backend.syncing() && !std::exchange(asked, true)) + backend.refreshAll(); + }); + QVERIFY(backend.setSyncNpub(syncNpub())); + QVERIFY(synced.wait(10000)); + QCOMPARE(relay.requests.size(), 2); + QVERIFY2(backend.status().startsWith("Cannot refresh Broken"), qPrintable(backend.status())); + QVERIFY(backend.statusError()); + QVERIFY(!backend.syncing()); + QTest::qWait(800); + QCOMPARE(synced.count(), 1); + QCOMPARE(relay.requests.size(), 2); + } + + // A feed one account's pull added, whose fetch waited for the follow-up + // pull, is still fetched when the account changes during that follow-up + // and the new account's pull adds nothing. + void backendFetchesAFeedAddedBeforeTheAccountChanged() + { + const qint64 now = QDateTime::currentSecsSinceEpoch() - 3600; + QTemporaryDir dir; + FakeRelay relay; + const EnvironmentGuard guard({"READSTR_HOME"}); + qputenv("READSTR_HOME", dir.path().toUtf8()); + relay.events = {syncEvent(Sync::subscriptionsKind, Sync::subscriptionsTag, + {{"rss", QJsonArray()}, {"nostr", QJsonArray{syncNpub()}}}, now), + signedEvent(0, R"({"name":"me"})", {}, now)}; + relay.delayMs = 300; + const QString other = Nip19::npub(signedEvent(1, "", {}, 1, 2).value("pubkey").toString()); + Backend backend; + backend.setRelays({relay.url()}); + QSignalSpy synced(&backend, &Backend::syncFinished); + QSignalSpy finished(&backend, &Backend::refreshFinished); + // Counted as each pull starts, since syncChanged also says the + // account changed. + int pulls = 0; + bool wasSyncing = false; + connect(&backend, &Backend::syncChanged, &backend, [&] { + if (!backend.syncing() || std::exchange(wasSyncing, true)) { + wasSyncing = backend.syncing(); + return; + } + if (++pulls == 1) + QVERIFY(backend.setSyncNpub(syncNpub())); + else if (pulls == 2) + QVERIFY(backend.setSyncNpub(other)); + }); + QVERIFY(backend.setSyncNpub(syncNpub())); + QVERIFY(synced.wait(10000)); + QCOMPARE(pulls, 3); + QCOMPARE(backend.syncNpub(), other); + QVERIFY2(backend.status().startsWith("Synced with Nostr: 0 feeds"), qPrintable(backend.status())); + QCOMPARE(backend.feedCount(), 1); + QVERIFY(finished.wait(10000)); + Store store; + QVERIFY(store.open()); + QVERIFY(store.feeds().first().lastFetchedAt.isValid()); + } + // Markdown void markdownRendersTheAllowedSubset() @@ -4508,7 +5422,7 @@ private slots: } Store store; QVERIFY2(store.open(path), qPrintable(store.lastError())); - QCOMPARE(store.schemaVersion(), 4); + QCOMPARE(store.schemaVersion(), 5); QList
articles = store.articles({}); QCOMPARE(articles.size(), 1); QCOMPARE(articles.first().title, QString("Old")); @@ -4571,7 +5485,7 @@ private slots: } Store store; QVERIFY2(store.open(path), qPrintable(store.lastError())); - QCOMPARE(store.schemaVersion(), 4); + QCOMPARE(store.schemaVersion(), 5); const QList feeds = store.feeds(); QCOMPARE(feeds.size(), 2); for (const Feed &feed : feeds) { @@ -4881,7 +5795,7 @@ private slots: { Store store; QVERIFY2(store.open(path), qPrintable(store.lastError())); - QCOMPARE(store.schemaVersion(), 4); + QCOMPARE(store.schemaVersion(), 5); const QList feeds = store.feeds(); QCOMPARE(feeds.size(), 1); QCOMPARE(feeds.first().title, QString("Ada")); @@ -5641,6 +6555,28 @@ private slots: {"sig", QString::fromLatin1(QByteArray(reinterpret_cast(signature), 64).toHex())}}; } + // The test key's public key and npub, which the sync tests pull for. + static QString syncPubkey() { return signedEvent(1, "", {}, 1).value("pubkey").toString(); } + static QString syncNpub() { return Nip19::npub(syncPubkey()); } + + // A sync event as the web app publishes it: `content` as JSON, with its + // d tag and client tag. + static QJsonObject syncEvent(int kind, const char *dTag, const QJsonObject &content, qint64 createdAt) + { + return signedEvent(kind, QString::fromUtf8(QJsonDocument(content).toJson(QJsonDocument::Compact)), + {{"d", dTag}, {"client", "readstr"}}, createdAt); + } + + // What a relay that answered would hand Sync::apply for these events. + static NostrResult syncResult(const QList &events) + { + NostrResult result; + result.relays = result.answered = 1; + for (const QJsonObject &event : events) + result.events << *NostrEvent::fromJson(event); + return result; + } + // Restores the variables a test changes, so later tests see the original // environment even when a comparison fails part way. class EnvironmentGuard {