Пример #1
0
    public void LoginStepTwo(SpotifyAccount account, ClientCall invoker)
    {
        //get Email
        string information = "";

        information += "Now your Spotify-E-Mail.";
        Ts3Client.SendMessage(information, invoker.ClientId.Value);

        void handler(object sender, TextMessage textMessage)
        {
            if (textMessage.InvokerId == invoker.ClientId)
            {
                string mail = textMessage.Message.ToString();
                Match  m    = Regex.Match(mail, @"\[URL=.*\](.*)\[\/URL\]");
                if (m.Success)
                {
                    account.email = m.Groups[m.Groups.Count - 1].Value;
                }
                else
                {
                    account.email = mail;
                }

                Ts3Client.OnMessageReceived -= handler;
                LoginStepThree(account, invoker);
            }
        };

        Ts3Client.OnMessageReceived += handler;
    }
Пример #2
0
    public bool _startControl(ClientCall invoker)
    {
        if (activeSpotifyAccount != null)
        {
            return(false);
        }
        SpotifyAccount account = spotifyPluginConfig.getAccount(invoker.ClientUid.Value);

        if (!account.Exists())
        {
            return(false);
        }
        SpotifyControl tempControl = new SpotifyControl(spotifyPluginConfig, rootConf);

        tempControl._refreshtoken(account.refreshToken).Wait();

        if (!tempControl.hasInit())
        {
            return(false);
        }

        activeSpotifyAccount = account;
        activeSpotifyAccount.setClient(invoker.ClientId.ToString());


        activeSpotifyControl = tempControl;
        activeSpotifyControl.setTimer(activeSpotifyAccount.refreshToken);

        return(true);
    }
Пример #3
0
    public void LoginStepOne(SpotifyAccount account, ClientCall invoker)
    {
        //get Auth-Key
        account.id = invoker.ClientUid.Value;
        var newControl = new SpotifyControl(spotifyPluginConfig, rootConf);

        newControl.firstTimeLogin((link) =>
        {
            string information = "";
            information       += "Grant rights and place the code from GET-Param into this chat.";
            Ts3Client.SendMessage(information, invoker.ClientId.Value);
            Ts3Client.SendMessage(link, invoker.ClientId.Value);

            void handler(object sender, TextMessage textMessage)
            {
                if (textMessage.InvokerId == invoker.ClientId)
                {
                    account.code = textMessage.Message.ToString();
                    Ts3Client.OnMessageReceived -= handler;
                    LoginStepTwo(account, invoker);
                }
            };

            Ts3Client.OnMessageReceived += handler;
        });
    }
Пример #4
0
    public string CommandSpotifyAccountEdit(ClientCall invoker, string property)
    {
        SpotifyAccount account = spotifyPluginConfig.getAccount(invoker.ClientUid.Value);

        if (!account.Exists())
        {
            return("No account found.");
        }

        property = property.ToLower();

        if (property == "pass" || property == "password" || property == "passwort")
        {
            LoginStepThree(account, invoker); //follow it, we dont store passwords
        }
        else if (property == "auth")
        {
            LoginStepOne(account, invoker);
        }
        else
        {
            return("Not found.");
        }

        return("");
    }
Пример #5
0
        public async Task AddOrUpdateUserAccountAsync(SpotifyAccount account, CancellationToken ct)
        {
            await Table.CreateIfNotExistsAsync();

            account.PartitionKey = "root";
            account.RowKey       = account.UserId;
            account.ETag         = "*";
            await Table.ExecuteAsync(TableOperation.InsertOrReplace(account));
        }
Пример #6
0
        public Task RemoveUserAccountAsync(ulong userId, CancellationToken ct)
        {
            var account = new SpotifyAccount()
            {
                UserId       = userId.ToString(),
                PartitionKey = "root",
                RowKey       = userId.ToString(),
                ETag         = "*"
            };

            return(Table.ExecuteAsync(TableOperation.Delete(account)));
        }
Пример #7
0
    public string CommandSpotifyAccountDelete(ClientCall invoker)
    {
        SpotifyAccount account = spotifyPluginConfig.getAccount(invoker.ClientUid.Value);

        if (account.Exists())
        {
            spotifyPluginConfig.removeAccount(account);
            saveConfig();
            return("Done.");
        }
        else
        {
            return("No Account found.");
        }
    }
