|
| 1 | +/* |
| 2 | + * Copyright 2021 devgianlu |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package xyz.gianlu.librespot.api.handlers; |
| 18 | + |
| 19 | +import com.google.gson.JsonArray; |
| 20 | +import com.google.gson.JsonObject; |
| 21 | +import io.undertow.server.HttpHandler; |
| 22 | +import io.undertow.server.HttpServerExchange; |
| 23 | +import io.undertow.util.Headers; |
| 24 | +import xyz.gianlu.librespot.ZeroconfServer; |
| 25 | +import xyz.gianlu.librespot.api.Utils; |
| 26 | +import xyz.gianlu.zeroconf.DiscoveredService; |
| 27 | +import xyz.gianlu.zeroconf.Zeroconf; |
| 28 | + |
| 29 | +import java.util.Deque; |
| 30 | +import java.util.Map; |
| 31 | + |
| 32 | +/** |
| 33 | + * @author devgianlu |
| 34 | + */ |
| 35 | +public final class DiscoveryHandler implements HttpHandler { |
| 36 | + private final Zeroconf zeroconf; |
| 37 | + |
| 38 | + public DiscoveryHandler() { |
| 39 | + zeroconf = new Zeroconf(); |
| 40 | + } |
| 41 | + |
| 42 | + @Override |
| 43 | + public void handleRequest(HttpServerExchange exchange) throws Exception { |
| 44 | + exchange.startBlocking(); |
| 45 | + if (exchange.isInIoThread()) { |
| 46 | + exchange.dispatch(this); |
| 47 | + return; |
| 48 | + } |
| 49 | + |
| 50 | + Map<String, Deque<String>> params = Utils.readParameters(exchange); |
| 51 | + String action = Utils.getFirstString(params, "action"); |
| 52 | + if (action == null) { |
| 53 | + Utils.invalidParameter(exchange, "action"); |
| 54 | + return; |
| 55 | + } |
| 56 | + |
| 57 | + switch (action) { |
| 58 | + case "list": |
| 59 | + JsonArray array = new JsonArray(); |
| 60 | + for (DiscoveredService service : zeroconf.discover(ZeroconfServer.SERVICE, "tcp", ".local")) { |
| 61 | + JsonObject obj = new JsonObject(); |
| 62 | + obj.addProperty("name", service.name); |
| 63 | + obj.addProperty("target", service.target); |
| 64 | + obj.addProperty("port", service.port); |
| 65 | + array.add(obj); |
| 66 | + } |
| 67 | + |
| 68 | + exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/json"); |
| 69 | + exchange.getResponseSender().send(array.toString()); |
| 70 | + break; |
| 71 | + default: |
| 72 | + Utils.invalidParameter(exchange, "action"); |
| 73 | + break; |
| 74 | + } |
| 75 | + } |
| 76 | +} |
0 commit comments