⬆️ ⬇️

Work with last.fm API on JavaScript

With the passage of time, the author realized that the underwritten is complete nonsense.



For those who do not want to read



The page on which all the following in the example (include alert).

An online player that made me get to this topic.



Introduction



Good day! Not so long ago, he touched on the topic of "online players" and the like. There are many, very much I would say. I wanted to make an analogue, first of all for myself. Wanted by the standard - the base vk.com, scramble last.fm (later the last), albums from it, playlists, hearts and so on. The problem immediately leaked out - my hosting is very bad for constant requests for it. There was nothing left but to go almost completely to javascript (later js). So, since I haven’t found the Russian description of “How to work with last.fm api javascript”, and spent a lot of time and nerves to solve this problem, let's start.



Let's analyze the work of last.fm api on the example of scrobbling. Touch sessions, authorization and function calls using javascript. Yes, and we will parse it in a language that everyone understands, so that both young and old can understand.



Working process



1. If there is no account for last.fm api, then run to do it . If the account is and the keys to him with you - read on.

')

2. From the last one there is a link to the [github.com] js library for working with javascript APIs. It is quite good, I did not googling the analogs, it works, so we will use it. So, let's call this library “standard”, and all the scripts in it are naturally “standard”.



3. The first thing we need to do is replace the standard md-hash ... torus ?! Let's call it md5 encoder. So here, for some reason, the standard md5-coder with Cyrillic does not work (or rather, it works, but the last one revolts and does not accept the hash). A proven version can be found here [pajhome.org.uk]. Download the zip in the Download section (at the time of writing Current version 2.2), find md5-min.js in it and replace it with the standard lastfm.api.md5.js.



4. In the standard lastfm.api.js, change the 841 line with return md5 (string); on return hex_md5 (string); . New encoder because.



5. Great, hashing is and will work. We start to connect the script.

<script type="text/javascript" src="md5-min.js"></script> <script type="text/javascript" src="lastfm.api.js"></script> 


I changed the standard lastfm.api.md5.js to md5-min.js, and not just changed the content of the standard, pay attention. And follow the order do not forget.



6. Authorize our site on the region with simple javascript code

 var lastfm = new LastFM({ apiKey : '96d047d302a8707f3a7410873466dbfd', apiSecret : '3afdcf3ccad058a82202544549cb141b' }); 


Yes, the main disadvantage of working with javascript and lastfm. Keys are open. apiKey - API Key on last, apiSecret - secret. This code after connecting scripts, do not forget.



7. Further, in the standard lastfm.api.js there is again a small drawback for scrobbling. We find 659-674 lines (I have reduced the extra lines, tabs and comments)

 scrobble : function(params, callbacks){ if(params.constructor.toString().indexOf("Array") != -1){ var p = {}; for(i in params){ for(j in params[i]){ p[j + '[' + i + ']'] = params[i][j]; } } params = p; } signedCall('track.scrobble', params, session, callbacks, 'POST'); } 




There is no session at the input, but there is at the output. Strange, but not a word about the session anywhere. Rewrite the first line.

scrobble: function (params, callbacks) { => scrobble: function (params, session, callbacks) {



8. Remember that our main goal is scrobbling. Here the paths diverge. Suppose that you do not have a session key - then we read on, briefly tell you how to get it. If there is a session key, go to step 11. Although you can read.



9. Getting a session key consists of two steps. The first is to get a temporary token. Practice shows that he can safely be the key of the session, but only for 60 minutes. The second stage is naturally the process of obtaining the session key.



10. You can get a token at

 http://www.lastfm.ru/api/auth?api_key=96d047d302a8707f3a7410873466dbfd 


Where after the "=" sign follows the API key with a flipper. You can, for example, make a simple link, by clicking on which the user will go to this page. In the flipper API account there is a Callback URL field. The user goes to the address specified in this field after authorization and is assigned to the address? Token = XXXXX. Further, there are two options for implementation:



First option


Server. Callback URL leads to the page where server processing script is present. Those. Some library for working with the last is connected, processing the token received from the address and assigning the session key already received to some user in the database for example. And then we load this key from the database and use it. It's easier for me, I did, but my goal is not to tell in detail about this method.



Second option


Client. We pull out the token from the address by js, drag it conditionally into the variable token. We have a token - we turn to api flipper for the first time in our life:

 lastfm.auth.getSession({token: token}, {success: function(data){ alert(", "+data.session.name+"!\n\r  ,    "+data.session.key); //   sk = data.session.key; //       . }, error: function(code, message){ if (code == 4) alert(" .   "); }}); 


Here is the call to get the session key. The answer is in json format. Here we need to take into account the nuance: if we need the session key for one time, then we will not need anything outside. If you want to communicate with a flipper for a long time, then it’s stupid to ask the user to reconnect every entry on the site. In this case, we need to use either cookies or a database, as the heart will like.

The auth.getSession is replaced by any other method from all the fin methods , and under the first braces we enter all the variables that need to be passed. Well, let's boldly change to track.scroble



11. Scrobble. The required parameters (as requested by the last one) are track name, artist and UNIX-time.

 var ts = Math.floor(new Date().getTime()/1000); lastfm.track.scrobble({artist: "Linkin Park", track: "Numb", timestamp: ts}, {key: sk}, {success: function(data){ alert(" !"); }, error: function(code, message){ alert("  ..."); }}); 


{key: sk} this is the session key. This is the mystical session.



12. A very important note: if you suddenly slip two requests for a fin in one second, there will be trouble. 93 line of standard last.fm api: var jsonp = 'jsonp' + new Date (). GetTime (); =>

var jsonp = 'jsonp' + new Date (). getTime () + '' + Math.round (1000000 * Math.random ());



Conclusion



That seems to be all. What else needs to be said: the output is constantly different objects, then data.result then data.artistmatches, so pay attention. Have a nice work!



Links



The page on which all the above in the example (include alert).

An online player that made me get to this topic.



Offtopic: the player is going to support while the eyes are looking at the monitor, but: the topic is not about the player, the player is in development, if anyone is interested in the topic topic and he would like to figure it out, so do not swear, please. For this there will be a separate topic. Later.

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



All Articles