public void BackgroundAcquire()
 {
     CancelSource = new CancellationTokenSource();
     Instance     = this;
     SignalDBContext.FailAllPendingMessages();
     Store = LibsignalDBContext.GetSignalStore();
     InitNetwork();
     Running = true;
 }
        public async Task <bool> Acquire(CoreDispatcher d, ISignalFrontend w) //TODO wrap trycatch dispatch auth failure
        {
            Logger.LogTrace("Acquire() locking");
            CancelSource = new CancellationTokenSource();
            SemaphoreSlim.Wait(CancelSource.Token);
            try
            {
                GlobalResetEvent = LibUtils.OpenResetEventSet();
                LibUtils.Lock();
                GlobalResetEvent.Reset();
                MainWindowDispatcher = d;
                MainWindow           = w;
                Logger.LogDebug("Acquire() locked (global and local)");
                var getConversationsTask = Task.Run(() =>
                {
                    return(GetConversations()); // we want to display the conversations asap!
                });
                Instance = this;
                Frames.Add(d, w);
                w.ReplaceConversationList(await getConversationsTask);
                var failTask = Task.Run(() =>
                {
                    SignalDBContext.FailAllPendingMessages(); // TODO GetMessages needs to be protected by semaphoreslim as we fail defered
                });
                Store = await Task.Run(() =>
                {
                    return(LibsignalDBContext.GetSignalStore());
                });

                if (Store == null)
                {
                    return(false);
                }
                else
                {
                    LikelyHasValidStore = true;
                }
                var initNetwork = Task.Run(async() =>
                {
                    await InitNetwork();
                });
                var recoverDownloadsTask = Task.Run(() =>
                {
                    RecoverDownloads().Wait();
                });
                await failTask; // has to complete before messages are loaded
                await recoverDownloadsTask;
                Running = true;
                return(true);
            }
            finally
            {
                SemaphoreSlim.Release();
                Logger.LogTrace("Acquire() released");
            }
        }
        public async Task Acquire(CoreDispatcher d, ISignalFrontend w) //TODO wrap trycatch dispatch auth failure
        {
            Logger.LogTrace("Acquire() locking");
            CancelSource = new CancellationTokenSource();
            SemaphoreSlim.Wait(CancelSource.Token);
            GlobalResetEvent = LibUtils.OpenResetEventSet();
            LibUtils.Lock();
            GlobalResetEvent.Reset();
            var getConversationsTask = Task.Run(() =>
            {
                return(GetConversations()); // we want to display the conversations asap!
            });

            Logger.LogDebug("Acquire() locked (global and local)");
            Instance = this;
            Frames.Add(d, w);
            w.ReplaceConversationList(await getConversationsTask);
            var failTask = Task.Run(() =>
            {
                SignalDBContext.FailAllPendingMessages(); // TODO GetMessages needs to be protected by semaphoreslim as we fail defered
            });

            Store = await Task.Run(() =>
            {
                return(LibsignalDBContext.GetSignalStore());
            });

            if (Store == null)
            {
                SemaphoreSlim.Release();
                throw new Exception("Signal Store has not been setup yet.");
            }
            await Task.Run(() =>
            {
                InitNetwork();
            });

            await failTask; // has to complete before messages are loaded

            Running = true;
            Logger.LogTrace("Acquire() releasing");
            SemaphoreSlim.Release();
        }
 public async Task Init()
 {
     Debug.WriteLine("Init lock wait");
     using (await ActionInProgress.LockAsync(CancelSource.Token))
     {
         Debug.WriteLine("Init lock grabbed");
         Running      = true;
         CancelSource = new CancellationTokenSource();
         try
         {
             await Task.Run(async() =>
             {
                 SignalDBContext.FailAllPendingMessages();
                 List <SignalContact> contacts = SignalDBContext.GetAllContactsLocked();
                 List <SignalGroup> groups     = SignalDBContext.GetAllGroupsLocked();
                 await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                 {
                     try
                     {
                         int amountContacts = contacts.Count;
                         int amountGroups   = groups.Count;
                         int contactsIdx    = 0;
                         int groupsIdx      = 0;
                         while (contactsIdx < amountContacts || groupsIdx < amountGroups)
                         {
                             if (contactsIdx < amountContacts)
                             {
                                 SignalConversation contact = contacts[contactsIdx];
                                 if (groupsIdx < amountGroups)
                                 {
                                     SignalConversation group = groups[groupsIdx];
                                     if (contact.LastActiveTimestamp > group.LastActiveTimestamp)
                                     {
                                         contactsIdx++;
                                         AddThread(contact);
                                     }
                                     else
                                     {
                                         groupsIdx++;
                                         AddThread(group);
                                     }
                                 }
                                 else
                                 {
                                     contactsIdx++;
                                     AddThread(contact);
                                 }
                             }
                             else if (groupsIdx < amountGroups)
                             {
                                 SignalConversation group = groups[groupsIdx];
                                 groupsIdx++;
                                 AddThread(group);
                             }
                         }
                     }
                     catch (Exception e)
                     {
                         Debug.WriteLine(e.Message);
                         Debug.WriteLine(e.StackTrace);
                     }
                 });
                 MessageReceiver      = new SignalServiceMessageReceiver(CancelSource.Token, App.ServiceUrls, new StaticCredentialsProvider(App.Store.Username, App.Store.Password, App.Store.SignalingKey, (int)App.Store.DeviceId), App.USER_AGENT);
                 Pipe                 = MessageReceiver.createMessagePipe();
                 MessageSender        = new SignalServiceMessageSender(CancelSource.Token, App.ServiceUrls, App.Store.Username, App.Store.Password, (int)App.Store.DeviceId, new Store(), Pipe, null, App.USER_AGENT);
                 IncomingMessagesTask = Task.Factory.StartNew(HandleIncomingMessages, TaskCreationOptions.LongRunning);
                 OutgoingMessagesTask = Task.Factory.StartNew(HandleOutgoingMessages, TaskCreationOptions.LongRunning);
             });
         }
         catch (AuthorizationFailedException)
         {
             Debug.WriteLine("OWS server rejected our credentials - redirecting to StartPage");
             Running = false;
             CancelSource.Cancel();
             View.Frame.Navigate(typeof(StartPage));
         }
         catch (Exception e)
         {
             Debug.WriteLine(e.Message);
             Debug.WriteLine(e.StackTrace);
         }
     }
     Debug.WriteLine("Init lock released");
 }