📜 ⬆️ ⬇️

We use Last.fm API with C #

Welcome, Habraludi!

In this post I talked about my program for scrobbling tracks at Last.fm. Now I want to tell you how in C # to interact with the Last.fm API using the example of scrobbling the track.

The first thing we need to do is register your API account. Go to your profile and follow this link . After filling in the required fields, we get the so-called API Key and secret key . They will be needed to identify your client with the service and obtain the session key. I didn’t have problems with getting them.

Since scrobbling a track requires getting a session key, we will be interested in the following methods:
- Getting a token
- Getting session key
- scrobble track

The simplified scheme is as follows - we get the token using our API Key, then we get the session key using the token and the secret key, then we scrobble the track using the session key, the token and a few more parameters.
')
We will also need to use two classes - HttpWebRequest and HttpWebResponse for making HTTP requests.

So let's get down to the code.
First, the method to get the session:
//   HttpWebRequest    Create  WebRequest,     HttpWebRequest.    ,    API,    - method=auth.gettoken   API Key HttpWebRequest tokenRequest = (HttpWebRequest)WebRequest.Create("http://ws.audioscrobbler.com/2.0/?method=auth.gettoken&api_key=" + ApiKey); //    HttpWebResponse tokenResponse = (HttpWebResponse)tokenRequest.GetResponse(); //       string tokenResult = new StreamReader(tokenResponse.GetResponseStream(), Encoding.UTF8).ReadToEnd(); //  ,   .      XML (,         ,    ). string token = String.Empty; for (int i = tokenResult.IndexOf("<token>") + 7; i < tokenResult.IndexOf("</token"); i++) { token += tokenResult[i]; } //       http://www.last.fm/api/auth/ c  API Key     ) Process s = Process.Start("http://www.last.fm/api/auth/?api_key=" + ApiKey + "&token=" + token); //  ,    ,        . //     DialogResult d = MessageBox.Show("  ?", "", MessageBoxButtons.OKCancel, MessageBoxIcon.Question); //     if (d == DialogResult.OK) { //      ( API Key, ,     ,     '&'  '=' string tmp = "api_key" + ApiKey + "methodauth.getsessiontoken" + token + mySecret; //    MD5 (,         ) string sig = MD5(tmp); //     HttpWebRequest sessionRequest = (HttpWebRequest)WebRequest.Create("http://ws.audioscrobbler.com/2.0/?method=auth.getsession&token=" + token + "&api_key=" + ApiKey + "&api_sig=" + sig); //   ,      true,   . -   . sessionRequest.AllowAutoRedirect = true; //   HttpWebResponse sessionResponse = (HttpWebResponse)sessionRequest.GetResponse(); string sessionResult = new StreamReader(sessionResponse.GetResponseStream(), Encoding.UTF8).ReadToEnd(); //   (    XML ) for (int i = sessionResult.IndexOf("<key>") + 5; i < sessionResult.IndexOf("</key>"); i++) { sessionKey += sessionResult[i]; } } 


So, half the battle is done, moving on. Now you need to scrape the track.

 //  UNIX-    TimeSpan rtime = DateTime.Now - (new DateTime(1970, 1, 1, 0, 0, 0)); TimeSpan t1 = new TimeSpan(3, 0, 0); rtime -= t1; //   ,     -     //    int timestamp = (int)rtime.TotalSeconds; //    string submissionReqString = String.Empty; //  ( ,   API Key): submissionReqString += "method=track.scrobble&sk=" + sessionKey + "&api_key=" + ApiKey; //       (, ,  , ),       UrlEncode  HttpUtility. submissionReqString += "&artist=" + HttpUtility.UrlEncode(artist); submissionReqString += "&track=" + HttpUtility.UrlEncode(track); submissionReqString += "& timestamp=" + timestamp.ToString(); //         &  t.  -     ,   . submissionReqString += "&album=" + HttpUtility.UrlEncode(album); //   (    (  '&'  '='    ): string signature = String.Empty; //    signature += "album" + album; //  API Key signature += "api_key" + ApiKey; //  signature += "artist" + artist; //     signature += "methodtrack.scrobblesk" + sessionKey; //  signature += "timestamp" + timestamp; //   signature += "track" + track; //      signature += mySecret; //     MD5     submissionReqString += "&api_sig=" + MD5(signature); //      POST     HttpWebRequest submissionRequest = (HttpWebRequest)WebRequest.Create("http://ws.audioscrobbler.com/2.0/"); //     //   .   ,   ,      submissionRequest.ServicePoint.Expect100Continue = false; //    submissionRequest.UserAgent = "Mozilla/5.0"; //     ,    POST  submissionRequest.Method = "POST"; //    POST   submissionRequest.ContentType = "application/x-www-form-urlencoded"; //  ,         ,   Exception submissionRequest.Timeout = 6000; //     ,        (UTF8 ) byte[] EncodedPostParams = Encoding.UTF8.GetBytes(submissionReqString); submissionRequest.ContentLength = EncodedPostParams.Length; //      ( ,  ,  ) submissionRequest.GetRequestStream().Write(EncodedPostParams, 0, EncodedPostParams.Length); //   submissionRequest.GetRequestStream().Close(); //    HttpWebResponse submissionResponse = (HttpWebResponse)submissionRequest.GetResponse(); //    string submissionResult = new StreamReader(submissionResponse.GetResponseStream(), Encoding.UTF8).ReadToEnd(); //  .     status="ok",   ,  Exception  -  . if (!submissionResult.Contains("status=\"ok\"")) throw new Exception("  !  - " + submissionResult); //   ,      ,   . 

Thus, the tracks scramble without entering a password. This is an updated API, before entering a password was required (this can be understood from my program). Having saved the session key somewhere, you will not need to ask the user to confirm access each time (the key will be valid until the user “disconnects” your client from his profile on this page).

I cited the main links at the beginning of the article. Perhaps it remains to add a link to the Last.fm forum for those using the API (in English only). Without its use I would hardly have reached the end.

That's all. I hope I have described each step in sufficient detail. I will be glad to answer your questions, if any.
Thanks for attention.

Source: https://habr.com/ru/post/143143/


All Articles