File: lastfm.ml

package info (click to toggle)
ocaml-lastfm 0.1.2-1
  • links: PTS, VCS
  • area: main
  • in suites: lenny
  • size: 364 kB
  • ctags: 59
  • sloc: ml: 619; makefile: 119; sh: 3
file content (603 lines) | stat: -rw-r--r-- 20,941 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
(*****************************************************************************

  Liquidsoap, a programmable audio stream generator.
  Copyright 2003-2007 Savonet team

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details, fully stated in the COPYING
  file at the root of the liquidsoap distribution.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

 *****************************************************************************)

(* lastfm protocol API for ocaml *)

exception Http of string

(* Records for client *)
type client = { client : string ; version : string }
type login = { user : string ; password : string }

let request ?(post="") ?(headers=[]) ?(port=80) ~host req =
let call = match post with
   | "" -> new Http_client.get_call
  	 | _ -> new Http_client.post_call
  in
  let pipeline = new Http_client.pipeline in
  let http_headers = call#request_header `Base in
  let body = call#request_body in
  call#set_request_uri (Printf.sprintf "http://%s:%d%s" host port req) ;
  let headers = ("User-agent",
      Printf.sprintf "ocaml-lastfm/%s" Constants.version) 
      :: headers
  in
  http_headers#set_fields headers ;
  begin
    match post with
  | "" -> ()
  | _ -> begin
  	         body#set_value post ; 
  		 call#set_request_body body ;
  		 http_headers#update_field 
  		   "Content-length" 
  		   (string_of_int (String.length post));
  	       end
  end ;
  call#set_request_header http_headers ;
  pipeline#add call ;
  try
    pipeline#run () ;
    call#response_body#value
  with
    | Http_client.Http_protocol e 
    | e -> 
       pipeline#reset() ; 
       raise (Http  (Printexc.to_string e))

