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