Extract class for supplying commands, improve tests for FCP interface
[Sone.git] / src / main / java / net / pterodactylus / sone / fcp / FcpInterface.java
1 /*
2  * Sone - FcpInterface.java - Copyright © 2011–2016 David Roden
3  *
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
16  */
17
18 package net.pterodactylus.sone.fcp;
19
20 import static com.google.common.base.Preconditions.checkNotNull;
21 import static java.util.logging.Logger.getLogger;
22
23 import java.util.HashMap;
24 import java.util.Map;
25 import java.util.concurrent.atomic.AtomicBoolean;
26 import java.util.concurrent.atomic.AtomicReference;
27 import java.util.logging.Level;
28 import java.util.logging.Logger;
29
30 import javax.inject.Singleton;
31
32 import net.pterodactylus.sone.core.Core;
33 import net.pterodactylus.sone.fcp.event.FcpInterfaceActivatedEvent;
34 import net.pterodactylus.sone.fcp.event.FcpInterfaceDeactivatedEvent;
35 import net.pterodactylus.sone.fcp.event.FullAccessRequiredChanged;
36 import net.pterodactylus.sone.freenet.fcp.Command.AccessType;
37 import net.pterodactylus.sone.freenet.fcp.Command.ErrorResponse;
38 import net.pterodactylus.sone.freenet.fcp.Command.Response;
39
40 import freenet.pluginmanager.FredPluginFCP;
41 import freenet.pluginmanager.PluginNotFoundException;
42 import freenet.pluginmanager.PluginReplySender;
43 import freenet.support.SimpleFieldSet;
44 import freenet.support.api.Bucket;
45
46 import com.google.common.annotations.VisibleForTesting;
47 import com.google.common.eventbus.Subscribe;
48 import com.google.inject.Inject;
49
50 /**
51  * Implementation of an FCP interface for other clients or plugins to
52  * communicate with Sone.
53  *
54  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
55  */
56 @Singleton
57 public class FcpInterface {
58
59         /**
60          * The action level that full access for the FCP connection is required.
61          *
62          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
63          */
64         public enum FullAccessRequired {
65
66                 /** No action requires full access. */
67                 NO,
68
69                 /** All writing actions require full access. */
70                 WRITING,
71
72                 /** All actions require full access. */
73                 ALWAYS,
74
75         }
76
77         /** The logger. */
78         private static final Logger logger = getLogger(FcpInterface.class.getName());
79
80         /** Whether the FCP interface is currently active. */
81         private final AtomicBoolean active = new AtomicBoolean();
82
83         /** What function full access is required for. */
84         private final AtomicReference<FullAccessRequired> fullAccessRequired = new AtomicReference<FullAccessRequired>(FullAccessRequired.ALWAYS);
85
86         /** All available FCP commands. */
87         private final Map<String, AbstractSoneCommand> commands;
88
89         /**
90          * Creates a new FCP interface.
91          *
92          * @param core
93          *            The core
94          */
95         @Inject
96         public FcpInterface(Core core, CommandSupplier commandSupplier) {
97                 commands = commandSupplier.supplyCommands(core);
98         }
99
100         //
101         // ACCESSORS
102         //
103
104         @VisibleForTesting
105         boolean isActive() {
106                 return active.get();
107         }
108
109         private void setActive(boolean active) {
110                 this.active.set(active);
111         }
112
113         @VisibleForTesting
114         FullAccessRequired getFullAccessRequired() {
115                 return fullAccessRequired.get();
116         }
117
118         private void setFullAccessRequired(FullAccessRequired fullAccessRequired) {
119                 this.fullAccessRequired.set(checkNotNull(fullAccessRequired, "fullAccessRequired must not be null"));
120         }
121
122         //
123         // ACTIONS
124         //
125
126         /**
127          * Handles a plugin FCP request.
128          *
129          * @param pluginReplySender
130          *            The reply sender
131          * @param parameters
132          *            The message parameters
133          * @param data
134          *            The message data (may be {@code null})
135          * @param accessType
136          *            One of {@link FredPluginFCP#ACCESS_DIRECT},
137          *            {@link FredPluginFCP#ACCESS_FCP_FULL},
138          *            {@link FredPluginFCP#ACCESS_FCP_RESTRICTED}
139          */
140         public void handle(PluginReplySender pluginReplySender, SimpleFieldSet parameters, Bucket data, int accessType) {
141                 if (!active.get()) {
142                         sendErrorReply(pluginReplySender, null, 503, "FCP Interface deactivated");
143                         return;
144                 }
145                 AbstractSoneCommand command = commands.get(parameters.get("Message"));
146                 if ((accessType == FredPluginFCP.ACCESS_FCP_RESTRICTED) && (((fullAccessRequired.get() == FullAccessRequired.WRITING) && command.requiresWriteAccess()) || (fullAccessRequired.get() == FullAccessRequired.ALWAYS))) {
147                         sendErrorReply(pluginReplySender, null, 401, "Not authorized");
148                         return;
149                 }
150                 if (command == null) {
151                         sendErrorReply(pluginReplySender, null, 404, "Unrecognized Message: " + parameters.get("Message"));
152                         return;
153                 }
154                 String identifier = parameters.get("Identifier");
155                 if ((identifier == null) || (identifier.length() == 0)) {
156                         sendErrorReply(pluginReplySender, null, 400, "Missing Identifier.");
157                         return;
158                 }
159                 try {
160                         Response response = command.execute(parameters, data, AccessType.values()[accessType]);
161                         sendReply(pluginReplySender, identifier, response);
162                 } catch (Exception e1) {
163                         logger.log(Level.WARNING, "Could not process FCP command “%s”.", command);
164                         sendErrorReply(pluginReplySender, identifier, 500, "Error executing command: " + e1.getMessage());
165                 }
166         }
167
168         private void sendErrorReply(PluginReplySender pluginReplySender, String identifier, int errorCode, String message) {
169                 try {
170                         sendReply(pluginReplySender, identifier, new ErrorResponse(errorCode, message));
171                 } catch (PluginNotFoundException pnfe1) {
172                         logger.log(Level.FINE, "Could not send error to plugin.", pnfe1);
173                 }
174         }
175
176         //
177         // PRIVATE METHODS
178         //
179
180         /**
181          * Sends the given response to the given plugin.
182          *
183          * @param pluginReplySender
184          *            The reply sender
185          * @param identifier
186          *            The identifier (may be {@code null})
187          * @param response
188          *            The response to send
189          * @throws PluginNotFoundException
190          *             if the plugin can not be found
191          */
192         private static void sendReply(PluginReplySender pluginReplySender, String identifier, Response response) throws PluginNotFoundException {
193                 SimpleFieldSet replyParameters = response.getReplyParameters();
194                 if (identifier != null) {
195                         replyParameters.putOverwrite("Identifier", identifier);
196                 }
197                 if (response.hasData()) {
198                         pluginReplySender.send(replyParameters, response.getData());
199                 } else if (response.hasBucket()) {
200                         pluginReplySender.send(replyParameters, response.getBucket());
201                 } else {
202                         pluginReplySender.send(replyParameters);
203                 }
204         }
205
206         @Subscribe
207         public void fcpInterfaceActivated(FcpInterfaceActivatedEvent fcpInterfaceActivatedEvent) {
208                 setActive(true);
209         }
210
211         @Subscribe
212         public void fcpInterfaceDeactivated(FcpInterfaceDeactivatedEvent fcpInterfaceDeactivatedEvent) {
213                 setActive(false);
214         }
215
216         @Subscribe
217         public void fullAccessRequiredChanged(FullAccessRequiredChanged fullAccessRequiredChanged) {
218                 setFullAccessRequired(fullAccessRequiredChanged.getFullAccessRequired());
219         }
220
221         @Singleton
222         public static class CommandSupplier {
223
224                 public Map<String, AbstractSoneCommand> supplyCommands(Core core) {
225                         Map<String, AbstractSoneCommand> commands = new HashMap<>();
226                         commands.put("Version", new VersionCommand(core));
227                         commands.put("GetLocalSones", new GetLocalSonesCommand(core));
228                         commands.put("GetSones", new GetSonesCommand(core));
229                         commands.put("GetSone", new GetSoneCommand(core));
230                         commands.put("GetPost", new GetPostCommand(core));
231                         commands.put("GetPosts", new GetPostsCommand(core));
232                         commands.put("GetPostFeed", new GetPostFeedCommand(core));
233                         commands.put("LockSone", new LockSoneCommand(core));
234                         commands.put("UnlockSone", new UnlockSoneCommand(core));
235                         commands.put("LikePost", new LikePostCommand(core));
236                         commands.put("LikeReply", new LikeReplyCommand(core));
237                         commands.put("CreatePost", new CreatePostCommand(core));
238                         commands.put("CreateReply", new CreateReplyCommand(core));
239                         commands.put("DeletePost", new DeletePostCommand(core));
240                         commands.put("DeleteReply", new DeleteReplyCommand(core));
241                         return commands;
242                 }
243
244         }
245
246 }