--script for https://www.arconai.tv (29/11/2015)

   local UpdateID='Arconai_TV01'
   local UseLocalLogo = nil

if UseLocalLogo == nil then
   local fhandle = io.open (m_simpleTV.MainScriptDir ..  "user/tvplaylists/tvmenu.ini")   
   if fhandle == nil then 
      UseLocalLogo = '1'
      return
   end
   local str = fhandle:read('*a')
   fhandle:close()

   UseLocalLogo = string.match(str,'UseLocalLogo=(%d);')
   if UseLocalLogo == nil then UseLocalLogo = 0 end
end

if UseLocalLogo == '1' then
   local sqlstr = 'Select main.id,main.pict from main where main.updateid like "%Arconai_%";'
   local dTable = m_simpleTV.Database.GetTable(sqlstr)
   if dTable ~= nil and dTable[1] ~= nil then
     for k, v in ipairs(dTable) do 
        --debug_in_file(v.id .. '  ' .. v.pict .. '\n')
        m_simpleTV.Database.ExecuteSql('DELETE FROM Main WHERE (Main.Id=' .. v.id .. ');',true) 
     end
   end
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 return end

  --INTERNET_OPTION_CONNECT_TIMEOUT
  m_simpleTV.WinInet.SetOptionInt(session,2,8000,0)
  --INTERNET_OPTION_RECEIVE_TIMEOUT
  m_simpleTV.WinInet.SetOptionInt(session,6,8000,0)
--INTERNET_FLAG_SECURE
m_simpleTV.WinInet.SetOpenRequestFlags(session, 0x00800000 + 0x00002000 + 0x00001000)
-------------------------------------------
-- convert numeric html entities to utf8
-- converts from stdin to stdout
-- example:  &#8364;    ->   €
 
local char = string.char
 
local function tail(n, k)
  local u, r=''
  for i=1,k do
    n,r = math.floor(n/0x40), n%0x40
    u = char(r+0x80) .. u
  end
  return u, n
end
 
local function to_utf8(a)
  local n, r, u = tonumber(a)
  if n<0x80 then                        -- 1 byte
    return char(n)
  elseif n<0x800 then                   -- 2 byte
    u, n = tail(n, 1)
    return char(n+0xc0) .. u
  elseif n<0x10000 then                 -- 3 byte
    u, n = tail(n, 2)
    return char(n+0xe0) .. u
  elseif n<0x200000 then                -- 4 byte
    u, n = tail(n, 3)
    return char(n+0xf0) .. u
  elseif n<0x4000000 then               -- 5 byte
    u, n = tail(n, 4)
    return char(n+0xf8) .. u
  else                                  -- 6 byte
    u, n = tail(n, 5)
    return char(n+0xfc) .. u
  end
end
 --[[
for line in io.lines() do
  out =  string.gsub(line, '&#(%d+);', to_utf8)
  print(out)
end
]]
  m_simpleTV.OSD.ShowMessage("ArconaiTV: start updating" ,0xFF00,10)
 
 local  tmpName = m_simpleTV.Common.GetTmpName()
 if tmpName == nil then return end 
 
  local tfile = io.open(tmpName,'w+')
  if tfile == nil then 
      os.remove(tmpName)
      return
  end
  
  tfile:write('#EXTM3U\n')
  tfile:close() 
 
 
 local url = 'https://www.arconai.tv'
 local rc,answer=m_simpleTV.WinInet.Get(session,url)
 m_simpleTV.WinInet.Close(session)
 
  if rc~=200 then
 	   m_simpleTV.WinInet.Close(session)
 	   m_simpleTV.OSD.ShowMessage("Connection error - " .. rc ,255,10)
 	   return
  end

 answer = string.gsub(answer,'[\r\n]+','')
--debug_in_file(answer ..  '\n')

 local content = findpattern (answer,'<div id="content" role="main">(.-)<footer id="footer">',1,1,0)
 if content == nil then content = '' end

 answer = findpattern (answer,'Channels(.-)Donate',1,0,0)
--debug_in_file(answer ..  '\n')
 if answer == nil then
    m_simpleTV.OSD.ShowMessage("ArconaiTV: script error"  ,255,10)
    return
 end

 local adr,name,img
 local m3ustr
 local grp --= 'ArconaiTV'

 local t={}
 local i=1
   for ww in string.gmatch(content,'<a(.-)</a>') do

      adr = findpattern (ww,'href="(.-)"',1,6,1)
      img = findpattern (ww,'src="(.-)"',1,5,1)
