-- script for cinema-hd.ru (12/12/2013)
require 'json'
require 'vkcore'
require 'moonwalkcore'

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://cinema%-hd%.ru') then return end

function GetMailFullAdr(session, Adr)
	if not string.match(Adr, 'my%.mail%.ru') then return Adr end
	local cookie = m_simpleTV.WinInet.GetCookies(session, Adr, '')
	if cookie == nil then return Adr end
	return  Adr .. '$OPT:http-referrer=\r\nCookie: ' .. cookie
end

function RuStr(Str, isFrom)
  if Str == nil then return end
  if isFrom == true then
   return m_simpleTV.Common.string_fromUTF8(Str, 1251)
  else
    return m_simpleTV.Common.string_toUTF8(Str, 1251)
  end
end

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

--local session = m_simpleTV.WinInet.New("Mozilla/5.0 (Windows NT 5.1; rv:26.0) Gecko/20100101 Firefox/26.0")
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, 7000, 0)
--INTERNET_OPTION_RECEIVE_TIMEOUT
m_simpleTV.WinInet.SetOptionInt(session, 6, 7000, 0)

local url = 'cinema-hd.ru'
local index = findpattern(inAdr, 'cinema%-hd%.ru/(.*)', 1, 13, 0)
if index == nil then
	m_simpleTV.WinInet.Close(session)
	return
end

local rc, answer = m_simpleTV.WinInet.Get(session, url, index)
if rc ~= 200 then
	m_simpleTV.WinInet.Close(session)
	return
end

answer = RuStr(answer, true)
--debug_in_file(answer, 'C:\\_TEMP\\debug_.txt', true)
--<title>Паршивые овцы (2010) смотреть онлайн в хорошем качестве HD 720p, Паршивые овцы (2010)</title>
local header = findpattern(answer, '<title>(.-)</title>', 1, 7, 8)
if header == nil then
	header = 'Выберите серию'
else
	local str = findpattern(header, '^(.-)%)', 1, 0, 0)
	if str ~= nil then header = str end
end
header = string.gsub(header, '&quot;', '"')
if m_simpleTV.Control.CurrentTitle ~= nil then m_simpleTV.Control.CurrentTitle = header end
local content = findpattern(answer, '<div class="message">(.-)</section>', 1, 0, 0)
--debug_in_file(content, 'C:\\_TEMP\\debug_.txt', true)
if content == nil then 
	m_simpleTV.OSD.ShowMessage_UTF8(RuStr("Блок видео не найден."), 255, 10)
	return
end
local c = '"'
local retAdr = string.match(content, '<iframe.-src="(.-)"', 1)
if retAdr == nil then
	c = "'"
	retAdr = string.match(content, "<iframe.-src='(.-)'", 1)
end
if retAdr == nil then 
	m_simpleTV.OSD.ShowMessage_UTF8(RuStr("Ошибка поиска"), 255, 10)
	return
end
--debug_in_file(retAdr .. '\n\n', 'C:\\_TEMP\\debug_.txt', true)
local t, i = {}, 1
local const = '<strong>(.-)</strong></span></span><br /><iframe.-src=' .. c .. '(.-)' .. c
--debug_in_file(const .. '\n\n', 'C:\\_TEMP\\debug_.txt', true)
for Name, Adr in string.gmatch(content, const) do
	--debug_in_file(Name .. '\n' .. Adr .. '\n\n', 'C:\\_TEMP\\debug_.txt')
	t[i]         = {}
	t[i].Id      = i
	if Name ~= nil then
		t[i].Name = Name
	else
		t[i].Name    = 'Cерия ' .. i
	end
	t[i].Adress  = Adr
	i = i + 1
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
else
	if t[1] ~= nil then retAdr = t[1].Adress end
end

