|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +# Deletes events that exist in a user's Google Calendar but have no tracking |
| 4 | +# row in google_calendar_events. These orphans were left behind when tracking |
| 5 | +# rows were cascade-destroyed (e.g. meeting times destroyed on schedule |
| 6 | +# re-upload) without deleting the real events, so every subsequent sync |
| 7 | +# created a duplicate next to them. |
| 8 | +# |
| 9 | +# The app owns these calendars end-to-end, so any untracked event is one we |
| 10 | +# created and lost the pointer to. Modified instances of a tracked recurring |
| 11 | +# series are preserved (user-edited occurrences carry their own event id). |
| 12 | +# |
| 13 | +# Run with dry_run: true first to log what would be deleted without deleting. |
| 14 | +class CleanupUntrackedGoogleEventsJob < ApplicationJob |
| 15 | + include GoogleApiRateLimiter |
| 16 | + |
| 17 | + queue_as :low |
| 18 | + |
| 19 | + def perform(google_calendar_id = nil, dry_run: false) |
| 20 | + calendars = if google_calendar_id |
| 21 | + GoogleCalendar.where(id: google_calendar_id) |
| 22 | + else |
| 23 | + GoogleCalendar.all |
| 24 | + end |
| 25 | + |
| 26 | + totals = { scanned: 0, deleted: 0, errors: 0 } |
| 27 | + |
| 28 | + calendars.find_each do |calendar| |
| 29 | + stats = reconcile_calendar(calendar, dry_run: dry_run) |
| 30 | + totals.each_key { |key| totals[key] += stats[key] } |
| 31 | + rescue => e |
| 32 | + totals[:errors] += 1 |
| 33 | + Rails.logger.error "[CleanupUntrackedGoogleEventsJob] Failed for calendar #{calendar.id}: #{e.message}" |
| 34 | + end |
| 35 | + |
| 36 | + Rails.logger.info "[CleanupUntrackedGoogleEventsJob] Completed (dry_run: #{dry_run}): #{totals.to_json}" |
| 37 | + totals |
| 38 | + end |
| 39 | + |
| 40 | + private |
| 41 | + |
| 42 | + def reconcile_calendar(calendar, dry_run:) |
| 43 | + stats = { scanned: 0, deleted: 0, errors: 0 } |
| 44 | + tracked_ids = calendar.google_calendar_events.pluck(:google_event_id).to_set |
| 45 | + |
| 46 | + untracked = [] |
| 47 | + page_token = nil |
| 48 | + |
| 49 | + loop do |
| 50 | + response = with_rate_limit_handling do |
| 51 | + calendar_service.list_events( |
| 52 | + calendar.google_calendar_id, |
| 53 | + max_results: 2500, |
| 54 | + page_token: page_token, |
| 55 | + show_deleted: false |
| 56 | + ) |
| 57 | + end |
| 58 | + |
| 59 | + Array(response.items).each do |event| |
| 60 | + stats[:scanned] += 1 |
| 61 | + next if event.status == "cancelled" |
| 62 | + next if tracked_ids.include?(event.id) |
| 63 | + # A user-edited occurrence of a tracked recurring series gets its own |
| 64 | + # event id; deleting it would wipe the user's edit. |
| 65 | + next if event.recurring_event_id.present? && tracked_ids.include?(event.recurring_event_id) |
| 66 | + |
| 67 | + untracked << event |
| 68 | + end |
| 69 | + |
| 70 | + page_token = response.next_page_token |
| 71 | + break if page_token.blank? |
| 72 | + end |
| 73 | + |
| 74 | + if dry_run |
| 75 | + untracked.each do |event| |
| 76 | + Rails.logger.info "[CleanupUntrackedGoogleEventsJob] [dry run] Would delete #{event.id} " \ |
| 77 | + "(#{event.summary.inspect}) from calendar #{calendar.id}" |
| 78 | + end |
| 79 | + stats[:deleted] = untracked.size |
| 80 | + return stats |
| 81 | + end |
| 82 | + |
| 83 | + with_batch_throttling(untracked) do |event| |
| 84 | + delete_untracked_event(calendar, event) |
| 85 | + stats[:deleted] += 1 |
| 86 | + rescue Google::Apis::Error => e |
| 87 | + stats[:errors] += 1 |
| 88 | + Rails.logger.error "[CleanupUntrackedGoogleEventsJob] Failed to delete #{event.id} " \ |
| 89 | + "from calendar #{calendar.id}: #{e.message}" |
| 90 | + end |
| 91 | + |
| 92 | + Rails.logger.info "[CleanupUntrackedGoogleEventsJob] Calendar #{calendar.id}: " \ |
| 93 | + "#{stats[:deleted]} untracked events deleted (#{stats[:scanned]} scanned)" |
| 94 | + stats |
| 95 | + end |
| 96 | + |
| 97 | + def delete_untracked_event(calendar, event) |
| 98 | + calendar_service.delete_event(calendar.google_calendar_id, event.id) |
| 99 | + Rails.logger.info "[CleanupUntrackedGoogleEventsJob] Deleted #{event.id} " \ |
| 100 | + "(#{event.summary.inspect}) from calendar #{calendar.id}" |
| 101 | + rescue Google::Apis::ClientError => e |
| 102 | + raise unless e.status_code == 404 |
| 103 | + end |
| 104 | + |
| 105 | + # The service account created and owns every app-managed calendar, so it can |
| 106 | + # list and delete regardless of the state of the user's OAuth tokens. |
| 107 | + def calendar_service |
| 108 | + @calendar_service ||= begin |
| 109 | + service = Google::Apis::CalendarV3::CalendarService.new |
| 110 | + service.authorization = service_account_credentials |
| 111 | + service |
| 112 | + end |
| 113 | + end |
| 114 | + |
| 115 | + def service_account_credentials |
| 116 | + service_account_config = Rails.application.credentials.dig(:google, :service_account) |
| 117 | + |
| 118 | + credentials_json = if service_account_config.is_a?(String) |
| 119 | + service_account_config |
| 120 | + else |
| 121 | + service_account_config.to_json |
| 122 | + end |
| 123 | + |
| 124 | + Google::Auth::ServiceAccountCredentials.make_creds( |
| 125 | + json_key_io: StringIO.new(credentials_json), |
| 126 | + scope: Google::Apis::CalendarV3::AUTH_CALENDAR |
| 127 | + ) |
| 128 | + end |
| 129 | +end |
0 commit comments