private void InitializeServiceAsync(System.Action callback)
        {
            Debug.WriteLine("[CallInProgressAgentImpl {0}] _mtProtoService == null {1}", GetHashCode(), _mtProtoService == null);

            if (MTProtoService == null)
            {
                var deviceInfoService = new Telegram.Api.Services.DeviceInfo.DeviceInfoService(GetInitConnection(), true, "BackgroundDifferenceLoader", 1);
                var cacheService      = new MockupCacheService();
                var updatesService    = new MockupUpdatesService();

                _transportService = new TransportService();
                var connectionService   = new ConnectionService(deviceInfoService);
                var publicConfigService = new MockupPublicConfigService();

                var mtProtoService = new MTProtoService(deviceInfoService, updatesService, cacheService, _transportService, connectionService, publicConfigService);
                mtProtoService.Initialized += (o, e) =>
                {
                    //Log(string.Format("[MTProtoUpdater {0}] Initialized", GetHashCode()));
                    Thread.Sleep(1000);
                    callback.SafeInvoke();
                };
                mtProtoService.InitializationFailed += (o, e) =>
                {
                    //Log(string.Format("[MTProtoUpdater {0}] InitializationFailed", GetHashCode()));
                };
                mtProtoService.Initialize();

                MTProtoService = mtProtoService;
            }
            else
            {
                callback.SafeInvoke();
            }
        }
Exemplo n.º 2
0
        private void RunAsync(Action callback)
        {
            var deviceInfoService   = new DeviceInfoService(GetInitConnection(), true, "BackgroundDifferenceLoader", _id);
            var eventAggregator     = new TelegramEventAggregator();
            var cacheService        = new InMemoryCacheService(eventAggregator);
            var updatesService      = new UpdatesService(cacheService, eventAggregator);
            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 lastTime = TLUtils.OpenObjectFromMTProtoFile <TLInt>(_differenceTimeSyncRoot, Constants.DifferenceTimeFileName);
                if (lastTime != null)
                {
                    var now = TLUtils.DateToUniversalTimeTLInt(mtProtoService.ClientTicksDelta, DateTime.Now);

                    if (lastTime.Value + Constants.DifferenceMinInterval > now.Value)
                    {
                        manualResetEvent.Set();
                        return;
                    }
                }

                var clientState = TLUtils.OpenObjectFromMTProtoFile <TLState>(_stateRoot, Constants.StateFileName);
                _results = TLUtils.OpenObjectFromMTProtoFile <TLVector <TLDifference> >(_differenceFileSyncRoot, Constants.DifferenceFileName) ?? new TLVector <TLDifference>();
                var state = GetState(clientState, _results);

                if (state != null)
                {
                    GetDifferenceAsync(mtProtoService, state, () => manualResetEvent.Set());
                }
                else
                {
                    manualResetEvent.Set();
                }
            };
            mtProtoService.InitializationFailed += (o, e) =>
            {
                manualResetEvent.Set();
            };
            mtProtoService.Initialize();

#if DEBUG
            manualResetEvent.WaitOne(15000);
#else
            manualResetEvent.WaitOne(15000);
#endif

            callback.SafeInvoke();
        }
