require("json")
local base = _G
module("vimeocore")
function vimeo_getadress(inAdr, quality)
  if quality == nil then
    quality = "hd"
  end
  if inAdr == nil then
    return nil
  end
  local session = base.m_simpleTV.WinInet.New("Opera/9.80 (Windows NT 6.1; U; ru) Presto/2.9.168 Version/11.52")
  if session == nil then
    return nil
  end
  base.m_simpleTV.WinInet.SetOptionInt(session, 2, 3000, 0)
  base.m_simpleTV.WinInet.SetOptionInt(session, 6, 5000, 0)
  local video_id = base.findpattern(inAdr, "/(%d+)", 1, 1, 0)
  if video_id == nil then
    base.m_simpleTV.WinInet.Close(session)
    return nil
  end
  local url = "player.vimeo.com"
  local index = "config/" .. video_id .. "?type=moogaloop&referrer=vimeo.com&cdn_server=a.vimeocdn.com&player_server=player.vimeo.com&clip_id=" .. video_id
  local rc, answer = base.m_simpleTV.WinInet.Get(session, url, index)
  if rc ~= 200 then
    base.m_simpleTV.WinInet.Close(session)
    return nil
  end
  if not base.string.match(answer, "{\"request\":{") then
    base.m_simpleTV.WinInet.Close(session)
    return nil
  end
  local t = base.json.decode(answer)
  if t == nil or t.request == nil or t.request.signature == nil or t.request.timestamp == nil or t.request.player_url == nil or t.video == nil or t.video.smil == nil or t.video.smil.qualities[1] == nil then
    base.m_simpleTV.WinInet.Close(session)
    return nil
  end
  local i_quality = t.video.smil.qualities[1]
  local i = 1
  while t.video.smil.qualities[i] ~= nil do
    if t.video.smil.qualities[i] == quality then
      i_quality = quality
      break
    end
    i = i + 1
  end
  url = t.request.player_url
  index = "play_redirect?clip_id=" .. video_id .. "&sig=" .. t.request.signature .. "&time=" .. t.request.timestamp .. "&quality=" .. i_quality .. "&codecs=H264,VP8,VP6&type=moogaloop_local&embed_location="
  base.m_simpleTV.WinInet.SetOpenRequestFlags(session, 2097152)
  rc = base.m_simpleTV.WinInet.Get(session, url, index)
  if rc ~= 302 then
    base.m_simpleTV.WinInet.Close(session)
    return nil
  end
  local header = base.m_simpleTV.WinInet.GetRawHeader(session)
  base.m_simpleTV.WinInet.Close(session)
  if header == nil then
    return nil
  end
  retadr = base.findpattern(header, "Location: (.-)\n", 1, 10, 1)
  if retadr == nil then
    return nil
  end
  retadr = retadr .. "$OPT:http-referrer=http://" .. url
  return retadr
end
