--script for tunein.com (10/11/2015)
--open link http://tunein.com/radio/Radio-Zvezda-956-s107214/
require "lfs"

--OSD Show Save menu  1 - yes 0 - no
local menu = 1
-----------------------

--Create TuneIn folder to save logo
local filepath  = m_simpleTV.Common.GetMainPath (0)
filepath = filepath .. 'RadioAddonLogo'
lfs.mkdir(filepath)
filepath = filepath .. '/TuneIn/'
lfs.mkdir(filepath)

require('json')

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://tunein%.com/radio/' ) then return end
--do return end
m_simpleTV.Control.ChangeAdress='Yes'
m_simpleTV.Control.CurrentAdress = ''
----------------------------------------------------------------
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,3000,0)
 --INTERNET_OPTION_RECEIVE_TIMEOUT
 m_simpleTV.WinInet.SetOptionInt(session,6,5000,0)
 --INTERNET_FLAG_NO_AUTO_REDIRECT 0x00200000
 m_simpleTV.WinInet.SetOpenRequestFlags(session,0x00200000)
---------------------------------------------------------------
local retAdr = ''
local header,filename
--------------------------------------------------
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
  str = string.gsub( str, '- Listen Online', '' )
  return str
end
---------------------------------------------------
local function GetRealAddress(retAdr)

   if string.match(retAdr,'radionomy') then

         m_simpleTV.Common.Wait(2000)
           local rc=m_simpleTV.WinInet.Get(session,retAdr)
     
          if rc~=302 then
         	   m_simpleTV.WinInet.Close(session)
         	   m_simpleTV.OSD.ShowMessage("Connection error - " .. rc ,255,10)
         	   return
          end
         
         local rawheader = m_simpleTV.WinInet.GetRawHeader(session)
          retAdr = findpattern(rawheader,'Location: (.-)\n',1,10,0)
                  if retAdr == nil then return nil end
    end
   return  retAdr
end
------------------------------------------------

local function GetTuneInAddress(inAdr,header,filename)
  
local rc,answer=m_simpleTV.WinInet.Get(session,inAdr)
--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 = m_simpleTV.Common.string_fromUTF8(answer)
--debug_in_file(answer .. "\n\n") 

header =  findpattern( answer,'<title>(.-)</title>',1,7,8)
if header==nil then header=inAdr end

header = unescape_html(header)
header = m_simpleTV.Common.string_toUTF8(header)

--if m_simpleTV.Control.CurrentTitle ~= nil then m_simpleTV.Control.CurrentTitle = header end
if m_simpleTV.Control.CurrentTitle ~= nil then m_simpleTV.Control.SetTitle(header) end

local url =  findpattern( answer,'StreamUrl":"(.-)"',1,12,1)
local name = findpattern( answer,'"description":"(.-)"',1,15,1)
local img = findpattern( answer,'image":"(.-)"',1,8,1)

if url == nil or name == nil or img == nil then
	   m_simpleTV.OSD.ShowMessage("tune.in error - can't find stream ",255,10)
           m_simpleTV.Common.Wait(2000)
	   return
 end

--logo name
--debug_in_file(img .. '\n')
filename = string.match(img,'cloudfront%.net/(.+)')

if filename == nil then 
    filename = string.match(img,'tunein%.com/(.+)')
end

if filename == nil then
 img = 'http://deep1.ru/wp-content/uploads/2014/07/tunein.png'
 filename = 'tunein.png'
end

if filename == nil then
  filename = ''
end

 rc,answer=m_simpleTV.WinInet.Get(session,url)

 if rc~=200 then
	   m_simpleTV.WinInet.Close(session)
	   m_simpleTV.OSD.ShowMessage("Connection error - " .. rc ,255,10)
	   return
 end
answer = string.gsub(answer,'[();]','')
local t = json.decode(answer)

if t == nil or t.Streams==nil then
   m_simpleTV.OSD.ShowMessage("Error - playlist not found"  ,255,10)
   return
end

local tab={}
local i=1

