Esempio n. 1
0
        private static async Task <(string, string)> Request(LoginKey key, string path, Dictionary <string, string> queryParams)
        {
            if (queryParams == null)
            {
                queryParams = new Dictionary <string, string>();
            }

            queryParams["countryCode"] = key.CountryCode;
            var url = HttpHelper.BuildQueryString(new Uri(BASE_URL + path), queryParams);

            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("X-Tidal-SessionId", key.SessionID.ToString());
                if (!string.IsNullOrWhiteSpace(key.AccessToken))
                {
                    client.DefaultRequestHeaders.Add("authorization", $"Bearer { key.AccessToken}");
                }

                try
                {
                    var response = await client.GetAsync(url);

                    if (!response.IsSuccessStatusCode)
                    {
                        return(response.ReasonPhrase, null);
                    }

                    return(null, await response.Content.ReadAsStringAsync());
                } catch (HttpRequestException e)
                {
                    return($"Exception while sending HTTP GET-Request: {e}", null);
                }
            }
        }
Esempio n. 2
0
        public ProtectedAccount(JsonAccounts.JsonAccount json) : base(json)
        {
            _log = LogCreator.Create("GC - " + json.Username + (!Titan.Instance.Options.Secure ? " (Protected)" : ""));

            _steamConfig = SteamConfiguration.Create(builder =>
            {
                builder.WithConnectionTimeout(TimeSpan.FromMinutes(1));

                var key = Titan.Instance.WebHandle.GetKey();

                if (!string.IsNullOrEmpty(key))
                {
                    builder.WithWebAPIKey(key);
                    _log.Debug("Initializing with preloaded API key.");
                }
                else
                {
                    _log.Debug("Initializing without API key.");
                }
            });

            _sentry   = new Sentry.Sentry(this);
            _loginKey = new LoginKey(this);

            _steamClient     = new SteamClient(_steamConfig);
            _callbacks       = new CallbackManager(_steamClient);
            _steamUser       = _steamClient.GetHandler <SteamUser>();
            _steamFriends    = _steamClient.GetHandler <SteamFriends>();
            _gameCoordinator = _steamClient.GetHandler <SteamGameCoordinator>();

            // This clause excludes SteamKit debug mode as that mode is handeled seperately.
            // Normal debug mode doesn't equal SteamKit debug mode.
            if (Titan.Instance.Options.Debug)
            {
                _titanHandle = new TitanHandler();
                _steamClient.AddHandler(_titanHandle);

                // Initialize debug network sniffer when debug mode is enabled
                var dir = new DirectoryInfo(Path.Combine(Titan.Instance.DebugDirectory.ToString(), json.Username));
                if (!dir.Exists)
                {
                    dir.Create();
                }

                _steamClient.DebugNetworkListener = new NetHookNetworkListener(
                    dir.ToString()
                    );
            }

            if (!string.IsNullOrWhiteSpace(JsonAccount.SharedSecret))
            {
                _sharedSecretGenerator = new SharedSecret(this);
            }

            _log.Debug("Successfully initialized account object for " + json.Username + ".");
        }
Esempio n. 3
0
        public async virtual Task <IUserLoginState> GetUserLoginAsync(string userId, LoginKey loginKey)
        {
            var uriParameters = new UserLoginUriParameters();

            uriParameters.UserId   = userId;
            uriParameters.LoginKey = (new LoginKeyFlattenedDtoFormatter()).ToString(new LoginKeyFlattenedDto(loginKey));

            var req  = new UserLoginGetRequest(uriParameters);
            var resp = await _ramlClient.UserLogin.Get(req);

            UserProxyUtils.ThrowOnHttpResponseError(resp);
            return(resp.Content);
        }
