Persoenliche Mediazentrale
ulrich
2021-04-21 5c621434b008d1671accfc4b9c9c9016a256fd9f
commit | author | age
b379f5 1 /*
5f70da 2   Mediazentrale - Personal Media Center
U 3   Copyright (C) 2021  Ulrich Hilger
4
5   This program is free software: you can redistribute it and/or modify
6   it under the terms of the GNU Affero General Public License as
7   published by the Free Software Foundation, either version 3 of the
8   License, or (at your option) any later version.
9
10   This program is distributed in the hope that it will be useful,
11   but WITHOUT ANY WARRANTY; without even the implied warranty of
12   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13   GNU Affero General Public License for more details.
14
15   You should have received a copy of the GNU Affero General Public License
16   along with this program.  If not, see <https://www.gnu.org/licenses/>.
b379f5 17  */
U 18 package de.uhilger.mediaz.api;
19
20 import com.google.gson.Gson;
21 import com.sun.net.httpserver.HttpExchange;
22 import de.uhilger.mediaz.App;
f45e20 23 import static de.uhilger.mediaz.App.RB_EP_LISTE;
a29f5c 24 import static de.uhilger.mediaz.App.RB_EP_LISTE_ALLES;
b379f5 25 import de.uhilger.mediaz.Server;
081606 26 import de.uhilger.mediaz.store.FileStorage;
b1bf96 27 import de.uhilger.mediaz.entity.Entity;
d769f3 28 import de.uhilger.mediaz.entity.Geraet;
d027b5 29 import static de.uhilger.mediaz.store.FileStorage.ST_ABLAGEORT;
d769f3 30 import static de.uhilger.mediaz.store.FileStorage.ST_GERAET;
757ace 31 import de.uhilger.mediaz.store.Storage;
b379f5 32 import java.io.IOException;
d769f3 33 import java.net.URI;
U 34 import java.util.Iterator;
2b5c60 35 import java.util.List;
081606 36 import java.util.logging.Level;
b379f5 37 import java.util.logging.Logger;
d769f3 38
U 39 import java.net.http.HttpClient;
40 import java.net.http.HttpClient.Version;
41 import java.net.http.HttpClient.Redirect;
42 import java.net.http.HttpRequest;
43 import java.net.http.HttpResponse;
44 import java.net.http.HttpResponse.BodyHandlers;
45 import java.time.Duration;
46 import java.util.ArrayList;
47
b379f5 48
U 49 /**
2597cd 50  * HttpHandler fuer die Verwaltung von Entitaeten der Mediazentrale
a29f5c 51  * 
U 52  * /mz/api/store/[name]/liste
53  * /mz/api/store/[name]/listealles  (nur Typ Geraet)
5f70da 54  * 
U 55  * @author Ulrich Hilger
56  * @version 1, 5.4.2021
b379f5 57  */
8d7d35 58 public class StorageHandler extends AbstractHandler {
b379f5 59   
081606 60   private static final Logger logger = Logger.getLogger(StorageHandler.class.getName());
b379f5 61
8d7d35 62   @Override
U 63   protected String put(HttpExchange e) throws IOException {
dfb7d3 64     String path = e.getRequestURI().toString();
0e9cd3 65     String[] elems = path.split(Server.SLASH);
dfb7d3 66     String type = elems[elems.length - 2];
U 67     String elemName = elems[elems.length - 1]; // alter Name, wenn Aenderung
68     if(!elemName.equalsIgnoreCase(App.getRs(RB_EP_LISTE))) {
69       FileStorage fs = new FileStorage(App.getInitParameter(App.getRs(App.RB_AP_CONF)));
70       Gson gson = new Gson();
71       logger.log(Level.FINE, "type: {0}, token: {1}", new Object[]{type, fs.typeFromName(type).getType().getTypeName()});
72       Object o = gson.fromJson(bodyLesen(e), fs.typeFromName(type).getType());
73       if(o instanceof Entity) {
74         Entity entity = (Entity) o;
75         if(fs.exists(type, elemName)) {
76           fs.delete(type, elemName);
77           fs.write(entity, true);
78         } else {
79           fs.write(entity, false);
80         }
0e9cd3 81         return type + Server.SLASH + entity.getName();
dfb7d3 82       } else {
U 83         return "Ungueltiges Objekt im Body.";
84       }
85     } else {
86       return "Ungueltiger Elementname: " + App.getRs(RB_EP_LISTE);
87     }
88   }
8d7d35 89   
2b5c60 90   private boolean loeschen(HttpExchange e) {
5f70da 91     String path = e.getRequestURI().toString();
0e9cd3 92     String[] elems = path.split(Server.SLASH);
5f70da 93     String type = elems[elems.length - 2];
U 94     String elemName = elems[elems.length - 1];
95     FileStorage fs = new FileStorage(App.getInitParameter(App.getRs(App.RB_AP_CONF)));
2b5c60 96     return fs.delete(type, elemName);
U 97   }
98   
d769f3 99   private String lesen(HttpExchange e) throws IOException, InterruptedException {
2b5c60 100     String path = e.getRequestURI().toString();
0e9cd3 101     String[] elems = path.split(Server.SLASH);
2b5c60 102     FileStorage fs = new FileStorage(App.getInitParameter(App.getRs(App.RB_AP_CONF)));
0e9cd3 103     if(path.endsWith(Server.SLASH)) {
f45e20 104       List list = null;
a29f5c 105       if(elems[elems.length - 1].equalsIgnoreCase(App.getRs(RB_EP_LISTE_ALLES))) {
f45e20 106         String type = elems[elems.length - 2];
U 107         logger.fine(type);
d769f3 108         if(type.equalsIgnoreCase(ST_GERAET)) {
757ace 109           list = collectDeviceStatus(fs, type);
29be41 110           Gson gson = new Gson();
U 111           Object o = gson.fromJson(bodyLesen(e), fs.typeFromName(type).getType());
757ace 112           return gson.toJson(list);
d769f3 113         }
a29f5c 114       } else if(elems[elems.length - 1].equalsIgnoreCase(App.getRs(RB_EP_LISTE))) {
U 115         String type = elems[elems.length - 2];
116         logger.fine(type);
117         list = fs.list(type);
d027b5 118         if(type.equalsIgnoreCase(ST_ABLAGEORT)) {
U 119           list.add("Livestreams");
120         }
f45e20 121       } else {
U 122         String type = elems[elems.length - 1];
123         logger.fine(type);
124         list = fs.listObjects(type);
125       }
a43e1a 126       return jsonWithEnclosingType(list);
2b5c60 127     } else {
U 128       String type = elems[elems.length - 2];
129       String elemName = elems[elems.length - 1];
130       return fs.readJson(type, elemName);
131     }
a43e1a 132   }
b379f5 133   
8d7d35 134   @Override
U 135   public String get(HttpExchange e) {
d769f3 136     try {
U 137       return lesen(e);
138     } catch (IOException | InterruptedException ex) {
139       Logger.getLogger(StorageHandler.class.getName()).log(Level.SEVERE, null, ex);
140       return ex.getLocalizedMessage();
141     }
8d7d35 142   }
U 143
144   @Override
145   public String post(HttpExchange e) {
146     return "nicht unterstuetzt";
147   }
148
149   @Override
150   public boolean delete(HttpExchange e) {
151     return loeschen(e);
b379f5 152   }
757ace 153   
U 154   private List collectDeviceStatus(Storage fs, String type) throws IOException, InterruptedException {
155     List list = fs.listObjects(type);
156     List<Geraet> newList = new ArrayList();
157     Iterator<Entity> i = list.iterator();
158     while (i.hasNext()) {
159       Entity entity = i.next();
160       if (entity instanceof Geraet) {
161         Geraet g = (Geraet) entity;
162         String statusurl = g.getStatusUrl();
163         logger.info(statusurl);
164
165         HttpRequest request = HttpRequest.newBuilder()
166                 .uri(URI.create(statusurl))
167                 .build();
168         HttpClient client = HttpClient.newBuilder()
169                 .version(Version.HTTP_1_1)
170                 .followRedirects(Redirect.NORMAL)
171                 .connectTimeout(Duration.ofSeconds(20))
172                 //.proxy(ProxySelector.of(new InetSocketAddress("proxy.example.com", 80)))
173                 //.authenticator(Authenticator.getDefault())
174                 .build();
175         HttpResponse<String> response = client.send(request, BodyHandlers.ofString());
176         logger.finer(Integer.toString(response.statusCode()));
177         logger.finer(response.body());
178         // {"ison":false,"has_timer":false,"overpower":false}
179         String[] parts = response.body().split(",")[0].split(":");
180         logger.finer("ison: " + parts[1]);
5c6214 181         g.setStatus(Boolean.parseBoolean(parts[1]));
757ace 182         newList.add(g);
U 183       }
184     }
185     return newList;
186   }
b379f5 187 }