--http://moonwalk.cc/serial/74cb86e3248b94daa377e990459b47f2/iframe?season=1
--http://moonwalk.cc/serial/74cb86e3248b94daa377e990459b47f2/iframe?season=1&episode=1
--http://moonwalk.cc/video/199df207c583edad/iframe
if string.match(retAdr, 'moonwalk%.cc') then
	if string.match(retAdr, 'moonwalk%.cc/serial') then
		rc, answer = m_simpleTV.WinInet.Get(session, retAdr)
		if rc ~= 200 then
			m_simpleTV.WinInet.Close(session)
			return
		end
		answer = RuStr(answer, true)
		--debug_in_file(answer, 'C:\\_TEMP\\debug_.txt', true)
		content = findpattern(answer, '<select id="episode"(.-)</select>', 1, 0, 0)
		if content == nil then 
			m_simpleTV.OSD.ShowMessage_UTF8(RuStr("Блок видео не найден."), 255, 10)
			return
		end
		t, i = {}, 1
		for Num in string.gmatch(content, '>Серия (.-)</option>') do
			t[i]         = {}
			t[i].Id      = i
			t[i].Name    = 'Cерия ' .. Num
			t[i].Adress  = retAdr .. '&episode=' .. i
			i = i + 1
		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
			header = header .. ' - ' .. t[id].Name
		else
			retAdr = t[1].Adress
			header = header .. ' - ' .. t[1].Name
		end
		if m_simpleTV.Control.CurrentTitle ~= nil then m_simpleTV.Control.CurrentTitle = header end
		--debug_in_file(retAdr, 'C:\\_TEMP\\debug_.txt', true)
	end
	retAdr = moonwalkcore.MoonwalkGetAddress(retAdr)
	if retAdr == nil then m_simpleTV.OSD.ShowMessage_UTF8(RuStr("Ошибка: видео не найдено."), 255, 5) return end
	--debug_in_file(retAdr .. '\n', 'C:\\_TEMP\\debug.txt')
	m_simpleTV.Control.CurrentAdress = retAdr
	return
end

--http://moevideo.net/framevideo/32441.31baaa211a78783a996b648345ff?width=610&height=370
if string.match(retAdr, 'moevideo%.net') then
	rc, answer = m_simpleTV.WinInet.Get(session, retAdr)
	if rc ~= 200 then
		m_simpleTV.WinInet.Close(session)
		return
	end
	--debug_in_file(answer .. '\n', 'C:\\_TEMP\\debug_.txt', true)
	--flashvars="file=32441.31baaa211a78783a996b648345ff&amp;d=videochart.net"
	local file, d = string.match(answer, 'flashvars="file=(.-)&amp;d=(.-)"')
	if file == nil then m_simpleTV.OSD.ShowMessage_UTF8(RuStr("Ошибка: видео не найдено."), 255, 5) return end
	retAdr = 'http://' .. d .. '/framevideo/' .. file
	m_simpleTV.Control.CurrentAdress = retAdr
	return
end

------------------------------------------------------------------------------------------------------------------
do return end



--http://online-cinema.biz/stream/get_player/16?s=2
--http://online-cinema.biz/stream/get_player/132
--http://online-cinema.biz/stream/get_trailer/1/16
--debug_in_file(retAdr .. '\n', 'C:\\_TEMP\\debug_.txt')
rc, answer = m_simpleTV.WinInet.Get(session, retAdr)
if rc ~= 200 then
	m_simpleTV.WinInet.Close(session)
	return
end
answer = m_simpleTV.Common.string_fromUTF8(answer)
--debug_in_file(answer .. '\n', 'C:\\_TEMP\\debug_.txt', true)
local content = string.match(answer, 'Серия: <select onchange="getPlayer%(this%)">(.-)</select>')
t, i = {}, 1
if content ~= nil then
	debug_in_file(content .. '\n', 'C:\\_TEMP\\debug.txt', true)
	for Adr, Num in string.gmatch(content, '<option value="(.-)".->(%d-)</option>') do
		debug_in_file(Num .. '\n' .. Adr .. '\n\n', 'C:\\_TEMP\\debug.txt')
		t[i]         = {}
		t[i].Id      = i
		t[i].Name    = 'Cерия ' .. Num
		t[i].Adress  = Adr
		i = i + 1
	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
	else
		retAdr = t[1].Adress
	end
	if retAdr ~= nil then
		rc, answer = m_simpleTV.WinInet.Get(session, retAdr)
		if rc ~= 200 then
			m_simpleTV.WinInet.Close(session)
			return
		end
	end
end

