示例#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());
        }
示例#2
0
        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());
        }
示例#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));
        }
示例#4
0
        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;
        }
示例#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);
        }
示例#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;
            }
        }
示例#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;
            }
        }
示例#8
0
        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);
        }
示例#9
0
 public Task <ISpotifyClient> GetClientAsync(MBUser user)
 {
     return(GetClientAsync(user.Id));
 }
示例#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());
        }
示例#11
0
 protected override Task ProcessInternalAsync(MBUser user, CallbackQuery callback, ILogger logger)
 {
     // Nothing to do
     return(Task.CompletedTask);
 }
示例#12
0
 protected abstract Task ProcessListenSessionCommandInternalAsync(MBUser user, Message message, ILogger logger, bool isAuthorizationCallback = false);
示例#13
0
 public async Task UpdateUser(MBUser user)
 {
     await table.ExecuteAsync(TableOperation.Merge(user));
 }
示例#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);
        }
示例#15
0
        public async Task SetLastSeenUser(MBUser user)
        {
            user.LastSeen = DateTimeOffset.UtcNow;

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