Пример #8
0
    private void stopSpotify()
    {
        lock (_lock)
        {
            if (spotifyInstance != null && !spotifyInstance.hasExited())
            {
                spotifyInstance.stopProcess();
            }

            producer?.Dispose();
            producer             = null;
            spotifyInstance      = null;
            activeSpotifyControl = null;
            activeSpotifyAccount = null;
        }
    }
Пример #9
0
    public void LoginStepFour(SpotifyAccount account, ClientCall invoker, string password)
    {
        //Start Librespot and check Password
        string information = "";

        information += "Lets check it quickly.";
        Ts3Client.SendMessage(information, invoker.ClientId.Value);

        SpotifyInstance newInstance = new SpotifyInstance(spotifyPluginConfig, account);

        newInstance.useLogin(account.email, password);
        newInstance.startProcess();

        int tries = 0;

        while (!newInstance.connected && tries++ < 4)
        {
            Thread.Sleep(500);
        }

        if (!newInstance.connected || newInstance.hasExited())
        {
            Ts3Client.SendMessage("Credentials not right.", invoker.ClientId.Value);
            return;
        }


        SpotifyControl newControl = new SpotifyControl(spotifyPluginConfig, rootConf);

        newControl.logintoken(account.code, (bool success, bool tell, string accessToken, string refreshToken) =>
        {
            if (success)
            {
                account.refreshToken = refreshToken;
                account.accessToken  = accessToken;

                spotifyPluginConfig.accountList.Add(account);
                saveConfig();

                Ts3Client.SendMessage("You can use Spotify now.", invoker.ClientId.Value);
            }
            else
            {
                Ts3Client.SendMessage("Something went wrong check your Auth-Token.", invoker.ClientId.Value);
            }
        });
    }
Пример #10
0
    public void CommandSpotifyAccount(ClientCall invoker)
    {
        SpotifyAccount account            = spotifyPluginConfig.getAccount(invoker.ClientUid.Value);
        string         accountInformation = "";

        if (account.Exists())
        {
            accountInformation += "Your Accountinformation:\n\n";
            accountInformation += "Your E-Mail: " + account.email + "\n";
            accountInformation += "Your Code: " + account.code + "\n";
        }
        else
        {
            accountInformation += "Yout dont have an Spotify-Account stored. Type !spotify account add";
        }
        Ts3Client.SendMessage(accountInformation, invoker.ClientId.Value);
    }
Пример #11
0
    public void LoginStepThree(SpotifyAccount account, ClientCall invoker)
    {
        //get password
        string information = "";

        information += "Now your Spotify-Password.";
        Ts3Client.SendMessage(information, invoker.ClientId.Value);

        void handler(object sender, TextMessage textMessage)
        {
            if (textMessage.InvokerId == invoker.ClientId)
            {
                Ts3Client.OnMessageReceived -= handler;
                LoginStepFour(account, invoker, textMessage.Message.ToString());
            }
        };

        Ts3Client.OnMessageReceived += handler;
    }
Пример #12
0
        public async Task <ActionResult> AuthenticateAsync(string returnUrl)
        {
            var authResult = await ConnectToSpotifyAsync(_spotify);

            var userInfo = authResult.GetPrivateProfile();

            user = new SpotifyAccount()
            {
                SpotifyId = userInfo.Id,
                Username  = userInfo.DisplayName,
            };

            var userRepo  = new UnitOfWork().GetUsersRepository();
            var spAccRepo = new UnitOfWork().GetSpotifyAccountsRepository();
            var appUser   = userRepo.FirstOrDefault(i => i.Id == HttpContext.User.Identity.GetUserId());

            if (spAccRepo.FirstOrDefault(a => a.UserId == appUser.Id) == null)
            {
                try
                {
                    appUser.SpotifyAccount = user;
                    userRepo.Update(appUser);

                    userRepo.Save();
                }
                catch (Exception)
                {
                }
            }


            this.Session["SpotifyToken"] = authResult.AccessToken;

            if (string.IsNullOrWhiteSpace(returnUrl))
            {
                return(RedirectToAction("ManageLogins", "Manage"));
            }
            else
            {
                return(this.Redirect(returnUrl));
            }
        }
