コード例 #1
0
ファイル: TelegramService.cs プロジェクト: jorgelg/TelegramWS
        public async Task <Respuestas> CerrarSesion(string pathArchivo)
        {
            Respuestas respuesta = new Respuestas();

            try
            {
                TeleSharp.TL.Auth.TLRequestLogOut x = new TeleSharp.TL.Auth.TLRequestLogOut();

                contexto = Iniciar();
                await contexto.ConnectAsync();

                var cerrado = await contexto.SendRequestAsync <Boolean>(x);

                JObject objeto = JObject.Parse(File.ReadAllText(pathArchivo.Replace("Registros.txt", "Sesion.txt")));
                info.Expiracion.Add(DateTime.Now.AddMilliseconds(objeto.Value <double>("SessionExpires")).ToString("MM/dd/yy H:mm:ss"));
                GuardarArchivo(pathArchivo, info);
                if (!contexto.IsUserAuthorized())
                {
                    respuesta.MESSAGE = "sesion cerrada exitosamente...";
                    respuesta.STATUS  = true;
                    contexto.Dispose();
                    File.Delete(HttpContext.Current.Server.MapPath("~/Resources/session/session.dat"));
                    File.Delete(HttpContext.Current.Server.MapPath("~/Resources/session/Registros.txt"));
                    File.Delete(HttpContext.Current.Server.MapPath("~/Resources/session/Sesion.txt"));
                }
                else
                {
                    respuesta.MESSAGE = "no se pudo cerrar sesion... probablemente ya se cerro anteriormente";
                    respuesta.STATUS  = false;
                }
                return(respuesta);
            }
            catch (Exception e)
            {
                TeleSharp.TL.Auth.TLRequestLogOut x = new TeleSharp.TL.Auth.TLRequestLogOut();
                var cerrado = await contexto.SendRequestAsync <Boolean>(x);

                JObject objeto = JObject.Parse(File.ReadAllText(pathArchivo.Replace("Registros.txt", "Sesion.txt")));
                info.Expiracion.Add(DateTime.Now.AddMilliseconds(objeto.Value <double>("SessionExpires")).ToString("MM/dd/yy H:mm:ss"));
                GuardarArchivo(pathArchivo, info);
                if (cerrado)
                {
                    respuesta.MESSAGE = "sesion cerrada exitosamente...";
                    respuesta.STATUS  = true;
                    contexto.Dispose();
                    File.Delete(HttpContext.Current.Server.MapPath("~/Resources/session/session.dat"));
                    File.Delete(HttpContext.Current.Server.MapPath("~/Resources/session/Registros.txt"));
                    File.Delete(HttpContext.Current.Server.MapPath("~/Resources/session/Sesion.txt"));
                }
                else
                {
                    respuesta.MESSAGE = "No se pudo cerrar sesión..." + e.Message;
                    respuesta.STATUS  = false;
                }
                return(respuesta);
            }
        }
コード例 #2
0
 public void Dispose()
 {
     if (!_isFullClient)
     {
         _client.Dispose();
     }
 }
コード例 #3
0
ファイル: TelegramAuth.cs プロジェクト: str1py/Ducky
        public async Task <bool> TryToConnect(string proxy)
        {
            testproxy = proxy;
            if (InternetConnection.IsConnectionExist == false)
            {
                MainWindowViewModel.instance.Alert(null, "Telegram", "Возможно отсутствует подключение к интернету. Статус интернет подключение : " + InternetConnection.IsConnectionExist);
                return(false);
            }
            else
            {
                try
                {
                    TelegramClient testclient = await CreateTestClientAsync();

                    await testclient.ConnectAsync(false);

                    await testclient.ConnectAsync();

                    var connect = testclient.IsConnected;
                    testclient.Dispose();
                    return(connect);
                }
                catch (Exception e)
                {
                    MethodBase m = MethodBase.GetCurrentMethod();
                    log.AddLog("ERROR : ", e.Message, "Error in ", m.DeclaringType.Name);
                    return(false);
                }
            }
        }
