--script for stagevu.com (11.04.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, 'http://stagevu%.com/video' )  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,5000,0)

---------------------------------------------------------------------------------------
local function unescape_html(str)
  str = string.gsub( str, '&lt;', '<' )
  str = string.gsub( str, '&gt;', '>' )
  str = string.gsub( str, '&quot;', '"' )
  str = string.gsub( str, '&apos;', "'" )
  str = string.gsub( str, '&#(%d+);', function(n) return string.char(n) end )
  str = string.gsub( str, '&#x(%d+);', function(n) return string.char(tonumber(n,16)) end )
  str = string.gsub( str, '&amp;', '&' ) -- Be sure to do this after all others
  return str
end

inAdr = string.gsub(inAdr, 'https', 'http')

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

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

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

answer = findpattern(answer,'<embed type(.-)</embed>',1,0,0)

if answer == nil then 
	   m_simpleTV.OSD.ShowMessage("Stagevu script error - can't find video",255,10)
	   return
 end

local retAdr = findpattern(answer,'src="(.-)"',1,5,1)
if retAdr == nil then return end

m_simpleTV.Control.CurrentAdress = retAdr
