--script for youtube user uploads (12/03/2014)
-- open link http://www.youtube.com/user/Fletcher2008/videos
require('json')

if m_LinkToPlay.Control.ChangeAddress ~= 'No' then return end

local inAdr =  m_LinkToPlay.Control.CurrentAddress

if inAdr==nil then return end
--https://www.youtube.com/user/yalksne07/videos
if not string.match(inAdr, 'www%.youtube%.com/channel/(.+)/videos$') then return end

require ('youtubecore')

m_LinkToPlay.Control.ChangeAddress = 'Yes'
m_LinkToPlay.Control.CurrentAddress = ''

local function unescape_html(str)
  str = string.gsub( str, '&lt;', '<' )
  str = string.gsub( str, '&gt;', '>' )
  str = string.gsub( str, '&quot;', '"' )
  str = string.gsub( str, '&apos;', "'" )
  str = string.gsub( str, '&#(%d+);', function(n) return string.char(n) end )
  str = string.gsub( str, '&#x(%d+);', function(n) return string.char(tonumber(n,16)) end )
  str = string.gsub( str, '&amp;', '&' ) -- Be sure to do this after all others
  return str
end

local session = m_LinkToPlay.WinInet.New("Opera/9.80 (Windows NT 6.1; U; ru) Presto/2.9.168 Version/11.52")
if session == nil then return end

if string.match(inAdr, '^https://') then
	--INTERNET_FLAG_SECURE + INTERNET_FLAG_IGNORE_CERT_DATE_INVALID + INTERNET_FLAG_IGNORE_CERT_CN_INVALID
	m_LinkToPlay.WinInet.SetOpenRequestFlags(0x00800000 + 0x00002000 + 0x00001000)
end

local rc, answer = m_LinkToPlay.WinInet.Get(session, inAdr)
m_LinkToPlay.WinInet.SetOpenRequestFlags(0)
if rc ~= 200 then return end

answer = m_LinkToPlay.Common.string_fromUTF8(answer)
debug_in_file(answer .. '\n', nil, true)

local header = findpattern(answer, '<title>(.-)</title>', 1, 7, 8)
if header == nil then header = inAdr end
header = string.gsub(header, '&quot;', '"')
header = string.gsub(header, '&raquo;', '')
header = string.gsub(header, '&#39;', "'")
header = string.gsub(header, '&amp;', "&")

if m_LinkToPlay.Control.CurrentTitle ~= nil then m_LinkToPlay.Control.CurrentTitle = unescape_html(header) end

local i, t, retAdr = 1, {}, ''
local name, adr
for w in string.gmatch(answer, '<div class="yt%-lockup%-content">(.-)</h3>') do
	name = findpattern (w, 'title="(.-)"', 1, 7, 1)
	adr = findpattern (w, 'href="(.-)"', 1, 6, 1)
	if adr == nil or name == nil then break end
	t[i]         = {}
	t[i].Id      =  i
	t[i].Name    =  i .. '. ' .. unescape_html(name)
	t[i].Address = 'http://www.youtube.com' .. adr
	if retAdr == '' then retAdr = t[i].Address end
	i = i + 1
end

if i > 2 then 
	m_LinkToPlay.Taskbar.AddList(header, 0, t, 5000)
	return
end

retAdr, header = youtubecore.GetWatchAddress(retAdr, true)
if retAdr == nil then return end
if type(retAdr) == 'table' then
	local ret = m_LinkToPlay.Taskbar.AddList(header, 0, retAdr, 7000, -1)
else
	m_LinkToPlay.Control.CurrentAddress = retAdr
end