twitter_spec.rb 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977
  1. # Copyright (C) 2012-2022 Zammad Foundation, https://zammad-foundation.org/
  2. require 'rails_helper'
  3. RSpec.describe Channel::Driver::Twitter, required_envs: %w[TWITTER_CONSUMER_KEY TWITTER_CONSUMER_SECRET TWITTER_OAUTH_TOKEN TWITTER_OAUTH_TOKEN_SECRET TWITTER_DM_RECIPIENT TWITTER_USER_ID] do
  4. subject(:channel) { create(:twitter_channel) }
  5. let(:external_credential) { ExternalCredential.find(channel.options[:auth][:external_credential_id]) }
  6. describe '#process', current_user_id: 1 do
  7. # Twitter channels must be configured to know whose account they're monitoring.
  8. subject(:channel) do
  9. create(:twitter_channel, custom_options: { user: { id: payload[:for_user_id] } })
  10. end
  11. let(:payload) { YAML.safe_load(File.read(payload_file), [ActiveSupport::HashWithIndifferentAccess]) }
  12. # https://git.zammad.com/zammad/zammad/-/issues/305
  13. shared_examples 'for user processing' do
  14. let(:sender_attributes) do
  15. {
  16. 'login' => sender_profile[:screen_name],
  17. 'firstname' => sender_profile[:name].capitalize,
  18. 'web' => sender_profile[:url],
  19. 'note' => sender_profile[:description],
  20. 'address' => sender_profile[:location],
  21. 'image_source' => sender_profile[:profile_image_url],
  22. }
  23. end
  24. let(:avatar_attributes) do
  25. {
  26. 'object_lookup_id' => ObjectLookup.by_name('User'),
  27. 'deletable' => true,
  28. 'source' => 'twitter',
  29. 'source_url' => sender_profile[:profile_image_url],
  30. }
  31. end
  32. let(:authorization_attributes) do
  33. {
  34. 'uid' => sender_profile[:id],
  35. 'username' => sender_profile[:screen_name],
  36. 'provider' => 'twitter',
  37. }
  38. end
  39. context 'from unknown user' do
  40. it 'creates a User record for the sender' do
  41. expect { channel.process(payload) }
  42. .to change(User, :count).by(1)
  43. .and change { User.exists?(sender_attributes) }.to(true)
  44. end
  45. it 'creates an Avatar record for the sender', :use_vcr do
  46. # Why 2, and not 1? Avatar.add auto-generates a default (source: 'init') record
  47. # before actually adding the specified (source: 'twitter') one.
  48. expect { channel.process(payload) }
  49. .to change(Avatar, :count).by_at_least(1)
  50. .and change { Avatar.exists?(avatar_attributes) }.to(true)
  51. expect(User.last.image).to eq(Avatar.last.store_hash)
  52. end
  53. it 'creates an Authorization record for the sender' do
  54. expect { channel.process(payload) }
  55. .to change(Authorization, :count).by(1)
  56. .and change { Authorization.exists?(authorization_attributes) }.to(true)
  57. end
  58. end
  59. context 'from known user' do
  60. let!(:user) { create(:user) }
  61. let!(:avatar) { create(:avatar, o_id: user.id, object_lookup_id: ObjectLookup.by_name('User'), source: 'twitter') }
  62. let!(:authorization) do
  63. Authorization.create(user_id: user.id, uid: sender_profile[:id], provider: 'twitter')
  64. end
  65. it 'updates the sender’s existing User record' do
  66. expect { channel.process(payload) }
  67. .to not_change(User, :count)
  68. .and not_change { user.reload.attributes.slice('login', 'firstname') }
  69. .and change { User.exists?(sender_attributes.except('login', 'firstname')) }.to(true)
  70. end
  71. it 'updates the sender’s existing Avatar record', :use_vcr do
  72. expect { channel.process(payload) }
  73. .to not_change(Avatar, :count)
  74. .and change { Avatar.exists?(avatar_attributes) }.to(true)
  75. expect(user.reload.image).to eq(avatar.reload.store_hash)
  76. end
  77. it 'updates the sender’s existing Authorization record' do
  78. expect { channel.process(payload) }
  79. .to not_change(Authorization, :count)
  80. .and change { Authorization.exists?(authorization_attributes) }.to(true)
  81. end
  82. end
  83. end
  84. context 'for incoming DM' do
  85. let(:payload_file) { Rails.root.join('test/data/twitter/webhook_events/direct_message-incoming.yml') }
  86. include_examples 'for user processing' do
  87. # Payload sent by Twitter is { ..., users: [{ <uid>: <sender> }, { <uid>: <receiver> }] }
  88. let(:sender_profile) { payload[:users].values.first }
  89. end
  90. describe 'ticket creation' do
  91. let(:ticket_attributes) do
  92. # NOTE: missing "customer_id" (because the value is generated as part of the #process method)
  93. {
  94. 'title' => title,
  95. 'group_id' => channel.options[:sync][:direct_messages][:group_id],
  96. 'state' => Ticket::State.find_by(default_create: true),
  97. 'priority' => Ticket::Priority.find_by(default_create: true),
  98. 'preferences' => {
  99. 'channel_id' => channel.id,
  100. 'channel_screen_name' => channel.options[:user][:screen_name],
  101. },
  102. }
  103. end
  104. let(:title) { payload[:direct_message_events].first[:message_create][:message_data][:text] }
  105. it 'creates a new ticket' do
  106. expect { channel.process(payload) }
  107. .to change(Ticket, :count).by(1)
  108. .and change { Ticket.exists?(ticket_attributes) }.to(true)
  109. end
  110. context 'for duplicate messages' do
  111. before do
  112. channel.process(
  113. YAML.safe_load(File.read(payload_file), [ActiveSupport::HashWithIndifferentAccess])
  114. )
  115. end
  116. it 'does not create duplicate ticket' do
  117. expect { channel.process(payload) }
  118. .to not_change(Ticket, :count)
  119. .and not_change(Ticket::Article, :count)
  120. end
  121. end
  122. context 'for message longer than 80 chars' do
  123. before { payload[:direct_message_events].first[:message_create][:message_data][:text] = 'a' * 81 }
  124. let(:title) { "#{'a' * 80}..." }
  125. it 'creates ticket with truncated title' do
  126. expect { channel.process(payload) }
  127. .to change(Ticket, :count).by(1)
  128. .and change { Ticket.exists?(ticket_attributes) }.to(true)
  129. end
  130. end
  131. context 'in reply to existing thread/ticket' do
  132. # import parent DM
  133. before do
  134. channel.process(
  135. YAML.safe_load(
  136. File.read(Rails.root.join('test/data/twitter/webhook_events/direct_message-incoming.yml')),
  137. [ActiveSupport::HashWithIndifferentAccess]
  138. )
  139. )
  140. end
  141. let(:payload_file) { Rails.root.join('test/data/twitter/webhook_events/direct_message-incoming_2.yml') }
  142. it 'uses existing ticket' do
  143. expect { channel.process(payload) }
  144. .to not_change(Ticket, :count)
  145. .and not_change { Ticket.last.state }
  146. end
  147. context 'marked "closed" / "merged" / "removed"' do
  148. before { Ticket.last.update(state: Ticket::State.find_by(name: 'closed')) }
  149. it 'creates a new ticket' do
  150. expect { channel.process(payload) }
  151. .to change(Ticket, :count).by(1)
  152. .and change { Ticket.exists?(ticket_attributes) }.to(true)
  153. end
  154. end
  155. context 'marked "pending reminder" / "pending close"' do
  156. before { Ticket.last.update(state: Ticket::State.find_by(name: 'pending reminder')) }
  157. it 'sets existing ticket to "open"' do
  158. expect { channel.process(payload) }
  159. .to not_change(Ticket, :count)
  160. .and change { Ticket.last.state.name }.to('open')
  161. end
  162. end
  163. end
  164. end
  165. describe 'article creation' do
  166. let(:article_attributes) do
  167. # NOTE: missing "ticket_id" (because the value is generated as part of the #process method)
  168. {
  169. 'from' => "@#{payload[:users].values.first[:screen_name]}",
  170. 'to' => "@#{payload[:users].values.second[:screen_name]}",
  171. 'body' => payload[:direct_message_events].first[:message_create][:message_data][:text],
  172. 'message_id' => payload[:direct_message_events].first[:id],
  173. 'in_reply_to' => nil,
  174. 'type_id' => Ticket::Article::Type.find_by(name: 'twitter direct-message').id,
  175. 'sender_id' => Ticket::Article::Sender.find_by(name: 'Customer').id,
  176. 'internal' => false,
  177. 'preferences' => { 'twitter' => twitter_prefs, 'links' => link_array }
  178. }
  179. end
  180. let(:twitter_prefs) do
  181. {
  182. 'created_at' => payload[:direct_message_events].first[:created_timestamp],
  183. 'recipient_id' => payload[:direct_message_events].first[:message_create][:target][:recipient_id],
  184. 'recipient_screen_name' => payload[:users].values.second[:screen_name],
  185. 'sender_id' => payload[:direct_message_events].first[:message_create][:sender_id],
  186. 'sender_screen_name' => payload[:users].values.first[:screen_name],
  187. 'app_id' => payload[:apps]&.values&.first&.dig(:app_id),
  188. 'app_name' => payload[:apps]&.values&.first&.dig(:app_name),
  189. 'geo' => {},
  190. 'place' => {},
  191. }
  192. end
  193. let(:link_array) do
  194. [
  195. {
  196. 'url' => "https://twitter.com/messages/#{user_ids.map(&:to_i).sort.join('-')}",
  197. 'target' => '_blank',
  198. 'name' => 'on Twitter',
  199. },
  200. ]
  201. end
  202. let(:user_ids) { payload[:users].values.pluck(:id) }
  203. it 'creates a new article' do
  204. expect { channel.process(payload) }
  205. .to change(Ticket::Article, :count).by(1)
  206. .and change { Ticket::Article.exists?(article_attributes) }.to(true)
  207. end
  208. context 'for duplicate messages' do
  209. before do
  210. channel.process(
  211. YAML.safe_load(File.read(payload_file), [ActiveSupport::HashWithIndifferentAccess])
  212. )
  213. end
  214. it 'does not create duplicate article' do
  215. expect { channel.process(payload) }
  216. .to not_change(Ticket::Article, :count)
  217. end
  218. end
  219. context 'when message contains shortened (t.co) url' do
  220. let(:payload_file) { Rails.root.join('test/data/twitter/webhook_events/direct_message-incoming_with_url.yml') }
  221. it 'replaces the t.co url for the original' do
  222. expect { channel.process(payload) }
  223. .to change { Ticket::Article.exists?(body: <<~BODY.chomp) }.to(true)
  224. Did you know about this? https://en.wikipedia.org/wiki/Frankenstein#Composition
  225. BODY
  226. end
  227. end
  228. end
  229. end
  230. context 'for outgoing DM' do
  231. let(:payload_file) { Rails.root.join('test/data/twitter/webhook_events/direct_message-outgoing.yml') }
  232. describe 'ticket creation' do
  233. let(:ticket_attributes) do
  234. # NOTE: missing "customer_id" (because User.last changes before and after the method is called)
  235. {
  236. 'title' => payload[:direct_message_events].first[:message_create][:message_data][:text],
  237. 'group_id' => channel.options[:sync][:direct_messages][:group_id],
  238. 'state' => Ticket::State.find_by(name: 'closed'),
  239. 'priority' => Ticket::Priority.find_by(default_create: true),
  240. 'preferences' => {
  241. 'channel_id' => channel.id,
  242. 'channel_screen_name' => channel.options[:user][:screen_name],
  243. },
  244. }
  245. end
  246. it 'creates a closed ticket' do
  247. expect { channel.process(payload) }
  248. .to change(Ticket, :count).by(1)
  249. .and change { Ticket.exists?(ticket_attributes) }.to(true)
  250. end
  251. end
  252. describe 'article creation' do
  253. let(:article_attributes) do
  254. # NOTE: missing "ticket_id" (because the value is generated as part of the #process method)
  255. {
  256. 'from' => "@#{payload[:users].values.first[:screen_name]}",
  257. 'to' => "@#{payload[:users].values.second[:screen_name]}",
  258. 'body' => payload[:direct_message_events].first[:message_create][:message_data][:text],
  259. 'message_id' => payload[:direct_message_events].first[:id],
  260. 'in_reply_to' => nil,
  261. 'type_id' => Ticket::Article::Type.find_by(name: 'twitter direct-message').id,
  262. 'sender_id' => Ticket::Article::Sender.find_by(name: 'Customer').id,
  263. 'internal' => false,
  264. 'preferences' => { 'twitter' => twitter_prefs, 'links' => link_array }
  265. }
  266. end
  267. let(:twitter_prefs) do
  268. {
  269. 'created_at' => payload[:direct_message_events].first[:created_timestamp],
  270. 'recipient_id' => payload[:direct_message_events].first[:message_create][:target][:recipient_id],
  271. 'recipient_screen_name' => payload[:users].values.second[:screen_name],
  272. 'sender_id' => payload[:direct_message_events].first[:message_create][:sender_id],
  273. 'sender_screen_name' => payload[:users].values.first[:screen_name],
  274. 'app_id' => payload[:apps]&.values&.first&.dig(:app_id),
  275. 'app_name' => payload[:apps]&.values&.first&.dig(:app_name),
  276. 'geo' => {},
  277. 'place' => {},
  278. }
  279. end
  280. let(:link_array) do
  281. [
  282. {
  283. 'url' => "https://twitter.com/messages/#{user_ids.map(&:to_i).sort.join('-')}",
  284. 'target' => '_blank',
  285. 'name' => 'on Twitter',
  286. },
  287. ]
  288. end
  289. let(:user_ids) { payload[:users].values.pluck(:id) }
  290. it 'creates a new article' do
  291. expect { channel.process(payload) }
  292. .to change(Ticket::Article, :count).by(1)
  293. .and change { Ticket::Article.exists?(article_attributes) }.to(true)
  294. end
  295. context 'when message contains shortened (t.co) url' do
  296. let(:payload_file) { Rails.root.join('test/data/twitter/webhook_events/direct_message-incoming_with_url.yml') }
  297. it 'replaces the t.co url for the original' do
  298. expect { channel.process(payload) }
  299. .to change { Ticket::Article.exists?(body: <<~BODY.chomp) }.to(true)
  300. Did you know about this? https://en.wikipedia.org/wiki/Frankenstein#Composition
  301. BODY
  302. end
  303. end
  304. context 'when message contains a media attachment (e.g., JPG)' do
  305. let(:payload_file) { Rails.root.join('test/data/twitter/webhook_events/direct_message-incoming_with_media.yml') }
  306. it 'does not store it as an attachment on the article' do
  307. channel.process(payload)
  308. expect(Ticket::Article.last.attachments).to be_empty
  309. end
  310. end
  311. end
  312. end
  313. context 'for incoming tweet' do
  314. let(:payload_file) { Rails.root.join('test/data/twitter/webhook_events/tweet_create-user_mention.yml') }
  315. include_examples 'for user processing' do
  316. # Payload sent by Twitter is { ..., tweet_create_events: [{ ..., user: <author> }] }
  317. let(:sender_profile) { payload[:tweet_create_events].first[:user] }
  318. end
  319. describe 'ticket creation' do
  320. let(:ticket_attributes) do
  321. # NOTE: missing "customer_id" (because User.last changes before and after the method is called)
  322. {
  323. 'title' => payload[:tweet_create_events].first[:text],
  324. 'group_id' => channel.options[:sync][:direct_messages][:group_id],
  325. 'state' => Ticket::State.find_by(default_create: true),
  326. 'priority' => Ticket::Priority.find_by(default_create: true),
  327. 'preferences' => {
  328. 'channel_id' => channel.id,
  329. 'channel_screen_name' => channel.options[:user][:screen_name],
  330. },
  331. }
  332. end
  333. it 'creates a new ticket' do
  334. expect { channel.process(payload) }
  335. .to change(Ticket, :count).by(1)
  336. end
  337. context 'for duplicate tweets' do
  338. before do
  339. channel.process(
  340. YAML.safe_load(File.read(payload_file), [ActiveSupport::HashWithIndifferentAccess])
  341. )
  342. end
  343. it 'does not create duplicate ticket' do
  344. expect { channel.process(payload) }
  345. .to not_change(Ticket, :count)
  346. .and not_change(Ticket::Article, :count)
  347. end
  348. end
  349. context 'in response to existing tweet thread' do
  350. let(:payload_file) { Rails.root.join('test/data/twitter/webhook_events/tweet_create-response.yml') }
  351. let(:parent_tweet_payload) do
  352. YAML.safe_load(
  353. File.read(Rails.root.join('test/data/twitter/webhook_events/tweet_create-user_mention.yml')),
  354. [ActiveSupport::HashWithIndifferentAccess]
  355. )
  356. end
  357. context 'that hasn’t been imported yet', :use_vcr do
  358. it 'creates a new ticket' do
  359. expect { channel.process(payload) }
  360. .to change(Ticket, :count).by(1)
  361. end
  362. it 'retrieves the parent tweet via the Twitter API' do
  363. expect { channel.process(payload) }
  364. .to change(Ticket::Article, :count).by(2)
  365. expect(Ticket::Article.second_to_last.body).to eq(parent_tweet_payload[:tweet_create_events].first[:text])
  366. end
  367. context 'after parent tweet has been deleted' do
  368. before do
  369. payload[:tweet_create_events].first[:in_reply_to_status_id] = 1207610954160037890 # rubocop:disable Style/NumericLiterals
  370. payload[:tweet_create_events].first[:in_reply_to_status_id_str] = '1207610954160037890'
  371. end
  372. it 'creates a new ticket' do
  373. expect { channel.process(payload) }
  374. .to change(Ticket, :count).by(1)
  375. end
  376. it 'silently ignores error when retrieving parent tweet' do
  377. expect { channel.process(payload) }.to not_raise_error
  378. end
  379. end
  380. end
  381. context 'that was previously imported' do
  382. # import parent tweet
  383. before { channel.process(parent_tweet_payload) }
  384. it 'uses existing ticket' do
  385. expect { channel.process(payload) }
  386. .to not_change(Ticket, :count)
  387. .and not_change { Ticket.last.state }
  388. end
  389. context 'and marked "closed" / "merged" / "removed" / "pending reminder" / "pending close"' do
  390. before { Ticket.last.update(state: Ticket::State.find_by(name: 'closed')) }
  391. it 'sets existing ticket to "open"' do
  392. expect { channel.process(payload) }
  393. .to not_change(Ticket, :count)
  394. .and change { Ticket.last.state.name }.to('open')
  395. end
  396. end
  397. end
  398. end
  399. end
  400. describe 'article creation' do
  401. let(:article_attributes) do
  402. # NOTE: missing "ticket_id" (because the value is generated as part of the #process method)
  403. {
  404. 'from' => "@#{payload[:tweet_create_events].first[:user][:screen_name]}",
  405. 'to' => "@#{payload[:tweet_create_events].first[:entities][:user_mentions].first[:screen_name]}",
  406. 'body' => payload[:tweet_create_events].first[:text],
  407. 'message_id' => payload[:tweet_create_events].first[:id_str],
  408. 'in_reply_to' => payload[:tweet_create_events].first[:in_reply_to_status_id],
  409. 'type_id' => Ticket::Article::Type.find_by(name: 'twitter status').id,
  410. 'sender_id' => Ticket::Article::Sender.find_by(name: 'Customer').id,
  411. 'internal' => false,
  412. 'preferences' => { 'twitter' => twitter_prefs, 'links' => link_array }
  413. }
  414. end
  415. let(:twitter_prefs) do
  416. {
  417. 'mention_ids' => payload[:tweet_create_events].first[:entities][:user_mentions].pluck(:id),
  418. 'geo' => payload[:tweet_create_events].first[:geo].to_h,
  419. 'retweeted' => payload[:tweet_create_events].first[:retweeted],
  420. 'possibly_sensitive' => payload[:tweet_create_events].first[:possibly_sensitive],
  421. 'in_reply_to_user_id' => payload[:tweet_create_events].first[:in_reply_to_user_id],
  422. 'place' => payload[:tweet_create_events].first[:place].to_h,
  423. 'retweet_count' => payload[:tweet_create_events].first[:retweet_count],
  424. 'source' => payload[:tweet_create_events].first[:source],
  425. 'favorited' => payload[:tweet_create_events].first[:favorited],
  426. 'truncated' => payload[:tweet_create_events].first[:truncated],
  427. }
  428. end
  429. let(:link_array) do
  430. [
  431. {
  432. 'url' => "https://twitter.com/_/status/#{payload[:tweet_create_events].first[:id]}",
  433. 'target' => '_blank',
  434. 'name' => 'on Twitter',
  435. },
  436. ]
  437. end
  438. it 'creates a new article' do
  439. expect { channel.process(payload) }
  440. .to change(Ticket::Article, :count).by(1)
  441. .and change { Ticket::Article.exists?(article_attributes) }.to(true)
  442. end
  443. context 'when message mentions multiple users' do
  444. let(:payload_file) { Rails.root.join('test/data/twitter/webhook_events/tweet_create-user_mention_multiple.yml') }
  445. let(:mentionees) { "@#{payload[:tweet_create_events].first[:entities][:user_mentions].pluck(:screen_name).join(', @')}" }
  446. it 'records all mentionees in comma-separated "to" attribute' do
  447. expect { channel.process(payload) }
  448. .to change { Ticket::Article.exists?(to: mentionees) }.to(true)
  449. end
  450. end
  451. context 'when message exceeds 140 characters' do
  452. let(:payload_file) { Rails.root.join('test/data/twitter/webhook_events/tweet_create-user_mention_extended.yml') }
  453. let(:full_body) { payload[:tweet_create_events].first[:extended_tweet][:full_text] }
  454. it 'records the full (extended) tweet body' do
  455. expect { channel.process(payload) }
  456. .to change { Ticket::Article.exists?(body: full_body) }.to(true)
  457. end
  458. end
  459. context 'when message contains shortened (t.co) url' do
  460. let(:payload_file) { Rails.root.join('test/data/twitter/webhook_events/tweet_create-user_mention_with_url.yml') }
  461. it 'replaces the t.co url for the original' do
  462. expect { channel.process(payload) }
  463. .to change { Ticket::Article.exists?(body: <<~BODY.chomp) }.to(true)
  464. @ScruffyMcG https://zammad.org/
  465. BODY
  466. end
  467. end
  468. context 'when message contains a media attachment (e.g., JPG)' do
  469. let(:payload_file) { Rails.root.join('test/data/twitter/webhook_events/tweet_create-user_mention_with_media.yml') }
  470. it 'replaces the t.co url for the original' do
  471. expect { channel.process(payload) }
  472. .to change { Ticket::Article.exists?(body: <<~BODY.chomp) }.to(true)
  473. @ScruffyMcG https://twitter.com/pennbrooke1/status/1209101446706122752/photo/1
  474. BODY
  475. end
  476. it 'stores it as an attachment on the article', :use_vcr do
  477. channel.process(payload)
  478. expect(Ticket::Article.last.attachments).to be_one
  479. end
  480. end
  481. context 'when message is a retweet' do
  482. let(:payload_file) { Rails.root.join('test/data/twitter/webhook_events/tweet_create-retweet.yml') }
  483. context 'and "conversion of retweets" is enabled' do
  484. before do
  485. channel.options['sync']['track_retweets'] = true
  486. channel.save
  487. end
  488. it 'creates a new article' do
  489. expect { channel.process(payload) }
  490. .to change(Ticket::Article, :count).by(1)
  491. .and change { Ticket::Article.exists?(article_attributes) }.to(true)
  492. end
  493. end
  494. context 'and "conversion of retweets" is disabled' do
  495. before do
  496. channel.options['sync']['track_retweets'] = false
  497. channel.save
  498. end
  499. it 'does not create a new article' do
  500. expect { channel.process(payload) }
  501. .not_to change(Ticket::Article, :count)
  502. end
  503. end
  504. end
  505. end
  506. end
  507. context 'for outgoing tweet' do
  508. let(:payload_file) { Rails.root.join('test/data/twitter/webhook_events/tweet_create-user_mention_outgoing.yml') }
  509. describe 'ticket creation' do
  510. let(:ticket_attributes) do
  511. # NOTE: missing "customer_id" (because User.last changes before and after the method is called)
  512. {
  513. 'title' => payload[:tweet_create_events].first[:text],
  514. 'group_id' => channel.options[:sync][:direct_messages][:group_id],
  515. 'state' => Ticket::State.find_by(name: 'closed'),
  516. 'priority' => Ticket::Priority.find_by(default_create: true),
  517. 'preferences' => {
  518. 'channel_id' => channel.id,
  519. 'channel_screen_name' => channel.options[:user][:screen_name],
  520. },
  521. }
  522. end
  523. it 'creates a closed ticket' do
  524. expect { channel.process(payload) }
  525. .to change(Ticket, :count).by(1)
  526. end
  527. end
  528. describe 'article creation' do
  529. let(:article_attributes) do
  530. # NOTE: missing "ticket_id" (because the value is generated as part of the #process method)
  531. {
  532. 'from' => "@#{payload[:tweet_create_events].first[:user][:screen_name]}",
  533. 'to' => "@#{payload[:tweet_create_events].first[:entities][:user_mentions].first[:screen_name]}",
  534. 'body' => payload[:tweet_create_events].first[:text],
  535. 'message_id' => payload[:tweet_create_events].first[:id_str],
  536. 'in_reply_to' => payload[:tweet_create_events].first[:in_reply_to_status_id],
  537. 'type_id' => Ticket::Article::Type.find_by(name: 'twitter status').id,
  538. 'sender_id' => Ticket::Article::Sender.find_by(name: 'Customer').id,
  539. 'internal' => false,
  540. 'preferences' => { 'twitter' => twitter_prefs, 'links' => link_array }
  541. }
  542. end
  543. let(:twitter_prefs) do
  544. {
  545. 'mention_ids' => payload[:tweet_create_events].first[:entities][:user_mentions].pluck(:id),
  546. 'geo' => payload[:tweet_create_events].first[:geo].to_h,
  547. 'retweeted' => payload[:tweet_create_events].first[:retweeted],
  548. 'possibly_sensitive' => payload[:tweet_create_events].first[:possibly_sensitive],
  549. 'in_reply_to_user_id' => payload[:tweet_create_events].first[:in_reply_to_user_id],
  550. 'place' => payload[:tweet_create_events].first[:place].to_h,
  551. 'retweet_count' => payload[:tweet_create_events].first[:retweet_count],
  552. 'source' => payload[:tweet_create_events].first[:source],
  553. 'favorited' => payload[:tweet_create_events].first[:favorited],
  554. 'truncated' => payload[:tweet_create_events].first[:truncated],
  555. }
  556. end
  557. let(:link_array) do
  558. [
  559. {
  560. 'url' => "https://twitter.com/_/status/#{payload[:tweet_create_events].first[:id]}",
  561. 'target' => '_blank',
  562. 'name' => 'on Twitter',
  563. },
  564. ]
  565. end
  566. it 'creates a new article' do
  567. expect { channel.process(payload) }
  568. .to change(Ticket::Article, :count).by(1)
  569. .and change { Ticket::Article.exists?(article_attributes) }.to(true)
  570. end
  571. end
  572. end
  573. end
  574. describe '#send', :use_vcr do
  575. shared_examples 'for #send' do
  576. # Channel#deliver takes a hash in the following format
  577. # (see CommunicateTwitterJob#perform)
  578. #
  579. # Why not just accept the whole article?
  580. # Presumably so all channels have a consistent interface...
  581. # but it might be a good idea to let it accept both one day
  582. # (the "robustness principle")
  583. let(:delivery_payload) do
  584. {
  585. type: outgoing_tweet.type.name,
  586. to: outgoing_tweet.to,
  587. body: outgoing_tweet.body,
  588. in_reply_to: outgoing_tweet.in_reply_to
  589. }
  590. end
  591. describe 'Import Mode behavior' do
  592. before { Setting.set('import_mode', true) }
  593. it 'is a no-op' do
  594. expect(Twitter::REST::Client).not_to receive(:new)
  595. channel.deliver(delivery_payload)
  596. end
  597. end
  598. describe 'Twitter API activity' do
  599. it 'returns the created tweet/DM' do
  600. expect(channel.deliver(delivery_payload)).to be_a(return_value)
  601. end
  602. end
  603. end
  604. context 'for tweets' do
  605. let!(:outgoing_tweet) { create(:twitter_article) }
  606. let(:return_value) { Twitter::Tweet }
  607. include_examples 'for #send'
  608. context 'in a thread' do
  609. let!(:outgoing_tweet) { create(:twitter_article, :reply) }
  610. it 'creates a tweet via the API' do
  611. expect { channel.deliver(delivery_payload) }.to not_raise_error
  612. end
  613. end
  614. context 'containing an asterisk (workaround for sferik/twitter #677)' do
  615. let!(:outgoing_tweet) { create(:twitter_article, body: 'foo * bar') }
  616. it 'converts it to a full-width asterisk (U+FF0A)' do
  617. expect { channel.deliver(delivery_payload) }.to not_raise_error
  618. end
  619. end
  620. end
  621. context 'for DMs' do
  622. let(:recipient) { create(:twitter_authorization, uid: ENV.fetch('TWITTER_DM_RECIPIENT', '1234567890')) }
  623. let!(:outgoing_tweet) { create(:twitter_dm_article, :pending_delivery, recipient: recipient) }
  624. let(:return_value) { Twitter::DirectMessage }
  625. include_examples 'for #send'
  626. end
  627. end
  628. describe '#fetch', use_vcr: :time_sensitive do
  629. context 'when ApplicationHandleInfo context' do
  630. it 'gets switched to "twitter"' do
  631. allow(ApplicationHandleInfo).to receive('context=')
  632. channel.fetch
  633. expect(ApplicationHandleInfo).to have_received('context=').with('twitter').at_least(1)
  634. end
  635. it 'reverts back to default' do
  636. allow(ApplicationHandleInfo).to receive('context=')
  637. channel.fetch
  638. expect(ApplicationHandleInfo.context).not_to eq 'twitter'
  639. end
  640. end
  641. describe 'rate limiting' do
  642. before do
  643. allow(Rails.env).to receive(:test?).and_return(false)
  644. channel.fetch
  645. end
  646. context 'within 20 minutes of last run' do
  647. before { travel(19.minutes) }
  648. it 'aborts' do
  649. expect { channel.fetch }
  650. .not_to change { channel.reload.preferences[:last_fetch] }
  651. end
  652. end
  653. context '20+ minutes since last run' do
  654. before { travel(20.minutes) }
  655. it 'runs again' do
  656. expect { channel.fetch }
  657. .to change { channel.reload.preferences[:last_fetch] }
  658. end
  659. end
  660. end
  661. describe 'Twitter API activity' do
  662. it 'sets successful status attributes' do
  663. expect { channel.fetch }
  664. .to change { channel.reload.attributes }
  665. .to hash_including(
  666. 'status_in' => 'ok',
  667. 'last_log_in' => '',
  668. 'status_out' => nil,
  669. 'last_log_out' => nil
  670. )
  671. end
  672. context 'with search term configured (at .options[:sync][:search])' do
  673. it 'creates an article for each recent tweet' do
  674. expect { channel.fetch }
  675. .to change(Ticket, :count).by(2)
  676. expect(Ticket.last.attributes).to include(
  677. 'title' => "Come and join our team to bring Zammad even further forward! It's gonna be ama...",
  678. 'preferences' => { 'channel_id' => channel.id,
  679. 'channel_screen_name' => channel.options[:user][:screen_name] },
  680. 'customer_id' => User.find_by(firstname: 'Mr.Generation', lastname: '').id
  681. )
  682. end
  683. context 'for responses to other tweets' do
  684. let(:thread) do
  685. Ticket.joins(articles: :type).where(ticket_article_types: { name: 'twitter status' })
  686. .group('tickets.id').having(
  687. case ActiveRecord::Base.connection_db_config.configuration_hash[:adapter]
  688. when 'mysql2'
  689. 'COUNT("ticket_articles.*") > 1'
  690. when 'postgresql'
  691. 'COUNT(ticket_articles.*) > 1'
  692. end
  693. ).first
  694. end
  695. it 'creates articles for parent tweets as well' do
  696. channel.fetch
  697. expect(thread.articles.last.body).to match(%r{zammad}i) # search result
  698. expect(thread.articles.first.body).not_to match(%r{zammad}i) # parent tweet
  699. end
  700. end
  701. context 'and "track_retweets" option' do
  702. context 'is false (default)' do
  703. it 'skips retweets' do
  704. expect { channel.fetch }
  705. .not_to change { Ticket.where('title LIKE ?', 'RT @%').count }.from(0)
  706. end
  707. end
  708. context 'is true' do
  709. subject(:channel) { create(:twitter_channel, custom_options: { sync: { track_retweets: true } }) }
  710. it 'creates an article for each recent tweet/retweet' do
  711. expect { channel.fetch }
  712. .to change { Ticket.where('title LIKE ?', 'RT @%').count }.by(49)
  713. .and change(Ticket, :count).by(73)
  714. end
  715. end
  716. end
  717. context 'and "import_older_tweets" option (legacy)' do
  718. context 'is false (default)' do
  719. it 'skips tweets 15+ days older than channel itself' do
  720. expect { channel.fetch }
  721. .not_to change { Ticket.where('title LIKE ?', 'GitHub Trending Archive, 29 Nov 2018, Ruby. %').count }.from(0)
  722. end
  723. end
  724. context 'is true' do
  725. subject(:channel) { create(:twitter_channel, :legacy) }
  726. it 'creates an article for each tweet' do
  727. expect { channel.fetch }
  728. .to change { Ticket.where('title LIKE ?', 'GitHub Trending Archive, 29 Nov 2018, Ruby. %').count }.by(1)
  729. .and change(Ticket, :count).by(3)
  730. end
  731. end
  732. end
  733. describe 'duplicate handling' do
  734. context 'when fetched tweets have already been imported' do
  735. before do
  736. tweet_ids.each { |tweet_id| create(:ticket_article, message_id: tweet_id) }
  737. end
  738. let(:tweet_ids) { [1222126386334388225, 1222109934923460608] } # rubocop:disable Style/NumericLiterals
  739. it 'does not import duplicates' do
  740. expect { channel.fetch }.not_to change(Ticket::Article, :count)
  741. end
  742. end
  743. describe 'Race condition: when #fetch finds a half-processed, outgoing tweet' do
  744. subject!(:channel) do
  745. create(:twitter_channel,
  746. search_term: 'zammadzammadzammad',
  747. custom_options: {
  748. user: {
  749. # "outgoing" tweets = authored by this Twitter user ID
  750. id: '1205290247124217856',
  751. },
  752. })
  753. end
  754. # This test case requires the use_vcr: :time_sensitive option
  755. # to travel_to(when the VCR cassette was recorded).
  756. #
  757. # This ensures that #fetch doesn't ignore
  758. # the "older" tweets stored in the VCR cassette,
  759. # but it also freezes time,
  760. # which breaks this test expectation logic:
  761. #
  762. # expect { channel.fetch }.to change(Time, :current).by_at_least(5)
  763. #
  764. # So, we unfreeze time here.
  765. before { travel_back }
  766. let!(:tweet) { create(:twitter_article, body: 'zammadzammadzammad') }
  767. context '(i.e., after the BG job has posted the article to Twitter…' do
  768. # NOTE: This context block cannot be set up programmatically.
  769. # Instead, the tweet was posted, fetched, recorded into a VCR cassette,
  770. # and then manually copied into the existing VCR cassette for this example.
  771. context '…but before the BG job has "synced" article.message_id with tweet.id)' do
  772. let(:twitter_job) { Delayed::Job.where("handler LIKE '%job_class: CommunicateTwitterJob%#{tweet.id}%'").first }
  773. around do |example|
  774. Thread.new do
  775. sleep 5 # Simulate other bg jobs holding up the queue.
  776. twitter_job.invoke_job
  777. end.tap { example.run }.join
  778. end
  779. it 'does not import the duplicate tweet (waits up to 60s for BG job to finish)' do
  780. expect { channel.fetch }
  781. .to not_change(Ticket::Article, :count)
  782. .and change(Time, :current).by_at_least(5)
  783. end
  784. end
  785. end
  786. # To reproduce this test case, the VCR cassette has been modified
  787. # so that the fetched tweet has a different ("incoming") author user ID.
  788. it 'skips race condition handling for incoming tweets' do
  789. expect { channel.fetch }
  790. .to change(Ticket::Article, :count)
  791. .and change(Time, :current).by_at_most(1)
  792. end
  793. end
  794. end
  795. context 'for very common search terms' do
  796. subject(:channel) { create(:twitter_channel, search_term: 'coronavirus') }
  797. let(:twitter_articles) { Ticket::Article.joins(:type).where(ticket_article_types: { name: 'twitter status' }) }
  798. # NOTE: Ordinarily, RSpec examples should be kept as small as possible.
  799. # In this case, we bundle these examples together because
  800. # separating them would duplicate expensive setup:
  801. # even with HTTP caching, this single example takes nearly a minute.
  802. #
  803. # Also, note that this rate limiting is partially duplicated
  804. # in #fetchable?, which prevents #fetch from running
  805. # more than once in a 20-minute period.
  806. it 'imports max. ~120 articles every 15 minutes' do
  807. channel.fetch
  808. expect((twitter_articles - Ticket.last.articles).count).to be <= 120
  809. expect(twitter_articles.count).to be > 120
  810. travel(14.minutes)
  811. expect { create(:twitter_channel).fetch }
  812. .not_to change(Ticket::Article, :count)
  813. travel(1.minute)
  814. expect { create(:twitter_channel).fetch }
  815. .to change(Ticket::Article, :count)
  816. end
  817. end
  818. end
  819. end
  820. end
  821. end