--script getaddress filmon (11/09/2015)

if m_simpleTV.Control.ChangeAdress ~= 'No' then return end

local inAdr =  m_simpleTV.Control.CurrentAdress

if inAdr==nil then return end

if  not string.match( inAdr, '^filmonlivetv=' ) then return end

m_simpleTV.Control.ChangeAdress='Yes'
m_simpleTV.Control.CurrentAdress = ''

----------------------------------------------------------------
local session = 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 end

 --INTERNET_OPTION_CONNECT_TIMEOUT
 m_simpleTV.WinInet.SetOptionInt(session,2,8000,0)
 --INTERNET_OPTION_RECEIVE_TIMEOUT
 m_simpleTV.WinInet.SetOptionInt(session,6,8000,0)
---------------------------------------------------------------
local id = string.match(inAdr,'%d+')
if id == nil then return end

local body = 'channel_id=' .. id .. '&quality=low'
local host = 'http://www.filmon.com/ajax/getChannelInfo'
local head = 
'Accept-Language: ru-RU,ru;q=0.9,en;q=0.8\n' ..
'Referer: http://www.filmon.com/tv/live\n' ..
'Cookie: flash-player-type=hls; \n' ..
'Content-Type: application/x-www-form-urlencoded; charset=UTF-8\n' ..
'Accept: application/json, text/javascript, */*; q=0.01\n' ..
'X-Requested-With: XMLHttpRequest'

local rc,answer=m_simpleTV.WinInet.Post(session,host,nil,head,body)
 m_simpleTV.WinInet.Close(session)

 if rc~=200 then
     m_simpleTV.WinInet.Close(session)
     m_simpleTV.OSD.ShowMessage("Connection error - " .. rc ,255,10)
  return
 end

if answer ~= nil or answer ~= '' then
   answer = string.gsub(answer,'":%[%]','":""')
end
 
--debug_in_file(answer ..  '\n')

require('json')

local t = json.decode(answer)

if t == nil then
   m_simpleTV.OSD.ShowMessage("Filmon: json decode error"  ,255,10)
   return
end

if t.streams == nil then
 --  m_simpleTV.OSD.ShowMessage("Filmon:  stream not found"  ,255,10)
     m_simpleTV.Control.ExecuteAction(63)
   return
end

--local retAdr = t.streams[1].url
--if retAdr == nil then retAdr = t.streams[2].url
local retAdr = t.streams[2].url
      if retAdr == nil then
         m_simpleTV.OSD.ShowMessage("Error Filmon: stream not found"  ,255,10)
         return
      end
--end
retAdr = retAdr:gsub('%.low','%.high')
--debug_in_file(retAdr .. '\n')

m_simpleTV.Control.CurrentAdress = retAdr

