Skip to content

Commit 788a60d

Browse files
committed
Adapt to libsignal changes, moar async
1 parent 3d45a97 commit 788a60d

13 files changed

+152
-132
lines changed

Signal-Windows.Lib/IncomingMessages.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -197,7 +197,7 @@ private async Task HandleMessage(SignalServiceEnvelope envelope)
197197
var groups = content.SynchronizeMessage.Groups;
198198
using (var tmpFile = LibUtils.CreateTmpFile("groups_sync"))
199199
{
200-
var plaintextStream = MessageReceiver.RetrieveAttachment(groups.AsPointer(), tmpFile, 10000, null);
200+
var plaintextStream = await MessageReceiver.RetrieveAttachment(Token, groups.AsPointer(), tmpFile, 10000, null);
201201
var deviceGroupsStream = new DeviceGroupsInputStream(plaintextStream);
202202
var groupsList = new List<(SignalGroup, IList<string>)>();
203203
DeviceGroup g;
@@ -233,7 +233,7 @@ private async Task HandleMessage(SignalServiceEnvelope envelope)
233233
ContactsMessage contacts = content.SynchronizeMessage.Contacts;
234234
using (var tmpFile = LibUtils.CreateTmpFile("contacts_sync"))
235235
{
236-
var plaintextStream = MessageReceiver.RetrieveAttachment(contacts.Contacts.AsPointer(), tmpFile, 10000, null);
236+
var plaintextStream = await MessageReceiver.RetrieveAttachment(Token, contacts.Contacts.AsPointer(), tmpFile, 10000, null);
237237
var deviceContactsStream = new DeviceContactsInputStream(plaintextStream);
238238
List<SignalContact> contactsList = new List<SignalContact>();
239239
DeviceContact c;
@@ -577,7 +577,7 @@ private async Task HandleSignalMessage(SignalServiceEnvelope envelope, SignalSer
577577
Group = group,
578578
Timestamp = Util.CurrentTimeMillis()
579579
};
580-
SignalLibHandle.Instance.OutgoingMessages.SendMessage(envelope.GetSourceAddress(), requestInfoMessage);
580+
await SignalLibHandle.Instance.OutgoingMessages.SendMessage(envelope.GetSourceAddress(), requestInfoMessage);
581581
}
582582
composedTimestamp = envelope.GetTimestamp();
583583
}

Signal-Windows.Lib/OutgoingMessages.cs

Lines changed: 8 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -33,35 +33,29 @@ public OutgoingMessages(CancellationToken token, SignalServiceMessageSender send
3333
Handle = handle;
3434
}
3535

36-
public void SendMessage(List<SignalServiceAddress> recipients, SignalServiceDataMessage message)
36+
public async Task SendMessage(List<SignalServiceAddress> recipients, SignalServiceDataMessage message)
3737
{
38-
lock (this)
39-
{
40-
MessageSender.SendMessage(recipients, message);
41-
}
38+
await MessageSender.SendMessage(Token, recipients, message);
4239
}
4340

44-
public void SendMessage(SignalServiceAddress recipient, SignalServiceDataMessage message)
41+
public async Task SendMessage(SignalServiceAddress recipient, SignalServiceDataMessage message)
4542
{
46-
lock (this)
47-
{
48-
MessageSender.SendMessage(recipient, message);
49-
}
43+
await MessageSender.SendMessage(Token, recipient, message);
5044
}
5145

5246
public void SendMessage(SignalServiceAddress recipient, SignalServiceSyncMessage message)
5347
{
5448
lock (this)
5549
{
56-
MessageSender.SendMessage(message);
50+
MessageSender.SendMessage(Token, message);
5751
}
5852
}
5953

6054
public void SendMessage(SignalServiceSyncMessage message)
6155
{
6256
lock (this)
6357
{
64-
MessageSender.SendMessage(message);
58+
MessageSender.SendMessage(Token, message);
6559
}
6660
}
6761

@@ -85,7 +79,7 @@ public async Task HandleOutgoingMessages()
8579
{
8680
if (!Token.IsCancellationRequested)
8781
{
88-
MessageSender.SendMessage(new SignalServiceAddress(outgoingSignalMessage.ThreadId), message);
82+
await MessageSender.SendMessage(Token, new SignalServiceAddress(outgoingSignalMessage.ThreadId), message);
8983
outgoingSignalMessage.Status = SignalMessageStatus.Confirmed;
9084
}
9185
}
@@ -107,7 +101,7 @@ public async Task HandleOutgoingMessages()
107101
};
108102
if (!Token.IsCancellationRequested)
109103
{
110-
SendMessage(recipients, message);
104+
await SendMessage(recipients, message);
111105
outgoingSignalMessage.Status = SignalMessageStatus.Confirmed;
112106
}
113107
}

