Exemple #1
0
        public Uri GetAuthorizationUri(MBUser user, AuthorizationState state, string[] additionalScopes = null)
        {
            var scopes = user.SpotifyScopesList ?? new List <string>();

            if (additionalScopes != null)
            {
                foreach (var scope in additionalScopes)
                {
                    if (!scopes.Contains(scope))
                    {
                        scopes.Add(scope);
                    }
                }
            }

            return(new LoginRequest(
                       RedirectUri,
                       config.SpotifyClientId,
                       LoginRequest.ResponseType.Code
                       )
            {
                Scope = scopes,
                State = SerializeState(state)
            }.ToUri());
        }
        private async Task <IActionResult> HandleTextMessage(Message message, MBUser user, ILogger log)
        {
            log.LogDebug("Handling text message {message}", message.Text);

            if (!(message.Entities?.Any(x => x.Type == MessageEntityType.BotCommand) ?? false))
            {
                log.LogInformation("Non-Command received");
                return(new OkResult());
            }

            var command = commandService.GetCommand(message.Text);

            if (command == null)
            {
                log.LogInformation("Nothing to do for {message} from {user}",
                                   message.Text,
                                   user);
                return(new OkResult());
            }

            log.LogInformation("Processing command {command} for {user} and message {message}",
                               command.GetType().Name,
                               user,
                               message.Text
                               );

            await command.Process(user, message, log);

            return(new OkResult());
        }
Exemple #3
0
        public async Task UpdateSpotifyDetails(MBUser user, string scopes, string spotifyId)
        {
            user.SpotifyScopes = scopes;
            user.SpotifyId     = spotifyId;
            user.LastSeen      = DateTimeOffset.UtcNow;

            await table.ExecuteAsync(TableOperation.Merge(user));
        }
        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;
        }
Exemple #5
0
        public async Task <PrivateUser> RedeemAuthorizationCode(MBUser user, string authorizationCode)
        {
            var response = await new OAuthClient().RequestToken(
                new AuthorizationCodeTokenRequest(
                    config.SpotifyClientId,
                    config.SpotifyClientSecret,
                    authorizationCode,
                    RedirectUri)
                );

            var spotify = new SpotifyClient(response.AccessToken);
            var profile = await spotify.UserProfile.Current();

            await userService.UpdateSpotifyDetails(user, response.Scope, profile.Id);

            await SaveTokenAsync(user.Id, response);

            return(profile);
        }
Exemple #6
0
        protected override async Task ProcessListenSessionCommandInternalAsync(MBUser user, Message message, ILogger logger, bool isAuthorizationCallback = false)
        {
            var listenSession = await ListenSessionService.GetGroupAsync(ChatServices.Telegram, message.Chat.Id.ToString());

            if (listenSession == null)
            {
                await TelegramClient.SendTextMessageAsync(
                    message.Chat.Id,
                    "This group isn't setup for listening. Run /init first.");
            }


            if (CurrentGroupPlaylist.Tracks.Total == 0)
            {
                await TelegramClient.SendTextMessageAsync(
                    message.Chat.Id,
                    "No tracks queued up. Add one!");

                return;
            }
        }
Exemple #7
0
        protected override async Task ProcessListenSessionCommandInternalAsync(MBUser user, Message message, ILogger logger, bool isAuthorizationCallback = false)
        {
            var splits = new List <string>(message.Text.Trim().Split(' '));

            splits.RemoveAll(x => string.IsNullOrWhiteSpace(x.Trim()));

            if (splits.Count == 1)
            {
                await TelegramClient.SendTextMessageAsync(
                    message.Chat.Id,
                    "You didn't provide a song, dummy.");

                return;
            }

            var resource = splits[1];

            // TODO: Allow Playlist, Album
            // TODO: Artist??

            // URL: https://open.spotify.com/track/2wJDK6Epha7t2rewssvELD?si=iYD2K3e-Sd-RGQEAaDHWfg
            if (resource.StartsWith(UrlQualifier, StringComparison.OrdinalIgnoreCase))
            {
                await Queue(resource.Substring(UrlQualifier.Length, resource.IndexOf('?') - UrlQualifier.Length), '/', logger);
            }
            // URI: spotify:track:2wJDK6Epha7t2rewssvELD
            else if (resource.StartsWith(UriQualifier, StringComparison.OrdinalIgnoreCase))
            {
                await Queue(resource.Substring(UriQualifier.Length), ':', logger);
            }
            else
            {
                // TODO: Search???
                await TelegramClient.SendTextMessageAsync(
                    message.Chat.Id,
                    "I'm not sure how to handle that");

                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);
        }
Exemple #9
0
 public Task <ISpotifyClient> GetClientAsync(MBUser user)
 {
     return(GetClientAsync(user.Id));
 }
Exemple #10
0
        private async Task <IActionResult> HandleGroupCreatedMessage(Message message, MBUser user, ILogger log)
        {
            log.LogDebug("Invited to group by {user} group created message {chat}", user, message.Chat.Title);

            // TODO: Onboard channel

            return(new OkResult());
        }
Exemple #11
0
 protected override Task ProcessInternalAsync(MBUser user, CallbackQuery callback, ILogger logger)
 {
     // Nothing to do
     return(Task.CompletedTask);
 }
 protected abstract Task ProcessListenSessionCommandInternalAsync(MBUser user, Message message, ILogger logger, bool isAuthorizationCallback = false);
Exemple #13
0
 public async Task UpdateUser(MBUser user)
 {
     await table.ExecuteAsync(TableOperation.Merge(user));
 }
Exemple #14
0
        public async Task <MBUser> GetUser(string id)
        {
            var result = await table.ExecuteAsync(TableOperation.Retrieve <MBUser>(MBUser.GetPartitionKey(id), id));

            return(result.Result as MBUser);
        }
Exemple #15
0
        public async Task SetLastSeenUser(MBUser user)
        {
            user.LastSeen = DateTimeOffset.UtcNow;

            await table.ExecuteAsync(TableOperation.InsertOrMerge(user));
        }
Exemple #16
0
 public async Task CreateUser(MBUser user)
 {
     await table.ExecuteAsync(TableOperation.Insert(user));
 }
Exemple #17
0
 public static string ToTelegramUserLink(this MBUser user)
 {
     return($"<a href=\"tg://user?id={user.ServiceId}\">{user.DisplayName}</a>");
 }
Exemple #18
0
 protected override async Task ProcessInternalAsync(MBUser user, CallbackQuery callback, ILogger logger)
 {
     // Nothing to respond to yet
 }