lavalink.client.io.LavalinkSocket Java Examples

The following examples show how to use lavalink.client.io.LavalinkSocket. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LavalinkPlayer.java    From Lavalink-Client with MIT License 6 votes vote down vote up
@Override
public void setPaused(boolean pause) {
    if (pause == paused) return;
    LavalinkSocket node = link.getNode(false);
    if (node != null) {
        JSONObject json = new JSONObject();
        json.put("op", "pause");
        json.put("guildId", link.getGuildId());
        json.put("pause", pause);
        node.send(json.toString());
    }
    paused = pause;

    if (pause) {
        emitEvent(new PlayerPauseEvent(this));
    } else {
        emitEvent(new PlayerResumeEvent(this));
    }
}
 
Example #2
Source File: LavalinkPlayer.java    From Lavalink-Client with MIT License 5 votes vote down vote up
@Override
public void stopTrack() {
    track = null;

    LavalinkSocket node = link.getNode(false);
    if (node == null) return;
    JSONObject json = new JSONObject();
    json.put("op", "stop");
    json.put("guildId", link.getGuildId());
    node.send(json.toString());
}
 
Example #3
Source File: LavalinkPlayer.java    From Lavalink-Client with MIT License 5 votes vote down vote up
@Override
public void setVolume(int volume) {
    volume = Math.min(1000, Math.max(0, volume)); // Lavaplayer bounds
    this.volume = volume;

    LavalinkSocket node = link.getNode(false);
    if (node == null) return;

    JSONObject json = new JSONObject();
    json.put("op", "volume");
    json.put("guildId", link.getGuildId());
    json.put("volume", volume);
    node.send(json.toString());
}
 
Example #4
Source File: LavalinkTrackLoader.java    From MantaroBot with GNU General Public License v3.0 5 votes vote down vote up
public static void load(AudioPlayerManager manager, Lavalink<?> lavalink, String query,
                        AudioLoadResultHandler handler) {
    Iterator<LavalinkSocket> sockets = lavalink.getNodes().iterator();
    if (!sockets.hasNext()) {
        manager.loadItem(query, handler);
        return;
    }

    CompletionStage<Runnable> last = tryLoad(manager, sockets.next().getRemoteUri(), query, handler);
    while (sockets.hasNext()) {
        URI uri = sockets.next().getRemoteUri();
        //TODO: java 12 replace this with the line commented below
        var cf = new CompletableFuture<Runnable>();
        last.thenApply(CompletableFuture::completedStage)
                .exceptionally(e -> tryLoad(manager, uri, query, handler))
                .thenCompose(Function.identity())
                .thenAccept(cf::complete)
                .exceptionally(e -> {
                    cf.completeExceptionally(e);
                    return null;
                });
        last = cf;
        //last = last.exceptionallyCompose(e -> tryLoad(manager, uri, query, handler));
    }
    last.whenComplete((ok, oof) -> {
        if (oof != null) {
            handler.loadFailed(new FriendlyException("Failed to load", FriendlyException.Severity.SUSPICIOUS, oof));
        } else {
            ok.run();
        }
    });
}
 
