--script for rutor.org / alt.rutor.org / new-rutor.org /  (19/12/2013)

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

local inAdr = m_simpleTV.Control.CurrentAdress
local retAdr

if inAdr == nil then return end

if not string.match(inAdr, 'rutor%.org/torrent/') and not string.match(inAdr, 'rutor%.org/download/') then return end

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

if string.match(inAdr, 'rutor%.org/download/') then
	retAdr = 'torrent://' ..  inAdr
	m_simpleTV.Control.CurrentAdress = retAdr
	return
end
---------------------------------------------------------------------------

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, 3000, 0)
--INTERNET_OPTION_RECEIVE_TIMEOUT
m_simpleTV.WinInet.SetOptionInt(session, 6, 5000, 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

m_simpleTV.WinInet.Close(session)

answer = m_simpleTV.Common.string_fromUTF8(answer)

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

--debug_in_file(header .. '\n')

header = string.gsub(header, '&quot;', '"')
header = string.gsub(header, '&#039;', '`')

if m_simpleTV.Control.CurrentTitle ~= nil then m_simpleTV.Control.CurrentTitle = header end

--debug_in_file(m_simpleTV.Control.CurrentTitle .. '\n', nil, true)

local torAdr = findpattern(answer,'<div id="download">(.-)<br />', 1, 0, 0)

local site = string.match(inAdr, '(.-rutor%.org)/')
if torAdr ~= nil then
	torAdr = string.match(torAdr, '<a href="(/download/.-)">')
	--debug_in_file(torAdr .. '\n')
end

if torAdr == nil then  
	m_simpleTV.OSD.ShowMessage("Ошибка - не могу найти адрес торрента", 255, 10)
	return
else
	torAdr = site .. torAdr
end

retAdr = 'torrent://' .. torAdr
--debug_in_file(retAdr .. '\n', nil, true)
m_simpleTV.Control.CurrentAdress = retAdr