module Audioscrobbler=
  struct

    (* See http://www.audioscrobbler.net/development/protocol/
     * For protocol description *)

    (* Data types *)
    type source = User | Broadcast | Recommendation | Lastfm | Unknown
    type rating = Love | Ban | Skip
    type action = NowPlaying | Submit

    (* song submission type *)
    type song = { artist : string; track: string; time: float option; 
                  source : source option; rating : rating option ;
                  length : float option ; album : string option ;
                  trackauth : string option ; tracknumber : int option; 
                  musicbrainzid : string option }

    type error = Http of string | Banned | Badauth | Badtime
                | Failed of string | UnknownError of string | Success
                | Internal of string | BadData of string
    exception Error of error
    
    let string_of_error e = 
      match e with
        | Http s -> Printf.sprintf "http connection failed: %s" s
        | Banned -> "banned client"
        | Badauth -> "wrong login/password"
        | Badtime -> "wrong timestamp, check your clock"
        | Failed s -> Printf.sprintf "failure: %s" s
        | UnknownError s -> Printf.sprintf "unknown error: %s" s
        | Internal s -> Printf.sprintf  "erreur interne: %s" s
        | BadData s -> Printf.sprintf "Wrong song data: %s" s
        | Success -> "success!"

    let error_of_response s = 
      try
        let parse s = 
           let regexp = Pcre.regexp "FAILED\\s([^\\r\\n]*)" in
           let sub = Pcre.exec ~rex:regexp s in
           Failed (Pcre.get_substring sub 1)
        in
	let test (p,e) = 
	  try
	    ignore(Pcre.exec ~pat:p s) ;
	    raise (Error e)
	  with
	    | Not_found -> ()
	in
	let values = [("OK",Success);
	              ("BANNED",Banned);
		      ("BADAUTH",Badauth);
		      ("BADTIME",Badtime)]
        in
	try
	  List.iter test values ;
          parse s
	with 
	  | Error e -> e
      with
        | Not_found -> UnknownError "unrecognized response code"

    (* Protocol constants *)
    let version = "1.2"
    let base_port = 80
    let base_host = "post.audioscrobbler.com"
    let handshake_req = Printf.sprintf "/?hs=true&p=%s&c=%s&v=%s&u=%s&t=%s&a=%s" version
    (* sessions contains (user,pass) => id *)
    let sessions = Hashtbl.create 1
    (* urls contains id => (np_url,submit_url) *)
    let urls = Hashtbl.create 1
    let raise e = raise (Error e)
    (* Wrapper for main request *)
    let request = try request with e -> raise (Http (Printexc.to_string e))
    let arg_value_string x = 
      match x with 
        | Some e -> e
        | None -> ""
    let arg_value_int x = 
      match x with 
        | Some e -> string_of_int e
        | None -> ""
    let arg_value_float x =
      match x with
        | Some e -> Printf.sprintf "%.0f" e
        | None -> ""


    let clear sessionid =
        let keys = Hashtbl.fold (fun a b r -> if b = sessionid then a::r else r)
                      sessions []
        in
        ignore (List.map (fun x -> Hashtbl.remove sessions x) keys) ;
        Hashtbl.remove urls sessionid

    let handshake client login = 
      let client,version,user,pass = 
         client.client,client.version,
         login.user,login.password
      in
      try 
        Hashtbl.find sessions (user,pass)
      with
        | Not_found ->
           let timestamp = Printf.sprintf "%.0f" (Unix.time ()) in
           let pass_digest = Digest.string pass in
           let token = Digest.string((Digest.to_hex pass_digest) ^ timestamp) in
           let req = handshake_req client version user timestamp (Digest.to_hex token) in
           let ans = request ~host:base_host ~port:base_port req in
           let state,id,v = 
             try
               let lines = Pcre.split ~pat:"[\r\n]+" ans in
               match lines with
                 | state :: id :: [a; b] -> state,id,(a,b)
                 | _ -> raise (error_of_response ans)
             with
               | Not_found -> raise (error_of_response ans)
           in
           match error_of_response state with
             | Success -> Hashtbl.replace sessions (user,pass) id; 
                          Hashtbl.replace urls id v; id
             | e -> raise e

    let check_song s a = 
      match s.source with
        | None when a = Submit ->
             raise (BadData "source field is required for submit action")
        | _ -> () ;
      match s.length with
        | None when a = Submit && s.source = Some User -> 
            raise (BadData "length required when source is User")
        | _ -> () ;
      match s.time with
        | None when s.source = Some User ->
             raise (BadData "time required when source is User")
        | _ -> () ;
      match s.trackauth with
        | None when s.source = Some Lastfm -> 
             raise (BadData "trackauth required when source is Lastfm")
        | _ -> () ;
      match s.rating with 
        | Some Ban
        | Some Skip when s.source <> Some Lastfm -> 
             raise (BadData "bad rating value (ban and skip are for lastfm sources only)")
        | _ -> ()


    let audioscrobbler_post id base_url values = 
      let url = Neturl.parse_url base_url in
      let host = Neturl.url_host url in
      let port = Neturl.url_port url in
      let req = String.concat "/" (Neturl.url_path url) in
      let args = List.map (fun (a,b) -> 
                             Printf.sprintf "%s=%s" 
                                a (Netencoding.Url.encode b) )
                            values
      in
      let post = String.concat "&" args in
      let headers = [("Content-type","application/x-www-form-urlencoded")] in
      let ans = request ~post:post ~headers:headers ~host:host ~port:port req in
      match error_of_response ans with
        | Success -> ()
        | e -> clear id; raise e

    let np id song = 
      let url,_ = 
        try 
          Hashtbl.find urls id
        with
          | Not_found -> raise Badauth
      in
      check_song song NowPlaying ;
      let values = [("s",id);("a",song.artist);("t",song.track);
                    ("album",arg_value_string song.album);
                    ("l",arg_value_float song.length);
                    ("n",arg_value_int song.tracknumber);
                    ("m",arg_value_string song.musicbrainzid)] 
      in
      audioscrobbler_post id url values

     let submit id songs = 
      let _,url = 
        try 
          Hashtbl.find urls id
        with
          | Not_found -> raise (Internal (Printf.sprintf "No session data for session ID %s" id))
      in
      let count = ref 0 in
      let failed = ref [] in
      let args = ref [("s",id)] in
      let get_arg = fun s -> Printf.sprintf "%s[%d]" s !count in
      let add_arg song =
        try 
          check_song song Submit ;
          let ar,tr,t,s,r,l,al,n,m,x =
             song.artist, song.track,song.time,
             song.source, song.rating,
             song.length, song.album,
             song.tracknumber, song.musicbrainzid,
             song.trackauth
          in
          let l = match l with
                    | None -> ""
                    | Some s -> Printf.sprintf "%.0f" s
          in
          let t = match t with
                    | Some t -> Printf.sprintf "%.0f" t
                    | None -> ""
          in
          let x = match x with
                    | Some x -> x
                    | None -> ""
          in
          let s =  match s with 
                     | Some User -> "P"
                     | Some Broadcast -> "P"
                     | Some Recommendation -> "E"
                     | Some Lastfm -> "L"
                     | Some Unknown -> "U"
                     | None -> raise (Internal "source field is required for submit")
          in
          let r =  match r with 
                     | Some Love -> "L"
                     | Some Ban -> "B"
                     | Some Skip -> "S"
                     | None -> ""
          in
          args := [(get_arg "a",ar);(get_arg "t",tr);(get_arg "i",t);
                   (get_arg "o",s ^ x);(get_arg "r",r);(get_arg "l",l);
                   (get_arg "b",arg_value_string al);(get_arg "n",arg_value_int n);
                   (get_arg "m",arg_value_string m)] @ (!args)
       with
         | Error e -> failed := (e,song) :: !failed 
     in
     List.iter add_arg songs ;
     audioscrobbler_post id url (!args) ;
     !failed

    let get_song ?time ?source ?rating
                 ?length ?album ?tracknumber 
		 ?musicbrainzid ?trackauth 
		 ~artist ~track () = 
    { artist = artist ; track = track ; time = time  ;
      source = source; rating = rating ; length = length ;
      album = album ; tracknumber = tracknumber ; 
      musicbrainzid = musicbrainzid ; trackauth = trackauth }

    let do_np client login song = 
      let id = handshake client login in
      try
        np id song
      with
        | Error Badauth -> (* Retry in case of expired session id *)
	                   clear id ;
	                   let id = handshake client login in
		           np id song

    let do_submit client login songs = 
      let id = handshake client login in
      try 
        submit id songs
      with
        | Error Badauth -> (* Retry in case of expired session id *)
                           clear id ;
                           let id = handshake client login in
                           submit id songs 

  end

