twitter_spec.rb 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029
  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 'rate limiting' do
  656. before do
  657. allow(Rails.env).to receive(:test?).and_return(false)
  658. channel.fetch
  659. end
  660. context 'within 20 minutes of last run' do
  661. before { travel(19.minutes) }
  662. it 'aborts' do
  663. expect { channel.fetch }
  664. .not_to change { channel.reload.preferences[:last_fetch] }
  665. end
  666. end
  667. context '20+ minutes since last run' do
  668. before { travel(20.minutes) }
  669. it 'runs again' do
  670. expect { channel.fetch }
  671. .to change { channel.reload.preferences[:last_fetch] }
  672. end
  673. end
  674. end
  675. describe 'Twitter API authentication' do
  676. let(:consumer_credentials) do
  677. {
  678. consumer_key: external_credential.credentials[:consumer_key],
  679. consumer_secret: external_credential.credentials[:consumer_secret],
  680. }
  681. end
  682. let(:oauth_credentials) do
  683. {
  684. access_token: channel.options[:auth][:oauth_token],
  685. access_token_secret: channel.options[:auth][:oauth_token_secret],
  686. }
  687. end
  688. it 'uses consumer key/secret stored on ExternalCredential' do
  689. expect(Twitter::REST::Client)
  690. .to receive(:new).with(hash_including(consumer_credentials))
  691. .and_call_original
  692. channel.fetch
  693. end
  694. it 'uses OAuth token/secret stored on #options hash' do
  695. expect(Twitter::REST::Client)
  696. .to receive(:new).with(hash_including(oauth_credentials))
  697. .and_call_original
  698. channel.fetch
  699. end
  700. end
  701. describe 'Twitter API activity' do
  702. it 'sets successful status attributes' do
  703. expect { channel.fetch }
  704. .to change { channel.reload.attributes }
  705. .to hash_including(
  706. 'status_in' => 'ok',
  707. 'last_log_in' => '',
  708. 'status_out' => nil,
  709. 'last_log_out' => nil
  710. )
  711. end
  712. context 'with search term configured (at .options[:sync][:search])' do
  713. it 'creates an article for each recent tweet' do
  714. expect { channel.fetch }
  715. .to change(Ticket, :count).by(2)
  716. expect(Ticket.last.attributes).to include(
  717. 'title' => "Come and join our team to bring Zammad even further forward! It's gonna be ama...",
  718. 'preferences' => { 'channel_id' => channel.id,
  719. 'channel_screen_name' => channel.options[:user][:screen_name] },
  720. 'customer_id' => User.find_by(firstname: 'Mr.Generation', lastname: '').id
  721. )
  722. end
  723. context 'for responses to other tweets' do
  724. let(:thread) do
  725. Ticket.joins(articles: :type).where(ticket_article_types: { name: 'twitter status' })
  726. .group('tickets.id').having(
  727. case ActiveRecord::Base.connection_config[:adapter]
  728. when 'mysql2'
  729. 'COUNT("ticket_articles.*") > 1'
  730. when 'postgresql'
  731. 'COUNT(ticket_articles.*) > 1'
  732. end
  733. ).first
  734. end
  735. it 'creates articles for parent tweets as well' do
  736. channel.fetch
  737. expect(thread.articles.last.body).to match(/zammad/i) # search result
  738. expect(thread.articles.first.body).not_to match(/zammad/i) # parent tweet
  739. end
  740. end
  741. context 'and "track_retweets" option' do
  742. context 'is false (default)' do
  743. it 'skips retweets' do
  744. expect { channel.fetch }
  745. .not_to change { Ticket.where('title LIKE ?', 'RT @%').count }.from(0)
  746. end
  747. end
  748. context 'is true' do
  749. subject(:channel) { create(:twitter_channel, custom_options: { sync: { track_retweets: true } }) }
  750. it 'creates an article for each recent tweet/retweet' do
  751. expect { channel.fetch }
  752. .to change { Ticket.where('title LIKE ?', 'RT @%').count }.by(1)
  753. .and change(Ticket, :count).by(3)
  754. end
  755. end
  756. end
  757. context 'and "import_older_tweets" option (legacy)' do
  758. context 'is false (default)' do
  759. it 'skips tweets 15+ days older than channel itself' do
  760. expect { channel.fetch }
  761. .not_to change { Ticket.where('title LIKE ?', 'GitHub Trending Archive, 29 Nov 2018, Ruby. %').count }.from(0)
  762. end
  763. end
  764. context 'is true' do
  765. subject(:channel) { create(:twitter_channel, :legacy) }
  766. it 'creates an article for each tweet' do
  767. expect { channel.fetch }
  768. .to change { Ticket.where('title LIKE ?', 'GitHub Trending Archive, 29 Nov 2018, Ruby. %').count }.by(1)
  769. .and change(Ticket, :count).by(3)
  770. end
  771. end
  772. end
  773. describe 'duplicate handling' do
  774. context 'when fetched tweets have already been imported' do
  775. before do
  776. tweet_ids.each { |tweet_id| create(:ticket_article, message_id: tweet_id) }
  777. end
  778. let(:tweet_ids) { [1222126386334388225, 1222109934923460608] } # rubocop:disable Style/NumericLiterals
  779. it 'does not import duplicates' do
  780. expect { channel.fetch }.not_to change(Ticket::Article, :count)
  781. end
  782. end
  783. describe 'Race condition: when #fetch finds a half-processed, outgoing tweet' do
  784. subject!(:channel) do
  785. create(:twitter_channel,
  786. search_term: 'zammadzammadzammad',
  787. custom_options: {
  788. user: {
  789. # "outgoing" tweets = authored by this Twitter user ID
  790. id: '1205290247124217856',
  791. },
  792. })
  793. end
  794. # This test case requires the use_vcr: :time_sensitive option
  795. # to travel_to(when the VCR cassette was recorded).
  796. #
  797. # This ensures that #fetch doesn't ignore
  798. # the "older" tweets stored in the VCR cassette,
  799. # but it also freezes time,
  800. # which breaks this test expectation logic:
  801. #
  802. # expect { channel.fetch }.to change(Time, :current).by_at_least(5)
  803. #
  804. # So, we unfreeze time here.
  805. before { travel_back }
  806. let!(:tweet) { create(:twitter_article, body: 'zammadzammadzammad') }
  807. context '(i.e., after the BG job has posted the article to Twitter…' do
  808. # NOTE: This context block cannot be set up programmatically.
  809. # Instead, the tweet was posted, fetched, recorded into a VCR cassette,
  810. # and then manually copied into the existing VCR cassette for this example.
  811. context '…but before the BG job has "synced" article.message_id with tweet.id)' do
  812. let(:twitter_job) { Delayed::Job.find_by(handler: <<~YML) }
  813. --- !ruby/object:Observer::Ticket::Article::CommunicateTwitter::BackgroundJob
  814. article_id: #{tweet.id}
  815. YML
  816. around do |example|
  817. # Run BG job (Why not use Scheduler.worker?
  818. # It led to hangs & failures elsewhere in test suite.)
  819. Thread.new do
  820. sleep 5 # simulate other bg jobs holding up the queue
  821. twitter_job.invoke_job
  822. end.tap { example.run }.join
  823. end
  824. it 'does not import the duplicate tweet (waits up to 60s for BG job to finish)' do
  825. expect { channel.fetch }
  826. .to not_change(Ticket::Article, :count)
  827. .and change(Time, :current).by_at_least(5)
  828. end
  829. end
  830. end
  831. # To reproduce this test case, the VCR cassette has been modified
  832. # so that the fetched tweet has a different ("incoming") author user ID.
  833. it 'skips race condition handling for incoming tweets' do
  834. expect { channel.fetch }
  835. .to change(Ticket::Article, :count)
  836. .and change(Time, :current).by_at_most(1)
  837. end
  838. end
  839. end
  840. context 'for very common search terms' do
  841. subject(:channel) { create(:twitter_channel, search_term: 'coronavirus') }
  842. let(:twitter_articles) { Ticket::Article.joins(:type).where(ticket_article_types: { name: 'twitter status' }) }
  843. # NOTE: Ordinarily, RSpec examples should be kept as small as possible.
  844. # In this case, we bundle these examples together because
  845. # separating them would duplicate expensive setup:
  846. # even with HTTP caching, this single example takes nearly a minute.
  847. #
  848. # Also, note that this rate limiting is partially duplicated
  849. # in #fetchable?, which prevents #fetch from running
  850. # more than once in a 20-minute period.
  851. it 'imports max. ~120 articles every 15 minutes' do
  852. channel.fetch
  853. expect((twitter_articles - Ticket.last.articles).count).to be <= 120
  854. expect(twitter_articles.count).to be > 120
  855. travel(14.minutes)
  856. expect { create(:twitter_channel).fetch }
  857. .not_to change(Ticket::Article, :count)
  858. travel(1.minute)
  859. expect { create(:twitter_channel).fetch }
  860. .to change(Ticket::Article, :count)
  861. end
  862. end
  863. end
  864. end
  865. end
  866. end