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;
}
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);
}
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()));
});
}
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);
}
}
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);
}
}
}
Aggregations