Search in sources :

Example 11 with GuildSettings

use of com.cloudcraftgaming.discal.api.object.GuildSettings in project DisCal-Discord-Bot by NovaFox161.

the class PermissionChecker method isCorrectChannel.

/**
 * Checks if the user sent the command in a DisCal channel (if set).
 *
 * @param event The event received to check for the correct channel.
 * @return <code>true</code> if in correct channel, otherwise <code>false</code>.
 */
public static boolean isCorrectChannel(MessageReceivedEvent event) {
    try {
        GuildSettings settings = DatabaseManager.getManager().getSettings(event.getGuild().getLongID());
        if (settings.getDiscalChannel().equalsIgnoreCase("all")) {
            return true;
        }
        IChannel channel = null;
        for (IChannel c : event.getMessage().getGuild().getChannels()) {
            if (c.getStringID().equals(settings.getDiscalChannel())) {
                channel = c;
                break;
            }
        }
        if (channel != null) {
            return event.getMessage().getChannel().getStringID().equals(channel.getStringID());
        }
        // If we got here, the channel no longer exists, reset data and return true.
        settings.setDiscalChannel("all");
        DatabaseManager.getManager().updateSettings(settings);
        return true;
    } catch (Exception e) {
        // Catch any errors so that the bot always responds...
        Logger.getLogger().exception(event.getMessage().getAuthor(), "Failed to check for discal channel.", e, PermissionChecker.class, true);
        return true;
    }
}
Also used : GuildSettings(com.cloudcraftgaming.discal.api.object.GuildSettings)

Example 12 with GuildSettings

use of com.cloudcraftgaming.discal.api.object.GuildSettings in project DisCal-Discord-Bot by NovaFox161.

the class PermissionChecker method hasSufficientRole.

public static boolean hasSufficientRole(IGuild guild, IUser user) {
    // TODO: Figure out exactly what is causing a NPE here...
    try {
        GuildSettings settings = DatabaseManager.getManager().getSettings(guild.getLongID());
        if (!settings.getControlRole().equalsIgnoreCase("everyone")) {
            String roleId = settings.getControlRole();
            IRole role = null;
            for (IRole r : guild.getRoles()) {
                if (r.getStringID().equals(roleId)) {
                    role = r;
                    break;
                }
            }
            if (role != null) {
                for (IRole r : user.getRolesForGuild(guild)) {
                    if (r.getStringID().equals(role.getStringID()) || r.getPosition() > role.getPosition()) {
                        return true;
                    }
                }
                return false;
            } else {
                // Role not found... reset Db...
                settings.setControlRole("everyone");
                DatabaseManager.getManager().updateSettings(settings);
                return true;
            }
        }
    } catch (Exception e) {
        // Something broke so we will harmlessly allow access and notify the dev team
        Logger.getLogger().exception(user, "Failed to check for sufficient control role.", e, PermissionChecker.class, true);
        return true;
    }
    return true;
}
Also used : GuildSettings(com.cloudcraftgaming.discal.api.object.GuildSettings)

Example 13 with GuildSettings

use of com.cloudcraftgaming.discal.api.object.GuildSettings in project DisCal-Discord-Bot by NovaFox161.

the class Authorization method pollForAuth.