Esempio n. 4
0
        public void Download()
        {
            LoginKey key = Tools.GetKey(true);

            //GetStream
            Progress.StatusMsg        = "GetStream...";
            (Progress.Errmsg, Stream) = Client.GetVideStreamUrl(key, TidalVideo.ID, Settings.VideoQuality).Result;
            if (Progress.Errmsg.IsNotBlank() || Stream == null)
            {
                goto ERR_RETURN;
            }

            Codec = Stream.Resolution;
            Progress.StatusMsg = "GetStream success...";

            //Get path
            string path = Tools.GetVideoPath(Settings, TidalVideo, TidalAlbum, TidalPlaylist, ".mp4");

            //Download
            string errmsg = "";

            Progress.StatusMsg = "Start...";
            string[] tsurls = M3u8Helper.GetTsUrls(Stream.M3u8Url);
            if (!(bool)M3u8Helper.Download(tsurls, path, UpdateDownloadNotify, ref errmsg, Proxy: key.Proxy))
            {
                Progress.Errmsg = "Download failed!" + errmsg;
                goto ERR_RETURN;
            }

            ////Convert
            //(Progress.Errmsg, path) = Tools.ConvertTsToMp4(path);
            //if (Progress.Errmsg.IsNotBlank() )
            //    goto ERR_RETURN;

            Progress.SetStatus(ProgressHelper.STATUS.COMPLETE);
            goto CALL_RETURN;

ERR_RETURN:
            if (Progress.GetStatus() == ProgressHelper.STATUS.CANCLE)
            {
                goto CALL_RETURN;
            }

            Progress.SetStatus(ProgressHelper.STATUS.ERROR);

CALL_RETURN:
            TellParentOver();

            DownloadSpeedString = "";
        }
Esempio n. 5
0
        public LoginUser Registrar(UserRegistrationModel model)
        {
            using (StudenAppHelperDBEntities conect = new StudenAppHelperDBEntities())
            {
                var Usuario = (from US in conect.Usurio where US.DocumentoUsuario == model.Identificacion && US.TipoDocumento == (int)model.TipoDocumento select US).FirstOrDefault();
                if (Usuario == null)
                {
                    Usuario = new Usurio();
                    Usuario.NombrePrimero    = model.NombreP;
                    Usuario.NombreSegundo    = model.NombreS;
                    Usuario.ApellidoPrimer   = model.ApellidoP;
                    Usuario.ApellidoSegundo  = model.ApellidoS;
                    Usuario.TipoDocumento    = (int)model.TipoDocumento;
                    Usuario.DocumentoUsuario = model.Identificacion;
                    Usuario.TipoUsuario      = (int)TipoUsuarios.Administrador;
                    Usuario.FechaNacimiento  = null;
                    conect.Usurio.Add(Usuario);
                    conect.SaveChanges();
                }

                var LoginRej = (from LK in conect.LoginKey where LK.loginUser == model.UserName select LK).FirstOrDefault();
                if (LoginRej == null)
                {
                    LoginRej             = new LoginKey();
                    LoginRej.loginUser   = model.UserName;
                    LoginRej.loginPass   = model.Password;
                    LoginRej.loginKey1   = Guid.NewGuid().ToString();
                    LoginRej.fechaAcceso = null;
                    conect.LoginKey.Add(LoginRej);
                    conect.SaveChanges();

                    Logueo UserLogeo = new Logueo();
                    UserLogeo.IdUsuario   = Usuario.IdUsuario;
                    UserLogeo.LoginKeyID  = LoginRej.LoginKeyID;
                    UserLogeo.TipoLoginID = (int)TipoLogin.Custom;
                    conect.Logueo.Add(UserLogeo);
                    conect.SaveChanges();
                }
                else
                {
                    LoginUser user = new LoginUser()
                    {
                        UserName  = LoginRej.loginUser,
                        UserModel = model
                    };
                    return(user);
                }
            }
            return(null);
        }
        public override byte[] Build()
        {
            MemoryStream ms     = new MemoryStream(Size);
            Writer       writer = new Writer(ms);

            writer.Write(Id);
            writer.WriteString(Login, Encoding.Unicode);
            writer.Write(GameKey.Skip(4).ToArray());
            writer.Write(LoginKey.Take(4).ToArray());
            writer.Write(GameKey.Take(4).ToArray());
            writer.Write(LoginKey.Skip(4).ToArray());
            writer.Write((Int32)1);

            return(ms.GetBuffer());
        }