Example #5
Source File: LavalinkCollector.java    From Lavalink-Client with MIT License 4 votes vote down vote up
@Override
public List<MetricFamilySamples> collect() {

    List<MetricFamilySamples> mfs = new ArrayList<>();
    List<String> labelNames = Collections.singletonList("node");


    GaugeMetricFamily players = new GaugeMetricFamily("lavalink_players_current",
            "Amount of players", labelNames);
    mfs.add(players);
    GaugeMetricFamily playingPlayers = new GaugeMetricFamily("lavalink_playing_players_current",
            "Amount of playing players", labelNames);
    mfs.add(playingPlayers);
    GaugeMetricFamily uptimeSeconds = new GaugeMetricFamily("lavalink_uptime_seconds",
            "Uptime of the node", labelNames);
    mfs.add(uptimeSeconds);


    GaugeMetricFamily memFree = new GaugeMetricFamily("lavalink_mem_free_bytes",
            "Amount of free memory", labelNames);
    mfs.add(memFree);
    GaugeMetricFamily memUsed = new GaugeMetricFamily("lavalink_mem_used_bytes",
            "Amount of used memory", labelNames);
    mfs.add(memUsed);
    GaugeMetricFamily memAllocated = new GaugeMetricFamily("lavalink_mem_allocated_bytes",
            "Amount of allocated memory", labelNames);
    mfs.add(memAllocated);
    GaugeMetricFamily memReservable = new GaugeMetricFamily("lavalink_mem_reservable_bytes",
            "Amount of reservable memory", labelNames);
    mfs.add(memReservable);

    GaugeMetricFamily cpuCores = new GaugeMetricFamily("lavalink_cpu_cores",
            "Amount of cpu cores", labelNames);
    mfs.add(cpuCores);
    GaugeMetricFamily systemLoad = new GaugeMetricFamily("lavalink_load_system",
            "Total load of the system", labelNames);
    mfs.add(systemLoad);
    GaugeMetricFamily lavalinkLoad = new GaugeMetricFamily("lavalink_load_lavalink",
            "Load caused by Lavalink", labelNames);
    mfs.add(lavalinkLoad);


    GaugeMetricFamily averageFramesSentPerMinute = new GaugeMetricFamily("lavalink_average_frames_sent_per_minute",
            "Average frames sent per minute", labelNames);
    mfs.add(averageFramesSentPerMinute);
    GaugeMetricFamily averageFramesNulledPerMinute = new GaugeMetricFamily("lavalink_average_frames_nulled_per_minute",
            "Average frames nulled per minute", labelNames);
    mfs.add(averageFramesNulledPerMinute);
    GaugeMetricFamily averageFramesDeficitPerMinute = new GaugeMetricFamily("lavalink_average_frames_deficit_per_minute",
            "Average frames deficit per minute", labelNames);
    mfs.add(averageFramesDeficitPerMinute);


    //noinspection unchecked
    List<LavalinkSocket> nodes = lavalink.getNodes();
    for (LavalinkSocket node : nodes) {
        List<String> labels = Collections.singletonList(node.getName());
        RemoteStats stats = node.getStats();
        if (stats == null) {
            continue;
        }

        players.addMetric(labels, stats.getPlayers());
        playingPlayers.addMetric(labels, stats.getPlayingPlayers());
        uptimeSeconds.addMetric(labels, stats.getUptime() / 1000);

        memFree.addMetric(labels, stats.getMemFree());
        memUsed.addMetric(labels, stats.getMemUsed());
        memAllocated.addMetric(labels, stats.getMemAllocated());
        memReservable.addMetric(labels, stats.getMemReservable());

        cpuCores.addMetric(labels, stats.getCpuCores());
        systemLoad.addMetric(labels, stats.getSystemLoad());
        lavalinkLoad.addMetric(labels, stats.getLavalinkLoad());

        averageFramesSentPerMinute.addMetric(labels, stats.getAvgFramesSentPerMinute());
        averageFramesNulledPerMinute.addMetric(labels, stats.getAvgFramesNulledPerMinute());
        averageFramesDeficitPerMinute.addMetric(labels, stats.getAvgFramesDeficitPerMinute());
    }

    return mfs;
}
 
Example #6
Source File: AudioMessageManager.java    From JuniperBot with GNU General Public License v3.0 4 votes vote down vote up
private EmbedBuilder getPlayMessage(TrackRequest request) {
    EmbedBuilder builder = getBasicMessage(request);
    builder.setDescription(null);

    AudioTrackInfo info = request.getTrack().getInfo();
    PlaybackInstance instance = TrackData.get(request.getTrack()).getInstance();
    boolean refreshable = isRefreshable(instance.getGuildId());

    String durationText;
    if (request.getEndReason() != null) {
        StringBuilder reasonBuilder = new StringBuilder();

        boolean hasDuration = !info.isStream && info.length > 0;
        if (hasDuration) {
            reasonBuilder.append(CommonUtils.formatDuration(request.getTrack().getDuration())).append(" (");
        }
        reasonBuilder.append(messageService.getEnumTitle(request.getEndReason()));

        String endMember = getMemberName(request, true);
        if (StringUtils.isNotBlank(endMember)) {
            reasonBuilder
                    .append(" - **")
                    .append(endMember)
                    .append("**");
        }
        if (hasDuration) {
            reasonBuilder.append(")");
        }
        reasonBuilder.append(CommonUtils.EMPTY_SYMBOL);
        durationText = reasonBuilder.toString();
    } else {
        durationText = getTextProgress(instance, request.getTrack(), refreshable);
    }

    if (instance.getPlaylistUuid() != null) {
        builder.setDescription(messageService.getMessage("discord.command.audio.panel.playlist",
                commonProperties.getBranding().getWebsiteUrl(), instance.getPlaylistUuid()));
    }

    int size = instance.getQueue().size();
    if (request.getEndReason() == null && size > 1) {
        MusicConfig config = musicConfigService.getByGuildId(instance.getGuildId());
        if (config != null && config.isShowQueue()) {
            List<TrackRequest> next = instance.getQueue().subList(1, Math.min(size, MAX_SHORT_QUEUE + 1));
            addQueue(builder, instance, next, 2 + instance.getCursor(), true);
        }
    }

    if (request.getTrack().getInfo().isStream || !refreshable) {
        builder.addField(messageService.getMessage("discord.command.audio.panel.duration"),
                durationText, true);
        builder.addField(messageService.getMessage("discord.command.audio.panel.requestedBy"),
                getMemberName(request, false), true);
    } else {
        String requestedBy = String.format("%s: %s",
                messageService.getMessage("discord.command.audio.panel.requestedBy"),
                getMemberName(request, false));
        builder.addField(requestedBy, durationText, true);
    }

    if (request.getEndReason() == null) {
        IPlayer player = instance.getPlayer();
        if (player.getVolume() != 100) {
            int volume = player.getVolume();
            builder.addField(messageService.getMessage("discord.command.audio.panel.volume"),
                    String.format("%d%% %s", volume, CommonUtils.getVolumeIcon(volume)), true);
        }
        if (!RepeatMode.NONE.equals(instance.getMode())) {
            builder.addField(messageService.getMessage("discord.command.audio.panel.repeatMode"),
                    instance.getMode().getEmoji(), true);
        }
        if (player.isPaused()) {
            builder.addField(messageService.getMessage("discord.command.audio.panel.paused"),
                    "\u23F8", true);
        }

        if (player instanceof LavalinkPlayer) {
            LavalinkPlayer lavalinkPlayer = (LavalinkPlayer) player;
            Link link = lavalinkPlayer.getLink();
            if (link != null) {
                LavalinkSocket socket = link.getNode(false);
                if (socket != null) {
                    StringBuilder statsBuilder = new StringBuilder(messageService
                            .getMessage("discord.command.audio.panel.poweredBy", socket.getName()));
                    if (refreshable && socket.getStats() != null) {
                        long load = Math.round(socket.getStats().getSystemLoad() * 100);
                        if (load < 0) load = 0;
                        if (load > 100) load = 100;
                        statsBuilder
                                .append(" ")
                                .append(messageService.getMessage("discord.command.audio.panel.load", load));
                    }
                    builder.setFooter(statsBuilder.toString(), null);
                }
            }
        }
    }
    return builder;
}
 
