2 * Copyright (c) 2010-2020 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
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
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.io.hueemulation.internal.rest;
16 import java.util.stream.Collectors;
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;
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;
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;
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.
70 * If the scheduled task should remove itself after completion, a RemoveRuleAction is used in the rule.
72 * The actual command execution uses HttpAction.
74 * @author David Graeff - Initial contribution
76 @Component(immediate = false, service = Schedules.class)
78 @JaxrsApplicationSelect("(" + JaxrsWhiteboardConstants.JAX_RS_NAME + "=" + HueEmulationService.REST_APP_NAME + ")")
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);
88 protected @NonNullByDefault({}) ConfigStore cs;
90 protected @NonNullByDefault({}) UserManagement userManagement;
93 protected @NonNullByDefault({}) RuleManager ruleManager;
95 protected @NonNullByDefault({}) RuleRegistry ruleRegistry;
98 * Registers to the {@link RuleRegistry} and enumerates currently existing rules.
101 public void activate() {
102 ruleRegistry.removeRegistryChangeListener(this);
103 ruleRegistry.addRegistryChangeListener(this);
105 for (Rule item : ruleRegistry.getAll()) {
111 public void deactivate() {
112 ruleRegistry.removeRegistryChangeListener(this);
116 * Called by the registry when a rule got added (and when a rule got modified).
118 * Converts the rule into a {@link HueScheduleEntry} object and add that to the hue datastore.
121 public void added(Rule rule) {
122 if (!rule.getTags().contains(SCHEDULE_TAG)) {
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";
131 String timeStringFromTrigger = RuleUtils.timeStringFromTrigger(rule.getTriggers());
132 if (timeStringFromTrigger == null) {
133 logger.warn("Schedule from rule '{}' invalid!", rule.getName());
137 entry.localtime = timeStringFromTrigger;
139 for (Action a : rule.getActions()) {
140 if (!a.getTypeUID().equals("rules.HttpAction")) {
143 HueCommand command = RuleUtils.httpActionToHueCommand(cs.ds, a, rule.getName());
144 if (command == null) {
147 entry.command = command;
150 cs.ds.schedules.put(rule.getUID(), entry);
154 public void removed(Rule element) {
155 cs.ds.schedules.remove(element.getUID());
159 public void updated(Rule oldElement, Rule element) {
165 * Creates a new rule that executes a http rule action, triggered by the scheduled time
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
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
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;
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!");
190 temp = data.description;
192 builder.withDescription(temp);
195 temp = data.localtime;
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!");
202 List<Action> actions = new ArrayList<>(oldActions);
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!");
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());
224 builder.withActions(actions);
226 return builder.withVisibility(Visibility.VISIBLE).withTags(SCHEDULE_TAG).build();
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");
238 return Response.ok(cs.gson.toJson(cs.ds.schedules)).build();
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");
250 return Response.ok(cs.gson.toJson(cs.ds.schedules.get(id))).build();
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");
265 Rule rule = ruleRegistry.remove(id);
267 return NetworkUtils.singleError(cs.gson, uri, HueResponse.NOT_AVAILABLE, "Schedule does not exist!");
270 return NetworkUtils.singleSuccess(cs.gson, "/schedules/" + id + " deleted.");
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");
284 final HueChangeScheduleEntry changeRequest = Objects
285 .requireNonNull(cs.gson.fromJson(body, HueChangeScheduleEntry.class));
287 Rule rule = ruleRegistry.remove(id);
289 return NetworkUtils.singleError(cs.gson, uri, HueResponse.NOT_AVAILABLE, "Schedule does not exist!");
292 RuleBuilder builder = RuleBuilder.create(rule);
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());
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") //
311 @SuppressWarnings({ "null" })
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");
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!");
328 String uid = UUID.randomUUID().toString();
329 RuleBuilder builder = RuleBuilder.create(uid);
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());
338 ruleRegistry.add(rule);
340 return NetworkUtils.singleSuccess(cs.gson, uid, "id");