/*
* rssnail (rss.snail.zone): when PC settings has an online account with
* its RSS reader turned on, the feeds are the ones followed there, read
* state goes both ways, and adding or unfollowing a source does it there.
* Without one, News follows its own feeds (news.ini) as before.
*
* The token comes from c8-accounts (org.cont8nuum.Accounts1), which
* refreshes it; a 401 hands the rejected one back for a new one, once.
* Requests are curl with the request on stdin, so the token isn't in the
* process list. The subscriptions and each feed's posts are kept in the
* cache, as feeds are, so stories show before the network answers.
*
* The first time an account is used, the feeds followed here that it
* doesn't have yet are added to it (once per account): switching to it
* shouldn't lose them.
*/
#include <gio/gio.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "json.h"
#include "news.h"
#include "http.h"
#define SERVICE "rssnail"
#define ACCOUNTS "org.cont8nuum.Accounts"
#define ACCOUNTS_PATH "/org/cont8nuum/Accounts"
#define ACCOUNTS_IFACE "org.cont8nuum.Accounts1"
#define POSTS "40" // per feed
bool news_synced;
static struct {
GDBusConnection *bus;
guint changed_sub;
char *account, *token, *api;
/* There's an account: its subscriptions are asked for. news_synced
* only once they came (or were in the cache), so News doesn't show
* an empty hub in between */
bool attached;
bool asking; // GetAccessToken is out
GPtrArray *waiting; // struct call, until there's a token
GPtrArray *feeds; // struct feed, while synced
news_remote_fn fn;
void *data;
bool syncing;
char *error; // the last thing that went wrong, for the Feeds page
bool told_sign_in; // that signing in again is needed
bool may_import; // the app does it, not the tile provider too
} rs;
/* Remembered between runs: the account last used, and the ones the
* local feeds were added to */
static char *state_path(void) {
return g_build_filename(g_get_user_data_dir(), "cont8nuum", "news",
"rssnail.ini", NULL);
}
static GKeyFile *state_load(void) {
GKeyFile *kf = g_key_file_new();
char *path = state_path();
g_key_file_load_from_file(kf, path, G_KEY_FILE_NONE, NULL);
g_free(path);
return kf;
}
static void state_save(GKeyFile *kf) {
char *path = state_path();
char *dir = g_path_get_dirname(path);
g_mkdir_with_parents(dir, 0700);
g_key_file_save_to_file(kf, path, NULL);
g_free(dir);
g_free(path);
}
static char *subs_path(void) {
return news_cache_path("rssnail-subscriptions.json");
}
/* loud: worth a dialog (it was asked for, or only the user can fix it);
* not: being offline, say, which the next refresh may mend */
/* For tests against a local mock, as c8-accounts allows */
static bool allow_http(void) {
return g_getenv("C8_ACCOUNTS_ALLOW_HTTP") != NULL;
}
static void tell(const char *error, bool loud) {
if (rs.fn) {
rs.fn(error, loud, rs.data);
}
}
static void set_error(const char *error) {
g_free(rs.error);
rs.error = g_strdup(error);
}
const char *rssnail_error(void) {
return rs.error;
}
/* Calls to the API */
typedef void (*api_fn)(int status, const char *body, void *data);
struct call {
char *method, *path, *body, *dest;
api_fn fn;
void *data;
bool retried;
};
static void call_free(struct call *c) {
g_free(c->method);
g_free(c->path);
g_free(c->body);
g_free(c->dest);
g_free(c);
}
static void get_token(const char *rejected);
static void call_run(struct call *c);
static void call_done(int status, const char *body, void *data) {
struct call *c = data;
if (status == 401 && !c->retried && rs.token) {
/* Ran out early, or was revoked: a new one, once */
c->retried = true;
char *rejected = g_steal_pointer(&rs.token);
g_ptr_array_add(rs.waiting, c);
get_token(rejected);
g_free(rejected);
return;
}
c->fn(status, body, c->data);
call_free(c);
}
/* Through c8-base's curl runner: the request on curl's stdin, so the
* token isn't in the process list */
static void call_run(struct call *c) {
char *url = g_strconcat(rs.api, c->path, NULL);
c8_http(&(struct c8_http){ .method = c->method, .url = url,
.body = c->body, .token = rs.token, .dest = c->dest,
.accept = "application/json", .agent = "c8-news/0.1 (cont8nuum)",
.allow_http = allow_http() }, call_done, c);
g_free(url);
}
/* dest: the answer goes to that file (fn gets body NULL); else fn gets it */
static void api(const char *method, const char *path, const char *body,
const char *dest, api_fn fn, void *data) {
struct call *c = g_new0(struct call, 1);
c->method = g_strdup(method);
c->path = g_strdup(path);
c->body = g_strdup(body);
c->dest = g_strdup(dest);
c->fn = fn;
c->data = data;
if (rs.token) {
call_run(c);
return;
}
g_ptr_array_add(rs.waiting, c);
get_token(NULL);
}
static void fail_waiting(void) {
GPtrArray *list = rs.waiting;
rs.waiting = g_ptr_array_new();
for (guint i = 0; i < list->len; i++) {
struct call *c = list->pdata[i];
c->fn(0, NULL, c->data);
call_free(c);
}
g_ptr_array_unref(list);
}
/* Feeds from the subscriptions */
static char *json_escape(const char *text) {
GString *out = g_string_new(NULL);
for (const unsigned char *p = (const unsigned char *)text; *p; p++) {
if (*p == '"' || *p == '\\') {
g_string_append_printf(out, "\\%c", *p);
} else if (*p < 0x20) {
g_string_append_printf(out, "\\u%04x", *p);
} else {
g_string_append_c(out, (char)*p);
}
}
return g_string_free(out, FALSE);
}
static int64_t num(struct json *j) {
return (int64_t)json_num(j, 0);
}
static struct feed *feed_by_remote(GPtrArray *list, int64_t id) {
for (guint i = 0; list && i < list->len; i++) {
struct feed *f = list->pdata[i];
if (f->remote == id) {
return f;
}
}
return NULL;
}
/* What the hub shows of a list of feeds: their order, names, addresses */
static char *signature(GPtrArray *list) {
GString *s = g_string_new(NULL);
for (guint i = 0; list && i < list->len; i++) {
struct feed *f = list->pdata[i];
g_string_append_printf(s, "%" G_GINT64_FORMAT "\n%s\n%s\n", f->remote,
f->name, f->url);
}
return g_string_free(s, FALSE);
}
/* The new list, reusing the feeds (and their stories) still in it;
* true if anything shown changed */
static bool take_subscriptions(struct json *list) {
GPtrArray *old = rs.feeds;
GPtrArray *now = g_ptr_array_new_with_free_func(news_feed_free);
char *before = old ? signature(old) : NULL;
for (int i = 0; i < json_length(list); i++) {
struct json *s = json_at(list, i);
int64_t id = num(json_get(s, "id"));
const char *url = json_str(json_get(s, "feed_url"), NULL);
if (id <= 0 || url == NULL || feed_by_remote(now, id)) {
continue;
}
const char *custom = json_str(json_get(s, "custom_title"), NULL);
const char *title = json_str(json_get(s, "feed_title"), NULL);
const char *name = custom && custom[0] ? custom : title && title[0] ?
title : url;
const char *site = json_str(json_get(s, "site_url"), NULL);
struct feed *f = NULL;
if (old) {
for (guint k = 0; k < old->len; k++) {
struct feed *o = old->pdata[k];
if (o->remote == id) {
/* Taken over: the old list mustn't free it */
f = g_ptr_array_steal_index(old, k);
break;
}
}
}
if (f == NULL) {
f = news_feed_new(url, name);
f->remote = id;
}
g_free(f->name);
f->name = g_strdup(name);
f->named = true; // the server's name, not the feed file's
g_free(f->url);
f->url = g_strdup(url);
if (site && site[0] && g_strcmp0(f->site, site) != 0) {
g_free(f->site);
f->site = g_strdup(site);
g_clear_pointer(&f->favicon, g_free);
}
g_ptr_array_add(now, f);
}
rs.feeds = now;
char *after = signature(now);
bool changed = before == NULL || strcmp(before, after) != 0;
g_free(before);
g_free(after);
if (news_synced) {
news_use_feeds(now);
}
if (old) {
g_ptr_array_unref(old); // what's left in it went
}
return changed;
}
static bool load_cached_subscriptions(void) {
char *path = subs_path(), *text = NULL;
bool ok = false;
if (g_file_get_contents(path, &text, NULL, NULL)) {
struct json *list = json_parse(text);
if (list && list->type == JSON_ARRAY) {
take_subscriptions(list);
ok = true;
}
json_free(list);
g_free(text);
}
g_free(path);
return ok;
}
static void import_local(struct json *subs);
static void got_subscriptions(int status, const char *body, void *data) {
rs.syncing = false;
if (!rs.attached) {
return;
}
struct json *list = status == 200 && body ? json_parse(body) : NULL;
if (list == NULL || list->type != JSON_ARRAY) {
json_free(list);
char *e = status ? g_strdup_printf("rssnail said %d", status) :
g_strdup("Couldn't reach rssnail");
set_error(e);
tell(e, false);
g_free(e);
return;
}
set_error(NULL);
char *path = subs_path();
char *dir = g_path_get_dirname(path);
g_mkdir_with_parents(dir, 0700);
g_file_set_contents(path, body, -1, NULL);
g_free(dir);
g_free(path);
import_local(list);
bool first = !news_synced;
news_synced = true;
if (take_subscriptions(list) || first) {
tell(NULL, false);
}
json_free(list);
}
void rssnail_sync(void) {
if (!rs.attached || rs.syncing) {
return;
}
rs.syncing = true;
api("GET", "/api/subscriptions", NULL, NULL, got_subscriptions, NULL);
}
/* Adding the feeds followed here to a new account, once */
static void imported_one(int status, const char *body, void *data) {
if (GPOINTER_TO_INT(data)) {
/* The last one: show them all */
rs.syncing = false;
rssnail_sync();
}
}
static void import_local(struct json *subs) {
if (!rs.may_import) {
return;
}
GKeyFile *kf = state_load();
char **done = g_key_file_get_string_list(kf, "rssnail", "imported", NULL,
NULL);
if (done && g_strv_contains((const char *const *)done, rs.account)) {
g_strfreev(done);
g_key_file_free(kf);
return;
}
GPtrArray *local = news_local_feeds();
GPtrArray *urls = g_ptr_array_new_with_free_func(g_free);
for (guint i = 0; i < local->len; i++) {
struct feed *f = local->pdata[i];
bool there = false;
for (int k = 0; k < json_length(subs) && !there; k++) {
const char *u = json_str(json_get(json_at(subs, k), "feed_url"), "");
there = strcmp(u, f->url) == 0;
}
if (!there) {
g_ptr_array_add(urls, g_strdup(f->url));
}
}
for (guint i = 0; i < urls->len; i++) {
char *esc = json_escape(urls->pdata[i]);
char *body = g_strdup_printf("{\"url\":\"%s\"}", esc);
/* The sync after the last shows them */
if (i + 1 == urls->len) {
rs.syncing = true;
}
api("POST", "/api/feeds", body, NULL, imported_one,
GINT_TO_POINTER(i + 1 == urls->len));
g_free(body);
g_free(esc);
}
g_ptr_array_unref(urls);
/* Remembered now: one that failed isn't tried again and again */
GPtrArray *list = g_ptr_array_new();
for (char **d = done; d && *d; d++) {
g_ptr_array_add(list, *d);
}
g_ptr_array_add(list, rs.account);
g_key_file_set_string_list(kf, "rssnail", "imported",
(const char *const *)list->pdata, list->len);
g_ptr_array_unref(list);
state_save(kf);
g_strfreev(done);
g_key_file_free(kf);
}
/* Becoming synced, or not */
/* The subscriptions and every feed's posts */
static void forget_cache(void) {
char *dir = news_cache_path("");
GDir *gd = g_dir_open(dir, 0, NULL);
const char *name;
while (gd && (name = g_dir_read_name(gd))) {
if (g_str_has_prefix(name, "rssnail-")) {
char *path = g_build_filename(dir, name, NULL);
g_unlink(path);
g_free(path);
}
}
if (gd) {
g_dir_close(gd);
}
g_free(dir);
}
static void detach(void) {
bool was = news_synced;
news_synced = false;
rs.attached = false;
g_clear_pointer(&rs.account, g_free);
g_clear_pointer(&rs.token, g_free);
g_clear_pointer(&rs.api, g_free);
set_error(NULL);
GKeyFile *kf = state_load();
g_key_file_remove_key(kf, "rssnail", "account", NULL);
g_key_file_remove_key(kf, "rssnail", "api", NULL);
state_save(kf);
g_key_file_free(kf);
forget_cache();
if (was) {
news_use_feeds(NULL);
tell(NULL, false); // the app lets go of the synced feeds here
}
g_clear_pointer(&rs.feeds, g_ptr_array_unref);
}
static void attach(const char *account) {
bool other = rs.account == NULL || strcmp(rs.account, account) != 0;
if (rs.attached && !other) {
return;
}
if (other && rs.feeds) {
/* Another account's feeds aren't this one's */
if (news_synced) {
news_synced = false;
news_use_feeds(NULL);
tell(NULL, false);
}
g_clear_pointer(&rs.feeds, g_ptr_array_unref);
forget_cache();
}
g_free(rs.account);
rs.account = g_strdup(account);
GKeyFile *kf = state_load();
g_key_file_set_string(kf, "rssnail", "account", account);
state_save(kf);
g_key_file_free(kf);
rs.attached = true;
rssnail_sync(); // news_synced when they come
}
/* Kept with the account: the cached posts' pictures are addresses on it,
* and they're read before c8-accounts has answered */
static void remember_api(void) {
GKeyFile *kf = state_load();
char *had = g_key_file_get_string(kf, "rssnail", "api", NULL);
if (g_strcmp0(had, rs.api) != 0) {
g_key_file_set_string(kf, "rssnail", "api", rs.api);
state_save(kf);
}
g_free(had);
g_key_file_free(kf);
}
static void got_token(GObject *source, GAsyncResult *res, gpointer data) {
rs.asking = false;
GError *error = NULL;
GVariant *r = g_dbus_connection_call_finish(G_DBUS_CONNECTION(source), res,
&error);
if (r == NULL) {
char *remote = g_dbus_error_get_remote_error(error);
g_dbus_error_strip_remote_error(error);
if (remote && (g_str_has_suffix(remote, ".NoAccount") ||
strcmp(remote, "org.freedesktop.DBus.Error.ServiceUnknown") == 0)) {
fail_waiting();
detach();
} else {
/* Sign in again, offline, wallet shut: keep what we have */
bool again = remote && g_str_has_suffix(remote, ".SignInNeeded");
/* Said once, not at every refresh */
bool loud = again && !rs.told_sign_in;
rs.told_sign_in |= again;
set_error(again ? "Sign in to your rssnail account again in PC "
"settings, under Online accounts." : error->message);
fail_waiting();
tell(rs.error, loud);
}
g_free(remote);
g_error_free(error);
return;
}
const char *account, *token, *api_url;
g_variant_get(r, "(&s&s&s)", &account, &token, &api_url);
if (!g_str_has_prefix(api_url, "https://") &&
!(allow_http() && g_str_has_prefix(api_url, "http://"))) {
g_variant_unref(r);
set_error("The rssnail account has no https address");
fail_waiting();
tell(rs.error, false);
return;
}
rs.told_sign_in = false;
g_free(rs.token);
rs.token = g_strdup(token);
g_free(rs.api);
rs.api = g_strdup(api_url);
char *acct = g_strdup(account);
g_variant_unref(r);
attach(acct);
g_free(acct);
remember_api();
/* attach may have run its own sync: now the rest */
GPtrArray *list = rs.waiting;
rs.waiting = g_ptr_array_new();
for (guint i = 0; i < list->len; i++) {
call_run(list->pdata[i]);
}
g_ptr_array_unref(list);
}
static void get_token(const char *rejected) {
if (rs.asking) {
return;
}
if (rs.bus == NULL) {
fail_waiting();
return;
}
rs.asking = true;
g_dbus_connection_call(rs.bus, ACCOUNTS, ACCOUNTS_PATH, ACCOUNTS_IFACE,
"GetAccessToken", g_variant_new("(ss)", SERVICE, rejected ? rejected : ""),
G_VARIANT_TYPE("(sss)"), G_DBUS_CALL_FLAGS_NONE, 60000, NULL, got_token,
NULL);
}
/* PC settings changed the accounts: is there one for us still? */
static void accounts_changed(GDBusConnection *c, const char *sender,
const char *path, const char *iface, const char *signal,
GVariant *params, gpointer data) {
g_clear_pointer(&rs.token, g_free);
get_token(NULL);
}
void rssnail_init(news_remote_fn fn, void *data, bool may_import) {
rs.may_import = may_import;
rs.fn = fn;
rs.data = data;
rs.waiting = g_ptr_array_new();
rs.bus = g_bus_get_sync(G_BUS_TYPE_SESSION, NULL, NULL);
if (rs.bus) {
rs.changed_sub = g_dbus_connection_signal_subscribe(rs.bus, NULL,
ACCOUNTS_IFACE, "Changed", ACCOUNTS_PATH, NULL,
G_DBUS_SIGNAL_FLAGS_NONE, accounts_changed, NULL, NULL);
}
/* Synced last time: those feeds at once, from the cache */
GKeyFile *kf = state_load();
char *account = g_key_file_get_string(kf, "rssnail", "account", NULL);
rs.api = g_key_file_get_string(kf, "rssnail", "api", NULL);
if (rs.api && !g_str_has_prefix(rs.api, "https://") && !(allow_http() &&
g_str_has_prefix(rs.api, "http://"))) {
g_clear_pointer(&rs.api, g_free);
}
g_key_file_free(kf);
if (account && load_cached_subscriptions()) {
rs.account = account;
rs.attached = true;
news_synced = true;
news_use_feeds(rs.feeds);
} else {
g_free(account);
}
get_token(NULL);
}
/* Posts */
struct posts {
struct feed *feed; // NULL once forgotten
fetch_fn fn;
void *data;
};
static void got_posts(int status, const char *body, void *data) {
struct posts *p = data;
p->fn(status, NULL, NULL, p->data);
g_free(p);
}
void rssnail_posts(struct feed *feed, const char *dest, fetch_fn fn,
void *data) {
if (!news_synced) {
fn(0, NULL, NULL, data);
return;
}
struct posts *p = g_new0(struct posts, 1);
p->feed = feed;
p->fn = fn;
p->data = data;
char *path = g_strdup_printf("/api/posts?subscription_id=%" G_GINT64_FORMAT
"&limit=" POSTS, feed->remote);
api("GET", path, NULL, dest, got_posts, p);
g_free(path);
}
static int64_t parse_time(const char *s) {
if (s == NULL || s[0] == '\0') {
return 0;
}
/* Times without a zone are the server's UTC */
GTimeZone *utc = g_time_zone_new_utc();
GDateTime *dt = g_date_time_new_from_iso8601(s, utc);
g_time_zone_unref(utc);
int64_t t = dt ? g_date_time_to_unix(dt) : 0;
if (dt) {
g_date_time_unref(dt);
}
return t;
}
/* A picture's address on rssnail (its image proxy: "/api/img/..."), NULL
* for one anywhere else: synced, the pictures come from rssnail too, not
* from the sites */
static char *absolute(const char *url) {
if (url == NULL || url[0] == '\0' || rs.api == NULL) {
return NULL;
}
char *abs = g_uri_resolve_relative(rs.api, url, G_URI_FLAGS_NONE, NULL);
size_t len = strlen(rs.api);
if (abs && !(strncmp(abs, rs.api, len) == 0 && (abs[len] == '/' ||
(len > 0 && rs.api[len - 1] == '/')))) {
g_clear_pointer(&abs, g_free);
}
return abs;
}
GPtrArray *rssnail_parse_posts(struct feed *feed, const char *text) {
struct json *root = json_parse(text);
struct json *items = json_get(root, "items");
if (items == NULL || items->type != JSON_ARRAY) {
json_free(root);
return NULL;
}
GPtrArray *stories = g_ptr_array_new();
for (int i = 0; i < json_length(items); i++) {
struct json *p = json_at(items, i);
int64_t id = num(json_get(p, "id"));
if (id <= 0) {
continue;
}
struct story *s = g_new0(struct story, 1);
s->feed = feed;
s->post = id;
s->id = g_strdup_printf("%" G_GINT64_FORMAT, id);
const char *title = json_str(json_get(p, "title"), NULL);
const char *summary = json_str(json_get(p, "summary"), NULL);
const char *full = json_str(json_get(p, "fulltext_html"), NULL);
const char *content = json_str(json_get(p, "content_html"), NULL);
const char *body = full && full[0] ? full : content && content[0] ?
content : summary;
char *html_image = NULL;
/* rssnail's own picture before the text's first (which it has
* pointed at its proxy as well); with one, the text is only
* parsed if the story is read */
s->image_url = absolute(json_str(json_get(p, "image_url"), NULL));
if (s->image_url) {
s->html = g_strdup(body);
} else {
s->markup = html_to_markup(body, &html_image);
s->image_url = absolute(html_image);
}
g_free(html_image);
s->summary = html_to_text(summary && summary[0] ? summary : body, 240);
s->title = title ? html_to_text(title, 300) : g_strdup("");
if (s->title[0] == '\0') {
g_free(s->title);
s->title = g_strdup(s->summary[0] ? s->summary : "Untitled");
}
s->link = g_strdup(json_str(json_get(p, "url"), NULL));
const char *author = json_str(json_get(p, "author"), NULL);
s->author = author && author[0] ? g_strdup(author) : NULL;
s->date = parse_time(json_str(json_get(p, "published_at"), NULL));
if (s->date == 0) {
s->date = parse_time(json_str(json_get(p, "fetched_at"), NULL));
}
s->read = json_bool(json_get(p, "is_read"));
g_ptr_array_add(stories, s);
}
json_free(root);
return stories;
}
/* Changes */
static void sent(int status, const char *body, void *data) {
if (status < 200 || status >= 300) {
char *e = status ? g_strdup_printf("rssnail said %d", status) :
g_strdup("Couldn't reach rssnail");
set_error(e);
tell(e, false);
g_free(e);
}
}
void rssnail_set_read(struct story *story) {
char *path = g_strdup_printf("/api/posts/%" G_GINT64_FORMAT "/state",
story->post);
api("POST", path, story->read ? "{\"is_read\":true}" :
"{\"is_read\":false}", NULL, sent, NULL);
g_free(path);
}
void rssnail_mark_all_read(void) {
api("POST", "/api/posts/mark_all", "{\"is_read\":true}", NULL, sent, NULL);
}
static void added(int status, const char *body, void *data) {
char *url = data;
if (status < 200 || status >= 300) {
struct json *j = body ? json_parse(body) : NULL;
const char *detail = json_str(json_get(j, "detail"), NULL);
char *e = detail ? g_strdup_printf("rssnail couldn't add %s: %s", url,
detail) : status ? g_strdup_printf("rssnail couldn't add %s (%d)",
url, status) : g_strdup("Couldn't reach rssnail");
json_free(j);
tell(e, true);
g_free(e);
} else {
rssnail_sync();
}
g_free(url);
}
void rssnail_add(const char *url) {
char *esc = json_escape(url);
char *body = g_strdup_printf("{\"url\":\"%s\"}", esc);
api("POST", "/api/feeds", body, NULL, added, g_strdup(url));
g_free(body);
g_free(esc);
}
static void removed(int status, const char *body, void *data) {
sent(status, body, data);
rssnail_sync(); // back again if it failed
}
void rssnail_remove(struct feed *feed) {
char *path = g_strdup_printf("/api/subscriptions/%" G_GINT64_FORMAT,
feed->remote);
api("DELETE", path, NULL, NULL, removed, NULL);
g_free(path);
/* Gone from here at once; the next sync agrees */
g_ptr_array_remove(rs.feeds, feed);
}