--script for lostfilm.tv (30/11/2014)

if m_simpleTV.Control.ChangeAdress ~= 'No' then return end
local inAdr = m_simpleTV.Control.CurrentAdress
if inAdr == nil then return end
--https://www.lostfilm.tv/nrdr.php?c=36&s=2&e=99
--http://www.lostfilm.tv/browse.php?cat=36
--http://www.lostfilm.tv/nrdr.php?c=36&s=2&e=2
if string.match(inAdr, 'http://tracktor%.in') then
	m_simpleTV.Control.CurrentAdress = 'torrent://' .. inAdr
	return
end
if not string.match(inAdr, 'www%.lostfilm%.tv') then return end

local res, login, password, head = xpcall(
	function()
		require('pm')
		-- получаем логин, пароль, заголовок браузера
		return pm.GetPassword('lostfilm')
	end, err
)
if (login == nil) or (password == nil) then
	Message("Lostfilm.tv - требуется ввести логин и пароль в PM")
	return
end

function Message(text, color)
	if text == nil then return end
	if color == nil then color = 255 end
	--text = m_simpleTV.Common.string_fromUTF8(text)
	m_simpleTV.OSD.ShowMessage(text, color, 10)
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
	Message("Не удалось создать сессию.")
	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)
m_simpleTV.WinInet.SetOpenRequestFlags(session, 0)
--РЕГИСТРАЦИЯ-----------------------------------------------------------------------------------------------------
local host = 'http://login1.bogi.ru/login.php?referer=https%3A%2F%2Fwww.lostfilm.tv%2F'
local body = 'login=' .. login .. '&password=' .. password .. '&module=1&target=http://lostfilm.tv%2F&repage=user&act=login'
local header =
	'Host: login1.bogi.ru\n' ..
	'Accept-Language: ru-RU,ru;q=0.9,en;q=0.8\n' ..
	'Referer: http://login1.bogi.ru/login.php\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 proxy = m_simpleTV.User.AnonymousProxy
local doc = m_simpleTV.User.AnonymousDocument
--local proxy = 'fast.proxy.yt'
--local doc = '/includes/process.php?action=update'
--Анонимный прокси-----------------------------------------
if (proxy ~= nil) and (doc ~= nil) then
	if proxy == 'fast.proxy.yt' then
		host = 'http://' .. proxy .. '/browse.php?u=http://login1.bogi.ru/login.php?referer=https%3A%2F%2Fwww.lostfilm.tv%2F'
	elseif proxy == 'www.proxyplus.ru' then
		host = 'http://' .. proxy .. doc .. '?q=http://login1.bogi.ru/login.php?referer=https%3A%2F%2Fwww.lostfilm.tv%2F'
	end
	header =
		'Host: ' .. proxy .. '\n' ..
		'Accept-Language: ru-RU,ru;q=0.9,en;q=0.8\n' ..
		'Referer: http://' .. proxy .. doc .. '\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'
end
local rc, answer = m_simpleTV.WinInet.Post(session, host, nil, header, body)
if rc ~= 200 then
	--debug_in_file(answer .. '\n\n\n', 'C:\\debug.txt', true)
	m_simpleTV.WinInet.Close(session)
	Message("1. Ошибка соединения - " .. rc)
	return
end
debug_in_file(answer .. '\n\n\n', 'C:\\lostfilm.txt', true)
--do return end
m_simpleTV.Control.ChangeAdress = 'Yes'
m_simpleTV.Control.CurrentAdress = ''
local iehack, sid, uid, first, last, nick, ava_small, ava_medium, ava_big, sex, transfer, email, sig
local content = findpattern(answer, 'name="b_form"(.-)</form>', 13, 7, 1) --nil
if content == nil then content = answer end
answer = content
--debug_in_file(answer .. '\n\n\n', 'C:\\lostfilm.txt', true)
action =  findpattern(answer,'action="(.-)"', 1, 8, 1)
iehack = findpattern(answer, 'name="iehack" type="hidden" value="(.-)"', 1, 35, 1)
sid = findpattern(answer, 'name="sid" value="(.-)"', 1, 18, 1)
uid = findpattern(answer, 'name="uid" value="(.-)"', 1, 18, 1)
first = findpattern(answer, 'name="first" value="(.-)"', 1, 20, 1)
last = findpattern(answer, 'name="last" value="(.-)"', 1, 19, 1)
nick = findpattern(answer, 'name="nick" value="(.-)"', 1, 19, 1)
ava_small = findpattern(answer, 'name="ava_small" value="(.-)"', 1, 24, 1)
ava_medium = findpattern(answer, 'name="ava_medium" value="(.-)"', 1, 25, 1)
ava_big = findpattern(answer, 'name="ava_big" value="(.-)"', 1, 22, 1)
sex = findpattern(answer, 'name="sex" value="(.-)"', 1, 18, 1)
transfer = findpattern(answer, 'name="transfer" value="(.-)"', 1, 23, 1)
email = findpattern(answer, 'name="email" value="(.-)"', 1, 20, 1)
sig = findpattern(answer, 'name="sig" value="(.-)"', 1, 18, 1)