Exemplo n.º 3
0
        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);
        }
        private void SendReply(TLInputPeerBase inputPeer, TLString message, TLInt msgId)
        {
            if (msgId == null)
            {
                return;
            }
            if (TLString.IsNullOrEmpty(message))
            {
                return;
            }

            var actionInfo = TLUtils.OpenObjectFromMTProtoFile <TLVector <TLActionInfo> >(_actionInfoSyncRoot, Constants.ActionQueueFileName) ?? new TLVector <TLActionInfo>();

            var count = actionInfo.Count;

            Log("send count=" + count);

            var peerChannel = inputPeer as TLInputPeerChannel;
            var readHistory = peerChannel != null
                ? (TLObject) new TLReadChannelHistory {
                Channel = new TLInputChannel {
                    ChannelId = peerChannel.ChatId, AccessHash = peerChannel.AccessHash
                }, MaxId = msgId
            }
                : new TLReadHistory {
                Peer = inputPeer, MaxId = msgId
            };

            var readHistoryActionInfo = new TLActionInfo();

            readHistoryActionInfo.SendBefore = new TLInt(0);
            readHistoryActionInfo.Action     = readHistory;

            actionInfo.Add(readHistoryActionInfo);

            var sendMessage = new TLSendMessage();

            sendMessage.Flags    = new TLInt(0);
            sendMessage.Peer     = inputPeer;
            sendMessage.Message  = message;
            sendMessage.RandomId = TLLong.Random();

            var sendMessageActionInfo = new TLActionInfo();

            sendMessageActionInfo.SendBefore = new TLInt(0);
            sendMessageActionInfo.Action     = sendMessage;

            actionInfo.Add(sendMessageActionInfo);

            TLUtils.SaveObjectToMTProtoFile(new object(), Constants.ActionQueueFileName, actionInfo);

            if (actionInfo.Count > 0)
            {
                var deviceInfoService   = new DeviceInfoService(GetInitConnection(), true, "InteractiveNotificationsBackgroundTask", _id);
                var eventAggregator     = new TelegramEventAggregator();
                var cacheService        = new InMemoryCacheService(eventAggregator);
                var updatesService      = new UpdatesService(cacheService, eventAggregator);
                var transportService    = new TransportService();
                var connectionService   = new ConnectionService(deviceInfoService);
                var publicConfigService = new MockupPublicConfigService();

                var manualResetEvent = new ManualResetEvent(false);
                Log("before init");
                var requestsToRemove = new List <TLObject>();
                var mtProtoService   = new MTProtoService(deviceInfoService, updatesService, cacheService, transportService, connectionService, publicConfigService);
                mtProtoService.Initialized += async(o, e) =>
                {
                    Log("init completed");

                    var actionsString = new StringBuilder();
                    foreach (var info in actionInfo)
                    {
                        actionsString.AppendLine(info.ToString());
                    }
                    Log(actionsString.ToString());

                    var       sendMessageActions = new List <TLObject>();
                    const int maxActionCount     = 10;
                    var       currentCount       = 0;
                    foreach (var ai in actionInfo)
                    {
                        if (TLUtils.IsValidAction(ai.Action) && currentCount < maxActionCount)
                        {
                            currentCount++;
                            sendMessageActions.Add(ai.Action);
                        }
                    }

                    if (sendMessageActions.Count > 0)
                    {
                        mtProtoService.SendActionsAsync(sendMessageActions,
                                                        (request, result) => // will be invoked for each sent action
                        {
                            requestsToRemove.Add(request);
                            var sendingMessages = mtProtoService.SendingMessages;
                            Log("send completed count=" + sendingMessages, () =>
                            {
                                if (sendingMessages == 0)
                                {
                                    _clearActionInfoFile = true;

                                    manualResetEvent.Set();
                                }
                            });
                        },
                                                        error =>
                        {
                            Log(string.Format("send error={0}\n{1}", error, error.Exception),
                                async() =>
                            {
                                await Task.Delay(TimeSpan.FromSeconds(1.0));
                                manualResetEvent.Set();
                            });
                        });
                    }
                    else
                    {
                        manualResetEvent.Set();
                    }
                };
                mtProtoService.InitializationFailed += (o, e) =>
                {
                    Log("init failed");

                    manualResetEvent.Set();
                };
                mtProtoService.Initialize();
#if DEBUG
                manualResetEvent.WaitOne();
#else
                manualResetEvent.WaitOne(15000);
#endif
                if (_clearActionInfoFile)
                {
                    Log("clear");
                    lock (_actionInfoSyncRoot)
                    {
                        var actions = actionInfo;

                        foreach (var o in requestsToRemove)
                        {
                            MTProtoService.RemoveActionInfoCommon(actions, o);
                        }

                        TLUtils.SaveObjectToMTProtoFile(_actionInfoSyncRoot, Constants.ActionQueueFileName, actions);
                    }
                }
            }
        }
        private void UpdateNotifySettings(TLInputPeerBase inputPeer, TLInt muteUntil)
        {
            var deviceInfoService   = new DeviceInfoService(GetInitConnection(), true, "InteractiveNotificationsBackgroundTask", _id);
            var eventAggregator     = new TelegramEventAggregator();
            var cacheService        = new InMemoryCacheService(eventAggregator);
            var updatesService      = new UpdatesService(cacheService, eventAggregator);
            var transportService    = new TransportService();
            var connectionService   = new ConnectionService(deviceInfoService);
            var publicConfigService = new MockupPublicConfigService();

            var manualResetEvent = new ManualResetEvent(false);

            Log("before init");
            var mtProtoService = new MTProtoService(deviceInfoService, updatesService, cacheService, transportService, connectionService, publicConfigService);

            mtProtoService.Initialized += (o, e) =>
            {
                Log("init completed");

                mtProtoService.GetNotifySettingsAsync(new TLInputNotifyPeer {
                    Peer = inputPeer
                },
                                                      result =>
                {
                    Log("getNotifySettings completed", () =>
                    {
                        var peerNotifySettings = result as TLPeerNotifySettings;
                        if (peerNotifySettings != null)
                        {
                            if (muteUntil.Value < int.MaxValue)
                            {
                                muteUntil = TLUtils.DateToUniversalTimeTLInt(mtProtoService.ClientTicksDelta, DateTime.Now.AddSeconds(muteUntil.Value));
                            }

                            var inputPeerNotifySettings = new TLInputPeerNotifySettings78
                            {
                                Flags     = new TLInt(0),
                                MuteUntil = muteUntil,
                                Sound     = peerNotifySettings.Sound,
                            };

                            mtProtoService.UpdateNotifySettingsAsync(new TLInputNotifyPeer {
                                Peer = inputPeer
                            },
                                                                     inputPeerNotifySettings,
                                                                     result2 =>
                            {
                                Log("setNotifySettings completed", () =>
                                {
                                    manualResetEvent.Set();
                                });
                            },
                                                                     error2 =>
                            {
                                Log(string.Format("setNotifySettings error={0}\n{1}", error2, error2.Exception),
                                    async() =>
                                {
                                    await Task.Delay(TimeSpan.FromSeconds(1.0));
                                    manualResetEvent.Set();
                                });
                            });
                        }
                        else
                        {
                            manualResetEvent.Set();
                        }
                    });
                },
                                                      error =>
                {
                    Log(string.Format("getNotifySettings error={0}\n{1}", error, error.Exception),
                        async() =>
                    {
                        await Task.Delay(TimeSpan.FromSeconds(1.0));
                        manualResetEvent.Set();
                    });
                });
            };
            mtProtoService.InitializationFailed += (o, e) =>
            {
                Log("init failed");

                manualResetEvent.Set();
            };
            mtProtoService.Initialize();
#if DEBUG
            manualResetEvent.WaitOne();
#else
            manualResetEvent.WaitOne(15000);
#endif
        }