while true do
  if t.Streams[i] == nil then break end
  
  tab[i] = {}
  tab[i].Id   =  i
  tab[i].Name = i .. '. ' .. name .. ' ' .. t.Streams[i].Bandwidth .. 'kb ' .. t.Streams[i].MediaType
  tab[i].Adress  = t.Streams[i].Url  
  tab[i].InfoPanelLogo = img
--debug_in_file(tab[i].Name  .. ' ' .. tab[i].Adress .. '\n')
  i = i+1

end

if i>2 then
    m_simpleTV.OSD.ShowSelect('Available Streams',0,tab,5000,32)
end

   if i>1 then
       if string.match(tab[1].Adress,'radionomy') then
           retAdr = GetRealAddress(tab[1].Adress)
         elseif
          retAdr == '' then retAdr = tab[1].Adress 
      end
  end
 if retAdr == nil then retAdr = '' end

 return retAdr, header, filename, img

end

local function SaveAddress(inAdr,header,filename,img)


if filename ~= nil then
    filepath = filepath ..  filename
end

local imgerr
rc = m_simpleTV.WinInet.GetFile(session, img ,nil, filepath) 
if rc~=200 then
        --m_simpleTV.OSD.ShowMessage("TuneIn Error - can't save logo"  ,255,10)
    imgerr = 0
end

 local m3ustr=
'#EXTM3U $BorpasFileFormat="1" $LogoPath="..\\Channel\\logo\\RadioAddonLogo\\TuneIn\\"\n' ..
'#EXTINF:-1 group-title="TuneIn" tvg-logo="..\\Channel\\logo\\RadioAddonLogo\\TuneIn\\'.. filename ..'",' .. header .. '\n' .. inAdr

--debug_in_file(m3ustr .. '\n')

m_simpleTV.Common.Wait(3000)

 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 = 0  --  -1-auto  0 - plane text  1- UTF8  2- unicode
p.BorpasFileFormat=1
p.ExtFilter = 'Radio'
p.AutoNumber = 0
p.ExtFilterLogo =  '..\\Channel\\logo\\icons\\radio.png'   -- the logo of extended filter (from ver. 0.4.8 b9)
p.ExtFilterLogoForce = 0

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

   if err==true then
	names = string.gsub(names,'%$end','')
        local mess = 'TuneIn: ' .. names .. ' channel saved successfully '	 
   	m_simpleTV.OSD.ShowMessage(mess,0xFF00,5)
   end
m_simpleTV.Common.Wait(3000)
if imgerr == 0 then m_simpleTV.OSD.ShowMessage("TuneIn Error: can't save logo"  ,255,5) end
end

--OSD Save menu
if menu ~= nil and menu ~= '' and menu ~= 0 then

local t ={}
 t[1] = {} t[2] = {} 
 
  t[1].Id=1
  t[1].Name='Play'
  t[1].Adress=''
 
  t[2].Id=2
  t[2].Name='Play and Save in Radio'
  t[2].Adress=''
   
    
 local ret,id = m_simpleTV.OSD.ShowSelect('Choose actions',0,t,8000,1+4+8)
  
 if id==1 then 
   if retAdr == '' then retAdr,header = GetTuneInAddress(inAdr,header) end

  elseif id==2 then

   if retAdr == '' then 

       retAdr,header,filename,img = GetTuneInAddress(inAdr,header,filename,img) 

       if inAdr ~= nil and header ~=nil then 
		local sqlstr = 'Select main.id from main where main.name="' .. header .. '"'
                local dTable = m_simpleTV.Database.GetTable(sqlstr)
                if dTable == nil or dTable[1]==nil or dTable[1].id==nil then
                     inAdr,header,filename,img = SaveAddress(inAdr,header,filename,img) 
                end
        end
   end
end

  else
         if retAdr == '' then retAdr,header = GetTuneInAddress(inAdr,header) end
end

	if retAdr == nil or retAdr == '' then return end

m_simpleTV.WinInet.Close(session)
m_simpleTV.Control.CurrentAdress = retAdr

