Add method to add a command for testing.
[Sone.git] / src / main / java / net / pterodactylus / sone / fcp / FcpInterface.java
1 /*
2  * Sone - FcpInterface.java - Copyright © 2011–2013 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
22 import java.util.Collections;
23 import java.util.HashMap;
24 import java.util.Map;
25 import java.util.logging.Level;
26 import java.util.logging.Logger;
27
28 import net.pterodactylus.sone.core.Core;
29 import net.pterodactylus.sone.freenet.fcp.Command.AccessType;
30 import net.pterodactylus.sone.freenet.fcp.Command.ErrorResponse;
31 import net.pterodactylus.sone.freenet.fcp.Command.Response;
32 import net.pterodactylus.util.logging.Logging;
33
34 import com.google.inject.Inject;
35
36 import freenet.pluginmanager.FredPluginFCP;
37 import freenet.pluginmanager.PluginNotFoundException;
38 import freenet.pluginmanager.PluginReplySender;
39 import freenet.support.SimpleFieldSet;
40 import freenet.support.api.Bucket;
41
42 import com.google.common.annotations.VisibleForTesting;
43 /**
44  * Implementation of an FCP interface for other clients or plugins to
45  * communicate with Sone.
46  *
47  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
48  */
49 public class FcpInterface {
50
51         /**
52          * The action level that full access for the FCP connection is required.
53          *
54          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
55          */
56         public enum FullAccessRequired {
57
58                 /** No action requires full access. */
59                 NO,
60
61                 /** All writing actions require full access. */
62                 WRITING,
63
64                 /** All actions require full access. */
65                 ALWAYS,
66
67         }
68
69         /** The logger. */
70         private static final Logger logger = Logging.getLogger(FcpInterface.class);
71
72         /** Whether the FCP interface is currently active. */
73         private volatile boolean active;
74
75         /** What function full access is required for. */
76         private volatile FullAccessRequired fullAccessRequired = FullAccessRequired.ALWAYS;
77
78         /** All available FCP commands. */
79         private final Map<String, AbstractSoneCommand> commands = Collections.synchronizedMap(new HashMap<String, AbstractSoneCommand>());
80
81         /**
82          * Creates a new FCP interface.
83          *
84          * @param core
85          *            The core
86          */
87         @Inject
88         public FcpInterface(Core core) {
89                 commands.put("Version", new VersionCommand(core));
90                 commands.put("GetLocalSones", new GetLocalSonesCommand(core));
91                 commands.put("GetSones", new GetSonesCommand(core));
92                 commands.put("GetSone", new GetSoneCommand(core));
93                 commands.put("GetPost", new GetPostCommand(core));
94                 commands.put("GetPosts", new GetPostsCommand(core));
95                 commands.put("GetPostFeed", new GetPostFeedCommand(core));
96                 commands.put("LockSone", new LockSoneCommand(core));
97                 commands.put("UnlockSone", new UnlockSoneCommand(core));
98                 commands.put("LikePost", new LikePostCommand(core));
99                 commands.put("LikeReply", new LikeReplyCommand(core));
100                 commands.put("CreatePost", new CreatePostCommand(core));
101                 commands.put("CreateReply", new CreateReplyCommand(core));
102                 commands.put("DeletePost", new DeletePostCommand(core));
103                 commands.put("DeleteReply", new DeleteReplyCommand(core));
104         }
105
106         //
107         // ACCESSORS
108         //
109
110         @VisibleForTesting
111         void addCommand(String name, AbstractSoneCommand command) {
112                 commands.put(name, command);
113         }
114
115         /**
116          * Sets whether the FCP interface should handle requests. If {@code active}
117          * is {@code false}, all requests are answered with an error.
118          *
119          * @param active
120          *            {@code true} to activate the FCP interface, {@code false} to
121          *            deactivate the FCP interface
122          */
123         public void setActive(boolean active) {
124                 this.active = active;
125         }
126
127         /**
128          * Sets the action level for which full FCP access is required.
129          *
130          * @param fullAccessRequired
131          *            The action level for which full FCP access is required
132          */
133         public void setFullAccessRequired(FullAccessRequired fullAccessRequired) {
134                 this.fullAccessRequired = checkNotNull(fullAccessRequired, "fullAccessRequired must not be null");
135         }
136
137         //
138         // ACTIONS
139         //
140
141         /**
142          * Handles a plugin FCP request.
143          *
144          * @param pluginReplySender
145          *            The reply sender
146          * @param parameters
147          *            The message parameters
148          * @param data
149          *            The message data (may be {@code null})
150          * @param accessType
151          *            One of {@link FredPluginFCP#ACCESS_DIRECT},
152          *            {@link FredPluginFCP#ACCESS_FCP_FULL},
153          *            {@link FredPluginFCP#ACCESS_FCP_RESTRICTED}
154          */
155         public void handle(PluginReplySender pluginReplySender, SimpleFieldSet parameters, Bucket data, int accessType) {
156                 if (!active) {
157                         try {
158                                 sendReply(pluginReplySender, null, new ErrorResponse(400, "FCP Interface deactivated"));
159                         } catch (PluginNotFoundException pnfe1) {
160                                 logger.log(Level.FINE, "Could not set error to plugin.", pnfe1);
161                         }
162                         return;
163                 }
164                 AbstractSoneCommand command = commands.get(parameters.get("Message"));
165                 if ((accessType == FredPluginFCP.ACCESS_FCP_RESTRICTED) && (((fullAccessRequired == FullAccessRequired.WRITING) && command.requiresWriteAccess()) || (fullAccessRequired == FullAccessRequired.ALWAYS))) {
166                         try {
167                                 sendReply(pluginReplySender, null, new ErrorResponse(401, "Not authorized"));
168                         } catch (PluginNotFoundException pnfe1) {
169                                 logger.log(Level.FINE, "Could not set error to plugin.", pnfe1);
170                         }
171                         return;
172                 }
173                 try {
174                         if (command == null) {
175                                 sendReply(pluginReplySender, null, new ErrorResponse("Unrecognized Message: " + parameters.get("Message")));
176                                 return;
177                         }
178                         String identifier = parameters.get("Identifier");
179                         if ((identifier == null) || (identifier.length() == 0)) {
180                                 sendReply(pluginReplySender, null, new ErrorResponse("Missing Identifier."));
181                                 return;
182                         }
183                         try {
184                                 Response response = command.execute(parameters, data, AccessType.values()[accessType]);
185                                 sendReply(pluginReplySender, identifier, response);
186                         } catch (Exception e1) {
187                                 logger.log(Level.WARNING, "Could not process FCP command “%s”.", command);
188                                 sendReply(pluginReplySender, identifier, new ErrorResponse("Error executing command: " + e1.getMessage()));
189                         }
190                 } catch (PluginNotFoundException pnfe1) {
191                         logger.log(Level.WARNING, "Could not find destination plugin: " + pluginReplySender);
192                 }
193         }
194
195         //
196         // PRIVATE METHODS
197         //
198
199         /**
200          * Sends the given response to the given plugin.
201          *
202          * @param pluginReplySender
203          *            The reply sender
204          * @param identifier
205          *            The identifier (may be {@code null})
206          * @param response
207          *            The response to send
208          * @throws PluginNotFoundException
209          *             if the plugin can not be found
210          */
211         private static void sendReply(PluginReplySender pluginReplySender, String identifier, Response response) throws PluginNotFoundException {
212                 SimpleFieldSet replyParameters = response.getReplyParameters();
213                 if (identifier != null) {
214                         replyParameters.putOverwrite("Identifier", identifier);
215                 }
216                 if (response.hasData()) {
217                         pluginReplySender.send(replyParameters, response.getData());
218                 } else if (response.hasBucket()) {
219                         pluginReplySender.send(replyParameters, response.getBucket());
220                 } else {
221                         pluginReplySender.send(replyParameters);
222                 }
223         }
224
225 }