channels_telegram_controller.rb 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. # Copyright (C) 2012-2016 Zammad Foundation, http://zammad-foundation.org/
  2. class ChannelsTelegramController < ApplicationController
  3. prepend_before_action -> { authentication_check(permission: 'admin.channel_telegram') }, except: [:webhook]
  4. skip_before_action :verify_csrf_token, only: [:webhook]
  5. def index
  6. assets = {}
  7. channel_ids = []
  8. Channel.where(area: 'Telegram::Bot').order(:id).each do |channel|
  9. assets = channel.assets(assets)
  10. channel_ids.push channel.id
  11. end
  12. render json: {
  13. assets: assets,
  14. channel_ids: channel_ids
  15. }
  16. end
  17. def add
  18. begin
  19. channel = Telegram.create_or_update_channel(params[:api_token], params)
  20. rescue => e
  21. raise Exceptions::UnprocessableEntity, e.message
  22. end
  23. render json: channel
  24. end
  25. def update
  26. channel = Channel.find_by(id: params[:id], area: 'Telegram::Bot')
  27. begin
  28. channel = Telegram.create_or_update_channel(params[:api_token], params, channel)
  29. rescue => e
  30. raise Exceptions::UnprocessableEntity, e.message
  31. end
  32. render json: channel
  33. end
  34. def enable
  35. channel = Channel.find_by(id: params[:id], area: 'Telegram::Bot')
  36. channel.active = true
  37. channel.save!
  38. render json: {}
  39. end
  40. def disable
  41. channel = Channel.find_by(id: params[:id], area: 'Telegram::Bot')
  42. channel.active = false
  43. channel.save!
  44. render json: {}
  45. end
  46. def destroy
  47. channel = Channel.find_by(id: params[:id], area: 'Telegram::Bot')
  48. channel.destroy
  49. render json: {}
  50. end
  51. def webhook
  52. raise Exceptions::UnprocessableEntity, 'bot param missing' if params['bid'].blank?
  53. channel = Telegram.bot_by_bot_id(params['bid'])
  54. raise Exceptions::UnprocessableEntity, 'bot not found' if !channel
  55. if channel.options[:callback_token] != params['callback_token']
  56. raise Exceptions::UnprocessableEntity, 'invalid callback token'
  57. end
  58. telegram = Telegram.new(channel.options[:api_token])
  59. telegram.to_group(params, channel.group_id, channel)
  60. render json: {}, status: :ok
  61. end
  62. end