--script for m3u8 firstonetv.com (12/07/2015)
--open http://en.firstonetv.com/stream/uk/8
--open http://de.firstonetv.com/stream/de/15
--open http://en.firstonetv.com/stream/it/3

require('json')

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, 'firstonetv%.com/stream/' ) then return end

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

---------------------------------------------------------------------------

local session = m_simpleTV.WinInet.New("Mozilla/5.0 (Linux; U; Android 4.0.3; ko-kr; LG-L160L Build/IML74K) AppleWebkit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30")
if session == nil then return end

--INTERNET_OPTION_CONNECT_TIMEOUT
  m_simpleTV.WinInet.SetOptionInt(session,2,10000,0)
--INTERNET_OPTION_RECEIVE_TIMEOUT
  m_simpleTV.WinInet.SetOptionInt(session,6,10000,0)

local rc,answer=m_simpleTV.WinInet.Get(session,inAdr)

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

local chanid = ''
local url = ''

chanid = findpattern( answer,'abc%(def%(geh%(grm%(%b""',0,17,1)

if chanid == nil then chanid = findpattern( answer,'abc%(def%(geh%(grm%(lol%(%b""',0,21,1) end

if chanid == nil then
	   m_simpleTV.WinInet.Close(session)
	   m_simpleTV.OSD.ShowMessage("Channel ID error" ,255,10)
	   return
end

local i = 0
local endurl = ''
local urlid = chanid
local hash = ''
local url = ''

repeat

i=i+1
urlid = decode64(urlid)
urlid = m_simpleTV.Common.string_toUTF8(urlid)
local newurlid = unescape(urlid)
endurl = findpattern( newurlid,'eval%((.*)%)',1,0,0)
if endurl ~= nil then i = 11 else urlid = findpattern( newurlid,'%b""',0,1,1) end

--debug_in_file('URL' .. i .. ' = \n' .. newurlid .. '\n\n')

until i >= 11

url =  findpattern( endurl,'aHR0(.-)|',1,0,1)

 if url == nil then
    m_simpleTV.WinInet.Close(session)
    m_simpleTV.OSD.ShowMessage("m3u8 was not found" ,255,10)
    return
 end

sizeurl = math.fmod(string.len(url),4)

--debug_in_file('sizeurl = ' .. sizeurl .. '\n\n')

if sizeurl == 1 then url = url .. '===' end
if sizeurl == 2 then url = url .. '==' end
if sizeurl == 3 then url = url .. '=' end

url=decode64(url)

hash = findpattern( endurl,'TkhN(.-)|',1,0,1)

 if hash == nil then
    local retAdr = url
    --debug_in_file(retAdr .. '\n\n')

    m_simpleTV.WinInet.Close(session)
    m_simpleTV.Control.CurrentAdress = retAdr
    return
 end

sizehash = math.fmod(string.len(hash),4)

--debug_in_file('sizehash = ' .. sizehash .. '\n\n')

if sizehash == 1 then hash = hash .. '===' end
if sizehash == 2 then hash = hash .. '==' end
if sizehash == 3 then hash = hash .. '=' end

hash = decode64(hash)

local retAdr = url .. '?' .. hash
--debug_in_file(retAdr .. '\n\n')

m_simpleTV.WinInet.Close(session)
m_simpleTV.Control.CurrentAdress = retAdr
