Skip to content

Commit 9c65cc2

Browse files
committed
Support contact synchronization
1 parent c0d967c commit 9c65cc2

15 files changed

+224
-72
lines changed

Signal-Windows.Lib/IncomingMessages.cs

Lines changed: 98 additions & 42 deletions
Large diffs are not rendered by default.

Signal-Windows.Lib/OutgoingMessages.cs

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,22 @@ public void SendMessage(List<SignalServiceAddress> recipients, SignalServiceData
4141
}
4242
}
4343

44+
public void SendMessage(SignalServiceAddress recipient, SignalServiceDataMessage message)
45+
{
46+
lock (this)
47+
{
48+
MessageSender.SendMessage(recipient, message);
49+
}
50+
}
51+
52+
public void SendMessage(SignalServiceAddress recipient, SignalServiceSyncMessage message)
53+
{
54+
lock (this)
55+
{
56+
MessageSender.SendMessage(message);
57+
}
58+
}
59+
4460
public void SendMessage(SignalServiceSyncMessage message)
4561
{
4662
lock (this)
@@ -86,7 +102,7 @@ public void HandleOutgoingMessages()
86102
}
87103
message.Group = new SignalServiceGroup()
88104
{
89-
GroupId = Base64.decode(g.ThreadId),
105+
GroupId = Base64.Decode(g.ThreadId),
90106
Type = SignalServiceGroup.GroupType.DELIVER
91107
};
92108
if (!Token.IsCancellationRequested)
@@ -105,8 +121,8 @@ public void HandleOutgoingMessages()
105121
{
106122
outgoingSignalMessage.Status = SignalMessageStatus.Confirmed;
107123
Logger.LogError("HandleOutgoingMessages() encountered libsignal exceptions");
108-
IList<UntrustedIdentityException> identityExceptions = exceptions.getUntrustedIdentityExceptions();
109-
if (exceptions.getNetworkExceptions().Count > 0)
124+
IList<UntrustedIdentityException> identityExceptions = exceptions.UntrustedIdentityExceptions;
125+
if (exceptions.NetworkExceptions.Count > 0)
110126
{
111127
outgoingSignalMessage.Status = SignalMessageStatus.Failed_Network;
112128
}

Signal-Windows.Lib/SignalLibHandle.cs

Lines changed: 38 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,8 @@ public interface ISignalLibHandle
5353
{
5454
//Frontend API
5555
SignalStore Store { get; set; }
56+
57+
void RequestSync();
5658
Task SendMessage(SignalMessage message, SignalConversation conversation);
5759
Task SetMessageRead(long index, SignalMessage message, SignalConversation conversation);
5860
void ResendMessage(SignalMessage message);
@@ -89,7 +91,7 @@ internal class SignalLibHandle : ISignalLibHandle
8991
public SignalStore Store { get; set; }
9092
private readonly ILogger Logger = LibsignalLogging.CreateLogger<SignalLibHandle>();
9193
public SemaphoreSlim SemaphoreSlim = new SemaphoreSlim(1, 1);
92-
private bool Headless;
94+
private readonly bool Headless;
9395
private bool Running = false;
9496
private bool LikelyHasValidStore = false;
9597
private CancellationTokenSource CancelSource = new CancellationTokenSource();
@@ -331,6 +333,24 @@ await Task.Run(() =>
331333
});
332334
}
333335

336+
public void RequestSync()
337+
{
338+
Task.Run(() =>
339+
{
340+
Logger.LogTrace("RequestSync()");
341+
var contactsRequest = SignalServiceSyncMessage.ForRequest(new RequestMessage(new SyncMessage.Types.Request()
342+
{
343+
Type = SyncMessage.Types.Request.Types.Type.Contacts
344+
}));
345+
OutgoingMessages.SendMessage(contactsRequest);
346+
var groupsRequest = SignalServiceSyncMessage.ForRequest(new RequestMessage(new SyncMessage.Types.Request()
347+
{
348+
Type = SyncMessage.Types.Request.Types.Type.Groups
349+
}));
350+
OutgoingMessages.SendMessage(groupsRequest);
351+
});
352+
}
353+
334354
/// <summary>
335355
/// Marks and dispatches a message as read. Must not be called on a task which holds the handle lock.
336356
/// </summary>
@@ -456,6 +476,22 @@ internal void DispatchHandleIdentityKeyChange(LinkedList<SignalMessage> messages
456476
Task.WaitAll(operations.ToArray());
457477
}
458478