Esempio n. 7
0
        /// <summary>
        /// Sends an email with an expirating one time login link for subscriber to gain access to their
        /// account and preferences in the application
        /// </summary>
        /// <param name="subscriber">The Subscriber to send the login link to.</param>
        /// <returns>Bool as to the success of this call with the EmailService.</returns>
        public async Task <bool> SendLoginKeyEmailAsync(string email)
        {
            try
            {
                if (string.IsNullOrEmpty(email))
                {
                    throw new ArgumentNullException(nameof(email));
                }
                LoginKey key = LoginKey.GenerateFor(email);
                await _dataService.ExecuteInsertAsync(key);

                return(await _retryPolicy.ExecuteAsync(async() => await _emailSender.SendLoginKeyEmailAsync(email, key.Kee)));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"Failure to send login email {email}, {ex.Message}, {ex.StackTrace}");
                return(false);
            }
        }
Esempio n. 8
0
        /// <summary>
        /// Sends a one time login link via SMS to a susbscribers phone number
        /// </summary>
        /// <param name="phoneDigits">The subscriber phone number send a login link to</param>
        /// <returns>Whether or not the SMS message sent successfully</returns>
        public async Task <bool> SendLoginKeySMSAsync(string phoneDigits)
        {
            if (string.IsNullOrEmpty(phoneDigits))
            {
                throw new ArgumentNullException(nameof(phoneDigits));
            }
            LoginKey key = LoginKey.GenerateFor(phoneDigits);

            try
            {
                await _dataService.ExecuteInsertAsync(key);

                var txt = $"Your login link: https://{_smsSettings.Host}/api/login-with-key/{phoneDigits}/{key.Kee}";
                return(await _retryPolicy.ExecuteAsync(async() => await _smsSender.SendMessageAsync(phoneDigits, _smsSettings.VerificationNumber, txt)));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"Failure to send login SMS {phoneDigits}, {ex.Message}, {ex.StackTrace}");
                return(false);
            }
        }
        //Update
        public void StartUpdate()
        {
            Progress.ValueInt  = 0;
            CountIncreSize     = 0;
            ShowProgress       = Visibility.Visible;
            DownloadStatusInfo = Language.Get("strmsgGetNewVersionUrl");

            string url = GithubHelper.getFileUrl(Global.NAME_GITHUB_AUTHOR, Global.NAME_GITHUB_PROJECT, LastVersion, Global.NAME_GITHUB_FILE);

            if (PathHelper.Mkdirs(Global.PATH_UPDATE) == false)
            {
                DownloadStatusInfo = Language.Get("strmsgCreatUpdateFolderFailed");
                EndUpdate();
                return;
            }

            DownloadStatusInfo = Language.Get("strmsgStartUpdate");
            Progress.SetStatus(ProgressHelper.STATUS.RUNNING);
            StartTime = TimeHelper.GetCurrentTime();
            LoginKey key = Tools.GetKey();

            DownloadFileHepler.StartAsync(url, Global.PATH_UPDATE + Global.NAME_GITHUB_FILE, null, UpdateDownloadNotify, CompleteDownloadNotify, ErrDownloadNotify, 3, Proxy: key.Proxy);
        }
