twitter_spec.rb 41 KB

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