From 7917f11f1d10f1c147745a7199975b2403e25984 Mon Sep 17 00:00:00 2001 From: bleakgrey Date: Sat, 2 Jun 2018 10:43:54 +0300 Subject: [PATCH] Reconnect push notifications (close #34) --- src/NetManager.vala | 2 +- src/Notificator.vala | 36 ++++++++++++++++++++++++++++++------ 2 files changed, 31 insertions(+), 7 deletions(-) diff --git a/src/NetManager.vala b/src/NetManager.vala index fe1136a..d6b0cce 100644 --- a/src/NetManager.vala +++ b/src/NetManager.vala @@ -35,7 +35,7 @@ public class Tootle.NetManager : GLib.Object { GLib.Object(); } - public async WebsocketConnection stream (Soup.Message msg) { + public async WebsocketConnection stream (Soup.Message msg) throws GLib.Error { return yield session.websocket_connect_async (msg, null, null, null); } diff --git a/src/Notificator.vala b/src/Notificator.vala index ceb0522..bbafef4 100644 --- a/src/Notificator.vala +++ b/src/Notificator.vala @@ -3,8 +3,10 @@ using Soup; public class Tootle.Notificator : GLib.Object { - WebsocketConnection? connection; - Soup.Message msg; + private WebsocketConnection? connection; + private Soup.Message msg; + private bool closing = false; + private int timeout = 2; public abstract signal void notification (ref Notification notification); public abstract signal void status_added (ref Status status); @@ -17,17 +19,39 @@ public class Tootle.Notificator : GLib.Object { } public async void start () { - debug ("Starting notificator"); - connection = yield Tootle.network.stream (msg); - connection.error.connect (on_error); - connection.message.connect (on_message); + try { + debug ("Starting notificator"); + connection = yield Tootle.network.stream (msg); + connection.error.connect (on_error); + connection.message.connect (on_message); + connection.closed.connect (on_closed); + } + catch (GLib.Error e) { + warning (e.message); + on_closed (); + } } public void close () { debug ("Stopping notificator"); + closing = true; connection.close (0, null); } + private bool reconnect () { + start (); + return false; + } + + private void on_closed () { + if (closing) + return; + + debug ("Notificator aborted. Reconnecting in %i seconds.", timeout); + GLib.Timeout.add_seconds (timeout, reconnect); + timeout = int.min (timeout*2, 60); + } + private void on_error (Error e) { error (e.message); }