module Radio=
  struct

    (* Type for track datas 
     * A track is a list of "field","value" metadatas
     * and an uri *)
    type track = (string * string) list * string

    type session = { login : login option; station : ((string*string) list*string) option;
                     base_url : string; playlist_url : string option; 
                     base_path: string }

    type error = Http of string | Auth of string | Adjust of string*string | Playlist | Empty
    exception Error of error
    exception Internal of string

    let string_of_error e = 
      match e with
        | Http s -> Printf.sprintf "http connection failed: %s" s
        | Auth s -> Printf.sprintf "could not open session:\n%s" s
        | Adjust (s,s') -> Printf.sprintf "could not adjust station to %s:\n%s\nIs the URI valid ?" s s'
        | Playlist -> "error while parsing the playlist"
        | Empty -> "no files available"
   
    let _raise = raise
    let raise e = raise (Error e)
    (* Wrapper for main request *)
    let request ~host = try request ~host:host with e -> raise (Http (Printexc.to_string e))

    (* Some constant for the protocol *)
    let base_host = "ext.last.fm"
    let sessions = Hashtbl.create 10
    let anon_req = "/1.0/webclient/xmlrpc.php"
    let anon_post = "<methodCall><methodName>getSession</methodName><params /></methodCall>"
    let anon_handshake = Printf.sprintf "/1.0/radio/webclient/handshake.php?sessionKey=%s&user=%s"
    let registered_handshake = Printf.sprintf "/radio/handshake.php?username=%s&passwordmd5=%s"
    let station_set base id url = Printf.sprintf "%s/adjust.php?session=%s&url=%s" base id url

    let playlist_req id options = 
      let d = 
        try
         Hashtbl.find sessions id
        with
          | Not_found -> 
              raise (Auth (Printf.sprintf "No session registered for id %s" id))
      in
      let options = 
        match options with
          | Some s -> s
          | None -> ""
      in
      let url = 
        match d.playlist_url with
          | None -> "http://ws.audioscrobbler.com/radio/xspf.php"
          | Some s -> s
      in
      Printf.sprintf "%s?sk=%s&%s" url id options

    let playlist id options = 
       let url = playlist_req id options in
       let data = 
         try
           Http_client.Convenience.http_get url
         with
           | e -> raise (Http (Printexc.to_string e))
       in
       let data = Netencoding.Base64.decode data in
       Netencoding.Url.decode data
    
    (* Some parsing functions *)

    let parse_args s = 
      let rex = Pcre.regexp "[&\n]" in
      let values = Pcre.split ~rex:rex s in
      let split s l = 
        try
          let sub = Pcre.exec ~pat:"([^=]*)=(.*)" s in
          (Pcre.get_substring sub 1,Pcre.get_substring sub 2) :: l
        with
          | Not_found -> l
      in
      List.fold_right split values []
    
    let parse_handshake s =
      let params = parse_args s in
      try
        let f x = List.assoc x params in
        let g x = try Some (f x) with Not_found -> None in
          f "session",g "playlist_url", 
          f "base_url", f "base_path"
      with
        | Not_found -> raise (Auth s)

    let adjust_pat = "response=OK"
    let check_adjust s =
        Pcre.pmatch ~pat:adjust_pat s
    
    let opt_split_rex = Pcre.regexp "^([^?]+)\\?(.+)$"
    let opt_parse s =
        try
          let sub = Pcre.exec ~rex:opt_split_rex s in
          Pcre.get_substring sub 1, Some (Pcre.get_substring sub 2)
        with
          | Not_found -> s,None

    let auth_split_rex = Pcre.regexp "^lastfm://([^:]+):([^@]+)@(.+)$"
    let parse uri = 
        try
          let sub = Pcre.exec ~rex:auth_split_rex uri in
          let data = Pcre.get_substring sub 3 in
          let station,options = opt_parse data in
          let user,password = Pcre.get_substring sub 1,
                              Pcre.get_substring sub 2
          in
          (Some { user = user ; password = password }),
                 Printf.sprintf "lastfm://%s" station,options
        with
          | Not_found -> let station,options = 
                           opt_parse uri 
                         in
                         None,
                         station,
                         options
    
    let anon_parse s = 
       try
         let content = Xml.parse_string s in
         let rec get_auth content = 
           match content with
             | Xml.Element("data",_,
                   [Xml.Element("value",_,[Xml.Element("string",_,[Xml.PCData x])]);
            	Xml.Element("value",_,[Xml.Element("string",_,[Xml.PCData y])])]) :: l
    	          -> x,y
             | Xml.Element(_,_,l) :: l' -> get_auth (l@l')
    	 | _ -> raise (Auth s)
        in
        get_auth [content]
       with
         | _ -> raise (Auth s)
    
    (* Core stuff.. *)
    
    let clear id =
        Hashtbl.remove sessions id
    
    let anon_session () = 
      let headers = [("Content-Type","text/xml")] in
      let ret = request ~host:base_host ~post:anon_post ~headers:headers anon_req in
      anon_parse ret
    
    let init login = 
      match login with
        | None -> let user,id = anon_session () in
                  let ret = request ~host:base_host 
                      (anon_handshake id (Netencoding.Url.encode user)) 
                  in
                  let id,playlist_url,
                      base_url,base_path = 
                      parse_handshake ret 
                  in
		  Hashtbl.replace sessions id {playlist_url=playlist_url;
                                               base_url=base_url;
                                               base_path=base_path;
                                               login=None;
                                               station=None} ;
		  id
       | Some login -> 
          try
            Hashtbl.iter (fun x d -> 
	                     if d.login = Some login then _raise (Internal x))
			 sessions ;
	    _raise Not_found
          with
            | Not_found -> 
	            let user,password = login.user,login.password in
                    let password = Digest.to_hex (Digest.string password) in
                    let ret = request ~host:base_host (registered_handshake 
    	                      (Netencoding.Url.encode user) password)
                    in
                    let id,playlist_url,
                        base_url,base_path = 
                        parse_handshake ret 
                    in
		    Hashtbl.replace sessions id {playlist_url=playlist_url;
                                                 base_url=base_url;
                                                 base_path=base_path;
                                                 login=Some login;
                                                 station=None} ;
		    id
	   | Internal x -> x
      
    
    let adjust id req = 
      let d = 
        try
          Hashtbl.find sessions id
	with
	  | Not_found -> 
	      raise (Auth (Printf.sprintf "No session registered for id %s" id))
      in
      let base_url,base_path = d.base_url,d.base_path in
        match d.station with
	  | Some (a,s) when s = req -> a
          | _ ->
                let http_req = station_set base_path id 
                   (Netencoding.Url.encode req)
                in
                let ret = request ~host:base_url http_req in
                if check_adjust ret then
                 let args = parse_args ret in
                 ( Hashtbl.replace sessions id 
                        {login=d.login;station=Some (args,req);
                         playlist_url=d.playlist_url;
                         base_url=base_url;base_path=base_path} ;
                  args )
                else
                  begin
                    clear id;
                    raise (Adjust (req,ret))
                  end
    
    let tracks id options = 
      try
        let playlist = playlist id options in
        Xmlplaylist.tracks playlist
      with
        | Xmlplaylist.Error e -> clear id; raise Playlist 
        | Error e -> clear id; raise e
    
    let get uri = 
      let login,station,options = parse uri in
      let id = 
        match login with
	  | None -> 
	    (* Check if another anonymous session is registered
	       for this station url.
	       
	       However, this cannot be optimal, we may end up
	       asking a new playlist for another session, which 
	       may stop any other simultaneous streaming on the 
	       same session. *)
	    begin
	      try
	        let ids = 
                  Hashtbl.fold (fun a d c -> 
		                  match d.station with
                                    | Some (_,s) when s = station -> a :: c
                                    | _ -> c)
			       sessions []
		in
		List.hd ids
	      with
	        |  Failure "hd" -> init login
	    end
	  | _ -> init login 
      in
      try
        ignore(adjust id station);
        tracks id options
      with Error _ when login <> None -> 
          (* Retry in case of expired session *)
	  clear id;
          let id = init login in
	  ignore(adjust id station);
	  tracks id options

end