diff --git a/build.gradle b/build.gradle index 9afef0c..68841ec 100644 --- a/build.gradle +++ b/build.gradle @@ -6,8 +6,8 @@ apply plugin: 'java' apply plugin: 'application' mainClassName = 'App' -sourceCompatibility = 1.8 -targetCompatibility = 1.8 +sourceCompatibility = 11 +targetCompatibility = 11 version = '1.0' compileJava.options.encoding = 'UTF-8' compileTestJava.options.encoding = "UTF-8" @@ -18,17 +18,17 @@ repositories { } dependencies { - implementation 'mysql:mysql-connector-java:8.0.25' + implementation 'mysql:mysql-connector-java:8.0.28' implementation 'org.apache.httpcomponents:httpclient:4.5.13' implementation 'com.googlecode.json-simple:json-simple:1.1.1' - implementation 'com.google.code.gson:gson:2.8.8' + implementation 'com.google.code.gson:gson:2.9.0' implementation platform('com.amazonaws:aws-java-sdk-bom:1.11.896') - implementation 'com.amazonaws:aws-java-sdk-s3:1.12.53' + implementation 'com.amazonaws:aws-java-sdk-s3:1.12.173' + implementation 'com.google.api-client:google-api-client:1.33.2' + implementation 'com.google.oauth-client:google-oauth-client-jetty:1.33.1' + implementation 'com.google.apis:google-api-services-calendar:v3-rev20211026-1.32.1' testImplementation 'junit:junit:4.13.2' - compile 'com.google.api-client:google-api-client:1.32.1' - compile 'com.google.oauth-client:google-oauth-client-jetty:1.32.1' - compile 'com.google.apis:google-api-services-calendar:v3-rev20210804-1.32.1' - compile 'com.google.guava:guava:30.1.1-jre' + compile 'com.google.guava:guava:31.1-jre' compile group: 'commons-cli', name: 'commons-cli', version: '1.3.1' compile group: 'net.sourceforge.argparse4j', name: 'argparse4j', version: '0.8.1' compile group: 'org.apache.logging.log4j', name: 'log4j-api', version: '2.14.1' diff --git a/src/main/java/de/jeyp91/googlecalendar/CalendarConfigProvider.java b/src/main/java/de/jeyp91/googlecalendar/CalendarConfigProvider.java index bd29ab5..f3bad9c 100644 --- a/src/main/java/de/jeyp91/googlecalendar/CalendarConfigProvider.java +++ b/src/main/java/de/jeyp91/googlecalendar/CalendarConfigProvider.java @@ -33,21 +33,13 @@ public class CalendarConfigProvider { return googleCalendarConfig; } - public static String getCalendarUrl(int league) { - - // Overwrite league from 2 to 1 because they share one calendar - league = league == 2 ? 1 : league; - - JSONObject leagueConfig = (JSONObject) getGoogleCalendarConfig().get(String.valueOf(league)); + public static String getCalendarUrl() { + JSONObject leagueConfig = (JSONObject) getGoogleCalendarConfig().get(String.valueOf(1)); return (String) leagueConfig.get("url"); } - public static String getCalendarId(int league) { - - // Overwrite league from 2 to 1 because they share one calendar - league = league == 2 ? 1 : league; - - JSONObject leagueConfig = (JSONObject) getGoogleCalendarConfig().get(String.valueOf(league)); + public static String getCalendarId() { + JSONObject leagueConfig = (JSONObject) getGoogleCalendarConfig().get(String.valueOf(1)); return (String) leagueConfig.get("id"); } } diff --git a/src/main/java/de/jeyp91/googlecalendar/ConditionalModificationSample.java b/src/main/java/de/jeyp91/googlecalendar/ConditionalModificationSample.java deleted file mode 100644 index b06f0bf..0000000 --- a/src/main/java/de/jeyp91/googlecalendar/ConditionalModificationSample.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright (c) 2014 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package de.jeyp91.googlecalendar; - -import com.google.api.client.googleapis.json.GoogleJsonResponseException; -import com.google.api.client.http.HttpHeaders; -import com.google.api.services.calendar.Calendar; -import com.google.api.services.calendar.CalendarScopes; -import com.google.api.services.calendar.model.Event; -import com.google.common.collect.Lists; - -import java.io.IOException; -import java.util.List; - -/** - * A sample that demonstrates how to update a - * Calendar resource - * safely, ensuring that other changes aren't overwritten. It does this by passing along the etag of - * the resource being updated in the "If-Match" HTTP header of the request, which will cause the - * request to fail if the version on the server is different. - * - * @author ekoleda+devrel@google.com (Eric Koleda) - */ -public class ConditionalModificationSample { - - /** The maximum number of times to attempt to update the event, before aborting. */ - private static final int MAX_UPDATE_ATTEMPTS = 5; - - /** Global instance of the Calendar client. */ - private static Calendar client; - - public static void main(String[] args) { - try { - List scopes = Lists.newArrayList(CalendarScopes.CALENDAR); - client = Utils.createCalendarClient(scopes); - run(); - } catch (Throwable t) { - t.printStackTrace(); - System.exit(1); - } - } - - /** - * Creates a test event, pauses while the user modifies the event in the Calendar UI, and then - * updates the event with a new location, ensure that the user's changes aren't overwritten. - */ - private static void run() throws IOException { - // Create a test event. - Event event = Utils.createTestEvent(client, "Test Event"); - System.out.println(String.format("Event created: %s", event.getHtmlLink())); - - // Pause while the user modifies the event in the Calendar UI. - System.out.println("Modify the event's description and hit enter to continue."); - System.in.read(); - - // Modify the local copy of the event. - event.setSummary("Updated Test Event"); - - // Update the event, making sure that we don't overwrite other changes. - int numAttempts = 0; - boolean isUpdated = false; - do { - Calendar.Events.Update request = client.events().update("primary", event.getId(), event); - request.setRequestHeaders(new HttpHeaders().setIfMatch(event.getEtag())); - try { - event = request.execute(); - isUpdated = true; - } catch (GoogleJsonResponseException e) { - if (e.getStatusCode() == 412) { - // A 412 status code, "Precondition failed", indicates that the etag values didn't - // match, and the event was updated on the server since we last retrieved it. Use - // {@link Calendar.Events.Get} to retrieve the latest version. - Event latestEvent = client.events().get("primary", event.getId()).execute(); - - // You may want to have more complex logic here to resolve conflicts. In this sample we're - // simply overwriting the summary. - latestEvent.setSummary(event.getSummary()); - event = latestEvent; - } else { - throw e; - } - } - numAttempts++; - } while (!isUpdated && numAttempts <= MAX_UPDATE_ATTEMPTS); - - if (isUpdated) { - System.out.println("Event updated."); - } else { - System.out.println(String.format("Failed to update event after %d attempts.", numAttempts)); - } - } -} \ No newline at end of file diff --git a/src/main/java/de/jeyp91/googlecalendar/ConditionalRetrievalSample.java b/src/main/java/de/jeyp91/googlecalendar/ConditionalRetrievalSample.java deleted file mode 100644 index 8786104..0000000 --- a/src/main/java/de/jeyp91/googlecalendar/ConditionalRetrievalSample.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (c) 2014 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package de.jeyp91.googlecalendar; - -import com.google.api.client.googleapis.json.GoogleJsonResponseException; -import com.google.api.client.http.HttpHeaders; -import com.google.api.services.calendar.Calendar; -import com.google.api.services.calendar.CalendarScopes; -import com.google.api.services.calendar.model.Event; -import com.google.common.collect.Lists; - -import java.io.IOException; -import java.util.List; - -/** - * A sample that demonstrates how to determine if a - * Calendar resource - * has been modified since you last retrieved it. It does this by passing along the etag of the - * resource being retrieved in the "If-None-Match" HTTP header of the request, which will cause the - * request to fail if the version on the server is the same as the local version. - * - * @author ekoleda+devrel@google.com (Eric Koleda) - */ -public class ConditionalRetrievalSample { - - /** Global instance of the Calendar client. */ - private static Calendar client; - - public static void main(String[] args) { - try { - List scopes = Lists.newArrayList(CalendarScopes.CALENDAR); - client = Utils.createCalendarClient(scopes); - run(); - } catch (Throwable t) { - t.printStackTrace(); - System.exit(1); - } - } - - /** - * Creates a test event, pauses while the user modifies the event in the Calendar UI, and then - * checks if the event has been modified. - */ - private static void run() throws IOException { - // Create a test event. - Event event = Utils.createTestEvent(client, "Test Event"); - System.out.println(String.format("Event created: %s", event.getHtmlLink())); - - // Pause while the user modifies the event in the Calendar UI. - System.out.println("Modify the event's description and hit enter to continue."); - System.in.read(); - - // Fetch the event again if it's been modified. - Calendar.Events.Get getRequest = client.events().get("primary", event.getId()); - getRequest.setRequestHeaders(new HttpHeaders().setIfNoneMatch(event.getEtag())); - try { - event = getRequest.execute(); - System.out.println("The event was modified, retrieved latest version."); - } catch (GoogleJsonResponseException e) { - if (e.getStatusCode() == 304) { - // A 304 status code, "Not modified", indicates that the etags match, and the event has - // not been modified since we last retrieved it. - System.out.println("The event was not modified, using local version."); - } else { - throw e; - } - } - } -} diff --git a/src/main/java/de/jeyp91/googlecalendar/GoogleCalendarConnector.java b/src/main/java/de/jeyp91/googlecalendar/GoogleCalendarConnector.java index 2e00b69..cfbb882 100644 --- a/src/main/java/de/jeyp91/googlecalendar/GoogleCalendarConnector.java +++ b/src/main/java/de/jeyp91/googlecalendar/GoogleCalendarConnector.java @@ -9,23 +9,15 @@ import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.gson.GsonFactory; -import com.google.api.client.util.DateTime; import com.google.api.client.util.store.FileDataStoreFactory; import com.google.api.services.calendar.CalendarScopes; import com.google.api.services.calendar.Calendar; -import com.google.api.services.calendar.model.Event; -import com.google.api.services.calendar.model.EventDateTime; -import com.google.api.services.calendar.model.EventReminder; -import com.google.api.services.calendar.model.Events; -import de.jeyp91.tippliga.TLWLeague; -import de.jeyp91.tippliga.TLWMatchday; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.security.GeneralSecurityException; -import java.util.Arrays; import java.util.Collections; import java.util.List; @@ -38,7 +30,7 @@ public class GoogleCalendarConnector { * Global instance of the scopes required by this quickstart. * If modifying these scopes, delete your previously saved tokens/ folder. */ - private static final List SCOPES = Collections.singletonList(CalendarScopes.CALENDAR_READONLY); + private static final List SCOPES = Collections.singletonList(CalendarScopes.CALENDAR); private static final String CREDENTIALS_FILE_PATH = "/Google_Credentials.json"; /** @@ -62,95 +54,25 @@ public class GoogleCalendarConnector { .setAccessType("offline") .build(); LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build(); - return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user"); + Credential credential = new AuthorizationCodeInstalledApp(flow, receiver).authorize("user"); + //returns an authorized Credential object. + return credential; } - private static com.google.api.services.calendar.Calendar getSerivce() { + public static com.google.api.services.calendar.Calendar getSerivce() { com.google.api.services.calendar.Calendar service = null; final NetHttpTransport HTTP_TRANSPORT; try { HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); - service = new com.google.api.services.calendar.Calendar.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT)) + service = new Calendar.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT)) .setApplicationName(APPLICATION_NAME) .build(); - } catch (GeneralSecurityException | IOException e) { e.printStackTrace(); } return service; } - - public static List getAllEventsStartingFromDateTime(int league, DateTime dateTime) { - - com.google.api.services.calendar.Calendar service = getSerivce(); - Events events = null; - - String calendarUrl = CalendarConfigProvider.getCalendarUrl(league); - - // Build a new authorized API client service. - try { - events = service.events().list(calendarUrl) - .setMaxResults(100) - .setTimeMin(dateTime) - .setOrderBy("startTime") - .setSingleEvents(true) - .execute(); - - } catch (IOException e) { - e.printStackTrace(); - } - - // List the next 10 events from the primary calendar. - assert events != null; - List items = events.getItems(); - - return items; - } - - public static void createNewEvent(TLWMatchday matchday) { - Calendar service = getSerivce(); - - String calendarId = CalendarConfigProvider.getCalendarId(matchday.getLeague()); - - String matchdayName = matchday.getMatchdayName() == "" ? matchday.getMatchday().toString() + ". Spieltag" : matchday.getMatchdayName(); - String summary = "Tippabgabeschluss " + TLWLeague.getLeagueNameCalendar(matchday.getLeague()) + " " + matchdayName; - String description = "Tippabgabeschluss " + TLWLeague.getLeagueNameCalendar(matchday.getLeague()) + " " + matchdayName; - - Event event = new Event() - .setSummary(summary) - .setLocation("https://www.tippliga-wuerzburg.de/app.php/football/bet") - .setDescription(description); - - DateTime deliveryDate = new DateTime(matchday.getDeliveryDate().replace(" ", "T")); - EventDateTime date = new EventDateTime() - .setDateTime(deliveryDate) - .setTimeZone("Europe/Berlin"); - event.setStart(date); - event.setEnd(date); - - // Set reminder to 12 hours before - Event.Reminders reminders = new Event.Reminders(); - EventReminder[] reminderOverrides = new EventReminder[] { - new EventReminder().setMethod("popup").setMinutes(12 * 60), - }; - reminders.setOverrides(Arrays.asList(reminderOverrides)); - event.setReminders(reminders); - - try { - service.events().insert(calendarId, event).execute(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - public static void updateMatchdayDate(TLWMatchday matchday) { - - } - - public static Event getEventForMatchday(TLWMatchday matchday) { - return null; - } } \ No newline at end of file diff --git a/src/main/java/de/jeyp91/googlecalendar/SyncTokenSample.java b/src/main/java/de/jeyp91/googlecalendar/SyncTokenSample.java deleted file mode 100644 index 0c8fcd9..0000000 --- a/src/main/java/de/jeyp91/googlecalendar/SyncTokenSample.java +++ /dev/null @@ -1,140 +0,0 @@ -/* - * Copyright (c) 2014 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package de.jeyp91.googlecalendar; - -import com.google.api.client.googleapis.json.GoogleJsonResponseException; -import com.google.api.client.util.DateTime; -import com.google.api.client.util.store.DataStore; -import com.google.api.services.calendar.Calendar; -import com.google.api.services.calendar.CalendarScopes; -import com.google.api.services.calendar.model.Event; -import com.google.api.services.calendar.model.Events; -import com.google.common.collect.Lists; - -import java.io.IOException; -import java.util.Date; -import java.util.List; -import java.util.TimeZone; - -/** - * A sample that demonstrates how to efficiently sync - * Calendar resource - * using sync tokens. - * - * @author ekoleda+devrel@google.com (Eric Koleda) - */ -public class SyncTokenSample { - - /** Global instance of the Calendar client. */ - private static Calendar client; - - /** Global instance of the event datastore. */ - private static DataStore eventDataStore; - - /** Global instance of the sync settings datastore. */ - private static DataStore syncSettingsDataStore; - - /** The key in the sync settings datastore that holds the current sync token. */ - private static final String SYNC_TOKEN_KEY = "syncToken"; - - public static void main(String[] args) { - try { - List scopes = Lists.newArrayList(CalendarScopes.CALENDAR_READONLY); - client = Utils.createCalendarClient(scopes); - eventDataStore = Utils.getDataStoreFactory().getDataStore("EventStore"); - syncSettingsDataStore = Utils.getDataStoreFactory().getDataStore("SyncSettings"); - run(); - } catch (Throwable t) { - t.printStackTrace(); - System.exit(1); - } - } - - /** - * Syncs events from the user's primary calendar to a local datastore. A full sync is performed on - * the first run, with incremental syncs on subsequent runs. - */ - private static void run() throws IOException { - // Construct the {@link Calendar.Events.List} request, but don't execute it yet. - Calendar.Events.List request = client.events().list("primary"); - - // Load the sync token stored from the last execution, if any. - String syncToken = syncSettingsDataStore.get(SYNC_TOKEN_KEY); - if (syncToken == null) { - System.out.println("Performing full sync."); - - // Set the filters you want to use during the full sync. Sync tokens aren't compatible with - // most filters, but you may want to limit your full sync to only a certain date range. - // In this example we are only syncing events up to a year old. - Date oneYearAgo = Utils.getRelativeDate(java.util.Calendar.YEAR, -1); - request.setTimeMin(new DateTime(oneYearAgo, TimeZone.getTimeZone("UTC"))); - } else { - System.out.println("Performing incremental sync."); - request.setSyncToken(syncToken); - } - - // Retrieve the events, one page at a time. - String pageToken = null; - Events events = null; - do { - request.setPageToken(pageToken); - - try { - events = request.execute(); - } catch (GoogleJsonResponseException e) { - if (e.getStatusCode() == 410) { - // A 410 status code, "Gone", indicates that the sync token is invalid. - System.out.println("Invalid sync token, clearing event store and re-syncing."); - syncSettingsDataStore.delete(SYNC_TOKEN_KEY); - eventDataStore.clear(); - run(); - } else { - throw e; - } - } - - List items = events.getItems(); - if (items.size() == 0) { - System.out.println("No new events to sync."); - } else { - for (Event event : items) { - syncEvent(event); - } - } - - pageToken = events.getNextPageToken(); - } while (pageToken != null); - - // Store the sync token from the last request to be used during the next execution. - syncSettingsDataStore.set(SYNC_TOKEN_KEY, events.getNextSyncToken()); - - System.out.println("Sync complete."); - } - - /** - * Sync an individual event. In this example we simply store it's string represenation to a file - * system data store. - */ - private static void syncEvent(Event event) throws IOException { - if ("cancelled".equals(event.getStatus()) && eventDataStore.containsKey(event.getId())) { - eventDataStore.delete(event.getId()); - System.out.println(String.format("Deleting event: ID=%s", event.getId())); - } else { - eventDataStore.set(event.getId(), event.toString()); - System.out.println( - String.format("Syncing event: ID=%s, Name=%s", event.getId(), event.getSummary())); - } - } -} \ No newline at end of file diff --git a/src/main/java/de/jeyp91/googlecalendar/TippligaGoogleEventManager.java b/src/main/java/de/jeyp91/googlecalendar/TippligaGoogleEventManager.java new file mode 100644 index 0000000..bc41a13 --- /dev/null +++ b/src/main/java/de/jeyp91/googlecalendar/TippligaGoogleEventManager.java @@ -0,0 +1,152 @@ +package de.jeyp91.googlecalendar; + +import com.google.api.client.util.DateTime; +import com.google.api.services.calendar.Calendar; +import com.google.api.services.calendar.model.Event; +import com.google.api.services.calendar.model.EventDateTime; +import com.google.api.services.calendar.model.EventReminder; +import com.google.api.services.calendar.model.Events; +import de.jeyp91.tippliga.TLWLeague; +import de.jeyp91.tippliga.TLWMatchday; + +import java.io.IOException; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.util.Arrays; +import java.util.List; + +import static de.jeyp91.googlecalendar.GoogleCalendarConnector.getSerivce; + +public class TippligaGoogleEventManager { + + private static List allEvents = null; + + private static List getAllEvents(Integer season) { + if(allEvents == null) { + allEvents = getAllEventsStartingFromDateTime(new DateTime(season-1 + "-01-01T00:00:00Z")); + } + return allEvents; + } + + public static List getAllEventsStartingFromDateTime(DateTime dateTime) { + + Calendar service = getSerivce(); + Events events = null; + + String calendarUrl = CalendarConfigProvider.getCalendarUrl(); + + // Build a new authorized API client service. + try { + events = service.events().list(calendarUrl) + .setMaxResults(500) + .setTimeMin(dateTime) + .setOrderBy("startTime") + .setSingleEvents(true) + .execute(); + + } catch (IOException e) { + e.printStackTrace(); + } + + assert events != null; + List items = events.getItems(); + + return items; + } + + public static Event findEvent(List allEvents, Integer season, Integer league, Integer matchday, Integer deliveryDateNumber) { + String description = getDescription(season, league, matchday, deliveryDateNumber); + for(int i = 0; i < allEvents.size(); i++) { + if(allEvents.get(i).getDescription().equals(description)) return allEvents.get(i); + } + return null; + } + + public static void createOrUpdateEventsForMatchday(TLWMatchday matchday) { + createOrUpdateEvent(matchday, matchday.getDeliveryDate(), 1); + if(!matchday.getDeliveryDate2().equals("")) createOrUpdateEvent(matchday, matchday.getDeliveryDate2(), 2); + if(!matchday.getDeliveryDate3().equals("")) createOrUpdateEvent(matchday, matchday.getDeliveryDate3(), 3); + } + + public static void createOrUpdateEvent(TLWMatchday matchday, String deliveryDateString, Integer deliverDateNumber) { + List allEvents = getAllEvents(matchday.getSeason()); + Event event = findEvent(allEvents, matchday.getSeason(), matchday.getLeague(), matchday.getMatchday(), deliverDateNumber); + if(event == null) + createNewEvent(matchday, deliveryDateString, deliverDateNumber); + else + updateEvent(event, matchday, deliveryDateString, deliverDateNumber); + } + + private static void createNewEvent(TLWMatchday matchday, String deliveryDateString, Integer deliverDateNumber) { + String calendarUrl = CalendarConfigProvider.getCalendarUrl(); + + Event event = getEvent(matchday, deliveryDateString, deliverDateNumber); + + try { + getSerivce().events().insert(calendarUrl, event).execute(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + private static void updateEvent(Event oldEvent, TLWMatchday matchday, String deliveryDateString, Integer deliverDateNumber) { + String calendarUrl = CalendarConfigProvider.getCalendarUrl(); + + Event event = getEvent(matchday, deliveryDateString, deliverDateNumber); + + try { + getSerivce().events().update(calendarUrl, oldEvent.getId(), event).execute(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public static void deleteEvent(TLWMatchday matchday, Integer deliverDateNumber) { + String calendarUrl = CalendarConfigProvider.getCalendarUrl(); + + Event event = findEvent(getAllEvents(matchday.getSeason()), matchday.getSeason(), matchday.getLeague(), matchday.getMatchday(), deliverDateNumber); + if(event != null) { + try { + getSerivce().events().delete(calendarUrl, event.getId()).execute(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + private static Event getEvent(TLWMatchday matchday, String deliveryDateString, Integer deliverDateNumber) { + String matchdayName = matchday.getMatchdayName().equals("") ? matchday.getMatchday().toString() + ". Spieltag" : matchday.getMatchdayName(); + String summary = TLWLeague.getLeagueNameCalendar(matchday.getLeague()) + " " + matchdayName + " tippen!"; + if(deliverDateNumber > 1) summary += " " + deliverDateNumber + ". Chance \uD83D\uDE43"; + String description = getDescription(matchday.getSeason(), matchday.getLeague(), matchday.getMatchday(), deliverDateNumber); + String location = "https://tippliga-wuerzburg.de/app.php/football/bet"; + + LocalDateTime deliveryLocalDateTime = LocalDateTime.parse(deliveryDateString.replace(" ", "T")); + ZonedDateTime zdtBerlin = ZonedDateTime.of(deliveryLocalDateTime, ZoneId.of("Europe/Berlin")); + DateTime deliveryDateTime = new DateTime(zdtBerlin.toInstant().toEpochMilli()); + EventDateTime date = new EventDateTime() + .setDateTime(deliveryDateTime) + .setTimeZone("Europe/Berlin"); + + // Set reminder to 12 hours before + Event.Reminders reminders = new Event.Reminders(); + reminders.setUseDefault(false); + EventReminder[] reminderOverrides = new EventReminder[] { + new EventReminder().setMethod("popup").setMinutes(12 * 60), + }; + reminders.setOverrides(Arrays.asList(reminderOverrides)); + + return new Event() + .setSummary(summary) + .setLocation(location) + .setDescription(description) + .setStart(date) + .setEnd(date) + .setReminders(reminders); + } + + private static String getDescription(Integer season, Integer league, Integer matchday, Integer deliverDateNumber) { + return "Saison: " + season + "\n" + "Liga: " + league + "\n" + "Spieltag: " + matchday + "\n" + "Abgabeschluss: " + deliverDateNumber; + } +} \ No newline at end of file diff --git a/src/main/java/de/jeyp91/googlecalendar/Utils.java b/src/main/java/de/jeyp91/googlecalendar/Utils.java deleted file mode 100644 index d16abe3..0000000 --- a/src/main/java/de/jeyp91/googlecalendar/Utils.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Copyright (c) 2014 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package de.jeyp91.googlecalendar; - -import com.google.api.client.auth.oauth2.Credential; -import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp; -import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver; -import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow; -import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets; -import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; -import com.google.api.client.http.HttpTransport; -import com.google.api.client.json.JsonFactory; -import com.google.api.client.json.gson.GsonFactory; -import com.google.api.client.util.DateTime; -import com.google.api.client.util.store.DataStoreFactory; -import com.google.api.client.util.store.FileDataStoreFactory; -import com.google.api.services.calendar.Calendar; -import com.google.api.services.calendar.model.Event; -import com.google.api.services.calendar.model.Event.Reminders; -import com.google.api.services.calendar.model.EventDateTime; - -import java.io.IOException; -import java.io.InputStreamReader; -import java.util.Date; -import java.util.List; -import java.util.TimeZone; - -/** - * A collection of utility methods used by these samples. - */ -public class Utils { - /** Application name */ - private static final String APPLICATION_NAME = "Calendar Sync Samples"; - - /** Directory to store user credentials. */ - private static final java.io.File DATA_STORE_DIR = - new java.io.File(System.getProperty("user.home"), ".store/calendar-sync"); - - /** Global instance of the {@link DataStoreFactory}. */ - private static FileDataStoreFactory dataStoreFactory; - - /** Global instance of the JSON factory. */ - private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance(); - - /** Global instance of the HTTP transport. */ - private static HttpTransport httpTransport; - - static { - try { - httpTransport = GoogleNetHttpTransport.newTrustedTransport(); - dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR); - } catch (Throwable t) { - t.printStackTrace(); - System.exit(1); - } - } - - /** Creates a new Calendar client to use when making requests to the API. */ - public static Calendar createCalendarClient(List scopes) throws Exception { - Credential credential = authorize(scopes); - return new Calendar.Builder( - httpTransport, JSON_FACTORY, credential).setApplicationName(APPLICATION_NAME).build(); - } - - /** Authorizes the installed application to access user's protected data. */ - public static Credential authorize(List scopes) throws Exception { - // Load client secrets. - GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, - new InputStreamReader(SyncTokenSample.class.getResourceAsStream("/client_secrets.json"))); - if (clientSecrets.getDetails().getClientId().startsWith("Enter") - || clientSecrets.getDetails().getClientSecret().startsWith("Enter")) { - System.out.println( - "Overwrite the src/main/resources/client_secrets.json file with the client secrets file " - + "you downloaded from your Google Developers Console project."); - System.exit(1); - } - - GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, - JSON_FACTORY, clientSecrets, scopes).setDataStoreFactory(dataStoreFactory).build(); - // Authorize. - LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build(); - return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user"); - } - - /** Gets the datastore factory used in these samples. */ - public static DataStoreFactory getDataStoreFactory() { - return dataStoreFactory; - } - - /** Creates a test event. */ - public static Event createTestEvent(Calendar client, String summary) throws IOException { - Date oneHourFromNow = Utils.getRelativeDate(java.util.Calendar.HOUR, 1); - Date twoHoursFromNow = Utils.getRelativeDate(java.util.Calendar.HOUR, 2); - DateTime start = new DateTime(oneHourFromNow, TimeZone.getTimeZone("UTC")); - DateTime end = new DateTime(twoHoursFromNow, TimeZone.getTimeZone("UTC")); - - Event event = new Event().setSummary(summary) - .setReminders(new Reminders().setUseDefault(false)) - .setStart(new EventDateTime().setDateTime(start)) - .setEnd(new EventDateTime().setDateTime(end)); - return client.events().insert("primary", event).execute(); - } - - /** - * Gets a new {@link java.util.Date} relative to the current date and time. - * - * @param field the field identifier from {@link java.util.Calendar} to increment - * @param amount the amount of the field to increment - * @return the new date - */ - public static Date getRelativeDate(int field, int amount) { - Date now = new Date(); - java.util.Calendar cal = java.util.Calendar.getInstance(); - cal.setTime(now); - cal.add(field, amount); - return cal.getTime(); - } -} diff --git a/src/main/java/de/jeyp91/tippliga/TLWLeague.java b/src/main/java/de/jeyp91/tippliga/TLWLeague.java index f2b5135..18dd09a 100644 --- a/src/main/java/de/jeyp91/tippliga/TLWLeague.java +++ b/src/main/java/de/jeyp91/tippliga/TLWLeague.java @@ -5,10 +5,7 @@ public class TLWLeague { String leagueName = ""; switch (id) { case 1: - leagueName = "1. Tippliga Würzburg"; - break; - case 2: - leagueName = "2. Tippliga Würzburg"; + leagueName = "Tippliga"; break; case 46: leagueName = "Elfmeter"; @@ -58,19 +55,19 @@ public class TLWLeague { switch (id) { case 1: case 2: - leagueName = "TLW"; + leagueName = "Tippliga"; break; case 46: - leagueName = "ELF"; + leagueName = "Elfmeter"; break; case 47: - leagueName = "REL"; + leagueName = "Relegation"; break; case 48: - leagueName = "WTL"; + leagueName = "WTL-Pokal"; break; case 49: - leagueName = "LC"; + leagueName = "Liga Cup"; break; default: break; } diff --git a/src/main/java/de/jeyp91/tippliga/TLWMatchdaysUpdater.java b/src/main/java/de/jeyp91/tippliga/TLWMatchdaysUpdater.java index fb0ffc1..cfe9410 100644 --- a/src/main/java/de/jeyp91/tippliga/TLWMatchdaysUpdater.java +++ b/src/main/java/de/jeyp91/tippliga/TLWMatchdaysUpdater.java @@ -9,6 +9,8 @@ import java.util.ArrayList; import java.util.Comparator; import java.util.Date; +import static de.jeyp91.googlecalendar.TippligaGoogleEventManager.*; + public class TLWMatchdaysUpdater { private final Logger logger = LogManager.getLogger(TLWMatch.class); @@ -72,6 +74,7 @@ public class TLWMatchdaysUpdater { condition; this.beautifulInfo += beautifulInfoStart + "Tippabgabeschluss 1 zu '" + matchdayUpdated.getDeliveryDate() + "'.\n"; + createOrUpdateEvent(matchdayUpdated, matchdayUpdated.getDeliveryDate(), 1); } if (!matchdayOriginal.getDeliveryDate2().equals(matchdayUpdated.getDeliveryDate2())) { @@ -80,6 +83,10 @@ public class TLWMatchdaysUpdater { condition; this.beautifulInfo += beautifulInfoStart + "Tippabgabeschluss 2 zu '" + matchdayUpdated.getDeliveryDate2() + "'.\n"; + if(!matchdayUpdated.getDeliveryDate2().equals("")) + createOrUpdateEvent(matchdayUpdated, matchdayUpdated.getDeliveryDate2(), 2); + else + deleteEvent(matchdayUpdated, 2); } if (!matchdayOriginal.getMatchdayName().equals(matchdayUpdated.getMatchdayName())) { @@ -88,6 +95,9 @@ public class TLWMatchdaysUpdater { condition; this.beautifulInfo += beautifulInfoStart + "Spieltagsname zu '" + matchdayUpdated.getMatchdayName() + "'.\n"; + createOrUpdateEvent(matchdayUpdated, matchdayUpdated.getDeliveryDate(), 1); + if(!matchdayUpdated.getDeliveryDate2().equals("")) + createOrUpdateEvent(matchdayUpdated, matchdayUpdated.getDeliveryDate2(), 2); } } } diff --git a/src/main/resources/Google_Calendar_Config.json b/src/main/resources/Google_Calendar_Config.json index 0cb345c..56202a4 100644 --- a/src/main/resources/Google_Calendar_Config.json +++ b/src/main/resources/Google_Calendar_Config.json @@ -2,21 +2,5 @@ "1": { "id": "825f79shtm9n3uknj99iuu2qho", "url": "825f79shtm9n3uknj99iuu2qho@group.calendar.google.com" - }, - "46": { - "id": "5adq7f0csmpihahran6nqmrhq8", - "url": "5adq7f0csmpihahran6nqmrhq8@group.calendar.google.com" - }, - "47": { - "id": "em2778be5ogeu7qkcqembcfti0", - "url": "em2778be5ogeu7qkcqembcfti0@group.calendar.google.com" - }, - "48": { - "id": "flmbok3dgujh9de0q2eml3tdcg", - "url": "flmbok3dgujh9de0q2eml3tdcg@group.calendar.google.com" - }, - "49": { - "id": "1hled0c9s699ds43hp0ga5gecc", - "url": "1hled0c9s699ds43hp0ga5gecc@group.calendar.google.com" } } \ No newline at end of file diff --git a/src/main/resources/Google_Credentials.json b/src/main/resources/Google_Credentials.json index 70f43c0..716dc42 100644 --- a/src/main/resources/Google_Credentials.json +++ b/src/main/resources/Google_Credentials.json @@ -1,12 +1,12 @@ { - "installed":{ - "client_id":"326748683996-ftm5p1qoscdm6pbvr1jpplsc3r8nd0sp.apps.googleusercontent.com", - "project_id":"quickstart-1564063275094", - "auth_uri":"https://accounts.google.com/o/oauth2/auth", - "token_uri":"https://oauth2.googleapis.com/token", - "auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs", - "client_secret":"rEn1rOHi_9Juw4HV6eOe5MVp", - "redirect_uris":[ + "installed": { + "client_id": "267204101826-2ps9m6httllrc7mrsvml50rsfb661k87.apps.googleusercontent.com", + "project_id": "tippliga", + "auth_uri": "https://accounts.google.com/o/oauth2/auth", + "token_uri": "https://oauth2.googleapis.com/token", + "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", + "client_secret": "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", + "redirect_uris": [ "urn:ietf:wg:oauth:2.0:oob", "http://localhost" ] diff --git a/src/test/java/de/jeyp91/googlecalendar/GoogleCalendarConnectorTest.java b/src/test/java/de/jeyp91/googlecalendar/GoogleCalendarConnectorTest.java deleted file mode 100644 index 6ff2316..0000000 --- a/src/test/java/de/jeyp91/googlecalendar/GoogleCalendarConnectorTest.java +++ /dev/null @@ -1,36 +0,0 @@ -package de.jeyp91.googlecalendar; - -import com.google.api.client.util.DateTime; -import com.google.api.services.calendar.model.Event; -import de.jeyp91.tippliga.TLWMatchday; -import org.junit.Test; - -import java.util.List; -import static org.junit.Assert.assertEquals; - -public class GoogleCalendarConnectorTest { - - @Test - public void getAllEventsStartingFromDateTimeTest() - { - DateTime dateTime = new DateTime("2020-01-01T00:00:00"); - - List events = GoogleCalendarConnector.getAllEventsStartingFromDateTime(1, dateTime); - - assertEquals("Tippliga 20. Spieltag tippen!", events.get(0).getSummary()); - DateTime startExpected = new DateTime("2020-01-17T20:30:00+01:00"); - DateTime startActual = events.get(0).getStart().getDateTime(); - assertEquals(startExpected, startActual); - - assertEquals("Tippliga 21. Spieltag tippen!", events.get(1).getSummary()); - startExpected = new DateTime("2020-01-24T20:30:00+01:00"); - startActual = events.get(1).getStart().getDateTime(); - assertEquals(startExpected, startActual); - } - - @Test - public void createEventTest() { - TLWMatchday matchday = new TLWMatchday(2020, 1, 1, 0, "2020-07-01 20:30:00", "", "", "", 1); - // GoogleCalendarConnector.createNewEvent(matchday); - } -} diff --git a/src/test/java/de/jeyp91/googlecalendar/TippligaGoogleEventManagerTest.java b/src/test/java/de/jeyp91/googlecalendar/TippligaGoogleEventManagerTest.java new file mode 100644 index 0000000..a917d92 --- /dev/null +++ b/src/test/java/de/jeyp91/googlecalendar/TippligaGoogleEventManagerTest.java @@ -0,0 +1,82 @@ +package de.jeyp91.googlecalendar; + +import com.google.api.client.util.DateTime; +import com.google.api.services.calendar.model.Event; +import de.jeyp91.tippliga.TLWMatchday; +import de.jeyp91.tippliga.TLWMatchdaysCreator; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; + +import static de.jeyp91.googlecalendar.TippligaGoogleEventManager.*; +import static org.junit.Assert.assertEquals; + +public class TippligaGoogleEventManagerTest { + + @Test + public void getAllEventsStartingFromDateTimeTest() + { + DateTime dateTime = new DateTime("2020-01-01T00:00:00"); + + List events = getAllEventsStartingFromDateTime(dateTime); + + assertEquals("Tippliga 20. Spieltag tippen!", events.get(0).getSummary()); + DateTime startExpected = new DateTime("2020-01-17T20:30:00+01:00"); + DateTime startActual = events.get(0).getStart().getDateTime(); + assertEquals(startExpected, startActual); + + assertEquals("Tippliga 21. Spieltag tippen!", events.get(1).getSummary()); + startExpected = new DateTime("2020-01-24T20:30:00+01:00"); + startActual = events.get(1).getStart().getDateTime(); + assertEquals(startExpected, startActual); + } + + @Test + public void createOrUpdateEventsForMatchdayTippligaTest() { + TLWMatchdaysCreator creator = new TLWMatchdaysCreator(2022, 1, "Tippliga"); + ArrayList matchdays = creator.getMatchdays(); + + matchdays.forEach(TippligaGoogleEventManager::createOrUpdateEventsForMatchday); + } + + @Test + public void createOrUpdateEventsForMatchdayWTLPokalTest() { + TLWMatchdaysCreator creator = new TLWMatchdaysCreator(2022, 48, "WTL-Pokal"); + ArrayList matchdays = creator.getMatchdays(); + // createOrUpdateEventsForMatchday(matchdays.get(4)); + + matchdays.forEach(TippligaGoogleEventManager::createOrUpdateEventsForMatchday); + } + + @Test + public void updateEventTest() { + TLWMatchdaysCreator creator = new TLWMatchdaysCreator(2022, 1, "Tippliga"); + ArrayList matchdays = creator.getMatchdays(); + createOrUpdateEvent(matchdays.get(28), matchdays.get(28).getDeliveryDate(), 1); + } + + @Test + public void deleteEventTippligaTest() { + TLWMatchdaysCreator creator = new TLWMatchdaysCreator(2022, 1, "Tippliga"); + ArrayList matchdays = creator.getMatchdays(); + + matchdays.forEach(tlwMatchday -> { + TippligaGoogleEventManager.deleteEvent(tlwMatchday, 1); + TippligaGoogleEventManager.deleteEvent(tlwMatchday, 2); + TippligaGoogleEventManager.deleteEvent(tlwMatchday, 3); + }); + } + + @Test + public void deleteEventWTLPokalTest() { + TLWMatchdaysCreator creator = new TLWMatchdaysCreator(2022, 48, "WTL-Pokal"); + ArrayList matchdays = creator.getMatchdays(); + + matchdays.forEach(tlwMatchday -> { + TippligaGoogleEventManager.deleteEvent(tlwMatchday, 1); + TippligaGoogleEventManager.deleteEvent(tlwMatchday, 2); + TippligaGoogleEventManager.deleteEvent(tlwMatchday, 3); + }); + } +} diff --git a/src/test/java/de/jeyp91/tippliga/TLWMatchesUpdaterFootballTest.java b/src/test/java/de/jeyp91/tippliga/TLWMatchesUpdaterFootballTest.java index bdb271e..45af32f 100644 --- a/src/test/java/de/jeyp91/tippliga/TLWMatchesUpdaterFootballTest.java +++ b/src/test/java/de/jeyp91/tippliga/TLWMatchesUpdaterFootballTest.java @@ -6,7 +6,7 @@ public class TLWMatchesUpdaterFootballTest { @Test public void getUpdateSqlTest1() { - TLWMatchesUpdaterFootball updater = new TLWMatchesUpdaterFootball(2021, 1, "Tippliga"); + TLWMatchesUpdaterFootball updater = new TLWMatchesUpdaterFootball(2022, 1, "Tippliga"); String sql = updater.getUpdateSQL(); // System.out.println(sql); diff --git a/tokens/StoredCredential b/tokens/StoredCredential index 7b1c4d4..c17c026 100644 Binary files a/tokens/StoredCredential and b/tokens/StoredCredential differ