1 package be
.nikiroo
.fanfix
;
4 import java
.io
.IOException
;
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
;
27 * Global state for the program (services and singletons).
31 public class Instance
{
32 static private Instance instance
;
33 static private Object instancelock
= new Object();
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
;
49 * Initialise the instance -- if already initialised, nothing will happen.
51 * Before calling this method, you may call
52 * {@link Bundles#setDirectory(String)} if wanted.
54 * Note that this method will honour some environment variables, the 3 most
55 * important ones probably being:
57 * <li><tt>DEBUG</tt>: will enable DEBUG output if set to 1 (or Y or TRUE or
58 * ON, case insensitive)</li>
59 * <li><tt>CONFIG_DIR</tt>: will use this directory as configuration
60 * directory (supports $HOME notation, defaults to $HOME/.fanfix</li>
61 * <li><tt>BOOKS_DIR</tt>: will use this directory as library directory
62 * (supports $HOME notation, defaults to $HOME/Books</li>
65 static public void init() {
70 * Initialise the instance -- if already initialised, nothing will happen unless
71 * you pass TRUE to <tt>force</tt>.
73 * Before calling this method, you may call {@link Bundles#setDirectory(String)}
76 * Note: forcing the initialisation can be dangerous, so make sure to only make
77 * it under controlled circumstances -- for instance, at the start of the
78 * program, you could call {@link Instance#init()}, change some settings because
79 * you want to force those settings (it will also forbid users to change them!)
80 * and then call {@link Instance#init(boolean)} with <tt>force</tt> set to TRUE.
82 * @param force force the initialisation even if already initialised
84 static public void init(boolean force
) {
85 synchronized (instancelock
) {
86 if (instance
== null || force
) {
87 instance
= new Instance();
94 * Force-initialise the {@link Instance} to a known value.
96 * Usually for DEBUG/Test purposes.
98 * @param instance the actual Instance to use
100 static public void init(Instance instance
) {
101 Instance
.instance
= instance
;
105 * The (mostly unique) instance of this {@link Instance}.
107 * @return the (mostly unique) instance
109 public static Instance
getInstance() {
114 * Actually initialise the instance.
116 * Before calling this method, you may call {@link Bundles#setDirectory(String)}
119 protected Instance() {
120 // Before we can configure it:
121 Boolean debug
= checkEnv("DEBUG");
122 boolean trace
= debug
!= null && debug
;
123 tracer
= new TraceHandler(true, trace
, trace
);
126 configDir
= getConfigDir();
127 if (!new File(configDir
).exists()) {
128 new File(configDir
).mkdirs();
131 // Most of the rest is dependent upon this:
132 createConfigs(configDir
, false);
135 Proxy
.use(config
.getString(Config
.NETWORK_PROXY
));
139 debug
= config
.getBoolean(Config
.DEBUG_ERR
, false);
140 trace
= config
.getBoolean(Config
.DEBUG_TRACE
, false);
143 tracer
= new TraceHandler(true, debug
, trace
);
146 remoteDir
= new File(configDir
, "remote");
147 lib
= createDefaultLibrary(remoteDir
);
149 // create cache and TMP
150 File tmp
= getFile(Config
.CACHE_DIR
, configDir
, "tmp");
151 Image
.setTemporaryFilesRoot(new File(tmp
.getParent(), "tmp.images"));
153 String ua
= config
.getString(Config
.NETWORK_USER_AGENT
, "");
155 int hours
= config
.getInteger(Config
.CACHE_MAX_TIME_CHANGING
, 0);
156 int hoursLarge
= config
.getInteger(Config
.CACHE_MAX_TIME_STABLE
, 0);
157 cache
= new DataLoader(tmp
, ua
, hours
, hoursLarge
);
158 } catch (IOException e
) {
159 tracer
.error(new IOException("Cannot create cache (will continue without cache)", e
));
160 cache
= new DataLoader(ua
);
163 cache
.setTraceHandler(tracer
);
165 // readerTmp / coverDir
166 readerTmp
= getFile(UiConfig
.CACHE_DIR_LOCAL_READER
, configDir
, "tmp-reader");
167 coverDir
= getFile(Config
.DEFAULT_COVERS_DIR
, configDir
, "covers");
171 tempFiles
= new TempFiles("fanfix");
172 } catch (IOException e
) {
173 tracer
.error(new IOException("Cannot create temporary directory", e
));
178 * The traces handler for this {@link Cache}.
182 * @return the traces handler (never NULL)
184 public TraceHandler
getTraceHandler() {
189 * The traces handler for this {@link Cache}.
191 * @param tracer the new traces handler or NULL
193 public void setTraceHandler(TraceHandler tracer
) {
194 if (tracer
== null) {
195 tracer
= new TraceHandler(false, false, false);
198 this.tracer
= tracer
;
199 cache
.setTraceHandler(tracer
);
203 * Get the (unique) configuration service for the program.
205 * @return the configuration service
207 public ConfigBundle
getConfig() {
212 * Get the (unique) UI configuration service for the program.
214 * @return the configuration service
216 public UiConfigBundle
getUiConfig() {
221 * Reset the configuration.
223 * @param resetTrans also reset the translation files
225 public void resetConfig(boolean resetTrans
) {
226 String dir
= Bundles
.getDirectory();
227 Bundles
.setDirectory(null);
230 ConfigBundle config
= new ConfigBundle();
231 config
.updateFile(configDir
);
232 } catch (IOException e
) {
236 UiConfigBundle uiconfig
= new UiConfigBundle();
237 uiconfig
.updateFile(configDir
);
238 } catch (IOException e
) {
244 StringIdBundle trans
= new StringIdBundle(null);
245 trans
.updateFile(configDir
);
246 } catch (IOException e
) {
251 Bundles
.setDirectory(dir
);
256 * Get the (unique) {@link DataLoader} for the program.
258 * @return the {@link DataLoader}
260 public DataLoader
getCache() {
265 * Get the (unique) {link StringIdBundle} for the program.
267 * This is used for the translations of the core parts of Fanfix.
269 * @return the {link StringIdBundle}
271 public StringIdBundle
getTrans() {
276 * Get the (unique) {link StringIdGuiBundle} for the program.
278 * This is used for the translations of the GUI parts of Fanfix.
280 * @return the {link StringIdGuiBundle}
282 public StringIdGuiBundle
getTransGui() {
287 * Get the (unique) {@link LocalLibrary} for the program.
289 * @return the {@link LocalLibrary}
291 public BasicLibrary
getLibrary() {
293 throw new NullPointerException("We don't have a library to return");
300 * Return the directory where to look for default cover pages.
302 * @return the default covers directory
304 public File
getCoverDir() {
309 * Return the directory where to store temporary files for the local reader.
311 * @return the directory
313 public File
getReaderDir() {
318 * Return the directory where to store temporary files for the remote
319 * {@link LocalLibrary}.
321 * @param host the remote for this host
323 * @return the directory
325 public File
getRemoteDir(String host
) {
326 return getRemoteDir(remoteDir
, host
);
330 * Return the directory where to store temporary files for the remote
331 * {@link LocalLibrary}.
333 * @param remoteDir the base remote directory
334 * @param host the remote for this host
336 * @return the directory
338 private File
getRemoteDir(File remoteDir
, String host
) {
342 return new File(remoteDir
, host
);
349 * Check if we need to check that a new version of Fanfix is available.
351 * @return TRUE if we need to
353 public boolean isVersionCheckNeeded() {
355 long wait
= config
.getInteger(Config
.NETWORK_UPDATE_INTERVAL
, 0) * 24 * 60 * 60 * 1000;
357 String lastUpString
= IOUtils
.readSmallFile(new File(configDir
, "LAST_UPDATE"));
358 long delay
= new Date().getTime() - Long
.parseLong(lastUpString
);
365 } catch (Exception e
) {
366 // No file or bad file:
374 * Notify that we checked for a new version of Fanfix.
376 public void setVersionChecked() {
378 IOUtils
.writeSmallFile(new File(configDir
), "LAST_UPDATE", Long
.toString(new Date().getTime()));
379 } catch (IOException e
) {
385 * The facility to use temporary files in this program.
387 * <b>MUST</b> be closed at end of program.
389 * @return the facility
391 public TempFiles
getTempFiles() {
396 * The configuration directory (will check, in order of preference, the system
397 * properties, the environment and then defaults to
398 * {@link Instance#getHome()}/.fanfix).
400 * @return the config directory
402 private String
getConfigDir() {
403 String configDir
= System
.getProperty("CONFIG_DIR");
405 if (configDir
== null) {
406 configDir
= System
.getenv("CONFIG_DIR");
409 if (configDir
== null) {
410 configDir
= new File(getHome(), ".fanfix").getPath();
417 * Create the config variables ({@link Instance#config},
418 * {@link Instance#uiconfig}, {@link Instance#trans} and
419 * {@link Instance#transGui}).
421 * @param configDir the directory where to find the configuration files
422 * @param refresh TRUE to reset the configuration files from the default
425 private void createConfigs(String configDir
, boolean refresh
) {
427 Bundles
.setDirectory(configDir
);
431 config
= new ConfigBundle();
432 config
.updateFile(configDir
);
433 } catch (IOException e
) {
438 uiconfig
= new UiConfigBundle();
439 uiconfig
.updateFile(configDir
);
440 } catch (IOException e
) {
444 // No updateFile for this one! (we do not want the user to have custom
445 // translations that won't accept updates from newer versions)
446 trans
= new StringIdBundle(getLang());
447 transGui
= new StringIdGuiBundle(getLang());
449 // Fix an old bug (we used to store custom translation files by
451 if (trans
.getString(StringId
.INPUT_DESC_CBZ
) == null) {
452 trans
.deleteFile(configDir
);
455 Boolean noutf
= checkEnv("NOUTF");
456 if (noutf
!= null && noutf
) {
457 trans
.setUnicode(false);
458 transGui
.setUnicode(false);
461 Bundles
.setDirectory(configDir
);
465 * Create the default library as specified by the config.
467 * @param remoteDir the base remote directory if needed
469 * @return the default {@link BasicLibrary}
471 private BasicLibrary
createDefaultLibrary(File remoteDir
) {
472 BasicLibrary lib
= null;
474 boolean useRemote
= config
.getBoolean(Config
.REMOTE_LIBRARY_ENABLED
, false);
479 host
= config
.getString(Config
.REMOTE_LIBRARY_HOST
);
480 port
= config
.getInteger(Config
.REMOTE_LIBRARY_PORT
, -1);
481 String key
= config
.getString(Config
.REMOTE_LIBRARY_KEY
);
483 tracer
.trace("Selecting remote library " + host
+ ":" + port
);
484 lib
= new RemoteLibrary(key
, host
, port
);
485 lib
= new CacheLibrary(getRemoteDir(remoteDir
, host
), lib
, uiconfig
);
486 } catch (Exception e
) {
487 tracer
.error(new IOException("Cannot create remote library for: " + host
+ ":" + port
, e
));
490 String libDir
= System
.getenv("BOOKS_DIR");
491 if (libDir
== null || libDir
.isEmpty()) {
492 libDir
= getFile(Config
.LIBRARY_DIR
, configDir
, "$HOME/Books").getPath();
495 lib
= new LocalLibrary(new File(libDir
), config
);
496 } catch (Exception e
) {
497 tracer
.error(new IOException("Cannot create library for directory: " + libDir
, e
));
505 * Return a path, but support the special $HOME variable.
507 * @param id the key for the path, which may contain "$HOME"
508 * @param configDir the directory to use as base if not absolute
509 * @param def the default value if none (will be configDir-rooted if needed)
510 * @return the path, with expanded "$HOME" if needed
512 protected File
getFile(Config id
, String configDir
, String def
) {
513 String path
= config
.getString(id
, def
);
514 return getFile(path
, configDir
);
518 * Return a path, but support the special $HOME variable.
520 * @param id the key for the path, which may contain "$HOME"
521 * @param configDir the directory to use as base if not absolute
522 * @param def the default value if none (will be configDir-rooted if needed)
523 * @return the path, with expanded "$HOME" if needed
525 protected File
getFile(UiConfig id
, String configDir
, String def
) {
526 String path
= uiconfig
.getString(id
, def
);
527 return getFile(path
, configDir
);
531 * Return a path, but support the special $HOME variable.
533 * @param path the path, which may contain "$HOME"
534 * @param configDir the directory to use as base if not absolute
535 * @return the path, with expanded "$HOME" if needed
537 protected File
getFile(String path
, String configDir
) {
539 if (path
!= null && !path
.isEmpty()) {
540 path
= path
.replace('/', File
.separatorChar
);
541 if (path
.contains("$HOME")) {
542 path
= path
.replace("$HOME", getHome());
543 } else if (!path
.startsWith("/")) {
544 path
= new File(configDir
, path
).getPath();
547 file
= new File(path
);
554 * Return the home directory from the environment (FANFIX_DIR) or the system
557 * The environment variable is tested first. Then, the custom property
558 * "fanfix.home" is tried, followed by the usual "user.home" then "java.io.tmp"
559 * if nothing else is found.
563 protected String
getHome() {
564 String home
= System
.getenv("FANFIX_DIR");
565 if (home
!= null && new File(home
).isFile()) {
569 if (home
== null || home
.trim().isEmpty()) {
570 home
= System
.getProperty("fanfix.home");
571 if (home
!= null && new File(home
).isFile()) {
576 if (home
== null || home
.trim().isEmpty()) {
577 home
= System
.getProperty("user.home");
578 if (!new File(home
).isDirectory()) {
583 if (home
== null || home
.trim().isEmpty()) {
584 home
= System
.getProperty("java.io.tmpdir");
585 if (!new File(home
).isDirectory()) {
598 * The language to use for the application (NULL = default system language).
600 * @return the language
602 protected String
getLang() {
603 String lang
= config
.getString(Config
.LANG
);
605 if (lang
== null || lang
.isEmpty()) {
606 if (System
.getenv("LANG") != null && !System
.getenv("LANG").isEmpty()) {
607 lang
= System
.getenv("LANG");
611 if (lang
!= null && lang
.isEmpty()) {
619 * Check that the given environment variable is "enabled".
621 * @param key the variable to check
623 * @return TRUE if it is
625 protected Boolean
checkEnv(String key
) {
626 String value
= System
.getenv(key
);
628 value
= value
.trim().toLowerCase();
629 if ("yes".equals(value
) || "true".equals(value
) || "on".equals(value
) || "1".equals(value
)
630 || "y".equals(value
)) {