media.rb 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. class Whatsapp::Retry::Media
  3. attr_reader :article, :channel
  4. def initialize(article:)
  5. @article = article
  6. raise ArticleInvalidError if media_id.blank?
  7. @channel = find_channel!
  8. end
  9. def process
  10. download_media
  11. update_article
  12. end
  13. private
  14. def update_article
  15. article.preferences['whatsapp'].delete('media_error')
  16. article.save!
  17. end
  18. def media_id
  19. @media_id ||= article.preferences&.dig('whatsapp', 'media_id')
  20. end
  21. def find_channel!
  22. channel_id = article.ticket.preferences&.dig('channel_id')
  23. raise ArticleInvalidError if channel_id.nil?
  24. Channel.find_by(id: channel_id).tap do |channel|
  25. if channel.nil? || channel.area != 'WhatsApp::Business' || !channel.active
  26. raise ArticleInvalidError
  27. end
  28. end
  29. end
  30. def download_media
  31. data, filename, mime_type = attachment
  32. Store.create!(
  33. object: 'Ticket::Article',
  34. o_id: article.id,
  35. data: data,
  36. filename: filename,
  37. preferences: {
  38. 'Mime-Type' => mime_type,
  39. },
  40. )
  41. end
  42. def attachment
  43. media = Whatsapp::Incoming::Media.new(access_token: channel.options[:access_token])
  44. data, mime_type = media.download(media_id: media_id)
  45. filename = article.preferences.dig('whatsapp', 'filename').presence || "#{article.ticket.number}-#{media_id}.#{Whatsapp.file_suffix(mime_type:)}"
  46. [data, filename, mime_type]
  47. end
  48. class ArticleInvalidError < StandardError
  49. attr_reader :reason
  50. def initialize(reason = __('The given article is not a media article.'))
  51. @reason = reason
  52. message = __('Retrying to download the sent media via WhatsApp failed.')
  53. message += " #{reason}" if reason.present?
  54. super(message)
  55. end
  56. end
  57. end