479+
internal void DispatchAddOrUpdateConversations(List<SignalContact> newConversations)
480+
{
481+
List<Task> operations = new List<Task>();
482+
foreach (var dispatcher in Frames.Keys)
483+
{
484+
operations.Add(dispatcher.RunTaskAsync(() =>
485+
{
486+
foreach (var contact in newConversations)
487+
{
488+
Frames[dispatcher].AddOrUpdateConversation(contact, null);
489+
}
490+
}));
491+
}
492+
Task.WaitAll(operations.ToArray());
493+
}
494+
459495
internal void DispatchAddOrUpdateConversation(SignalConversation conversation, SignalMessage updateMessage)
460496
{
461497
List<Task> operations = new List<Task>();
@@ -630,7 +666,7 @@ private void InitNetwork()
630666
MessageReceiver = new SignalServiceMessageReceiver(CancelSource.Token, LibUtils.ServiceConfiguration, new StaticCredentialsProvider(Store.Username, Store.Password, Store.SignalingKey, (int)Store.DeviceId), LibUtils.USER_AGENT, null);
631667
Pipe = MessageReceiver.CreateMessagePipe();
632668
MessageSender = new SignalServiceMessageSender(CancelSource.Token, LibUtils.ServiceConfiguration, Store.Username, Store.Password, (int)Store.DeviceId, new Store(), Pipe, null, LibUtils.USER_AGENT);
633-
IncomingMessagesTask = Task.Factory.StartNew(() => new IncomingMessages(CancelSource.Token, Pipe, this).HandleIncomingMessages(), TaskCreationOptions.LongRunning);
669+
IncomingMessagesTask = Task.Factory.StartNew(() => new IncomingMessages(CancelSource.Token, Pipe, MessageReceiver).HandleIncomingMessages(), TaskCreationOptions.LongRunning);
634670
OutgoingMessages = new OutgoingMessages(CancelSource.Token, MessageSender, this);
635671
OutgoingMessagesTask = Task.Factory.StartNew(() => OutgoingMessages.HandleOutgoingMessages(), TaskCreationOptions.LongRunning);
636672
}

Signal-Windows.Lib/SignalLogging.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -182,14 +182,14 @@ public static void ExportUILog(StorageFile file)
182182
var oldLog = File.OpenRead(ApplicationData.Current.LocalCacheFolder.Path + @"\Signal-Windows.ui.log.old");
183183
MoveFileContent(oldLog, writer);
184184
oldLog.Dispose();
185-
} catch (Exception e) { }
185+
} catch (Exception) { }
186186
try
187187
{
188188
var newLog = File.OpenRead(ApplicationData.Current.LocalCacheFolder.Path + @"\Signal-Windows.ui.log");
189189
MoveFileContent(newLog, writer);
190190
newLog.Dispose();
191191
}
192-
catch (Exception e) { }
192+
catch (Exception) { }
193193
Windows.Storage.Provider.FileUpdateStatus status = CachedFileManager.CompleteUpdatesAsync(file).AsTask().Result;
194194
}
195195
}

Signal-Windows.Lib/Storage/DB.cs