Signal-Windows.Lib/Signal-Windows.Lib.csproj

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -166,7 +166,7 @@
166166
</ItemGroup>
167167
<ItemGroup>
168168
<PackageReference Include="libsignal-service-dotnet">
169-
<Version>2.7.5.9</Version>
169+
<Version>2.7.5.11</Version>
170170
</PackageReference>
171171
<PackageReference Include="Microsoft.EntityFrameworkCore">
172172
<Version>1.1.4</Version>

Signal-Windows.Lib/SignalLibHandle.cs

Lines changed: 37 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -203,9 +203,9 @@ public async Task<bool> Acquire(CoreDispatcher d, ISignalFrontend w) //TODO wrap
203203
{
204204
LikelyHasValidStore = true;
205205
}
206-
var initNetwork = Task.Run(() =>
206+
var initNetwork = Task.Run(async () =>
207207
{
208-
InitNetwork();
208+
await InitNetwork();
209209
});
210210
var recoverDownloadsTask = Task.Run(() =>
211211
{
@@ -246,19 +246,35 @@ public async Task Reacquire()
246246
GlobalResetEvent.Reset();
247247
LibsignalDBContext.ClearSessionCache();
248248
Instance = this;
249-
await Task.Run(() =>
249+
await Task.Run(async () =>
250250
{
251251
List<Task> tasks = new List<Task>();
252252
foreach (var f in Frames)
253253
{
254254
var conversations = GetConversations();
255-
tasks.Add(f.Key.RunTaskAsync(() =>
255+
var taskCompletionSource = new TaskCompletionSource<bool>();
256+
await f.Key.RunAsync(CoreDispatcherPriority.Normal, () =>
256257
{
257-
f.Value.ReplaceConversationList(conversations);
258-
}));
258+
try
259+
{
260+
f.Value.ReplaceConversationList(conversations);
261+
}
262+
catch (Exception e)
263+
{
264+
Logger.LogError("Reacquire() ReplaceConversationList() failed: {0}\n{1}", e.Message, e.StackTrace);
265+
}
266+
finally
267+
{
268+
taskCompletionSource.SetResult(false);
269+
}
270+
});
271+
tasks.Add(taskCompletionSource.Task);
259272
}
260-
Task.WaitAll(tasks.ToArray());
261-
RecoverDownloads().Wait();
273+
foreach (var t in tasks)
274+
{
275+
await t;
276+
}
277+
await RecoverDownloads();
262278
Store = LibsignalDBContext.GetSignalStore();
263279
if (Store != null)
264280
{
@@ -267,9 +283,9 @@ await Task.Run(() =>
267283
});
268284
if (LikelyHasValidStore)
269285
{
270-
var initNetworkTask = Task.Run(() =>
286+
var initNetworkTask = Task.Run(async () =>
271287
{
272-
InitNetwork();
288+
await InitNetwork();
273289
});
274290
}
275291
Running = true;
@@ -429,14 +445,14 @@ public async Task SendBlockedMessage()
429445
public void StartAttachmentDownload(SignalAttachment sa)
430446
{
431447
//TODO lock, check if already downloading, start a new download if not exists
432-
Task.Run(() =>
448+
Task.Run(async () =>
433449
{
434450
try
435451
{
436452
Logger.LogTrace("StartAttachmentDownload() locking");
437453
SemaphoreSlim.Wait(CancelSource.Token);
438454
Logger.LogTrace("StartAttachmentDownload() locked");
439-
TryScheduleAttachmentDownload(sa);
455+
await TryScheduleAttachmentDownload(sa);
440456
}
441457
catch(Exception e)
442458
{
@@ -844,12 +860,12 @@ private List<SignalConversation> GetConversations()
844860
/// <summary>
845861
/// Initializes the websocket connection handling. Must not not be called on a UI thread. Must not be called on a task which holds the handle lock.
846862
/// </summary>
847-
private void InitNetwork()
863+
private async Task InitNetwork()
848864
{
849865
try
850866
{
851-
MessageReceiver = new SignalServiceMessageReceiver(CancelSource.Token, LibUtils.ServiceConfiguration, new StaticCredentialsProvider(Store.Username, Store.Password, Store.SignalingKey, (int)Store.DeviceId), LibUtils.USER_AGENT, null);
852-
Pipe = MessageReceiver.CreateMessagePipe();
867+
MessageReceiver = new SignalServiceMessageReceiver(LibUtils.ServiceConfiguration, new StaticCredentialsProvider(Store.Username, Store.Password, Store.SignalingKey, (int)Store.DeviceId), LibUtils.USER_AGENT, null);
868+
Pipe = await MessageReceiver.CreateMessagePipe(CancelSource.Token);
853869
MessageSender = new SignalServiceMessageSender(CancelSource.Token, LibUtils.ServiceConfiguration, Store.Username, Store.Password, (int)Store.DeviceId, new Store(), Pipe, null, LibUtils.USER_AGENT);
854870
IncomingMessagesTask = Task.Factory.StartNew(async () => await new IncomingMessages(CancelSource.Token, Pipe, MessageReceiver).HandleIncomingMessages(), TaskCreationOptions.LongRunning);
855871
OutgoingMessages = new OutgoingMessages(CancelSource.Token, MessageSender, this);
@@ -858,7 +874,7 @@ private void InitNetwork()
858874
catch(Exception e)
859875
{
860876
Logger.LogError("InitNetwork failed: {0}\n{1}", e.Message, e.StackTrace);
861-
HandleAuthFailure();
877+
await HandleAuthFailure();
862878
}
863879
}
864880

@@ -885,27 +901,27 @@ private async Task HandleAuthFailure()
885901
}
886902
}
887903

888-
private void TryScheduleAttachmentDownload(SignalAttachment attachment)
904+
private async Task TryScheduleAttachmentDownload(SignalAttachment attachment)
889905
{
890906
if (Downloads.Count < 100)
891907
{
892908
if (attachment.Status != SignalAttachmentStatus.Finished && !Downloads.ContainsKey(attachment.Id))
893909
{
894910
SignalServiceAttachmentPointer attachmentPointer = attachment.ToAttachmentPointer();
895911
IStorageFolder localFolder = ApplicationData.Current.LocalFolder;
896-
IStorageFile tmpDownload = Task.Run(async () =>
912+
IStorageFile tmpDownload = await Task.Run(async () =>
897913
{
898914
return await ApplicationData.Current.LocalCacheFolder.CreateFileAsync(@"Attachments\" + attachment.Id + ".cipher", CreationCollisionOption.ReplaceExisting);
899-
}).Result;
915+
});
900916
BackgroundDownloader downloader = new BackgroundDownloader();
901917
downloader.SetRequestHeader("Content-Type", "application/octet-stream");
902918
// this is the recommended way to call CreateDownload
903919
// see https://docs.microsoft.com/en-us/uwp/api/windows.networking.backgroundtransfer.backgrounddownloader#Methods
904-
DownloadOperation download = downloader.CreateDownload(new Uri(RetrieveAttachmentUrl(attachmentPointer)), tmpDownload);
920+
DownloadOperation download = downloader.CreateDownload(new Uri(await MessageReceiver.RetrieveAttachmentDownloadUrl(CancelSource.Token, attachmentPointer)), tmpDownload);
905921
attachment.Guid = download.Guid.ToString();
906922
SignalDBContext.UpdateAttachmentGuid(attachment);
907923
Downloads.Add(attachment.Id, download);
908-
Task.Run(async () =>
924+
var downloadSuccessfulHandler = Task.Run(async () =>
909925
{
910926
Logger.LogInformation("Waiting for download {0}({1})", attachment.SentFileName, attachment.Id);
911927
var t = await download.StartAsync();
@@ -947,11 +963,6 @@ private async Task HandleSuccessfullDownload(SignalAttachment attachment, IStora
947963
}
948964
}
949965

950-
private string RetrieveAttachmentUrl(SignalServiceAttachmentPointer pointer)
951-
{
952-
return MessageReceiver.RetrieveAttachmentDownloadUrl(pointer);
953-
}
954-
955966
private void DecryptAttachment(SignalServiceAttachmentPointer pointer, Stream ciphertextFileStream, Stream plaintextFileStream)
956967
{
957968
byte[] buf = new byte[32];

Signal-Windows.Lib/Storage/DB.cs

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
using System;
1515
using System.Collections.Generic;
1616
using System.Linq;
17+
using System.Threading;
1718
using System.Threading.Tasks;
1819

1920
namespace Signal_Windows.Storage
@@ -597,11 +598,11 @@ public static void RemoveSignedPreKey(uint id)
597598
}
598599
}
599600

600-
public static void RefreshPreKeys(SignalServiceAccountManager accountManager) //TODO wrap in extra lock? enforce reload?
601+
public static async Task RefreshPreKeys(CancellationToken token, SignalServiceAccountManager accountManager) //TODO wrap in extra lock? enforce reload?
601602
{
602603
List<PreKeyRecord> oneTimePreKeys = GeneratePreKeys();
603-
SignedPreKeyRecord signedPreKeyRecord = generateSignedPreKey(GetIdentityKeyPair());
604-
accountManager.SetPreKeys(GetIdentityKeyPair().getPublicKey(), signedPreKeyRecord, oneTimePreKeys);
604+
SignedPreKeyRecord signedPreKeyRecord = GenerateSignedPreKey(GetIdentityKeyPair());
605+
await accountManager.SetPreKeys(token, GetIdentityKeyPair().getPublicKey(), signedPreKeyRecord, oneTimePreKeys);
605606
}
606607

607608
private static List<PreKeyRecord> GeneratePreKeys()
@@ -620,7 +621,7 @@ private static List<PreKeyRecord> GeneratePreKeys()
620621
return records;
621622
}
622623

623-
private static PreKeyRecord getOrGenerateLastResortPreKey()
624+
private static PreKeyRecord GetOrGenerateLastResortPreKey()
624625
{
625626
if (ContainsPreKey(Medium.MAX_VALUE))
626627
{
@@ -639,7 +640,7 @@ private static PreKeyRecord getOrGenerateLastResortPreKey()
639640
return record;
640641
}
641642

642-
private static SignedPreKeyRecord generateSignedPreKey(IdentityKeyPair identityKeyPair)
643+
private static SignedPreKeyRecord GenerateSignedPreKey(IdentityKeyPair identityKeyPair)
643644
{
644645
try
645646
{

Signal-Windows.Lib/Storage/Store.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ public uint GetLocalRegistrationId()
1919

2020
public bool SaveIdentity(SignalProtocolAddress address, IdentityKey identityKey)
2121
{
22-
LibsignalDBContext.SaveIdentityLocked(address, Base64.EncodeBytes(identityKey.serialize()));
22+
LibsignalDBContext.SaveIdentityLocked(address, Base64.EncodeBytes(identityKey.serialize())).Wait(); //TODO wait is bad
2323
return true;
2424
}
2525

Signal-Windows.Lib/Util/LibUtils.cs

Lines changed: 0 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -18,53 +18,6 @@
1818

1919
namespace Signal_Windows.Lib
2020
{
21-
public static class DispatcherTaskExtensions
22-
{
23-
// Taken from https://github.com/Microsoft/Windows-task-snippets/blob/master/tasks/UI-thread-task-await-from-background-thread.md
24-
public static async Task<T> RunTaskAsync<T>(this CoreDispatcher dispatcher,
25-
Func<Task<T>> func, CoreDispatcherPriority priority = CoreDispatcherPriority.Normal)
26-
{
27-
var taskCompletionSource = new TaskCompletionSource<T>();
28-
await dispatcher.RunAsync(priority, async () =>
29-
{
30-
try
31-
{
32-
taskCompletionSource.SetResult(await func());
33-
}
34-
catch (Exception ex)
35-
{
36-
taskCompletionSource.SetException(ex);
37-
}
38-
});
39-
return await taskCompletionSource.Task;
40-
}
41-
42-
// There is no TaskCompletionSource<void> so we use a bool that we throw away.
43-
public static async Task RunTaskAsync(this CoreDispatcher dispatcher,
44-
Func<Task> func, CoreDispatcherPriority priority = CoreDispatcherPriority.Normal) =>
45-
await RunTaskAsync(dispatcher, async () => { await func(); return false; }, priority);
46-
47-
// We want to await
48-
public static async Task<bool> RunTaskAsync(this CoreDispatcher dispatcher,
49-
Action func, CoreDispatcherPriority priority = CoreDispatcherPriority.Normal)
50-
{
51-
var taskCompletionSource = new TaskCompletionSource<bool>();
52-
await dispatcher.RunAsync(priority, () =>
53-
{
54-
try
55-
{
56-
func();
57-
taskCompletionSource.SetResult(false);
58-
}
59-
catch (Exception ex)
60-
{
61-
taskCompletionSource.SetException(ex);
62-
}
63-
});
64-
return await taskCompletionSource.Task;
65-
}
66-
}
67-
6821
public class LibUtils
6922
{
7023
private static readonly ILogger Logger = LibsignalLogging.CreateLogger<LibUtils>();

0 commit comments

Comments
 (0)