file.rb 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. # Copyright (C) 2012-2014 Zammad Foundation, http://zammad-foundation.org/
  2. class Store::File < ApplicationModel
  3. include ApplicationLib
  4. after_destroy :destroy_provider
  5. # add new file
  6. def self.add(data)
  7. sha = Digest::SHA256.hexdigest( data )
  8. file = Store::File.where( :sha => sha ).first
  9. if file == nil
  10. # load backend based on config
  11. adapter_name = Setting.get('storage_provider') || 'DB'
  12. if !adapter_name
  13. raise "Missing storage_provider setting option"
  14. end
  15. adapter = self.load_adapter( "Store::Provider::#{ adapter_name }" )
  16. adapter.add( data, sha )
  17. file = Store::File.create(
  18. :provider => adapter_name,
  19. :sha => sha,
  20. )
  21. end
  22. file
  23. end
  24. # read content
  25. def content
  26. adapter = self.class.load_adapter("Store::Provider::#{ self.provider }")
  27. if self.sha
  28. c = adapter.get( self.sha )
  29. else
  30. # fallback until migration is done
  31. c = Store::Provider::DB.where( :md5 => self.md5 ).first.data
  32. end
  33. c
  34. end
  35. # check data and sha, in case fix it
  36. def self.verify(fix_it = nil)
  37. success = true
  38. Store::File.all.each {|item|
  39. content = item.content
  40. sha = Digest::SHA256.hexdigest( content )
  41. puts "CHECK: Store::File.find(#{item.id}) "
  42. if sha != item.sha
  43. success = false
  44. puts "DIFF: sha diff of Store::File.find(#{item.id}) "
  45. if fix_it
  46. item.update_attribute( :sha, sha )
  47. end
  48. end
  49. }
  50. success
  51. end
  52. # move file from one to other provider
  53. # e. g. Store::File.move('File', 'DB')
  54. # e. g. Store::File.move('DB', 'File')
  55. def self.move(source, target)
  56. adapter_source = load_adapter("Store::Provider::#{ source }")
  57. adapter_target = load_adapter("Store::Provider::#{ target }")
  58. Store::File.all.each {|item|
  59. next if item.provider == target
  60. content = item.content
  61. # add to new provider
  62. adapter_target.add( content, item.sha )
  63. # update meta data
  64. item.update_attribute( :provider, target )
  65. # remove from old provider
  66. adapter_source.delete( item.sha )
  67. puts "NOTICE: Moved file #{item.sha} from #{source} to #{target}"
  68. }
  69. true
  70. end
  71. private
  72. def destroy_provider
  73. adapter = self.class.load_adapter("Store::Provider::#{ self.provider }")
  74. adapter.delete( self.sha )
  75. end
  76. end