Search in sources :

Example 1 with XmlElement

use of net.robinfriedli.jxp.api.XmlElement in project aiode by robinfriedli.

the class HibernatePlaylistMigrator method perform.

@Override
public Map<Playlist, List<PlaylistItem>> perform() throws Exception {
    ShardManager shardManager = Aiode.get().getShardManager();
    SpotifyTrackBulkLoadingService spotifyBulkLoadingService = new SpotifyTrackBulkLoadingService(spotifyApi);
    List<XmlElement> playlists = context.query(tagName("playlist")).collect();
    Map<Playlist, List<PlaylistItem>> playlistMap = new HashMap<>();
    for (XmlElement playlist : playlists) {
        Playlist newPlaylist = new Playlist();
        newPlaylist.setName(playlist.getAttribute("name").getValue());
        newPlaylist.setCreatedUser(playlist.getAttribute("createdUser").getValue());
        newPlaylist.setCreatedUserId(playlist.getAttribute("createdUserId").getValue());
        newPlaylist.setGuild(guild.getName());
        newPlaylist.setGuildId(guild.getId());
        List<XmlElement> items = playlist.getSubElements();
        Map<PlaylistItem, Integer> itemsWithIndex = new HashMap<>();
        for (int i = 0; i < items.size(); i++) {
            XmlElement item = items.get(i);
            switch(item.getTagName()) {
                case "song":
                    loadSpotifyItem(item, i, spotifyBulkLoadingService, shardManager, newPlaylist, itemsWithIndex, TRACK);
                    break;
                case "episode":
                    loadSpotifyItem(item, i, spotifyBulkLoadingService, shardManager, newPlaylist, itemsWithIndex, EPISODE);
                    break;
                case "video":
                    Video video = new Video();
                    video.setId(item.getAttribute("id").getValue());
                    video.setTitle(item.getAttribute("title").getValue());
                    if (item.hasAttribute("redirectedSpotifyId")) {
                        video.setRedirectedSpotifyId(item.getAttribute("redirectedSpotifyId").getValue());
                    }
                    if (item.hasAttribute("spotifyTrackName")) {
                        video.setSpotifyTrackName(item.getAttribute("spotifyTrackName").getValue());
                    }
                    video.setPlaylist(newPlaylist);
                    video.setDuration(item.getAttribute("duration").getLong());
                    video.setAddedUser(item.getAttribute("addedUser").getValue());
                    video.setAddedUserId(item.getAttribute("addedUserId").getValue());
                    newPlaylist.getVideos().add(video);
                    itemsWithIndex.put(video, i);
                    break;
                case "urlTrack":
                    UrlTrack urlTrack = new UrlTrack();
                    urlTrack.setUrl(item.getAttribute("url").getValue());
                    urlTrack.setTitle(item.getAttribute("title").getValue());
                    urlTrack.setDuration(item.getAttribute("duration").getLong());
                    urlTrack.setAddedUser(item.getAttribute("addedUser").getValue());
                    urlTrack.setAddedUserId(item.getAttribute("addedUserId").getValue());
                    urlTrack.setPlaylist(newPlaylist);
                    newPlaylist.getUrlTracks().add(urlTrack);
                    itemsWithIndex.put(urlTrack, i);
                    break;
            }
        }
        SpotifyInvoker.create(spotifyApi).invoke(() -> {
            spotifyBulkLoadingService.perform();
            return null;
        });
        List<PlaylistItem> playlistItems = itemsWithIndex.keySet().stream().sorted(Comparator.comparing(itemsWithIndex::get)).collect(Collectors.toList());
        playlistMap.put(newPlaylist, playlistItems);
    }
    return playlistMap;
}
Also used : HashMap(java.util.HashMap) ShardManager(net.dv8tion.jda.api.sharding.ShardManager) Playlist(net.robinfriedli.aiode.entities.Playlist) SpotifyTrackBulkLoadingService(net.robinfriedli.aiode.audio.spotify.SpotifyTrackBulkLoadingService) Video(net.robinfriedli.aiode.entities.Video) UrlTrack(net.robinfriedli.aiode.entities.UrlTrack) XmlElement(net.robinfriedli.jxp.api.XmlElement) List(java.util.List) PlaylistItem(net.robinfriedli.aiode.entities.PlaylistItem)

Example 2 with XmlElement

use of net.robinfriedli.jxp.api.XmlElement in project aiode by robinfriedli.

the class GroovyWhitelistManager method createFromConfiguration.

