コード例 #1
0
        private async void CreateSession()
        {
            try
            {
                Application.DoEvents();
                Log("Connecting...");


                _client = new LastfmClient(_config.ApiKey, _config.ApiSecret);
                var result = await _client.Auth.GetSessionTokenAsync(_config.Username, _config.Password);

                if (result.Success)
                {
                    Log("OK");
                }
                else
                {
                    Log(result.Status.ToString());
                }
            }
            catch (Exception ex)
            {
                Log("Error: {0}", ex.Message);
            }
        }
コード例 #2
0
        public StatusViewComponent(HomeContext dbContext, IConfiguration configuration, IMemoryCache memoryCache, ILoggerFactory loggerFactory)
        {
            _dbContext   = dbContext;
            _memoryCache = memoryCache;
            _logger      = loggerFactory.CreateLogger <StatusViewComponent>();

            LastfmUserName = configuration["LastfmUser"];
            SteamId        = configuration.GetValue <ulong>("SteamID");
            TwitchUserId   = configuration.GetValue <ulong>("TwitchUserId");
            TwitchClientId = configuration["TwitchClientId"];

            var lastfmApiKey = configuration["LastfmApiKey"];
            var lastfmSecret = configuration["LastfmSharedSecret"];

            if (lastfmApiKey != null && lastfmSecret != null)
            {
                Client = new LastfmClient(lastfmApiKey, lastfmSecret, s_httpClient);
            }

            var steamWebApiKey = configuration["SteamWebApiKey"];

            if (steamWebApiKey != null)
            {
                SteamFactory = new SteamWebInterfaceFactory(steamWebApiKey);
            }
        }
コード例 #3
0
        private async Task Authenticate(LastfmClient client)
        {
            const string fileName = "last.fm";

            if (!File.Exists(fileName))
            {
                var result = await client.Auth.GetSessionTokenAsync(USERNAME, PASSWORD);

                if (client.Auth.Authenticated)
                {
                    var json = JsonConvert.SerializeObject(client.Auth.UserSession);
                    File.WriteAllText("last.fm", json, Encoding.UTF8);
                }
                else
                {
                    throw new Exception("Last.FM Authenticate problem");
                }
            }
            else
            {
                var json    = File.ReadAllText(fileName, Encoding.UTF8);
                var session = JsonConvert.DeserializeObject <LastUserSession>(json);

                client.Auth.LoadSession(session);

                if (!client.Auth.Authenticated)
                {
                    File.Delete(fileName);
                    throw new Exception("Last.FM Authenticate problem");
                }
            }
        }
コード例 #4
0
ファイル: LastFMService.cs プロジェクト: Paralectic/fmbot
 public LastFMService(IConfigurationRoot configuration, ILastfmApi lastfmApi)
 {
     this._key          = configuration.GetSection("LastFm:Key").Value;
     this._secret       = configuration.GetSection("LastFm:Secret").Value;
     this._lastFMClient = new LastfmClient(this._key, this._secret);
     this._lastfmApi    = lastfmApi;
 }
