-
Notifications
You must be signed in to change notification settings - Fork 74
/
Copy pathScheduledAgentImpl.cs
executable file
·354 lines (310 loc) · 15.3 KB
/
ScheduledAgentImpl.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
//
// This is the source code of Telegram for Windows Phone v. 3.x.x.
// It is licensed under GNU GPL v. 2 or later.
// You should have received a copy of the license in this archive (see LICENSE).
//
// Copyright Evgeny Nadymov, 2013-present.
//
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;
using System.Xml.Serialization;
using Windows.Data.Xml.Dom;
using Windows.UI.Notifications;
using Microsoft.Phone.Networking.Voip;
using Microsoft.Phone.Scheduler;
using PhoneVoIPApp.BackEnd;
using Telegram.Api;
using Telegram.Api.Aggregator;
using Telegram.Api.Services;
using Telegram.Api.Services.Cache;
using Telegram.Api.Services.Connection;
using Telegram.Api.Services.Location;
using Telegram.Api.Services.Updates;
using Telegram.Api.TL;
using Telegram.Api.TL.Functions.Phone;
using Telegram.Api.Transport;
namespace PhoneVoIPApp.Agents
{
public class ScheduledAgentImpl : ScheduledTaskAgent
{
private readonly Mutex _appOpenMutex = new Mutex(false, Constants.TelegramMessengerMutexName);
private static bool _logEnabled = true;
private static readonly int _id = new Random().Next(999);
private static void Log(string message, Action callback = null)
{
if (!_logEnabled) return;
Telegram.Logs.Log.WriteSync = true;
Telegram.Logs.Log.Write(string.Format("::ScheduledAgentImpl {0} {1}", _id, message), callback);
#if DEBUG
//PushUtils.AddToast("push", message, string.Empty, string.Empty, null, null);
#endif
}
public ScheduledAgentImpl()
{
}
//private static void SetText(XmlDocument document, string caption, string message)
//{
// var toastTextElements = document.GetElementsByTagName("text");
// toastTextElements[0].InnerText = caption ?? string.Empty;
// toastTextElements[1].InnerText = message ?? string.Empty;
//}
private static void SetText(XmlDocument document, string caption, string message)
{
var toastTextElements = document.GetElementsByTagName("text");
toastTextElements[0].InnerText = caption ?? string.Empty;
toastTextElements[1].InnerText = message ?? string.Empty;
}
protected override void OnInvoke(ScheduledTask task)
{
Debug.WriteLine("[ScheduledAgentImpl {0}] ScheduledAgentImpl has been invoked with argument of type {1}.", GetHashCode(), task.GetType());
// Indicate that an agent has started running
AgentHost.OnAgentStarted();
Log(string.Format("start with argument of type {0}", task.GetType()));
if (!_appOpenMutex.WaitOne(0))
{
Log("cancel");
Complete();
return;
}
_appOpenMutex.ReleaseMutex();
var incomingCallTask = task as VoipHttpIncomingCallTask;
if (incomingCallTask != null)
{
isIncomingCallAgent = true;
var messageBody = HttpUtility.HtmlDecode(Encoding.UTF8.GetString(incomingCallTask.MessageBody, 0, incomingCallTask.MessageBody.Length));
Notification pushNotification = null;
try
{
using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(messageBody ?? string.Empty)))
{
var xs = new XmlSerializer(typeof(Notification));
pushNotification = (Notification)xs.Deserialize(ms);
}
}
catch (Exception ex)
{
Log(string.Format("cannot deserialize message_body={0}", messageBody));
#if DEBUG
var toastNotifier = ToastNotificationManager.CreateToastNotifier();
var toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText02);
SetText(toastXml, "Notification Exception", string.Empty);
try
{
var toast = new ToastNotification(toastXml);
//RemoveToastGroup(group);
toastNotifier.Show(toast);
}
catch (Exception ex2)
{
Telegram.Logs.Log.Write(ex.ToString());
}
#endif
}
if (pushNotification != null)
{
var rootObject = PushUtils2.GetRootObject<RootObject>(pushNotification.Data);
if (rootObject != null
&& rootObject.data != null)
{
if (rootObject.data.custom != null
&& rootObject.data.custom.from_id != null
&& rootObject.data.custom.call_id != null
&& rootObject.data.custom.call_ah != null)
{
var contactImage = PushUtils2.GetImageSource(rootObject.data.custom.mtpeer) ?? string.Empty;
var contactName = rootObject.data.loc_args != null && rootObject.data.loc_args.Length > 0
? rootObject.data.loc_args[0]
: string.Empty;
Debug.WriteLine("[{0}] Incoming call from caller {1}, id {2}", incomingCallAgentId,
contactName, rootObject.data.custom.from_id);
long contactId = 0;
long callId = 0;
long callAccessHash = 0;
if (long.TryParse(rootObject.data.custom.from_id, out contactId)
&& long.TryParse(rootObject.data.custom.call_id, out callId)
&& long.TryParse(rootObject.data.custom.call_ah, out callAccessHash))
{
if (string.Equals(rootObject.data.loc_key, "PHONE_CALL_REQUEST",
StringComparison.OrdinalIgnoreCase))
{
if (BackEnd.Globals.Instance.CallController.CallStatus == CallStatus.InProgress)
{
OnIncomingCallDialogDismissed(callId, callAccessHash, true);
return;
}
// Initiate incoming call processing
// If you want to pass in additional information such as pushNotification.Number, you can
var incomingCallProcessingStarted =
BackEnd.Globals.Instance.CallController.OnIncomingCallReceived(contactName,
contactId, contactImage, callId, callAccessHash,
OnIncomingCallDialogDismissed);
if (incomingCallProcessingStarted)
{
// will Complete() at OnIncomingCallDialogDismissed
return;
}
//PushUtils2.AddToast(rootObject, "Caption", "Message", "", "", "tag", "group");
}
else if (string.Equals(rootObject.data.loc_key, "PHONE_CALL_DECLINE",
StringComparison.OrdinalIgnoreCase))
{
var currentCallId = BackEnd.Globals.Instance.CallController.CallId;
if (currentCallId == callId)
{
Log(string.Format("PHONE_CALL_DECLINE CallController.EndCall call_id={0}", callId));
var result = BackEnd.Globals.Instance.CallController.EndCall();
Log(string.Format("PHONE_CALL_DECLINE CallController.EndCall call_id={0} result={1}", callId, result));
}
}
}
}
else if (string.Equals(rootObject.data.loc_key, "GEO_LIVE_PENDING"))
{
ProcessLiveLocations();
}
else
{
//PushUtils2.UpdateToastAndTiles(rootObject);
}
}
}
Complete();
return;
}
else
{
VoipKeepAliveTask keepAliveTask = task as VoipKeepAliveTask;
if (keepAliveTask != null)
{
this.isIncomingCallAgent = false;
// Refresh tokens, get new certs from server, etc.
BackEnd.Globals.Instance.DoPeriodicKeepAlive();
this.Complete();
}
else
{
throw new InvalidOperationException(string.Format("Unknown scheduled task type {0}", task.GetType()));
}
}
}
// This is a request to complete this agent
protected override void OnCancel()
{
Debug.WriteLine("[{0}] Cancel requested.", this.isIncomingCallAgent ? ScheduledAgentImpl.incomingCallAgentId : ScheduledAgentImpl.keepAliveAgentId);
this.Complete();
}
private readonly object _initConnectionSyncRoot = new object();
private TLInitConnection GetInitConnection()
{
return TLUtils.OpenObjectFromMTProtoFile<TLInitConnection>(_initConnectionSyncRoot, Constants.InitConnectionFileName) ??
new TLInitConnection
{
DeviceModel = new TLString("unknown"),
AppVersion = new TLString("background task"),
SystemVersion = new TLString("8.10.0.0")
};
}
// This method is called when the incoming call processing is complete
private void OnIncomingCallDialogDismissed(long callId, long callAccessHash, bool rejected)
{
Debug.WriteLine("[IncomingCallAgent] Incoming call processing is now complete.");
if (rejected)
{
var deviceInfoService = new Telegram.Api.Services.DeviceInfo.DeviceInfoService(GetInitConnection(), true, "BackgroundDifferenceLoader", 1);
var cacheService = new MockupCacheService();
var updatesService = new MockupUpdatesService();
var transportService = new TransportService();
var connectionService = new ConnectionService(deviceInfoService);
var publicConfigService = new MockupPublicConfigService();
var manualResetEvent = new ManualResetEvent(false);
var mtProtoService = new MTProtoService(deviceInfoService, updatesService, cacheService, transportService, connectionService, publicConfigService);
mtProtoService.Initialized += (o, e) =>
{
var peer = new TLInputPhoneCall
{
Id = new TLLong(callId),
AccessHash = new TLLong(callAccessHash)
};
var getStateAction = new TLDiscardCall
{
Peer = peer,
Duration = new TLInt(0),
Reason = new TLPhoneCallDiscardReasonBusy(),
ConnectionId = new TLLong(0)
};
var actions = new List<TLObject> { getStateAction };
mtProtoService.SendActionsAsync(actions,
(request, result) =>
{
manualResetEvent.Set();
},
error =>
{
manualResetEvent.Set();
});
};
mtProtoService.InitializationFailed += (o, e) =>
{
manualResetEvent.Set();
};
mtProtoService.Initialize();
#if DEBUG
manualResetEvent.WaitOne();
#else
manualResetEvent.WaitOne(TimeSpan.FromSeconds(10.0));
#endif
mtProtoService.Stop();
}
this.Complete();
}
private void ProcessLiveLocations()
{
var deviceInfoService = new Telegram.Api.Services.DeviceInfo.DeviceInfoService(GetInitConnection(), true, "BackgroundDifferenceLoader", 1);
var cacheService = new MockupCacheService();
var updatesService = new MockupUpdatesService();
var transportService = new TransportService();
var connectionService = new ConnectionService(deviceInfoService);
var publicConfigService = new MockupPublicConfigService();
var manualResetEvent = new ManualResetEvent(false);
var eventAggregator = new TelegramEventAggregator();
var mtProtoService = new MTProtoService(deviceInfoService, updatesService, cacheService, transportService, connectionService, publicConfigService);
mtProtoService.Initialized += (o, e) =>
{
var liveLocationsService = new LiveLocationService(mtProtoService, eventAggregator);
liveLocationsService.Load();
liveLocationsService.UpdateAll();
manualResetEvent.Set();
};
mtProtoService.InitializationFailed += (o, e) =>
{
manualResetEvent.Set();
};
mtProtoService.Initialize();
var timeout =
#if DEBUG
Timeout.InfiniteTimeSpan;
#else
TimeSpan.FromSeconds(30.0);
#endif
var result = manualResetEvent.WaitOne(timeout);
}
// Complete this agent.
private void Complete()
{
Debug.WriteLine("[{0}] Calling NotifyComplete", this.isIncomingCallAgent ? ScheduledAgentImpl.incomingCallAgentId : ScheduledAgentImpl.keepAliveAgentId);
Log(string.Format("[{0}] Calling NotifyComplete", this.isIncomingCallAgent ? ScheduledAgentImpl.incomingCallAgentId : ScheduledAgentImpl.keepAliveAgentId));
// This agent is done
base.NotifyComplete();
}
// Strings used in tracing
private const string keepAliveAgentId = "KeepAliveAgent";
private const string incomingCallAgentId = "IncomingCallAgent";
// Indicates if this agent instance is handling an incoming call or not
private bool isIncomingCallAgent;
}
}