file-api.lua 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. return function (connection, req, args)
  2. dofile('httpserver-header.lc')(connection, 200, 'html')
  3. if req.method == 'POST' then
  4. --print('POST method')
  5. local rd = req.getRequestData()
  6. --print(node.heap())
  7. collectgarbage()
  8. --print(node.heap())
  9. if rd['action'] == 'list' then
  10. print('retrieve file list')
  11. local l, filelist, n, s, ok, json
  12. l = file.list()
  13. filelist = {}
  14. for n, s in pairs(l) do
  15. if ((string.sub(n, -3) ~= '.gz') and (string.sub(n, -3) ~= '.lc')) then
  16. filelist[n] = s
  17. end
  18. end
  19. ok, json = pcall(sjson.encode, filelist)
  20. if ok then
  21. --print(json)
  22. connection:send(json)
  23. else
  24. --print("failed to encode!")
  25. end
  26. elseif rd['action'] == 'load' then
  27. print('load file: '..rd['filename'])
  28. file.open(rd['filename'], 'r')
  29. local buffer = file.read()
  30. while buffer ~= nil do
  31. connection:send(buffer)
  32. buffer = file.read()
  33. end
  34. file.close()
  35. elseif rd['action'] == 'save' then
  36. --print('save file: '..rd['filename'])
  37. local data = rd['data']
  38. file.open(rd['filename'], 'w+')
  39. file.write(data)
  40. file.close()
  41. connection:send('initial write: ' .. string.len(data))
  42. elseif rd['action'] == 'append' then
  43. --print('append file: '..rd['filename'])
  44. local data = rd['data']
  45. file.open(rd['filename'], 'a+')
  46. file.seek('end')
  47. file.write(data)
  48. file.close()
  49. connection:send('Append: '..string.len(data))
  50. elseif rd['action'] == 'compile' then
  51. --print('compile file: '..rd['filename'])
  52. node.compile(rd['filename'])
  53. local compiledfile = string.sub(rd['filename'], 1, -5)..'.lc'
  54. connection:send('Compiled file: <a href="'..compiledfile..'?" target="_blank">'..compiledfile..'</a>')
  55. elseif rd['action'] == 'new' then
  56. --print('create new file')
  57. local i = 1
  58. local f = 'new'..i..'.lua'
  59. -- find a new file name
  60. while file.open(f, 'r') do
  61. file.close()
  62. i = i + 1
  63. f = 'new'..i..'.lua'
  64. end
  65. file.open(f, 'w+')
  66. file.close()
  67. connection:send('Created file: '..f)
  68. elseif rd['action'] == 'rename' then
  69. --print('rename file from "'..rd['filename']..'" to "'..rd['newfilename']..'"')
  70. file.rename(rd['filename'], rd['newfilename'])
  71. connection:send('Renamed file from "'..rd['filename']..'" to "'..rd['newfilename']..'"')
  72. elseif rd['action'] == 'delete' then
  73. --print('deleted file: '..rd['filename'])
  74. file.remove(rd['filename'])
  75. connection:send('Deleted file: '..rd['filename'])
  76. end
  77. end
  78. collectgarbage()
  79. end