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