public static GroovyWhitelistManager createFromConfiguration(Context configuration) {
    Map<Class<?>, WhitelistedClassContribution> whitelistContributions = configuration.query(tagName("whitelistClass")).getResultStream().map(elem -> {
        try {
            return new WhitelistedClassContribution(true, elem.getAttribute("onlyGenerated").getBool() ? ClassAccessMode.GENERATED : ClassAccessMode.FULL, Class.forName(elem.getAttribute("class").getValue()), elem.getAttribute("maxMethodInvocations").getInt());
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("Invalid whitelist configuration, invalid class encountered", e);
        }
    }).collect(Collectors.toMap(WhitelistedClassContribution::getType, contribution -> contribution));
    for (XmlElement methodWhitelist : configuration.query(tagName("whitelistMethods")).collect()) {
        Class<?> allowedClass;
        try {
            allowedClass = Class.forName(methodWhitelist.getAttribute("class").getValue());
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("Invalid whitelist configuration, invalid  class encountered", e);
        }
        WhitelistedClassContribution allowedClassContribution = new WhitelistedClassContribution(methodWhitelist.getAttribute("allowConstructorCall").getBool(), ClassAccessMode.METHODS, allowedClass, methodWhitelist.getAttribute("maxMethodInvocations").getInt());
        methodWhitelist.query(tagName("method")).getResultStream().forEach(elem -> new WhitelistedMethodContribution(elem.getAttribute("name").getValue(), !elem.hasAttribute("inheritable") || elem.getAttribute("inheritable").getBool(), elem.getAttribute("onlyGenerated").getBool(), elem.getAttribute("maxInvocationCount").getInt(), allowedClassContribution));
        methodWhitelist.query(tagName("writeProperty")).getResultStream().forEach(elem -> new WhitelistedPropertyWriteAccessContribution(elem.getAttribute("name").getValue(), !elem.hasAttribute("inheritable") || elem.getAttribute("inheritable").getBool(), allowedClassContribution));
        whitelistContributions.put(allowedClassContribution.getType(), allowedClassContribution);
    }
    // set the parent contribution of all contributions to the contribution describing the closest superclass
    Collection<WhitelistedClassContribution> allWhitelistContributions = whitelistContributions.values();
    for (WhitelistedClassContribution whitelistContribution : allWhitelistContributions) {
        Class<?> currentType = whitelistContribution.getType();
        for (WhitelistedClassContribution otherContribution : allWhitelistContributions) {
            if (whitelistContribution == otherContribution) {
                continue;
            }
            Class<?> otherType = otherContribution.getType();
            if (otherType.isAssignableFrom(currentType)) {
                Collection<WhitelistedClassContribution> parentContributions = whitelistContribution.getParentContributions();
                if (parentContributions == null || parentContributions.isEmpty()) {
                    whitelistContribution.setParentContributions(Collections.singleton(otherContribution));
                } else {
                    Set<WhitelistedClassContribution> contendingContributions = Sets.newHashSet();
                    contendingContributions.addAll(parentContributions);
                    contendingContributions.add(otherContribution);
                    whitelistContribution.setParentContributions(selectClosestNodes(contendingContributions, currentType));
                }
            }
        }
    }
    return new GroovyWhitelistManager(whitelistContributions);
}
Also used : Context(net.robinfriedli.jxp.persist.Context) ClassDescriptorNode(net.robinfriedli.aiode.util.ClassDescriptorNode) Collection(java.util.Collection) Map(java.util.Map) Set(java.util.Set) XmlElement(net.robinfriedli.jxp.api.XmlElement) HashMap(java.util.HashMap) Conditions(net.robinfriedli.jxp.queries.Conditions) Collections(java.util.Collections) Collectors(java.util.stream.Collectors) Sets(com.google.api.client.util.Sets) XmlElement(net.robinfriedli.jxp.api.XmlElement)

Example 3 with XmlElement

use of net.robinfriedli.jxp.api.XmlElement in project aiode by robinfriedli.

the class HelpCommand method showCommandHelp.

