-- vim:set ft=lua:
dofile(mg.document_root..'\\api\\util.lua')

MakeThumbs=mg.get_var(mg.request_info.query_string,'thumbs')

if MakeThumbs then
  AssertCsrf(mg.request_info.query_string)

  dir=edcb.GetPrivateProfile('SET', 'ModulePath', '', 'Common.ini')..'\\Tools\\'
  ffmpeg=edcb.GetPrivateProfile('SET','ffmpeg',dir..'ffmpeg.exe',ini)
end

ct={'<?xml version="1.0" encoding="UTF-8" ?><entry>'}

if edcb.FindFile then
  function finddir(path)
    local i=0
    local t=edcb.FindFile(path..'\\*', 0) or {}
    return function() i=i+1 return t[i] end
  end
else
  local status, lfs=pcall(require, 'lfs')
  if status then
    function finddir(path)
      path=edcb.Convert('cp932', 'utf-8', path)
      local f, s, fname=lfs.dir(path)
      return function()
        fname=f(s, fname)
        if fname then
          local attr=lfs.attributes(path..'\\'..fname)
          return {name=edcb.Convert('utf-8', 'cp932', fname), iserr=not attr, isdir=(attr and attr.mode=='directory'), mtime=(attr and os.date('!*t', attr.modification+9*3600))}
        end
        return nil
      end
    end
  end
end

if finddir then
  thumbsUsing={}
  id=0
  function attrdir(path)
    local filelist={}
    for v in finddir(path) do
      local fname=v.name
      if fname ~= '.' and fname ~= '..' then
        fpath=path..'\\'..fname
        if not v.iserr then
          if v.isdir then
            if fname ~= 'chapters' and not fpath:find('\\video\\thumbs$') then
              if MakeThumbs then
                attrdir(fpath)
              else
                id=id+1
                table.insert(ct, '<dir><name>'..fname:gsub('&', '&amp;')..'</name><id>'..id..'</id>')
                attrdir(fpath)
                table.insert(ct, '</dir>')
              end
            end
          elseif mg.get_mime_type(fname):find('^video/') or fname:lower():find('%.ts$') or fname:lower():find('%.m2ts$') then
            thumbHash=mg.md5(fpath:lower())
            thumbs=edcb.FindFile and edcb.FindFile(mg.document_root..'\\video\\thumbs\\'..thumbHash..'.jpg', 1)
            if MakeThumbs then
              if not thumbs and edcb.FindFile then
                edcb.os.execute('""'..ffmpeg..'" -ss 5 -i "'..fpath..'" -vframes 1 -f image2 -s 480x270 "'..mg.document_root..'\\video\\thumbs\\'..thumbHash..'.jpg'..'""')
              end
              thumbsUsing[thumbHash]=true
            else
              table.insert(filelist, '<file><name>'..fname:gsub('&', '&amp;')..'</name><path>'
                ..(NativeToDocumentPath(fpath) and mg.url_encode(NativeToDocumentPath(fpath)):gsub('%%2f', '/')..'</path><public>1</public>'
                                                or mg.url_encode(fpath):gsub('%%2f', '/')..'</path>')
                ..(v.mtime and '<date>'..TimeWithZone(v.mtime, 9*3600)..'</date>' or '')
                ..(thumbs and '<thumbs>'..thumbHash..'.jpg'..'</thumbs>' or '')
                ..'</file>')
            end
          end
        else
          table.insert(ct, '<err>'..fpath:gsub('&', '&amp;')..'</err>')
        end
      end
    end
    table.insert(ct, table.concat(filelist))
  end

  if not MakeThumbs then table.insert(ct, '<dir><name>ホーム</name><id>home</id>') end

  for i,v in ipairs(GetLibraryPathList()) do
    if MakeThumbs then
      attrdir(v)
    else
      id=id+1
      table.insert(ct, '<dir><name>'..(NativeToDocumentPath(v) or v):gsub('&', '&amp;')..'</name><id>'..id..'</id>')
      attrdir(v)
      table.insert(ct, '</dir>')
    end
  end

  if MakeThumbs then
    -- 未使用サムネを掃除
    for i,v in ipairs(edcb.FindFile and edcb.FindFile(mg.document_root..'\\video\\thumbs\\????????????????????????????????.jpg', 0) or {}) do
      if v.name:match('^%x+%.[Jj][Pp][Gg]$') and not thumbsUsing[v.name:match('^%x+'):lower()] then
        edcb.os.remove(mg.document_root..'\\video\\thumbs\\'..v.name)
      end
    end
    table.insert(ct, '<info>サムネを作成しました</info></entry>')
  else
    table.insert(ct, '</dir></entry>')
  end
else
  table.insert(ct, '<error>EDCBが非対応です</error></entry>')
end

cl=0
for i,v in ipairs(ct) do cl=cl+#v end
mg.write(Response(200, 'text/xml', 'utf-8', cl) ..'\r\n')
if mg.request_info.request_method~='HEAD' then
  for i,v in ipairs(ct) do mg.write(v) end
end
