3 crypto = require 'crypto'
4 xml = require 'node-xml'
6 # soooo annoying that setTimeout takes the ms arg last
7 timeout = (ms, func) -> setTimeout func, ms
12 sum = crypto.createHash 'md5'
14 return sum.digest 'hex'
16 new_auth_token = (user, pass) ->
17 token = md5(user + md5(pass))
22 auth_file = "#{process.env.HOME}/.libre.fm-cmus.auth"
23 save_auth = (user, pass, callback) ->
24 token = new_auth_token(user, pass)
25 text = JSON.stringify user: user, token: new_auth_token(user, pass)
26 fs.writeFile auth_file, text, 'utf8', callback
29 # load login credentials from settings file
30 load_auth = (callback) ->
31 if auth.user and auth.token
35 fs.readFile auth_file, 'utf8', (err, data) ->
39 callback null, JSON.parse data
41 # login and get a session key
43 load_auth (err, auth) ->
44 return callback(err) if err?
46 http.get { host: 'alpha.libre.fm', port: 80, path: "/2.0/?method=auth.getmobilesession&username=#{auth.user}&authToken=#{auth.token}"}, (res) ->
47 if res.statusCode != 200
48 console.log "login response code: #{res.statusCode}"
49 callback "login response code: #{res.statusCode}"
52 res.setEncoding 'utf8'
54 res.on 'data', (chunk) ->
61 # FIXME switch to an xml parser that will tell me when it's done
64 callback "xml parser failed to do anything with login server response"
65 console.log "xml parser didn't exit: #{body}"
66 parser = new xml.SaxParser (cb) ->
67 cb.onStartElementNS (name, attrs, prefix, uri, namespaces) ->
70 cb.onCharacters (str) ->
72 cb.onEndElementNS (name, attrs, prefix, uri, namespaces) ->
76 console.log("got key \"#{content}\"")
77 callback null, content
78 else if element is 'error'
80 callback "login failed: \"#{content}\""
81 # ignore other tags stuff in there
83 parser.parseString body
87 exports.login = login # fixme remove this from the API and call it automatically
88 exports.new_auth_token = new_auth_token
89 exports.save_auth = save_auth