Search in sources :

Example 1 with Playlist

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;
}
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 Playlist

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);
}
Also used : PlaylistItem(net.robinfriedli.aiode.entities.PlaylistItem) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) UpdatePlaylistItemIndicesTask(net.robinfriedli.aiode.persist.tasks.UpdatePlaylistItemIndicesTask) InvalidCommandException(net.robinfriedli.aiode.exceptions.InvalidCommandException) Song(net.robinfriedli.aiode.entities.Song) Set(java.util.Set) Interceptor(org.hibernate.Interceptor) Collectors(java.util.stream.Collectors) Serializable(java.io.Serializable) Transaction(org.hibernate.Transaction) Playlist(net.robinfriedli.aiode.entities.Playlist) SpringPropertiesConfig(net.robinfriedli.aiode.boot.SpringPropertiesConfig) StreamSupport(java.util.stream.StreamSupport) Video(net.robinfriedli.aiode.entities.Video) Comparator(java.util.Comparator) UrlTrack(net.robinfriedli.aiode.entities.UrlTrack) Type(org.hibernate.type.Type) Playlist(net.robinfriedli.aiode.entities.Playlist) UpdatePlaylistItemIndicesTask(net.robinfriedli.aiode.persist.tasks.UpdatePlaylistItemIndicesTask) PlaylistItem(net.robinfriedli.aiode.entities.PlaylistItem)

Example 3 with Playlist

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();
        }
    }
}
Also used : Playlist(net.robinfriedli.aiode.entities.Playlist) User(net.dv8tion.jda.api.entities.User) OutputStream(java.io.OutputStream) ErrorResponseException(net.dv8tion.jda.api.exceptions.ErrorResponseException) InvalidRequestException(net.robinfriedli.aiode.exceptions.InvalidRequestException) InvalidRequestException(net.robinfriedli.aiode.exceptions.InvalidRequestException) ErrorResponseException(net.dv8tion.jda.api.exceptions.ErrorResponseException) IOException(java.io.IOException) Session(org.hibernate.Session)

Example 4 with Playlist

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);
    }
}
Also used : User(net.dv8tion.jda.api.entities.User) ShardManager(net.dv8tion.jda.api.sharding.ShardManager) YouTubePlaylist(net.robinfriedli.aiode.audio.youtube.YouTubePlaylist) Playlist(net.robinfriedli.aiode.entities.Playlist) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) NoResultsFoundException(net.robinfriedli.aiode.exceptions.NoResultsFoundException) ErrorResponseException(net.dv8tion.jda.api.exceptions.ErrorResponseException) SpringPropertiesConfig(net.robinfriedli.aiode.boot.SpringPropertiesConfig) EmbedTable(net.robinfriedli.aiode.util.EmbedTable) PlaylistItem(net.robinfriedli.aiode.entities.PlaylistItem) Session(org.hibernate.Session)

Example 5 with Playlist

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;
    });
}
Also used : Playlist(net.robinfriedli.aiode.entities.Playlist) InvalidCommandException(net.robinfriedli.aiode.exceptions.InvalidCommandException) SpotifyTrack(net.robinfriedli.aiode.audio.spotify.SpotifyTrack) SpotifyApi(se.michaelthelin.spotify.SpotifyApi) List(java.util.List)

Aggregations

Playlist (net.robinfriedli.aiode.entities.Playlist)24 Session (org.hibernate.Session)15 PlaylistItem (net.robinfriedli.aiode.entities.PlaylistItem)12 InvalidCommandException (net.robinfriedli.aiode.exceptions.InvalidCommandException)10 NoResultsFoundException (net.robinfriedli.aiode.exceptions.NoResultsFoundException)10 List (java.util.List)8 Playable (net.robinfriedli.aiode.audio.Playable)5 User (net.dv8tion.jda.api.entities.User)4 Aiode (net.robinfriedli.aiode.Aiode)4 UrlTrack (net.robinfriedli.aiode.entities.UrlTrack)4 IOException (java.io.IOException)3 Collectors (java.util.stream.Collectors)3 EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)3 AudioQueue (net.robinfriedli.aiode.audio.AudioQueue)3 PlayableFactory (net.robinfriedli.aiode.audio.PlayableFactory)3 CommandContext (net.robinfriedli.aiode.command.CommandContext)3 CommandManager (net.robinfriedli.aiode.command.CommandManager)3 Song (net.robinfriedli.aiode.entities.Song)3 CommandContribution (net.robinfriedli.aiode.entities.xml.CommandContribution)3 SearchEngine (net.robinfriedli.aiode.util.SearchEngine)3