file.rb 2.0 KB

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