Lines changed: 41 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -275,7 +275,7 @@ public static IdentityKeyPair GetIdentityKeyPair()
275275
var ikp = ctx.Store
276276
.AsNoTracking()
277277
.Single().IdentityKeyPair;
278-
return new IdentityKeyPair(Base64.decode(ikp));
278+
return new IdentityKeyPair(Base64.Decode(ikp));
279279
}
280280
}
281281
}
@@ -329,7 +329,7 @@ public static SessionRecord LoadSession(SignalProtocolAddress address)
329329
.SingleOrDefault();
330330
if (session != null)
331331
{
332-
record = new SessionRecord(Base64.decode(session.Session));
332+
record = new SessionRecord(Base64.Decode(session.Session));
333333
}
334334
else
335335
{
@@ -456,7 +456,7 @@ public static PreKeyRecord LoadPreKey(uint preKeyId)
456456
.Where(p => p.Id == preKeyId)
457457
.AsNoTracking()
458458
.Single();
459-
return new PreKeyRecord(Base64.decode(pk.Key));
459+
return new PreKeyRecord(Base64.Decode(pk.Key));
460460
}
461461
}
462462
}
@@ -520,7 +520,7 @@ public static SignedPreKeyRecord LoadSignedPreKey(uint signedPreKeyId)
520520
.AsNoTracking()
521521
.Where(b => b.Id == signedPreKeyId)
522522
.Single();
523-
return new SignedPreKeyRecord(Base64.decode(preKeys.Key));
523+
return new SignedPreKeyRecord(Base64.Decode(preKeys.Key));
524524
}
525525
}
526526
}
@@ -537,7 +537,7 @@ public static List<SignedPreKeyRecord> LoadSignedPreKeys()
537537
var v = new List<SignedPreKeyRecord>();
538538
foreach (var preKey in preKeys)
539539
{
540-
v.Add(new SignedPreKeyRecord(Base64.decode(preKey.Key)));
540+
v.Add(new SignedPreKeyRecord(Base64.Decode(preKey.Key)));
541541
}
542542
return v;
543543
}
@@ -886,7 +886,7 @@ public static SignalMessage IncreaseReceiptCountLocked(SignalServiceEnvelope env
886886
{
887887
using (var ctx = new SignalDBContext())
888888
{
889-
m = ctx.Messages.SingleOrDefault(t => t.ComposedTimestamp == envelope.getTimestamp());
889+
m = ctx.Messages.SingleOrDefault(t => t.ComposedTimestamp == envelope.GetTimestamp());
890890
if (m != null)
891891
{
892892
m.Receipts++;
@@ -900,9 +900,9 @@ public static SignalMessage IncreaseReceiptCountLocked(SignalServiceEnvelope env
900900
{
901901
ctx.EarlyReceipts.Add(new SignalEarlyReceipt()
902902
{
903-
DeviceId = (uint)envelope.getSourceDevice(),
904-
Timestamp = envelope.getTimestamp(),
905-
Username = envelope.getSource()
903+
DeviceId = (uint)envelope.GetSourceDevice(),
904+
Timestamp = envelope.GetTimestamp(),
905+
Username = envelope.GetSource()
906906
});
907907
}
908908
ctx.SaveChanges();
@@ -1001,7 +1001,7 @@ internal static SignalConversation UpdateMessageRead(ReadMessage readMessage)
10011001
using (var ctx = new SignalDBContext())
10021002
{
10031003
var message = ctx.Messages
1004-
.Where(m => m.ComposedTimestamp == readMessage.getTimestamp())
1004+
.Where(m => m.ComposedTimestamp == readMessage.Timestamp)
10051005
.Single(); //TODO care about early reads sometime
10061006
conversation = GetSignalConversation(ctx, message.ThreadId);
10071007
var currentLastSeenMessage = ctx.Messages
@@ -1086,6 +1086,37 @@ internal static SignalConversation UpdateMessageRead(long index, SignalConversat
10861086
return dbConversation;
10871087
}
10881088

1089+
internal static List<SignalContact> InsertOrUpdateContacts(List<SignalContact> contactsList)
1090+
{
1091+
List<SignalContact> refreshedContacts = new List<SignalContact>();
1092+
lock (DBLock)
1093+
{
1094+
using (var ctx = new SignalDBContext())
1095+
{
1096+
foreach (var contact in contactsList)
1097+
{
1098+
var dbContact = ctx.Contacts
1099+
.Where(c => c.ThreadId == contact.ThreadId)
1100+
.SingleOrDefault();
1101+
if (dbContact != null)
1102+
{
1103+
refreshedContacts.Add(dbContact);
1104+
dbContact.ThreadDisplayName = contact.ThreadDisplayName;
1105+
dbContact.Color = contact.Color;
1106+
dbContact.ExpiresInSeconds = contact.ExpiresInSeconds;
1107+
}
1108+
else
1109+
{
1110+
refreshedContacts.Add(dbContact);
1111+
ctx.Contacts.Add(contact);
1112+
}
1113+
}
1114+
ctx.SaveChanges();
1115+
}
1116+
}
1117+
return refreshedContacts;
1118+
}
1119+
10891120
#endregion Threads
10901121

10911122
#region Groups
@@ -1323,7 +1354,6 @@ public static void InsertOrUpdateConversationLocked(SignalConversation conversat
13231354
}
13241355
}
13251356
}
1326-
13271357
#endregion Contacts
13281358
}
13291359
}

Signal-Windows.Lib/Util/LibUtils.cs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
using Microsoft.Toolkit.Uwp.Notifications;
66
using System;
77
using System.Collections.Generic;
8+
using System.IO;
89
using System.Linq;
910
using System.Text;
1011
using System.Threading;
@@ -177,5 +178,10 @@ public static ToastNotification CreateToastNotification(string text)
177178
};
178179
return new ToastNotification(toastContent.GetXml());
179180
}
181+
182+
public static FileStream CreateTmpFile(string name)
183+
{
184+
return File.Open(ApplicationData.Current.LocalCacheFolder.Path + Path.AltDirectorySeparatorChar + name, FileMode.Create, FileAccess.ReadWrite);
185+
}
180186
}
181187
}

