file.rb 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. # Copyright (C) 2012-2014 Zammad Foundation, http://zammad-foundation.org/
  2. class Store
  3. module Provider
  4. module File
  5. def self.add(data, sha)
  6. write_to_fs(data, sha)
  7. true
  8. end
  9. def self.get(sha)
  10. read_from_fs(sha)
  11. end
  12. def self.delete(sha)
  13. unlink_from_fs(sha)
  14. end
  15. private
  16. # generate file location
  17. def self.get_locaton(sha)
  18. # generate directory
  19. base = Rails.root.to_s + '/storage/fs/'
  20. parts = sha.scan(/.{1,4}/)
  21. path = parts[ 1 .. 10 ].join('/') + '/'
  22. file = parts[ 11 .. parts.count ].join('')
  23. location = "#{base}/#{path}"
  24. # create directory if not exists
  25. if !File.exist?( location )
  26. FileUtils.mkdir_p( location )
  27. end
  28. location += file
  29. end
  30. # unlink file from fs
  31. def self.unlink_from_fs(sha)
  32. if File.exist?( get_locaton(sha) )
  33. puts "NOTICE: storge remove '#{ get_locaton(sha) }'"
  34. File.delete( get_locaton(sha) )
  35. end
  36. end
  37. # read file from fs
  38. def self.read_from_fs(sha)
  39. puts "read from fs #{ get_locaton(sha) }"
  40. if !File.exist?( get_locaton(sha) )
  41. raise "ERROR: No such file #{ get_locaton(sha) }"
  42. end
  43. data = File.open( get_locaton(sha), 'rb' )
  44. content = data.read
  45. # check sha
  46. local_sha = Digest::SHA256.hexdigest( content )
  47. if local_sha != sha
  48. raise "ERROR: Corrupt file in fs #{ get_locaton(sha) }, sha should be #{sha} but is #{local_sha}"
  49. end
  50. content
  51. end
  52. # write file to fs
  53. def self.write_to_fs(data, sha)
  54. # install file
  55. permission = '600'
  56. if !File.exist?( get_locaton(sha) )
  57. puts "NOTICE: storge write '#{ get_locaton(sha) }' (#{permission})"
  58. file = File.new( get_locaton(sha), 'wb' )
  59. file.write( data )
  60. file.close
  61. end
  62. File.chmod( permission.to_i(8), get_locaton(sha) )
  63. # check sha
  64. local_sha = Digest::SHA256.hexdigest( read_from_fs(sha) )
  65. if sha != local_sha
  66. raise "ERROR: Corrupt file in fs #{ get_locaton(sha) }, sha should be #{sha} but is #{local_sha}"
  67. end
  68. true
  69. end
  70. end
  71. end
  72. end