コード例 #5
0
ファイル: MySearchCloudStore.cs プロジェクト: mew22/chronique
        public MySearchCloudStore()
        {
            items = new ObservableCollection <GenericRequestObject>();

            //TODO: Mocking data
            //            var mockItems = new List<GenericRequestObject>
            //            {
            //                new GenericRequestObject (Guid.NewGuid().ToString(), "Rihanna", "Chanteuse, parolière, actrice, designer, mannequin", "Pop, RnB, hip-hop, reggae, dance", DataType.Artiste, "https://upload.wikimedia.org/wikipedia/commons/thumb/4/47/Rihanna_concert_in_Washington_DC_%282%29.jpg/1280px-Rihanna_concert_in_Washington_DC_%282%29.jpg"),
            //                new GenericRequestObject (Guid.NewGuid().ToString(), "Shakira", "Chanteuse, auteure-compositrice-interprète, productrice, danseuse, actrice" , "Latino, pop, rock, dance", DataType.Artiste, "https://upload.wikimedia.org/wikipedia/commons/thumb/7/79/Shakira_2014.jpg/498px-Shakira_2014.jpg"),
            //                new GenericRequestObject (Guid.NewGuid().ToString(), "Faded", "Alan Walker", "Electro house", DataType.Track, "https://upload.wikimedia.org/wikipedia/commons/3/3e/Alan_Walker-_Logo.png"),
            //                new GenericRequestObject (Guid.NewGuid().ToString(), "El Dorado", "Shakira", "26 mai 2017", DataType.Album, "https://upload.wikimedia.org/wikipedia/commons/3/3d/El_Dorado_Shakira.png")
            //            };
            //
            //            foreach (var item in mockItems)
            //            {
            //                items.Add(item);
            //            }

            //TODO: logging error
//            var httpClient = new HttpClient(new HttpLoggingHandler()) { BaseAddress = new Uri("http://ws.audioscrobbler.com")};
//            searchApi = RestService.For<ISearchAPI>(httpClient);

//            searchApi = RestService.For<ISearchAPI>("http://ws.audioscrobbler.com");
            lastFm = LastfmSingleton.Instance.LastFm;
        }
コード例 #6
0
        private async void Request(string albumID)
        {
            if (!string.IsNullOrEmpty(albumID))
            {
                var client = new LastfmClient(Config.apikey, Config.apisecret);

                var responseAlbums = await client.Album.GetInfoByMbidAsync(albumID);

                LastAlbum album = responseAlbums.Content;

                Album_Name.Text   = album.Name;
                Album_Artist.Text = album.ArtistName;

                if (!string.IsNullOrEmpty(album.Images.Large.ToString()))
                {
                    var imageBitmap = GetImageBitmapFromUrl(album.Images.Large.ToString());
                    Album_Image.SetImageBitmap(imageBitmap);
                    Album_Image.Click += (sender, ea) =>
                    {
                        Method.Vibrate(this);
                        //Method.Show(this, album.Images.Large.ToString());
                        if (!string.IsNullOrEmpty(album.Images.ExtraLarge.ToString()))
                        {
                            var myIntent = new Intent(this, typeof(ImageViewActivity));
                            myIntent.PutExtra("image", album.Images.ExtraLarge.ToString());
                            StartActivity(myIntent);
                        }
                    };
                }

                List <LastTrack> lst = (from t in album.Tracks select t).ToList();
                Album_lvTracks.Adapter = new TracksAdapter(this, lst);
            }
        }
コード例 #7
0
        private async Task <int> Request(string track)
        {
            int records = 0;

            Method.ProgressShow(this, GetString(Resource.String.Progress_message));
            var client = new LastfmClient(Config.apikey, Config.apisecret);

            if (!string.IsNullOrEmpty(track))
            {
                var responseTracks = await client.Track.SearchAsync(track);

                tracks = responseTracks.Content;
                if (tracks.Count > 0)
                {
                    records = tracks.Count;
                    await db.AddAsync(new History()
                    {
                        Query = track, Type = SearchType.Track
                    });

                    List <LastTrack> lst = (from t in tracks select t).ToList();
                    Track_lvArtist.Adapter = new TrackListAdapter(this, lst);
                }
            }
            Method.ProgressHide(this);
            return(records);
        }
コード例 #8
0
        public LastFm(BotContext botcontext)
        {
            var config = new ConfigurationBuilder().AddJsonFile("_config.json").Build();

            this._client  = new LastfmClient(config["tokens:lastfm_key"], config["tokens:lastfm_secret"]);
            this._context = botcontext;
        }
コード例 #9
0
        /// <inheritdoc/>
        public async Task <JsonResult> GetLastFMRecentlyPlayed(string username, DateTimeOffset?after = null)
        {
            var client       = new LastfmClient("d3cf196e63d20375eb8d6729ebb982b3", "3b2dd16f5d94f119aa724dd3efe3b393");
            var recentTracks = await client.User.GetRecentScrobbles(username, after);

            return(new JsonResult(recentTracks));
        }
