--script for dittotv.com (03/11/2015)

 require('jsdecode')

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, '^http://www%.dittotv%.com/livetv/' ) 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,5000,0)
  --INTERNET_OPTION_RECEIVE_TIMEOUT
  m_simpleTV.WinInet.SetOptionInt(session,6,8000,0)
-------------------------------------------
 local function FindKey (str)
   if not string.match(str,'class="livetv%-url%-val') then return false end
     return true 
 end
-------------------------------------------
 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
  answer = string.gsub(answer,'&amp;','&')
--debug_in_file(answer .. "\n\n")

 local header =  findpattern( answer,'<title>(.-)</title>',1,7,8)
 if header==nil then header=inAdr end
 if m_simpleTV.Control.CurrentTitle ~= nil then m_simpleTV.Control.CurrentTitle=header end

local key
 for w in string.gmatch(answer,'<input type="hidden"(.-)<') do
    if w == nil then break end
    if FindKey(w) then 
        key = findpattern (w,'value="(.-)"',1,7,1)
 	if key == nil then 
 	  m_simpleTV.OSD.ShowMessage("DittoTV error - key not found",255,5)
 	   return 
 	end
    end
 end
--debug_in_file(key .. '\n')

  local str = findpattern (answer,'"file":"(.-)"',1,8,1)
	if str == nil then 
	  m_simpleTV.OSD.ShowMessage("DittoTV error - stream not found",255,5)
	   return 
	end
 
--debug_in_file(key .. '  ' .. str .. '\n')
   
 rc,answer=m_simpleTV.WinInet.Get(session,'http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/aes.js')  
 m_simpleTV.WinInet.Close(session)
  
 local prescr = answer .. 
'var y=CryptoJS.AES.decrypt({ciphertext:CryptoJS.enc.Base64.parse("' .. str ..'")},CryptoJS.enc.Base64.parse("' .. key .. '"),{iv:CryptoJS.enc.Hex.parse("00000000000000000000000000000000")});var adr=y.toString(CryptoJS.enc.Utf8);'

 local retAdr = jsdecode.DoDecode('adr',false,prescr,0)
 if retAdr == nil then return end

 retAdr = string.gsub(retAdr,'&amp;','&')
 --debug_in_file(retAdr .. '\n') 

 m_simpleTV.Control.CurrentAdress = retAdr .. '$OPT:http-user-agent=Opera/9.80 (Windows NT 6.1; U; ru) Presto/2.9.168 Version/11.52'
