telegram.rb 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820
  1. # Copyright (C) 2012-2015 Zammad Foundation, http://zammad-foundation.org/
  2. class Telegram
  3. attr_accessor :client
  4. =begin
  5. check token and return bot attributes of token
  6. bot = Telegram.check_token('token')
  7. =end
  8. def self.check_token(token)
  9. api = TelegramAPI.new(token)
  10. begin
  11. bot = api.getMe()
  12. rescue
  13. raise Exceptions::UnprocessableEntity, 'invalid api token'
  14. end
  15. bot
  16. end
  17. =begin
  18. set webhook for bot
  19. success = Telegram.set_webhook('token', callback_url)
  20. returns
  21. true|false
  22. =end
  23. def self.set_webhook(token, callback_url)
  24. if callback_url.match?(%r{^http://}i)
  25. raise Exceptions::UnprocessableEntity, 'webhook url need to start with https://, you use http://'
  26. end
  27. api = TelegramAPI.new(token)
  28. begin
  29. api.setWebhook(callback_url)
  30. rescue
  31. raise Exceptions::UnprocessableEntity, 'Unable to set webhook at Telegram, seems to be a invalid url.'
  32. end
  33. true
  34. end
  35. =begin
  36. create or update channel, store bot attributes and verify token
  37. channel = Telegram.create_or_update_channel('token', params)
  38. returns
  39. channel # instance of Channel
  40. =end
  41. def self.create_or_update_channel(token, params, channel = nil)
  42. # verify token
  43. bot = Telegram.check_token(token)
  44. if !channel
  45. if Telegram.bot_duplicate?(bot['id'])
  46. raise Exceptions::UnprocessableEntity, 'Bot already exists!'
  47. end
  48. end
  49. if params[:group_id].blank?
  50. raise Exceptions::UnprocessableEntity, 'Group needed!'
  51. end
  52. group = Group.find_by(id: params[:group_id])
  53. if !group
  54. raise Exceptions::UnprocessableEntity, 'Group invalid!'
  55. end
  56. # generate random callback token
  57. callback_token = if Rails.env.test?
  58. 'callback_token'
  59. else
  60. SecureRandom.urlsafe_base64(10)
  61. end
  62. # set webhook / callback url for this bot @ telegram
  63. callback_url = "#{Setting.get('http_type')}://#{Setting.get('fqdn')}/api/v1/channels_telegram_webhook/#{callback_token}?bid=#{bot['id']}"
  64. Telegram.set_webhook(token, callback_url)
  65. if !channel
  66. channel = Telegram.bot_by_bot_id(bot['id'])
  67. if !channel
  68. channel = Channel.new
  69. end
  70. end
  71. channel.area = 'Telegram::Bot'
  72. channel.options = {
  73. bot: {
  74. id: bot['id'],
  75. username: bot['username'],
  76. first_name: bot['first_name'],
  77. last_name: bot['last_name'],
  78. },
  79. callback_token: callback_token,
  80. callback_url: callback_url,
  81. api_token: token,
  82. welcome: params[:welcome],
  83. goodbye: params[:goodbye],
  84. }
  85. channel.group_id = group.id
  86. channel.active = true
  87. channel.save!
  88. channel
  89. end
  90. =begin
  91. check if bot already exists as channel
  92. success = Telegram.bot_duplicate?(bot_id)
  93. returns
  94. channel # instance of Channel
  95. =end
  96. def self.bot_duplicate?(bot_id, channel_id = nil)
  97. Channel.where(area: 'Telegram::Bot').each do |channel|
  98. next if !channel.options
  99. next if !channel.options[:bot]
  100. next if !channel.options[:bot][:id]
  101. next if channel.options[:bot][:id] != bot_id
  102. next if channel.id.to_s == channel_id.to_s
  103. return true
  104. end
  105. false
  106. end
  107. =begin
  108. get channel by bot_id
  109. channel = Telegram.bot_by_bot_id(bot_id)
  110. returns
  111. true|false
  112. =end
  113. def self.bot_by_bot_id(bot_id)
  114. Channel.where(area: 'Telegram::Bot').each do |channel|
  115. next if !channel.options
  116. next if !channel.options[:bot]
  117. next if !channel.options[:bot][:id]
  118. return channel if channel.options[:bot][:id].to_s == bot_id.to_s
  119. end
  120. nil
  121. end
  122. =begin
  123. generate message_id for message
  124. message_id = Telegram.message_id(message)
  125. returns
  126. message_id # 123456@telegram
  127. =end
  128. def self.message_id(params)
  129. message_id = nil
  130. %i[message edited_message].each do |key|
  131. next if !params[key]
  132. next if !params[key][:message_id]
  133. message_id = params[key][:message_id]
  134. break
  135. end
  136. if message_id
  137. %i[message edited_message].each do |key|
  138. next if !params[key]
  139. next if !params[key][:chat]
  140. next if !params[key][:chat][:id]
  141. message_id = "#{message_id}.#{params[key][:chat][:id]}"
  142. end
  143. end
  144. if !message_id
  145. message_id = params[:update_id]
  146. end
  147. "#{message_id}@telegram"
  148. end
  149. =begin
  150. client = Telegram.new('token')
  151. =end
  152. def initialize(token)
  153. @token = token
  154. @api = TelegramAPI.new(token)
  155. end
  156. =begin
  157. client.message(chat_id, 'some message', language_code)
  158. =end
  159. def message(chat_id, message, language_code = 'en')
  160. return if Rails.env.test?
  161. locale = Locale.find_by(alias: language_code)
  162. if !locale
  163. locale = Locale.where('locale LIKE :prefix', prefix: "#{language_code}%").first
  164. end
  165. if locale
  166. message = Translation.translate(locale[:locale], message)
  167. end
  168. @api.sendMessage(chat_id, message)
  169. end
  170. def user(params)
  171. {
  172. id: params[:message][:from][:id],
  173. username: params[:message][:from][:username],
  174. first_name: params[:message][:from][:first_name],
  175. last_name: params[:message][:from][:last_name]
  176. }
  177. end
  178. def to_user(params)
  179. Rails.logger.debug { 'Create user from message...' }
  180. Rails.logger.debug { params.inspect }
  181. # do message_user lookup
  182. message_user = user(params)
  183. auth = Authorization.find_by(uid: message_user[:id], provider: 'telegram')
  184. # create or update user
  185. login = message_user[:username] || message_user[:id]
  186. user_data = {
  187. login: login,
  188. firstname: message_user[:first_name],
  189. lastname: message_user[:last_name],
  190. }
  191. if auth
  192. user = User.find(auth.user_id)
  193. user.update!(user_data)
  194. else
  195. if message_user[:username]
  196. user_data[:note] = "Telegram @#{message_user[:username]}"
  197. end
  198. user_data[:active] = true
  199. user_data[:role_ids] = Role.signup_role_ids
  200. user = User.create(user_data)
  201. end
  202. # create or update authorization
  203. auth_data = {
  204. uid: message_user[:id],
  205. username: login,
  206. user_id: user.id,
  207. provider: 'telegram'
  208. }
  209. if auth
  210. auth.update!(auth_data)
  211. else
  212. Authorization.create(auth_data)
  213. end
  214. user
  215. end
  216. def to_ticket(params, user, group_id, channel)
  217. UserInfo.current_user_id = user.id
  218. Rails.logger.debug { 'Create ticket from message...' }
  219. Rails.logger.debug { params.inspect }
  220. Rails.logger.debug { user.inspect }
  221. Rails.logger.debug { group_id.inspect }
  222. # prepare title
  223. title = '-'
  224. %i[text caption].each do |area|
  225. next if !params[:message]
  226. next if !params[:message][area]
  227. title = params[:message][area]
  228. break
  229. end
  230. if title == '-'
  231. %i[sticker photo document voice].each do |area|
  232. next if !params[:message]
  233. next if !params[:message][area]
  234. next if !params[:message][area][:emoji]
  235. title = params[:message][area][:emoji]
  236. break
  237. rescue
  238. # just go ahead
  239. title
  240. end
  241. end
  242. if title.length > 60
  243. title = "#{title[0, 60]}..."
  244. end
  245. # find ticket or create one
  246. state_ids = Ticket::State.where(name: %w[closed merged removed]).pluck(:id)
  247. possible_tickets = Ticket.where(customer_id: user.id).where.not(state_id: state_ids).order(:updated_at)
  248. ticket = possible_tickets.find_each.find { |possible_ticket| possible_ticket.preferences[:channel_id] == channel.id }
  249. if ticket
  250. # check if title need to be updated
  251. if ticket.title == '-'
  252. ticket.title = title
  253. end
  254. new_state = Ticket::State.find_by(default_create: true)
  255. if ticket.state_id != new_state.id
  256. ticket.state = Ticket::State.find_by(default_follow_up: true)
  257. end
  258. ticket.save!
  259. return ticket
  260. end
  261. ticket = Ticket.new(
  262. group_id: group_id,
  263. title: title,
  264. state_id: Ticket::State.find_by(default_create: true).id,
  265. priority_id: Ticket::Priority.find_by(default_create: true).id,
  266. customer_id: user.id,
  267. preferences: {
  268. channel_id: channel.id,
  269. telegram: {
  270. bid: params['bid'],
  271. chat_id: params[:message][:chat][:id]
  272. }
  273. },
  274. )
  275. ticket.save!
  276. ticket
  277. end
  278. def to_article(params, user, ticket, channel, article = nil)
  279. if article
  280. Rails.logger.debug { 'Update article from message...' }
  281. else
  282. Rails.logger.debug { 'Create article from message...' }
  283. end
  284. Rails.logger.debug { params.inspect }
  285. Rails.logger.debug { user.inspect }
  286. Rails.logger.debug { ticket.inspect }
  287. UserInfo.current_user_id = user.id
  288. if article
  289. article.preferences[:edited_message] = {
  290. message: {
  291. created_at: params[:message][:date],
  292. message_id: params[:message][:message_id],
  293. from: params[:message][:from],
  294. },
  295. update_id: params[:update_id],
  296. }
  297. else
  298. article = Ticket::Article.new(
  299. ticket_id: ticket.id,
  300. type_id: Ticket::Article::Type.find_by(name: 'telegram personal-message').id,
  301. sender_id: Ticket::Article::Sender.find_by(name: 'Customer').id,
  302. from: user(params)[:username],
  303. to: "@#{channel[:options][:bot][:username]}",
  304. message_id: Telegram.message_id(params),
  305. internal: false,
  306. preferences: {
  307. message: {
  308. created_at: params[:message][:date],
  309. message_id: params[:message][:message_id],
  310. from: params[:message][:from],
  311. },
  312. update_id: params[:update_id],
  313. }
  314. )
  315. end
  316. # add photo
  317. if params[:message][:photo]
  318. # find photo with best resolution for us
  319. photo = nil
  320. max_width = 650 * 2
  321. last_width = 0
  322. last_height = 0
  323. params[:message][:photo].each do |file|
  324. if !photo
  325. photo = file
  326. last_width = file['width'].to_i
  327. last_height = file['height'].to_i
  328. end
  329. next if file['width'].to_i >= max_width || file['width'].to_i <= last_width
  330. photo = file
  331. last_width = file['width'].to_i
  332. last_height = file['height'].to_i
  333. end
  334. if last_width > 650
  335. last_width = (last_width / 2).to_i
  336. last_height = (last_height / 2).to_i
  337. end
  338. # download photo
  339. photo_result = get_file(params, photo)
  340. body = "<img style=\"width:#{last_width}px;height:#{last_height}px;\" src=\"data:image/png;base64,#{Base64.strict_encode64(photo_result.body)}\">"
  341. if params[:message][:caption]
  342. body += "<br>#{params[:message][:caption].text2html}"
  343. end
  344. article.content_type = 'text/html'
  345. article.body = body
  346. article.save!
  347. return article
  348. end
  349. # add document
  350. if params[:message][:document]
  351. document = params[:message][:document]
  352. thumb = params[:message][:document][:thumb]
  353. body = '&nbsp;'
  354. if thumb
  355. width = thumb[:width]
  356. height = thumb[:height]
  357. thumb_result = get_file(params, thumb)
  358. body = "<img style=\"width:#{width}px;height:#{height}px;\" src=\"data:image/png;base64,#{Base64.strict_encode64(thumb_result.body)}\">"
  359. end
  360. if params[:message][:caption]
  361. body += "<br>#{params[:message][:caption].text2html}"
  362. end
  363. document_result = get_file(params, document)
  364. article.content_type = 'text/html'
  365. article.body = body
  366. article.save!
  367. Store.remove(
  368. object: 'Ticket::Article',
  369. o_id: article.id,
  370. )
  371. Store.add(
  372. object: 'Ticket::Article',
  373. o_id: article.id,
  374. data: document_result.body,
  375. filename: document[:file_name],
  376. preferences: {
  377. 'Mime-Type' => document[:mime_type],
  378. },
  379. )
  380. return article
  381. end
  382. # add video
  383. if params[:message][:video]
  384. video = params[:message][:video]
  385. thumb = params[:message][:video][:thumb]
  386. body = '&nbsp;'
  387. if thumb
  388. width = thumb[:width]
  389. height = thumb[:height]
  390. thumb_result = get_file(params, thumb)
  391. body = "<img style=\"width:#{width}px;height:#{height}px;\" src=\"data:image/png;base64,#{Base64.strict_encode64(thumb_result.body)}\">"
  392. end
  393. if params[:message][:caption]
  394. body += "<br>#{params[:message][:caption].text2html}"
  395. end
  396. video_result = get_file(params, video)
  397. article.content_type = 'text/html'
  398. article.body = body
  399. article.save!
  400. Store.remove(
  401. object: 'Ticket::Article',
  402. o_id: article.id,
  403. )
  404. # get video type
  405. type = video[:mime_type].gsub(%r{(.+/)}, '')
  406. Store.add(
  407. object: 'Ticket::Article',
  408. o_id: article.id,
  409. data: video_result.body,
  410. filename: video[:file_name] || "video-#{video[:file_id]}.#{type}",
  411. preferences: {
  412. 'Mime-Type' => video[:mime_type],
  413. },
  414. )
  415. return article
  416. end
  417. # add voice
  418. if params[:message][:voice]
  419. voice = params[:message][:voice]
  420. body = '&nbsp;'
  421. if params[:message][:caption]
  422. body = "<br>#{params[:message][:caption].text2html}"
  423. end
  424. document_result = get_file(params, voice)
  425. article.content_type = 'text/html'
  426. article.body = body
  427. article.save!
  428. Store.remove(
  429. object: 'Ticket::Article',
  430. o_id: article.id,
  431. )
  432. Store.add(
  433. object: 'Ticket::Article',
  434. o_id: article.id,
  435. data: document_result.body,
  436. filename: voice[:file_path] || "audio-#{voice[:file_id]}.ogg",
  437. preferences: {
  438. 'Mime-Type' => voice[:mime_type],
  439. },
  440. )
  441. return article
  442. end
  443. # add sticker
  444. if params[:message][:sticker]
  445. sticker = params[:message][:sticker]
  446. emoji = sticker[:emoji]
  447. thumb = sticker[:thumb]
  448. body = '&nbsp;'
  449. if thumb
  450. width = thumb[:width]
  451. height = thumb[:height]
  452. thumb_result = get_file(params, thumb)
  453. body = "<img style=\"width:#{width}px;height:#{height}px;\" src=\"data:image/webp;base64,#{Base64.strict_encode64(thumb_result.body)}\">"
  454. article.content_type = 'text/html'
  455. elsif emoji
  456. article.content_type = 'text/plain'
  457. body = emoji
  458. end
  459. article.body = body
  460. article.save!
  461. if sticker[:file_id]
  462. document_result = get_file(params, sticker)
  463. Store.remove(
  464. object: 'Ticket::Article',
  465. o_id: article.id,
  466. )
  467. Store.add(
  468. object: 'Ticket::Article',
  469. o_id: article.id,
  470. data: document_result.body,
  471. filename: sticker[:file_name] || "#{sticker[:set_name]}.webp",
  472. preferences: {
  473. 'Mime-Type' => 'image/webp', # mime type is not given from Telegram API but this is actually WebP
  474. },
  475. )
  476. end
  477. return article
  478. end
  479. # add text
  480. if params[:message][:text]
  481. article.content_type = 'text/plain'
  482. article.body = params[:message][:text]
  483. article.save!
  484. return article
  485. end
  486. raise Exceptions::UnprocessableEntity, 'invalid telegram message'
  487. end
  488. def to_group(params, group_id, channel)
  489. # begin import
  490. Rails.logger.debug { 'import message' }
  491. # map channel_post params to message
  492. if params[:channel_post]
  493. return if params[:channel_post][:new_chat_title] # happens when channel title is renamed, we use [:chat][:title] already, safely ignore this.
  494. # note: used .blank? which is a rails method. empty? does not work on integers (values like date, width, height) to check.
  495. # need delete_if to remove any empty hashes, .compact only removes keys with nil values.
  496. params[:message] = {
  497. document: {
  498. file_name: params.dig(:channel_post, :document, :file_name),
  499. mime_type: params.dig(:channel_post, :document, :mime_type),
  500. file_id: params.dig(:channel_post, :document, :file_id),
  501. file_size: params.dig(:channel_post, :document, :file_size),
  502. thumb: {
  503. file_id: params.dig(:channel_post, :document, :thumb, :file_id),
  504. file_size: params.dig(:channel_post, :document, :thumb, :file_size),
  505. width: params.dig(:channel_post, :document, :thumb, :width),
  506. height: params.dig(:channel_post, :document, :thumb, :height)
  507. }.compact
  508. }.delete_if { |_, v| v.blank? },
  509. video: {
  510. duration: params.dig(:channel_post, :video, :duration),
  511. width: params.dig(:channel_post, :video, :width),
  512. height: params.dig(:channel_post, :video, :height),
  513. mime_type: params.dig(:channel_post, :video, :mime_type),
  514. file_id: params.dig(:channel_post, :video, :file_id),
  515. file_size: params.dig(:channel_post, :video, :file_size),
  516. thumb: {
  517. file_id: params.dig(:channel_post, :video, :thumb, :file_id),
  518. file_size: params.dig(:channel_post, :video, :thumb, :file_size),
  519. width: params.dig(:channel_post, :video, :thumb, :width),
  520. height: params.dig(:channel_post, :video, :thumb, :height)
  521. }.compact
  522. }.delete_if { |_, v| v.blank? },
  523. voice: {
  524. duration: params.dig(:channel_post, :voice, :duration),
  525. mime_type: params.dig(:channel_post, :voice, :mime_type),
  526. file_id: params.dig(:channel_post, :voice, :file_id),
  527. file_size: params.dig(:channel_post, :voice, :file_size)
  528. }.compact,
  529. sticker: {
  530. width: params.dig(:channel_post, :sticker, :width),
  531. height: params.dig(:channel_post, :sticker, :height),
  532. emoji: params.dig(:channel_post, :sticker, :emoji),
  533. set_name: params.dig(:channel_post, :sticker, :set_name),
  534. file_id: params.dig(:channel_post, :sticker, :file_id),
  535. file_path: params.dig(:channel_post, :sticker, :file_path),
  536. file_size: params.dig(:channel_post, :sticker, :file_size),
  537. thumb: {
  538. file_id: params.dig(:channel_post, :sticker, :thumb, :file_id),
  539. file_size: params.dig(:channel_post, :sticker, :thumb, :file_size),
  540. width: params.dig(:channel_post, :sticker, :thumb, :width),
  541. height: params.dig(:channel_post, :sticker, :thumb, :height),
  542. file_path: params.dig(:channel_post, :sticker, :thumb, :file_path)
  543. }.compact
  544. }.delete_if { |_, v| v.blank? },
  545. chat: {
  546. id: params.dig(:channel_post, :chat, :id),
  547. first_name: params.dig(:channel_post, :chat, :title),
  548. last_name: 'Channel',
  549. username: "channel#{params.dig(:channel_post, :chat, :id)}"
  550. },
  551. from: {
  552. id: params.dig(:channel_post, :chat, :id),
  553. first_name: params.dig(:channel_post, :chat, :title),
  554. last_name: 'Channel',
  555. username: "channel#{params.dig(:channel_post, :chat, :id)}"
  556. },
  557. caption: (params.dig(:channel_post, :caption) || {}),
  558. date: params.dig(:channel_post, :date),
  559. message_id: params.dig(:channel_post, :message_id),
  560. text: params.dig(:channel_post, :text),
  561. photo: (params[:channel_post][:photo].map { |photo| { file_id: photo[:file_id], file_size: photo[:file_size], width: photo[:width], height: photo[:height] } } if params.dig(:channel_post, :photo))
  562. }.delete_if { |_, v| v.blank? }
  563. params.delete(:channel_post) # discard unused :channel_post hash
  564. end
  565. # checks if the channel post is being edited, and map it when it is
  566. if params[:edited_channel_post]
  567. # updates on telegram can only be on messages, no attachments
  568. params[:edited_message] = {
  569. chat: {
  570. id: params.dig(:edited_channel_post, :chat, :id),
  571. first_name: params.dig(:edited_channel_post, :chat, :title),
  572. last_name: 'Channel',
  573. username: "channel#{params.dig(:edited_channel_post, :chat, :id)}"
  574. },
  575. from: {
  576. id: params.dig(:edited_channel_post, :chat, :id),
  577. first_name: params.dig(:edited_channel_post, :chat, :title),
  578. last_name: 'Channel',
  579. username: "channel#{params.dig(:edited_channel_post, :chat, :id)}"
  580. },
  581. date: params.dig(:edited_channel_post, :date),
  582. edit_date: params.dig(:edited_channel_post, :edit_date),
  583. message_id: params.dig(:edited_channel_post, :message_id),
  584. text: params.dig(:edited_channel_post, :text)
  585. }
  586. params.delete(:edited_channel_post) # discard unused :edited_channel_post hash
  587. end
  588. # prevent multiple update
  589. if !params[:edited_message]
  590. return if Ticket::Article.exists?(message_id: Telegram.message_id(params))
  591. end
  592. # update article
  593. if params[:edited_message]
  594. article = Ticket::Article.find_by(message_id: Telegram.message_id(params))
  595. return if !article
  596. params[:message] = params[:edited_message]
  597. user = to_user(params)
  598. to_article(params, user, article.ticket, channel, article)
  599. return article
  600. end
  601. # send welcome message and don't create ticket
  602. text = params[:message][:text]
  603. if text.present? && text.start_with?('/start')
  604. message(params[:message][:chat][:id], channel.options[:welcome] || 'You are welcome! Just ask me something!', params[:message][:from][:language_code])
  605. return
  606. # find ticket and close it
  607. elsif text.present? && text.start_with?('/end')
  608. user = to_user(params)
  609. # get the last ticket of customer which is not closed yet, and close it
  610. state_ids = Ticket::State.where(name: %w[closed merged removed]).pluck(:id)
  611. possible_tickets = Ticket.where(customer_id: user.id).where.not(state_id: state_ids).order(:updated_at)
  612. ticket = possible_tickets.find_each.find { |possible_ticket| possible_ticket.preferences[:channel_id] == channel.id }
  613. return if !ticket
  614. ticket.state = Ticket::State.find_by(name: 'closed')
  615. ticket.save!
  616. return if !channel.options[:goodbye]
  617. message(params[:message][:chat][:id], channel.options[:goodbye], params[:message][:from][:language_code])
  618. return
  619. end
  620. ticket = nil
  621. # use transaction
  622. Transaction.execute(reset_user_id: true) do
  623. user = to_user(params)
  624. ticket = to_ticket(params, user, group_id, channel)
  625. to_article(params, user, ticket, channel)
  626. end
  627. ticket
  628. end
  629. def from_article(article)
  630. message = nil
  631. Rails.logger.debug { "Create telegram personal message from article to '#{article[:to]}'..." }
  632. message = {}
  633. # TODO: create telegram message here
  634. Rails.logger.debug { message.inspect }
  635. message
  636. end
  637. def get_file(params, file)
  638. # telegram bot files are limited up to 20MB
  639. # https://core.telegram.org/bots/api#getfile
  640. if !validate_file_size(file)
  641. message_text = 'Telegram file is to big. (Maximum 20mb)'
  642. message(params[:message][:chat][:id], "Sorry, we could not handle your message. #{message_text}", params[:message][:from][:language_code])
  643. raise Exceptions::UnprocessableEntity, message_text
  644. end
  645. result = download_file(file[:file_id])
  646. if !validate_download(result)
  647. message_text = 'Unable to get you file from bot.'
  648. message(params[:message][:chat][:id], "Sorry, we could not handle your message. #{message_text}", params[:message][:from][:language_code])
  649. raise Exceptions::UnprocessableEntity, message_text
  650. end
  651. result
  652. end
  653. def download_file(file_id)
  654. document = @api.getFile(file_id)
  655. url = "https://api.telegram.org/file/bot#{@token}/#{document['file_path']}"
  656. UserAgent.get(
  657. url,
  658. {},
  659. {
  660. open_timeout: 20,
  661. read_timeout: 40,
  662. },
  663. )
  664. end
  665. def validate_file_size(file)
  666. Rails.logger.error 'validate_file_size'
  667. Rails.logger.error file[:file_size]
  668. return false if file[:file_size] >= 20.megabytes
  669. true
  670. end
  671. def validate_download(result)
  672. return false if !result.success? || !result.body
  673. true
  674. end
  675. end