body = 'iehack=' .. escape(iehack) .. '&sid=' .. sid .. '&uid=' .. uid .. '&first=' .. first .. '&last=' .. last .. '&nick=' .. nick .. '&ava_small=' .. escape(ava_small) .. '&ava_medium=' .. escape(ava_medium) .. '&ava_big=' .. escape(ava_big) .. '&sex=' .. sex .. '&transfer=' .. transfer .. '&email=' .. escape(email) .. '&sig=' .. sig
header = 
	"Host: www.lostfilm.tv\n" ..
	"Origin: http://login1.bogi.ru\n" ..
	"Accept-Language: ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4,bg;q=0.2,fr;q=0.2\n" ..
	"Referer: " .. host .. "\n" ..
	"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\n" ..
	"Content-Type: application/x-www-form-urlencoded"
if (proxy ~= nil) and (doc ~= nil) then
	header = 
		'Host: ' .. proxy .. '\n' ..
		"Origin: http://login1.bogi.ru\n" ..
		'Accept-Language: ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4,bg;q=0.2,fr;q=0.2\n' ..
		'Referer: ' .. host .. '\n' ..
		'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\n' ..
		'Content-Type: application/x-www-form-urlencoded'
	if proxy == 'fast.proxy.yt' then
		host = 'http://' .. proxy .. action
	elseif proxy == 'www.proxyplus.ru' then
	
	end
else
	host = action
	if string.match(action, '^//') then host = 'http:' .. host end
	--m_simpleTV.WinInet.SetOpenRequestFlags(session, 0x00800000 + 0x00002000 + 0x00001000)
end
rc, answer = m_simpleTV.WinInet.Post(session, host, nil, header, body)
if rc ~= 200 then
	m_simpleTV.WinInet.Close(session)
	Message("2. Ошибка соединения - " .. rc)
	return
end
--РЕГИСТРАЦИЯ-----------------------------------------------------------------------------------------------------

--debug_in_file(answer .. '\n', 'C:\\lostfilm.txt', true)
--do return end

local t, i, retAdr = {}, 1, inAdr
local sezon, seriya = 0, 99
if string.match(retAdr, 'www%.lostfilm%.tv/discuss%.php') then
	sezon = tonumber(string.match(retAdr, '&s=(%d+)&'))
	seriya = tonumber(string.match(retAdr, '&e=(%d+)$'))
	if seriya == nil then seriya = 99 end
	if seriya == 99 then
		retAdr = string.match(retAdr, '^(.-)&s=')
		retAdr = string.gsub(retAdr, 'discuss%.php', 'browse%.php')
	else
		retAdr = string.gsub(retAdr, 'discuss%.php%?cat=', 'nrdr%.php%?c=')
	end
	--debug_in_file(retAdr, 'C:\\debug.txt', true)
end

retAdr = string.gsub(retAdr, 'https://', 'http://')
--debug_in_file(retAdr, 'C:\\lostfilm.txt', true)
--do return end

if string.match(retAdr, 'www%.lostfilm%.tv/browse%.php') then
	local cat = string.match(retAdr, 'cat=(%d+)')
	if (proxy ~= nil) and (doc ~= nil) then
		retAdr = string.gsub(retAdr, ':', '%%3A')
		retAdr = string.gsub(retAdr, '/', '%%2F')
		retAdr = string.gsub(retAdr, '?', '%%3F')
		retAdr = string.gsub(retAdr, '=', '%%3D')
		retAdr = string.gsub(retAdr, '&', '%%26')
		if proxy == 'fast.proxy.yt' then
			retAdr = 'http://' .. proxy .. '/browse.php?u=' .. retAdr .. '&b=4'
		elseif proxy == 'www.proxyplus.ru' then
			retAdr = 'http://' .. proxy .. doc .. '?q=' .. retAdr .. '&hl=2e5'
		end
		rc, answer = m_simpleTV.WinInet.Post(session, retAdr)
	else
		--retAdr = string.gsub(retAdr, 'http://', 'https://')
		rc, answer = m_simpleTV.WinInet.Get(session, retAdr)
	end
	--debug_in_file(answer, 'C:\\lostfilm.txt', true)
	if rc ~= 200 then
		m_simpleTV.WinInet.Close(session)
		Message("3. Ошибка соединения - " .. rc)
		return
	end
	--debug_in_file(answer, 'C:\\_TEMP\\lostfilm.txt', true)
	debug_in_file('', 'C:\\_TEMP\\lostfilm.txt', true)
	header = string.match(answer, '<h1>(.-)</h1><br />')
	if header ~= nil then header = string.gsub(header, '&quot;', '"') end
	m_simpleTV.Control.CurrentTitle = header
	
	local temp = 'http://www.lostfilm.tv/nrdr.php?c=%s&s=%s&e=%s'
	
	for w1, w2 in string.gmatch(answer, '<td class="t_episode_title" onClick="ShowAllReleases%((.-)%)"(.-)</td>') do
		if w1 == nil then break end
		local c, s, e = string.match(w1, "'(.-)','(.-)','(.-)'")
		local adr = string.format(temp, c, s, e)
		local name = string.gsub('<' .. w2, '%b\<\>', '')
		if e ~= '99' then name = name .. ' - ' .. s .. ' сезон ' .. e .. ' серия' end
		t[i] = {}
		t[i].Id      = i
		t[i].Name    = name
		t[i].Adress  = adr
		i = i + 1
		debug_in_file(w1 .. '\n\n' .. w2 .. '\n\n', 'C:\\_TEMP\\lostfilm.txt')
	end

	if t[1] ~= nil then retAdr = t[1].Adress end
	if t[2] ~= nil then
		local _, id = m_simpleTV.OSD.ShowSelect(header, 0, t, 0, 1)
		if id == nil then id = 1 end
		retAdr = t[id].Adress
	end
	if retAdr == nil then
		m_simpleTV.WinInet.Close(session)
		Message("Видео не найдено.")
		return
	end
	--http://www.lostfilm.tv/nrdr.php?c=36&s=4&e=99
