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