2022-12-27 22:41:07 +01:00
# frozen_string_literal: true
2014-12-12 23:45:49 +01:00
class ShareWorker
include Sidekiq :: Worker
2021-12-25 13:40:21 +01:00
sidekiq_options queue : :share , retry : 5
2014-12-12 23:45:49 +01:00
2014-12-27 17:33:49 +01:00
# @param user_id [Integer] the user id
# @param answer_id [Integer] the user id
2021-12-25 13:40:21 +01:00
# @param service [String] the service to post to
2023-01-02 09:41:14 +01:00
def perform ( user_id , answer_id , service ) # rubocop:disable Metrics/AbcSize
2023-01-03 12:38:19 +01:00
@user_service = User . find ( user_id ) . services . find_by! ( type : " Services:: #{ service . camelize } " )
2021-12-25 13:40:21 +01:00
2023-01-02 09:09:29 +01:00
@user_service . post ( Answer . find ( answer_id ) )
2021-12-27 17:44:42 +01:00
rescue ActiveRecord :: RecordNotFound
2021-12-27 18:17:47 +01:00
logger . info " Tried to post answer # #{ answer_id } for user # #{ user_id } to #{ service . titleize } but the user/answer/service did not exist (likely deleted), will not retry. "
2021-12-27 17:44:42 +01:00
# The question to be posted was deleted
rescue Twitter :: Error :: DuplicateStatus
2021-12-27 23:03:51 +01:00
logger . info " Tried to post answer # #{ answer_id } from user # #{ user_id } to Twitter but the status was already posted. "
2022-12-27 17:53:02 +01:00
rescue Twitter :: Error :: Forbidden
# User's Twitter account is suspended
logger . info " Tried to post answer # #{ answer_id } from user # #{ user_id } to Twitter but the account is suspended. "
2021-12-27 17:44:42 +01:00
rescue Twitter :: Error :: Unauthorized
# User's Twitter token has expired or been revoked
2023-01-02 09:36:28 +01:00
logger . info " Tried to post answer # #{ answer_id } from user # #{ user_id } to Twitter but the token has expired or been revoked. "
2023-01-01 23:52:46 +01:00
revoke_and_notify ( user_id , service )
rescue = > e
logger . info " failed to post answer #{ answer_id } to #{ service } for user #{ user_id } : #{ e . message } "
Sentry . capture_exception ( e )
raise
end
def revoke_and_notify ( user_id , service )
2023-01-02 09:09:29 +01:00
@user_service . destroy
2023-01-01 23:46:10 +01:00
2023-01-02 09:30:51 +01:00
Notification :: ServiceTokenExpired . create (
2023-01-01 23:46:10 +01:00
target_id : user_id ,
target_type : " User::Expired #{ service . camelize } ServiceConnection " ,
recipient_id : user_id ,
new : true
)
2014-12-12 23:45:49 +01:00
end
2015-07-27 08:59:56 +02:00
end