use of com.google.api.services.calendar.Calendar in project Saber-Bot by notem.
the class SyncCommand method action.
@Override
public void action(String head, String[] args, MessageReceivedEvent event) {
// get user Google credentials (if they exist)
Credential credential = GoogleAuth.getCredential(event.getAuthor().getId());
Calendar service = GoogleAuth.getCalendarService(credential);
int index = 0;
String cId = args[index].replaceAll("[^\\d]", "");
TextChannel channel = event.getGuild().getTextChannelById(cId);
index++;
boolean importFlag = true;
String address;
if (args.length == 1) {
address = Main.getScheduleManager().getAddress(cId);
} else {
if (args[index].equalsIgnoreCase("export")) {
importFlag = false;
index++;
} else if (args[index].equalsIgnoreCase("import")) {
index++;
}
address = args[index];
if (importFlag) {
// enable auto-sync'ing timezone
Main.getDBDriver().getScheduleCollection().updateOne(eq("_id", cId), set("timezone_sync", true));
// set user who has authorized the sync
if (GoogleAuth.authorize(event.getAuthor().getId()) != null)
Main.getDBDriver().getScheduleCollection().updateOne(eq("_id", cId), set("sync_user", event.getAuthor().getId()));
else
Main.getDBDriver().getScheduleCollection().updateOne(eq("_id", cId), set("sync_user", null));
}
}
if (importFlag) {
Main.getCalendarConverter().importCalendar(address, channel, service);
Main.getScheduleManager().setAddress(cId, address);
String content = "I have finished syncing <#" + cId + ">!";
MessageUtilities.sendMsg(content, event.getChannel(), null);
} else {
boolean success = Main.getCalendarConverter().exportCalendar(address, channel, service);
String content;
if (success) {
content = "I have finished exporting <#" + cId + ">!";
} else {
content = "I was unable to export <#" + cId + "> to " + address + "!\n" + "Please make sure I am authorized to edit that calendar!\n" + "You can provide me access through the ``oauth`` command.";
}
MessageUtilities.sendMsg(content, event.getChannel(), null);
}
}
use of com.google.api.services.calendar.Calendar in project Saber-Bot by notem.
the class ScheduleSyncer method run.
public void run() {
Logging.info(this.getClass(), "Running schedule syncer. . .");
Bson query = and(ne("sync_address", "off"), lte("sync_time", new Date()));
Main.getDBDriver().getScheduleCollection().find(query).projection(fields(include("_id", "sync_time", "sync_address", "sync_user", "guildId"))).forEach((Consumer<? super Document>) document -> {
executor.execute(() -> {
try {
String guildId = document.getString("guildId");
JDA jda = Main.getShardManager().getJDA(guildId);
if (jda == null)
return;
if (JDA.Status.valueOf("CONNECTED") != jda.getStatus())
return;
String scheduleId = document.getString("_id");
Date syncTime = Date.from(ZonedDateTime.ofInstant(document.getDate("sync_time").toInstant(), Main.getScheduleManager().getTimeZone(scheduleId)).plusDays(1).toInstant());
Main.getDBDriver().getScheduleCollection().updateOne(eq("_id", scheduleId), set("sync_time", syncTime));
String address = document.getString("sync_address");
Credential credential = document.get("sync_user") == null ? GoogleAuth.authorize() : GoogleAuth.getCredential(document.getString("sync_user"));
Calendar service = GoogleAuth.getCalendarService(credential);
TextChannel channel = jda.getTextChannelById(document.getString("_id"));
if (channel == null)
return;
if (Main.getCalendarConverter().checkValidAddress(address, service)) {
Main.getCalendarConverter().importCalendar(address, channel, service);
Logging.info(this.getClass(), "Synchronized schedule #" + channel.getName() + " [" + document.getString("_id") + "] on '" + channel.getGuild().getName() + "' [" + channel.getGuild().getId() + "]");
} else {
GuildSettingsManager.GuildSettings gs = Main.getGuildSettingsManager().getGuildSettings(guildId);
TextChannel control = Main.getShardManager().getJDA(guildId).getTextChannelById(gs.getCommandChannelId());
String content = "**Warning:** I failed to auto-sync <#" + scheduleId + "> to *" + address + "*!\n" + "Please make sure that the calendar address is still correct and that the calendar privacy settings have not changed!";
MessageUtilities.sendMsg(content, control, null);
Logging.warn(this.getClass(), "Failed to synchronize schedule #" + channel.getName() + " [" + document.getString("_id") + "] on '" + channel.getGuild().getName() + "' [" + channel.getGuild().getId() + "]");
}
} catch (Exception e) {
Logging.exception(this.getClass(), e);
}
});
});
}
use of com.google.api.services.calendar.Calendar in project openhab1-addons by openhab.
the class GCalEventDownloader method downloadEventFeed.
/**
* Connects to Google-Calendar Service and returns the specified Events
*
* @return the corresponding Events or <code>null</code> if an error
* occurs. <i>Note:</i> We do only return events if their startTime lies between
* <code>now</code> and <code>now + 2 * refreshInterval</code> to reduce
* the amount of events to process.
*/
private static Events downloadEventFeed() {
if (StringUtils.isBlank(calendar_name)) {
logger.warn("Login aborted no calendar name defined");
return null;
}
// authorization
CalendarListEntry calendarID = GCalGoogleOAuth.getCalendarId(calendar_name);
if (calendarID == null) {
return null;
}
DateTime start = new DateTime(new Date(), TimeZone.getTimeZone(calendarID.getTimeZone()));
DateTime end = new DateTime(new Date(start.getValue() + (2 * refreshInterval)), TimeZone.getTimeZone(calendarID.getTimeZone()));
logger.debug("Downloading calendar feed for time interval: {} to {} ", start, end);
Events feed = null;
try {
Credential credential = GCalGoogleOAuth.getCredential(false);
// set up global Calendar instance
Calendar client = new Calendar.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName("openHAB").build();
Calendar.Events.List l = client.events().list(calendarID.getId()).setSingleEvents(true).setTimeMin(start).setTimeMax(end);
// add the fulltext filter if it has been configured
if (StringUtils.isNotBlank(filter)) {
l = l.setQ(filter);
}
feed = l.execute();
} catch (IOException e1) {
logger.error("Event fetch failed: {}", e1.getMessage());
}
try {
if (feed != null) {
checkIfFullCalendarFeed(feed.getItems());
}
return feed;
} catch (Exception e) {
logger.error("downloading CalendarEventFeed throws exception: {}", e.getMessage());
}
return null;
}
use of com.google.api.services.calendar.Calendar in project DisCal-Discord-Bot by NovaFox161.
the class AnnouncementMessageFormatter method getCondensedAnnouncementEmbed.
/**
* Gets the EmbedObject for a Condensed Announcement.
* @param a The Announcement to embed.
* @return The EmbedObject for a Condensed Announcement.
*/
public static EmbedObject getCondensedAnnouncementEmbed(Announcement a, GuildSettings settings) {
EmbedBuilder em = new EmbedBuilder();
em.withAuthorIcon(Main.client.getGuildByID(266063520112574464L).getIconURL());
em.withAuthorName("DisCal");
em.withTitle(MessageManager.getMessage("Embed.Announcement.Condensed.Title", settings));
em.appendField(MessageManager.getMessage("Embed.Announcement.Condensed.ID", settings), a.getAnnouncementId().toString(), false);
em.appendField(MessageManager.getMessage("Embed.Announcement.Condensed.Time", settings), condensedTime(a), false);
if (a.getAnnouncementType().equals(AnnouncementType.SPECIFIC)) {
em.appendField(MessageManager.getMessage("Embed.Announcement.Condensed.EventID", settings), a.getEventId(), false);
try {
Calendar service;
if (settings.useExternalCalendar()) {
service = CalendarAuth.getCalendarService(settings);
} else {
service = CalendarAuth.getCalendarService();
}
// TODO: Handle multiple calendars...
CalendarData data = DatabaseManager.getManager().getMainCalendar(a.getGuildId());
Event event = service.events().get(data.getCalendarAddress(), a.getEventId()).execute();
EventData ed = DatabaseManager.getManager().getEventData(settings.getGuildID(), event.getId());
if (ed.getImageLink() != null && ImageUtils.validate(ed.getImageLink())) {
em.withThumbnail(ed.getImageLink());
}
if (event.getSummary() != null) {
String summary = event.getSummary();
if (summary.length() > 250) {
summary = summary.substring(0, 250);
summary = summary + " (continues on Google Calendar View)";
}
em.appendField(MessageManager.getMessage("Embed.Announcement.Condensed.Summary", settings), summary, true);
}
} catch (Exception e) {
// Failed to get from google cal.
Logger.getLogger().exception(null, "Failed to get event for announcement.", e, AnnouncementMessageFormatter.class, true);
}
} else if (a.getAnnouncementType().equals(AnnouncementType.COLOR)) {
em.appendField(MessageManager.getMessage("Embed.Announcement.Condensed.Color", settings), a.getEventColor().name(), true);
} else if (a.getAnnouncementType().equals(AnnouncementType.RECUR)) {
em.appendField(MessageManager.getMessage("Embed.Announcement.Condensed.RecurID", settings), a.getEventId(), true);
}
em.withFooterText(MessageManager.getMessage("Embed.Announcement.Condensed.Type", "%type%", a.getAnnouncementType().name(), settings));
if (a.getAnnouncementType().equals(AnnouncementType.COLOR)) {
EventColor c = a.getEventColor();
em.withColor(c.getR(), c.getG(), c.getB());
} else {
em.withColor(56, 138, 237);
}
em.appendField(MessageManager.getMessage("Embed.Announcement.Info.Enabled", settings), a.isEnabled() + "", true);
return em.build();
}
use of com.google.api.services.calendar.Calendar in project DisCal-Discord-Bot by NovaFox161.
the class AnnouncementMessageFormatter method sendAnnouncementDM.
static void sendAnnouncementDM(Announcement announcement, Event event, IUser user, CalendarData data, GuildSettings settings) {
EmbedBuilder em = new EmbedBuilder();
em.withAuthorIcon(Main.client.getGuildByID(266063520112574464L).getIconURL());
em.withAuthorName("DisCal");
em.withTitle(MessageManager.getMessage("Embed.Announcement.Announce.Title", settings));
EventData ed = DatabaseManager.getManager().getEventData(announcement.getGuildId(), event.getId());
if (ed.getImageLink() != null && ImageUtils.validate(ed.getImageLink())) {
em.withImage(ed.getImageLink());
}
if (event.getSummary() != null) {
String summary = event.getSummary();
if (summary.length() > 250) {
summary = summary.substring(0, 250);
summary = summary + " (continues on Google Calendar View)";
}
em.appendField(MessageManager.getMessage("Embed.Announcement.Announce.Summary", settings), summary, true);
}
if (event.getDescription() != null) {
String description = event.getDescription();
if (description.length() > 250) {
description = description.substring(0, 250);
description = description + " (continues on Google Calendar View)";
}
em.appendField(MessageManager.getMessage("Embed.Announcement.Announce.Description", settings), description, true);
}
if (!settings.usingSimpleAnnouncements()) {
em.appendField(MessageManager.getMessage("Embed.Announcement.Announce.Date", settings), EventMessageFormatter.getHumanReadableDate(event.getStart(), settings, false), true);
em.appendField(MessageManager.getMessage("Embed.Announcement.Announce.Time", settings), EventMessageFormatter.getHumanReadableTime(event.getStart(), settings, false), true);
try {
Calendar service = CalendarAuth.getCalendarService();
String tz = service.calendars().get(data.getCalendarAddress()).execute().getTimeZone();
em.appendField(MessageManager.getMessage("Embed.Announcement.Announce.TimeZone", settings), tz, true);
} catch (Exception e1) {
em.appendField(MessageManager.getMessage("Embed.Announcement.Announce.TimeZone", settings), "Unknown *Error Occurred", true);
}
} else {
String start = EventMessageFormatter.getHumanReadableDate(event.getStart(), settings, false) + " at " + EventMessageFormatter.getHumanReadableTime(event.getStart(), settings, false);
try {
Calendar service = CalendarAuth.getCalendarService();
String tz = service.calendars().get(data.getCalendarAddress()).execute().getTimeZone();
start = start + " " + tz;
} catch (Exception e1) {
start = start + " (TZ UNKNOWN/ERROR)";
}
em.appendField(MessageManager.getMessage("Embed.Announcement.Announce.Start", settings), start, false);
}
if (event.getLocation() != null && !event.getLocation().equalsIgnoreCase("")) {
if (event.getLocation().length() > 300) {
String location = event.getLocation().substring(0, 300).trim() + "... (cont. on Google Cal)";
em.appendField(MessageManager.getMessage("Embed.Event.Confirm.Location", settings), location, true);
} else {
em.appendField(MessageManager.getMessage("Embed.Event.Confirm.Location", settings), event.getLocation(), true);
}
}
if (!settings.usingSimpleAnnouncements()) {
em.appendField(MessageManager.getMessage("Embed.Announcement.Announce.EventID", settings), event.getId(), false);
}
em.appendField(MessageManager.getMessage("Embed.Announcement.Announce.Info", settings), announcement.getInfo(), false);
em.withUrl(event.getHtmlLink());
if (!settings.usingSimpleAnnouncements()) {
em.withFooterText(MessageManager.getMessage("Embed.Announcement.Announce.ID", "%id%", announcement.getAnnouncementId().toString(), settings));
}
try {
EventColor ec = EventColor.fromNameOrHexOrID(event.getColorId());
em.withColor(ec.getR(), ec.getG(), ec.getB());
} catch (Exception e) {
// I dunno, color probably null.
em.withColor(56, 138, 237);
}
IGuild guild = Main.client.getGuildByID(announcement.getGuildId());
String msg = MessageManager.getMessage("Embed.Announcement.Announce.Dm.Message", "%guild%", guild.getName(), settings);
Message.sendDirectMessage(msg, em.build(), user);
}
Aggregations