Advertisement
paulportellimt

syncEvents

Mar 20th, 2025
182
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.97 KB | None | 0 0
  1. public function syncEvents(User $user, string $calendarId, ?string $syncToken = null)
  2. {
  3.     try {
  4.         $params = [
  5.             'maxResults' => 2500,
  6.             'singleEvents' => true,
  7.         ];
  8.        
  9.         if ($syncToken) {
  10.             $params['syncToken'] = $syncToken;
  11.         } else {
  12.             // If no sync token, use timeMin for full sync
  13.             $params['timeMin'] = date(DATE_RFC3339, strtotime('-30 days'));
  14.         }
  15.        
  16.         $pageToken = null;
  17.         $newSyncToken = null;
  18.        
  19.         do {
  20.             if ($pageToken) {
  21.                 $params['pageToken'] = $pageToken;
  22.             }
  23.            
  24.             $events = $this->calendarService->events->listEvents($calendarId, $params);
  25.             $pageToken = $events->getNextPageToken();
  26.             $newSyncToken = $events->getNextSyncToken();
  27.            
  28.             foreach ($events->getItems() as $event) {
  29.                 // Process each event - update your local database
  30.                 $this->processEvent($user, $calendarId, $event);
  31.             }
  32.         } while ($pageToken);
  33.        
  34.         // Update the sync token in database
  35.         if ($newSyncToken) {
  36.             CalendarWebhook::where('user_id', $user->id)
  37.                 ->where('calendar_id', $calendarId)
  38.                 ->update(['sync_token' => $newSyncToken]);
  39.         }
  40.        
  41.         return true;
  42.     } catch (\Exception $e) {
  43.         // Handle sync token expired
  44.         if (strpos($e->getMessage(), 'Sync token') !== false) {
  45.             // Clear sync token and do a full sync
  46.             CalendarWebhook::where('user_id', $user->id)
  47.                 ->where('calendar_id', $calendarId)
  48.                 ->update(['sync_token' => null]);
  49.            
  50.             // Try again without sync token
  51.             return $this->syncEvents($user, $calendarId, null);
  52.         }
  53.        
  54.         Log::error('Failed to sync Google Calendar events: ' . $e->getMessage());
  55.         return false;
  56.     }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement