Beispiel #1
0
 public ArtistCommands(Logger.Logger logger,
                       ILastfmApi lastfmApi,
                       IPrefixService prefixService,
                       ArtistsService artistsService,
                       WhoKnowsArtistService whoKnowsArtistService,
                       GuildService guildService,
                       UserService userService,
                       LastFMService lastFmService,
                       PlayService playService,
                       IUpdateService updateService,
                       SpotifyService spotifyService,
                       IIndexService indexService)
 {
     this._logger               = logger;
     this._lastfmApi            = lastfmApi;
     this._lastFmService        = lastFmService;
     this._playService          = playService;
     this._updateService        = updateService;
     this._spotifyService       = spotifyService;
     this._indexService         = indexService;
     this._prefixService        = prefixService;
     this._artistsService       = artistsService;
     this._whoKnowArtistService = whoKnowsArtistService;
     this._guildService         = guildService;
     this._userService          = userService;
     this._embed = new EmbedBuilder()
                   .WithColor(DiscordConstants.LastFMColorRed);
     this._embedAuthor = new EmbedAuthorBuilder();
     this._embedFooter = new EmbedFooterBuilder();
 }
Beispiel #2
0
        public void AllShouldReturnCorrectNumber()
        {
            var artistsRepository = new Mock <IRepository <Artist> >();

            artistsRepository.Setup(r => r.All()).Returns(new List <Artist>()
            {
                new Artist(),
                new Artist(),
                new Artist()
            }.AsQueryable());

            var service = new ArtistsService(artistsRepository.Object, null, null, null);

            Assert.Equal(3, service.All().Count());
        }
 public SpotifyPlayerBotAccessors(ConversationState conversationState,
                                  OAuthService oAuthService,
                                  PlayerService playerService,
                                  CurrentTrackService currentTrackService,
                                  UIService uiService,
                                  SearchService searchService,
                                  ArtistsService artistsService,
                                  TracksService tracksService)
 {
     ConversationState   = conversationState ?? throw new ArgumentNullException(nameof(conversationState));
     OAuthService        = oAuthService ?? throw new ArgumentNullException(nameof(oAuthService));
     PlayerService       = playerService ?? throw new ArgumentNullException(nameof(playerService));
     CurrentTrackService = currentTrackService ?? throw new ArgumentNullException(nameof(currentTrackService));
     UIService           = uiService ?? throw new ArgumentNullException(nameof(uiService));
     SearchService       = searchService ?? throw new ArgumentNullException(nameof(searchService));
     ArtistsService      = artistsService ?? throw new ArgumentNullException(nameof(artistsService));
     TracksService       = tracksService ?? throw new ArgumentNullException(nameof(tracksService));
 }
Beispiel #4
0
        public async Task AddBookShouldActuallyAddBookToDatabase()
        {
            var options = new DbContextOptionsBuilder <TattooShopContext>()
                          .UseInMemoryDatabase(databaseName: "Unique_Db_Name_5785216")
                          .Options;
            var dbContext = new TattooShopContext(options);

            dbContext.Artists.Add(new Artist()
            {
                Id = "1"
            });
            dbContext.Users.Add(new TattooShopUser()
            {
                Id = "2"
            });
            dbContext.SaveChanges();

            var artistsRepository = new DbRepository <Artist>(dbContext);
            var booksRepository   = new DbRepository <Book>(dbContext);
            var imageService      = new ImageService(dbContext);
            var tattoosRepository = new DbRepository <Tattoo>(dbContext);

            var artistsService = new ArtistsService(artistsRepository, imageService, booksRepository, tattoosRepository);
            var fileMock       = new Mock <IFormFile>();
            var content        = "Hallo world from a fake file!";
            var fileName       = "test.pdf";
            var ms             = new MemoryStream();
            var writer         = new StreamWriter(ms);

            writer.Write(content);
            writer.Flush();
            ms.Position = 0;
            fileMock.Setup(x => x.OpenReadStream()).Returns(ms);
            fileMock.Setup(x => x.FileName).Returns(fileName);
            fileMock.Setup(x => x.Length).Returns(ms.Length);

            await artistsService.AddBook(DateTime.UtcNow.AddDays(3).ToString(), "short description", fileMock.Object, "Geometric",
                                         "2", "1");

            Assert.Equal(1, booksRepository.All().Count());
        }
