Discord bot that plays music from every website ever via youtube-dl
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Chords/src/main/java/moe/nekojimi/chords/Playlist.java

122 lines
3.2 KiB

/*
* Copyright (C) 2022 jimj316
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package moe.nekojimi.chords;
import com.amihaiemil.eoyaml.Yaml;
import com.amihaiemil.eoyaml.YamlMapping;
import com.amihaiemil.eoyaml.YamlSequence;
import com.amihaiemil.eoyaml.YamlSequenceBuilder;
import java.net.MalformedURLException;
import java.util.*;
import java.util.function.Consumer;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author jimj316
*/
public class Playlist implements Consumer<Song>
{
private static final int SHUFFLE_DONT_REPEAT_LAST = 3;
private final String name;
private final List<Song> songs = new ArrayList<>();
private final LinkedList<Song> playHistory = new LinkedList<>();
public Playlist(String name)
{
this.name = name;
}
public YamlMapping toYaml()
{
YamlSequenceBuilder songList = Yaml.createYamlSequenceBuilder();
for (Song song : songs)
songList = songList.add(song.toYaml());
return Yaml.createYamlMappingBuilder()
.add("name", name)
.add("songs", songList.build())
.build();
}
public static Playlist fromYaml(YamlMapping yaml)
{
Playlist ret = new Playlist(yaml.string("name"));
YamlSequence songList = yaml.value("songs").asSequence();
for (int i = 0; i < songList.size(); i++)
{
try
{
ret.addSong(Song.fromYaml(songList.yamlMapping(i)));
} catch (MalformedURLException ex)
{
Logger.getLogger(Playlist.class.getName()).log(Level.SEVERE, null, ex);
}
}
return ret;
}
public void addSong(Song song)
{
song.setKept(true);
songs.add(song);
}
public String getName()
{
return name;
}
public List<Song> getSongs()
{
return songs;
}
public Song getNextSong()
{
Song ret;
// copy the song list
List<Song> toShuffle = new LinkedList<>(songs);
// remove play history from candidates, latest first, unless we'd have less than 2 options
for (int i = playHistory.size() - 1; i >= 0; i--)
{
if (toShuffle.size() <= 2)
break;
toShuffle.remove(playHistory.get(i));
}
Collections.shuffle(toShuffle);
ret = toShuffle.get(0);
playHistory.add(ret);
if (playHistory.size() > SHUFFLE_DONT_REPEAT_LAST)
playHistory.remove();
return ret;
}
@Override
public void accept(Song t)
{
addSong(t);
}
}