server.rb 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. # coding: utf-8
  2. require 'sinatra'
  3. require 'securerandom'
  4. require 'json'
  5. set :storage_directory, './storage/'
  6. def is_base32?(str)
  7. table = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567='
  8. if str.force_encoding("UTF-8").ascii_only?
  9. str.each_char { |c| return false unless table.include?(c) }
  10. return true
  11. else
  12. return false
  13. end
  14. end
  15. def path_is_base32?(str)
  16. str.split('/').each do |p|
  17. return false unless is_base32?(p)
  18. end
  19. return true
  20. end
  21. get '/' do
  22. redirect 'index.html'
  23. end
  24. # create a room
  25. post '/room' do
  26. id = SecureRandom.hex(6)
  27. Dir.mkdir(settings.storage_directory+id)
  28. content_type 'text/json'
  29. {id: id}.to_json
  30. end
  31. # mkdir
  32. post '/room/mkdir/:id' do |id|
  33. if Dir.exists?(settings.storage_directory+id)
  34. if params[:path] && path_is_base32?(params[:path])
  35. Dir.mkdir(settings.storage_directory+id+"/"+params[:path])
  36. return 200
  37. end
  38. end
  39. 403
  40. end
  41. # get room content
  42. get '/room/:id/*?' do |id,path|
  43. dir = settings.storage_directory+id
  44. dir += path_is_base32?(path) ? '/'+path : ''
  45. if Dir.exist?(dir)
  46. content_type 'text/json'
  47. Dir.glob(dir+'/*').map { |f|
  48. {
  49. is_directory: File.directory?(f),
  50. name: File.basename(f),
  51. last_updated: File.mtime(f)
  52. }}.to_json
  53. else
  54. 404
  55. end
  56. end
  57. # upload a file
  58. post '/room/:id' do |id|
  59. if Dir.exists?(settings.storage_directory+id)
  60. unless params[:file] &&
  61. (tmpfile = params[:file][:tempfile]) &&
  62. (name = params[:file][:filename]) &&
  63. params[:path] &&
  64. path_is_base32?(params[:path]) &&
  65. Dir.exists?(settings.storage_directory+id+'/'+params[:path])
  66. 403
  67. return
  68. end
  69. FileUtils.cp(tmpfile, settings.storage_directory+id+'/'+params[:path]+'/'+name)
  70. 200
  71. else
  72. 404
  73. end
  74. end
  75. # remove a room
  76. delete '/room/:id' do |id|
  77. end
  78. # get a file
  79. get '/files/:id/*?' do |id, filename|
  80. puts filename
  81. if path_is_base32?(filename)
  82. send_file File.join(settings.storage_directory+id, filename)
  83. else
  84. 404
  85. end
  86. end
  87. # remove a file
  88. delete '/room/:id/*?' do |id, filename|
  89. if path_is_base32?(filename)
  90. FileUtils.rm_rf(settings.storage_directory+id+"/"+filename)
  91. else
  92. 404
  93. end
  94. end