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