コード例 #10
0
        public async Task <(bool Success, ServiceRequestResult Result)> AuthenticateUser(string username, string password)
        {
            if (username == null)
            {
                throw new ArgumentNullException(nameof(username));
            }
            if (password == null)
            {
                throw new ArgumentNullException(nameof(password));
            }
            if (_lastFmClient != null && _lastFmClient.Auth.Authenticated)
            {
                throw new InvalidOperationException("Another user is already authenticated.");
            }

            // create client
            _lastFmClient = _trackScrobblingClientFactory.CreateTrackScrobblingClient();

            // authenticate
            var response = await _lastFmClient.Auth.GetSessionTokenAsync(username, password);

            // parse result
            ServiceRequestResult result = ParseRequestResult(response.Status);

            return(response.Success, result);
        }
コード例 #11
0
        public TopTracksViewModel(LastfmClient lfClient, INavigationService navigationService)
        {
            _lfClient          = lfClient;
            _navigationService = navigationService;

            GoToTrackInfoCommand = new DelegateCommand <LastTrack>(OnGoToTrackInfoCommand);
            Tracks = new PaginatedCollection <LastTrack>(LoadMoreTopTracks);
        }
コード例 #12
0
        public TopArtistsViewModel(
            LastfmClient lfClient,
            INavigationService navigationService)
        {
            _lfClient          = lfClient;
            _navigationService = navigationService;

            GoToArtistInfoCommand = new DelegateCommand <LastArtist>(OnGoToArtistInfoCommand);
        }
コード例 #13
0
 /// <summary>
 /// Constructor. Creates the client.
 /// </summary>
 public MainForm()
 {
     InitializeComponent();
     Icon    = Scrubbler.Properties.Resources.scrubbler_64;
     _client = new LastfmClient(APIKEY, APISECRET);
     dateTimePicker1.MinDate = dateTimePicker1.Value.AddDays(-14.0);
     dateTimePicker1.MaxDate = dateTimePicker1.Value;
     LoadLastSession();
 }
コード例 #14
0
        public void Initialise()
        {
            Lastfm = new LastfmClient(LastFm.TEST_APIKEY, LastFm.TEST_APISECRET);

            var authTask = Lastfm.Auth.GetSessionTokenAsync(INTEGRATION_TEST_USER, INTEGRATION_TEST_PASSWORD);

            authTask.Wait();
            Assert.IsTrue(authTask.Result.Success);
        }
コード例 #15
0
        public async Task NowPlaying()
        {
            using var typing = Context.Channel.EnterTypingState();
            var userId = Context.User.Id;

            string?lastFmUserName = null;

            using (var connection = new SqliteConnection("Data Source=data.db"))
            {
                await connection.OpenAsync();

                using (var command = connection.CreateCommand())
                {
                    command.CommandText = "SELECT * FROM users WHERE id=$id";
                    command.Parameters.AddWithValue("$id", userId);

                    using (var reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            var isNull = await reader.IsDBNullAsync(1);

                            lastFmUserName = isNull == true ? null : reader.GetString(1);
                        }
                    }
                }
            }

            if (lastFmUserName != null)
            {
                using var client = new LastfmClient(config["LastFmKey"], config["LastFmSecret"]);

                var track = await client.User.GetRecentScrobbles(lastFmUserName, count : 1);

                var lastTrack = track.FirstOrDefault();

                if (lastTrack != null)
                {
                    var songName = lastTrack.ArtistName + " " + lastTrack.Name;

                    var spotifyResultTask = SearchSpotify(songName);
                    var youTubeResultTask = SearchYouTube(songName);
                    await Task.WhenAll(spotifyResultTask, youTubeResultTask);

                    await ReplyAsync(spotifyResultTask.Result ?? "No Spotify match found.");
                    await ReplyAsync(youTubeResultTask.Result ?? "No YouTube match found");
                }
                else
                {
                    await ReplyAsync("No now playing data found for Last.fm user");
                }
            }
            else
            {
                await ReplyAsync("No Last.fm user name found. Use !npset <username> to set your Last.fm user name");
            }
        }
