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