]> git.basschouten.com Git - openhab-addons.git/blob
a9ac8648d1c62309ff7257d106e832237bd9482f
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
7  * This program and the accompanying materials are made available under the
8  * terms of the Eclipse Public License 2.0 which is available at
9  * http://www.eclipse.org/legal/epl-2.0
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.magentatv.internal.network;
14
15 import static org.openhab.binding.magentatv.internal.MagentaTVBindingConstants.*;
16 import static org.openhab.binding.magentatv.internal.MagentaTVUtil.substringBetween;
17
18 import java.io.IOException;
19 import java.nio.charset.StandardCharsets;
20 import java.util.Map;
21 import java.util.Scanner;
22
23 import javax.servlet.ServletException;
24 import javax.servlet.http.HttpServlet;
25 import javax.servlet.http.HttpServletRequest;
26 import javax.servlet.http.HttpServletResponse;
27
28 import org.eclipse.jdt.annotation.NonNullByDefault;
29 import org.eclipse.jdt.annotation.Nullable;
30 import org.openhab.binding.magentatv.internal.MagentaTVHandlerFactory;
31 import org.osgi.service.component.annotations.Activate;
32 import org.osgi.service.component.annotations.Component;
33 import org.osgi.service.component.annotations.ConfigurationPolicy;
34 import org.osgi.service.component.annotations.Reference;
35 import org.osgi.service.http.HttpService;
36 import org.osgi.service.http.NamespaceException;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39
40 /**
41  * Main OSGi service and HTTP servlet for MagentaTV NOTIFY.
42  *
43  * @author Markus Michels - Initial contribution
44  */
45 @NonNullByDefault
46 @Component(service = HttpServlet.class, configurationPolicy = ConfigurationPolicy.OPTIONAL)
47 public class MagentaTVNotifyServlet extends HttpServlet {
48     private static final long serialVersionUID = 2119809008606371618L;
49     private final Logger logger = LoggerFactory.getLogger(MagentaTVNotifyServlet.class);
50
51     private final MagentaTVHandlerFactory handlerFactory;
52
53     @Activate
54     public MagentaTVNotifyServlet(@Reference MagentaTVHandlerFactory handlerFactory, @Reference HttpService httpService,
55             Map<String, Object> config) {
56         this.handlerFactory = handlerFactory;
57         try {
58             httpService.registerServlet(PAIRING_NOTIFY_URI, this, null, httpService.createDefaultHttpContext());
59             logger.debug("Servlet started at {}", PAIRING_NOTIFY_URI);
60             if (!handlerFactory.getNotifyServletStatus()) {
61                 handlerFactory.setNotifyServletStatus(true);
62             }
63         } catch (ServletException | NamespaceException e) {
64             logger.warn("Could not start MagentaTVNotifyServlet: {}", e.getMessage());
65         }
66     }
67
68     /**
69      * Notify servlet handler (will be called by jetty
70      *
71      * Format of SOAP message:
72      * <e:propertyset xmlns:e="urn:schemas-upnp-org:event-1-0"> <e:property>
73      * <uniqueDeviceID>1C18548DAF7DE9BC231249DB28D2A650</uniqueDeviceID>
74      * </e:property> <e:property> <messageBody>X-pairingCheck:5218C0AA</messageBody>
75      * </e:property> </e:propertyset>
76      *
77      * Format of event message: <?xml version="1.0"?>
78      * <e:propertyset xmlns:e="urn:schemas-upnp-org:event-1-0"> <e:property>
79      * <STB_Mac>AC6FBB61B1E5</STB_Mac> </e:property> <e:property>
80      * <STB_playContent>{&quot;new_play_mode&quot;:0,&quot;playBackState&quot;:1,&
81      * quot;mediaType&quot;:1,&quot;mediaCode&quot;:&quot;3682&quot;}</
82      * STB_playContent> </e:property> </e:propertyset>
83      *
84      * @param request
85      * @param resp
86      *
87      * @throws ServletException, IOException
88      */
89     @Override
90     protected void service(@Nullable HttpServletRequest request, @Nullable HttpServletResponse response)
91             throws ServletException, IOException {
92
93         String data = inputStreamToString(request);
94         try {
95             if ((request == null) || (response == null)) {
96                 return;
97             }
98             String ipAddress = request.getHeader("HTTP_X_FORWARDED_FOR");
99             if (ipAddress == null) {
100                 ipAddress = request.getRemoteAddr();
101             }
102             String path = request.getRequestURI();
103             logger.trace("Reqeust from {}:{}{} ({}, {})", ipAddress, request.getRemotePort(), path,
104                     request.getRemoteHost(), request.getProtocol());
105             if (!path.equalsIgnoreCase(PAIRING_NOTIFY_URI)) {
106                 logger.debug("Invalid request received - path = {}", path);
107                 return;
108             }
109
110             if (data.contains(NOTIFY_PAIRING_CODE)) {
111                 String deviceId = data.substring(data.indexOf("<uniqueDeviceID>") + "<uniqueDeviceID>".length(),
112                         data.indexOf("</uniqueDeviceID>"));
113                 String pairingCode = data.substring(data.indexOf(NOTIFY_PAIRING_CODE) + NOTIFY_PAIRING_CODE.length(),
114                         data.indexOf("</messageBody>"));
115                 logger.debug("Pairing code {} received for deviceID {}", pairingCode, deviceId);
116                 if (!handlerFactory.notifyPairingResult(deviceId, ipAddress, pairingCode)) {
117                     logger.trace("Pairing data={}", data);
118                 }
119             } else {
120                 if (data.contains("STB_")) {
121                     data = data.replaceAll("&quot;", "\"");
122                     String stbMac = substringBetween(data, "<STB_Mac>", "</STB_Mac>");
123                     String stbEvent = "";
124                     if (data.contains("<STB_playContent>")) {
125                         stbEvent = substringBetween(data, "<STB_playContent>", "</STB_playContent>");
126                     } else if (data.contains("<STB_EitChanged>")) {
127                         stbEvent = substringBetween(data, "<STB_EitChanged>", "</STB_EitChanged>");
128                     } else {
129                         logger.debug("Unknown STB event: {}", data);
130                     }
131                     if (!stbEvent.isEmpty()) {
132                         if (!handlerFactory.notifyMREvent(stbMac, stbEvent)) {
133                             logger.debug("Event not processed, data={}", data);
134                         }
135                     }
136                 }
137             }
138         } catch (RuntimeException e) {
139             logger.debug("Unable to process http request, data={}", data != null ? data : "<empty>");
140         } finally {
141             // send response
142             if (response != null) {
143                 response.setCharacterEncoding(StandardCharsets.UTF_8.name());
144                 response.getWriter().write("");
145             }
146         }
147     }
148
149     @SuppressWarnings("resource")
150     private String inputStreamToString(@Nullable HttpServletRequest request) throws IOException {
151         if (request == null) {
152             return "";
153         }
154         Scanner scanner = new Scanner(request.getInputStream()).useDelimiter("\\A");
155         return scanner.hasNext() ? scanner.next() : "";
156     }
157 }