media.rb 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. class Whatsapp::Outgoing::Message::Media < Whatsapp::Outgoing::Message
  3. SUPPORTED_MEDIA_TYPES = {
  4. audio: WhatsappSdk::Resource::MediaTypes::AUDIO_TYPES,
  5. document: WhatsappSdk::Resource::MediaTypes::DOCUMENT_TYPES,
  6. image: WhatsappSdk::Resource::MediaTypes::IMAGE_TYPES,
  7. sticker: WhatsappSdk::Resource::MediaTypes::STICKER_TYPES,
  8. video: WhatsappSdk::Resource::MediaTypes::VIDEO_TYPES,
  9. }.freeze
  10. attr_reader :medias_api
  11. def initialize(access_token:, phone_number_id:, recipient_number:)
  12. super
  13. @medias_api = WhatsappSdk::Api::Medias.new client
  14. end
  15. def supported_media_type?(mime_type:)
  16. detect_media_type(mime_type:).present?
  17. rescue ArgumentError
  18. false
  19. end
  20. def deliver(store:, caption: nil)
  21. mime_type = store.preferences['Mime-Type'] || store.preferences['Content-Type'] || 'application/octet-stream'
  22. media_type = detect_media_type(mime_type:)
  23. media_id = upload(store:, mime_type:)
  24. response = send(:"deliver_#{media_type}", media_id:, caption:)
  25. handle_error(response:)
  26. handle_response(response:)
  27. end
  28. private
  29. def detect_media_type(mime_type:)
  30. media_type = SUPPORTED_MEDIA_TYPES.find { |_, mime_types| mime_types.include?(mime_type) }
  31. raise ArgumentError, "Unsupported media type: #{mime_type}" if !media_type
  32. media_type.first
  33. end
  34. def upload(store:, mime_type:)
  35. with_tmpfile(prefix: 'whatsapp-media-upload') do |file|
  36. File.binwrite(file.path, store.content)
  37. response = medias_api.upload(sender_id: phone_number_id.to_i, file_path: file.path, type: mime_type)
  38. handle_error(response:)
  39. response.data.id
  40. end
  41. end
  42. def deliver_audio(media_id:, caption:)
  43. messages_api.send_audio(sender_id: phone_number_id.to_i, recipient_number: recipient_number.to_i, audio_id: media_id.to_s)
  44. end
  45. def deliver_document(media_id:, caption:)
  46. messages_api.send_document(sender_id: phone_number_id.to_i, recipient_number: recipient_number.to_i, document_id: media_id.to_s, caption:)
  47. end
  48. def deliver_image(media_id:, caption:)
  49. messages_api.send_image(sender_id: phone_number_id.to_i, recipient_number: recipient_number.to_i, image_id: media_id.to_s, caption:)
  50. end
  51. def deliver_sticker(media_id:, caption:)
  52. messages_api.send_sticker(sender_id: phone_number_id.to_i, recipient_number: recipient_number.to_i, sticker_id: media_id.to_s)
  53. end
  54. def deliver_video(media_id:, caption:)
  55. messages_api.send_video(sender_id: phone_number_id.to_i, recipient_number: recipient_number.to_i, video_id: media_id.to_s, caption:)
  56. end
  57. end