file.rb 1.8 KB

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