end

--retAdr = string.gsub(retAdr, 'http://', 'https://')
--m_simpleTV.WinInet.SetOpenRequestFlags(session, 0x00800000 + 0x00002000 + 0x00001000)

--debug_in_file(retAdr, 'C:\\lostfilm.txt', true)
--do return end

rc, answer = m_simpleTV.WinInet.Get(session, retAdr)
if rc ~= 200 then
	m_simpleTV.WinInet.Close(session)
	Message("4. Ошибка соединения - " .. rc)
	return
end
--debug_in_file(answer, 'C:\\debug.txt', true)
local const = '<span style="(.-)">Найдено 0 файла</span>'
content = findpattern(answer, const, 1, 0, 0)
if content ~= nil then 
	m_simpleTV.WinInet.Close(session)
	Message("Файлов не найдено.")
	return
end
header = string.match(answer, '<span class="h1">(.-)</span><br />')
if header ~= nil then header = string.gsub(header, '&quot;', '"') end
m_simpleTV.Control.CurrentTitle = header
--debug_in_file(header, 'C:\\debug.txt', true)
t, i, retAdr = {}, 1, ''
for w in string.gmatch(answer, '<table width="100%%" border="0">(.-)</table>') do
	--Видео: HDTV-Rip. Размер: 2.74 ГБ.<br />
	local name = findpattern(w, 'Видео: (.-)<br />', 1, 7, 6)
	if name == nil then break end
	local address = findpattern(w, '<a href="(.-)"', 1, 9, 1)
	if address == nil then break end
	--[[
	if (proxy ~= nil) and (doc ~= nil) then
		address = string.match(address, 'index%.php%?q=(.+)')
		address = unescape(address)
	end
	]]
	t[i] = {}
	t[i].Id      = i
	t[i].Name    = name
	t[i].Adress  = address
	--debug_in_file(t[i].Name .. '	' .. t[i].Adress .. '\n\n', 'C:\\_TEMP\\debug.txt')
	i = i + 1
end
if i > 1 then retAdr = t[1].Adress end
if i > 2 then
	local _, id = m_simpleTV.OSD.ShowSelect(header, 0, t, 0, 1)
	if id == nil then id = 1 end
	retAdr = t[id].Adress
end

if retAdr == nil then
	m_simpleTV.WinInet.Close(session)
	Message("Видео не найдено.")
	return
end

if string.match(retAdr, '^https://') then
	m_simpleTV.WinInet.SetOpenRequestFlags(session, 0x00800000 + 0x00002000 + 0x00001000)
else
	m_simpleTV.WinInet.SetOpenRequestFlags(session, 0)
end

local filename = m_simpleTV.Common.GetTmpName()
filename = string.match(filename, '(.+)\\(.-)$')
filename = filename .. '\\' .. 'torrent.tmp'
debug_in_file(retAdr, 'C:\\debug.txt', true)

if m_simpleTV.WinInet.GetFile(session, retAdr, nil, filename) == 0 then
	m_simpleTV.WinInet.Close(session)
	Message("Не удалось скачать торрент-файл\n" .. retAdr)
	return
end
m_simpleTV.WinInet.Close(session)

retAdr = 'torrent://' .. filename
--retAdr = 'torrent://' .. retAdr
debug_in_file(retAdr, 'C:\\debug.txt', true)
m_simpleTV.Control.CurrentAdress = retAdr