--script for rutracker.org (22/04/2013)

local res, login, password, header = xpcall(
  function()
   require('pm')
   -- получаем логин, пароль, заголовок браузера
   return pm.GetPassword('rutracker')
  end, err
)

if login == nil then login = '' end
if password == nil then password = '' end 
----------------------------------------
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, 'rutracker%.org/forum/' ) then return end

if login =='' or password=='' or login ==nil or password==nil then
	m_simpleTV.OSD.ShowMessage("rutracker.org - Login and Password is required",255,10)
 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,3000,0)
  --INTERNET_OPTION_RECEIVE_TIMEOUT
  m_simpleTV.WinInet.SetOptionInt(session,6,5000,0)


host = 'http://login.rutracker.org/forum/login.php'
body = 'login_username=' .. login .. '&login_password=' .. password .. '&login=%C2%F5%EE%E4'

header = 
'Host: login.rutracker.org\n' ..
'Accept-Language: ru-RU,ru;q=0.9,en;q=0.8\n' ..
'Referer: ' .. inAdr .. '\n' ..
'Accept: text/html, application/xml;q=0.9, application/xhtml+xml, image/png, image/webp, image/jpeg, image/gif, image/x-xbitmap, */*;q=0.1\n' ..
'Content-Type: application/x-www-form-urlencoded'

local rc,answer=m_simpleTV.WinInet.Post(session,host,nil,header,body)

 if rc~=200 then
	   m_simpleTV.WinInet.Close(session)
	  m_simpleTV.OSD.ShowMessage("Connection error - " .. rc ,255,10)
	   return
 end
--debug_in_file(answer.. "\n\n")
local t = findpattern(inAdr,'%?(.+)',1,1,0)

 if t==nil then return end

 local tmpName = m_simpleTV.Common.GetTmpName()
 if tmpName==nil then 
        return 
 end 
  
host = 'http://dl.rutracker.org/forum/dl.php?' .. t
--debug_in_file(host.. "\n\n")
body = ''
header = 
--'Host: dl.rutracker.org\n' ..
'Accept-Language: ru-RU,ru;q=0.9,en;q=0.8\n' ..
'Referer: ' .. inAdr .. '\n' ..
'Accept: text/html, application/xml;q=0.9, application/xhtml+xml, image/png, image/webp, image/jpeg, image/gif, image/x-xbitmap, */*;q=0.1\n' 

 rc,answer=m_simpleTV.WinInet.Post(session,host,nil,header,body,tmpName)

 if rc~=200 then
	   m_simpleTV.WinInet.Close(session)
	   m_simpleTV.OSD.ShowMessage("Connection error - " .. rc ,255,10)
	   os.remove(tmpName)
	   return
 end
 
local retAdr = 'torrent://' .. tmpName

--debug_in_file(retAdr.. "\n\n")

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