--debug_in_file(adr .. '  ' .. img .. '\n')
      if img == nil or adr == nil then break end
      t[i] = {}
      t[i][1] = adr
      t[i][2] = img

  i=i+1
   end

  local function GetImg(adr)
    img = ''
      for k, v in ipairs(t) do 
          if adr == v[1] then img = v[2] end
     end 
    return img
  end 

  local function CheckAdr(adr)
  if string.match(adr,'https://www.arconaitv.me/(.+)')  then return true end
    return false
  end 

 local channels = findpattern (answer,'Channels(.-)Cable',1,0,0)
 if channels == nil then return end

 for w in string.gmatch(channels,'<a(.-)</a>') do
	
	grp = 'Channels'
	adr = findpattern (w,'href="(.-)"',1,6,1)
	name = findpattern (w,'<span class="link_text">(.-)<',1,24,1)
	if adr == nil or name == nil then break end

        name =  string.gsub(name, '&#(%d+);', to_utf8)

--        adr = adr:gsub('www.','')
        img = GetImg(adr)
  if CheckAdr(adr) then
--debug_in_file(name .. '  ' ..  adr .. '  ' .. img .. '\n')

          if UseLocalLogo == '1' then    

              m3ustr = '#EXTINF:-1 update-code="' .. UpdateID .. grp .. name .. '" group-title="' .. grp .. '",' .. name .. '\n' .. adr .. '\n'

           elseif UseLocalLogo ~= '1' then

             m3ustr = '#EXTINF:-1 update-code="' .. UpdateID .. grp .. name .. '" group-title="' .. grp .. '" tvg-logo="' .. img .. '",' .. name .. '\n' .. adr .. '\n'

         end

        tfile = io.open(tmpName,'a+')
        tfile:write(m3ustr)
        tfile:close()
  end
end

--do return end
 local cable = findpattern (answer,'Cable(.-)Donate',1,0,0)
 if cable == nil then return end

 for w in string.gmatch(cable,'<a(.-)</a>') do

	grp = 'Cable TV'
	adr = findpattern (w,'href="(.-)"',1,6,1)
	name = findpattern (w,'<span class="link_text">(.-)<',1,24,1)
	if adr == nil or name == nil then break end

        name =  string.gsub(name, '&#(%d+);', to_utf8)

--        adr = adr:gsub('www.','')
        img = GetImg(adr)
--debug_in_file(name .. '  ' .. adr .. '  ' .. img .. '\n')
          if UseLocalLogo == '1' then    

              m3ustr = '#EXTINF:-1 update-code="' .. UpdateID .. grp .. name .. '" group-title="' .. grp .. '",' .. name .. '\n' .. adr .. '\n'

           elseif UseLocalLogo ~= '1' then

             m3ustr = '#EXTINF:-1 update-code="' .. UpdateID .. grp .. name .. '" group-title="' .. grp .. '" tvg-logo="' .. img .. '",' .. name .. '\n' .. adr .. '\n'

         end
      --  m3ustr = '#EXTINF:-1,ArconaiTV:' .. name ..'\n'.. adr ..'\n'
        tfile = io.open(tmpName,'a+')
        tfile:write(m3ustr)
        tfile:close()
end


  --опции  для загрузки плейлиста 
local p={}
p.TypeSourse = 1
p.DeleteBeforeLoad = 0
p.TypeSkip   = 1
p.TypeFind =   0
p.AutoSearch = 1
p.NumberM3U =  1
p.Find_Group = 1
p.TypeCoding = 1  --  -1-auto  0 - plane text  1- UTF8  2- unicode
p.BorpasFileFormat=1
p.AutoNumber = 0
p.ExtFilter = 'ArconaiTV'
p.ExtFilterLogo =  '..\\Channel\\logo\\extFiltersLogo\\arconaitv.png'   -- the logo of extended filter (from ver. 0.4.8 b9)
p.ExtFilterLogoForce = 0
p.UpdateID=UpdateID

local err,add,ref,names = m_simpleTV.Common.LoadPlayList (tmpName,p,0,true,false)
os.remove(tmpName)

if err==true then
     local mess = "ArconaiTV: channels updated (" .. add .. ")"
	 if add > 0 and add < 25 then 
	    names = string.gsub(names,'%$end','\n')
		mess = mess .. '\n' .. names
	 end
	 
	 m_simpleTV.OSD.ShowMessage(mess,0xFF00,5)
	 
end
