]> git.basschouten.com Git - openhab-addons.git/blob
2d8877b6b5d25e758e08edc3aa16f5a948a7d81b
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2020 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.io.hueemulation.internal.rest;
14
15 import java.util.*;
16 import java.util.stream.Collectors;
17
18 import javax.ws.rs.Consumes;
19 import javax.ws.rs.DELETE;
20 import javax.ws.rs.GET;
21 import javax.ws.rs.POST;
22 import javax.ws.rs.PUT;
23 import javax.ws.rs.Path;
24 import javax.ws.rs.PathParam;
25 import javax.ws.rs.Produces;
26 import javax.ws.rs.core.Context;
27 import javax.ws.rs.core.MediaType;
28 import javax.ws.rs.core.Response;
29 import javax.ws.rs.core.UriInfo;
30
31 import org.eclipse.jdt.annotation.NonNullByDefault;
32 import org.openhab.core.automation.Action;
33 import org.openhab.core.automation.Rule;
34 import org.openhab.core.automation.RuleManager;
35 import org.openhab.core.automation.RuleRegistry;
36 import org.openhab.core.automation.Trigger;
37 import org.openhab.core.automation.Visibility;
38 import org.openhab.core.automation.util.ModuleBuilder;
39 import org.openhab.core.automation.util.RuleBuilder;
40 import org.openhab.core.common.registry.RegistryChangeListener;
41 import org.openhab.core.config.core.Configuration;
42 import org.openhab.io.hueemulation.internal.ConfigStore;
43 import org.openhab.io.hueemulation.internal.HueEmulationService;
44 import org.openhab.io.hueemulation.internal.NetworkUtils;
45 import org.openhab.io.hueemulation.internal.RuleUtils;
46 import org.openhab.io.hueemulation.internal.dto.HueDataStore;
47 import org.openhab.io.hueemulation.internal.dto.HueScheduleEntry;
48 import org.openhab.io.hueemulation.internal.dto.changerequest.HueChangeScheduleEntry;
49 import org.openhab.io.hueemulation.internal.dto.changerequest.HueCommand;
50 import org.openhab.io.hueemulation.internal.dto.response.HueResponse;
51 import org.openhab.io.hueemulation.internal.dto.response.HueSuccessGeneric;
52 import org.osgi.service.component.annotations.Activate;
53 import org.osgi.service.component.annotations.Component;
54 import org.osgi.service.component.annotations.Deactivate;
55 import org.osgi.service.component.annotations.Reference;
56 import org.osgi.service.jaxrs.whiteboard.JaxrsWhiteboardConstants;
57 import org.osgi.service.jaxrs.whiteboard.propertytypes.JaxrsApplicationSelect;
58 import org.osgi.service.jaxrs.whiteboard.propertytypes.JaxrsResource;
59 import org.slf4j.Logger;
60 import org.slf4j.LoggerFactory;
61
62 import io.swagger.v3.oas.annotations.Operation;
63 import io.swagger.v3.oas.annotations.Parameter;
64 import io.swagger.v3.oas.annotations.responses.ApiResponse;
65
66 /**
67  * Enables the schedule part of the Hue REST API. Uses automation rules with GenericCronTrigger, TimerTrigger and
68  * AbsoluteDateTimeTrigger depending on the schedule time pattern.
69  * <p>
70  * If the scheduled task should remove itself after completion, a RemoveRuleAction is used in the rule.
71  * <p>
72  * The actual command execution uses HttpAction.
73  *
74  * @author David Graeff - Initial contribution
75  */
76 @Component(immediate = false, service = Schedules.class)
77 @JaxrsResource
78 @JaxrsApplicationSelect("(" + JaxrsWhiteboardConstants.JAX_RS_NAME + "=" + HueEmulationService.REST_APP_NAME + ")")
79 @NonNullByDefault
80 @Path("")
81 @Produces(MediaType.APPLICATION_JSON)
82 @Consumes(MediaType.APPLICATION_JSON)
83 public class Schedules implements RegistryChangeListener<Rule> {
84     public static final String SCHEDULE_TAG = "hueemulation_schedule";
85     private final Logger logger = LoggerFactory.getLogger(Schedules.class);
86
87     @Reference
88     protected @NonNullByDefault({}) ConfigStore cs;
89     @Reference
90     protected @NonNullByDefault({}) UserManagement userManagement;
91
92     @Reference
93     protected @NonNullByDefault({}) RuleManager ruleManager;
94     @Reference
95     protected @NonNullByDefault({}) RuleRegistry ruleRegistry;
96
97     /**
98      * Registers to the {@link RuleRegistry} and enumerates currently existing rules.
99      */
100     @Activate
101     public void activate() {
102         ruleRegistry.removeRegistryChangeListener(this);
103         ruleRegistry.addRegistryChangeListener(this);
104
105         for (Rule item : ruleRegistry.getAll()) {
106             added(item);
107         }
108     }
109
110     @Deactivate
111     public void deactivate() {
112         ruleRegistry.removeRegistryChangeListener(this);
113     }
114
115     /**
116      * Called by the registry when a rule got added (and when a rule got modified).
117      * <p>
118      * Converts the rule into a {@link HueScheduleEntry} object and add that to the hue datastore.
119      */
120     @Override
121     public void added(Rule rule) {
122         if (!rule.getTags().contains(SCHEDULE_TAG)) {
123             return;
124         }
125         HueScheduleEntry entry = new HueScheduleEntry();
126         entry.name = rule.getName();
127         entry.description = rule.getDescription();
128         entry.autodelete = rule.getActions().stream().anyMatch(p -> p.getId().equals("autodelete"));
129         entry.status = ruleManager.isEnabled(rule.getUID()) ? "enabled" : "disabled";
130
131         String timeStringFromTrigger = RuleUtils.timeStringFromTrigger(rule.getTriggers());
132         if (timeStringFromTrigger == null) {
133             logger.warn("Schedule from rule '{}' invalid!", rule.getName());
134             return;
135         }
136
137         entry.localtime = timeStringFromTrigger;
138
139         for (Action a : rule.getActions()) {
140             if (!a.getTypeUID().equals("rules.HttpAction")) {
141                 continue;
142             }
143             HueCommand command = RuleUtils.httpActionToHueCommand(cs.ds, a, rule.getName());
144             if (command == null) {
145                 continue;
146             }
147             entry.command = command;
148         }
149
150         cs.ds.schedules.put(rule.getUID(), entry);
151     }
152
153     @Override
154     public void removed(Rule element) {
155         cs.ds.schedules.remove(element.getUID());
156     }
157
158     @Override
159     public void updated(Rule oldElement, Rule element) {
160         removed(oldElement);
161         added(element);
162     }
163
164     /**
165      * Creates a new rule that executes a http rule action, triggered by the scheduled time
166      *
167      * @param uid A rule unique id.
168      * @param builder A rule builder that will be used for creating the rule. It must have been created with the given
169      *            uid.
170      * @param oldActions Old actions. Useful if `data` is only partially set and old actions should be preserved
171      * @param data The configuration for the http action and trigger time is in here
172      * @return A new rule with the given uid
173      * @throws IllegalStateException If a required parameter is not set or if a light / group that is referred to is not
174      *             existing
175      */
176     protected static Rule createRule(String uid, RuleBuilder builder, List<Action> oldActions,
177             List<Trigger> oldTriggers, HueChangeScheduleEntry data, HueDataStore ds) throws IllegalStateException {
178         HueCommand command = data.command;
179         Boolean autodelete = data.autodelete;
180
181         String temp;
182
183         temp = data.name;
184         if (temp != null) {
185             builder.withName(temp);
186         } else if (oldActions.isEmpty()) { // This is a new rule without a name yet
187             throw new IllegalStateException("Name not set!");
188         }
189
190         temp = data.description;
191         if (temp != null) {
192             builder.withDescription(temp);
193         }
194
195         temp = data.localtime;
196         if (temp != null) {
197             builder.withTriggers(RuleUtils.createTriggerForTimeString(temp));
198         } else if (oldTriggers.isEmpty()) { // This is a new rule without triggers yet
199             throw new IllegalStateException("localtime not set!");
200         }
201
202         List<Action> actions = new ArrayList<>(oldActions);
203
204         if (command != null) {
205             RuleUtils.validateHueHttpAddress(ds, command.address);
206             actions.removeIf(a -> a.getId().equals("command")); // Remove old command action if any and add new one
207             actions.add(RuleUtils.createHttpAction(command, "command"));
208         } else if (oldActions.isEmpty()) { // This is a new rule without an action yet
209             throw new IllegalStateException("No command set!");
210         }
211
212         if (autodelete != null) {
213             // Remove action to remove rule after execution
214             actions = actions.stream().filter(e -> !e.getId().equals("autodelete"))
215                     .collect(Collectors.toCollection(() -> new ArrayList<>()));
216             if (autodelete) { // Add action to remove this rule again after execution
217                 final Configuration actionConfig = new Configuration();
218                 actionConfig.put("removeuid", uid);
219                 actions.add(ModuleBuilder.createAction().withId("autodelete").withTypeUID("rules.RemoveRuleAction")
220                         .withConfiguration(actionConfig).build());
221             }
222         }
223
224         builder.withActions(actions);
225
226         return builder.withVisibility(Visibility.VISIBLE).withTags(SCHEDULE_TAG).build();
227     }
228
229     @GET
230     @Path("{username}/schedules")
231     @Produces(MediaType.APPLICATION_JSON)
232     @Operation(summary = "Return all schedules", responses = { @ApiResponse(responseCode = "200", description = "OK") })
233     public Response getSchedulesApi(@Context UriInfo uri,
234             @PathParam("username") @Parameter(description = "username") String username) {
235         if (!userManagement.authorizeUser(username)) {
236             return NetworkUtils.singleError(cs.gson, uri, HueResponse.UNAUTHORIZED, "Not Authorized");
237         }
238         return Response.ok(cs.gson.toJson(cs.ds.schedules)).build();
239     }
240
241     @GET
242     @Path("{username}/schedules/{id}")
243     @Operation(summary = "Return a schedule", responses = { @ApiResponse(responseCode = "200", description = "OK") })
244     public Response getScheduleApi(@Context UriInfo uri, //
245             @PathParam("username") @Parameter(description = "username") String username,
246             @PathParam("id") @Parameter(description = "schedule id") String id) {
247         if (!userManagement.authorizeUser(username)) {
248             return NetworkUtils.singleError(cs.gson, uri, HueResponse.UNAUTHORIZED, "Not Authorized");
249         }
250         return Response.ok(cs.gson.toJson(cs.ds.schedules.get(id))).build();
251     }
252
253     @DELETE
254     @Path("{username}/schedules/{id}")
255     @Operation(summary = "Deletes a schedule", responses = {
256             @ApiResponse(responseCode = "200", description = "The user got removed"),
257             @ApiResponse(responseCode = "403", description = "Access denied") })
258     public Response removeScheduleApi(@Context UriInfo uri,
259             @PathParam("username") @Parameter(description = "username") String username,
260             @PathParam("id") @Parameter(description = "Schedule to remove") String id) {
261         if (!userManagement.authorizeUser(username)) {
262             return NetworkUtils.singleError(cs.gson, uri, HueResponse.UNAUTHORIZED, "Not Authorized");
263         }
264
265         Rule rule = ruleRegistry.remove(id);
266         if (rule == null) {
267             return NetworkUtils.singleError(cs.gson, uri, HueResponse.NOT_AVAILABLE, "Schedule does not exist!");
268         }
269
270         return NetworkUtils.singleSuccess(cs.gson, "/schedules/" + id + " deleted.");
271     }
272
273     @PUT
274     @Path("{username}/schedules/{id}")
275     @Operation(summary = "Set schedule attributes", responses = {
276             @ApiResponse(responseCode = "200", description = "OK") })
277     public Response modifyScheduleApi(@Context UriInfo uri, //
278             @PathParam("username") @Parameter(description = "username") String username,
279             @PathParam("id") @Parameter(description = "schedule id") String id, String body) {
280         if (!userManagement.authorizeUser(username)) {
281             return NetworkUtils.singleError(cs.gson, uri, HueResponse.UNAUTHORIZED, "Not Authorized");
282         }
283
284         final HueChangeScheduleEntry changeRequest = Objects
285                 .requireNonNull(cs.gson.fromJson(body, HueChangeScheduleEntry.class));
286
287         Rule rule = ruleRegistry.remove(id);
288         if (rule == null) {
289             return NetworkUtils.singleError(cs.gson, uri, HueResponse.NOT_AVAILABLE, "Schedule does not exist!");
290         }
291
292         RuleBuilder builder = RuleBuilder.create(rule);
293
294         try {
295             ruleRegistry.add(
296                     createRule(rule.getUID(), builder, rule.getActions(), rule.getTriggers(), changeRequest, cs.ds));
297         } catch (IllegalStateException e) {
298             return NetworkUtils.singleError(cs.gson, uri, HueResponse.ARGUMENTS_INVALID, e.getMessage());
299         }
300
301         return NetworkUtils.successList(cs.gson, Arrays.asList( //
302                 new HueSuccessGeneric(changeRequest.name, "/schedules/" + id + "/name"), //
303                 new HueSuccessGeneric(changeRequest.description, "/schedules/" + id + "/description"), //
304                 new HueSuccessGeneric(changeRequest.localtime, "/schedules/" + id + "/localtime"), //
305                 new HueSuccessGeneric(changeRequest.status, "/schedules/" + id + "/status"), //
306                 new HueSuccessGeneric(changeRequest.autodelete, "/schedules/1/autodelete"), //
307                 new HueSuccessGeneric(changeRequest.command, "/schedules/1/command") //
308         ));
309     }
310
311     @SuppressWarnings({ "null" })
312     @POST
313     @Path("{username}/schedules")
314     @Operation(summary = "Create a new schedule", responses = {
315             @ApiResponse(responseCode = "200", description = "OK") })
316     public Response postNewSchedule(@Context UriInfo uri,
317             @PathParam("username") @Parameter(description = "username") String username, String body) {
318         if (!userManagement.authorizeUser(username)) {
319             return NetworkUtils.singleError(cs.gson, uri, HueResponse.UNAUTHORIZED, "Not Authorized");
320         }
321
322         HueScheduleEntry newScheduleData = cs.gson.fromJson(body, HueScheduleEntry.class);
323         if (newScheduleData == null || newScheduleData.name.isEmpty() || newScheduleData.localtime.isEmpty()) {
324             return NetworkUtils.singleError(cs.gson, uri, HueResponse.INVALID_JSON,
325                     "Invalid request: No name or localtime!");
326         }
327
328         String uid = UUID.randomUUID().toString();
329         RuleBuilder builder = RuleBuilder.create(uid);
330
331         Rule rule;
332         try {
333             rule = createRule(uid, builder, Collections.emptyList(), Collections.emptyList(), newScheduleData, cs.ds);
334         } catch (IllegalStateException e) { // No stacktrace required, we just need the exception message
335             return NetworkUtils.singleError(cs.gson, uri, HueResponse.ARGUMENTS_INVALID, e.getMessage());
336         }
337
338         ruleRegistry.add(rule);
339
340         return NetworkUtils.singleSuccess(cs.gson, uid, "id");
341     }
342 }