Updated the Google_sync.php library to work with the updated code.

This commit is contained in:
Alex Tselegidis 2021-10-28 14:00:10 +02:00
parent e4c01f54f8
commit f540922abc

View file

@ -11,50 +11,42 @@
* @since v1.0.0 * @since v1.0.0
* ---------------------------------------------------------------------------- */ * ---------------------------------------------------------------------------- */
use Google\Service\Calendar\Events;
/** /**
* Class Google_sync * Google sync library
* *
* This class implements all the core synchronization between the Google Calendar and the Easy!Appointments system. * Handles Google Calendar API related functionality.
*
* Do not place any model handling inside this library.
* *
* @package Libraries * @package Libraries
*/ */
class Google_sync { class Google_sync {
/** /**
* CodeIgniter Instance
*
* @var EA_Controller * @var EA_Controller
*/ */
protected $CI; protected $CI;
/** /**
* Google API Client
*
* @var Google_Client * @var Google_Client
*/ */
protected $client; protected $client;
/** /**
* Google Calendar Service
*
* @var Google_Service_Calendar * @var Google_Service_Calendar
*/ */
protected $service; protected $service;
/** /**
* Class Constructor * Google_sync constructor.
* *
* This method initializes the Google client class and the Calendar service * This method initializes the Google client class and the Calendar service class so that they can be used by the
* class so that they can be used by the other methods. * other methods.
*/ */
public function __construct() public function __construct()
{ {
$this->CI =& get_instance(); $this->CI =& get_instance();
// Initialize google client and calendar service.
$this->client = new Google_Client(); $this->client = new Google_Client();
$this->client->setApplicationName(config('google_application_name')); $this->client->setApplicationName(config('google_application_name'));
$this->client->setClientId(config('google_client_id')); $this->client->setClientId(config('google_client_id'));
$this->client->setClientSecret(config('google_client_secret')); $this->client->setClientSecret(config('google_client_secret'));
@ -66,7 +58,6 @@ class Google_sync {
Google_Service_Calendar::CALENDAR, Google_Service_Calendar::CALENDAR,
Google_Service_Calendar::CALENDAR_READONLY Google_Service_Calendar::CALENDAR_READONLY
]); ]);
$this->service = new Google_Service_Calendar($this->client); $this->service = new Google_Service_Calendar($this->client);
} }
@ -76,28 +67,26 @@ class Google_sync {
* This url must be used to redirect the user to the Google user consent page, * This url must be used to redirect the user to the Google user consent page,
* where the user grants access to his data for the Easy!Appointments app. * where the user grants access to his data for the Easy!Appointments app.
*/ */
public function get_auth_url() public function get_auth_url(): string
{ {
// "max_auth_age" is needed because the user needs to always log in // The "max_auth_age" is needed because the user needs to always log in and not use an existing session.
// and not use an existing session.
return $this->client->createAuthUrl() . '&max_auth_age=0'; return $this->client->createAuthUrl() . '&max_auth_age=0';
} }
/** /**
* Authenticate the Google API usage. * Authenticate the Google API usage.
* *
* When the user grants consent for his data usage, google is going to redirect * When the user grants consent for his data usage, Google is going to redirect the browser back to the given
* the browser back to the given redirect url. There a authentication code is * redirect URL. There an authentication code is provided. Using this code, we can authenticate the API usage and
* provided. Using this code, we can authenticate the API usage and store the * store the token information to the database.
* token information to the database.
* *
* @param $code * @param string $code
* *
* @return array * @return array
* *
* @throws Exception * @throws Exception
*/ */
public function authenticate($code) public function authenticate(string $code): array
{ {
$response = $this->client->fetchAccessTokenWithAuthCode($code); $response = $this->client->fetchAccessTokenWithAuthCode($code);
@ -112,17 +101,14 @@ class Google_sync {
/** /**
* Refresh the Google Client access token. * Refresh the Google Client access token.
* *
* This method must be executed every time we need to make actions on a * This method must be executed every time we need to make actions on a provider's Google Calendar account. A new
* provider's Google Calendar account. A new token is necessary and the * token is necessary and the only way to get it is to use the stored refresh token that was provided when the
* only way to get it is to use the stored refresh token that was provided * provider granted consent to Easy!Appointments for use his Google Calendar account.
* when the provider granted consent to Easy!Appointments for use his
* Google Calendar account.
* *
* @param string $refresh_token The provider's refresh token. This value is * @param string $refresh_token The provider's refresh token. This value is stored in the database and used every
* stored in the database and used every time we need to make actions to his * time we need to make actions to his Google Calendar account.
* Google Caledar account.
*/ */
public function refresh_token($refresh_token) public function refresh_token(string $refresh_token)
{ {
$this->client->refreshToken($refresh_token); $this->client->refreshToken($refresh_token);
} }
@ -134,31 +120,31 @@ class Google_sync {
* and the stored access token is still valid. If yes, the selected appointment record is going to be added to the * and the stored access token is still valid. If yes, the selected appointment record is going to be added to the
* Google Calendar account. * Google Calendar account.
* *
* @param array $appointment Contains the appointment record data. * @param array $appointment Appointment data.
* @param array $provider Contains the provider record data. * @param array $provider Provider data.
* @param array $service Contains the service record data. * @param array $service Service data.
* @param array $customer Contains the customer recod data. * @param array $customer Customer data.
* @param array $settings Contains some company settings that are used by this method. * @param array $settings Required settings.
* *
* @return Google_Service_Calendar_Event Returns the Google_Event class object. * @return Google_Service_Calendar_Event Returns the Google_Event class object.
*
* @throws Exception
*/ */
public function add_appointment($appointment, $provider, $service, $customer, $settings) public function add_appointment(array $appointment, array $provider, array $service, array $customer, array $settings): Google_Service_Calendar_Event
{ {
$this->CI->load->helper('general');
$event = new Google_Service_Calendar_Event(); $event = new Google_Service_Calendar_Event();
$event->setSummary(($service != NULL) ? $service['name'] : 'Unavailable'); $event->setSummary(! empty($service) ? $service['name'] : 'Unavailable');
$event->setDescription($appointment['notes']); $event->setDescription($appointment['notes']);
$event->setLocation(isset($appointment['location']) ? $appointment['location'] : $settings['company_name']); $event->setLocation($appointment['location'] ?? $settings['company_name']);
$timezone = new DateTimeZone($provider['timezone']); $timezone = new DateTimeZone($provider['timezone']);
$start = new Google_Service_Calendar_EventDateTime(); $start = new Google_Service_Calendar_EventDateTime();
$start->setDateTime((new DateTime($appointment['start_datetime'], $timezone))->format(DateTime::RFC3339)); $start->setDateTime((new DateTime($appointment['start_datetime'], $timezone))->format(DateTimeInterface::RFC3339));
$event->setStart($start); $event->setStart($start);
$end = new Google_Service_Calendar_EventDateTime(); $end = new Google_Service_Calendar_EventDateTime();
$end->setDateTime((new DateTime($appointment['end_datetime'], $timezone))->format(DateTime::RFC3339)); $end->setDateTime((new DateTime($appointment['end_datetime'], $timezone))->format(DateTimeInterface::RFC3339));
$event->setEnd($end); $event->setEnd($end);
$event->attendees = []; $event->attendees = [];
@ -169,7 +155,7 @@ class Google_sync {
$event_provider->setEmail($provider['email']); $event_provider->setEmail($provider['email']);
$event->attendees[] = $event_provider; $event->attendees[] = $event_provider;
if ($customer != NULL) if ( ! empty($customer))
{ {
$event_customer = new Google_Service_Calendar_EventAttendee(); $event_customer = new Google_Service_Calendar_EventAttendee();
$event_customer->setDisplayName($customer['first_name'] . ' ' . $customer['last_name']); $event_customer->setDisplayName($customer['first_name'] . ' ' . $customer['last_name']);
@ -177,45 +163,43 @@ class Google_sync {
$event->attendees[] = $event_customer; $event->attendees[] = $event_customer;
} }
// Add the new event to the google calendar. // Add the new event to the Google Calendar.
$created_event = $this->service->events->insert($provider['settings']['google_calendar'], $event); return $this->service->events->insert($provider['settings']['google_calendar'], $event);
return $created_event;
} }
/** /**
* Update an existing appointment that is already synced with Google Calendar. * Update an existing appointment that is already synced with Google Calendar.
* *
* This method updates the google calendar event item that is connected with the * This method updates the Google Calendar event item that is connected with the provided appointment record of
* provided appointment record of Easy!Appointments. * Easy!Appointments.
* *
* @param array $appointment Contains the appointment record data. * @param array $appointment Appointment data.
* @param array $provider Contains the provider record data. * @param array $provider Provider data.
* @param array $service Contains the service record data. * @param array $service Service data.
* @param array $customer Contains the customer recod data. * @param array $customer Customer data.
* @parma array $settings Contains some company settings that are used by this method. * @parma array $settings Required settings.
* *
* @return Google_Service_Calendar_Event Returns the Google_Service_Calendar_Event class object. * @return Google_Service_Calendar_Event Returns the Google_Service_Calendar_Event class object.
*
* @throws Exception
*/ */
public function update_appointment($appointment, $provider, $service, $customer, $settings) public function update_appointment(array $appointment, array $provider, array $service, array $customer, array $settings): Google_Service_Calendar_Event
{ {
$this->CI->load->helper('general');
$event = $this->service->events->get($provider['settings']['google_calendar'], $event = $this->service->events->get($provider['settings']['google_calendar'],
$appointment['id_google_calendar']); $appointment['id_google_calendar']);
$event->setSummary($service['name']); $event->setSummary($service['name']);
$event->setDescription($appointment['notes']); $event->setDescription($appointment['notes']);
$event->setLocation(isset($appointment['location']) ? $appointment['location'] : $settings['company_name']); $event->setLocation($appointment['location'] ?? $settings['company_name']);
$timezone = new DateTimeZone($provider['timezone']); $timezone = new DateTimeZone($provider['timezone']);
$start = new Google_Service_Calendar_EventDateTime(); $start = new Google_Service_Calendar_EventDateTime();
$start->setDateTime((new DateTime($appointment['start_datetime'], $timezone))->format(DateTime::RFC3339)); $start->setDateTime((new DateTime($appointment['start_datetime'], $timezone))->format(DateTimeInterface::RFC3339));
$event->setStart($start); $event->setStart($start);
$end = new Google_Service_Calendar_EventDateTime(); $end = new Google_Service_Calendar_EventDateTime();
$end->setDateTime((new DateTime($appointment['end_datetime'], $timezone))->format(DateTime::RFC3339)); $end->setDateTime((new DateTime($appointment['end_datetime'], $timezone))->format(DateTimeInterface::RFC3339));
$event->setEnd($end); $event->setEnd($end);
$event->attendees = []; $event->attendees = [];
@ -225,7 +209,7 @@ class Google_sync {
$event_provider->setEmail($provider['email']); $event_provider->setEmail($provider['email']);
$event->attendees[] = $event_provider; $event->attendees[] = $event_provider;
if ($customer != NULL) if ( ! empty($customer))
{ {
$event_customer = new Google_Service_Calendar_EventAttendee(); $event_customer = new Google_Service_Calendar_EventAttendee();
$event_customer->setDisplayName($customer['first_name'] . ' ' $event_customer->setDisplayName($customer['first_name'] . ' '
@ -234,43 +218,32 @@ class Google_sync {
$event->attendees[] = $event_customer; $event->attendees[] = $event_customer;
} }
$updated_event = $this->service->events->update($provider['settings']['google_calendar'], return $this->service->events->update($provider['settings']['google_calendar'], $event->getId(), $event);
$event->getId(), $event);
return $updated_event;
} }
/** /**
* Delete an existing appointment from Google Calendar. * Delete an existing appointment from Google Calendar.
* *
* @param array $provider Contains the provider record data. * @param array $provider Provider data.
* @param string $google_event_id The Google Calendar event id to * @param string $google_event_id The Google Calendar event ID to be removed.
* be deleted.
*/ */
public function delete_appointment($provider, $google_event_id) public function delete_appointment(array $provider, string $google_event_id)
{ {
try $this->service->events->delete($provider['settings']['google_calendar'], $google_event_id);
{
$this->service->events->delete($provider['settings']['google_calendar'], $google_event_id);
}
catch (Exception $ex)
{
// Event was not found on Google Calendar.
}
} }
/** /**
* Add unavailable period event to Google Calendar. * Add unavailable period event to Google Calendar.
* *
* @param array $provider Contains the provider record data. * @param array $provider Provider data.
* @param array $unavailable Contains unavailable period's data. * @param array $unavailable Unavailable data.
* *
* @return Google_Service_Calendar_Event Returns the google event's object. * @return Google_Service_Calendar_Event Returns the Google event.
*
* @throws Exception
*/ */
public function add_unavailable($provider, $unavailable) public function add_unavailable(array $provider, array $unavailable): Google_Service_Calendar_Event
{ {
$this->CI->load->helper('general');
$event = new Google_Service_Calendar_Event(); $event = new Google_Service_Calendar_Event();
$event->setSummary('Unavailable'); $event->setSummary('Unavailable');
$event->setDescription($unavailable['notes']); $event->setDescription($unavailable['notes']);
@ -278,79 +251,67 @@ class Google_sync {
$timezone = new DateTimeZone($provider['timezone']); $timezone = new DateTimeZone($provider['timezone']);
$start = new Google_Service_Calendar_EventDateTime(); $start = new Google_Service_Calendar_EventDateTime();
$start->setDateTime((new DateTime($unavailable['start_datetime'], $timezone))->format(DateTime::RFC3339)); $start->setDateTime((new DateTime($unavailable['start_datetime'], $timezone))->format(DateTimeInterface::RFC3339));
$event->setStart($start); $event->setStart($start);
$end = new Google_Service_Calendar_EventDateTime(); $end = new Google_Service_Calendar_EventDateTime();
$end->setDateTime((new DateTime($unavailable['end_datetime'], $timezone))->format(DateTime::RFC3339)); $end->setDateTime((new DateTime($unavailable['end_datetime'], $timezone))->format(DateTimeInterface::RFC3339));
$event->setEnd($end); $event->setEnd($end);
// Add the new event to the google calendar. // Add the new event to the Google Calendar.
$created_event = $this->service->events->insert($provider['settings']['google_calendar'], $event); return $this->service->events->insert($provider['settings']['google_calendar'], $event);
return $created_event;
} }
/** /**
* Update Google Calendar unavailable period event. * Update Google Calendar unavailable period event.
* *
* @param array $provider Contains the provider record data. * @param array $provider Provider data.
* @param array $unavailable Contains the unavailable period data. * @param array $unavailable Unavailable data.
* *
* @return Google_Service_Calendar_Event Returns the Google_Service_Calendar_Event object. * @return Google_Service_Calendar_Event Returns the Google_Service_Calendar_Event object.
*
* @throws Exception
*/ */
public function update_unavailable($provider, $unavailable) public function update_unavailable(array $provider, array $unavailable): Google_Service_Calendar_Event
{ {
$this->CI->load->helper('general'); $event = $this->service->events->get($provider['settings']['google_calendar'], $unavailable['id_google_calendar']);
$event = $this->service->events->get($provider['settings']['google_calendar'],
$unavailable['id_google_calendar']);
$event->setDescription($unavailable['notes']); $event->setDescription($unavailable['notes']);
$timezone = new DateTimeZone($provider['timezone']); $timezone = new DateTimeZone($provider['timezone']);
$start = new Google_Service_Calendar_EventDateTime(); $start = new Google_Service_Calendar_EventDateTime();
$start->setDateTime((new DateTime($unavailable['start_datetime'], $timezone))->format(DateTime::RFC3339)); $start->setDateTime((new DateTime($unavailable['start_datetime'], $timezone))->format(DateTimeInterface::RFC3339));
$event->setStart($start); $event->setStart($start);
$end = new Google_Service_Calendar_EventDateTime(); $end = new Google_Service_Calendar_EventDateTime();
$end->setDateTime((new DateTime($unavailable['end_datetime'], $timezone))->format(DateTime::RFC3339)); $end->setDateTime((new DateTime($unavailable['end_datetime'], $timezone))->format(DateTimeInterface::RFC3339));
$event->setEnd($end); $event->setEnd($end);
$updated_event = $this->service->events->update($provider['settings']['google_calendar'], return $this->service->events->update($provider['settings']['google_calendar'], $event->getId(), $event);
$event->getId(), $event);
return $updated_event;
} }
/** /**
* Delete unavailable period event from Google Calendar. * Delete unavailable period event from Google Calendar.
* *
* @param array $provider Contains the provider record data. * @param array $provider Provider data.
* @param string $google_event_id Google Calendar event id to be deleted. * @param string $google_event_id Google Calendar event ID to be removed.
*/ */
public function delete_unavailable($provider, $google_event_id) public function delete_unavailable(array $provider, string $google_event_id)
{ {
try $this->service->events->delete($provider['settings']['google_calendar'], $google_event_id);
{
$this->service->events->delete($provider['settings']['google_calendar'], $google_event_id);
}
catch (Exception $ex)
{
// Event was not found on Google Calendar.
}
} }
/** /**
* Get an event object from gcal * Get a Google Calendar event.
* *
* @param array $provider Contains the provider record data. * @param array $provider Provider data.
* @param string $google_event_id Id of the google calendar event. * @param string $google_event_id Google Calendar event ID.
* *
* @return Google_Service_Calendar_Event Returns the google event object. * @return Google_Service_Calendar_Event Returns the Google Calendar event.
*/ */
public function get_event($provider, $google_event_id) public function get_event(array $provider, string $google_event_id): Google_Service_Calendar_Event
{ {
return $this->service->events->get($provider['settings']['google_calendar'], $google_event_id); return $this->service->events->get($provider['settings']['google_calendar'], $google_event_id);
} }
@ -358,20 +319,17 @@ class Google_sync {
/** /**
* Get all the events between the sync period. * Get all the events between the sync period.
* *
* @param string $google_calendar The name of the google calendar to be used. * @param string $google_calendar The name of the Google Calendar to be used.
* @param string $start The start date of sync period. * @param string $start The start date of sync period.
* @param string $end The end date of sync period. * @param string $end The end date of sync period.
* *
* @return object Returns an array with Google_Service_Calendar_Event objects that belong on the given * @return Events Returns a collection of events.
* sync period (start, end).
*/ */
public function get_sync_events($google_calendar, $start, $end) public function get_sync_events(string $google_calendar, string $start, string $end): Events
{ {
$this->CI->load->helper('general');
$params = [ $params = [
'timeMin' => date(DateTime::RFC3339, $start), 'timeMin' => date(DateTimeInterface::RFC3339, $start),
'timeMax' => date(DateTime::RFC3339, $end), 'timeMax' => date(DateTimeInterface::RFC3339, $end),
'singleEvents' => TRUE, 'singleEvents' => TRUE,
]; ];
@ -379,20 +337,20 @@ class Google_sync {
} }
/** /**
* Return available google calendars for specific user. * Return available Google Calendars for specific user.
* *
* The given user's token must already exist in db in order to get access to his * The given user's token must already exist in db in order to get access to his
* Google Calendar account. * Google Calendar account.
* *
* @param string $google_token The user's token will be used to grant access to google calendar.
*
* @return array Returns an array with the available calendars. * @return array Returns an array with the available calendars.
*/ */
public function get_google_calendars() public function get_google_calendars(): array
{ {
$calendarList = $this->service->calendarList->listCalendarList(); $calendar_list = $this->service->calendarList->listCalendarList();
$calendars = []; $calendars = [];
foreach ($calendarList->items as $google_calendar)
foreach ($calendar_list->items as $google_calendar)
{ {
if ($google_calendar->getAccessRole() === 'reader') if ($google_calendar->getAccessRole() === 'reader')
{ {
@ -404,6 +362,7 @@ class Google_sync {
'summary' => $google_calendar->summary 'summary' => $google_calendar->summary
]; ];
} }
return $calendars; return $calendars;
} }
} }