コード例 #16
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext <ApplicationSignInManager>(ApplicationSignInManager.Create);

            // Enable the application to use a cookie to store information for the signed in user
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider
            // Configure the sign in cookie
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/Account/Login"),
                Provider           = new CookieAuthenticationProvider
                {
                    // Enables the application to validate the security stamp when the user logs in.
                    // This is a security feature which is used when you change a password or add an external login to your account.
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <ApplicationUserManager, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                }
            });
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            // Enables the application to remember the second login verification factor such as phone or email.
            // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
            // This is similar to the RememberMe option when you log in.
            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

            string apikey    = WebConfigurationManager.AppSettings["apikey"];
            string apisecret = WebConfigurationManager.AppSettings["apisecret"];
            var    client    = new LastfmClient(apikey, apisecret);

            LastFm.Client = client;
            // Uncomment the following lines to enable logging in with third party login providers
            //app.UseMicrosoftAccountAuthentication(
            //    clientId: "",
            //    clientSecret: "");

            //app.UseTwitterAuthentication(
            //   consumerKey: "",
            //   consumerSecret: "");

            //app.UseFacebookAuthentication(
            //   appId: "",
            //   appSecret: "");

            //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            //{
            //    ClientId = "",
            //    ClientSecret = ""
            //});
        }
コード例 #17
0
 public OnlineWorker()
 {
     LastFmStart();
     artists      = new List <LastArtist>();
     albums       = new List <LastAlbum>();
     tracks       = new List <LastTrack>();
     lastfmClient = new LastfmClient(api_key, shared_secret, new HttpClient());
     //var response = lastfmClient.Auth.GetSessionTokenAsync("artiom0724", "xtkjdtr1998.Q");
 }
コード例 #18
0
ファイル: UsersController.cs プロジェクト: sg48003/DM_Project
 public UsersController(MovieService movieService, UserService userService, TrackService trackService, IOptions <AppSettings> appSettings)
 {
     _movieService = movieService;
     _userService  = userService;
     _trackService = trackService;
     _appSettings  = appSettings.Value;
     _imdb         = new Imdb(appSettings.Value.ImdbApiKey);
     _musicClient  = new LastfmClient(appSettings.Value.LastfmApiKey, appSettings.Value.LastfmApiSecret);
 }
コード例 #19
0
 public GlobalIndexService(
     IConfigurationRoot configuration,
     LastFMService lastFmService)
 {
     this.lastFmService     = lastFmService;
     this._key              = configuration.GetSection("LastFm:Key").Value;
     this._secret           = configuration.GetSection("LastFm:Secret").Value;
     this._connectionString = configuration.GetSection("Database:ConnectionString").Value;
     this._lastFMClient     = new LastfmClient(this._key, this._secret);
 }
コード例 #20
0
ファイル: LastFMContext.cs プロジェクト: Reyth3/LFMSync
        public LastFMContext(Context context)
        {
            Context = context;
            //SourceUser = "******";
            LastAuth auth = new LastAuth(Token.CLIENT, Token.SECRET);

            client         = new LastfmClient(auth);
            ReythScrobbles = new List <LastTrack>();
            GinaScrobbles  = new List <LastTrack>();
        }
コード例 #21
0
        public RetrievePlaylist()
        {
            InitializeComponent();

            IApiKeys apiKeys = new ApiKeys();

            _client = new LastfmClient(apiKeys.GetLastfmApiKey(), apiKeys.GetLastfmApiSecret());

            _tracks = new BindingList <Track>(_backingTracks); // Backing needed for sorting
            dataGrid_recent.DataSource = _tracks;
        }
コード例 #22
0
        public ArtistsSearchViewModel(LastfmClient lastfmClient, ILocService locService,
                                      INavigationService navigationService, ISettingsService settingsService)
        {
            _lastfmClient      = lastfmClient;
            _locService        = locService;
            _navigationService = navigationService;
            _settingsService   = settingsService;

            QueryBoxKeyDownCommand = new DelegateCommand <KeyRoutedEventArgs>(OnQueryBoxKeyDownCommand);
            GoToArtistInfoCommand  = new DelegateCommand <LastArtist>(OnGoToArtistInfoCommand);
            ReloadCommand          = new DelegateCommand(Search);
        }
