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