private void showCommandHelp() {
    getManager().getCommand(getContext(), getCommandInput()).ifPresentOrElse(command -> {
        String prefix;
        GuildSpecification specification = getContext().getGuildContext().getSpecification();
        String setPrefix = specification.getPrefix();
        String botName = specification.getBotName();
        if (!Strings.isNullOrEmpty(setPrefix)) {
            prefix = setPrefix;
        } else if (!Strings.isNullOrEmpty(botName)) {
            prefix = botName + " ";
        } else {
            prefix = PrefixProperty.DEFAULT_FALLBACK + " ";
        }
        char argumentPrefix = ArgumentPrefixProperty.getForCurrentContext().getArgumentPrefix();
        EmbedBuilder embedBuilder = new EmbedBuilder();
        embedBuilder.setTitle("Command " + command.getIdentifier() + ":");
        String descriptionFormat = command.getDescription();
        String descriptionText = String.format(descriptionFormat, prefix, argumentPrefix);
        embedBuilder.setDescription(descriptionText);
        Guild guild = getContext().getGuild();
        Optional<AccessConfiguration> accessConfiguration = Aiode.get().getSecurityManager().getAccessConfiguration(command.getPermissionTarget(), guild);
        if (accessConfiguration.isPresent()) {
            String title = "Available to roles: ";
            String text;
            List<Role> roles = accessConfiguration.get().getRoles(guild);
            if (!roles.isEmpty()) {
                text = StringList.create(roles, Role::getName).toSeparatedString(", ");
            } else {
                text = "Guild owner and administrator roles only";
            }
            embedBuilder.addField(title, text, false);
        }
        ArgumentController argumentController = command.getArgumentController();
        if (argumentController.hasArguments()) {
            embedBuilder.addField("__Arguments__", "Keywords that alter the command behavior or define a search scope.", false);
            argumentController.getArguments().values().stream().sorted(Comparator.comparing(CommandArgument::getIdentifier)).forEach(argument -> embedBuilder.addField(argumentPrefix + argument.getIdentifier(), String.format(argument.getDescription(), prefix, argumentPrefix), false));
        }
        List<XmlElement> examples = command.getCommandContribution().query(tagName("example")).collect();
        if (!examples.isEmpty()) {
            embedBuilder.addField("__Examples__", "Practical usage examples for this command.", false);
            for (XmlElement example : examples) {
                String exampleText = String.format(example.getTextContent(), prefix, argumentPrefix);
                String titleText = String.format(example.getAttribute("title").getValue(), prefix, argumentPrefix);
                embedBuilder.addField(titleText, exampleText, false);
            }
        }
        sendMessage(embedBuilder);
    }, () -> {
        throw new InvalidCommandException(String.format("No command found for '%s'", getCommandInput()));
    });
}
Also used : CommandArgument(net.robinfriedli.aiode.command.argument.CommandArgument) Guild(net.dv8tion.jda.api.entities.Guild) Role(net.dv8tion.jda.api.entities.Role) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) ArgumentController(net.robinfriedli.aiode.command.argument.ArgumentController) InvalidCommandException(net.robinfriedli.aiode.exceptions.InvalidCommandException) GuildSpecification(net.robinfriedli.aiode.entities.GuildSpecification) XmlElement(net.robinfriedli.jxp.api.XmlElement) AccessConfiguration(net.robinfriedli.aiode.entities.AccessConfiguration)

Example 4 with XmlElement

use of net.robinfriedli.jxp.api.XmlElement in project aiode by robinfriedli.

the class VersionUpdateAlertTask method sendUpdateAlert.

private void sendUpdateAlert(Context context, Version versionElem, JDA shard) {
    List<XmlElement> lowerLaunchedVersions = context.query(and(tagName("version"), attribute("launched").is(true), lowerVersionThan(versionElem.getVersion()))).collect();
    if (!lowerLaunchedVersions.isEmpty()) {
        String message = "Aiode has been updated to " + versionElem.getVersion() + ". [Check the releases here](" + "https://github.com/robinfriedli/botify/releases)";
        EmbedBuilder embedBuilder = new EmbedBuilder();
        embedBuilder.setTitle("Update");
        embedBuilder.setDescription(message);
        List<XmlElement> features = versionElem.query(tagName("feature")).collect();
        if (!features.isEmpty()) {
            embedBuilder.addField("**Features**", "Changes in this update", false);
            for (XmlElement feature : features) {
                embedBuilder.addField(feature.getAttribute("title").getValue(), feature.getTextContent(), false);
            }
        }
        List<Guild> guilds = shard.getGuilds();
        long delaySecs = OFFSET++ * (guilds.size() / MESSAGES_PER_SECOND);
        if (delaySecs > 0) {
            delaySecs += 10;
        }
        MESSAGE_DISPATCH.schedule(() -> {
            // with the other shards
            synchronized (DISPATCH_LOCK) {
                // setup current thread session and handle all guilds within one session instead of opening a new session for each
                StaticSessionProvider.consumeSession((CheckedConsumer<Session>) session -> {
                    int counter = 0;
                    long currentTimeMillis = System.currentTimeMillis();
                    for (Guild guild : guilds) {
                        messageService.sendWithLogo(embedBuilder, guild);
                        if (++counter % MESSAGES_PER_SECOND == 0) {
                            long delta = System.currentTimeMillis() - currentTimeMillis;
                            if (delta < 1000) {
                                Thread.sleep(1000 - delta);
                            }
                            currentTimeMillis = System.currentTimeMillis();
                        }
                    }
                });
            }
        }, delaySecs, TimeUnit.SECONDS);
    }
}
Also used : CheckedConsumer(net.robinfriedli.aiode.function.CheckedConsumer) Context(net.robinfriedli.jxp.persist.Context) StartupTask(net.robinfriedli.aiode.boot.StartupTask) Logger(org.slf4j.Logger) JDA(net.dv8tion.jda.api.JDA) MessageService(net.robinfriedli.aiode.discord.MessageService) LoggerFactory(org.slf4j.LoggerFactory) VersionManager(net.robinfriedli.aiode.boot.VersionManager) Session(org.hibernate.Session) LoggingThreadFactory(net.robinfriedli.aiode.concurrent.LoggingThreadFactory) StartupTaskContribution(net.robinfriedli.aiode.entities.xml.StartupTaskContribution) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Version(net.robinfriedli.aiode.entities.xml.Version) Conditions(net.robinfriedli.jxp.queries.Conditions) Executors(java.util.concurrent.Executors) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) Guild(net.dv8tion.jda.api.entities.Guild) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) StaticSessionProvider(net.robinfriedli.aiode.persist.StaticSessionProvider) XmlElement(net.robinfriedli.jxp.api.XmlElement) Conditions(net.robinfriedli.aiode.boot.VersionManager.Conditions) Nullable(javax.annotation.Nullable) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) XmlElement(net.robinfriedli.jxp.api.XmlElement) Guild(net.dv8tion.jda.api.entities.Guild) Session(org.hibernate.Session)

