Add some more tests for FCP interface and refactor
[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.Collections;
24 import java.util.HashMap;
25 import java.util.Map;
26 import java.util.concurrent.atomic.AtomicBoolean;
27 import java.util.concurrent.atomic.AtomicReference;
28 import java.util.logging.Level;
29 import java.util.logging.Logger;
30
31 import net.pterodactylus.sone.core.Core;
32 import net.pterodactylus.sone.fcp.event.FcpInterfaceActivatedEvent;
33 import net.pterodactylus.sone.fcp.event.FcpInterfaceDeactivatedEvent;
34 import net.pterodactylus.sone.fcp.event.FullAccessRequiredChanged;
35 import net.pterodactylus.sone.freenet.fcp.Command.AccessType;
36 import net.pterodactylus.sone.freenet.fcp.Command.ErrorResponse;
37 import net.pterodactylus.sone.freenet.fcp.Command.Response;
38
39 import freenet.pluginmanager.FredPluginFCP;
40 import freenet.pluginmanager.PluginNotFoundException;
41 import freenet.pluginmanager.PluginReplySender;
42 import freenet.support.SimpleFieldSet;
43 import freenet.support.api.Bucket;
44
45 import com.google.common.annotations.VisibleForTesting;
46 import com.google.common.eventbus.Subscribe;
47 import com.google.inject.Inject;
48 import com.google.inject.Singleton;
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 = Collections.synchronizedMap(new HashMap<String, AbstractSoneCommand>());
88
89         /**
90          * Creates a new FCP interface.
91          *
92          * @param core
93          *            The core
94          */
95         @Inject
96         public FcpInterface(Core core) {
97                 commands.put("Version", new VersionCommand(core));
98                 commands.put("GetLocalSones", new GetLocalSonesCommand(core));
99                 commands.put("GetSones", new GetSonesCommand(core));
100                 commands.put("GetSone", new GetSoneCommand(core));
101                 commands.put("GetPost", new GetPostCommand(core));
102                 commands.put("GetPosts", new GetPostsCommand(core));
103                 commands.put("GetPostFeed", new GetPostFeedCommand(core));
104                 commands.put("LockSone", new LockSoneCommand(core));
105                 commands.put("UnlockSone", new UnlockSoneCommand(core));
106                 commands.put("LikePost", new LikePostCommand(core));
107                 commands.put("LikeReply", new LikeReplyCommand(core));
108                 commands.put("CreatePost", new CreatePostCommand(core));
109                 commands.put("CreateReply", new CreateReplyCommand(core));
110                 commands.put("DeletePost", new DeletePostCommand(core));
111                 commands.put("DeleteReply", new DeleteReplyCommand(core));
112         }
113
114         //
115         // ACCESSORS
116         //
117
118         @VisibleForTesting
119         boolean isActive() {
120                 return active.get();
121         }
122
123         private void setActive(boolean active) {
124                 this.active.set(active);
125         }
126
127         @VisibleForTesting
128         FullAccessRequired getFullAccessRequired() {
129                 return fullAccessRequired.get();
130         }
131
132         private void setFullAccessRequired(FullAccessRequired fullAccessRequired) {
133                 this.fullAccessRequired.set(checkNotNull(fullAccessRequired, "fullAccessRequired must not be null"));
134         }
135
136         //
137         // ACTIONS
138         //
139
140         /**
141          * Handles a plugin FCP request.
142          *
143          * @param pluginReplySender
144          *            The reply sender
145          * @param parameters
146          *            The message parameters
147          * @param data
148          *            The message data (may be {@code null})
149          * @param accessType
150          *            One of {@link FredPluginFCP#ACCESS_DIRECT},
151          *            {@link FredPluginFCP#ACCESS_FCP_FULL},
152          *            {@link FredPluginFCP#ACCESS_FCP_RESTRICTED}
153          */
154         public void handle(PluginReplySender pluginReplySender, SimpleFieldSet parameters, Bucket data, int accessType) {
155                 if (!active.get()) {
156                         sendErrorReply(pluginReplySender, null, 503, "FCP Interface deactivated");
157                         return;
158                 }
159                 AbstractSoneCommand command = commands.get(parameters.get("Message"));
160                 if ((accessType == FredPluginFCP.ACCESS_FCP_RESTRICTED) && (((fullAccessRequired.get() == FullAccessRequired.WRITING) && command.requiresWriteAccess()) || (fullAccessRequired.get() == FullAccessRequired.ALWAYS))) {
161                         sendErrorReply(pluginReplySender, null, 401, "Not authorized");
162                         return;
163                 }
164                 if (command == null) {
165                         sendErrorReply(pluginReplySender, null, 404, "Unrecognized Message: " + parameters.get("Message"));
166                         return;
167                 }
168                 String identifier = parameters.get("Identifier");
169                 if ((identifier == null) || (identifier.length() == 0)) {
170                         sendErrorReply(pluginReplySender, null, 400, "Missing Identifier.");
171                         return;
172                 }
173                 try {
174                         Response response = command.execute(parameters, data, AccessType.values()[accessType]);
175                         sendReply(pluginReplySender, identifier, response);
176                 } catch (Exception e1) {
177                         logger.log(Level.WARNING, "Could not process FCP command “%s”.", command);
178                         sendErrorReply(pluginReplySender, identifier, 500, "Error executing command: " + e1.getMessage());
179                 }
180         }
181
182         private void sendErrorReply(PluginReplySender pluginReplySender, String identifier, int errorCode, String message) {
183                 try {
184                         sendReply(pluginReplySender, identifier, new ErrorResponse(errorCode, message));
185                 } catch (PluginNotFoundException pnfe1) {
186                         logger.log(Level.FINE, "Could not send error to plugin.", pnfe1);
187                 }
188         }
189
190         //
191         // PRIVATE METHODS
192         //
193
194         /**
195          * Sends the given response to the given plugin.
196          *
197          * @param pluginReplySender
198          *            The reply sender
199          * @param identifier
200          *            The identifier (may be {@code null})
201          * @param response
202          *            The response to send
203          * @throws PluginNotFoundException
204          *             if the plugin can not be found
205          */
206         private static void sendReply(PluginReplySender pluginReplySender, String identifier, Response response) throws PluginNotFoundException {
207                 SimpleFieldSet replyParameters = response.getReplyParameters();
208                 if (identifier != null) {
209                         replyParameters.putOverwrite("Identifier", identifier);
210                 }
211                 if (response.hasData()) {
212                         pluginReplySender.send(replyParameters, response.getData());
213                 } else if (response.hasBucket()) {
214                         pluginReplySender.send(replyParameters, response.getBucket());
215                 } else {
216                         pluginReplySender.send(replyParameters);
217                 }
218         }
219
220         @Subscribe
221         public void fcpInterfaceActivated(FcpInterfaceActivatedEvent fcpInterfaceActivatedEvent) {
222                 setActive(true);
223         }
224
225         @Subscribe
226         public void fcpInterfaceDeactivated(FcpInterfaceDeactivatedEvent fcpInterfaceDeactivatedEvent) {
227                 setActive(false);
228         }
229
230         @Subscribe
231         public void fullAccessRequiredChanged(FullAccessRequiredChanged fullAccessRequiredChanged) {
232                 setFullAccessRequired(fullAccessRequiredChanged.getFullAccessRequired());
233         }
234
235 }