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