3 crypto = require 'crypto'
4 xml = require 'node-xml'
9 sum = crypto.createHash 'md5'
11 return sum.digest 'hex'
13 new_auth_token = (user, pass) ->
14 token = md5(user + md5(pass))
19 auth_file = "#{process.env.HOME}/.libre.fm-cmus.auth"
20 save_auth = (user, pass, callback) ->
21 token = new_auth_token(user, pass)
22 text = JSON.stringify user: user, token: new_auth_token(user, pass)
23 fs.writeFile auth_file, text, 'utf8', callback
26 # load login credentials from settings file
27 load_auth = (callback) ->
28 if auth.user and auth.token
32 fs.readFile auth_file, 'utf8', (err, data) ->
36 callback null, JSON.parse data
38 # login and get a session key
40 load_auth (err, auth) ->
41 return callback(err) if err?
43 http.get { host: 'alpha.libre.fm', port: 80, path: "/2.0/?method=auth.getmobilesession&username=#{auth.user}&authToken=#{auth.token}"}, (res) ->
44 if res.statusCode != 200
45 console.log "login response code: #{res.statusCode}"
46 callback "login response code: #{res.statusCode}"
49 res.setEncoding 'utf8'
51 res.on 'data', (chunk) ->
56 parser = new xml.SaxParser (cb) ->
57 cb.onStartElementNS (name, attrs, prefix, uri, namespaces) ->
59 cb.onCharacters (str) ->
63 console.log("got key \"#{str}\"")
65 else if cur_tag is 'error'
67 callback "login failed: #{str}"
68 # ignore other stuff in there
69 unless parser.parse body, true
71 callback "login server response wouldn't parse as XML."
72 console.log "login server sent us bad XML: #{body}"
75 callback "Couldn't understand response from login server"
79 exports.login = login # fixme remove this from the API and call it automatically
80 exports.new_auth_token = new_auth_token
81 exports.save_auth = save_auth