#!/usr/bin/env python
# devloop.lyua.org 08/2008
# Reading your Entire Library playlist randomly
import urllib, urllib2, cookielib, random
import sys, socket, os
try:
  import library
except ImportError:
  print "No library found! Launch get_library.py first!"
  sys.exit(1)

nb_songs=len(library.library)

# >> Please modify account information <<
account={'login':'toto','password':'toto'}

cj = cookielib.LWPCookieJar()

opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
urllib2.install_opener(opener)

# Get our PHPSESSID
print "Connecting on the server..."
req=urllib2.Request("http://www.anywhere.fm/")
socket.setdefaulttimeout(6)
try:
  fd=urllib2.urlopen(req)
except IOError:
  print "Error getting url"
  sys.exit(1)

# Hardcoded initial Unique Request ID : works! :)
urid=1218964000
# Open a session with account information
req = urllib2.Request("http://music.anywhere.fm/account/login?_unique_request_id_="+str(urid),urllib.urlencode(account))
try:
  fd=urllib2.urlopen(req)
  htmlSource=fd.read()
except IOError:
  print "Error getting url"
  sys.exit(1)
except socket.timeout:
  print "timeout error"
  sys.exit(1)

if htmlSource.strip()!="<success>true</success>":
  print "Warning: Connexion error! Check the credentials!"
  print "Using default user_id (demo)"
else:
  print "Connexion successfull"

urid+=1
# Get our user_id
req=urllib2.Request("http://music.anywhere.fm/account/get_current_user?_unique_request_id_="+str(urid))
try:
  fd=urllib2.urlopen(req)
  htmlSource=fd.read()
except IOError:
  print "Error getting url"
  sys.exit(1)
except socket.timeout:
  print "timeout error"
  sys.exit(1)

user_id=[q.strip() for q in htmlSource.split("\n") if q.find("user_id")>=0][0].split('>')[1].split('<')[0]
print "user_id =",user_id

# ! required for AMF queries, don't remove !
session_id=cj._cookies['music.anywhere.fm']['/']['auth_session_id'].value

# Now let's go AMF :p
# feel free to modify user_id here for study, for example to 46 (=free music)
#user_id=46
import pyamf
from pyamf.remoting import client
from pyamf.flex import messaging
from pyamf import remoting
from pyamf import util
import uuid
from pyamf.amf3 import Decoder
import random

random_list=range(0,nb_songs)
random.shuffle(random_list)

for current in random_list:
  song=library.library[current]
  print song['name'],"-",song['artist'],"(",song['album'],")"

  urid+=1
  # Get a valid url for an mp3 file (thumbs up lol)
  url='http://www.anywhere.fm/amfphp/gateway.php?_unique_request_id_='+str(urid)
  gw = client.RemotingService(url,pyamf.AMF0,pyamf.ClientTypes.Flash9)
  message = messaging.RemotingMessage(operation=u'get_song_url',
      source=u'BlazingFast.DBQueries',
      timestamp=0,
      destination=u'amf',
      clientId=None,
      headers={u'DSEndpoint':None,u'DSId': u'nil'},
      timeToLive=0,
      messageId=unicode(uuid.uuid4()),
      messageRefType=u'flex.messaging.messages.RemotingMessage',
      body=[unicode(session_id),user_id,song['master_id'],song['song_resource_id']])
  gw.addRequest('null', message)

  # Encode and inject
  #print "Getting a valid music url..."
  x=remoting.encode(gw.getAMFRequest(gw.requests)).getvalue()
  xamf =  {'Content-Type' : 'application/x-amf'}
  req=urllib2.Request(url,data=x,headers=xamf)
  socket.setdefaulttimeout(6)
  try:
    fd=urllib2.urlopen(req)
    htmlSource=fd.read()
  except IOError:
    print "Error getting url"
    sys.exit(1)

  # This one works (the payload is very small, url in "standard" ascii)
  liste=remoting.decode(htmlSource)
  sesame=liste['/1'].body.body['url']
  #print "Reading url",sesame
  # Let's play music hax0rz !!
  os.system("mplayer -really-quiet '"+sesame+"' >/dev/null 2>&1")
