Make about page injectable
[Sone.git] / src / main / java / net / pterodactylus / sone / main / SonePlugin.java
1 /*
2  * Sone - SonePlugin.java - Copyright © 2010–2016 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.fcp.FcpInterface;
31 import net.pterodactylus.sone.freenet.PluginStoreConfigurationBackend;
32 import net.pterodactylus.sone.freenet.wot.Context;
33 import net.pterodactylus.sone.freenet.wot.WebOfTrustConnector;
34 import net.pterodactylus.sone.web.WebInterface;
35 import net.pterodactylus.util.config.Configuration;
36 import net.pterodactylus.util.config.ConfigurationException;
37 import net.pterodactylus.util.config.MapConfigurationBackend;
38 import net.pterodactylus.util.version.Version;
39
40 import com.google.common.base.Optional;
41 import com.google.common.cache.CacheBuilder;
42 import com.google.common.cache.CacheLoader;
43 import com.google.common.cache.LoadingCache;
44 import com.google.common.eventbus.EventBus;
45 import com.google.inject.AbstractModule;
46 import com.google.inject.Guice;
47 import com.google.inject.Injector;
48 import com.google.inject.TypeLiteral;
49 import com.google.inject.matcher.Matchers;
50 import com.google.inject.spi.InjectionListener;
51 import com.google.inject.spi.TypeEncounter;
52 import com.google.inject.spi.TypeListener;
53
54 import freenet.client.async.PersistenceDisabledException;
55 import freenet.l10n.BaseL10n.LANGUAGE;
56 import freenet.l10n.PluginL10n;
57 import freenet.node.Node;
58 import freenet.pluginmanager.FredPlugin;
59 import freenet.pluginmanager.FredPluginBaseL10n;
60 import freenet.pluginmanager.FredPluginFCP;
61 import freenet.pluginmanager.FredPluginL10n;
62 import freenet.pluginmanager.FredPluginThreadless;
63 import freenet.pluginmanager.FredPluginVersioned;
64 import freenet.pluginmanager.PluginReplySender;
65 import freenet.pluginmanager.PluginRespirator;
66 import freenet.support.SimpleFieldSet;
67 import freenet.support.api.Bucket;
68
69 /**
70  * This class interfaces with Freenet. It is the class that is loaded by the
71  * node and starts up the whole Sone system.
72  *
73  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
74  */
75 public class SonePlugin implements FredPlugin, FredPluginFCP, FredPluginL10n, FredPluginBaseL10n, FredPluginThreadless, FredPluginVersioned {
76
77         private static final Logger soneLogger = getLogger("net.pterodactylus.sone");
78
79         static {
80                 /* initialize logging. */
81                 soneLogger.setUseParentHandlers(false);
82                 soneLogger.addHandler(new Handler() {
83                         private final LoadingCache<String, Class<?>> classCache = CacheBuilder.newBuilder()
84                                         .build(new CacheLoader<String, Class<?>>() {
85                                                 @Override
86                                                 public Class<?> load(String key) throws Exception {
87                                                         return Class.forName(key);
88                                                 }
89                                         });
90
91                         @Override
92                         public void publish(LogRecord logRecord) {
93                                 int recordLevel = logRecord.getLevel().intValue();
94                                 Class<?> loggingClass = classCache.getUnchecked(logRecord.getLoggerName());
95                                 if (recordLevel < Level.FINE.intValue()) {
96                                         freenet.support.Logger.debug(loggingClass, logRecord.getMessage(), logRecord.getThrown());
97                                 } else if (recordLevel < Level.INFO.intValue()) {
98                                         freenet.support.Logger.minor(loggingClass, logRecord.getMessage(), logRecord.getThrown());
99                                 } else if (recordLevel < Level.WARNING.intValue()) {
100                                         freenet.support.Logger.normal(loggingClass, logRecord.getMessage(), logRecord.getThrown());
101                                 } else if (recordLevel < Level.SEVERE.intValue()) {
102                                         freenet.support.Logger.warning(loggingClass, logRecord.getMessage(), logRecord.getThrown());
103                                 } else {
104                                         freenet.support.Logger.error(loggingClass, 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         private static final Version VERSION = new Version(0, 9, 6);
120
121         /** The current year at time of release. */
122         private static final int YEAR = 2016;
123         private static final String SONE_HOMEPAGE = "USK@nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI,DuQSUZiI~agF8c-6tjsFFGuZ8eICrzWCILB60nT8KKo,AQACAAE/sone/";
124         private static final int LATEST_EDITION = 73;
125
126         /** The logger. */
127         private static final Logger logger = getLogger(SonePlugin.class.getName());
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 String getPluginVersion() {
179                 return VERSION.toString();
180         }
181
182         public static int getYear() {
183                 return YEAR;
184         }
185
186         public static String getHomepage() {
187                 return SONE_HOMEPAGE + LATEST_EDITION;
188         }
189
190         public static long getLatestEdition() {
191                 return LATEST_EDITION;
192         }
193
194         //
195         // FREDPLUGIN METHODS
196         //
197
198         /**
199          * {@inheritDoc}
200          */
201         @Override
202         public void runPlugin(PluginRespirator pluginRespirator) {
203                 this.pluginRespirator = pluginRespirator;
204
205                 /* create a configuration. */
206                 Configuration oldConfiguration;
207                 Configuration newConfiguration = null;
208                 boolean firstStart = !new File("sone.properties").exists();
209                 boolean newConfig = false;
210                 try {
211                         oldConfiguration = new Configuration(new MapConfigurationBackend(new File("sone.properties"), false));
212                         newConfiguration = oldConfiguration;
213                 } catch (ConfigurationException ce1) {
214                         newConfig = true;
215                         logger.log(Level.INFO, "Could not load configuration file, trying plugin store…", ce1);
216                         try {
217                                 newConfiguration = new Configuration(new MapConfigurationBackend(new File("sone.properties"), true));
218                                 logger.log(Level.INFO, "Created new configuration file.");
219                         } catch (ConfigurationException ce2) {
220                                 logger.log(Level.SEVERE, "Could not create configuration file, using Plugin Store!", ce2);
221                         }
222                         try {
223                                 oldConfiguration = new Configuration(new PluginStoreConfigurationBackend(pluginRespirator));
224                                 logger.log(Level.INFO, "Plugin store loaded.");
225                         } catch (PersistenceDisabledException pde1) {
226                                 logger.log(Level.SEVERE, "Could not load any configuration, using empty configuration!");
227                                 oldConfiguration = new Configuration(new MapConfigurationBackend());
228                         }
229                 }
230
231                 final Configuration startConfiguration;
232                 if ((newConfiguration != null) && (oldConfiguration != newConfiguration)) {
233                         logger.log(Level.INFO, "Setting configuration to file-based configuration.");
234                         startConfiguration = newConfiguration;
235                 } else {
236                         startConfiguration = oldConfiguration;
237                 }
238                 final EventBus eventBus = new EventBus();
239
240                 /* Freenet injector configuration. */
241                 AbstractModule freenetModule = new AbstractModule() {
242
243                         @Override
244                         @SuppressWarnings("synthetic-access")
245                         protected void configure() {
246                                 bind(PluginRespirator.class).toInstance(SonePlugin.this.pluginRespirator);
247                                 bind(Node.class).toInstance(SonePlugin.this.pluginRespirator.getNode());
248                         }
249                 };
250                 /* Sone injector configuration. */
251                 AbstractModule soneModule = new AbstractModule() {
252
253                         @Override
254                         protected void configure() {
255                                 bind(EventBus.class).toInstance(eventBus);
256                                 bind(Configuration.class).toInstance(startConfiguration);
257                                 Context context = new Context("Sone");
258                                 bind(Context.class).toInstance(context);
259                                 bind(getOptionalContextTypeLiteral()).toInstance(of(context));
260                                 bind(SonePlugin.class).toInstance(SonePlugin.this);
261                                 bind(Version.class).toInstance(VERSION);
262                                 bind(PluginVersion.class).toInstance(new PluginVersion(getVersion()));
263                                 bind(PluginYear.class).toInstance(new PluginYear(getYear()));
264                                 bind(PluginHomepage.class).toInstance(new PluginHomepage(getHomepage()));
265                                 if (startConfiguration.getBooleanValue("Developer.LoadFromFilesystem").getValue(false)) {
266                                         String path = startConfiguration.getStringValue("Developer.FilesystemPath").getValue(null);
267                                         if (path != null) {
268                                                 bind(Loaders.class).toInstance(new DebugLoaders(path));
269                                         }
270                                 }
271                                 bindListener(Matchers.any(), new TypeListener() {
272
273                                         @Override
274                                         public <I> void hear(TypeLiteral<I> typeLiteral, TypeEncounter<I> typeEncounter) {
275                                                 typeEncounter.register(new InjectionListener<I>() {
276
277                                                         @Override
278                                                         public void afterInjection(I injectee) {
279                                                                 eventBus.register(injectee);
280                                                         }
281                                                 });
282                                         }
283                                 });
284                         }
285
286                         private TypeLiteral<Optional<Context>> getOptionalContextTypeLiteral() {
287                                 return new TypeLiteral<Optional<Context>>() {
288                                 };
289                         }
290
291                 };
292                 Injector injector = Guice.createInjector(freenetModule, soneModule);
293                 core = injector.getInstance(Core.class);
294
295                 /* create web of trust connector. */
296                 webOfTrustConnector = injector.getInstance(WebOfTrustConnector.class);
297
298                 /* create FCP interface. */
299                 fcpInterface = injector.getInstance(FcpInterface.class);
300
301                 /* create the web interface. */
302                 webInterface = injector.getInstance(WebInterface.class);
303
304                 /* start core! */
305                 core.start();
306                 webInterface.start();
307                 webInterface.setFirstStart(firstStart);
308                 webInterface.setNewConfig(newConfig);
309         }
310
311         /**
312          * {@inheritDoc}
313          */
314         @Override
315         public void terminate() {
316                 try {
317                         /* stop the web interface. */
318                         webInterface.stop();
319
320                         /* stop the core. */
321                         core.stop();
322
323                         /* stop the web of trust connector. */
324                         webOfTrustConnector.stop();
325                 } catch (Throwable t1) {
326                         logger.log(Level.SEVERE, "Error while shutting down!", t1);
327                 } finally {
328                         deregisterLoggerHandlers();
329                 }
330         }
331
332         private void deregisterLoggerHandlers() {
333                 for (Handler handler : soneLogger.getHandlers()) {
334                         soneLogger.removeHandler(handler);
335                 }
336         }
337
338         //
339         // INTERFACE FredPluginFCP
340         //
341
342         /**
343          * {@inheritDoc}
344          */
345         @Override
346         public void handle(PluginReplySender pluginReplySender, SimpleFieldSet parameters, Bucket data, int accessType) {
347                 fcpInterface.handle(pluginReplySender, parameters, data, accessType);
348         }
349
350         //
351         // INTERFACE FredPluginL10n
352         //
353
354         /**
355          * {@inheritDoc}
356          */
357         @Override
358         public String getString(String key) {
359                 return l10n.getBase().getString(key);
360         }
361
362         /**
363          * {@inheritDoc}
364          */
365         @Override
366         public void setLanguage(LANGUAGE newLanguage) {
367                 l10n = new PluginL10n(this, newLanguage);
368         }
369
370         //
371         // INTERFACE FredPluginBaseL10n
372         //
373
374         /**
375          * {@inheritDoc}
376          */
377         @Override
378         public String getL10nFilesBasePath() {
379                 return "i18n";
380         }
381
382         /**
383          * {@inheritDoc}
384          */
385         @Override
386         public String getL10nFilesMask() {
387                 return "sone.${lang}.properties";
388         }
389
390         /**
391          * {@inheritDoc}
392          */
393         @Override
394         public String getL10nOverrideFilesMask() {
395                 return "sone.${lang}.override.properties";
396         }
397
398         /**
399          * {@inheritDoc}
400          */
401         @Override
402         public ClassLoader getPluginClassLoader() {
403                 return SonePlugin.class.getClassLoader();
404         }
405
406         //
407         // INTERFACE FredPluginVersioned
408         //
409
410         /**
411          * {@inheritDoc}
412          */
413         @Override
414         public String getVersion() {
415                 return VERSION.toString();
416         }
417
418         public static class PluginVersion {
419
420                 private final String version;
421
422                 public PluginVersion(String version) {
423                         this.version = version;
424                 }
425
426                 public String getVersion() {
427                         return version;
428                 }
429
430         }
431
432         public static class PluginYear {
433
434                 private final int year;
435
436                 public PluginYear(int year) {
437                         this.year = year;
438                 }
439
440                 public int getYear() {
441                         return year;
442                 }
443
444         }
445
446         public static class PluginHomepage {
447
448                 private final String homepage;
449
450                 public PluginHomepage(String homepage) {
451                         this.homepage = homepage;
452                 }
453
454                 public String getHomepage() {
455                         return homepage;
456                 }
457
458         }
459
460 }