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