file.rb 1.8 KB

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