3960479cb06aec50bece94c1ae116fff71cdb09a
[Sone.git] / src / main / java / net / pterodactylus / sone / main / SonePlugin.java
1 /*
2  * Sone - SonePlugin.java - Copyright © 2010–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.main;
19
20 import static com.google.common.base.Optional.of;
21 import static java.util.logging.Logger.getLogger;
22
23 import java.io.File;
24 import java.util.logging.Handler;
25 import java.util.logging.Level;
26 import java.util.logging.LogRecord;
27 import java.util.logging.Logger;
28
29 import net.pterodactylus.sone.core.Core;
30 import net.pterodactylus.sone.core.FreenetInterface;
31 import net.pterodactylus.sone.core.WebOfTrustUpdater;
32 import net.pterodactylus.sone.core.WebOfTrustUpdaterImpl;
33 import net.pterodactylus.sone.database.Database;
34 import net.pterodactylus.sone.database.PostBuilderFactory;
35 import net.pterodactylus.sone.database.PostProvider;
36 import net.pterodactylus.sone.database.PostReplyBuilderFactory;
37 import net.pterodactylus.sone.database.SoneProvider;
38 import net.pterodactylus.sone.database.memory.MemoryDatabase;
39 import net.pterodactylus.sone.fcp.FcpInterface;
40 import net.pterodactylus.sone.freenet.PluginStoreConfigurationBackend;
41 import net.pterodactylus.sone.freenet.plugin.PluginConnector;
42 import net.pterodactylus.sone.freenet.wot.Context;
43 import net.pterodactylus.sone.freenet.wot.IdentityManager;
44 import net.pterodactylus.sone.freenet.wot.IdentityManagerImpl;
45 import net.pterodactylus.sone.freenet.wot.WebOfTrustConnector;
46 import net.pterodactylus.sone.web.WebInterface;
47 import net.pterodactylus.util.config.Configuration;
48 import net.pterodactylus.util.config.ConfigurationException;
49 import net.pterodactylus.util.config.MapConfigurationBackend;
50 import net.pterodactylus.util.version.Version;
51
52 import com.google.common.base.Optional;
53 import com.google.common.eventbus.EventBus;
54 import com.google.inject.AbstractModule;
55 import com.google.inject.Guice;
56 import com.google.inject.Injector;
57 import com.google.inject.Singleton;
58 import com.google.inject.TypeLiteral;
59 import com.google.inject.matcher.Matchers;
60 import com.google.inject.spi.InjectionListener;
61 import com.google.inject.spi.TypeEncounter;
62 import com.google.inject.spi.TypeListener;
63
64 import freenet.client.async.PersistenceDisabledException;
65 import freenet.l10n.BaseL10n.LANGUAGE;
66 import freenet.l10n.PluginL10n;
67 import freenet.node.Node;
68 import freenet.pluginmanager.FredPlugin;
69 import freenet.pluginmanager.FredPluginBaseL10n;
70 import freenet.pluginmanager.FredPluginFCP;
71 import freenet.pluginmanager.FredPluginL10n;
72 import freenet.pluginmanager.FredPluginThreadless;
73 import freenet.pluginmanager.FredPluginVersioned;
74 import freenet.pluginmanager.PluginReplySender;
75 import freenet.pluginmanager.PluginRespirator;
76 import freenet.support.SimpleFieldSet;
77 import freenet.support.api.Bucket;
78
79 /**
80  * This class interfaces with Freenet. It is the class that is loaded by the
81  * node and starts up the whole Sone system.
82  *
83  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
84  */
85 public class SonePlugin implements FredPlugin, FredPluginFCP, FredPluginL10n, FredPluginBaseL10n, FredPluginThreadless, FredPluginVersioned {
86
87         static {
88                 /* initialize logging. */
89                 Logger soneLogger = getLogger("Sone");
90                 soneLogger.setUseParentHandlers(false);
91                 soneLogger.addHandler(new Handler() {
92                         @Override
93                         public void publish(LogRecord logRecord) {
94                                 int recordLevel = logRecord.getLevel().intValue();
95                                 if (recordLevel < Level.FINE.intValue()) {
96                                         freenet.support.Logger.debug(logRecord.getLoggerName(), logRecord.getMessage(), logRecord.getThrown());
97                                 } else if (recordLevel < Level.INFO.intValue()) {
98                                         freenet.support.Logger.minor(logRecord.getLoggerName(), logRecord.getMessage(), logRecord.getThrown());
99                                 } else if (recordLevel < Level.WARNING.intValue()) {
100                                         freenet.support.Logger.normal(logRecord.getLoggerName(), logRecord.getMessage(), logRecord.getThrown());
101                                 } else if (recordLevel < Level.SEVERE.intValue()) {
102                                         freenet.support.Logger.warning(logRecord.getLoggerName(), logRecord.getMessage(), logRecord.getThrown());
103                                 } else {
104                                         freenet.support.Logger.error(logRecord.getLoggerName(), logRecord.getMessage(), logRecord.getThrown());
105                                 }
106                         }
107
108                         @Override
109                         public void flush() {
110                         }
111
112                         @Override
113                         public void close() {
114                         }
115                 });
116         }
117
118         /** The version. */
119         public static final Version VERSION = new Version(0, 9, 1);
120
121         /** The current year at time of release. */
122         private static final int YEAR = 2015;
123         private static final String SONE_HOMEPAGE = "USK@nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI,DuQSUZiI~agF8c-6tjsFFGuZ8eICrzWCILB60nT8KKo,AQACAAE/sone/";
124         private static final int LATEST_EDITION = 68;
125
126         /** The logger. */
127         private static final Logger logger = getLogger("Sone.Plugin");
128
129         /** The plugin respirator. */
130         private PluginRespirator pluginRespirator;
131
132         /** The core. */
133         private Core core;
134
135         /** The web interface. */
136         private WebInterface webInterface;
137
138         /** The FCP interface. */
139         private FcpInterface fcpInterface;
140
141         /** The l10n helper. */
142         private PluginL10n l10n;
143
144         /** The web of trust connector. */
145         private WebOfTrustConnector webOfTrustConnector;
146
147         //
148         // ACCESSORS
149         //
150
151         /**
152          * Returns the plugin respirator for this plugin.
153          *
154          * @return The plugin respirator
155          */
156         public PluginRespirator pluginRespirator() {
157                 return pluginRespirator;
158         }
159
160         /**
161          * Returns the core started by this plugin.
162          *
163          * @return The core
164          */
165         public Core core() {
166                 return core;
167         }
168
169         /**
170          * Returns the plugin’s l10n helper.
171          *
172          * @return The plugin’s l10n helper
173          */
174         public PluginL10n l10n() {
175                 return l10n;
176         }
177
178         public static int getYear() {
179                 return YEAR;
180         }
181
182         public static String getHomepage() {
183                 return SONE_HOMEPAGE + LATEST_EDITION;
184         }
185
186         //
187         // FREDPLUGIN METHODS
188         //
189
190         /**
191          * {@inheritDoc}
192          */
193         @Override
194         public void runPlugin(PluginRespirator pluginRespirator) {
195                 this.pluginRespirator = pluginRespirator;
196
197                 /* create a configuration. */
198                 Configuration oldConfiguration;
199                 Configuration newConfiguration = null;
200                 boolean firstStart = !new File("sone.properties").exists();
201                 boolean newConfig = false;
202                 try {
203                         oldConfiguration = new Configuration(new MapConfigurationBackend(new File("sone.properties"), false));
204                         newConfiguration = oldConfiguration;
205                 } catch (ConfigurationException ce1) {
206                         newConfig = true;
207                         logger.log(Level.INFO, "Could not load configuration file, trying plugin store…", ce1);
208                         try {
209                                 newConfiguration = new Configuration(new MapConfigurationBackend(new File("sone.properties"), true));
210                                 logger.log(Level.INFO, "Created new configuration file.");
211                         } catch (ConfigurationException ce2) {
212                                 logger.log(Level.SEVERE, "Could not create configuration file, using Plugin Store!", ce2);
213                         }
214                         try {
215                                 oldConfiguration = new Configuration(new PluginStoreConfigurationBackend(pluginRespirator));
216                                 logger.log(Level.INFO, "Plugin store loaded.");
217                         } catch (PersistenceDisabledException pde1) {
218                                 logger.log(Level.SEVERE, "Could not load any configuration, using empty configuration!");
219                                 oldConfiguration = new Configuration(new MapConfigurationBackend());
220                         }
221                 }
222
223                 final Configuration startConfiguration;
224                 if ((newConfiguration != null) && (oldConfiguration != newConfiguration)) {
225                         logger.log(Level.INFO, "Setting configuration to file-based configuration.");
226                         startConfiguration = newConfiguration;
227                 } else {
228                         startConfiguration = oldConfiguration;
229                 }
230                 final EventBus eventBus = new EventBus();
231
232                 /* Freenet injector configuration. */
233                 AbstractModule freenetModule = new AbstractModule() {
234
235                         @Override
236                         @SuppressWarnings("synthetic-access")
237                         protected void configure() {
238                                 bind(PluginRespirator.class).toInstance(SonePlugin.this.pluginRespirator);
239                                 bind(Node.class).toInstance(SonePlugin.this.pluginRespirator.getNode());
240                         }
241                 };
242                 /* Sone injector configuration. */
243                 AbstractModule soneModule = new AbstractModule() {
244
245                         @Override
246                         protected void configure() {
247                                 bind(EventBus.class).toInstance(eventBus);
248                                 bind(Configuration.class).toInstance(startConfiguration);
249                                 Context context = new Context("Sone");
250                                 bind(Context.class).toInstance(context);
251                                 bind(getOptionalContextTypeLiteral()).toInstance(of(context));
252                                 bind(SonePlugin.class).toInstance(SonePlugin.this);
253                                 bindListener(Matchers.any(), new TypeListener() {
254
255                                         @Override
256                                         public <I> void hear(TypeLiteral<I> typeLiteral, TypeEncounter<I> typeEncounter) {
257                                                 typeEncounter.register(new InjectionListener<I>() {
258
259                                                         @Override
260                                                         public void afterInjection(I injectee) {
261                                                                 eventBus.register(injectee);
262                                                         }
263                                                 });
264                                         }
265                                 });
266                         }
267
268                         private TypeLiteral<Optional<Context>> getOptionalContextTypeLiteral() {
269                                 return new TypeLiteral<Optional<Context>>() {
270                                 };
271                         }
272
273                 };
274                 Injector injector = Guice.createInjector(freenetModule, soneModule);
275                 core = injector.getInstance(Core.class);
276
277                 /* create web of trust connector. */
278                 webOfTrustConnector = injector.getInstance(WebOfTrustConnector.class);
279
280                 /* create FCP interface. */
281                 fcpInterface = injector.getInstance(FcpInterface.class);
282
283                 /* create the web interface. */
284                 webInterface = injector.getInstance(WebInterface.class);
285
286                 /* start core! */
287                 core.start();
288                 webInterface.start();
289                 webInterface.setFirstStart(firstStart);
290                 webInterface.setNewConfig(newConfig);
291         }
292
293         /**
294          * {@inheritDoc}
295          */
296         @Override
297         public void terminate() {
298                 try {
299                         /* stop the web interface. */
300                         webInterface.stop();
301
302                         /* stop the core. */
303                         core.stop();
304
305                         /* stop the web of trust connector. */
306                         webOfTrustConnector.stop();
307                 } catch (Throwable t1) {
308                         logger.log(Level.SEVERE, "Error while shutting down!", t1);
309                 }
310         }
311
312         //
313         // INTERFACE FredPluginFCP
314         //
315
316         /**
317          * {@inheritDoc}
318          */
319         @Override
320         public void handle(PluginReplySender pluginReplySender, SimpleFieldSet parameters, Bucket data, int accessType) {
321                 fcpInterface.handle(pluginReplySender, parameters, data, accessType);
322         }
323
324         //
325         // INTERFACE FredPluginL10n
326         //
327
328         /**
329          * {@inheritDoc}
330          */
331         @Override
332         public String getString(String key) {
333                 return l10n.getBase().getString(key);
334         }
335
336         /**
337          * {@inheritDoc}
338          */
339         @Override
340         public void setLanguage(LANGUAGE newLanguage) {
341                 l10n = new PluginL10n(this, newLanguage);
342         }
343
344         //
345         // INTERFACE FredPluginBaseL10n
346         //
347
348         /**
349          * {@inheritDoc}
350          */
351         @Override
352         public String getL10nFilesBasePath() {
353                 return "i18n";
354         }
355
356         /**
357          * {@inheritDoc}
358          */
359         @Override
360         public String getL10nFilesMask() {
361                 return "sone.${lang}.properties";
362         }
363
364         /**
365          * {@inheritDoc}
366          */
367         @Override
368         public String getL10nOverrideFilesMask() {
369                 return "sone.${lang}.override.properties";
370         }
371
372         /**
373          * {@inheritDoc}
374          */
375         @Override
376         public ClassLoader getPluginClassLoader() {
377                 return SonePlugin.class.getClassLoader();
378         }
379
380         //
381         // INTERFACE FredPluginVersioned
382         //
383
384         /**
385          * {@inheritDoc}
386          */
387         @Override
388         public String getVersion() {
389                 return VERSION.toString();
390         }
391
392 }