t, i = {}, 1
retAdr = string.match(answer, '<param name="flashvars" value="st=.-&file=(.-)"')
if retAdr == nil then
	content = string.match(answer, '<param name="flashvars" value="uid=.-&amp;host=(.-)"')
	--debug_in_file(content .. '\n\n', 'C:\\_TEMP\\debug.txt', true)
	if content == nil then
		m_simpleTV.OSD.ShowMessage("Ошибка - видео недоступно для воспроизведения", 255, 10)
		return
	end
	for Quality, Adr in string.gmatch(content, ';url(%d-)=(.-)&amp') do
		--debug_in_file(Quality .. '\n' .. Adr .. '\n\n', 'C:\\_TEMP\\debug.txt')
		t[i]         = {}
		t[i].Id      = i
		t[i].Name    = Quality
		t[i].Adress  = Adr
		i = i + 1
	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
	else
		retAdr = t[1].Adress
	end
end
if retAdr ~= nil then
	--debug_in_file(retAdr .. '\n', 'C:\\_TEMP\\debug.txt', true)
	m_simpleTV.Control.CurrentAdress = retAdr
	return
end

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

--OLD---------------------------------------------------------------------------------------------------------------
tmp = string.match(answer, '"metadataUrl":"(.-)"')
if tmp ~= nil then
	rc, answer = m_simpleTV.WinInet.Get(session, tmp)
	if rc ~= 200 then
		m_simpleTV.WinInet.Close(session)
		return
	end
	local t = json.decode(answer)
	if t == nil then
		m_simpleTV.OSD.ShowMessage("Error - video is not available for playback", 255, 10)
		return
	end
	local a, j = {}, 1
	if t.videos['sd'] ~= nil then
		a[j]         = {}
		a[j].Id      = j
		a[j].Name    = 'SD - качество'
		a[j].Adress  = GetMailFullAdr(session, unescape(t.videos['sd']))
		j = j + 1
	end
	if t.videos['hd'] ~= nil then
		a[j]         = {}
		a[j].Id      = j
		a[j].Name    = 'HD - качество'
		a[j].Adress  = GetMailFullAdr(session, unescape(t.videos['hd']))
		j = j + 1
	end
	if j > 2 then
		local _, id = m_simpleTV.OSD.ShowSelect(header, 0, a, 0, 1)
		if id == nil then id = 1 end
		retAdr = a[id].Adress
	else
		retAdr = a[1].Adress
	end
	--debug_in_file(retAdr .. '\n', 'C:\\debug.txt', true)
end
m_simpleTV.WinInet.Close(session)
--debug_in_file(answer .. '\n', 'C:\\_TEMP\\debug.txt', true)
-----------------------------------------------------------------------------------------------------------------------------------
if string.match(retAdr, 'serpens%.nl') or string.match(retAdr, 'moonwalk%.cc') then
	local content = findpattern(answer, 'select id="episode" (.-)</div>', 1, 13, 1)
	t, i = {}, 1
	for _, w in string.gmatch(content, '<option.-value="(%d+)">(.-)</option>' ) do
		t[i]         = {}
		t[i].Id      = i
		t[i].Name    = m_simpleTV.Common.string_fromUTF8(w)
		t[i].Adress  = retAdr .. '&episode=' .. i
		i = i + 1
	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
	else
		retAdr = t[1].Adress
	end
	retAdr = moonwalkcore.MoonwalkGetAddress(retAdr)
	--debug_in_file(retAdr .. '\n', 'C:\\_TEMP\\debug.txt', true)
	if retAdr == nil then m_simpleTV.OSD.ShowMessage("Ошибка: видео не найдено.", 255, 5) return end
end
-----------------------------------------------------------------------------------------------------------------------------------

if string.match(retAdr, 'vk%.com') then
	retAdr = vkcore.vk_getadress(retAdr)
	if retAdr == nil then m_simpleTV.OSD.ShowMessage("Ошибка: видео не найдено.", 255, 5) return end
	--debug_in_file(retAdr .. '\n', 'C:\\debug.txt')
end
-----------------------------------------------------------------------------------------------------------------------------------
--debug_in_file(retAdr .. '\n')
m_simpleTV.Control.CurrentAdress = retAdr
