twitter.rb 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  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 if @stream_client
  94. @rest_client.disconnect if @rest_client
  95. end
  96. =begin
  97. create stream endpoint form twitter account
  98. options = {
  99. adapter: 'twitter',
  100. auth: {
  101. consumer_key: consumer_key,
  102. consumer_secret: consumer_secret,
  103. oauth_token: armin_theo_token,
  104. oauth_token_secret: armin_theo_token_secret,
  105. },
  106. sync: {
  107. search: [
  108. {
  109. term: '#citheo42',
  110. group_id: 2,
  111. },
  112. {
  113. term: '#citheo24',
  114. group_id: 1,
  115. },
  116. ],
  117. mentions: {
  118. group_id: 2,
  119. },
  120. direct_messages: {
  121. group_id: 2,
  122. }
  123. }
  124. }
  125. instance = Channel::Driver::Twitter.new
  126. stream_instance = instance.stream_instance(channel)
  127. returns
  128. instance_of_stream_handle
  129. =end
  130. def stream_instance(channel)
  131. @channel = channel
  132. options = @channel.options
  133. @stream_client = TweetStream.new(options[:auth])
  134. end
  135. =begin
  136. stream tweets from twitter account
  137. instance.stream
  138. returns
  139. # endless loop
  140. =end
  141. def stream
  142. sleep_on_unauthorized = 61
  143. 2.times { |loop_count|
  144. begin
  145. stream_start
  146. rescue Twitter::Error::Unauthorized => e
  147. Rails.logger.info "Unable to stream, try #{loop_count}, error #{e.inspect}"
  148. if loop_count < 2
  149. Rails.logger.info "wait for #{sleep_on_unauthorized} sec. and try it again"
  150. sleep sleep_on_unauthorized
  151. else
  152. raise "Unable to stream, try #{loop_count}, error #{e.inspect}"
  153. end
  154. end
  155. }
  156. end
  157. def stream_start
  158. sync = @channel.options['sync']
  159. raise 'Need channel.options[\'sync\'] for account, but no params found' if !sync
  160. filter = {}
  161. if sync['search']
  162. hashtags = []
  163. sync['search'].each { |item|
  164. hashtags.push item['term']
  165. }
  166. filter[:track] = hashtags.join(',')
  167. end
  168. if sync['mentions'] && sync['mentions']['group_id'] != ''
  169. filter[:replies] = 'all'
  170. end
  171. return if filter.empty?
  172. @stream_client.client.user(filter) do |tweet|
  173. next if tweet.class != Twitter::Tweet && tweet.class != Twitter::DirectMessage
  174. # wait until own posts are stored in local database to prevent importing own tweets
  175. next if @stream_client.locale_sender?(tweet) && own_tweet_already_imported?(tweet)
  176. next if Ticket::Article.find_by(message_id: tweet.id)
  177. # check direct message
  178. if tweet.class == Twitter::DirectMessage
  179. if sync['direct_messages'] && sync['direct_messages']['group_id'] != ''
  180. next if @stream_client.direct_message_limit_reached(tweet, 2)
  181. @stream_client.to_group(tweet, sync['direct_messages']['group_id'], @channel)
  182. end
  183. next
  184. end
  185. next if !track_retweets? && tweet.retweet?
  186. next if @stream_client.tweet_limit_reached(tweet, 2)
  187. # check if it's mention
  188. if sync['mentions'] && sync['mentions']['group_id'] != ''
  189. hit = false
  190. if tweet.user_mentions
  191. tweet.user_mentions.each { |user|
  192. if user.id.to_s == @channel.options['user']['id'].to_s
  193. hit = true
  194. end
  195. }
  196. end
  197. if hit
  198. @stream_client.to_group(tweet, sync['mentions']['group_id'], @channel)
  199. next
  200. end
  201. end
  202. # check hashtags
  203. if sync['search'] && tweet.hashtags
  204. hit = false
  205. sync['search'].each { |item|
  206. tweet.hashtags.each { |hashtag|
  207. next if item['term'] !~ /^#/
  208. if item['term'].sub(/^#/, '') == hashtag.text
  209. hit = item
  210. end
  211. }
  212. }
  213. if hit
  214. @stream_client.to_group(tweet, hit['group_id'], @channel)
  215. next
  216. end
  217. end
  218. # check stings
  219. if sync['search']
  220. hit = false
  221. body = tweet.text
  222. sync['search'].each { |item|
  223. next if item['term'] =~ /^#/
  224. if body =~ /#{item['term']}/
  225. hit = item
  226. end
  227. }
  228. if hit
  229. @stream_client.to_group(tweet, hit['group_id'], @channel)
  230. end
  231. end
  232. end
  233. end
  234. private
  235. def fetch_search
  236. return if @sync[:search].blank?
  237. @sync[:search].each { |search|
  238. next if search[:term].blank?
  239. next if search[:group_id].blank?
  240. result_type = search[:type] || 'mixed'
  241. Rails.logger.debug " - searching for '#{search[:term]}'"
  242. older_import = 0
  243. older_import_max = 20
  244. @rest_client.client.search(search[:term], result_type: result_type).collect { |tweet|
  245. next if !track_retweets? && tweet.retweet?
  246. # ignore older messages
  247. if (@channel.created_at - 15.days) > tweet.created_at || older_import >= older_import_max
  248. older_import += 1
  249. Rails.logger.debug "tweet to old: #{tweet.id}/#{tweet.created_at}"
  250. next
  251. end
  252. next if @rest_client.locale_sender?(tweet) && own_tweet_already_imported?(tweet)
  253. next if Ticket::Article.find_by(message_id: tweet.id)
  254. break if @rest_client.tweet_limit_reached(tweet)
  255. @rest_client.to_group(tweet, search[:group_id], @channel)
  256. }
  257. }
  258. end
  259. def fetch_mentions
  260. return if @sync[:mentions].blank?
  261. return if @sync[:mentions][:group_id].blank?
  262. Rails.logger.debug ' - searching for mentions'
  263. older_import = 0
  264. older_import_max = 20
  265. @rest_client.client.mentions_timeline.each { |tweet|
  266. next if !track_retweets? && tweet.retweet?
  267. # ignore older messages
  268. if (@channel.created_at - 15.days) > tweet.created_at || older_import >= older_import_max
  269. older_import += 1
  270. Rails.logger.debug "tweet to old: #{tweet.id}/#{tweet.created_at}"
  271. next
  272. end
  273. next if Ticket::Article.find_by(message_id: tweet.id)
  274. break if @rest_client.tweet_limit_reached(tweet)
  275. @rest_client.to_group(tweet, @sync[:mentions][:group_id], @channel)
  276. }
  277. end
  278. def fetch_direct_messages
  279. return if @sync[:direct_messages].blank?
  280. return if @sync[:direct_messages][:group_id].blank?
  281. Rails.logger.debug ' - searching for direct_messages'
  282. older_import = 0
  283. older_import_max = 20
  284. @rest_client.client.direct_messages(full_text: 'true').each { |tweet|
  285. # ignore older messages
  286. if (@channel.created_at - 15.days) > tweet.created_at || older_import >= older_import_max
  287. older_import += 1
  288. Rails.logger.debug "tweet to old: #{tweet.id}/#{tweet.created_at}"
  289. next
  290. end
  291. next if Ticket::Article.find_by(message_id: tweet.id)
  292. break if @rest_client.direct_message_limit_reached(tweet)
  293. @rest_client.to_group(tweet, @sync[:direct_messages][:group_id], @channel)
  294. }
  295. end
  296. def check_external_credential(options)
  297. if options[:auth] && options[:auth][:external_credential_id]
  298. external_credential = ExternalCredential.find_by(id: options[:auth][:external_credential_id])
  299. raise "No such ExternalCredential.find(#{options[:auth][:external_credential_id]})" if !external_credential
  300. options[:auth][:consumer_key] = external_credential.credentials['consumer_key']
  301. options[:auth][:consumer_secret] = external_credential.credentials['consumer_secret']
  302. end
  303. options
  304. end
  305. def track_retweets?
  306. @channel.options && @channel.options['sync'] && @channel.options['sync']['track_retweets']
  307. end
  308. def own_tweet_already_imported?(tweet)
  309. event_time = Time.zone.now
  310. sleep 4
  311. 12.times { |loop_count|
  312. if Ticket::Article.find_by(message_id: tweet.id)
  313. Rails.logger.debug "Own tweet already imported, skipping tweet #{tweet.id}"
  314. return true
  315. end
  316. count = Delayed::Job.where('created_at < ?', event_time).count
  317. break if count.zero?
  318. sleep_time = 2 * count
  319. sleep_time = 5 if sleep_time > 5
  320. Rails.logger.debug "Delay importing own tweets - sleep #{sleep_time} (loop #{loop_count})"
  321. sleep sleep_time
  322. }
  323. if Ticket::Article.find_by(message_id: tweet.id)
  324. Rails.logger.debug "Own tweet already imported, skipping tweet #{tweet.id}"
  325. return true
  326. end
  327. false
  328. end
  329. end