Beispiel #5
0
 public ArtistCommands(Logger.Logger logger,
                       ILastfmApi lastfmApi,
                       IPrefixService prefixService,
                       ArtistsService artistsService,
                       WhoKnowsService whoKnowsService,
                       GuildService guildService,
                       UserService userService)
 {
     this._logger          = logger;
     this._lastfmApi       = lastfmApi;
     this._lastFmService   = new LastFMService(lastfmApi);
     this._prefixService   = prefixService;
     this._artistsService  = artistsService;
     this._whoKnowsService = whoKnowsService;
     this._guildService    = guildService;
     this._userService     = userService;
     this._embed           = new EmbedBuilder()
                             .WithColor(Constants.LastFMColorRed);
     this._embedAuthor = new EmbedAuthorBuilder();
     this._embedFooter = new EmbedFooterBuilder();
 }
Beispiel #6
0
 public ArtistsController(ArtistsService service)
 {
     _service = service;
 }
Beispiel #7
0
 public ArtistsController(ArtistsService service, PaintingsService ps)
 {
     _service = service;
     _ps      = ps;
 }
Beispiel #8
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.Configure <RazorViewEngineOptions>(o =>
            {
                o.ViewLocationFormats.Clear();
                o.ViewLocationFormats.Add("/Callback/Views/{1}/{0}" + RazorViewEngine.ViewExtension);
            });

            var authorizationMapper = new AuthorizationMapper();

            services.AddSingleton(typeof(IAuthorizationMapper), authorizationMapper);
            services.AddBot <SpotifyPlayerBot>(options =>
            {
                var secretKey = Configuration.GetSection("botFileSecret")?.Value;

                var botConfig = BotConfiguration.Load(@".\Bots\SpotifyPlayerBot.bot", secretKey);
                services.AddSingleton(sp => botConfig);

                var service = botConfig.Services.Where(s => s.Type == "endpoint" && s.Name == "development").FirstOrDefault();
                if (!(service is EndpointService endpointService))
                {
                    throw new InvalidOperationException($"The .bot file does not contain a development endpoint.");
                }

                options.CredentialProvider = new SimpleCredentialProvider(endpointService.AppId, endpointService.AppPassword);

                options.OnTurnError = async(context, exception) =>
                {
                    await context.SendActivityAsync("Sorry, it looks like something went wrong.");
                };
            });

            var dataStore         = new MemoryStorage();
            var conversationState = new ConversationState(dataStore);

            var oAuthService        = new OAuthService(authorizationMapper, Configuration.GetSection("spotifyAppId")?.Value, Configuration.GetSection("spotifyAppSecret")?.Value);
            var playerService       = new PlayerService();
            var currentTrackService = new CurrentTrackService();
            var uiService           = new UIService(oAuthService.GetAuthorizeUrl());
            var searchService       = new SearchService();
            var artistsService      = new ArtistsService();
            var tracksService       = new TracksService();

            services.AddSingleton(serviceProvider => {
                var options   = serviceProvider.GetRequiredService <IOptions <BotFrameworkOptions> >().Value;
                var accessors = new SpotifyPlayerBotAccessors(conversationState,
                                                              oAuthService,
                                                              playerService,
                                                              currentTrackService,
                                                              uiService,
                                                              searchService,
                                                              artistsService,
                                                              tracksService)
                {
                    ConversationDialogState  = conversationState.CreateProperty <DialogState>("DialogState"),
                    OAuthServiceState        = conversationState.CreateProperty <OAuthService>("OAuthServiceState"),
                    PlayerServiceState       = conversationState.CreateProperty <PlayerService>("PlayerServiceState"),
                    CurrentTrackServiceState = conversationState.CreateProperty <CurrentTrackService>("CurrentServiceState"),
                    UIServiceState           = conversationState.CreateProperty <UIService>("UIServiceState"),
                    SearchServiceState       = conversationState.CreateProperty <SearchService>("SearchServiceState"),
                    ArtistsServiceState      = conversationState.CreateProperty <ArtistsService>("ArtistsServiceState"),
                    TracksServiceState       = conversationState.CreateProperty <TracksService>("TracksServiceState")
                };

                return(accessors);
            });
        }