Signal-Windows/App.xaml.cs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -201,7 +201,6 @@ private async Task CreateSecondaryWindowOrShowMain(ActivationViewSwitcher switch
201201
var currView = ApplicationView.GetForCurrentView();
202202
currView.Consolidated += CurrView_Consolidated;
203203
newViewId = currView.Id;
204-
//await switcher.ShowAsStandaloneAsync(newViewId);
205204
ViewModelLocator newVML = (ViewModelLocator)Resources["Locator"];
206205
SetupTopBar();
207206
return new SignalWindowsFrontend(newView.Dispatcher, newVML, newViewId);

Signal-Windows/ViewModels/FinishRegistrationPageViewModel.cs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
using GalaSoft.MvvmLight;
88
using libsignalservice;
99
using libsignalservice.util;
10+
using Microsoft.Extensions.Logging;
1011
using Signal_Windows.Lib;
1112
using Signal_Windows.Models;
1213
using Signal_Windows.Storage;
@@ -17,6 +18,7 @@ namespace Signal_Windows.ViewModels
1718
{
1819
public class FinishRegistrationPageViewModel : ViewModelBase
1920
{
21+
private readonly ILogger Logger = LibsignalLogging.CreateLogger<FinishRegistrationPageViewModel>();
2022
public FinishRegistrationPage View { get; set; }
2123

2224
internal async Task OnNavigatedTo()
@@ -25,7 +27,7 @@ internal async Task OnNavigatedTo()
2527
{
2628
await Task.Run(() =>
2729
{
28-
string SignalingKey = Base64.EncodeBytes(Util.getSecretBytes(52));
30+
string SignalingKey = Base64.EncodeBytes(Util.GetSecretBytes(52));
2931
App.CurrentSignalWindowsFrontend(App.MainViewId).Locator.RegisterFinalizationPageInstance.AccountManager.VerifyAccountWithCode(
3032
App.CurrentSignalWindowsFrontend(App.MainViewId).Locator.RegisterFinalizationPageInstance.VerificationCode.Replace("-", ""),
3133
SignalingKey, App.CurrentSignalWindowsFrontend(App.MainViewId).Locator.RegisterFinalizationPageInstance.SignalRegistrationId,
@@ -65,7 +67,7 @@ await Task.Run(() =>
6567
}
6668
catch (Exception e)
6769
{
68-
// TODO log exception
70+
Logger.LogError("OnNavigatedTo() failed: {0}\n{1}", e.Message, e.StackTrace);
6971
var title = "Verification failed";
7072
var content = "Please enter the correct verification code.";
7173
MessageDialog dialog = new MessageDialog(content, title);

Signal-Windows/ViewModels/GlobalSettingsPageViewModel.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ public void BackButton_Click(object sender, BackRequestedEventArgs e)
2323
e.Handled = true;
2424
}
2525

26-
public async Task OnNavigatedTo()
26+
public void OnNavigatedTo()
2727
{
2828
}
2929

Signal-Windows/ViewModels/LinkPageViewModel.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -76,21 +76,21 @@ await Task.Run(() =>
7676

7777
(string password, IdentityKeyPair tmpIdentity) = await Task.Run(() =>
7878
{
79-
string newPassword = Base64.EncodeBytes(Util.getSecretBytes(18));
79+
string newPassword = Base64.EncodeBytes(Util.GetSecretBytes(18));
8080
IdentityKeyPair newTmpIdentity = KeyHelper.generateIdentityKeyPair();
8181
return (newPassword, newTmpIdentity);
8282
});
8383

8484
// fetch new device uuid
8585
SignalServiceAccountManager accountManager = new SignalServiceAccountManager(App.ServiceConfiguration, CancelSource.Token, "Signal-Windows");
8686
string uuid = await accountManager.GetNewDeviceUuid(CancelSource.Token);
87-
string tsdevice = "tsdevice:/?uuid=" + Uri.EscapeDataString(uuid) + "&pub_key=" + Uri.EscapeDataString(Base64.encodeBytesWithoutPadding(tmpIdentity.getPublicKey().serialize()));
87+
string tsdevice = "tsdevice:/?uuid=" + Uri.EscapeDataString(uuid) + "&pub_key=" + Uri.EscapeDataString(Base64.EncodeBytesWithoutPadding(tmpIdentity.getPublicKey().serialize()));
8888

8989
View.SetQR(tsdevice); //TODO generate qrcode in worker task
9090
QRVisible = Visibility.Visible;
9191
QRCodeString = tsdevice;
9292

93-
string tmpSignalingKey = Base64.EncodeBytes(Util.getSecretBytes(52));
93+
string tmpSignalingKey = Base64.EncodeBytes(Util.GetSecretBytes(52));
9494
int registrationId = (int)KeyHelper.generateRegistrationId(false);
9595

9696
var provisionMessage = await accountManager.GetProvisioningMessage(CancelSource.Token, tmpIdentity);

0 commit comments

Comments
 (0)