Exemplo n.º 6
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();
        }
Exemplo n.º 7
0
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            try
            {
                Telegram.Logs.Log.WriteSync = true;

                taskInstance.Canceled += OnTaskCanceled;
                var deferral = taskInstance.GetDeferral();

                var stopwatch = Stopwatch.StartNew();
                var task      = taskInstance.Task;
                var name      = task != null ? task.Name : null;
                Log("start " + name);
                if (!_appOpenMutex.WaitOne(0))
                {
                    Log("cancel", deferral.Complete);

                    return;
                }
                _appOpenMutex.ReleaseMutex();
                Log("release mutex");
                var isAuthorized = SettingsHelper.GetValue <bool>(Constants.IsAuthorizedKey);
                if (!isAuthorized)
                {
                    Log("cancel isAuthorized=false", deferral.Complete);

                    return;
                }
                Log("isAuthorized=true");

                var actionInfo = TLUtils.OpenObjectFromMTProtoFile <TLVector <TLActionInfo> >(_actionInfoSyncRoot, Constants.ActionQueueFileName) ?? new TLVector <TLActionInfo>();
                var count      = actionInfo.Count;
                Log("send count=" + count);

                if (count > 0)
                {
                    var deviceInfoService = new DeviceInfoService(GetInitConnection(), true, "MessageSchedulerBackgroundTask", _id);

                    var publicConfigService = new MockupPublicConfigService();
                    var eventAggregator     = new TelegramEventAggregator();
                    var cacheService        = new InMemoryCacheService(eventAggregator);
                    var updatesService      = new UpdatesService(cacheService, eventAggregator);
                    var transportService    = new TransportService();
                    var connectionService   = new ConnectionService(deviceInfoService);

                    var manualResetEvent = new ManualResetEvent(false);
                    Log("before init");
                    var requestsToRemove = new List <TLObject>();
                    var mtProtoService   = new MTProtoService(deviceInfoService, updatesService, cacheService, transportService, connectionService, publicConfigService);
                    mtProtoService.Initialized += async(o, e) =>
                    {
                        Log("init completed");

                        var actionsString = new StringBuilder();
                        foreach (var info in actionInfo)
                        {
                            actionsString.AppendLine(info.ToString());
                        }
                        Log(actionsString.ToString());

                        var       sendMessageActions = new List <TLObject>();
                        const int maxActionCount     = 10;
                        var       currentCount       = 0;
                        foreach (var ai in actionInfo)
                        {
                            if (TLUtils.IsValidAction(ai.Action) && currentCount < maxActionCount)
                            {
                                currentCount++;
                                sendMessageActions.Add(ai.Action);
                            }
                        }

                        if (sendMessageActions.Count > 0)
                        {
                            await Task.Delay(TimeSpan.FromSeconds(3.0));

                            mtProtoService.SendActionsAsync(sendMessageActions,
                                                            (request, result) => // will be invoked for each sent action
                            {
                                requestsToRemove.Add(request);
                                var sendingMessages = mtProtoService.SendingMessages;
                                Log("send completed count=" + sendingMessages, () =>
                                {
                                    if (sendingMessages == 0)
                                    {
                                        _clearActionInfoFile = true;

                                        manualResetEvent.Set();
                                    }
                                });
                            },
                                                            error =>
                            {
                                Log(string.Format("send error={0}\n{1}", error, error.Exception),
                                    async() =>
                                {
                                    await Task.Delay(TimeSpan.FromSeconds(1.0));
                                    manualResetEvent.Set();
                                });
                            });
                        }
                        else
                        {
                            manualResetEvent.Set();
                        }
                    };
                    mtProtoService.InitializationFailed += (o, e) =>
                    {
                        Log("init failed");

                        manualResetEvent.Set();
                    };
                    mtProtoService.Initialize();
#if DEBUG
                    manualResetEvent.WaitOne();
#else
                    manualResetEvent.WaitOne(15000);
#endif
                    if (_clearActionInfoFile)
                    {
                        Log("clear");
                        lock (_actionInfoSyncRoot)
                        {
                            var actions = actionInfo;

                            foreach (var o in requestsToRemove)
                            {
                                MTProtoService.RemoveActionInfoCommon(actions, o);
                            }

                            TLUtils.SaveObjectToMTProtoFile(_actionInfoSyncRoot, Constants.ActionQueueFileName, actions);
                        }
                    }
                }

                Log("stop " + stopwatch.Elapsed, deferral.Complete);
            }
            catch (Exception ex)
            {
            }
        }