コード例 #23
0
        public ImagesCacheService(
            IGrooveMusicService grooveMusicService,
            LastfmClient lfClient,
            INetworkInfoService networkInfoService)
        {
            _grooveMusicService = grooveMusicService;
            _lfClient           = lfClient;
            _networkInfoService = networkInfoService;

            _artistsQueue = new TaskQueue();
            _albumsQueue  = new TaskQueue();
        }
コード例 #24
0
        public LastFMHandler(Sniffer sniffer)
        {
            Client = new LastfmClient(Program.config.lastFMSettings.LAST_FM_API_KEY, Program.config.lastFMSettings.LAST_FM_API_SECRET);

            if (string.IsNullOrWhiteSpace(Program.config.lastFMSettings.LAST_FM_USERNAME) || string.IsNullOrWhiteSpace(Program.config.lastFMSettings.LAST_FM_PASSWORD))
            {
                Logger.Log("[Last.FM] Last.FM Enabled but no user credentials exist.");

                var username = Program.config.lastFMSettings.LAST_FM_USERNAME;
                while (string.IsNullOrWhiteSpace(username))
                {
                    username = Interaction.InputBox("Last.FM Username");
                }

                var password = "";
                while (string.IsNullOrWhiteSpace(password))
                {
                    password = Interaction.InputBox("Last.FM Password");
                }

                var passwordHashed = Crypto.EncryptStringAES(password, username + SECRET);

                Program.config.lastFMSettings.LAST_FM_USERNAME = username;
                Program.config.lastFMSettings.LAST_FM_PASSWORD = passwordHashed;

                Program.config.SaveLastFMSettings();
            }

            var passwordUnhashed = Crypto.DecryptStringAES(Program.config.lastFMSettings.LAST_FM_PASSWORD, Program.config.lastFMSettings.LAST_FM_USERNAME + SECRET);
            var response         = Client.Auth.GetSessionTokenAsync(Program.config.lastFMSettings.LAST_FM_USERNAME, passwordUnhashed).Result;

            if (response.Success)
            {
                Logger.Log("[Last.FM] Received Ready from user {0}", Client.Auth.UserSession.Username);
            }
            else
            {
                Logger.Log("[Last.FM] Invalid Last.FM Credentials. Please run the program again and ensure you inputted the data correctly.");

                Program.config.lastFMSettings.LAST_FM_USERNAME = "";
                Program.config.lastFMSettings.LAST_FM_PASSWORD = "";

                Program.config.SaveLastFMSettings();

                return;
            }

            sniffer.OnStateChanged  += Sniffer_OnStateChanged;
            sniffer.OnSongChanged   += Sniffer_OnSongChanged;
            sniffer.OnMemoryReadout += Sniffer_OnMemoryReadout;
        }
コード例 #25
0
        private async void Window_Loaded(object sender, RoutedEventArgs e)
        {
            SourceUser = "******";
            LastAuth auth = new LastAuth(Token.CLIENT, Token.SECRET);

            client = new LastfmClient(auth);

            ReythScrobbles            = new ObservableCollection <LastTrack>();
            GinaScrobbles             = new ObservableCollection <LastTrack>();
            leftListView.ItemsSource  = ReythScrobbles;
            rightListView.ItemsSource = GinaScrobbles;
            await Authenticate();

            ReloadScrobbles();
        }
