use of net.robinfriedli.aiode.entities.Playlist 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.aiode.entities.Playlist in project aiode by robinfriedli.
the class VerifyPlaylistInterceptor method preFlush.
@Override
public void preFlush(Iterator entities) {
@SuppressWarnings("unchecked") Iterable<Object> iterable = () -> entities;
Set<Playlist> playlistsToUpdate = StreamSupport.stream(iterable.spliterator(), false).filter(entity -> entity instanceof PlaylistItem).map(entity -> ((PlaylistItem) entity).getPlaylist()).collect(Collectors.toSet());
if (!playlistsToUpdate.isEmpty()) {
playlistsToUpdate.forEach(this::checkPlaylistSize);
UpdatePlaylistItemIndicesTask task = new UpdatePlaylistItemIndicesTask(playlistsToUpdate, Comparator.comparing(PlaylistItem::getOrdinal));
task.perform();
}
super.preFlush(entities);
}
use of net.robinfriedli.aiode.entities.Playlist in project aiode by robinfriedli.
the class PlaylistViewHandler method handle.
@Override
public void handle(HttpExchange exchange) throws IOException {
Session session = null;
try {
String html = Files.readString(Path.of("html/playlist_view.html"));
Map<String, String> parameterMap = ServerUtil.getParameters(exchange);
String guildId = parameterMap.get("guildId");
String name = parameterMap.get("name");
boolean isPartitioned = Aiode.get().getGuildManager().getMode() == GuildManager.Mode.PARTITIONED;
if (name != null && (guildId != null || !isPartitioned)) {
session = sessionFactory.openSession();
Playlist playlist = SearchEngine.searchLocalList(session, name, isPartitioned, guildId);
if (playlist != null) {
String createdUserId = playlist.getCreatedUserId();
String createdUser;
if (createdUserId.equals("system")) {
createdUser = playlist.getCreatedUser();
} else {
User userById;
try {
userById = shardManager.retrieveUserById(createdUserId).complete();
} catch (ErrorResponseException e) {
if (e.getErrorResponse() == ErrorResponse.UNKNOWN_USER) {
userById = null;
} else {
throw e;
}
}
createdUser = userById != null ? userById.getName() : playlist.getCreatedUser();
}
String htmlString = String.format(html, playlist.getName(), playlist.getName(), Util.normalizeMillis(playlist.getDuration()), createdUser, playlist.getSize(), getList(playlist));
byte[] bytes = htmlString.getBytes();
exchange.sendResponseHeaders(200, bytes.length);
OutputStream os = exchange.getResponseBody();
os.write(bytes);
os.close();
} else {
throw new InvalidRequestException("No playlist found");
}
} else {
throw new InvalidRequestException("Insufficient request parameters");
}
} catch (InvalidRequestException e) {
ServerUtil.handleError(exchange, e);
} catch (Exception e) {
ServerUtil.handleError(exchange, e);
LoggerFactory.getLogger(getClass()).error("Error in HttpHandler", e);
} finally {
if (session != null) {
session.close();
}
}
}
use of net.robinfriedli.aiode.entities.Playlist in project aiode by robinfriedli.
the class SearchCommand method listLocalList.
private void listLocalList() {
if (getCommandInput().isBlank()) {
Session session = getContext().getSession();
List<Playlist> playlists = getQueryBuilderFactory().find(Playlist.class).build(session).getResultList();
EmbedBuilder embedBuilder = new EmbedBuilder();
if (playlists.isEmpty()) {
embedBuilder.setDescription("No playlists");
} else {
EmbedTable table = new EmbedTable(embedBuilder);
table.addColumn("Playlist", playlists, Playlist::getName);
table.addColumn("Duration", playlists, playlist -> Util.normalizeMillis(playlist.getDuration()));
table.addColumn("Items", playlists, playlist -> String.valueOf(playlist.getSize()));
table.build();
}
sendMessage(embedBuilder);
} else {
Playlist playlist = SearchEngine.searchLocalList(getContext().getSession(), getCommandInput());
if (playlist == null) {
throw new NoResultsFoundException(String.format("No local list found for '%s'", getCommandInput()));
}
String createdUserId = playlist.getCreatedUserId();
String createdUser;
if (createdUserId.equals("system")) {
createdUser = playlist.getCreatedUser();
} else {
ShardManager shardManager = Aiode.get().getShardManager();
User userById;
try {
userById = shardManager.retrieveUserById(createdUserId).complete();
} catch (ErrorResponseException e) {
if (e.getErrorResponse() == ErrorResponse.UNKNOWN_USER) {
userById = null;
} else {
throw e;
}
}
createdUser = userById != null ? userById.getName() : playlist.getCreatedUser();
}
SpringPropertiesConfig springPropertiesConfig = Aiode.get().getSpringPropertiesConfig();
String baseUri = springPropertiesConfig.requireApplicationProperty("aiode.server.base_uri");
EmbedBuilder embedBuilder = new EmbedBuilder();
embedBuilder.addField("Name", playlist.getName(), true);
embedBuilder.addField("Duration", Util.normalizeMillis(playlist.getDuration()), true);
embedBuilder.addField("Created by", createdUser, true);
embedBuilder.addField("Tracks", String.valueOf(playlist.getSize()), true);
embedBuilder.addBlankField(false);
String url = baseUri + String.format("/list?name=%s&guildId=%s", URLEncoder.encode(playlist.getName(), StandardCharsets.UTF_8), playlist.getGuildId());
embedBuilder.addField("First tracks:", "[Full list](" + url + ")", false);
List<PlaylistItem> items = playlist.getItemsSorted();
Util.appendEmbedList(embedBuilder, items.size() > 5 ? items.subList(0, 5) : items, item -> item.display() + " - " + Util.normalizeMillis(item.getDuration()), "Track - Duration");
sendWithLogo(embedBuilder);
}
}
use of net.robinfriedli.aiode.entities.Playlist in project aiode by robinfriedli.
the class UploadCommand method doRun.
@Override
public void doRun() throws Exception {
SpotifyApi spotifyApi = getContext().getSpotifyApi();
Playlist playlist = SearchEngine.searchLocalList(getContext().getSession(), getCommandInput());
if (playlist == null) {
throw new InvalidCommandException(String.format("No local list found for '%s'", getCommandInput()));
}
runWithLogin(() -> {
List<SpotifyTrack> tracks = playlist.asTrackList(spotifyApi);
String name = playlist.getName();
if (tracks.isEmpty()) {
throw new InvalidCommandException("Playlist " + name + " has no Spotify tracks.");
}
String userId = spotifyApi.getCurrentUsersProfile().build().execute().getId();
se.michaelthelin.spotify.model_objects.specification.Playlist spotifyPlaylist = spotifyApi.createPlaylist(userId, name).build().execute();
uploadedPlaylistName = spotifyPlaylist.getName();
String playlistId = spotifyPlaylist.getId();
List<String> trackUris = tracks.stream().map(SpotifyTrack::getUri).collect(Collectors.toList());
List<List<String>> sequences = Lists.partition(trackUris, 90);
for (List<String> sequence : sequences) {
spotifyApi.addItemsToPlaylist(playlistId, sequence.toArray(new String[0])).build().execute();
}
return null;
});
}
Aggregations