void pollForAuth(Poll poll) {
    GuildSettings settings = DatabaseManager.getManager().getSettings(poll.getGuild().getLongID());
    try {
        String body = "client_id=" + clientData.getClientId() + "&client_secret=" + clientData.getClientSecret() + "&code=" + poll.getDevice_code() + "&grant_type=http://oauth.net/grant_type/device/1.0";
        // Execute
        com.mashape.unirest.http.HttpResponse<JsonNode> response = Unirest.post("https://www.googleapis.com/oauth2/v4/token").header("Content-Type", "application/x-www-form-urlencoded").body(body).asJson();
        // Handle response.
        if (response.getStatus() == 403) {
            // Handle access denied
            Message.sendDirectMessage(MessageManager.getMessage("AddCalendar.Auth.Poll.Failure.Deny", settings), poll.getUser());
        } else if (response.getStatus() == 400) {
            try {
                // See if auth is pending, if so, just reschedule.
                Type type = new TypeToken<AuthPollResponseError>() {
                }.getType();
                AuthPollResponseError apre = new Gson().fromJson(response.getBody().toString(), type);
                if (apre.error.equalsIgnoreCase("authorization_pending")) {
                    // Response pending
                    PollManager.getManager().scheduleNextPoll(poll);
                } else if (apre.error.equalsIgnoreCase("expired_token")) {
                    Message.sendDirectMessage(MessageManager.getMessage("AddCalendar.Auth.Poll.Failure.Expired", settings), poll.getUser());
                } else {
                    Message.sendDirectMessage(MessageManager.getMessage("Notification.Error.Network", settings), poll.getUser());
                    Logger.getLogger().debug(poll.getUser(), "Poll Failure!", "Status code: " + response.getStatus() + " | " + response.getStatusText() + " | " + response.getBody().toString(), this.getClass(), true);
                }
            } catch (Exception e) {
                // Auth is not pending, error occurred.
                Logger.getLogger().exception(poll.getUser(), "Failed to poll for authorization to google account.", e, this.getClass(), true);
                Logger.getLogger().debug(poll.getUser(), "More info on failure", "Status code: " + response.getStatus() + " | " + response.getStatusText() + " | " + response.getBody().toString(), this.getClass(), true);
                Message.sendDirectMessage(MessageManager.getMessage("Notification.Error.Network", settings), poll.getUser());
            }
        } else if (response.getStatus() == 429) {
            // We got rate limited... oops. Let's just poll half as often.
            poll.setInterval(poll.getInterval() * 2);
            PollManager.getManager().scheduleNextPoll(poll);
        } else if (response.getStatus() == HttpStatusCodes.STATUS_CODE_OK) {
            // Access granted
            Type type = new TypeToken<AuthPollResponseGrant>() {
            }.getType();
            AuthPollResponseGrant aprg = new Gson().fromJson(response.getBody().toString(), type);
            // Save credentials securely.
            GuildSettings gs = DatabaseManager.getManager().getSettings(poll.getGuild().getLongID());
            AESEncryption encryption = new AESEncryption(gs);
            gs.setEncryptedAccessToken(encryption.encrypt(aprg.access_token));
            gs.setEncryptedRefreshToken(encryption.encrypt(aprg.refresh_token));
            DatabaseManager.getManager().updateSettings(gs);
            try {
                Calendar service = CalendarAuth.getCalendarService(gs);
                List<CalendarListEntry> items = service.calendarList().list().setMinAccessRole("writer").execute().getItems();
                Message.sendDirectMessage(MessageManager.getMessage("AddCalendar.Auth.Poll.Success", settings), poll.getUser());
                for (CalendarListEntry i : items) {
                    if (!i.isDeleted()) {
                        EmbedBuilder em = new EmbedBuilder();
                        em.withAuthorIcon(Main.client.getGuildByID(266063520112574464L).getIconURL());
                        em.withAuthorName("DisCal");
                        em.withTitle(MessageManager.getMessage("Embed.AddCalendar.List.Title", settings));
                        em.appendField(MessageManager.getMessage("Embed.AddCalendar.List.Name", settings), i.getSummary(), false);
                        em.appendField(MessageManager.getMessage("Embed.AddCalendar.List.TimeZone", settings), i.getTimeZone(), false);
                        em.appendField(MessageManager.getMessage("Embed.AddCalendar.List.ID", settings), i.getId(), false);
                        em.withUrl(CalendarMessageFormatter.getCalendarLink(i.getId()));
                        em.withColor(56, 138, 237);
                        Message.sendDirectMessage(em.build(), poll.getUser());
                    }
                }
            // Response will be handled in guild, and will check. We already saved the tokens anyway.
            } catch (IOException e1) {
                // Failed to get calendars list and check for calendars.
                Logger.getLogger().exception(poll.getUser(), "Failed to list calendars from external account!", e1, this.getClass(), true);
                Message.sendDirectMessage(MessageManager.getMessage("AddCalendar.Auth.Poll.Failure.ListCalendars", settings), poll.getUser());
            }
        } else {
            // Unknown network error...
            Message.sendDirectMessage(MessageManager.getMessage("Notification.Error.Network", settings), poll.getUser());
            Logger.getLogger().debug(poll.getUser(), "Network error; poll failure", "Status code: " + response.getStatus() + " | " + response.getStatusText() + " | " + response.getBody().toString(), this.getClass(), true);
        }
    } catch (Exception e) {
        // Handle exception.
        Logger.getLogger().exception(poll.getUser(), "Failed to poll for authorization to google account", e, this.getClass(), true);
        Message.sendDirectMessage(MessageManager.getMessage("Notification.Error.Unknown", settings), poll.getUser());
    }
}
Also used : AESEncryption(com.cloudcraftgaming.discal.api.crypto.AESEncryption) Calendar(com.google.api.services.calendar.Calendar) Gson(com.google.gson.Gson) JsonNode(com.mashape.unirest.http.JsonNode) IOException(java.io.IOException) AuthPollResponseGrant(com.cloudcraftgaming.discal.api.object.json.google.AuthPollResponseGrant) IOException(java.io.IOException) Type(java.lang.reflect.Type) CalendarListEntry(com.google.api.services.calendar.model.CalendarListEntry) EmbedBuilder(sx.blah.discord.util.EmbedBuilder) TypeToken(com.google.gson.reflect.TypeToken) List(java.util.List) AuthPollResponseError(com.cloudcraftgaming.discal.api.object.json.google.AuthPollResponseError) GuildSettings(com.cloudcraftgaming.discal.api.object.GuildSettings)

