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