0f70221672898b8ca72b559fccf23ef3e5cf0d84
[Sone.git] / src / main / java / net / pterodactylus / sone / main / SonePlugin.java
1 /*
2  * Sone - SonePlugin.java - Copyright © 2010–2020 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 java.util.logging.Logger.*;
21
22 import java.util.logging.Logger;
23 import java.util.logging.*;
24
25 import javax.annotation.Nonnull;
26
27 import net.pterodactylus.sone.core.*;
28 import net.pterodactylus.sone.core.event.*;
29 import net.pterodactylus.sone.fcp.*;
30 import net.pterodactylus.sone.freenet.wot.*;
31 import net.pterodactylus.sone.web.*;
32 import net.pterodactylus.sone.web.notification.NotificationHandler;
33 import net.pterodactylus.sone.web.notification.NotificationHandlerModule;
34
35 import freenet.l10n.BaseL10n.*;
36 import freenet.l10n.*;
37 import freenet.pluginmanager.*;
38 import freenet.support.*;
39 import freenet.support.api.*;
40
41 import com.google.common.annotations.*;
42 import com.google.common.eventbus.*;
43 import com.google.common.cache.*;
44 import com.google.inject.*;
45 import com.google.inject.Module;
46 import com.google.inject.name.*;
47 import kotlin.jvm.functions.*;
48
49 /**
50  * This class interfaces with Freenet. It is the class that is loaded by the
51  * node and starts up the whole Sone system.
52  */
53 public class SonePlugin implements FredPlugin, FredPluginFCP, FredPluginL10n, FredPluginBaseL10n, FredPluginThreadless, FredPluginVersioned {
54
55         private static final Logger soneLogger = getLogger("net.pterodactylus.sone");
56
57         static {
58                 /* initialize logging. */
59                 soneLogger.setUseParentHandlers(false);
60                 soneLogger.setLevel(Level.ALL);
61                 soneLogger.addHandler(new Handler() {
62                         private final LoadingCache<String, Class<?>> classCache = CacheBuilder.newBuilder()
63                                         .build(new CacheLoader<String, Class<?>>() {
64                                                 @Override
65                                                 public Class<?> load(@Nonnull String key) throws Exception {
66                                                         return SonePlugin.class.getClassLoader().loadClass(key);
67                                                 }
68                                         });
69
70                         @Override
71                         public void publish(LogRecord logRecord) {
72                                 int recordLevel = logRecord.getLevel().intValue();
73                                 Class<?> loggingClass = classCache.getUnchecked(logRecord.getLoggerName());
74                                 if (recordLevel < Level.FINE.intValue()) {
75                                         freenet.support.Logger.debug(loggingClass, logRecord.getMessage(), logRecord.getThrown());
76                                 } else if (recordLevel < Level.INFO.intValue()) {
77                                         freenet.support.Logger.minor(loggingClass, logRecord.getMessage(), logRecord.getThrown());
78                                 } else if (recordLevel < Level.WARNING.intValue()) {
79                                         freenet.support.Logger.normal(loggingClass, logRecord.getMessage(), logRecord.getThrown());
80                                 } else if (recordLevel < Level.SEVERE.intValue()) {
81                                         freenet.support.Logger.warning(loggingClass, logRecord.getMessage(), logRecord.getThrown());
82                                 } else {
83                                         freenet.support.Logger.error(loggingClass, logRecord.getMessage(), logRecord.getThrown());
84                                 }
85                         }
86
87                         @Override
88                         public void flush() {
89                         }
90
91                         @Override
92                         public void close() {
93                         }
94                 });
95         }
96
97         /** The current year at time of release. */
98         private static final int YEAR = 2019;
99         private static final String SONE_HOMEPAGE = "USK@nwa8lHa271k2QvJ8aa0Ov7IHAV-DFOCFgmDt3X6BpCI,DuQSUZiI~agF8c-6tjsFFGuZ8eICrzWCILB60nT8KKo,AQACAAE/sone/";
100         private static final int LATEST_EDITION = 79;
101
102         /** The logger. */
103         private static final Logger logger = getLogger(SonePlugin.class.getName());
104
105         private final Function1<Module[], Injector> injectorCreator;
106
107         /** The plugin respirator. */
108         private PluginRespirator pluginRespirator;
109
110         /** The core. */
111         private Core core;
112
113         /** The event bus. */
114         private EventBus eventBus;
115
116         /** The web interface. */
117         private WebInterface webInterface;
118
119         /** The FCP interface. */
120         private FcpInterface fcpInterface;
121
122         /** The l10n helper. */
123         private PluginL10n l10n;
124
125         /** The web of trust connector. */
126         private WebOfTrustConnector webOfTrustConnector;
127
128         public SonePlugin() {
129                 this(Guice::createInjector);
130         }
131
132         @VisibleForTesting
133         public SonePlugin(Function1<Module[], Injector> injectorCreator) {
134                 this.injectorCreator = injectorCreator;
135         }
136
137         //
138         // ACCESSORS
139         //
140
141         /**
142          * Returns the plugin respirator for this plugin.
143          *
144          * @return The plugin respirator
145          */
146         public PluginRespirator pluginRespirator() {
147                 return pluginRespirator;
148         }
149
150         /**
151          * Returns the core started by this plugin.
152          *
153          * @return The core
154          */
155         public Core core() {
156                 return core;
157         }
158
159         /**
160          * Returns the plugin’s l10n helper.
161          *
162          * @return The plugin’s l10n helper
163          */
164         public PluginL10n l10n() {
165                 return l10n;
166         }
167
168         public static String getPluginVersion() {
169                 net.pterodactylus.sone.main.Version version = VersionParserKt.getParsedVersion();
170                 return (version == null) ? "unknown" : version.getNice();
171         }
172
173         public int getYear() {
174                 return YEAR;
175         }
176
177         public String getHomepage() {
178                 return SONE_HOMEPAGE + LATEST_EDITION;
179         }
180
181         public static long getLatestEdition() {
182                 return LATEST_EDITION;
183         }
184
185         //
186         // FREDPLUGIN METHODS
187         //
188
189         /**
190          * {@inheritDoc}
191          */
192         @Override
193         public void runPlugin(PluginRespirator pluginRespirator) {
194                 this.pluginRespirator = pluginRespirator;
195
196                 Injector injector = createInjector();
197                 core = injector.getInstance(Core.class);
198
199                 /* create web of trust connector. */
200                 webOfTrustConnector = injector.getInstance(WebOfTrustConnector.class);
201
202                 /* create FCP interface. */
203                 fcpInterface = injector.getInstance(FcpInterface.class);
204
205                 /* create the web interface. */
206                 webInterface = injector.getInstance(WebInterface.class);
207
208                 /* we need to request this to install all notification handlers. */
209                 injector.getInstance(NotificationHandler.class);
210
211                 /* and this is required to shutdown all tickers. */
212                 injector.getInstance(TickerShutdown.class);
213
214                 /* start core! */
215                 core.start();
216
217                 /* start the web interface! */
218                 webInterface.start();
219
220                 /* send some events on startup */
221                 eventBus = injector.getInstance(EventBus.class);
222
223                 /* first start? */
224                 if (injector.getInstance(Key.get(Boolean.class, Names.named("FirstStart")))) {
225                         eventBus.post(new FirstStart());
226                 } else {
227                         /* new config? */
228                         if (injector.getInstance(Key.get(Boolean.class, Names.named("NewConfig")))) {
229                                 eventBus.post(new ConfigNotRead());
230                         }
231                 }
232
233                 eventBus.post(new Startup());
234         }
235
236         @VisibleForTesting
237         protected Injector createInjector() {
238                 FreenetModule freenetModule = new FreenetModule(pluginRespirator);
239                 AbstractModule soneModule = new SoneModule(this, new EventBus());
240                 Module webInterfaceModule = new WebInterfaceModule();
241                 Module notificationHandlerModule = new NotificationHandlerModule();
242
243                 return createInjector(freenetModule, soneModule, webInterfaceModule, notificationHandlerModule);
244         }
245
246         @VisibleForTesting
247         protected Injector createInjector(Module... modules) {
248                 return injectorCreator.invoke(modules);
249         }
250
251         /**
252          * {@inheritDoc}
253          */
254         @Override
255         public void terminate() {
256                 /* send shutdown event. */
257                 eventBus.post(new Shutdown());
258
259                 try {
260                         /* stop the web interface. */
261                         webInterface.stop();
262
263                         /* stop the core. */
264                         core.stop();
265
266                         /* stop the web of trust connector. */
267                         webOfTrustConnector.stop();
268                 } catch (Throwable t1) {
269                         logger.log(Level.SEVERE, "Error while shutting down!", t1);
270                 } finally {
271                         deregisterLoggerHandlers();
272                 }
273         }
274
275         private void deregisterLoggerHandlers() {
276                 for (Handler handler : soneLogger.getHandlers()) {
277                         soneLogger.removeHandler(handler);
278                 }
279         }
280
281         //
282         // INTERFACE FredPluginFCP
283         //
284
285         /**
286          * {@inheritDoc}
287          */
288         @Override
289         public void handle(PluginReplySender pluginReplySender, SimpleFieldSet parameters, Bucket data, int accessType) {
290                 fcpInterface.handle(pluginReplySender, parameters, data, accessType);
291         }
292
293         //
294         // INTERFACE FredPluginL10n
295         //
296
297         /**
298          * {@inheritDoc}
299          */
300         @Override
301         public String getString(String key) {
302                 return l10n.getBase().getString(key);
303         }
304
305         /**
306          * {@inheritDoc}
307          */
308         @Override
309         public void setLanguage(LANGUAGE newLanguage) {
310                 l10n = new PluginL10n(this, newLanguage);
311         }
312
313         //
314         // INTERFACE FredPluginBaseL10n
315         //
316
317         /**
318          * {@inheritDoc}
319          */
320         @Override
321         public String getL10nFilesBasePath() {
322                 return "i18n";
323         }
324
325         /**
326          * {@inheritDoc}
327          */
328         @Override
329         public String getL10nFilesMask() {
330                 return "sone.${lang}.properties";
331         }
332
333         /**
334          * {@inheritDoc}
335          */
336         @Override
337         public String getL10nOverrideFilesMask() {
338                 return "sone.${lang}.override.properties";
339         }
340
341         /**
342          * {@inheritDoc}
343          */
344         @Override
345         public ClassLoader getPluginClassLoader() {
346                 return SonePlugin.class.getClassLoader();
347         }
348
349         //
350         // INTERFACE FredPluginVersioned
351         //
352
353         /**
354          * {@inheritDoc}
355          */
356         @Override
357         public String getVersion() {
358                 return getPluginVersion();
359         }
360
361 }