twitter_sync.rb 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969
  1. # Copyright (C) 2012-2015 Zammad Foundation, http://zammad-foundation.org/
  2. require 'http/uri'
  3. class TwitterSync
  4. attr_accessor :client
  5. def initialize(auth, payload = nil)
  6. @client = Twitter::REST::Client.new do |config|
  7. config.consumer_key = auth[:consumer_key]
  8. config.consumer_secret = auth[:consumer_secret]
  9. config.access_token = auth[:oauth_token] || auth[:access_token]
  10. config.access_token_secret = auth[:oauth_token_secret] || auth[:access_token_secret]
  11. end
  12. @payload = payload
  13. end
  14. def disconnect
  15. return if !@client
  16. @client = nil
  17. end
  18. def user(tweet)
  19. raise "Unknown tweet type '#{tweet.class}'" if tweet.class != Twitter::Tweet
  20. Rails.logger.debug { "Twitter sender for tweet (#{tweet.id}): found" }
  21. Rails.logger.debug { tweet.user.inspect }
  22. tweet.user
  23. end
  24. def to_user(tweet)
  25. Rails.logger.debug { 'Create user from tweet...' }
  26. Rails.logger.debug { tweet.inspect }
  27. # do tweet_user lookup
  28. tweet_user = user(tweet)
  29. auth = Authorization.find_by(uid: tweet_user.id, provider: 'twitter')
  30. # create or update user
  31. user_data = {
  32. image_source: tweet_user.profile_image_url.to_s,
  33. }
  34. if auth
  35. user = User.find(auth.user_id)
  36. map = {
  37. note: 'description',
  38. web: 'website',
  39. address: 'location',
  40. }
  41. # ignore if value is already set
  42. map.each do |target, source|
  43. next if user[target].present?
  44. new_value = tweet_user.send(source).to_s
  45. next if new_value.blank?
  46. user_data[target] = new_value
  47. end
  48. user.update!(user_data)
  49. else
  50. user_data[:login] = tweet_user.screen_name
  51. user_data[:firstname] = tweet_user.name
  52. user_data[:web] = tweet_user.website.to_s
  53. user_data[:note] = tweet_user.description
  54. user_data[:address] = tweet_user.location
  55. user_data[:active] = true
  56. user_data[:role_ids] = Role.signup_role_ids
  57. user = User.create!(user_data)
  58. end
  59. if user_data[:image_source]
  60. avatar = Avatar.add(
  61. object: 'User',
  62. o_id: user.id,
  63. url: user_data[:image_source],
  64. source: 'twitter',
  65. deletable: true,
  66. updated_by_id: user.id,
  67. created_by_id: user.id,
  68. )
  69. # update user link
  70. if avatar && user.image != avatar.store_hash
  71. user.image = avatar.store_hash
  72. user.save
  73. end
  74. end
  75. # create or update authorization
  76. auth_data = {
  77. uid: tweet_user.id,
  78. username: tweet_user.screen_name,
  79. user_id: user.id,
  80. provider: 'twitter'
  81. }
  82. if auth
  83. auth.update!(auth_data)
  84. else
  85. Authorization.create!(auth_data)
  86. end
  87. user
  88. end
  89. def to_ticket(tweet, user, group_id, channel)
  90. UserInfo.current_user_id = user.id
  91. Rails.logger.debug { 'Create ticket from tweet...' }
  92. Rails.logger.debug { tweet.inspect }
  93. Rails.logger.debug { user.inspect }
  94. Rails.logger.debug { group_id.inspect }
  95. # normalize message
  96. message = {}
  97. if tweet.class == Twitter::Tweet
  98. message = {
  99. type: 'tweet',
  100. text: tweet.text,
  101. }
  102. state = get_state(channel, tweet)
  103. end
  104. if tweet.is_a?(Hash) && tweet['type'] == 'message_create'
  105. message = {
  106. type: 'direct_message',
  107. text: tweet['message_create']['message_data']['text'],
  108. }
  109. state = get_state(channel, tweet)
  110. end
  111. if tweet.is_a?(Hash) && tweet['text'].present?
  112. message = {
  113. type: 'tweet',
  114. text: tweet['text'],
  115. }
  116. state = get_state(channel, tweet)
  117. end
  118. # process message
  119. if message[:type] == 'direct_message'
  120. ticket = Ticket.find_by(
  121. create_article_type: Ticket::Article::Type.lookup(name: 'twitter direct-message'),
  122. customer_id: user.id,
  123. state: Ticket::State.where.not(
  124. state_type_id: Ticket::StateType.where(
  125. name: %w[closed merged removed],
  126. )
  127. )
  128. )
  129. return ticket if ticket
  130. end
  131. # prepare title
  132. title = message[:text]
  133. if title.length > 80
  134. title = "#{title[0, 80]}..."
  135. end
  136. Ticket.create!(
  137. customer_id: user.id,
  138. title: title,
  139. group_id: group_id || Group.first.id,
  140. state: state,
  141. priority: Ticket::Priority.find_by(default_create: true),
  142. preferences: {
  143. channel_id: channel.id,
  144. channel_screen_name: channel.options['user']['screen_name'],
  145. },
  146. )
  147. end
  148. def to_article_webhook(item, user, ticket, channel)
  149. Rails.logger.debug { 'Create article from tweet...' }
  150. Rails.logger.debug { item.inspect }
  151. Rails.logger.debug { user.inspect }
  152. Rails.logger.debug { ticket.inspect }
  153. # import tweet
  154. to = nil
  155. from = nil
  156. text = nil
  157. message_id = nil
  158. article_type = nil
  159. in_reply_to = nil
  160. twitter_preferences = {}
  161. attachments = []
  162. if item['type'] == 'message_create'
  163. message_id = item['id']
  164. text = item['message_create']['message_data']['text']
  165. if item['message_create']['message_data']['entities'] && item['message_create']['message_data']['entities']['urls'].present?
  166. item['message_create']['message_data']['entities']['urls'].each do |local_url|
  167. next if local_url['url'].blank?
  168. if local_url['expanded_url'].present?
  169. text.gsub!(/#{Regexp.quote(local_url['url'])}/, local_url['expanded_url'])
  170. elsif local_url['display_url']
  171. text.gsub!(/#{Regexp.quote(local_url['url'])}/, local_url['display_url'])
  172. end
  173. end
  174. end
  175. app = get_app_webhook(item['message_create']['source_app_id'])
  176. article_type = 'twitter direct-message'
  177. recipient_screen_name = to_user_webhook_data(item['message_create']['target']['recipient_id'])['screen_name']
  178. sender_screen_name = to_user_webhook_data(item['message_create']['sender_id'])['screen_name']
  179. to = "@#{recipient_screen_name}"
  180. from = "@#{sender_screen_name}"
  181. twitter_preferences = {
  182. created_at: item['created_timestamp'],
  183. recipient_id: item['message_create']['target']['recipient_id'],
  184. recipient_screen_name: recipient_screen_name,
  185. sender_id: item['message_create']['sender_id'],
  186. sender_screen_name: sender_screen_name,
  187. app_id: app['app_id'],
  188. app_name: app['app_name'],
  189. }
  190. elsif item['text'].present?
  191. message_id = item['id']
  192. text = item['text']
  193. if item['extended_tweet'] && item['extended_tweet']['full_text'].present?
  194. text = item['extended_tweet']['full_text']
  195. end
  196. article_type = 'twitter status'
  197. sender_screen_name = item['user']['screen_name']
  198. from = "@#{sender_screen_name}"
  199. mention_ids = []
  200. if item['entities']
  201. item['entities']['user_mentions']&.each do |local_user|
  202. if !to
  203. to = ''
  204. else
  205. to += ', '
  206. end
  207. to += "@#{local_user['screen_name']}"
  208. mention_ids.push local_user['id']
  209. end
  210. item['entities']['media']&.each do |local_media|
  211. if local_media['url'].present?
  212. if local_media['expanded_url'].present?
  213. text.gsub!(/#{Regexp.quote(local_media['url'])}/, local_media['expanded_url'])
  214. elsif local_media['display_url']
  215. text.gsub!(/#{Regexp.quote(local_media['url'])}/, local_media['display_url'])
  216. end
  217. end
  218. url = local_media['media_url_https'] || local_media['media_url']
  219. next if url.blank?
  220. result = download_file(url)
  221. if !result.success? || !result.body
  222. Rails.logger.error "Unable for download image from twitter (#{url}): #{result.code}"
  223. next
  224. end
  225. attachment = {
  226. filename: url.sub(%r{^.*/(.+?)$}, '\1'),
  227. content: result.body,
  228. }
  229. attachments.push attachment
  230. end
  231. end
  232. in_reply_to = item['in_reply_to_status_id']
  233. twitter_preferences = {
  234. mention_ids: mention_ids,
  235. geo: item['geo'],
  236. retweeted: item['retweeted'],
  237. possibly_sensitive: item['possibly_sensitive'],
  238. in_reply_to_user_id: item['in_reply_to_user_id'],
  239. place: item['place'],
  240. retweet_count: item['retweet_count'],
  241. source: item['source'],
  242. favorited: item['favorited'],
  243. truncated: item['truncated'],
  244. }
  245. else
  246. raise "Unknown tweet type '#{item.class}'"
  247. end
  248. UserInfo.current_user_id = user.id
  249. # set ticket state to open if not new
  250. ticket_state = get_state(channel, item, ticket)
  251. if ticket_state.name != ticket.state.name
  252. ticket.state = ticket_state
  253. ticket.save!
  254. end
  255. article_preferences = {
  256. twitter: self.class.preferences_cleanup(twitter_preferences),
  257. links: [
  258. {
  259. url: "https://twitter.com/statuses/#{item['id']}",
  260. target: '_blank',
  261. name: 'on Twitter',
  262. },
  263. ],
  264. }
  265. article = Ticket::Article.create!(
  266. from: from,
  267. to: to,
  268. body: text,
  269. message_id: message_id,
  270. ticket_id: ticket.id,
  271. in_reply_to: in_reply_to,
  272. type_id: Ticket::Article::Type.find_by(name: article_type).id,
  273. sender_id: Ticket::Article::Sender.find_by(name: 'Customer').id,
  274. internal: false,
  275. preferences: self.class.preferences_cleanup(article_preferences),
  276. )
  277. attachments.each do |attachment|
  278. Store.add(
  279. object: 'Ticket::Article',
  280. o_id: article.id,
  281. data: attachment[:content],
  282. filename: attachment[:filename],
  283. preferences: {},
  284. )
  285. end
  286. end
  287. def to_article(tweet, user, ticket, channel)
  288. Rails.logger.debug { 'Create article from tweet...' }
  289. Rails.logger.debug { tweet.inspect }
  290. Rails.logger.debug { user.inspect }
  291. Rails.logger.debug { ticket.inspect }
  292. # import tweet
  293. to = nil
  294. from = nil
  295. article_type = nil
  296. in_reply_to = nil
  297. twitter_preferences = {}
  298. raise "Unknown tweet type '#{tweet.class}'" if tweet.class != Twitter::Tweet
  299. article_type = 'twitter status'
  300. from = "@#{tweet.user.screen_name}"
  301. mention_ids = []
  302. tweet.user_mentions&.each do |local_user|
  303. if !to
  304. to = ''
  305. else
  306. to += ', '
  307. end
  308. to += "@#{local_user.screen_name}"
  309. mention_ids.push local_user.id
  310. end
  311. in_reply_to = tweet.in_reply_to_status_id
  312. twitter_preferences = {
  313. mention_ids: mention_ids,
  314. geo: tweet.geo,
  315. retweeted: tweet.retweeted?,
  316. possibly_sensitive: tweet.possibly_sensitive?,
  317. in_reply_to_user_id: tweet.in_reply_to_user_id,
  318. place: tweet.place,
  319. retweet_count: tweet.retweet_count,
  320. source: tweet.source,
  321. favorited: tweet.favorited?,
  322. truncated: tweet.truncated?,
  323. }
  324. UserInfo.current_user_id = user.id
  325. # set ticket state to open if not new
  326. ticket_state = get_state(channel, tweet, ticket)
  327. if ticket_state.name != ticket.state.name
  328. ticket.state = ticket_state
  329. ticket.save!
  330. end
  331. article_preferences = {
  332. twitter: self.class.preferences_cleanup(twitter_preferences),
  333. links: [
  334. {
  335. url: "https://twitter.com/statuses/#{tweet.id}",
  336. target: '_blank',
  337. name: 'on Twitter',
  338. },
  339. ],
  340. }
  341. Ticket::Article.create!(
  342. from: from,
  343. to: to,
  344. body: tweet.text,
  345. message_id: tweet.id,
  346. ticket_id: ticket.id,
  347. in_reply_to: in_reply_to,
  348. type_id: Ticket::Article::Type.find_by(name: article_type).id,
  349. sender_id: Ticket::Article::Sender.find_by(name: 'Customer').id,
  350. internal: false,
  351. preferences: self.class.preferences_cleanup(article_preferences),
  352. )
  353. end
  354. def to_group(tweet, group_id, channel)
  355. Rails.logger.debug { 'import tweet' }
  356. ticket = nil
  357. Transaction.execute(reset_user_id: true) do
  358. # check if parent exists
  359. user = to_user(tweet)
  360. raise "Unknown tweet type '#{tweet.class}'" if tweet.class != Twitter::Tweet
  361. if tweet.in_reply_to_status_id && tweet.in_reply_to_status_id.to_s != ''
  362. existing_article = Ticket::Article.find_by(message_id: tweet.in_reply_to_status_id)
  363. if existing_article
  364. ticket = existing_article.ticket
  365. else
  366. begin
  367. parent_tweet = @client.status(tweet.in_reply_to_status_id)
  368. ticket = to_group(parent_tweet, group_id, channel)
  369. rescue Twitter::Error::NotFound, Twitter::Error::Forbidden => e
  370. # just ignore if tweet has already gone
  371. Rails.logger.info "Can't import tweet (#{tweet.in_reply_to_status_id}), #{e.message}"
  372. end
  373. end
  374. end
  375. if !ticket
  376. ticket = to_ticket(tweet, user, group_id, channel)
  377. end
  378. to_article(tweet, user, ticket, channel)
  379. end
  380. ticket
  381. end
  382. =begin
  383. create a tweet ot direct message from an article
  384. =end
  385. def from_article(article)
  386. tweet = nil
  387. if article[:type] == 'twitter direct-message'
  388. Rails.logger.debug { "Create twitter direct message from article to '#{article[:to]}'..." }
  389. # tweet = @client.create_direct_message(
  390. # article[:to],
  391. # article[:body],
  392. # {}
  393. # )
  394. article[:to].delete!('@')
  395. authorization = Authorization.find_by(provider: 'twitter', username: article[:to])
  396. raise "Unable to lookup user_id for @#{article[:to]}" if !authorization
  397. data = {
  398. event: {
  399. type: 'message_create',
  400. message_create: {
  401. target: {
  402. recipient_id: authorization.uid,
  403. },
  404. message_data: {
  405. text: article[:body],
  406. }
  407. }
  408. }
  409. }
  410. tweet = Twitter::REST::Request.new(@client, :json_post, '/1.1/direct_messages/events/new.json', data).perform
  411. elsif article[:type] == 'twitter status'
  412. Rails.logger.debug { 'Create tweet from article...' }
  413. tweet = @client.update(
  414. article[:body],
  415. {
  416. in_reply_to_status_id: article[:in_reply_to]
  417. }
  418. )
  419. else
  420. raise "Can't handle unknown twitter article type '#{article[:type]}'."
  421. end
  422. Rails.logger.debug { tweet.inspect }
  423. tweet
  424. end
  425. def get_state(channel, tweet, ticket = nil)
  426. user_id = nil
  427. user_id = if tweet.is_a?(Hash)
  428. if tweet['user'] && tweet['user']['id']
  429. tweet['user']['id']
  430. else
  431. tweet['message_create']['sender_id']
  432. end
  433. else
  434. user(tweet).id
  435. end
  436. # no changes in post is from page user it self
  437. if channel.options[:user][:id].to_s == user_id.to_s
  438. if !ticket
  439. return Ticket::State.find_by(name: 'closed') if !ticket
  440. end
  441. return ticket.state
  442. end
  443. state = Ticket::State.find_by(default_create: true)
  444. return state if !ticket
  445. return ticket.state if ticket.state_id == state.id
  446. Ticket::State.find_by(default_follow_up: true)
  447. end
  448. def tweet_limit_reached(tweet, factor = 1)
  449. max_count = 120
  450. max_count = max_count * factor
  451. type_id = Ticket::Article::Type.lookup(name: 'twitter status').id
  452. created_at = Time.zone.now - 15.minutes
  453. created_count = Ticket::Article.where('created_at > ? AND type_id = ?', created_at, type_id).count
  454. if created_count > max_count
  455. Rails.logger.info "Tweet limit of #{created_count}/#{max_count} reached, ignored tweed id (#{tweet.id})"
  456. return true
  457. end
  458. false
  459. end
  460. def direct_message_limit_reached(tweet, factor = 1)
  461. max_count = 100
  462. max_count = max_count * factor
  463. type_id = Ticket::Article::Type.lookup(name: 'twitter direct-message').id
  464. created_at = Time.zone.now - 15.minutes
  465. created_count = Ticket::Article.where('created_at > ? AND type_id = ?', created_at, type_id).count
  466. if created_count > max_count
  467. Rails.logger.info "Tweet direct message limit reached #{created_count}/#{max_count}, ignored tweed id (#{tweet.id})"
  468. return true
  469. end
  470. false
  471. end
  472. =begin
  473. replace Twitter::Place and Twitter::Geo as hash and replace Twitter::NullObject with nil
  474. preferences = TwitterSync.preferences_cleanup(
  475. twitter: twitter_preferences,
  476. links: [
  477. {
  478. url: 'https://twitter.com/statuses/123',
  479. target: '_blank',
  480. name: 'on Twitter',
  481. },
  482. ],
  483. )
  484. or
  485. preferences = {
  486. twitter: TwitterSync.preferences_cleanup(twitter_preferences),
  487. links: [
  488. {
  489. url: 'https://twitter.com/statuses/123',
  490. target: '_blank',
  491. name: 'on Twitter',
  492. },
  493. ],
  494. }
  495. =end
  496. def self.preferences_cleanup(preferences)
  497. # replace Twitter::NullObject with nill to prevent elasticsearch index issue
  498. preferences.each do |key, value|
  499. if value.class == Twitter::Place || value.class == Twitter::Geo
  500. preferences[key] = value.to_h
  501. next
  502. end
  503. if value.class == Twitter::NullObject
  504. preferences[key] = nil
  505. next
  506. end
  507. next if !value.is_a?(Hash)
  508. value.each do |sub_key, sub_level|
  509. if sub_level.class == NilClass
  510. value[sub_key] = nil
  511. next
  512. end
  513. if sub_level.class == Twitter::Place || sub_level.class == Twitter::Geo
  514. value[sub_key] = sub_level.to_h
  515. next
  516. end
  517. next if sub_level.class != Twitter::NullObject
  518. value[sub_key] = nil
  519. end
  520. end
  521. if preferences[:twitter]
  522. if preferences[:twitter][:geo].blank?
  523. preferences[:twitter][:geo] = {}
  524. end
  525. if preferences[:twitter][:place].blank?
  526. preferences[:twitter][:place] = {}
  527. end
  528. else
  529. if preferences[:geo].blank?
  530. preferences[:geo] = {}
  531. end
  532. if preferences[:place].blank?
  533. preferences[:place] = {}
  534. end
  535. end
  536. preferences
  537. end
  538. =begin
  539. check if tweet is from local sender
  540. client = TwitterSync.new
  541. client.locale_sender?(tweet)
  542. =end
  543. def locale_sender?(tweet)
  544. tweet_user = user(tweet)
  545. Channel.where(area: 'Twitter::Account').each do |local_channel|
  546. next if !local_channel.options
  547. next if !local_channel.options[:user]
  548. next if !local_channel.options[:user][:id]
  549. next if local_channel.options[:user][:id].to_s != tweet_user.id.to_s
  550. Rails.logger.debug { "Tweet is sent by local account with user id #{tweet_user.id} and tweet.id #{tweet.id}" }
  551. return true
  552. end
  553. false
  554. end
  555. =begin
  556. process webhook messages from twitter
  557. client = TwitterSync.new
  558. client.process_webhook(channel)
  559. =end
  560. def process_webhook(channel)
  561. Rails.logger.debug { 'import tweet' }
  562. ticket = nil
  563. if @payload['direct_message_events'].present? && channel.options[:sync][:direct_messages][:group_id].present?
  564. @payload['direct_message_events'].each do |item|
  565. next if item['type'] != 'message_create'
  566. next if Ticket::Article.find_by(message_id: item['id'])
  567. user = to_user_webhook(item['message_create']['sender_id'])
  568. ticket = to_ticket(item, user, channel.options[:sync][:direct_messages][:group_id], channel)
  569. to_article_webhook(item, user, ticket, channel)
  570. end
  571. end
  572. if @payload['tweet_create_events'].present?
  573. @payload['tweet_create_events'].each do |item|
  574. next if Ticket::Article.find_by(message_id: item['id'])
  575. # check if it's mention
  576. group_id = nil
  577. if channel.options[:sync][:mentions][:group_id].present? && item['entities']['user_mentions']
  578. item['entities']['user_mentions'].each do |local_user|
  579. next if channel.options[:user][:id].to_s != local_user['id'].to_s
  580. group_id = channel.options[:sync][:mentions][:group_id]
  581. break
  582. end
  583. end
  584. # check if it's search term
  585. if !group_id && channel.options[:sync][:search].present?
  586. channel.options[:sync][:search].each do |local_search|
  587. next if local_search[:term].blank?
  588. next if local_search[:group_id].blank?
  589. next if item['text'] !~ /#{Regexp.quote(local_search[:term])}/i
  590. group_id = local_search[:group_id]
  591. break
  592. end
  593. end
  594. next if !group_id
  595. user = to_user_webhook(item['user']['id'], item['user'])
  596. if item['in_reply_to_status_id'].present?
  597. existing_article = Ticket::Article.find_by(message_id: item['in_reply_to_status_id'])
  598. if existing_article
  599. ticket = existing_article.ticket
  600. else
  601. begin
  602. parent_tweet = @client.status(item['in_reply_to_status_id'])
  603. ticket = to_group(parent_tweet, group_id, channel)
  604. rescue Twitter::Error::NotFound, Twitter::Error::Forbidden => e
  605. # just ignore if tweet has already gone
  606. Rails.logger.info "Can't import tweet (#{item['in_reply_to_status_id']}), #{e.message}"
  607. end
  608. end
  609. end
  610. if !ticket
  611. ticket = to_ticket(item, user, group_id, channel)
  612. end
  613. to_article_webhook(item, user, ticket, channel)
  614. end
  615. end
  616. ticket
  617. end
  618. def get_app_webhook(app_id)
  619. return {} if !@payload['apps']
  620. return {} if !@payload['apps'][app_id]
  621. @payload['apps'][app_id]
  622. end
  623. def to_user_webhook_data(user_id)
  624. if @payload['user'] && @payload['user']['id'].to_s == user_id.to_s
  625. return @payload['user']
  626. end
  627. raise 'no users in payload' if !@payload['users']
  628. raise 'no users in payload' if !@payload['users'][user_id]
  629. @payload['users'][user_id]
  630. end
  631. =begin
  632. download public media file from twitter
  633. client = TwitterSync.new
  634. result = client.download_file(url)
  635. result.body
  636. =end
  637. def download_file(url)
  638. UserAgent.get(
  639. url,
  640. {},
  641. {
  642. open_timeout: 20,
  643. read_timeout: 40,
  644. },
  645. )
  646. end
  647. def to_user_webhook(user_id, payload_user = nil)
  648. user_payload = if payload_user && payload_user['id'].to_s == user_id.to_s
  649. payload_user
  650. else
  651. to_user_webhook_data(user_id)
  652. end
  653. auth = Authorization.find_by(uid: user_payload['id'], provider: 'twitter')
  654. # create or update user
  655. user_data = {
  656. image_source: user_payload['profile_image_url'],
  657. }
  658. if auth
  659. user = User.find(auth.user_id)
  660. map = {
  661. note: 'description',
  662. web: 'url',
  663. address: 'location',
  664. }
  665. # ignore if value is already set
  666. map.each do |target, _source|
  667. next if user[target].present?
  668. new_value = user_payload['source'].to_s
  669. next if new_value.blank?
  670. user_data[target] = new_value
  671. end
  672. user.update!(user_data)
  673. else
  674. user_data[:login] = user_payload['screen_name']
  675. user_data[:firstname] = user_payload['name']
  676. user_data[:web] = user_payload['url']
  677. user_data[:note] = user_payload['description']
  678. user_data[:address] = user_payload['location']
  679. user_data[:active] = true
  680. user_data[:role_ids] = Role.signup_role_ids
  681. user = User.create!(user_data)
  682. end
  683. if user_data[:image_source].present?
  684. avatar = Avatar.add(
  685. object: 'User',
  686. o_id: user.id,
  687. url: user_data[:image_source],
  688. source: 'twitter',
  689. deletable: true,
  690. updated_by_id: user.id,
  691. created_by_id: user.id,
  692. )
  693. # update user link
  694. if avatar && user.image != avatar.store_hash
  695. user.image = avatar.store_hash
  696. user.save
  697. end
  698. end
  699. # create or update authorization
  700. auth_data = {
  701. uid: user_payload['id'],
  702. username: user_payload['screen_name'],
  703. user_id: user.id,
  704. provider: 'twitter'
  705. }
  706. if auth
  707. auth.update!(auth_data)
  708. else
  709. Authorization.create!(auth_data)
  710. end
  711. user
  712. end
  713. =begin
  714. get the user of current twitter client
  715. client = TwitterSync.new
  716. user_hash = client.who_am_i
  717. =end
  718. def who_am_i
  719. @client.user
  720. end
  721. =begin
  722. request a new webhook verification request from twitter
  723. client = TwitterSync.new
  724. webhook_request_verification(webhook_id, env_name, webhook_url)
  725. =end
  726. def webhook_request_verification(webhook_id, env_name, webhook_url)
  727. Twitter::REST::Request.new(@client, :put, "/1.1/account_activity/all/#{env_name}/webhooks/#{webhook_id}.json", {}).perform
  728. rescue => e
  729. raise "Webhook registered but not valid (#{webhook_url}). Unable to set webhook to valid: #{e.message}"
  730. end
  731. =begin
  732. get webhooks by env_name
  733. client = TwitterSync.new
  734. webhooks = webhooks_by_env_name(env_name)
  735. =end
  736. def webhooks_by_env_name(env_name)
  737. Twitter::REST::Request.new(@client, :get, "/1.1/account_activity/all/#{env_name}/webhooks.json", {}).perform
  738. end
  739. =begin
  740. get all webhooks
  741. client = TwitterSync.new
  742. webhooks = webhooks(env_name)
  743. =end
  744. def webhooks
  745. Twitter::REST::Request.new(@client, :get, '/1.1/account_activity/all/webhooks.json', {}).perform
  746. end
  747. =begin
  748. delete a webhooks
  749. client = TwitterSync.new
  750. webhook_delete(webhook_id)
  751. =end
  752. def webhook_delete(webhook_id)
  753. Twitter::REST::Request.new(@client, :delete, "/1.1/account_activity/all/#{env_name}/webhooks/#{webhook_id}.json", {}).perform
  754. end
  755. =begin
  756. register a new webhooks at twitter
  757. client = TwitterSync.new
  758. webhook_register(env_name, webhook_url)
  759. =end
  760. def webhook_register(env_name, webhook_url)
  761. options = {
  762. url: webhook_url,
  763. }
  764. begin
  765. response = Twitter::REST::Request.new(@client, :post, "/1.1/account_activity/all/#{env_name}/webhooks.json", options).perform
  766. rescue => e
  767. message = "Unable to register webhook: #{e.message}"
  768. if %r{http://}.match?(webhook_url)
  769. message += ' Only https webhooks possible to register.'
  770. elsif webhooks.count.positive?
  771. message += " Already #{webhooks.count} webhooks registered. Maybe you need to delete one first."
  772. end
  773. raise message
  774. end
  775. response
  776. end
  777. =begin
  778. subscribe a user to a webhooks at twitter
  779. client = TwitterSync.new
  780. webhook_subscribe(env_name)
  781. =end
  782. def webhook_subscribe(env_name)
  783. Twitter::REST::Request.new(@client, :post, "/1.1/account_activity/all/#{env_name}/subscriptions.json", {}).perform
  784. rescue => e
  785. raise "Unable to subscriptions with via webhook: #{e.message}"
  786. end
  787. end