--megatv.lua

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, 'megatv%.cc') then return end

--set your login and password here
local res, login, password, head = xpcall(
	function()
		require('pm')
		-- получаем логин, пароль, заголовок браузера
		return pm.GetPassword('megatv')
	end, err
)
if (login == nil) or (password == nil) then
	Message("megatv.cc - требуется ввести логин и пароль в PM")
	--m_simpleTV.OSD.ShowMessage("Lostfilm.tv - требуется ввести логин и пароль в PM", 255, 10)
	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("Не удалось создать сессию.")
	--m_simpleTV.OSD.ShowMessage("Не удалось создать сессию.", 255, 10)
	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)
local host = 'http://megatv.cc/auth.php'
local body = 'email=' .. login .. '&password=' .. password .. '&enter=Войти'
local header =
	'Host: megatv.cc\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: http://megatv.cc/auth.php\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'
local rc, answer = m_simpleTV.WinInet.Post(session, host, nil, header, body)
if rc ~= 200 then
	m_simpleTV.WinInet.Close(session)
	Message("1. Ошибка соединения - " .. rc)
	return
end
m_simpleTV.Control.ChangeAdress = 'Yes'
--m_simpleTV.Control.CurrentAdress = ''
rc, answer = m_simpleTV.WinInet.Get(session, inAdr)
if rc ~= 200 then
	m_simpleTV.WinInet.Close(session)
	Message("2. Ошибка соединения - " .. rc)
	return
end
--debug_in_file(answer, 'C:\\_TEMP\\debug.txt', true)
m_simpleTV.WinInet.Close(session)

local retAdr = findpattern(answer, 'this%.loadPlayer%("(.-)"', 1, 17, 1)
if retAdr == nil then
	retAdr = findpattern(answer, 'this%.loadTorrent%("(.-)"', 1, 18, 1)
	if retAdr == nil then return end
	local tmpName = m_simpleTV.Common.DownloadFileInTmp (retAdr, 'torrent.acestream',false)
	m_simpleTV.Control.CurrentAdress = 'torrent://' .. tmpName
	return
end
if retAdr == nil then return end
--debug_in_file(retAdr, 'C:\\_TEMP\\debug.txt', true)
m_simpleTV.Control.PlayAddress(retAdr)