Esempio n. 10
0
        public static bool Login(LoginKey loginKey)
        {
            _loginKey = loginKey;
            var client = new RestClient(Url);

            client.Authenticator = new HttpBasicAuthenticator(_loginKey.Login, _loginKey.Pass);
            var request = new RestRequest("/api/2/trading/balance", Method.GET);

            request.RequestFormat = DataFormat.Json;
            var result = client.Execute <List <Balance> >(request);

            if (result.IsSuccessful)
            {
                IsLogin = true;
                OnLoginEvent();
                return(true);
            }
            else
            {
                IsLogin = false;
                return(false);
            }
        }
        public void Download()
        {
            try
            {
                LoginKey key = Tools.GetKey();

                //GetStream
                Progress.StatusMsg        = "GetStream...";
                (Progress.Errmsg, Stream) = Client.GetTrackStreamUrl(key, TidalTrack.ID, Settings.AudioQuality).Result;
                if (Progress.Errmsg.IsNotBlank() || Stream == null)
                {
                    goto ERR_RETURN;
                }

                Codec = Stream.Codec;
                Progress.StatusMsg = "GetStream success...";

                if (TidalAlbum == null && TidalTrack.Album != null)
                {
                    string tmpmsg;
                    (tmpmsg, TidalAlbum) = Client.GetAlbum(key, TidalTrack.Album.ID, false).Result;
                }

                //Get path
                string path = Tools.GetTrackPath(Settings, TidalTrack, Stream, TidalAlbum, TidalPlaylist);

                //Check if song downloaded already
                string checkpath = Settings.OnlyM4a ? path.Replace(".mp4", ".m4a") : path;
                if (Settings.CheckExist && System.IO.File.Exists(checkpath))
                {
                    Progress.UpdateInt(100, 100);
                    Progress.SetStatus(ProgressHelper.STATUS.COMPLETE);
                    goto CALL_RETURN;
                }

                //Download
                Progress.StatusMsg = "Start...";
                for (int i = 0; i < 50 && Progress.GetStatus() != ProgressHelper.STATUS.CANCLE; i++)
                {
                    StartTime = TimeHelper.GetCurrentTime();
                    if ((bool)DownloadFileHepler.Start(Stream.Url, path, Timeout: 5 * 1000, UpdateFunc: UpdateDownloadNotify, ErrFunc: ErrDownloadNotify, Proxy: key.Proxy))
                    {
                        //Decrypt
                        if (!Tools.DecryptTrackFile(Stream, path))
                        {
                            Progress.Errmsg = "Decrypt failed!";
                            goto ERR_RETURN;
                        }

                        if (Settings.OnlyM4a)
                        {
                            (Progress.Errmsg, path) = Tools.ConvertMp4ToM4a(path, Stream);
                            if (Progress.Errmsg.IsNotBlank())
                            {
                                goto ERR_RETURN;
                            }
                        }

                        //SetMetaData
                        if (TidalAlbum == null)
                        {
                            (Progress.Errmsg, TidalAlbum) = Client.GetAlbum(key, TidalTrack.Album.ID, false).Result;
                        }
                        Progress.Errmsg = Tools.SetMetaData(path, TidalAlbum, TidalTrack);
                        if (Progress.Errmsg.IsNotBlank())
                        {
                            Progress.Errmsg = "Set metadata failed!" + Progress.Errmsg;
                            goto ERR_RETURN;
                        }

                        Progress.SetStatus(ProgressHelper.STATUS.COMPLETE);
                        goto CALL_RETURN;
                    }
                }
                Progress.Errmsg = "Download failed!";
                System.IO.File.Delete(path);
            }
            catch (Exception e)
            {
                Progress.Errmsg = "Download failed!" + e.Message;
            }

ERR_RETURN:
            if (Progress.GetStatus() == ProgressHelper.STATUS.CANCLE)
            {
                goto CALL_RETURN;
            }
            Progress.SetStatus(ProgressHelper.STATUS.ERROR);

CALL_RETURN:
            TellParentOver();

            DownloadSpeedString = "";
        }
        public virtual IUserLoginState GetUserLogin(string userId, LoginKey loginKey)
        {
            var entityId = new UserLoginId(userId, loginKey);

            return(CurrentSession.Get <UserLoginState>(entityId));
        }
Esempio n. 13
0
 public virtual IUserLoginState GetUserLogin(string userId, LoginKey loginKey)
 {
     return(GetUserLoginAsync(userId, loginKey).GetAwaiter().GetResult());
 }