--script for 4ip.tv.ru (11/09/2015)

require('json')

--dofile (m_simpleTV.MainScriptDir .. "user/tvplaylists/tvscr/filter.lua")
 local fhandle = io.open(m_simpleTV.MainScriptDir .. "user/tvplaylists/misc/filter.default")
 if fhandle == nil then return end
 local value = fhandle:read("*all")
 fhandle:close()


--download logo from 4ip.tv website 1 - yes 0 - no
--local downloadlogo = 0
--local filepath  = m_simpleTV.Common.GetMainPath (0)
--------------------------

   local UpdateID='4ip_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 "%4ip_%";'
   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,5000,0)
  --INTERNET_OPTION_RECEIVE_TIMEOUT
  m_simpleTV.WinInet.SetOptionInt(session,6,8000,0)
-------------------------------------------
local function trim(s)
  return (s:gsub("^%s*(.-)%s*$", "%1"))
end
-------------------------------------------------------
local function String2Upper(s)
  for i = 224, 255 do
    s = s:gsub(string.char(i), string.char(i - 32))
  end
  s = s:gsub(string.char(184), string.char(168))
  return s:upper()
end
-------------------------------------------------------
local function GetFilterTable(value)
     local FilterTable = {}
     local i=1
     for w in string.gmatch(value,'"(.-)"') do 
         if w == nil then break end
         w = trim(w)
         local CurrenName,NewName,GroupName,EpgSource = string.match(w,'(.-),(.-),(.-),(.-)$')
         if CurrenName == nil or NewName == nil or GroupName == nil or EpgSource == nil then break end
   --debug_in_file(CurrenName .. ' ,' .. NewName .. ' ,' .. GroupName .. ' ,' .. EpgSource .. '\n')
   
         FilterTable[i] = {}
         FilterTable[i][1] = CurrenName
         FilterTable[i][2] = NewName
         FilterTable[i][3] = GroupName
         FilterTable[i][4] = EpgSource
     
        i=i+1
     end
  return FilterTable
end

-----------------------------------------------------------------
local function FilterChannels(name,filter)

if filter == nil then filter = GetFilterTable(value) end

if filter == nil then return nil end

local group=''
local epgSource =''

name = m_simpleTV.Common.string_fromUTF8(name)

local upname = String2Upper(name)
upname = m_simpleTV.Common.string_toUTF8(upname)
--debug_in_file(upname .. '\n')

name = m_simpleTV.Common.string_toUTF8(name)

  for k,v in ipairs(filter) do
     if upname == v[1] then name = v[2] group = v[3] epgSource = v[4] end
  end
  return name,group,epgSource
end
-------------------------------------------------------

 m_simpleTV.OSD.ShowMessage("4ip.tv - start channels updating" ,0xFF00,10)

local head  = 
'Host: 4ip.tv\n' ..
'Accept-Language: ru-RU,ru;q=0.9,en;q=0.8\n' ..
'Referer: http://4ip.tv/\n' ..
'Accept: application/json, text/javascript, */*; q=0.01\n' ..
'X-Requested-With: XMLHttpRequest'

local url = 'http://4ip.tv/brad.php'
local rc,answer=m_simpleTV.WinInet.Get(session,url,nil,0,head)
--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

--debug_in_file(answer ..  '\n')
--answer = string.gsub(answer, "\\", "\\\")
answer = string.gsub( answer, '[\u]','\\u')
--debug_in_file(answer ..  '\n')
local t = json.decode(answer)
if t == nil or t.channels==nil then
   m_simpleTV.OSD.ShowMessage("Error 4ip.tv - playlist not found"  ,255,10)
   return
end

local tab={}
local i=1
local m3ustr = '#EXTM3U\n'
local name,grp,prg,logo

  while true do
    if t.channels[i] == nil then break end
    
    tab[i] = {}
    tab[i].Id   =  i --t.channels[i].description
    tab[i].Name = unescape1(t.channels[i].title)
    tab[i].Adress  = decode64(t.channels[i].stream ) 
    tab[i].Adress = decode64(tab[i].Adress)
    tab[i].Img = 'http://4ip.tv/' .. t.channels[i].logo
  --debug_in_file(tab[i].Name .. '\n' .. tab[i].Adress .. '\n')
   -- m3ustr = '#EXTINF:-1,4iptv:' .. tab[i].Name..'\n'..tab[i].Adress..'\n'

    name,grp = FilterChannels(tab[i].Name)
    if name == nil then name = tab[i].Name end
    if grp == nil or grp == '' then grp ='!No Group' end

    img = tab[i].Img
    adr = tab[i].Adress 

 --[[  
   if downloadlogo == 1 then
        local sqlstr = 'Select main.pict from main where main.pict like "%4iptv%";'
        local dTable = m_simpleTV.Database.GetTable(sqlstr)
        local sqlstr2 = 'Select extfilter.id from extfilter where extfilter.name="4ip.tv"'
        local dTable2 = m_simpleTV.Database.GetTable(sqlstr2)

        if (dTable == nil or dTable[1]==nil or dTable[1].pict==nil) and (dTable2 == nil or dTable2[1]==nil or dTable2[1].id==nil) then 
             rc = m_simpleTV.WinInet.GetFile(session, tab[i].Img  ,nil, filepath .. '4iptv' .. i .. '.png') 
             if rc == nil then 
        	   m_simpleTV.OSD.ShowMessage("4iptv error - can't save logo " .. tab[i].Img .. '\n' ,255,3)
             end
        end  

          m3ustr =  m3ustr .. '#EXTINF:-1 update-code="' .. UpdateID .. grp .. name .. '" group-title="' .. grp .. '" tvg-logo="..\\Channel\\logo\\4iptv' .. i .. '.png",' .. name .. '\n' .. tab[i].Adress .. '\n'

      elseif  downloadlogo ~= 1 then
         m3ustr =  m3ustr .. '#EXTINF:-1 update-code="' .. UpdateID .. grp .. name .. '" group-title="' .. grp .. '",' .. name .. '\n' .. tab[i].Adress .. '\n'
       
    end
]]

          if UseLocalLogo == '1' then    

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

           elseif UseLocalLogo ~= '1' then

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

         end

    i = i + 1
  end
--debug_infile(m3ustr)
--do return end
m_simpleTV.WinInet.Close(session)

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(m3ustr)
 tfile:close() 


  --опции  для загрузки плейлиста 
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 = '4ip.tv'
p.ExtFilterLogo =  '..\\Channel\\logo\\extFiltersLogo\\4ip.tv.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 = "4ip.tv - 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,0x37BEDF,3) 
  end