Beispiel #1
0
        private async Task <bool> TryHandleRequiresSpotifyConnection(MBUser user, ILogger logger, Message message, bool isAuthorizationCallback = false)
        {
            if (RequiresSpotify && UserIsMissingSpotify(user))
            {
                logger.LogInformation("User {user} was missing spotify authorization for command {command}", user, this);
                await RequestSpotifyAuthForUser(user, message, logger);

                return(true);
            }

            if (RequiresSpotify && UserIsMissingScopes(user))
            {
                logger.LogInformation("User {user} was missing scopes {scopes} for command {command}", user, string.Join(" ", ScopesRequired), this);
                await ProcessMissingScopes(user, message, isAuthorizationCallback, logger);

                return(true);
            }

            if (RequiresSpotify && RequiresSpotifyPremium)
            {
                var client = await SpotifyService.GetClientAsync(user);

                try
                {
                    var profile = await client.UserProfile.Current();

                    if (profile.Product != "premium")
                    {
                        logger.LogInformation("User {user} tried to use command requiring spotify premium, but found {product}", user, profile.Product);
                        await TelegramClient.SendTextMessageAsync(
                            message.Chat.Id,
                            $"Sorry {user.ToTelegramUserLink()} but you need spotify premium to use this command. Consider upgrading your account and try again.",
                            ParseMode.Html);

                        return(true);
                    }
                }
                catch (SpotifyAPI.Web.APIException ex)
                {
                    if (ex.Response.StatusCode == HttpStatusCode.BadRequest)
                    {
                        var error = JsonConvert.DeserializeObject <SpotifyError>(ex.Response.Body as string);
                        if (error.ErrorDescription == "Refresh token revoked")
                        {
                            // TODO: Make this more language natural.. currently acts like a new user
                            logger.LogWarning("User {user} revoked Spotify credentials", user);
                            await RequestSpotifyAuthForUser(user, message, logger);

                            return(true);
                        }
                    }

                    throw;
                }
            }

            return(false);
        }
        protected override async Task ProcessListenSessionCommandInternalAsync(MBUser user, Message message, ILogger logger, bool isAuthorizationCallback = false)
        {
            if (ListenGroup != null)
            {
                logger.LogInformation("Group {group} is already setup for listen session", ListenGroup);
                await TelegramClient.SendTextMessageAsync(
                    message.Chat.Id,
                    "This group is already setup for listening.");

                return;
            }

            var spotifyClient = await SpotifyService.GetClientAsync(user);

            var playlist = await spotifyClient.Playlists.Create(user.SpotifyId, new PlaylistCreateRequest($"{message.Chat.Title} Playlist")
            {
                Description   = $"Playlist managed by Music Bot. For Telegram group chat '{message.Chat.Title}'",
                Collaborative = true,
                Public        = false
            });

            var group = new ListenGroup()
            {
                Id                         = ListenGroup.GetId(ChatServices.Telegram, message.Chat.Id.ToString()),
                ServiceId                  = message.Chat.Id.ToString(),
                OwnerMBDisplayName         = user.DisplayName,
                OwnerMBUserId              = user.Id,
                OwnerSpotifyUserId         = user.SpotifyId,
                ActiveListenerIds          = new string[] { },
                LastListened               = DateTimeOffset.UtcNow,
                SpotifyPlaylistDisplayName = playlist.Name,
                SpotifyPlaylistId          = playlist.Id,
                Created                    = DateTimeOffset.UtcNow
            };

            await ListenSessionService.CreateGroupAsync(group);

            await TelegramClient.SendTextMessageAsync(
                message.Chat.Id,
                "Setup Complete. " + playlist.ExternalUrls.FirstOrDefault().Value);

            return;
        }
        protected override async Task ProcessInternalAsync(MBUser user, Message message, ILogger logger, bool isAuthorizationCallback = false)
        {
            ListenGroup = await ListenSessionService.GetGroupAsync(ChatServices.Telegram, message.Chat.Id.ToString());

            if (ListenGroup != null)
            {
                OwnerSpotifyClient = await SpotifyService.GetClientAsync(ListenGroup.OwnerMBUserId);

                MessageSenderSpotifyClient = await SpotifyService.GetClientAsync(user);

                try
                {
                    CurrentGroupPlaylist = await OwnerSpotifyClient.Playlists.Get(ListenGroup.SpotifyPlaylistId);

                    if (CurrentGroupPlaylist == null)
                    {
                        // TODO: handle User deleted playlist
                        logger.LogError("Playlist wasn't found.. must have been deleted");
                        return;
                    }
                }
                catch (Exception ex)
                {
                    logger.LogError(ex, "Error retrieving playlist");
                }
            }
            else if (RequiresActiveGroup)
            {
                logger.LogInformation("Requires active group to run this command.");
                await TelegramClient.SendTextMessageAsync(
                    message.Chat.Id,
                    "Requires an active group to do this. Run /init");

                return;
            }

            await ProcessListenSessionCommandInternalAsync(user, message, logger, isAuthorizationCallback);
        }