-- This is a proprietary plugin, property of Andreas Bielawski, (c) 2015 <andi (dot) b (at) outlook (dot) de>
-- DO NOT USE WITHOUT PERMISSION

do

local BASE_URL = 'http://music.163.com/api'

local function get_netease_data(id)
  local url = BASE_URL..'/song/detail/?ids=['..id..']'
  local res,code = http.request(url)
  if code ~= 200 then return "HTTP-FEHLER" end
  local data = json:decode(res).songs[1]
  return data
end

local function send_netease_data(data, receiver)
  local mp3_url = data.mp3Url
  local title = data.name
  local artist = data.artists[1].name
  local cb_extra = {
    receiver=receiver,
    url=mp3_url
  }
  local text = '"'..title..'" von '..artist
  send_msg(receiver, text, send_document_from_url_callback, cb_extra)
end

local function run(msg, matches)
  local id = matches[1]
  local data = get_netease_data(id)
  local receiver = get_receiver(msg)
  if mp3url == "HTTP-FEHLER" then
    return "Keinen Song gefunden :("
  else
    send_netease_data(data, receiver)
  end
end

return {
  description = "Sendet MP3 und Infos eines Tracks von music.163.com", 
  usage = {
    "#getmp3 [ID]: Downloadet MP3 und sendet Infos",
    "Link zu music.163.com-Track: Downloadet MP3 und sendet Infos"
  },
  patterns = {
    "^#getmp3 (%d+[%d%.]*)",
    "music.163.com/%#/song%?id=(%d+[%d%.]*)",
    "music.163.com/song%?id=(%d+[%d%.]*)"
  },
  run = run 
}

end