Exemplo n.º 1
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.º 2
0
        public void Initialize(BackgroundTaskDeferral deferral)
        {
            if (_connection == null & _protoService == null)
            {
                VoIPCallTask.Log("Mediator initialized", "Creating proto service");

                var deviceInfoService = new DeviceInfoService();
                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 statsService      = new StatsService();
                var protoService      = new MTProtoService(deviceInfoService, updatesService, cacheService, transportService, connectionService, statsService);

                protoService.Initialized += (s, args) =>
                {
                    VoIPCallTask.Log("ProtoService initialized", "waiting for updates");

                    updatesService.LoadStateAndUpdate(() =>
                    {
                        VoIPCallTask.Log("Difference processed", "Difference processed");

                        if (_phoneCall == null)
                        {
                            VoIPCallTask.Log("Difference processed", "No call found in difference");

                            if (_systemCall != null)
                            {
                                _systemCall.NotifyCallEnded();
                            }
                        }
                    });
                };

                eventAggregator.Subscribe(this);
                protoService.Initialize();
                _protoService     = protoService;
                _transportService = transportService;
            }
            else
            {
                VoIPCallTask.Log("Mediator initialized", "_connection is null: " + (_connection == null));
            }

            _deferral    = deferral;
            _initialized = true;

            ProcessUpdates();
        }
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);
        }
Exemplo n.º 4
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            var deferral = taskInstance.GetDeferral();

            var data = Toast.GetData(taskInstance);

            if (data != null)
            {
                if (data.ContainsKey("QuickMessage"))
                {
                    var deviceInfoService = new DeviceInfoService();
                    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 statsService      = new StatsService();
                    var manualResetEvent  = new ManualResetEvent(false);
                    var protoService      = new MTProtoService(deviceInfoService, updatesService, cacheService, transportService, connectionService, statsService);

                    protoService.Initialized += (s, args) =>
                    {
                        var text         = data["QuickMessage"];
                        var messageText  = text.Replace("\r\n", "\n").Replace('\v', '\n').Replace('\r', '\n');
                        var entitiesBase = Utils.GetEntities(ref messageText);

                        var replyToMsgId = 0;
                        var inputPeer    = default(TLInputPeerBase);
                        if (data.ContainsKey("from_id"))
                        {
                            inputPeer = new TLInputPeerUser {
                                UserId = int.Parse(data["from_id"]), AccessHash = long.Parse(data["access_hash"])
                            };
                        }
                        else if (data.ContainsKey("channel_id"))
                        {
                            inputPeer = new TLInputPeerChannel {
                                ChannelId = int.Parse(data["channel_id"]), AccessHash = long.Parse(data["access_hash"])
                            };
                            replyToMsgId = data.ContainsKey("msg_id") ? int.Parse(data["msg_id"]) : 0;
                        }
                        else if (data.ContainsKey("chat_id"))
                        {
                            inputPeer = new TLInputPeerChat {
                                ChatId = int.Parse(data["chat_id"])
                            };
                            replyToMsgId = data.ContainsKey("msg_id") ? int.Parse(data["msg_id"]) : 0;
                        }

                        TLVector <TLMessageEntityBase> entities = null;
                        if (entitiesBase != null)
                        {
                            entities = new TLVector <TLMessageEntityBase>(entitiesBase);
                        }

                        var obj = new TLMessagesSendMessage {
                            Peer = inputPeer, ReplyToMsgId = replyToMsgId, Message = messageText, Entities = entities, IsBackground = true, RandomId = TLLong.Random()
                        };

                        protoService.SendInformativeMessageInternal <TLUpdatesBase>("messages.sendMessage", obj, result =>
                        {
                            manualResetEvent.Set();
                        },
                                                                                    faultCallback: fault =>
                        {
                            // TODO: alert user?
                            manualResetEvent.Set();
                        },
                                                                                    fastCallback: () =>
                        {
                            manualResetEvent.Set();
                        });

                        //var date = TLUtils.DateToUniversalTimeTLInt(protoService.ClientTicksDelta, DateTime.Now);
                        //var message = TLUtils.GetMessage(SettingsHelper.UserId, inputPeer, TLMessageState.Sending, true, true, date, text, new TLMessageMediaEmpty(), TLLong.Random(), replyToMsgId);
                        //var history = cacheService.GetHistory(inputPeer, 1);

                        //cacheService.SyncSendingMessage(message, null, async (m) =>
                        //{
                        //    await protoService.SendMessageAsync(message, () =>
                        //    {
                        //        // TODO: fast callback
                        //    });
                        //    manualResetEvent.Set();
                        //});
                    };
                    protoService.InitializationFailed += (s, args) =>
                    {
                        manualResetEvent.Set();
                    };

                    //cacheService.Init();
                    protoService.Initialize();

                    manualResetEvent.WaitOne(15000);
                }
            }

            deferral.Complete();
        }
        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
        }
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            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 deviceInfoService = new DeviceInfoService(GetInitConnection(), true, "MessageSchedulerBackgroundTask", _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 manualResetEvent = new ManualResetEvent(false);

            Log("before init");
            var requestsToRemove = new List <TLObject>();
            var mtProtoService   = new MTProtoService(deviceInfoService, updatesService, cacheService, transportService, connectionService);

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

                var actionInfos = mtProtoService.GetActionInfoFromFile();
                var count       = actionInfos != null ? actionInfos.Count : 0;
                Log("send count=" + count);

                if (actionInfos != null &&
                    actionInfos.Count > 0)
                {
                    var actionsString = new StringBuilder();
                    foreach (var info in actionInfos)
                    {
                        actionsString.AppendLine(info.ToString());
                    }
                    Log(actionsString.ToString());

                    var       sendMessageActions = new List <TLObject>();
                    const int maxActionCount     = 10;
                    var       currentCount       = 0;
                    foreach (var actionInfo in actionInfos)
                    {
                        if (TLUtils.IsValidAction(actionInfo.Action) && currentCount < maxActionCount)
                        {
                            currentCount++;
                            sendMessageActions.Add(actionInfo.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();
                    }
                }
                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");
                mtProtoService.RemoveActionInfoFromFile(requestsToRemove);
            }

            Log("stop " + stopwatch.Elapsed, deferral.Complete);
        }