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