Esempio n. 1
0
        public static async void NavigateToProxy(IProtoService protoService, string server, int port, string username, string password, string secret)
        {
            var userText   = username != null ? $"{Strings.Resources.UseProxyUsername}: {username}\n" : string.Empty;
            var passText   = password != null ? $"{Strings.Resources.UseProxyPassword}: {password}\n" : string.Empty;
            var secretText = secret != null ? $"{Strings.Resources.UseProxySecret}: {secret}\n" : string.Empty;
            var secretInfo = secret != null ? $"\n\n{Strings.Resources.UseProxyTelegramInfo2}" : string.Empty;
            var confirm    = await TLMessageDialog.ShowAsync($"{Strings.Resources.EnableProxyAlert}\n\n{Strings.Resources.UseProxyAddress}: {server}\n{Strings.Resources.UseProxyPort}: {port}\n{userText}{passText}{secretText}\n{Strings.Resources.EnableProxyAlert2}{secretInfo}", Strings.Resources.Proxy, Strings.Resources.ConnectingConnectProxy, Strings.Resources.Cancel);

            if (confirm == ContentDialogResult.Primary)
            {
                ProxyType type;
                if (secret != null)
                {
                    type = new ProxyTypeMtproto(secret);
                }
                else
                {
                    type = new ProxyTypeSocks5(username ?? string.Empty, password ?? string.Empty);
                }

                protoService.Send(new AddProxy(server ?? string.Empty, port, true, type));
            }
        }
