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