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