src/Service/GoogleCalendarService.php line 232

Open in your IDE?
  1. <?php
  2. namespace App\Service;
  3. use App\Entity\Child;
  4. use App\Entity\Guardian;
  5. use App\Entity\Lesson;
  6. use App\Entity\Teacher;
  7. use Doctrine\ORM\EntityManagerInterface;
  8. use Google_Client;
  9. use Google_Service_Calendar;
  10. use Google_Service_Calendar_Event;
  11. use Google_Service_Calendar_EventDateTime;
  12. use Google_Service_Exception;
  13. use Psr\Container\ContainerInterface;
  14. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  15. class GoogleCalendarService
  16. {
  17. private $client;
  18. private EntityManagerInterface $entityManager;
  19. private $user = null;
  20. private UrlGeneratorInterface $urlGenerator;
  21. private ContainerInterface $container;
  22. public function __construct(EntityManagerInterface $entityManager, UrlGeneratorInterface $urlGenerator, ContainerInterface $container)
  23. {
  24. $this->client = new Google_Client();
  25. $this->client->setClientId($_ENV['GOOGLE_ID']);
  26. $this->client->setClientSecret($_ENV['GOOGLE_SECRET']);
  27. $this->client->addScope('https://www.googleapis.com/auth/calendar');
  28. $this->client->addScope('https://www.googleapis.com/auth/calendar.events');
  29. // $this->client->addScope(Google_Service_Calendar::CALENDAR);
  30. $this->entityManager = $entityManager;
  31. $this->urlGenerator = $urlGenerator;
  32. $this->container = $container;
  33. }
  34. public function authenticate($authCode)
  35. {
  36. $accessToken = $this->client->fetchAccessTokenWithAuthCode($authCode);
  37. $this->client->setAccessToken($accessToken);
  38. return $accessToken;
  39. }
  40. public function setAccessToken($accessToken)
  41. {
  42. $this->client->setAccessToken($accessToken);
  43. }
  44. public function setUser($user)
  45. {
  46. $this->client = new Google_Client();
  47. $this->client->setClientId($_ENV['GOOGLE_ID']);
  48. $this->client->setClientSecret($_ENV['GOOGLE_SECRET']);
  49. $this->client->addScope('https://www.googleapis.com/auth/calendar');
  50. $this->client->addScope('https://www.googleapis.com/auth/calendar.events');
  51. if (!$user->getGoogleAccessToken()) {
  52. $this->user = null;
  53. }
  54. $this->user = $user;
  55. $this->client->setAccessToken($user->getGoogleAccessToken());
  56. if ($this->client->isAccessTokenExpired()) {
  57. // Refresh the token if it's expired
  58. $refreshToken = $user->getGoogleRefreshToken();
  59. if ($refreshToken) {
  60. $this->client->fetchAccessTokenWithRefreshToken($refreshToken);
  61. $newAccessToken = $this->client->getAccessToken();
  62. $user->setGoogleAccessToken($newAccessToken);
  63. $this->client->setAccessToken($newAccessToken);
  64. $this->entityManager->persist($user);
  65. $this->entityManager->flush();
  66. } else {
  67. $this->user = null;
  68. }
  69. }
  70. }
  71. public function manageLessonEvent(Lesson $lesson)
  72. {
  73. try {
  74. if ($this->user instanceof Teacher) {
  75. if (!$lesson->getGoogleCalendarIdTeacher()) {
  76. $calendarId = 'primary';
  77. // dump('event create');
  78. $response = $this->createEvent($calendarId, $this->formatLessonEvent($lesson));
  79. if($response) {
  80. $lesson->setGoogleCalendarIdTeacher($response->getId());
  81. }
  82. $this->entityManager->persist($lesson);
  83. $this->entityManager->flush();
  84. if($lesson->getGoogleCalendarIdTeacher()) {
  85. $this->checkForDuplicates($lesson, $lesson->getGoogleCalendarIdTeacher());
  86. }
  87. } else {
  88. $calendarId = 'primary';
  89. $response = $this->updateEvent($calendarId, $lesson->getGoogleCalendarIdTeacher(), $this->formatLessonEvent($lesson));
  90. // dump($response);
  91. // die();
  92. if($response) {
  93. $lesson->setGoogleCalendarIdTeacher($response->getId());
  94. }
  95. $this->entityManager->persist($lesson);
  96. $this->entityManager->flush();
  97. if($lesson->getGoogleCalendarIdTeacher()) {
  98. $this->checkForDuplicates($lesson, $lesson->getGoogleCalendarIdTeacher());
  99. }
  100. }
  101. }
  102. if ($this->user instanceof Child) {
  103. if (!$lesson->getGoogleCalendarIdChild()) {
  104. $calendarId = 'primary';
  105. $response = $this->createEvent($calendarId, $this->formatLessonEvent($lesson));
  106. if($response) {
  107. $lesson->setGoogleCalendarIdChild($response->getId());
  108. }
  109. $this->entityManager->persist($lesson);
  110. $this->entityManager->flush();
  111. if($lesson->getGoogleCalendarIdChild()) {
  112. $this->checkForDuplicates($lesson, $lesson->getGoogleCalendarIdChild());
  113. }
  114. } else {
  115. $calendarId = 'primary';
  116. $response = $this->updateEvent($calendarId, $lesson->getGoogleCalendarIdChild(), $this->formatLessonEvent($lesson));
  117. if($response) {
  118. $lesson->setGoogleCalendarIdChild($response->getId());
  119. }
  120. $this->entityManager->persist($lesson);
  121. $this->entityManager->flush();
  122. if($lesson->getGoogleCalendarIdChild()) {
  123. $this->checkForDuplicates($lesson, $lesson->getGoogleCalendarIdChild());
  124. }
  125. }
  126. }
  127. if ($this->user instanceof Guardian) {
  128. if (!$lesson->getGoogleCalendarIdGuardian()) {
  129. $calendarId = 'primary';
  130. $response = $this->createEvent($calendarId, $this->formatLessonEvent($lesson));
  131. if($response) {
  132. $lesson->setGoogleCalendarIdGuardian($response->getId());
  133. }
  134. $this->entityManager->persist($lesson);
  135. $this->entityManager->flush();
  136. if($lesson->getGoogleCalendarIdGuardian()) {
  137. $this->checkForDuplicates($lesson, $lesson->getGoogleCalendarIdGuardian());
  138. }
  139. } else {
  140. $calendarId = 'primary';
  141. $response = $this->updateEvent($calendarId, $lesson->getGoogleCalendarIdGuardian(), $this->formatLessonEvent($lesson));
  142. if($response) {
  143. $lesson->setGoogleCalendarIdGuardian($response->getId());
  144. }
  145. $this->entityManager->persist($lesson);
  146. $this->entityManager->flush();
  147. if($lesson->getGoogleCalendarIdGuardian()) {
  148. $this->checkForDuplicates($lesson, $lesson->getGoogleCalendarIdGuardian());
  149. }
  150. }
  151. }
  152. } catch (\Exception $e) {
  153. return null;
  154. }
  155. }
  156. public function formatLessonEvent(Lesson $lesson)
  157. {
  158. if ($this->user instanceof Teacher) {
  159. $child = $lesson->getChild();
  160. $name = '';
  161. if ($child) {
  162. $name = $child->getFullname();
  163. }
  164. $summary = "{$lesson->getDiscipline()->getName()} - {$lesson->getClass()} - {$name} | COREPETITUS";
  165. $location = "https://app.corepetitus.lt";
  166. }
  167. if ($this->user instanceof Child || $this->user instanceof Guardian) {
  168. $summary = "{$lesson->getDiscipline()->getName()} - {$lesson->getClass()} - {$lesson->getTeacher()->getFullname()} | COREPETITUS";
  169. $location = $this->container->getParameter('domain') . $this->urlGenerator->generate('unicko_public_router', ['token' => $lesson->getPublicToken()]);
  170. }
  171. $event = [
  172. 'status' => "confirmed",
  173. 'summary' => $summary,
  174. 'location' => $location,
  175. 'start' => new Google_Service_Calendar_EventDateTime([
  176. 'dateTime' => $lesson->getStartTime()->format(\DateTime::RFC3339),
  177. 'timeZone' => 'Europe/Vilnius',
  178. ]),
  179. 'end' => new Google_Service_Calendar_EventDateTime([
  180. 'dateTime' => $lesson->getEndTime()->format(\DateTime::RFC3339),
  181. 'timeZone' => 'Europe/Vilnius',
  182. ]),
  183. ];
  184. return $event;
  185. }
  186. public function createEvent($calendarId = 'primary', $eventData)
  187. {
  188. $service = new Google_Service_Calendar($this->client);
  189. $event = new Google_Service_Calendar_Event($eventData);
  190. try {
  191. return $service->events->insert($calendarId, $event);
  192. } catch (\Exception $e) {
  193. return null;
  194. }
  195. }
  196. public function updateEvent($calendarId = 'primary', $eventId, $eventData)
  197. {
  198. $service = new Google_Service_Calendar($this->client);
  199. $event = $service->events->get($calendarId, $eventId);
  200. foreach ($eventData as $key => $value) {
  201. $event->$key = $value;
  202. }
  203. try {
  204. return $service->events->update($calendarId, $event->getId(), $event);
  205. } catch (\Exception $e) {
  206. return null;
  207. }
  208. }
  209. public function deleteEvent($calendarId = 'primary', $eventId)
  210. {
  211. $service = new Google_Service_Calendar($this->client);
  212. try {
  213. return $service->events->delete($calendarId, $eventId);
  214. } catch (\Exception $e) {
  215. return null;
  216. }
  217. }
  218. public function checkForDuplicates($lesson,$googleCalendarId)
  219. {
  220. $calendarId = 'primary';
  221. $service = new Google_Service_Calendar($this->client);
  222. $summary = '';
  223. if ($this->user instanceof Teacher) {
  224. $child = $lesson->getChild();
  225. $name = '';
  226. if ($child) {
  227. $name = $child->getFullname();
  228. }
  229. $summary = "{$lesson->getDiscipline()->getName()} - {$lesson->getClass()} - {$name} | COREPETITUS";
  230. }
  231. if ($this->user instanceof Child || $this->user instanceof Guardian) {
  232. $summary = "{$lesson->getDiscipline()->getName()} - {$lesson->getClass()} - {$lesson->getTeacher()->getFullname()} | COREPETITUS";
  233. }
  234. if ($this->user instanceof Teacher) {
  235. try {
  236. $events = $service->events->listEvents($calendarId, [
  237. 'q' => "https://app.corepetitus.lt",
  238. 'timeMin' => $lesson->getStartTime()->format(\DateTime::RFC3339),
  239. 'timeMax' => $lesson->getEndTime()->format(\DateTime::RFC3339),
  240. ]);
  241. $items = $events->getItems();
  242. if ($items > 1) {
  243. foreach ($items as $item) {
  244. if ($item->getId() != $googleCalendarId && $item->getLocation() == 'https://app.corepetitus.lt' && $item->getSummary() == $summary) {
  245. $this->deleteEvent($calendarId, $item->getId());
  246. }
  247. }
  248. }
  249. } catch (\Exception $e) {
  250. return null;
  251. }
  252. }
  253. if ($this->user instanceof Child or $this->user instanceof Guardian) {
  254. try {
  255. $events = $service->events->listEvents($calendarId, [
  256. 'q' => "https://app.corepetitus.lt/pamoka/{$lesson->getPublicToken()}",
  257. 'timeMin' => $lesson->getStartTime()->format(\DateTime::RFC3339),
  258. 'timeMax' => $lesson->getEndTime()->format(\DateTime::RFC3339),
  259. ]);
  260. $items = $events->getItems();
  261. if ($items > 1) {
  262. foreach ($items as $item) {
  263. if ($item->getId() != $googleCalendarId && $item->getSummary() == $summary) {
  264. $this->deleteEvent($calendarId, $item->getId());
  265. }
  266. }
  267. }
  268. } catch (\Exception $e) {
  269. return null;
  270. }
  271. }
  272. }
  273. public function deleteEverything()
  274. {
  275. $calendarId = 'primary';
  276. $service = new Google_Service_Calendar($this->client);
  277. try {
  278. $events = $service->events->listEvents($calendarId, [
  279. 'q' => "https://app.corepetitus.lt",
  280. ]);
  281. $items = $events->getItems();
  282. foreach ($items as $item) {
  283. $this->deleteEvent($calendarId, $item->getId());
  284. usleep(500000);
  285. }
  286. } catch (\Exception $e) {
  287. return null;
  288. }
  289. }
  290. }