--script for cloud.mail.ru (19/07/2015)
--open URL https://cloud.mail.ru/public/7CdY/Pad8iFRi4 / https://cloud.mail.ru/public/A7hf/PBsG4XDpS

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, '^https://cloud%.mail%.ru/public/' ) then return end

local id = findpattern(inAdr,'public/(.+)/$',1,7,1)
 if id == nil then 
   id = findpattern(inAdr,'public/(.+)',1,7,0)
   if id == nil then return end
 end
--debug_in_file(id .. '\n')

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

 local session = m_simpleTV.WinInet.New("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.84 Safari/537.36 OPR/31.0.1889.74 (Edition beta)")
 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,5000,0)
  --INTERNET_FLAG_SECURE
  m_simpleTV.WinInet.SetOpenRequestFlags(session, 0x00800000 + 0x00002000 + 0x00001000)
-------------------------------------------

 local  rc,answer=m_simpleTV.WinInet.Get(session,inAdr)

 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')

 local tmp = findpattern( answer,'cloudBuilder%((.-)%);',1,13,2)
 if tmp == nil then return end
 tmp = string.gsub(tmp,'%[%]','""')
 --debug_in_file(tmp .. '\n\n')

 local t = json.decode(tmp)
--debug_in_file(t.folders.folder.list[1].name .. '\n\n')
--do return end

 if t == nil then
    m_simpleTV.OSD.ShowMessage("cloud.mail.ru - json error"  ,255,10)
    return
 end

 if m_simpleTV.Control.CurrentTitle ~= nil then 
  if t.folders.folder.count.files == 1 then
     m_simpleTV.Control.CurrentTitle=t.folders.folder.list[1].name 
    
     else
    m_simpleTV.Control.CurrentTitle=t.folders.folder.name 
  end
end

 local tab={}
 local i=1
 while true do
   if t.folders.folder.list[i] == nil then break end
  
   tab[i] = {}
   tab[i].Id   =  i
   tab[i].Name =  t.folders.folder.list[i].name
   local file = string.gsub(t.folders.folder.list[i].name,' ', '%%20')
   tab[i].Adress = t.dispatcher.weblink_get[1].url .. id .. '/' .. file .. '?x-email=undefined'

 --debug_in_file(tab[i].Name .. ' ' .. tab[i].Adress  .. "\n\n")
   i=i+1
 end

   if i>1 then
	retAdr = tab[1].Adress
  end

 if i>2 then
    m_simpleTV.OSD.ShowSelect('Select video',0,tab,5000)
 end

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