コード例 #26
0
ファイル: SongsController.cs プロジェクト: Blowdire/Tesina
        public async Task Edit(int id, string titolo, string artista)
        {
            try
            {
                titolo  = titolo.Trim();
                artista = artista.Trim();
                Song c = (from x in _context.Song
                          where x.ID == id
                          select x).First();
                c.Title  = titolo;
                c.Artist = artista;
                if (titolo != null && artista != null)
                {
                    try
                    {
                        var client   = new LastfmClient("71465dd8f4ec55f6df53ff7b015c9ba1", "9f6aa87f2e9636875073a6e0b0904954");
                        var response = await client.Track.GetInfoAsync(titolo, artista);

                        LastTrack track = response.Content;
                        var       alb   = await client.Album.GetInfoAsync(track.ArtistName, track.AlbumName);

                        LastAlbum album = alb.Content;
                        c.Title  = track.Name;
                        c.Artist = track.ArtistName;
                        c.Album  = album.Name;
                        //c.ReleaseDate =DateTime.Parse(album.ReleaseDateUtc.ToString());
                        c.AlbumArtSmall  = album.Images.Small.ToString();
                        c.AlbumArtMedium = album.Images.Medium.ToString();
                        c.AlbumArtBig    = album.Images.Large.ToString();
                    }
                    catch (Exception ex)
                    {
                        c.Title  = titolo;
                        c.Artist = artista;
                    }

                    _context.SaveChanges();
                }
                _context.SaveChanges();
            }
            catch (Exception ex)
            {
                _context.Errors.Add(new ErrorModel {
                    errore = ex.Message
                });
                _context.SaveChanges();
            }
        }
コード例 #27
0
ファイル: Main.cs プロジェクト: microsockss/lastfm-wallpaper
        private async Task <string> GetRecentTracks()
        {
            recentTracks.Clear();

            var client = new LastfmClient(Globals.InitVars.apiKey, null);

            var response = await client.User.GetRecentScrobbles(username);

            foreach (IF.Lastfm.Core.Objects.LastTrack i in response)
            {
                recentTracks.Add(i);
            }

            Console.WriteLine("Artist: " + recentTracks[0].ArtistName);
            client.Dispose();
            return(recentTracks[0].ArtistName);
        }
コード例 #28
0
        private async Task <string> GetRecentTracks()
        {
            recentTracks.Clear();

            var client = new LastfmClient("f129e1e61eec3e59e1730738845abd1f", null);

            var response = await client.User.GetRecentScrobbles(username);

            foreach (IF.Lastfm.Core.Objects.LastTrack i in response)
            {
                recentTracks.Add(i);
            }

            Console.WriteLine("Artist: " + recentTracks[0].ArtistName);
            client.Dispose();
            return(recentTracks[0].ArtistName);
        }
コード例 #29
0
        public ArtistAlbumViewModel(
            LastfmClient lfClient,
            INavigationService navigationService,
            ISettingsService settingsService,
            IImagesCacheService imagesCacheService,
            ILocService locService)
        {
            _lfClient           = lfClient;
            _navigationService  = navigationService;
            _settingsService    = settingsService;
            _imagesCacheService = imagesCacheService;
            _locService         = locService;

            GoToTrackInfoCommand  = new DelegateCommand <LastTrack>(OnGoToTrackInfoCommand);
            FindArtistInVKCommand = new DelegateCommand(OnFindArtistInVKCommand);
            ReloadAlbumCommand    = new DelegateCommand(OnReloadAlbumCommand);
        }
コード例 #30
0
        public ArtistInfoViewModel(
            LastfmClient lfClient,
            INavigationService navigationService,
            ISettingsService settingsService,
            IPurchaseService purchaseService,
            IImagesCacheService imagesCacheService)
        {
            _lfClient           = lfClient;
            _navigationService  = navigationService;
            _settingsService    = settingsService;
            _purchaseService    = purchaseService;
            _imagesCacheService = imagesCacheService;

            GoToTrackInfoCommand         = new DelegateCommand <LastTrack>(OnGoToTrackInfoCommand);
            GoToSimilarArtistInfoCommand = new DelegateCommand <LastArtist>(OnGoToSimilarArtistInfoCommand);
            GoToAlbumInfoCommand         = new DelegateCommand <LastAlbum>(OnGoToAlbumInfoCommand);
            FindArtistInVKCommand        = new DelegateCommand(OnFindArtistInVKCommand);
        }