Esempio n. 2
0
        /// <summary>
        /// initializes api instance
        /// </summary>
        /// <param name="debugMode">determines if software is in debug mode</param>
        /// <param name="token">cancellation token to stop tasks</param>
        internal void Initialize(bool debugMode, CancellationToken token)
        {
            #region tdlib log file path

            // file to write tdlib log in
            string tdlibLogFilePath = $"tdlibLog-{_setting.name}.txt";

            // setting log file path
            if (tdLib.Client.Execute(new tdApi.SetLogStream(new tdApi.LogStreamFile(tdlibLogFilePath, 1 << 27, false))) is tdApi.Error)
            {
                throw new System.IO.IOException("Write access to the current directory is required");
            }

            #endregion tdlib log file path

            // disabling log if software is not in debug mode
            if (!debugMode)
            {
                // fatal errors only
                tdLib.Client.Execute(new tdApi.SetLogVerbosityLevel(0));
            }

            #region adding some global handlers

            addGlobalHandler(typeof(UpdateAuthorizationState), async(obj) =>
            {
                // casting update
                AuthorizationState authorizationState = (obj as UpdateAuthorizationState).AuthorizationState;
                if (authorizationState is AuthorizationStateClosed)
                {
                    _authorizationState = Enum.AuhtorizationState.Closed;
                }
                else if (authorizationState is AuthorizationStateClosing)
                {
                    _authorizationState = Enum.AuhtorizationState.Closing;
                }
                else if (authorizationState is AuthorizationStateLoggingOut)
                {
                    _authorizationState = Enum.AuhtorizationState.LoggingOut;
                }
                else if (authorizationState is AuthorizationStateReady)
                {
                    _authorizationState = Enum.AuhtorizationState.Ready;

                    // check if function to call when state is ready is set
                    if (onReady is null)
                    {
                        throw new Exception("There is no function call when authentication is ready is not set");
                    }

                    // invoking function
                    onReady.Invoke(this);
                }
                else if (authorizationState is AuthorizationStateWaitEncryptionKey)
                {
                    _authorizationState = Enum.AuhtorizationState.BackgroundActions;
                    await executeCommand(new CheckDatabaseEncryptionKey(), typeof(Ok));

                    #region set proxy

                    // check if proxy setting exists
                    if (_setting.proxy != null)
                    {
                        ProxyType type;
                        switch (_setting.proxy.type)
                        {
                        case Enum.ProxyType.MTProto:
                            type = new ProxyTypeMtproto();
                            break;

                        case Enum.ProxyType.Socks5:
                            type = new ProxyTypeSocks5();
                            break;

                        default:
                            type = new ProxyTypeHttp();
                            break;
                        }

                        // sending and enabling proxy
                        var res = await executeCommand(new AddProxy(_setting.proxy.ip, _setting.proxy.port, true, type), typeof(Proxy));

                        if (res.status == Enum.ResponseStatus.Success)
                        {
                            Logger.Debug("proxy enabled successfully");
                        }
                        else
                        {
                            Logger.Debug("proxy enabling failed, => {0}", res.obj.JSONSerialize());
                        }
                    }
                    else
                    {
                        // disabling proxy
                        var res = await executeCommand(new DisableProxy());
                        if (res.status == Enum.ResponseStatus.Success)
                        {
                            Logger.Debug("proxy disabled successfully");
                        }
                        else
                        {
                            Logger.Debug("proxy enabdisabledling failed, => {0}", res.obj.JSONSerialize());
                        }
                    }

                    #endregion set proxy
                }
                else if (authorizationState is AuthorizationStateWaitOtherDeviceConfirmation)
                {
                    _authorizationState = Enum.AuhtorizationState.BackgroundActions;
                }
                else if (authorizationState is AuthorizationStateWaitPhoneNumber)
                {
                    _authorizationState = Enum.AuhtorizationState.WaitingForPhoneNumber;

                    // check if function to get phone number is set
                    if (onPhoneNumberRequired is null)
                    {
                        throw new Exception("There is no function to get phone number from");
                    }

                    runLocked(async() =>
                    {
                        // gathering phone number
                        string phoneNumber = onPhoneNumberRequired(_setting.name);

                        await executeCommand(new SetAuthenticationPhoneNumber(phoneNumber, new PhoneNumberAuthenticationSettings()
                        {
                            AllowFlashCall       = true,
                            AllowSmsRetrieverApi = true
                        }));
                    });
                }
                else if (authorizationState is AuthorizationStateWaitCode)
                {
                    _authorizationState = Enum.AuhtorizationState.WaitingForVerificationCode;

                    // check if function to get phone number is set
                    if (onVerificationCodeRequired is null)
                    {
                        throw new Exception("There is no function to get verification code from");
                    }

                    runLocked(async() =>
                    {
                        // gathering verification code form user provided function
                        string code = onVerificationCodeRequired(_setting.name);

                        await executeCommand(new CheckAuthenticationCode(code));
                    });
                }
                else if (authorizationState is AuthorizationStateWaitPassword)
                {
                    _authorizationState = Enum.AuhtorizationState.WaitingForVerificationPassword;

                    // check if function to get password is set
                    if (onPasswordRequired is null)
                    {
                        throw new Exception("There is no function to get password from");
                    }

                    runLocked(async() =>
                    {
                        // gathering password form user provided function
                        string password = onPasswordRequired(_setting.name);

                        await executeCommand(new CheckAuthenticationPassword(password));
                    });
                }
                else if (authorizationState is AuthorizationStateWaitTdlibParameters)
                {
                    _authorizationState = Enum.AuhtorizationState.BackgroundActions;
                    var res             = await executeCommand(new SetTdlibParameters(new TdlibParameters()
                    {
                        ApiHash                = _setting.api_hash,
                        ApiId                  = _setting.api_id,
                        ApplicationVersion     = "1.3.1",
                        DeviceModel            = "Desktop",
                        SystemLanguageCode     = "en",
                        UseSecretChats         = true,
                        UseMessageDatabase     = true,
                        UseChatInfoDatabase    = true,
                        EnableStorageOptimizer = true,
                        DatabaseDirectory      = $"TDLibCoreData-{_setting.name}"
                    }), typeof(Ok));
                }
                else
                {
                    _authorizationState = Enum.AuhtorizationState.InvalidData;
                }
            });
            addGlobalHandler(typeof(UpdateConnectionState), (obj) =>
            {
                // casting update
                ConnectionState update = (obj as UpdateConnectionState).State;

                if (update is ConnectionStateConnecting)
                {
                    _connectionState = Enum.ConnectionState.Connecting;
                }
                else if (update is ConnectionStateConnectingToProxy)
                {
                    _connectionState = Enum.ConnectionState.ConnectingToProxy;
                }
                else if (update is ConnectionStateReady)
                {
                    _connectionState = Enum.ConnectionState.Connected;
                }
                else if (update is ConnectionStateUpdating)
                {
                    _connectionState = Enum.ConnectionState.Updating;
                }
                else if (update is ConnectionStateWaitingForNetwork)
                {
                    _connectionState = Enum.ConnectionState.WaitingForNetwork;
                }
                else
                {
                    _connectionState = Enum.ConnectionState.InvalidData;
                }
            });

            #endregion adding some global handlers

            // we run core only if it's first time in whole application
            if (!tdlibInitialized)
            {
                // starting client
                _ = Task.Factory.StartNew(() =>
                {
                    // we run core
                    tdLib.Client.Run();
                }, token);

                // preventing from double running tdlib
                tdlibInitialized = true;
            }

            // generating clinet instance
            _client = tdLib.Client.Create(_responseHandler);

            _initialized = true;
        }