twitter.rb 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. # Copyright (C) 2012-2015 Zammad Foundation, http://zammad-foundation.org/
  2. class Channel::Driver::Twitter
  3. =begin
  4. fetch tweets from twitter account
  5. options = {
  6. adapter: 'twitter',
  7. auth: {
  8. consumer_key: consumer_key,
  9. consumer_secret: consumer_secret,
  10. oauth_token: armin_theo_token,
  11. oauth_token_secret: armin_theo_token_secret,
  12. },
  13. sync: {
  14. search: [
  15. {
  16. term: '#citheo42',
  17. group_id: 2,
  18. },
  19. {
  20. term: '#citheo24',
  21. group_id: 1,
  22. },
  23. ],
  24. mentions: {
  25. group_id: 2,
  26. },
  27. direct_messages: {
  28. group_id: 2,
  29. }
  30. }
  31. }
  32. instance = Channel::Driver::Twitter.new
  33. result = instance.fetch(options, channel)
  34. returns
  35. {
  36. result: 'ok',
  37. }
  38. =end
  39. def fetch(options, channel)
  40. options = check_external_credential(options)
  41. @rest_client = TweetRest.new(options[:auth])
  42. @sync = options[:sync]
  43. @channel = channel
  44. Rails.logger.debug { 'twitter fetch started' }
  45. fetch_mentions
  46. fetch_search
  47. fetch_direct_messages
  48. disconnect
  49. Rails.logger.debug { 'twitter fetch completed' }
  50. {
  51. result: 'ok',
  52. notice: '',
  53. }
  54. end
  55. =begin
  56. instance = Channel::Driver::Twitter.new
  57. instance.fetchable?(channel)
  58. =end
  59. def fetchable?(channel)
  60. return true if Rails.env.test?
  61. # only fetch once in 30 minutes
  62. return true if !channel.preferences
  63. return true if !channel.preferences[:last_fetch]
  64. return false if channel.preferences[:last_fetch] > Time.zone.now - 20.minutes
  65. true
  66. end
  67. =begin
  68. instance = Channel::Driver::Twitter.new
  69. instance.send(
  70. {
  71. adapter: 'twitter',
  72. auth: {
  73. consumer_key: consumer_key,
  74. consumer_secret: consumer_secret,
  75. oauth_token: armin_theo_token,
  76. oauth_token_secret: armin_theo_token_secret,
  77. },
  78. },
  79. twitter_attributes,
  80. notification
  81. )
  82. =end
  83. def send(options, article, _notification = false)
  84. # return if we run import mode
  85. return if Setting.get('import_mode')
  86. options = check_external_credential(options)
  87. @rest_client = TweetRest.new(options[:auth])
  88. tweet = @rest_client.from_article(article)
  89. disconnect
  90. tweet
  91. end
  92. def disconnect
  93. @stream_client&.disconnect
  94. @rest_client&.disconnect
  95. end
  96. =begin
  97. Channel::Driver::Twitter.streamable?
  98. returns
  99. true|false
  100. =end
  101. def self.streamable?
  102. true
  103. end
  104. =begin
  105. create stream endpoint form twitter account
  106. options = {
  107. adapter: 'twitter',
  108. auth: {
  109. consumer_key: consumer_key,
  110. consumer_secret: consumer_secret,
  111. oauth_token: armin_theo_token,
  112. oauth_token_secret: armin_theo_token_secret,
  113. },
  114. sync: {
  115. search: [
  116. {
  117. term: '#citheo42',
  118. group_id: 2,
  119. },
  120. {
  121. term: '#citheo24',
  122. group_id: 1,
  123. },
  124. ],
  125. mentions: {
  126. group_id: 2,
  127. },
  128. direct_messages: {
  129. group_id: 2,
  130. }
  131. }
  132. }
  133. instance = Channel::Driver::Twitter.new
  134. stream_instance = instance.stream_instance(channel)
  135. returns
  136. instance_of_stream_handle
  137. =end
  138. def stream_instance(channel)
  139. @channel = channel
  140. options = @channel.options
  141. @stream_client = TweetStream.new(options[:auth])
  142. end
  143. =begin
  144. stream tweets from twitter account
  145. instance.stream
  146. returns
  147. # endless loop
  148. =end
  149. def stream
  150. sleep_on_unauthorized = 65
  151. 2.times do |loop_count|
  152. begin
  153. stream_start
  154. rescue Twitter::Error::Unauthorized => e
  155. Rails.logger.info "Unable to stream, try #{loop_count}, error #{e.inspect}"
  156. if loop_count >= 2
  157. raise "Unable to stream, try #{loop_count}, error #{e.inspect}"
  158. end
  159. Rails.logger.info "wait for #{sleep_on_unauthorized} sec. and try it again"
  160. sleep sleep_on_unauthorized
  161. end
  162. end
  163. end
  164. def stream_start
  165. sync = @channel.options['sync']
  166. raise 'Need channel.options[\'sync\'] for account, but no params found' if !sync
  167. filter = {}
  168. if sync['search']
  169. hashtags = []
  170. sync['search'].each do |item|
  171. next if item['term'].blank?
  172. next if item['term'] == '#'
  173. next if item['group_id'].blank?
  174. hashtags.push item['term']
  175. end
  176. filter[:track] = hashtags.join(',')
  177. end
  178. if sync['mentions'] && sync['mentions']['group_id'] != ''
  179. filter[:replies] = 'all'
  180. end
  181. return if filter.blank?
  182. @stream_client.client.user(filter) do |tweet|
  183. next if tweet.class != Twitter::Tweet && tweet.class != Twitter::DirectMessage
  184. # wait until own posts are stored in local database to prevent importing own tweets
  185. next if @stream_client.locale_sender?(tweet) && own_tweet_already_imported?(tweet)
  186. next if Ticket::Article.find_by(message_id: tweet.id)
  187. # check direct message
  188. if tweet.class == Twitter::DirectMessage
  189. if sync['direct_messages'] && sync['direct_messages']['group_id'] != ''
  190. next if @stream_client.direct_message_limit_reached(tweet, 2)
  191. @stream_client.to_group(tweet, sync['direct_messages']['group_id'], @channel)
  192. end
  193. next
  194. end
  195. next if !track_retweets? && tweet.retweet?
  196. next if @stream_client.tweet_limit_reached(tweet, 2)
  197. # check if it's mention
  198. if sync['mentions'] && sync['mentions']['group_id'].present?
  199. hit = false
  200. tweet.user_mentions&.each do |user|
  201. if user.id.to_s == @channel.options['user']['id'].to_s
  202. hit = true
  203. end
  204. end
  205. if hit
  206. @stream_client.to_group(tweet, sync['mentions']['group_id'], @channel)
  207. next
  208. end
  209. end
  210. # check hashtags
  211. if sync['search'] && tweet.hashtags
  212. hit = false
  213. sync['search'].each do |item|
  214. next if item['term'].blank?
  215. next if item['term'] == '#'
  216. next if item['group_id'].blank?
  217. tweet.hashtags.each do |hashtag|
  218. next if item['term'] !~ /^#/
  219. if item['term'].sub(/^#/, '') == hashtag.text
  220. hit = item
  221. end
  222. end
  223. end
  224. if hit
  225. @stream_client.to_group(tweet, hit['group_id'], @channel)
  226. next
  227. end
  228. end
  229. # check stings
  230. if sync['search']
  231. hit = false
  232. body = tweet.text
  233. sync['search'].each do |item|
  234. next if item['term'].blank?
  235. next if item['term'] == '#'
  236. next if item['group_id'].blank?
  237. if body.match?(/#{item['term']}/)
  238. hit = item
  239. end
  240. end
  241. if hit
  242. @stream_client.to_group(tweet, hit['group_id'], @channel)
  243. end
  244. end
  245. end
  246. end
  247. private
  248. def fetch_search
  249. return if @sync[:search].blank?
  250. @sync[:search].each do |search|
  251. next if search[:term].blank?
  252. next if search[:term] == '#'
  253. next if search[:group_id].blank?
  254. result_type = search[:type] || 'mixed'
  255. Rails.logger.debug { " - searching for '#{search[:term]}'" }
  256. older_import = 0
  257. older_import_max = 20
  258. @rest_client.client.search(search[:term], result_type: result_type).collect do |tweet|
  259. next if !track_retweets? && tweet.retweet?
  260. # ignore older messages
  261. if (@channel.created_at - 15.days) > tweet.created_at.dup.utc || older_import >= older_import_max
  262. older_import += 1
  263. Rails.logger.debug { "tweet to old: #{tweet.id}/#{tweet.created_at}" }
  264. next
  265. end
  266. next if @rest_client.locale_sender?(tweet) && own_tweet_already_imported?(tweet)
  267. next if Ticket::Article.find_by(message_id: tweet.id)
  268. break if @rest_client.tweet_limit_reached(tweet)
  269. @rest_client.to_group(tweet, search[:group_id], @channel)
  270. end
  271. end
  272. end
  273. def fetch_mentions
  274. return if @sync[:mentions].blank?
  275. return if @sync[:mentions][:group_id].blank?
  276. Rails.logger.debug { ' - searching for mentions' }
  277. older_import = 0
  278. older_import_max = 20
  279. @rest_client.client.mentions_timeline.each do |tweet|
  280. next if !track_retweets? && tweet.retweet?
  281. # ignore older messages
  282. if (@channel.created_at - 15.days) > tweet.created_at.dup.utc || older_import >= older_import_max
  283. older_import += 1
  284. Rails.logger.debug { "tweet to old: #{tweet.id}/#{tweet.created_at}" }
  285. next
  286. end
  287. next if Ticket::Article.find_by(message_id: tweet.id)
  288. break if @rest_client.tweet_limit_reached(tweet)
  289. @rest_client.to_group(tweet, @sync[:mentions][:group_id], @channel)
  290. end
  291. end
  292. def fetch_direct_messages
  293. return if @sync[:direct_messages].blank?
  294. return if @sync[:direct_messages][:group_id].blank?
  295. Rails.logger.debug { ' - searching for direct_messages' }
  296. older_import = 0
  297. older_import_max = 20
  298. @rest_client.client.direct_messages(full_text: 'true').each do |tweet|
  299. # ignore older messages
  300. if (@channel.created_at - 15.days) > tweet.created_at.dup.utc || older_import >= older_import_max
  301. older_import += 1
  302. Rails.logger.debug { "tweet to old: #{tweet.id}/#{tweet.created_at}" }
  303. next
  304. end
  305. next if Ticket::Article.find_by(message_id: tweet.id)
  306. break if @rest_client.direct_message_limit_reached(tweet)
  307. @rest_client.to_group(tweet, @sync[:direct_messages][:group_id], @channel)
  308. end
  309. end
  310. def check_external_credential(options)
  311. if options[:auth] && options[:auth][:external_credential_id]
  312. external_credential = ExternalCredential.find_by(id: options[:auth][:external_credential_id])
  313. raise "No such ExternalCredential.find(#{options[:auth][:external_credential_id]})" if !external_credential
  314. options[:auth][:consumer_key] = external_credential.credentials['consumer_key']
  315. options[:auth][:consumer_secret] = external_credential.credentials['consumer_secret']
  316. end
  317. options
  318. end
  319. def track_retweets?
  320. @channel.options && @channel.options['sync'] && @channel.options['sync']['track_retweets']
  321. end
  322. def own_tweet_already_imported?(tweet)
  323. event_time = Time.zone.now
  324. sleep 4
  325. 12.times do |loop_count|
  326. if Ticket::Article.find_by(message_id: tweet.id)
  327. Rails.logger.debug { "Own tweet already imported, skipping tweet #{tweet.id}" }
  328. return true
  329. end
  330. count = Delayed::Job.where('created_at < ?', event_time).count
  331. break if count.zero?
  332. sleep_time = 2 * count
  333. sleep_time = 5 if sleep_time > 5
  334. Rails.logger.debug { "Delay importing own tweets - sleep #{sleep_time} (loop #{loop_count})" }
  335. sleep sleep_time
  336. end
  337. if Ticket::Article.find_by(message_id: tweet.id)
  338. Rails.logger.debug { "Own tweet already imported, skipping tweet #{tweet.id}" }
  339. return true
  340. end
  341. false
  342. end
  343. end