Example 5 with XmlElement

use of net.robinfriedli.jxp.api.XmlElement in project aiode by robinfriedli.

the class InitialiseCommandContributionsTask method perform.

@Override
public void perform(@Nullable JDA shard) throws Exception {
    Context commandContributionContext = commandManager.getCommandContributionContext();
    @SuppressWarnings("rawtypes") List<CommandHierarchyNode> commandHierarchyNodes = commandContributionContext.getInstancesOf(CommandHierarchyNode.class);
    for (@SuppressWarnings("unchecked") CommandHierarchyNode<ArgumentContributionDelegate> commandHierarchyNode : commandHierarchyNodes) {
        Map<String, ArgumentContributionDelegate> argumentContributions = commandHierarchyNode.getArguments();
        for (ArgumentContributionDelegate argumentContributionDelegate : argumentContributions.values()) {
            ArgumentContribution argumentContribution = argumentContributionDelegate.unwrapArgumentContribution();
            List<XmlElement> excludedArguments = argumentContribution.getExcludedArguments();
            List<XmlElement> requiredArguments = argumentContribution.getRequiredArguments();
            validateReferencedArguments(commandHierarchyNode, argumentContribution, excludedArguments);
            validateReferencedArguments(commandHierarchyNode, argumentContribution, requiredArguments);
        }
    }
}
Also used : Context(net.robinfriedli.jxp.persist.Context) CommandHierarchyNode(net.robinfriedli.aiode.entities.xml.CommandHierarchyNode) XmlElement(net.robinfriedli.jxp.api.XmlElement) ArgumentContributionDelegate(net.robinfriedli.aiode.command.argument.ArgumentContributionDelegate) ArgumentContribution(net.robinfriedli.aiode.entities.xml.ArgumentContribution)

Aggregations

XmlElement (net.robinfriedli.jxp.api.XmlElement)10 Context (net.robinfriedli.jxp.persist.Context)4 HashMap (java.util.HashMap)3 List (java.util.List)3 EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)3 Guild (net.dv8tion.jda.api.entities.Guild)3 Role (net.dv8tion.jda.api.entities.Role)2 AccessConfiguration (net.robinfriedli.aiode.entities.AccessConfiguration)2 GuildSpecification (net.robinfriedli.aiode.entities.GuildSpecification)2 ArgumentContribution (net.robinfriedli.aiode.entities.xml.ArgumentContribution)2 Conditions (net.robinfriedli.jxp.queries.Conditions)2 Sets (com.google.api.client.util.Sets)1 File (java.io.File)1 Collection (java.util.Collection)1 Collections (java.util.Collections)1 Map (java.util.Map)1 Set (java.util.Set)1 Executors (java.util.concurrent.Executors)1 ScheduledExecutorService (java.util.concurrent.ScheduledExecutorService)1 TimeUnit (java.util.concurrent.TimeUnit)1