doc
[nikiroo-utils.git] / Instance.java
... / ...
CommitLineData
1package be.nikiroo.fanfix;
2
3import java.io.File;
4import java.io.IOException;
5import java.util.Date;
6
7import be.nikiroo.fanfix.bundles.Config;
8import be.nikiroo.fanfix.bundles.ConfigBundle;
9import be.nikiroo.fanfix.bundles.StringId;
10import be.nikiroo.fanfix.bundles.StringIdBundle;
11import be.nikiroo.fanfix.bundles.StringIdGuiBundle;
12import be.nikiroo.fanfix.bundles.UiConfig;
13import be.nikiroo.fanfix.bundles.UiConfigBundle;
14import be.nikiroo.fanfix.library.BasicLibrary;
15import be.nikiroo.fanfix.library.CacheLibrary;
16import be.nikiroo.fanfix.library.LocalLibrary;
17import be.nikiroo.fanfix.library.RemoteLibrary;
18import be.nikiroo.utils.Cache;
19import be.nikiroo.utils.IOUtils;
20import be.nikiroo.utils.Image;
21import be.nikiroo.utils.Proxy;
22import be.nikiroo.utils.TempFiles;
23import be.nikiroo.utils.TraceHandler;
24import be.nikiroo.utils.resources.Bundles;
25
26/**
27 * Global state for the program (services and singletons).
28 *
29 * @author niki
30 */
31public class Instance {
32 private static ConfigBundle config;
33 private static UiConfigBundle uiconfig;
34 private static StringIdBundle trans;
35 private static DataLoader cache;
36 private static StringIdGuiBundle transGui;
37 private static BasicLibrary lib;
38 private static File coverDir;
39 private static File readerTmp;
40 private static File remoteDir;
41 private static String configDir;
42 private static TraceHandler tracer;
43 private static TempFiles tempFiles;
44
45 private static boolean init;
46
47 /**
48 * Initialise the instance -- if already initialised, nothing will happen.
49 * <p>
50 * Before calling this method, you may call
51 * {@link Bundles#setDirectory(String)} if wanted.
52 */
53 static public void init() {
54 init(false);
55 }
56
57 /**
58 * Initialise the instance -- if already initialised, nothing will happen
59 * unless you pass TRUE to <tt>force</tt>.
60 * <p>
61 * Before calling this method, you may call
62 * {@link Bundles#setDirectory(String)} if wanted.
63 * <p>
64 * Note: forcing the initialisation can be dangerous, so make sure to only
65 * make it under controlled circumstances -- for instance, at the start of
66 * the program, you could call {@link Instance#init()}, change some settings
67 * because you want to force those settings (it will also forbid users to
68 * change them!) and then call {@link Instance#init(boolean)} with
69 * <tt>force</tt> set to TRUE.
70 *
71 * @param force
72 * force the initialisation even if already initialised
73 */
74 static public void init(boolean force) {
75 if (init && !force) {
76 return;
77 }
78
79 init = true;
80
81 // Before we can configure it:
82 Boolean debug = checkEnv("DEBUG");
83 boolean trace = debug != null && debug;
84 tracer = new TraceHandler(true, trace, trace);
85
86 // config dir:
87 configDir = getConfigDir();
88 if (!new File(configDir).exists()) {
89 new File(configDir).mkdirs();
90 }
91
92 // Most of the rest is dependent upon this:
93 createConfigs(configDir, false);
94
95 // Proxy support
96 Proxy.use(Instance.getConfig().getString(Config.NETWORK_PROXY));
97
98 // update tracer:
99 if (debug == null) {
100 debug = Instance.getConfig().getBoolean(Config.DEBUG_ERR, false);
101 trace = Instance.getConfig().getBoolean(Config.DEBUG_TRACE, false);
102 }
103
104 tracer = new TraceHandler(true, debug, trace);
105
106 // default Library
107 remoteDir = new File(configDir, "remote");
108 lib = createDefaultLibrary(remoteDir);
109
110 // create cache and TMP
111 File tmp = getFile(Config.CACHE_DIR, new File(configDir, "tmp"));
112 if (!tmp.isAbsolute()) {
113 tmp = new File(configDir, tmp.getPath());
114 }
115 Image.setTemporaryFilesRoot(new File(tmp.getParent(), "tmp.images"));
116
117 String ua = config.getString(Config.NETWORK_USER_AGENT, "");
118 try {
119 int hours = config.getInteger(Config.CACHE_MAX_TIME_CHANGING, 0);
120 int hoursLarge = config.getInteger(Config.CACHE_MAX_TIME_STABLE, 0);
121 cache = new DataLoader(tmp, ua, hours, hoursLarge);
122 } catch (IOException e) {
123 tracer.error(new IOException(
124 "Cannot create cache (will continue without cache)", e));
125 cache = new DataLoader(ua);
126 }
127
128 cache.setTraceHandler(tracer);
129
130 // readerTmp / coverDir
131 readerTmp = getFile(UiConfig.CACHE_DIR_LOCAL_READER, new File(
132 configDir, "tmp-reader"));
133
134 coverDir = getFile(Config.DEFAULT_COVERS_DIR, new File(configDir,
135 "covers"));
136 coverDir.mkdirs();
137
138 try {
139 tempFiles = new TempFiles("fanfix");
140 } catch (IOException e) {
141 tracer.error(new IOException("Cannot create temporary directory", e));
142 }
143 }
144
145 /**
146 * The traces handler for this {@link Cache}.
147 * <p>
148 * It is never NULL.
149 *
150 * @return the traces handler (never NULL)
151 */
152 public static TraceHandler getTraceHandler() {
153 return tracer;
154 }
155
156 /**
157 * The traces handler for this {@link Cache}.
158 *
159 * @param tracer
160 * the new traces handler or NULL
161 */
162 public static void setTraceHandler(TraceHandler tracer) {
163 if (tracer == null) {
164 tracer = new TraceHandler(false, false, false);
165 }
166
167 Instance.tracer = tracer;
168 cache.setTraceHandler(tracer);
169 }
170
171 /**
172 * Get the (unique) configuration service for the program.
173 *
174 * @return the configuration service
175 */
176 public static ConfigBundle getConfig() {
177 return config;
178 }
179
180 /**
181 * Get the (unique) UI configuration service for the program.
182 *
183 * @return the configuration service
184 */
185 public static UiConfigBundle getUiConfig() {
186 return uiconfig;
187 }
188
189 /**
190 * Reset the configuration.
191 *
192 * @param resetTrans
193 * also reset the translation files
194 */
195 public static void resetConfig(boolean resetTrans) {
196 String dir = Bundles.getDirectory();
197 Bundles.setDirectory(null);
198 try {
199 try {
200 ConfigBundle config = new ConfigBundle();
201 config.updateFile(configDir);
202 } catch (IOException e) {
203 tracer.error(e);
204 }
205 try {
206 UiConfigBundle uiconfig = new UiConfigBundle();
207 uiconfig.updateFile(configDir);
208 } catch (IOException e) {
209 tracer.error(e);
210 }
211
212 if (resetTrans) {
213 try {
214 StringIdBundle trans = new StringIdBundle(null);
215 trans.updateFile(configDir);
216 } catch (IOException e) {
217 tracer.error(e);
218 }
219 }
220 } finally {
221 Bundles.setDirectory(dir);
222 }
223 }
224
225 /**
226 * Get the (unique) {@link DataLoader} for the program.
227 *
228 * @return the {@link DataLoader}
229 */
230 public static DataLoader getCache() {
231 return cache;
232 }
233
234 /**
235 * Get the (unique) {link StringIdBundle} for the program.
236 * <p>
237 * This is used for the translations of the core parts of Fanfix.
238 *
239 * @return the {link StringIdBundle}
240 */
241 public static StringIdBundle getTrans() {
242 return trans;
243 }
244
245 /**
246 * Get the (unique) {link StringIdGuiBundle} for the program.
247 * <p>
248 * This is used for the translations of the GUI parts of Fanfix.
249 *
250 * @return the {link StringIdGuiBundle}
251 */
252 public static StringIdGuiBundle getTransGui() {
253 return transGui;
254 }
255
256 /**
257 * Get the (unique) {@link LocalLibrary} for the program.
258 *
259 * @return the {@link LocalLibrary}
260 */
261 public static BasicLibrary getLibrary() {
262 if (lib == null) {
263 throw new NullPointerException("We don't have a library to return");
264 }
265
266 return lib;
267 }
268
269 /**
270 * Return the directory where to look for default cover pages.
271 *
272 * @return the default covers directory
273 */
274 public static File getCoverDir() {
275 return coverDir;
276 }
277
278 /**
279 * Return the directory where to store temporary files for the local reader.
280 *
281 * @return the directory
282 */
283 public static File getReaderDir() {
284 return readerTmp;
285 }
286
287 /**
288 * Return the directory where to store temporary files for the remote
289 * {@link LocalLibrary}.
290 *
291 * @param host
292 * the remote for this host
293 *
294 * @return the directory
295 */
296 public static File getRemoteDir(String host) {
297 return getRemoteDir(remoteDir, host);
298 }
299
300 /**
301 * Return the directory where to store temporary files for the remote
302 * {@link LocalLibrary}.
303 *
304 * @param remoteDir
305 * the base remote directory
306 * @param host
307 * the remote for this host
308 *
309 * @return the directory
310 */
311 private static File getRemoteDir(File remoteDir, String host) {
312 remoteDir.mkdirs();
313
314 if (host != null) {
315 return new File(remoteDir, host);
316 }
317
318 return remoteDir;
319 }
320
321 /**
322 * Check if we need to check that a new version of Fanfix is available.
323 *
324 * @return TRUE if we need to
325 */
326 public static boolean isVersionCheckNeeded() {
327 try {
328 long wait = config.getInteger(Config.NETWORK_UPDATE_INTERVAL, 0)
329 * 24 * 60 * 60 * 1000;
330 if (wait >= 0) {
331 String lastUpString = IOUtils.readSmallFile(new File(configDir,
332 "LAST_UPDATE"));
333 long delay = new Date().getTime()
334 - Long.parseLong(lastUpString);
335 if (delay > wait) {
336 return true;
337 }
338 } else {
339 return false;
340 }
341 } catch (Exception e) {
342 // No file or bad file:
343 return true;
344 }
345
346 return false;
347 }
348
349 /**
350 * Notify that we checked for a new version of Fanfix.
351 */
352 public static void setVersionChecked() {
353 try {
354 IOUtils.writeSmallFile(new File(configDir), "LAST_UPDATE",
355 Long.toString(new Date().getTime()));
356 } catch (IOException e) {
357 tracer.error(e);
358 }
359 }
360
361 /**
362 * The facility to use temporary files in this program.
363 * <p>
364 * <b>MUST</b> be closed at end of program.
365 *
366 * @return the facility
367 */
368 public static TempFiles getTempFiles() {
369 return tempFiles;
370 }
371
372 /**
373 * The configuration directory (will check, in order of preference, the
374 * system properties, the environment and then defaults to
375 * {@link Instance#getHome()}/.fanfix).
376 *
377 * @return the config directory
378 */
379 private static String getConfigDir() {
380 String configDir = System.getProperty("CONFIG_DIR");
381
382 if (configDir == null) {
383 configDir = System.getenv("CONFIG_DIR");
384 }
385
386 if (configDir == null) {
387 configDir = new File(getHome(), ".fanfix").getPath();
388 }
389
390 return configDir;
391 }
392
393 /**
394 * Create the config variables ({@link Instance#config},
395 * {@link Instance#uiconfig}, {@link Instance#trans} and
396 * {@link Instance#transGui}).
397 *
398 * @param configDir
399 * the directory where to find the configuration files
400 * @param refresh
401 * TRUE to reset the configuration files from the default
402 * included ones
403 */
404 private static void createConfigs(String configDir, boolean refresh) {
405 if (!refresh) {
406 Bundles.setDirectory(configDir);
407 }
408
409 try {
410 config = new ConfigBundle();
411 config.updateFile(configDir);
412 } catch (IOException e) {
413 tracer.error(e);
414 }
415
416 try {
417 uiconfig = new UiConfigBundle();
418 uiconfig.updateFile(configDir);
419 } catch (IOException e) {
420 tracer.error(e);
421 }
422
423 // No updateFile for this one! (we do not want the user to have custom
424 // translations that won't accept updates from newer versions)
425 trans = new StringIdBundle(getLang());
426 transGui = new StringIdGuiBundle(getLang());
427
428 // Fix an old bug (we used to store custom translation files by
429 // default):
430 if (trans.getString(StringId.INPUT_DESC_CBZ) == null) {
431 trans.deleteFile(configDir);
432 }
433
434 Boolean noutf = checkEnv("NOUTF");
435 if (noutf != null && noutf) {
436 trans.setUnicode(false);
437 transGui.setUnicode(false);
438 }
439
440 Bundles.setDirectory(configDir);
441 }
442
443 /**
444 * Create the default library as specified by the config.
445 *
446 * @param remoteDir
447 * the base remote directory if needed
448 *
449 * @return the default {@link BasicLibrary}
450 */
451 private static BasicLibrary createDefaultLibrary(File remoteDir) {
452 BasicLibrary lib = null;
453
454 boolean useRemote = config.getBoolean(Config.REMOTE_LIBRARY_ENABLED,
455 false);
456
457 if (useRemote) {
458 String host = null;
459 int port = -1;
460 try {
461 host = config.getString(Config.REMOTE_LIBRARY_HOST);
462 port = config.getInteger(Config.REMOTE_LIBRARY_PORT, -1);
463 String key = config.getString(Config.REMOTE_LIBRARY_KEY);
464
465 tracer.trace("Selecting remote library " + host + ":" + port);
466 lib = new RemoteLibrary(key, host, port);
467 lib = new CacheLibrary(getRemoteDir(remoteDir, host), lib);
468 } catch (Exception e) {
469 tracer.error(new IOException(
470 "Cannot create remote library for: " + host + ":"
471 + port, e));
472 }
473 } else {
474 String libDir = System.getenv("BOOKS_DIR");
475 if (libDir == null || libDir.isEmpty()) {
476 libDir = config.getString(Config.LIBRARY_DIR, "$HOME/Books");
477 if (!getFile(libDir).isAbsolute()) {
478 libDir = new File(configDir, libDir).getPath();
479 }
480 }
481 try {
482 lib = new LocalLibrary(getFile(libDir));
483 } catch (Exception e) {
484 tracer.error(new IOException(
485 "Cannot create library for directory: "
486 + getFile(libDir), e));
487 }
488 }
489
490 return lib;
491 }
492
493 /**
494 * Return a path, but support the special $HOME variable.
495 *
496 * @return the path
497 */
498 private static File getFile(Config id, File def) {
499 String path = config.getString(id, def.getPath());
500 return getFile(path);
501 }
502
503 /**
504 * Return a path, but support the special $HOME variable.
505 *
506 * @return the path
507 */
508 private static File getFile(UiConfig id, File def) {
509 String path = uiconfig.getString(id, def.getPath());
510 return getFile(path);
511 }
512
513 /**
514 * Return a path, but support the special $HOME variable.
515 *
516 * @return the path
517 */
518 private static File getFile(String path) {
519 File file = null;
520 if (path != null && !path.isEmpty()) {
521 path = path.replace('/', File.separatorChar);
522 if (path.contains("$HOME")) {
523 path = path.replace("$HOME", getHome());
524 }
525
526 file = new File(path);
527 }
528
529 return file;
530 }
531
532 /**
533 * Return the home directory from the environment (FANFIX_DIR) or the system
534 * properties.
535 * <p>
536 * The environment variable is tested first. Then, the custom property
537 * "fanfix.home" is tried, followed by the usual "user.home" then
538 * "java.io.tmp" if nothing else is found.
539 *
540 * @return the home
541 */
542 private static String getHome() {
543 String home = System.getenv("FANFIX_DIR");
544 if (home != null && new File(home).isFile()) {
545 home = null;
546 }
547
548 if (home == null || home.trim().isEmpty()) {
549 home = System.getProperty("fanfix.home");
550 if (home != null && new File(home).isFile()) {
551 home = null;
552 }
553 }
554
555 if (home == null || home.trim().isEmpty()) {
556 home = System.getProperty("user.home");
557 if (!new File(home).isDirectory()) {
558 home = null;
559 }
560 }
561
562 if (home == null || home.trim().isEmpty()) {
563 home = System.getProperty("java.io.tmpdir");
564 if (!new File(home).isDirectory()) {
565 home = null;
566 }
567 }
568
569 if (home == null) {
570 home = "";
571 }
572
573 return home;
574 }
575
576 /**
577 * The language to use for the application (NULL = default system language).
578 *
579 * @return the language
580 */
581 private static String getLang() {
582 String lang = config.getString(Config.LANG);
583
584 if (lang == null || lang.isEmpty()) {
585 if (System.getenv("LANG") != null
586 && !System.getenv("LANG").isEmpty()) {
587 lang = System.getenv("LANG");
588 }
589 }
590
591 if (lang != null && lang.isEmpty()) {
592 lang = null;
593 }
594
595 return lang;
596 }
597
598 /**
599 * Check that the given environment variable is "enabled".
600 *
601 * @param key
602 * the variable to check
603 *
604 * @return TRUE if it is
605 */
606 private static Boolean checkEnv(String key) {
607 String value = System.getenv(key);
608 if (value != null) {
609 value = value.trim().toLowerCase();
610 if ("yes".equals(value) || "true".equals(value)
611 || "on".equals(value) || "1".equals(value)
612 || "y".equals(value)) {
613 return true;
614 }
615
616 return false;
617 }
618
619 return null;
620 }
621}