media.rb 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. class Whatsapp::Incoming::Media < Whatsapp::Client
  3. attr_reader :medias_api
  4. def initialize(access_token:)
  5. super(access_token:)
  6. @medias_api = WhatsappSdk::Api::Medias.new client
  7. end
  8. def download(media_id:)
  9. metadata = retrieve_metadata(media_id:)
  10. content = retrieve_content(url: metadata[:url], media_type: metadata[:media_type])
  11. raise InvalidChecksumError if !valid_checksum?(content, metadata[:sha256])
  12. [content, metadata[:media_type]]
  13. rescue WhatsappSdk::Api::Medias::InvalidMediaTypeError => e
  14. raise InvalidMediaTypeError, e.message
  15. end
  16. private
  17. def retrieve_metadata(media_id:)
  18. response = medias_api.media(media_id:)
  19. handle_error(response:)
  20. {
  21. url: response.data.url,
  22. media_type: response.data.mime_type,
  23. sha256: response.data.sha256,
  24. }
  25. end
  26. def retrieve_content(url:, media_type:)
  27. with_tmpfile(prefix: 'whatsapp-media-download') do |file|
  28. response = medias_api.download(url:, file_path: file.path, media_type:)
  29. handle_error(response:)
  30. file.read
  31. end
  32. end
  33. def valid_checksum?(content, sha256)
  34. Digest::SHA2.new(256).hexdigest(content) == sha256
  35. end
  36. class InvalidChecksumError < StandardError
  37. def initialize
  38. super(__('Integrity verification of the downloaded WhatsApp media failed.'))
  39. end
  40. end
  41. class InvalidMediaTypeError < StandardError; end
  42. end