channels_sms_controller.rb 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. class ChannelsSmsController < ApplicationChannelController
  2. PERMISSION = 'admin.channel_sms'.freeze
  3. AREA = ['Sms::Notification'.freeze, 'Sms::Account'.freeze].freeze
  4. prepend_before_action -> { authentication_check(permission: self.class::PERMISSION) }, except: [:webhook]
  5. skip_before_action :verify_csrf_token, only: [:webhook]
  6. def index
  7. assets = {}
  8. render json: {
  9. account_channel_ids: channels_data('Sms::Account', assets),
  10. notification_channel_ids: channels_data('Sms::Notification', assets),
  11. config: channels_config,
  12. assets: assets
  13. }
  14. end
  15. def test
  16. raise 'Missing parameter options.adapter' if params[:options][:adapter].blank?
  17. driver = Channel.driver_class(params[:options][:adapter])
  18. resp = driver.new.send(params[:options], test_options)
  19. render json: { success: resp }
  20. rescue => e
  21. render json: { error: e.inspect, error_human: e.message }
  22. end
  23. def webhook
  24. raise Exceptions::UnprocessableEntity, 'token param missing' if params['token'].blank?
  25. channel = nil
  26. Channel.where(active: true, area: 'Sms::Account').each do |local_channel|
  27. next if local_channel.options[:webhook_token] != params['token']
  28. channel = local_channel
  29. end
  30. if !channel
  31. render(
  32. json: { message: 'channel not found' },
  33. status: :not_found
  34. )
  35. return
  36. end
  37. conten_type, content = channel.process(params.permit!.to_h)
  38. send_data content, type: conten_type
  39. end
  40. private
  41. def test_options
  42. params.permit(:recipient, :message)
  43. end
  44. def channel_params
  45. raise 'Missing area params' if params[:area].blank?
  46. if !self.class::AREA.include?(params[:area])
  47. raise "Invalid area '#{params[:area]}'!"
  48. end
  49. raise 'Missing options params' if params[:options].blank?
  50. raise 'Missing options.adapter params' if params[:options][:adapter].blank?
  51. params
  52. end
  53. def channels_config
  54. list = []
  55. Dir.glob(Rails.root.join('app', 'models', 'channel', 'driver', 'sms', '*.rb')).each do |path|
  56. filename = File.basename(path)
  57. require_dependency "channel/driver/sms/#{filename.sub('.rb', '')}"
  58. list.push Channel.driver_class("sms/#{filename}").definition
  59. end
  60. list
  61. end
  62. def channels_data(area, assets)
  63. channel_ids = []
  64. Channel.where(area: area).each do |channel|
  65. assets = channel.assets(assets)
  66. channel_ids.push(channel.id)
  67. end
  68. channel_ids
  69. end
  70. end