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