Пример #13
0
    public void CommandSpotifyAccountAdd(ClientCall invoker)
    {
        SpotifyAccount account = spotifyPluginConfig.getAccount(invoker.ClientUid.Value);

        bool cancel = false;

        if (spotifyPluginConfig.returnUrl.Length < 10)
        {
            Ts3Client.SendMessage("Return-URL is not set", invoker.ClientId.Value);
            cancel = true;
        }
        if (spotifyPluginConfig.clientSecret.Length < 10)
        {
            Ts3Client.SendMessage("clientSecret is not set", invoker.ClientId.Value);
            cancel = true;
        }
        if (spotifyPluginConfig.clientId.Length < 10)
        {
            Ts3Client.SendMessage("clientId is not set", invoker.ClientId.Value);
            cancel = true;
        }

        if (cancel == true)
        {
            Ts3Client.SendMessage("aborting", invoker.ClientId.Value);
            return;
        }

        if (account.Exists())
        {
            CommandSpotifyAccount(invoker);
        }
        else
        {
            string information = "Follow instructions";
            Ts3Client.SendMessage(information, invoker.ClientId.Value);
            LoginStepOne(account, invoker);
        }
    }
Пример #14
0
        public async Task <IActionResult> ConnectLanding()
        {
            _logger.LogInformation("Received Spotify OAuth2 authorization code");

            if (!Request.Cookies.TryGetValue("SpotifyOAuth2State", out var state))
            {
                return(BadRequest("Your session has expired, please try again."));
            }

            Response.Cookies.Delete("SpotifyOAuth2State");

            if (Request.Query["state"] != state)
            {
                return(BadRequest("Invalid state"));
            }

            var userIdClaim   = User.FindFirst(c => c.Type == ClaimTypes.NameIdentifier)?.Value;
            var userNameClaim = User.FindFirst(c => c.Type == ClaimTypes.Name)?.Value;
            var id            = DecodeState(state);

            if (id != ulong.Parse(userIdClaim))
            {
                return(BadRequest("Invalid user"));
            }

            if (Request.Query.ContainsKey("error"))
            {
                _logger.LogError($"Spotify OAuth2 authorization code error: {Request.Query["error"]}");
                return(BadRequest("Spotify returned an error."));
            }

            if (!Request.Query.TryGetValue("code", out var code))
            {
                _logger.LogError($"Spotify OAuth2 authorization code missing");
                return(BadRequest("Spotify returned an invalid response."));
            }

            string refreshToken;

            using (var request = new HttpRequestMessage(HttpMethod.Post, "https://accounts.spotify.com/api/token"))
            {
                var content = new Dictionary <string, string>()
                {
                    { "grant_type", "authorization_code" },
                    { "code", code },
                    { "redirect_uri", GetSpotifyRedirectUri() },
                    { "client_id", Environment.GetEnvironmentVariable("SpotifyClientId") },
                    { "client_secret", Environment.GetEnvironmentVariable("SpotifyClientSecret") },
                };

                request.Content = new FormUrlEncodedContent(content);
                using (var response = await _httpClientFactory.CreateClient().SendAsync(request))
                {
                    if (!response.IsSuccessStatusCode)
                    {
                        _logger.LogError($"Failed to get Spotify token: {response.StatusCode}");
                        return(Error());
                    }

                    var result = JObject.Parse(await response.Content.ReadAsStringAsync());
                    refreshToken = (string)result["refresh_token"];
                    if (refreshToken == null)
                    {
                        _logger.LogError($"Didn't receive Spotify token");
                        return(Error());
                    }
                }
            }

            var account = new SpotifyAccount()
            {
                UserId       = id.ToString(),
                RefreshToken = refreshToken
            };

            var options = Options.Create(new DatabaseOptions()
            {
                TableStorageConnectionString = Environment.GetEnvironmentVariable("TableStorageConnectionString")
            });
            var service = new SpotifyAccountsService(options);
            await service.AddOrUpdateUserAccountAsync(account, CancellationToken.None);

            ViewData["UserName"] = userNameClaim;
            return(View());
        }
Пример #15
0
 public void removeAccount(SpotifyAccount account)
 {
     accountList.Remove(account);
 }
Пример #16
0
 public SpotifyInstance(SpotifyPluginConfig config, SpotifyAccount account)
 {
     this.config  = config;
     this.account = account;
     resetArgs();
 }