コード例 #4
0
        public static void Start()
        {
            try
            {
                InitialiseClients();
                StartThreads();

                while (true)
                {
                    Thread.Sleep(10000);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.Write(ex.StackTrace);
                Console.ReadKey();
            }
            finally
            {
                // Dispose of any resources
                if (_ircClient != null)
                {
                    _ircClient.Dispose();
                    _ircClient = null;
                }

                if (_telegramClient != null)
                {
                    _telegramClient.Dispose();
                    _telegramClient = null;
                }
            }
        }
コード例 #5
0
            public DownloadManager(Document document, Telegram telegram)
            {
                _document = document;
                _fileSize = document.Size;
                _telegram = telegram;
                int dcId = (int)_document.DcId;

                //initialize the dc we want to download from
                if (_document.DcId != _telegram.Settings.NearestDcId)
                {
Retry:
                    // if its not the nearest dc, it could be unintialized. so lets check and init it.
                    var dc = DcDatabase.Get(dcId);
                    if (dc == null)
                    {
                        _telegram.GetClient(dcId);
                        //after this our dc configuration is ready, the connection should die out in a 60 secs.
                    }
                    var dcCached = DcDatabase.Get(dcId);
                    if (dcCached == null)
                    {
                        return;
                    }
                    var dcOption  = _telegram.Config.DcOptions.Cast <DcOption>().FirstOrDefault(x => x.Id == dcId);
                    var tcpConfig = new TcpClientTransportConfig(dcOption.IpAddress, (int)dcOption.Port);
                    var authInfo  = new SharpMTProto.Authentication.AuthInfo(dcCached.Key,
                                                                             BitConverter.ToUInt64(dcCached.Salt, 0));
                    _client = new TelegramClient(tcpConfig,
                                                 new ConnectionConfig(authInfo.AuthKey, authInfo.Salt), AppInfo);
                    TelegramUtils.RunSynchronously(_client.Connect());
                    try
                    {
                        TelegramUtils.RunSynchronously(_client.Methods.AccountGetAccountTTLAsync(new AccountGetAccountTTLArgs()));
                    }
                    catch (Exception x)
                    {
                        if (x.Message != null && x.Message.Contains("401"))
                        {
                            telegram.DebugPrint("Yikes! DC went down. Let's reinstate it...");
                            _client.Dispose();
                            DcDatabase.Delete(dcId);
                            goto Retry;
                        }
                    }
                }
                else
                {
                    var tcpConfig = new TcpClientTransportConfig(_telegram.Settings.NearestDcIp, (int)_telegram.Settings.NearestDcPort);
                    var authInfo  = new SharpMTProto.Authentication.AuthInfo(_telegram.Settings.AuthKey,
                                                                             _telegram.Settings.Salt);
                    _client = new TelegramClient(tcpConfig,
                                                 new ConnectionConfig(authInfo.AuthKey, authInfo.Salt), AppInfo);
                    TelegramUtils.RunSynchronously(_client.Connect());
                }
            }
コード例 #6
0
 //Stop the bot, and dispose of objects.
 public bool Stop()
 {
     try
     {
         client.Dispose();
         return(true);
     }
     catch (Exception e)
     {
         Console.Out.WriteLine(e.Message);
         return(false);
     }
 }
コード例 #7
0
        public async Task <bool> LogIn(int key, string token, string phone)
        {
            try
            {
                if (_client == null)
                {
                    _client = new TelegramClient(key, token);
                    await _client.ConnectAsync();
                }
                if (_user != null)
                {
                    return(true);
                }
                _phone = phone;

                var hash = await _client.SendCodeRequestAsync(_phone);

                string code = "";

                Application.Current.Dispatcher.Invoke(() =>
                {
                    var input = new InputBox();
                    input.ShowDialog();
                    code = input.Code;
                });

                if (string.IsNullOrEmpty(code))
                {
                    MessageBox.Show("Empty code!");
                    return(false);
                }

                _user = await _client.MakeAuthAsync(_phone, hash, code);

                if (_user != null)
                {
                    return(true);
                }

                return(false);
            }
            catch (Exception e)
            {
                _client?.Dispose();
                _client = null;
                _user   = null;
                return(false);
            }
        }
コード例 #8
0
ファイル: TelegramAuth.cs プロジェクト: str1py/Ducky
        public async Task LogOut()
        {
            try
            {
                Properties.Socials.Default.TelegramUserID = 0;
                Properties.Socials.Default.Save();
                var  LogOut = new TLRequestLogOut();
                bool lo     = await client.SendRequestAsync <Boolean>(LogOut);

                client.Dispose();
                string dic = Directory.GetCurrentDirectory();
                File.Delete(dic + "session.dat");
            }catch (Exception e)
            {
                MethodBase m = MethodBase.GetCurrentMethod();
                log.AddLog("ERROR : ", e.Message, "Error in ", m.DeclaringType.Name);
            }
        }
コード例 #9
0
 public void Dispose()
 {
     _client.Dispose();
 }
コード例 #10
0
ファイル: TelegramService.cs プロジェクト: jorgelg/TelegramWS
        public async Task <Respuestas> AutenticarUsuario(string codigo, string filepath)
        {
            try
            {
                Respuestas respuesta = new Respuestas();
                contexto = Iniciar();
                TLContacts contactos = new TLContacts();
                info = CargarDeArchivo <Informacion_sesion>(filepath);
                info.Codigo_autenticacion = codigo;
                TLUser usuario = null;
                await contexto.ConnectAsync();

                if (contexto.IsConnected)
                {
                    usuario = await contexto.MakeAuthAsync(info.NumeroPropietario, info.Codigo_solicitud, info.Codigo_autenticacion);

                    if (usuario != null)
                    {
                        info.NombreUsuario = usuario.FirstName;
                        contactos          = await contexto.GetContactsAsync();

                        List <Usuarios> lista = new List <Usuarios>();
                        foreach (var item in contactos.Users.OfType <TLUser>())
                        {
                            var contacto = new Usuarios
                            {
                                Nombre   = item.FirstName + " " + item.LastName,
                                Telefono = "+" + item.Phone
                            };
                            lista.Add(contacto);
                        }
                        info.contactos = lista.OrderBy(x => x.Nombre).ToList();
                        JObject objeto = JObject.Parse(File.ReadAllText(filepath.Replace("Registros.txt", "Sesion.txt")));
                        info.Expiracion.Add(DateTime.Now.AddMilliseconds(objeto.Value <double>("SessionExpires")).ToString("MM/dd/yy H:mm:ss"));
                        GuardarArchivo(filepath, info);
                        respuesta.STATUS  = true;
                        respuesta.MESSAGE = "Autenticación exitosa...";
                        respuesta.data    = info;
                        return(respuesta);
                    }
                    else
                    {
                        respuesta.MESSAGE = "no se pudo obtener datos de usuario...";
                        respuesta.STATUS  = false;
                        return(respuesta);
                    }
                }
                else
                {
                    respuesta.MESSAGE = "ya se encuentra autenticado...";
                    respuesta.STATUS  = false;
                    contexto.Dispose();
                    return(respuesta);
                }
            }
            catch (Exception e)
            {
                return(new Respuestas()
                {
                    STATUS = false, MESSAGE = "No se pudo autenticar usuario" + e.InnerException.Message
                });
            }
        }
コード例 #11
0
 public void LogOut()
 {
     _client.Dispose();
 }
コード例 #12
0
 public void Dispose()
 {
     m_telegramClient?.Dispose();
 }
コード例 #13
0
        private TelegramClient SpinUpClient(int dc)
        {
            object dcLock;

            lock (_spinUpLocks)
            {
                if (_spinUpLocks.ContainsKey(dc))
                {
                    dcLock = _spinUpLocks[dc];
                }
                else
                {
                    dcLock           = new object();
                    _spinUpLocks[dc] = dcLock;
                }
            }

            lock (dcLock)
            {
                var client = GetClientInternal(dc);
                if (client != null)
                {
                    return(client);
                }

Retry:

                if (_config == null)
                {
                    DebugPrint("Config is null. Unable to resolve DC information.");
                    return(null);
                }

                var dcOption = _config.DcOptions.Cast <DcOption>().FirstOrDefault(x => x.Id == dc);

                if (dcOption == null)
                {
                    DebugPrint("Unable to find DC for DC ID: " + dc);
                    return(null);
                }

                var dcCached = DcDatabase.Get(dc);

                var transportConfig =
                    new TcpClientTransportConfig(dcOption.IpAddress, (int)dcOption.Port);

                SharpMTProto.Authentication.AuthInfo authInfo;
                AuthExportedAuthorization            exportedAuth = null;

                if (dcCached == null)
                {
                    DebugPrint("Looks like we'll have to authenticate a new connection to: "
                               + ObjectDumper.Dump(dcOption));

                    DebugPrint(">>>>>>>> Exporting auth...");

                    using (var clientDisposable = new FullClientDisposable(this))
                    {
                        exportedAuth = (AuthExportedAuthorization)TelegramUtils.RunSynchronously(clientDisposable.Client.Methods.AuthExportAuthorizationAsync(
                                                                                                     new SharpTelegram.Schema.AuthExportAuthorizationArgs
                        {
                            DcId = (uint)dc,
                        }));
                    }

                    DebugPrint(">>>>>>> Got exported auth.");

                    if (exportedAuth == null)
                    {
                        DebugPrint("Exported auth is null for some weird reason. DC ID: " + dc);
                        return(null);
                    }

                    DebugPrint(">>>>>>> Fetching new authentication...");

                    authInfo = TelegramUtils.RunSynchronously(FetchNewAuthentication(transportConfig));
                }
                else
                {
                    authInfo = new SharpMTProto.Authentication.AuthInfo(dcCached.Key,
                                                                        BitConverter.ToUInt64(dcCached.Salt, 0));
                }

                DebugPrint(">>>>>>>> Starting new client...");

                var newClient = new TelegramClient(transportConfig,
                                                   new ConnectionConfig(authInfo.AuthKey, authInfo.Salt), AppInfo);

                newClient.OnClosedInternally += (sender, e) =>
                {
                    DebugPrint("Removing connection to DC: " + dc);
                    lock (_activeClients)
                    {
                        _activeClients.Remove(dc);
                    }
                };

                var result = TelegramUtils.RunSynchronously(newClient.Connect());
                if (result != MTProtoConnectResult.Success)
                {
                    DebugPrint("Failed to connect to DC: " + dc + ": " + result);
                    return(null);
                }

                if (exportedAuth != null)
                {
                    TelegramUtils.RunSynchronously(newClient.Methods.AuthImportAuthorizationAsync(new AuthImportAuthorizationArgs
                    {
                        Id    = exportedAuth.Id,
                        Bytes = exportedAuth.Bytes,
                    }));
                }

                try
                {
                    TelegramUtils.RunSynchronously(newClient.Methods.AccountGetAccountTTLAsync(new AccountGetAccountTTLArgs()));
                }
                catch (Exception x)
                {
                    if (x.Message != null && x.Message.Contains("401"))
                    {
                        DebugPrint("Yikes! DC went down. Let's reinstate it...");
                        newClient.Dispose();
                        DcDatabase.Delete(dc);
                        goto Retry;
                    }
                }

                PingDelay(newClient, 60);

                lock (_activeClients)
                {
                    _activeClients[dc] = newClient;
                }

                if (dcCached == null)
                {
                    DcDatabase.Set(new TelegramDc
                    {
                        Dc   = dc,
                        Key  = authInfo.AuthKey,
                        Salt = BitConverter.GetBytes(authInfo.Salt),
                    });
                }

                return(newClient);
            }
        }