--script for videomega.tv (03/12/2015)
--open links http://videomega.tv/?ref=RL2O9GGWD99DWGG9O2LR / http://videomega.tv/cdn.php?ref=057086115071121115049076098055055098076049115121071115086057&width=660&height=400

 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://videomega%.tv/%?ref=' ) and not string.match (inAdr,'^http://videomega%.tv/cdn%.php') 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 function GetVideomegaAdr(url)

            local head = 
            'Referer: ' .. inAdr .. '\n' .. 
            'Cookie:  hashopen4=1' ..
            'User-Agent: Opera/9.80 (Windows NT 6.1; U; ru) Presto/2.9.168 Version/11.52'
            
             local rc,answer=m_simpleTV.WinInet.Get(session,url,nil,0,head)
             m_simpleTV.WinInet.Close(session)
             if rc~=200 then
            	   m_simpleTV.WinInet.Close(session)
            	   m_simpleTV.OSD.ShowMessage("Connection error2 - " .. rc ,255,10)
            	   return
             end
            --debug_in_file(answer .. '\n')

      local retAdr = string.match(answer,'eval(.-)</script>')
      if retAdr == nil then return nil end

  return retAdr
end
----------------------------------------
local retAdr

if string.match (inAdr,'^http://videomega%.tv/cdn%.php') then
   retAdr = GetVideomegaAdr(inAdr)
   if retAdr == nil then  m_simpleTV.OSD.ShowMessage("VideoMega.TV script error",255,5) return end

 elseif string.match (inAdr,'^http://videomega%.tv/%?ref=') then
--http://videomega.tv/view.php?ref=RL2O9GGWD99DWGG9O2LR&width=100%&height=400
   local ref = findpattern( inAdr,'%?ref=(.+)',1,5,0)
   if ref == nil then return end
  
   local url = 'http://videomega.tv/view.php?ref=' .. ref .. '&width=100%&height=400'
  
   retAdr = GetVideomegaAdr(url)
   if retAdr == nil then  m_simpleTV.OSD.ShowMessage("VideoMega.TV script error",255,5) return end
end

 retAdr = jsdecode.DoDecode(retAdr,false)
 if retAdr == nil then return end

 retAdr = findpattern( retAdr,'src","(.-)"',1,6,1)
 if retAdr == nil then return end
--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'

