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