Example 14 with GuildSettings

use of com.cloudcraftgaming.discal.api.object.GuildSettings in project DisCal-Discord-Bot by NovaFox161.

the class DatabaseManager method getSettings.

public GuildSettings getSettings(long guildId) {
    GuildSettings settings = new GuildSettings(guildId);
    try {
        if (databaseInfo.getMySQL().checkConnection()) {
            String dataTableName = String.format("%sguild_settings", databaseInfo.getPrefix());
            String query = "SELECT * FROM " + dataTableName + " WHERE GUILD_ID = '" + String.valueOf(guildId) + "';";
            PreparedStatement statement = databaseInfo.getConnection().prepareStatement(query);
            ResultSet res = statement.executeQuery();
            Boolean hasStuff = res.next();
            if (hasStuff && res.getString("GUILD_ID") != null) {
                settings.setUseExternalCalendar(res.getBoolean("EXTERNAL_CALENDAR"));
                settings.setPrivateKey(res.getString("PRIVATE_KEY"));
                settings.setEncryptedAccessToken(res.getString("ACCESS_TOKEN"));
                settings.setEncryptedRefreshToken(res.getString("REFRESH_TOKEN"));
                settings.setControlRole(res.getString("CONTROL_ROLE"));
                settings.setDiscalChannel(res.getString("DISCAL_CHANNEL"));
                settings.setSimpleAnnouncements(res.getBoolean("SIMPLE_ANNOUNCEMENT"));
                settings.setLang(res.getString("LANG"));
                settings.setPrefix(res.getString("PREFIX"));
                settings.setPatronGuild(res.getBoolean("PATRON_GUILD"));
                settings.setDevGuild(res.getBoolean("DEV_GUILD"));
                settings.setMaxCalendars(res.getInt("MAX_CALENDARS"));
                settings.setDmAnnouncementsFromString(res.getString("DM_ANNOUNCEMENTS"));
                settings.setTwelveHour(res.getBoolean("12_HOUR"));
                settings.setBranded(res.getBoolean("BRANDED"));
                statement.close();
            } else {
                // Data not present.
                statement.close();
                return settings;
            }
        }
    } catch (SQLException e) {
        Logger.getLogger().exception(null, "Failed to get Guild Settings.", e, this.getClass(), true);
    }
    return settings;
}
Also used : GuildSettings(com.cloudcraftgaming.discal.api.object.GuildSettings)

