+# load login credentials from settings file
+load_auth = (callback) ->
+ if auth.user and auth.token
+ callback auth
+ return
+
+ fs.readFile auth_file, 'utf8', (err, data) ->
+ if err
+ callback err
+ else
+ callback null, JSON.parse data
+
+# login and get a session key
+login = (callback) ->
+ load_auth (err, auth) ->
+ return callback(err) if err?
+
+ http.get { host: 'alpha.libre.fm', port: 80, path: "/2.0/?method=auth.getmobilesession&username=#{auth.user}&authToken=#{auth.token}"}, (res) ->
+ if res.statusCode != 200
+ console.log "login response code: #{res.statusCode}"
+ callback "login response code: #{res.statusCode}"
+ return
+
+ res.setEncoding 'utf8'
+ body = ''
+ res.on 'data', (chunk) ->
+ body += chunk
+ res.on 'end', ->
+ parser = new expat.Parser 'UTF-8'
+ cur_tag = ''
+ done = false
+ parser.on 'startElement', (name, attrs) ->
+ cur_tag = name
+ parser.on 'text', (str) ->
+ if cur_tag is 'key'
+ done = true
+ auth.sk = str
+ console.log("got key \"#{str}\"")
+ callback null, str
+ else if cur_tag is 'error'
+ done = true
+ callback "login failed: #{str}"
+ # ignore other stuff in there
+ unless parser.parse body, true
+ done = true
+ callback "login server response wouldn't parse as XML."
+ console.log "login server sent us bad XML: #{body}"
+
+ unless done
+ callback "Couldn't understand response from login server"
+
+
+
+exports.login = login # fixme remove this from the API and call it automatically