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