Example #7
Source File: StatusQueueListener.java    From JuniperBot with GNU General Public License v3.0 4 votes vote down vote up
@RabbitListener(queues = RabbitConfiguration.QUEUE_STATUS_REQUEST)
public StatusDto getStatus(String dummy) {
    Map<String, Metric> metricMap = metricRegistry.getMetrics();

    StatusDto result = new StatusDto();
    result.setGuildCount(getMetricGauge(metricMap, DiscordMetricsRegistry.GAUGE_GUILDS));
    result.setUserCount(getMetricGauge(metricMap, DiscordMetricsRegistry.GAUGE_USERS));
    result.setTextChannelCount(getMetricGauge(metricMap, DiscordMetricsRegistry.GAUGE_TEXT_CHANNELS));
    result.setVoiceChannelCount(getMetricGauge(metricMap, DiscordMetricsRegistry.GAUGE_VOICE_CHANNELS));
    result.setActiveConnections(getMetricGauge(metricMap, PlayerService.ACTIVE_CONNECTIONS));
    result.setExecutedCommands(getMetricGauge(metricMap, "commands.executions.persist"));
    result.setUptimeDuration(getMetricGauge(metricMap, "jvm.uptime"));

    result.setShards(discordService.getShardManager().getShards().stream()
            .sorted(Comparator.comparing(e -> e.getShardInfo().getShardId()))
            .map(e -> {
                ShardDto dto = new ShardDto();
                dto.setId(e.getShardInfo().getShardId());
                dto.setGuilds(e.getGuildCache().size());
                dto.setUsers(e.getUserCache().size());
                dto.setChannels(e.getTextChannelCache().size() + e.getVoiceChannelCache().size());
                dto.setPing(e.getGatewayPing());
                dto.setConnected(JDA.Status.CONNECTED.equals(e.getStatus()));
                return dto;
            })
            .collect(Collectors.toList()));

    if (workerProperties.getAudio().getLavalink().isEnabled()) {
        result.setLinkNodes(lavaAudioService.getLavaLink().getNodes().stream()
                .sorted(Comparator.comparing(LavalinkSocket::getName))
                .map(e -> {
                    LavaLinkNodeDto nodeDto = new LavaLinkNodeDto();
                    nodeDto.setName(e.getName());
                    nodeDto.setAvailable(e.isAvailable());
                    RemoteStats stats = e.getStats();
                    if (stats != null) {
                        nodeDto.setPlayers(stats.getPlayers());
                        nodeDto.setPlayingPlayers(stats.getPlayingPlayers());
                        nodeDto.setLavalinkLoad(stats.getLavalinkLoad());
                        nodeDto.setSystemLoad(stats.getSystemLoad());
                    }
                    return nodeDto;
                }).collect(Collectors.toList()));
    }
    return result;
}