Beispiel #9
0
        public async Task WhoKnowsAsync(params string[] artistValues)
        {
            if (this._guildService.CheckIfDM(this.Context))
            {
                await ReplyAsync("This command is not supported in DMs.");

                return;
            }

            var userSettings = await this._userService.GetUserSettingsAsync(this.Context.User);

            if (userSettings?.UserNameLastFM == null)
            {
                await UsernameNotSetErrorResponseAsync();

                return;
            }

            var lastIndex = await this._guildService.GetGuildIndexTimestampAsync(Context.Guild);

            if (lastIndex == null)
            {
                await ReplyAsync("This server hasn't been indexed yet.\n" +
                                 "Please run `.fmindex` to index this server.");

                return;
            }
            if (lastIndex < DateTime.UtcNow.AddDays(-60))
            {
                await ReplyAsync("Server index data is out of date, it was last updated over 60 days ago.\n" +
                                 "Please run `.fmindex` to re-index this server.");

                return;
            }

            _ = this.Context.Channel.TriggerTypingAsync();

            var artistQuery = await GetArtistOrHelp(artistValues, userSettings, "fmartist");

            if (artistQuery == null)
            {
                return;
            }

            var queryParams = new Dictionary <string, string>
            {
                { "artist", artistQuery },
                { "username", userSettings.UserNameLastFM },
                { "autocorrect", "1" }
            };

            var artistCall = await this._lastfmApi.CallApiAsync <ArtistResponse>(queryParams, Call.ArtistInfo);

            if (!artistCall.Success)
            {
                this._embed.ErrorResponse(artistCall.Error.Value, artistCall.Message, this.Context, this._logger);
                await ReplyAsync("", false, this._embed.Build());

                return;
            }
            Statistics.LastfmApiCalls.Inc();

            var artist = artistCall.Content;

            try
            {
                var guildUsers = await this.Context.Guild.GetUsersAsync();

                var usersWithArtist = await this._artistsService.GetIndexedUsersForArtist(guildUsers, artist.Artist.Name);

                if (usersWithArtist.Count == 0 && artist.Artist.Stats.Userplaycount != 0)
                {
                    var guildUser = await Context.Guild.GetUserAsync(Context.User.Id);

                    usersWithArtist =
                        ArtistsService.AddUserToIndexList(usersWithArtist, userSettings, guildUser, artist);
                }
                if (!usersWithArtist.Select(s => s.UserId).Contains(userSettings.UserId) && usersWithArtist.Count != 14 && artist.Artist.Stats.Userplaycount != 0)
                {
                    var guildUser = await Context.Guild.GetUserAsync(Context.User.Id);

                    usersWithArtist =
                        ArtistsService.AddUserToIndexList(usersWithArtist, userSettings, guildUser, artist);
                }

                var serverUsers = ArtistsService.ArtistWithUserToStringList(usersWithArtist, artist, userSettings.UserId);
                if (usersWithArtist.Count == 0)
                {
                    serverUsers = "Nobody in this server (not even you) has listened to this artist.";
                }

                this._embed.WithDescription(serverUsers);
                var footer = "";

                var timeTillIndex = DateTime.UtcNow - lastIndex.Value;
                footer += $"Last updated {(int)timeTillIndex.TotalHours}h{timeTillIndex:mm}m ago";
                if (lastIndex < DateTime.UtcNow.Add(-Constants.GuildIndexCooldown))
                {
                    footer += " - Update data with `.fmindex`";
                }

                if (guildUsers.Count < 100)
                {
                    var serverListeners = await this._artistsService.GetArtistListenerCountForServer(guildUsers, artist.Artist.Name);

                    var serverPlaycount = await this._artistsService.GetArtistPlayCountForServer(guildUsers, artist.Artist.Name);

                    var avgServerListenerPlaycount = await this._artistsService.GetArtistAverageListenerPlaycountForServer(guildUsers, artist.Artist.Name);

                    footer += $"\n{serverListeners} listeners - ";
                    footer += $"{serverPlaycount} total plays - ";
                    footer += $"{(int)avgServerListenerPlaycount} median plays";
                }
                else if (guildUsers.Count < 125)
                {
                    footer += "\nView server artist averages in `.fmartist`";
                }

                this._embed.WithTitle($"Who knows {artist.Artist.Name} in {Context.Guild.Name}");
                this._embed.WithUrl(artist.Artist.Url);

                this._embedFooter.WithText(footer);
                this._embed.WithFooter(this._embedFooter);

                await this.Context.Channel.SendMessageAsync("", false, this._embed.Build());

                this._logger.LogCommandUsed(this.Context.Guild?.Id, this.Context.Channel.Id, this.Context.User.Id,
                                            this.Context.Message.Content);
            }
            catch (Exception e)
            {
                this._logger.LogError(e.Message, this.Context.Message.Content, this.Context.User.Username,
                                      this.Context.Guild?.Name, this.Context.Guild?.Id);
                await ReplyAsync(
                    "Something went wrong while using whoknows. Please let us know as this feature is in beta.");
            }
        }