twitter_spec.rb 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000
  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.map { |u| u[: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.map { |u| u[: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].map { |um| um[: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].map { |um| um[: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. end
  481. end
  482. context 'for outgoing tweet' do
  483. let(:payload_file) { Rails.root.join('test/data/twitter/webhook_events/tweet_create-user_mention_outgoing.yml') }
  484. describe 'ticket creation' do
  485. let(:ticket_attributes) do
  486. # NOTE: missing "customer_id" (because User.last changes before and after the method is called)
  487. {
  488. 'title' => payload[:tweet_create_events].first[:text],
  489. 'group_id' => channel.options[:sync][:direct_messages][:group_id],
  490. 'state' => Ticket::State.find_by(name: 'closed'),
  491. 'priority' => Ticket::Priority.find_by(default_create: true),
  492. 'preferences' => {
  493. 'channel_id' => channel.id,
  494. 'channel_screen_name' => channel.options[:user][:screen_name],
  495. },
  496. }
  497. end
  498. it 'creates a closed ticket' do
  499. expect { channel.process(payload) }
  500. .to change(Ticket, :count).by(1)
  501. end
  502. end
  503. describe 'article creation' do
  504. let(:article_attributes) do
  505. # NOTE: missing "ticket_id" (because the value is generated as part of the #process method)
  506. {
  507. 'from' => "@#{payload[:tweet_create_events].first[:user][:screen_name]}",
  508. 'to' => "@#{payload[:tweet_create_events].first[:entities][:user_mentions].first[:screen_name]}",
  509. 'body' => payload[:tweet_create_events].first[:text],
  510. 'message_id' => payload[:tweet_create_events].first[:id_str],
  511. 'in_reply_to' => payload[:tweet_create_events].first[:in_reply_to_status_id],
  512. 'type_id' => Ticket::Article::Type.find_by(name: 'twitter status').id,
  513. 'sender_id' => Ticket::Article::Sender.find_by(name: 'Customer').id,
  514. 'internal' => false,
  515. 'preferences' => { 'twitter' => twitter_prefs, 'links' => link_array }
  516. }
  517. end
  518. let(:twitter_prefs) do
  519. {
  520. 'mention_ids' => payload[:tweet_create_events].first[:entities][:user_mentions].map { |um| um[:id] },
  521. 'geo' => payload[:tweet_create_events].first[:geo].to_h,
  522. 'retweeted' => payload[:tweet_create_events].first[:retweeted],
  523. 'possibly_sensitive' => payload[:tweet_create_events].first[:possibly_sensitive],
  524. 'in_reply_to_user_id' => payload[:tweet_create_events].first[:in_reply_to_user_id],
  525. 'place' => payload[:tweet_create_events].first[:place].to_h,
  526. 'retweet_count' => payload[:tweet_create_events].first[:retweet_count],
  527. 'source' => payload[:tweet_create_events].first[:source],
  528. 'favorited' => payload[:tweet_create_events].first[:favorited],
  529. 'truncated' => payload[:tweet_create_events].first[:truncated],
  530. }
  531. end
  532. let(:link_array) do
  533. [
  534. {
  535. 'url' => "https://twitter.com/_/status/#{payload[:tweet_create_events].first[:id]}",
  536. 'target' => '_blank',
  537. 'name' => 'on Twitter',
  538. },
  539. ]
  540. end
  541. it 'creates a new article' do
  542. expect { channel.process(payload) }
  543. .to change(Ticket::Article, :count).by(1)
  544. .and change { Ticket::Article.exists?(article_attributes) }.to(true)
  545. end
  546. end
  547. end
  548. end
  549. describe '#send', :use_vcr do
  550. shared_examples 'for #send' do
  551. # Channel#deliver takes a hash in the following format
  552. # (see Observer::Ticket::Article::CommunicateTwitter::BackgroundJob#perform)
  553. #
  554. # Why not just accept the whole article?
  555. # Presumably so all channels have a consistent interface...
  556. # but it might be a good idea to let it accept both one day
  557. # (the "robustness principle")
  558. let(:delivery_payload) do
  559. {
  560. type: outgoing_tweet.type.name,
  561. to: outgoing_tweet.to,
  562. body: outgoing_tweet.body,
  563. in_reply_to: outgoing_tweet.in_reply_to
  564. }
  565. end
  566. describe 'Import Mode behavior' do
  567. before { Setting.set('import_mode', true) }
  568. it 'is a no-op' do
  569. expect(Twitter::REST::Client).not_to receive(:new)
  570. channel.deliver(delivery_payload)
  571. end
  572. end
  573. describe 'Twitter API authentication' do
  574. let(:consumer_credentials) do
  575. {
  576. consumer_key: external_credential.credentials[:consumer_key],
  577. consumer_secret: external_credential.credentials[:consumer_secret],
  578. }
  579. end
  580. let(:oauth_credentials) do
  581. {
  582. access_token: channel.options[:auth][:oauth_token],
  583. access_token_secret: channel.options[:auth][:oauth_token_secret],
  584. }
  585. end
  586. it 'uses consumer key/secret stored on ExternalCredential' do
  587. expect(Twitter::REST::Client)
  588. .to receive(:new).with(hash_including(consumer_credentials))
  589. .and_call_original
  590. channel.deliver(delivery_payload)
  591. end
  592. it 'uses OAuth token/secret stored on #options hash' do
  593. expect(Twitter::REST::Client)
  594. .to receive(:new).with(hash_including(oauth_credentials))
  595. .and_call_original
  596. channel.deliver(delivery_payload)
  597. end
  598. end
  599. describe 'Twitter API activity' do
  600. it 'creates a tweet/DM via the API' do
  601. channel.deliver(delivery_payload)
  602. expect(WebMock)
  603. .to have_requested(:post, "https://api.twitter.com/1.1#{endpoint}")
  604. .with(body: request_body)
  605. end
  606. it 'returns the created tweet/DM' do
  607. expect(channel.deliver(delivery_payload)).to match(return_value)
  608. end
  609. end
  610. end
  611. context 'for tweets' do
  612. let!(:outgoing_tweet) { create(:twitter_article) }
  613. let(:endpoint) { '/statuses/update.json' }
  614. let(:request_body) { <<~BODY.chomp }
  615. in_reply_to_status_id&status=#{URI.encode_www_form_component(outgoing_tweet.body)}
  616. BODY
  617. let(:return_value) { Twitter::Tweet }
  618. include_examples 'for #send'
  619. context 'in a thread' do
  620. let!(:outgoing_tweet) { create(:twitter_article, :reply) }
  621. let(:request_body) { <<~BODY.chomp }
  622. in_reply_to_status_id=#{outgoing_tweet.in_reply_to}&status=#{URI.encode_www_form_component(outgoing_tweet.body)}
  623. BODY
  624. it 'creates a tweet 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. end
  631. context 'containing an asterisk (workaround for sferik/twitter #677)' do
  632. let!(:outgoing_tweet) { create(:twitter_article, body: 'foo * bar') }
  633. let(:request_body) { <<~BODY.chomp }
  634. in_reply_to_status_id&status=#{URI.encode_www_form_component('foo * bar')}
  635. BODY
  636. it 'converts it to a full-width asterisk (U+FF0A)' do
  637. channel.deliver(delivery_payload)
  638. expect(WebMock)
  639. .to have_requested(:post, "https://api.twitter.com/1.1#{endpoint}")
  640. .with(body: request_body)
  641. end
  642. end
  643. end
  644. context 'for DMs' do
  645. let!(:outgoing_tweet) { create(:twitter_dm_article, :pending_delivery) }
  646. let(:endpoint) { '/direct_messages/events/new.json' }
  647. let(:request_body) { <<~BODY.chomp }
  648. {"event":{"type":"message_create","message_create":{"target":{"recipient_id":"#{Authorization.last.uid}"},"message_data":{"text":"#{outgoing_tweet.body}"}}}}
  649. BODY
  650. let(:return_value) { { event: hash_including(type: 'message_create') } }
  651. include_examples 'for #send'
  652. end
  653. end
  654. describe '#fetch', use_vcr: :time_sensitive do
  655. describe 'Twitter API authentication' do
  656. let(:consumer_credentials) do
  657. {
  658. consumer_key: external_credential.credentials[:consumer_key],
  659. consumer_secret: external_credential.credentials[:consumer_secret],
  660. }
  661. end
  662. let(:oauth_credentials) do
  663. {
  664. access_token: channel.options[:auth][:oauth_token],
  665. access_token_secret: channel.options[:auth][:oauth_token_secret],
  666. }
  667. end
  668. it 'uses consumer key/secret stored on ExternalCredential' do
  669. expect(Twitter::REST::Client)
  670. .to receive(:new).with(hash_including(consumer_credentials))
  671. .and_call_original
  672. channel.fetch
  673. end
  674. it 'uses OAuth token/secret stored on #options hash' do
  675. expect(Twitter::REST::Client)
  676. .to receive(:new).with(hash_including(oauth_credentials))
  677. .and_call_original
  678. channel.fetch
  679. end
  680. end
  681. describe 'Twitter API activity' do
  682. it 'sets successful status attributes' do
  683. expect { channel.fetch }
  684. .to change { channel.reload.attributes }
  685. .to hash_including(
  686. 'status_in' => 'ok',
  687. 'last_log_in' => '',
  688. 'status_out' => nil,
  689. 'last_log_out' => nil
  690. )
  691. end
  692. context 'with search term configured (at .options[:sync][:search])' do
  693. it 'creates an article for each recent tweet' do
  694. expect { channel.fetch }
  695. .to change(Ticket, :count).by(8)
  696. expect(Ticket.last.attributes).to include(
  697. 'title' => "Come and join our team to bring Zammad even further forward! It's gonna be ama...",
  698. 'preferences' => { 'channel_id' => channel.id,
  699. 'channel_screen_name' => channel.options[:user][:screen_name] },
  700. 'customer_id' => User.find_by(firstname: 'Mr.Generation', lastname: '').id
  701. )
  702. end
  703. it 'skips retweets' do
  704. expect { channel.fetch }
  705. .not_to change { Ticket.where('title LIKE ?', 'RT @%').count }.from(0)
  706. end
  707. it 'skips tweets 15+ days older than channel itself' do
  708. expect { channel.fetch }
  709. .not_to change { Ticket.where('title LIKE ?', 'GitHub Trending Archive, 2_ Nov 2018, Ruby. %').count }.from(0)
  710. end
  711. context 'when fetched tweets have already been imported' do
  712. before do
  713. tweet_ids.each { |tweet_id| create(:ticket_article, message_id: tweet_id) }
  714. end
  715. let(:tweet_ids) do
  716. [1224440380881428480,
  717. 1224426978557800449,
  718. 1224427517869809666,
  719. 1224427776654135297,
  720. 1224428510225354753,
  721. 1223188240078909440,
  722. 1223273797987508227,
  723. 1223103807283810304,
  724. 1223121619561799682,
  725. 1222872891320143878,
  726. 1222881209384161283,
  727. 1222896407524212736,
  728. 1222237955588227075,
  729. 1222108036795334657,
  730. 1222126386334388225,
  731. 1222109934923460608]
  732. end
  733. it 'does not import duplicates' do
  734. expect { channel.fetch }.not_to change(Ticket::Article, :count)
  735. end
  736. end
  737. context 'for very common search terms' do
  738. subject(:channel) { create(:twitter_channel, custom_options: custom_options) }
  739. let(:custom_options) do
  740. {
  741. sync: {
  742. search: [
  743. {
  744. term: 'coronavirus',
  745. group_id: Group.first.id
  746. }
  747. ]
  748. }
  749. }
  750. end
  751. let(:twitter_articles) { Ticket::Article.joins(:type).where(ticket_article_types: { name: 'twitter status' }) }
  752. it 'stops importing threads after 120 new articles' do
  753. channel.fetch
  754. expect((twitter_articles - Ticket.last.articles).count).to be < 120
  755. expect(twitter_articles.count).to be >= 120
  756. end
  757. it 'refuses to import any other tweets for the next 15 minutes' do
  758. channel.fetch
  759. travel(14.minutes)
  760. expect { create(:twitter_channel).fetch }
  761. .not_to change(Ticket::Article, :count)
  762. end
  763. it 'resumes importing again after 15 minutes' do
  764. channel.fetch
  765. travel(15.minutes)
  766. expect { create(:twitter_channel).fetch }
  767. .to change(Ticket::Article, :count)
  768. end
  769. end
  770. context 'and "track_retweets" option' do
  771. subject(:channel) { create(:twitter_channel, custom_options: { sync: { track_retweets: true } }) }
  772. it 'creates an article for each recent tweet/retweet' do
  773. expect { channel.fetch }
  774. .to change { Ticket.where('title LIKE ?', 'RT @%').count }
  775. .and change(Ticket, :count).by(21)
  776. end
  777. end
  778. context 'and "import_older_tweets" option (legacy)' do
  779. subject(:channel) { create(:twitter_channel, :legacy) }
  780. it 'creates an article for each tweet' do
  781. expect { channel.fetch }
  782. .to change { Ticket.where('title LIKE ?', 'GitHub Trending Archive, 2_ Nov 2018, Ruby. %').count }
  783. .and change(Ticket, :count).by(21)
  784. end
  785. end
  786. describe 'Race condition: when #fetch finds a half-processed, outgoing tweet' do
  787. subject!(:channel) { create(:twitter_channel, custom_options: custom_options) }
  788. let(:custom_options) do
  789. {
  790. user: {
  791. # Must match outgoing tweet author Twitter user ID
  792. id: '1205290247124217856',
  793. },
  794. sync: {
  795. search: [
  796. {
  797. term: 'zammadzammadzammad',
  798. group_id: Group.first.id
  799. }
  800. ]
  801. }
  802. }
  803. end
  804. let!(:tweet) { create(:twitter_article, body: 'zammadzammadzammad') }
  805. context '(i.e., after the BG job has posted the article to Twitter…' do
  806. # NOTE: This context block cannot be set up programmatically.
  807. # Instead, the tweet was posted, fetched, recorded into a VCR cassette,
  808. # and then manually copied into the existing VCR cassette for this example.
  809. context '…but before the BG job has "synced" article.message_id with tweet.id)' do
  810. let(:twitter_job) { Delayed::Job.find_by(handler: <<~YML) }
  811. --- !ruby/object:Observer::Ticket::Article::CommunicateTwitter::BackgroundJob
  812. article_id: #{tweet.id}
  813. YML
  814. around do |example|
  815. # This test case requires the use_vcr: :time_sensitive option
  816. # to travel_to(when the VCR cassette was recorded).
  817. #
  818. # This ensures that #fetch doesn't ignore
  819. # the "older" tweets stored in the VCR cassette,
  820. # but it also freezes time,
  821. # which breaks this race condition handling logic:
  822. #
  823. # break if Delayed::Job.where('created_at < ?', Time.current).none?
  824. #
  825. # So, we unfreeze time here.
  826. travel_back
  827. # Run BG job (Why not use Scheduler.worker?
  828. # It led to hangs & failures elsewhere in test suite.)
  829. Thread.new do
  830. sleep 5 # simulate other bg jobs holding up the queue
  831. twitter_job.invoke_job
  832. end.tap { example.run }.join
  833. end
  834. it 'does not import the duplicate tweet (waits up to 60s for BG job to finish)' do
  835. expect { channel.fetch }
  836. .to not_change(Ticket::Article, :count)
  837. end
  838. end
  839. end
  840. end
  841. end
  842. end
  843. end
  844. end