Example 15 with GuildSettings

use of com.cloudcraftgaming.discal.api.object.GuildSettings in project DisCal-Discord-Bot by NovaFox161.

the class DatabaseManager method getAllSettings.

public ArrayList<GuildSettings> getAllSettings() {
    ArrayList<GuildSettings> allSettings = new ArrayList<>();
    try {
        if (databaseInfo.getMySQL().checkConnection()) {
            String dataTableName = String.format("%sguild_settings", databaseInfo.getPrefix());
            PreparedStatement stmt = databaseInfo.getConnection().prepareStatement("SELECT * FROM " + dataTableName);
            ResultSet res = stmt.executeQuery();
            while (res.next()) {
                if (res.getString("GUILD_ID") != null) {
                    GuildSettings settings = new GuildSettings(Long.valueOf(res.getString("GUILD_ID")));
                    settings.setUseExternalCalendar(res.getBoolean("EXTERNAL_CALENDAR"));
                    settings.setPrivateKey(res.getString("PRIVATE_KEY"));
                    settings.setEncryptedAccessToken(res.getString("ACCESS_TOKEN"));
                    settings.setEncryptedRefreshToken(res.getString("REFRESH_TOKEN"));
                    settings.setControlRole(res.getString("CONTROL_ROLE"));
                    settings.setDiscalChannel(res.getString("DISCAL_CHANNEL"));
                    settings.setSimpleAnnouncements(res.getBoolean("SIMPLE_ANNOUNCEMENT"));
                    settings.setLang(res.getString("LANG"));
                    settings.setPrefix(res.getString("PREFIX"));
                    settings.setPatronGuild(res.getBoolean("PATRON_GUILD"));
                    settings.setDevGuild(res.getBoolean("DEV_GUILD"));
                    settings.setMaxCalendars(res.getInt("MAX_CALENDARS"));
                    settings.setDmAnnouncementsFromString(res.getString("DM_ANNOUNCEMENTS"));
                    settings.setBranded(res.getBoolean("BRANDED"));
                    allSettings.add(settings);
                }
            }
            stmt.close();
        }
    } catch (SQLException e) {
        Logger.getLogger().exception(null, "Failed to get all guild settings", e, this.getClass(), true);
    }
    return allSettings;
}
Also used : ArrayList(java.util.ArrayList) GuildSettings(com.cloudcraftgaming.discal.api.object.GuildSettings)

Aggregations

GuildSettings (com.cloudcraftgaming.discal.api.object.GuildSettings)19 JSONObject (org.json.JSONObject)7 CalendarData (com.cloudcraftgaming.discal.api.object.calendar.CalendarData)6 WebGuild (com.cloudcraftgaming.discal.api.object.web.WebGuild)6 Calendar (com.google.api.services.calendar.Calendar)6 Map (java.util.Map)6 Event (com.google.api.services.calendar.model.Event)5 DateTime (com.google.api.client.util.DateTime)4 EventDateTime (com.google.api.services.calendar.model.EventDateTime)4 ArrayList (java.util.ArrayList)4 EventData (com.cloudcraftgaming.discal.api.object.event.EventData)3 Recurrence (com.cloudcraftgaming.discal.api.object.event.Recurrence)3 JSONException (org.json.JSONException)3 Events (com.google.api.services.calendar.model.Events)2 IOException (java.io.IOException)2 AESEncryption (com.cloudcraftgaming.discal.api.crypto.AESEncryption)1 Announcement (com.cloudcraftgaming.discal.api.object.announcement.Announcement)1 AuthPollResponseError (com.cloudcraftgaming.discal.api.object.json.google.AuthPollResponseError)1 AuthPollResponseGrant (com.cloudcraftgaming.discal.api.object.json.google.AuthPollResponseGrant)1 WebCalendar (com.cloudcraftgaming.discal.api.object.web.WebCalendar)1