Instance.init()
[nikiroo-utils.git] / src / be / nikiroo / fanfix / Instance.java
index 14977822bec55ca032a26e266ac35445ca96c570..84a583e6635d8ec966c7fb8cf1ef334ecaa0bb9a 100644 (file)
@@ -6,13 +6,21 @@ import java.util.Date;
 
 import be.nikiroo.fanfix.bundles.Config;
 import be.nikiroo.fanfix.bundles.ConfigBundle;
+import be.nikiroo.fanfix.bundles.StringId;
 import be.nikiroo.fanfix.bundles.StringIdBundle;
+import be.nikiroo.fanfix.bundles.StringIdGuiBundle;
 import be.nikiroo.fanfix.bundles.UiConfig;
 import be.nikiroo.fanfix.bundles.UiConfigBundle;
 import be.nikiroo.fanfix.library.BasicLibrary;
+import be.nikiroo.fanfix.library.CacheLibrary;
 import be.nikiroo.fanfix.library.LocalLibrary;
-import be.nikiroo.fanfix.output.BasicOutput.OutputType;
+import be.nikiroo.fanfix.library.RemoteLibrary;
+import be.nikiroo.utils.Cache;
 import be.nikiroo.utils.IOUtils;
+import be.nikiroo.utils.Image;
+import be.nikiroo.utils.Proxy;
+import be.nikiroo.utils.TempFiles;
+import be.nikiroo.utils.TraceHandler;
 import be.nikiroo.utils.resources.Bundles;
 
 /**
@@ -21,152 +29,131 @@ import be.nikiroo.utils.resources.Bundles;
  * @author niki
  */
 public class Instance {
-       /**
-        * A handler when a recoverable exception was caught by the program.
-        * 
-        * @author niki
-        */
-       public interface SyserrHandler {
-               /**
-                * An exception happened, log it.
-                * 
-                * @param e
-                *            the exception
-                * @param showDetails
-                *            show more details (usually equivalent to the value of
-                *            DEBUG)
-                */
-               public void notify(Exception e, boolean showDetails);
-       }
-
-       /**
-        * A handler when a trace message is sent.
-        * 
-        * @author niki
-        */
-       public interface TraceHandler {
-               /**
-                * A trace happened, show it.
-                * <p>
-                * Will only be called if TRACE is true.
-                * 
-                * @param message
-                *            the trace message
-                */
-               public void trace(String message);
-       }
-
        private static ConfigBundle config;
        private static UiConfigBundle uiconfig;
        private static StringIdBundle trans;
        private static DataLoader cache;
-       private static LocalLibrary lib;
-       private static boolean debug;
-       private static boolean trace;
+       private static StringIdGuiBundle transGui;
+       private static BasicLibrary lib;
        private static File coverDir;
        private static File readerTmp;
        private static File remoteDir;
        private static String configDir;
+       private static TraceHandler tracer;
+       private static TempFiles tempFiles;
 
-       private static SyserrHandler syserrHandler;
-
-       private static TraceHandler traceHandler;
+       private static boolean init;
 
-       static {
-               // Most of the rest is dependent upon this:
-               config = new ConfigBundle();
-
-               configDir = System.getProperty("CONFIG_DIR");
-               if (configDir == null) {
-                       configDir = System.getenv("CONFIG_DIR");
+       /**
+        * Initialise the instance -- if already initialised, nothing will happen.
+        * <p>
+        * Before calling this method, you may call {@link Bundles#getDirectory()}
+        * if wanted.
+        */
+       static public void init() {
+               if (init) {
+                       return;
                }
 
-               if (configDir == null) {
-                       configDir = new File(System.getProperty("user.home"), ".fanfix")
-                                       .getPath();
-               }
+               init = true;
+
+               // Before we can configure it:
+               Boolean debug = checkEnv("DEBUG");
+               boolean trace = debug != null && debug;
+               tracer = new TraceHandler(true, trace, trace);
 
+               // config dir:
+               configDir = getConfigDir();
                if (!new File(configDir).exists()) {
                        new File(configDir).mkdirs();
-               } else {
-                       Bundles.setDirectory(configDir);
                }
 
-               try {
-                       config = new ConfigBundle();
-                       config.updateFile(configDir);
-               } catch (IOException e) {
-                       syserr(e);
-               }
-               try {
-                       uiconfig = new UiConfigBundle();
-                       uiconfig.updateFile(configDir);
-               } catch (IOException e) {
-                       syserr(e);
-               }
-               try {
-                       trans = new StringIdBundle(getLang());
-                       trans.updateFile(configDir);
-               } catch (IOException e) {
-                       syserr(e);
-               }
+               // Most of the rest is dependent upon this:
+               createConfigs(configDir, false);
 
-               Bundles.setDirectory(configDir);
+               // Proxy support
+               Proxy.use(Instance.getConfig().getString(Config.USE_PROXY));
 
-               uiconfig = new UiConfigBundle();
-               trans = new StringIdBundle(getLang());
-               try {
-                       lib = new LocalLibrary(getFile(Config.LIBRARY_DIR),
-                                       OutputType.INFO_TEXT, OutputType.CBZ);
-               } catch (Exception e) {
-                       syserr(new IOException("Cannot create library for directory: "
-                                       + getFile(Config.LIBRARY_DIR), e));
+               // update tracer:
+               if (debug == null) {
+                       debug = Instance.getConfig().getBoolean(Config.DEBUG_ERR, false);
+                       trace = Instance.getConfig().getBoolean(Config.DEBUG_TRACE, false);
                }
 
-               debug = Instance.getConfig().getBoolean(Config.DEBUG_ERR, false);
-               trace = Instance.getConfig().getBoolean(Config.DEBUG_TRACE, false);
-               coverDir = getFile(Config.DEFAULT_COVERS_DIR);
-               File tmp = getFile(Config.CACHE_DIR);
-               readerTmp = getFile(UiConfig.CACHE_DIR_LOCAL_READER);
-               remoteDir = new File(getFile(Config.LIBRARY_DIR), "remote");
-
-               if (checkEnv("NOUTF")) {
-                       trans.setUnicode(false);
-               }
+               tracer = new TraceHandler(true, debug, trace);
 
-               if (checkEnv("DEBUG")) {
-                       debug = true;
-               }
+               // default Library
+               remoteDir = new File(configDir, "remote");
+               lib = createDefaultLibrary(remoteDir);
 
-               // Could have used: System.getProperty("java.io.tmpdir")
+               // create cache and TMP
+               Image.setTemporaryFilesRoot(new File(configDir, "tmp.images"));
+               File tmp = getFile(Config.CACHE_DIR);
                if (tmp == null) {
+                       // Could have used: System.getProperty("java.io.tmpdir")
                        tmp = new File(configDir, "tmp");
                }
+               String ua = config.getString(Config.USER_AGENT);
+               try {
+                       int hours = config.getInteger(Config.CACHE_MAX_TIME_CHANGING, -1);
+                       int hoursLarge = config
+                                       .getInteger(Config.CACHE_MAX_TIME_STABLE, -1);
+                       cache = new DataLoader(tmp, ua, hours, hoursLarge);
+               } catch (IOException e) {
+                       tracer.error(new IOException(
+                                       "Cannot create cache (will continue without cache)", e));
+                       cache = new DataLoader(ua);
+               }
+
+               cache.setTraceHandler(tracer);
+
+               // readerTmp / coverDir
+               readerTmp = getFile(UiConfig.CACHE_DIR_LOCAL_READER);
                if (readerTmp == null) {
                        readerTmp = new File(configDir, "tmp-reader");
                }
-               //
 
+               coverDir = getFile(Config.DEFAULT_COVERS_DIR);
                if (coverDir != null && !coverDir.exists()) {
-                       syserr(new IOException(
+                       tracer.error(new IOException(
                                        "The 'default covers' directory does not exists: "
                                                        + coverDir));
                        coverDir = null;
                }
 
                try {
-                       String ua = config.getString(Config.USER_AGENT);
-                       int hours = config.getInteger(Config.CACHE_MAX_TIME_CHANGING, -1);
-                       int hoursLarge = config
-                                       .getInteger(Config.CACHE_MAX_TIME_STABLE, -1);
-
-                       cache = new DataLoader(tmp, ua, hours, hoursLarge);
+                       tempFiles = new TempFiles("fanfix");
                } catch (IOException e) {
-                       syserr(new IOException(
-                                       "Cannot create cache (will continue without cache)", e));
+                       tracer.error(new IOException("Cannot create temporary directory", e));
                }
        }
 
+       /**
+        * The traces handler for this {@link Cache}.
+        * <p>
+        * It is never NULL.
+        * 
+        * @return the traces handler (never NULL)
+        */
+       public static TraceHandler getTraceHandler() {
+               return tracer;
+       }
+
+       /**
+        * The traces handler for this {@link Cache}.
+        * 
+        * @param tracer
+        *            the new traces handler or NULL
+        */
+       public static void setTraceHandler(TraceHandler tracer) {
+               if (tracer == null) {
+                       tracer = new TraceHandler(false, false, false);
+               }
+
+               Instance.tracer = tracer;
+               cache.setTraceHandler(tracer);
+       }
+
        /**
         * Get the (unique) configuration service for the program.
         * 
@@ -185,6 +172,42 @@ public class Instance {
                return uiconfig;
        }
 
+       /**
+        * Reset the configuration.
+        * 
+        * @param resetTrans
+        *            also reset the translation files
+        */
+       public static void resetConfig(boolean resetTrans) {
+               String dir = Bundles.getDirectory();
+               Bundles.setDirectory(null);
+               try {
+                       try {
+                               ConfigBundle config = new ConfigBundle();
+                               config.updateFile(configDir);
+                       } catch (IOException e) {
+                               tracer.error(e);
+                       }
+                       try {
+                               UiConfigBundle uiconfig = new UiConfigBundle();
+                               uiconfig.updateFile(configDir);
+                       } catch (IOException e) {
+                               tracer.error(e);
+                       }
+
+                       if (resetTrans) {
+                               try {
+                                       StringIdBundle trans = new StringIdBundle(null);
+                                       trans.updateFile(configDir);
+                               } catch (IOException e) {
+                                       tracer.error(e);
+                               }
+                       }
+               } finally {
+                       Bundles.setDirectory(dir);
+               }
+       }
+
        /**
         * Get the (unique) {@link DataLoader} for the program.
         * 
@@ -196,6 +219,8 @@ public class Instance {
 
        /**
         * Get the (unique) {link StringIdBundle} for the program.
+        * <p>
+        * This is used for the translations of the core parts of Fanfix.
         * 
         * @return the {link StringIdBundle}
         */
@@ -203,12 +228,27 @@ public class Instance {
                return trans;
        }
 
+       /**
+        * Get the (unique) {link StringIdGuiBundle} for the program.
+        * <p>
+        * This is used for the translations of the GUI parts of Fanfix.
+        * 
+        * @return the {link StringIdGuiBundle}
+        */
+       public static StringIdGuiBundle getTransGui() {
+               return transGui;
+       }
+
        /**
         * Get the (unique) {@link LocalLibrary} for the program.
         * 
         * @return the {@link LocalLibrary}
         */
        public static BasicLibrary getLibrary() {
+               if (lib == null) {
+                       throw new NullPointerException("We don't have a library to return");
+               }
+
                return lib;
        }
 
@@ -240,6 +280,21 @@ public class Instance {
         * @return the directory
         */
        public static File getRemoteDir(String host) {
+               return getRemoteDir(remoteDir, host);
+       }
+
+       /**
+        * Return the directory where to store temporary files for the remote
+        * {@link LocalLibrary}.
+        * 
+        * @param remoteDir
+        *            the base remote directory
+        * @param host
+        *            the remote for this host
+        * 
+        * @return the directory
+        */
+       private static File getRemoteDir(File remoteDir, String host) {
                remoteDir.mkdirs();
 
                if (host != null) {
@@ -285,62 +340,152 @@ public class Instance {
                        IOUtils.writeSmallFile(new File(configDir), "LAST_UPDATE",
                                        Long.toString(new Date().getTime()));
                } catch (IOException e) {
-                       syserr(e);
+                       tracer.error(e);
                }
        }
 
        /**
-        * Replace the global syserr handler.
+        * The facility to use temporary files in this program.
+        * <p>
+        * <b>MUST</b> be closed at end of program.
         * 
-        * @param syserrHandler
-        *            the new syserr handler
+        * @return the facility
         */
-       public static void setSyserrHandler(SyserrHandler syserrHandler) {
-               Instance.syserrHandler = syserrHandler;
+       public static TempFiles getTempFiles() {
+               return tempFiles;
        }
 
        /**
-        * Replace the global trace handler.
+        * The configuration directory (will check, in order of preference,
+        * {@link Bundles#getDirectory()}, the system properties, the environment
+        * and then defaults to $HOME/.fanfix).
         * 
-        * @param traceHandler
-        *            the new trace handler
+        * @return the config directory
         */
-       public static void setTraceHandler(TraceHandler traceHandler) {
-               Instance.traceHandler = traceHandler;
+       private static String getConfigDir() {
+               String configDir = Bundles.getDirectory();
+
+               if (configDir == null) {
+                       configDir = System.getProperty("CONFIG_DIR");
+               }
+
+               if (configDir == null) {
+                       configDir = System.getenv("CONFIG_DIR");
+               }
+
+               if (configDir == null) {
+                       configDir = new File(getHome(), ".fanfix").getPath();
+               }
+
+               return configDir;
        }
 
        /**
-        * Report an error to the user
+        * Create the config variables ({@link Instance#config},
+        * {@link Instance#uiconfig}, {@link Instance#trans} and
+        * {@link Instance#transGui}).
         * 
-        * @param e
-        *            the {@link Exception} to report
+        * @param configDir
+        *            the directory where to find the configuration files
+        * @param refresh
+        *            TRUE to reset the configuration files from the default
+        *            included ones
         */
-       public static void syserr(Exception e) {
-               if (syserrHandler != null) {
-                       syserrHandler.notify(e, debug);
-               } else {
-                       if (debug) {
-                               e.printStackTrace();
-                       } else {
-                               System.err.println(e.getMessage());
-                       }
+       private static void createConfigs(String configDir, boolean refresh) {
+               if (!refresh) {
+                       Bundles.setDirectory(configDir);
+               }
+
+               try {
+                       config = new ConfigBundle();
+                       config.updateFile(configDir);
+               } catch (IOException e) {
+                       tracer.error(e);
                }
+
+               try {
+                       uiconfig = new UiConfigBundle();
+                       uiconfig.updateFile(configDir);
+               } catch (IOException e) {
+                       tracer.error(e);
+               }
+
+               // No updateFile for this one! (we do not want the user to have custom
+               // translations that won't accept updates from newer versions)
+               trans = new StringIdBundle(getLang());
+               transGui = new StringIdGuiBundle(getLang());
+
+               // Fix an old bug (we used to store custom translation files by
+               // default):
+               if (trans.getString(StringId.INPUT_DESC_CBZ) == null) {
+                       trans.deleteFile(configDir);
+               }
+
+               Boolean noutf = checkEnv("NOUTF");
+               if (noutf != null && noutf) {
+                       trans.setUnicode(false);
+                       transGui.setUnicode(false);
+               }
+
+               Bundles.setDirectory(configDir);
        }
 
        /**
-        * Notify of a debug message.
+        * Create the default library as specified by the config.
+        * 
+        * @param remoteDir
+        *            the base remote directory if needed
         * 
-        * @param message
-        *            the message
+        * @return the default {@link BasicLibrary}
         */
-       public static void trace(String message) {
-               if (trace) {
-                       if (traceHandler != null) {
-                               traceHandler.trace(message);
-                       } else {
-                               System.out.println(message);
+       private static BasicLibrary createDefaultLibrary(File remoteDir) {
+               BasicLibrary lib = null;
+
+               String remoteLib = config.getString(Config.DEFAULT_LIBRARY);
+               if (remoteLib == null || remoteLib.trim().isEmpty()) {
+                       String libDir = System.getProperty("fanfix.libdir");
+                       if (libDir == null || libDir.isEmpty()) {
+                               libDir = config.getString(Config.LIBRARY_DIR);
+                       }
+                       try {
+                               lib = new LocalLibrary(getFile(libDir));
+                       } catch (Exception e) {
+                               tracer.error(new IOException(
+                                               "Cannot create library for directory: "
+                                                               + getFile(libDir), e));
+                       }
+               } else {
+                       Exception ex = null;
+                       int pos = remoteLib.lastIndexOf(":");
+                       if (pos >= 0) {
+                               String port = remoteLib.substring(pos + 1).trim();
+                               remoteLib = remoteLib.substring(0, pos);
+                               pos = remoteLib.lastIndexOf(":");
+                               if (pos >= 0) {
+                                       String host = remoteLib.substring(pos + 1).trim();
+                                       String key = remoteLib.substring(0, pos).trim();
+
+                                       try {
+                                               tracer.trace("Selecting remote library " + host + ":"
+                                                               + port);
+                                               lib = new RemoteLibrary(key, host,
+                                                               Integer.parseInt(port));
+                                               lib = new CacheLibrary(getRemoteDir(remoteDir, host),
+                                                               lib);
+
+                                       } catch (Exception e) {
+                                               ex = e;
+                                       }
+                               }
+                       }
+
+                       if (lib == null) {
+                               tracer.error(new IOException(
+                                               "Cannot create remote library for: " + remoteLib, ex));
                        }
                }
+
+               return lib;
        }
 
        /**
@@ -371,8 +516,7 @@ public class Instance {
                if (path != null && !path.isEmpty()) {
                        path = path.replace('/', File.separatorChar);
                        if (path.contains("$HOME")) {
-                               path = path.replace("$HOME",
-                                               "" + System.getProperty("user.home"));
+                               path = path.replace("$HOME", getHome());
                        }
 
                        file = new File(path);
@@ -381,6 +525,38 @@ public class Instance {
                return file;
        }
 
+       /**
+        * Return the home directory from the system properties.
+        * 
+        * @return the home
+        */
+       private static String getHome() {
+               String home = System.getProperty("fanfix.home");
+               if (home != null && new File(home).isFile()) {
+                       home = null;
+               }
+
+               if (home == null || home.trim().isEmpty()) {
+                       home = System.getProperty("user.home");
+                       if (!new File(home).isDirectory()) {
+                               home = null;
+                       }
+               }
+
+               if (home == null || home.trim().isEmpty()) {
+                       home = System.getProperty("java.io.tmpdir");
+                       if (!new File(home).isDirectory()) {
+                               home = null;
+                       }
+               }
+
+               if (home == null) {
+                       home = "";
+               }
+
+               return home;
+       }
+
        /**
         * The language to use for the application (NULL = default system language).
         * 
@@ -389,8 +565,11 @@ public class Instance {
        private static String getLang() {
                String lang = config.getString(Config.LANG);
 
-               if (System.getenv("LANG") != null && !System.getenv("LANG").isEmpty()) {
-                       lang = System.getenv("LANG");
+               if (lang == null || lang.isEmpty()) {
+                       if (System.getenv("LANG") != null
+                                       && !System.getenv("LANG").isEmpty()) {
+                               lang = System.getenv("LANG");
+                       }
                }
 
                if (lang != null && lang.isEmpty()) {
@@ -408,7 +587,7 @@ public class Instance {
         * 
         * @return TRUE if it is
         */
-       private static boolean checkEnv(String key) {
+       private static Boolean checkEnv(String key) {
                String value = System.getenv(key);
                if (value != null) {
                        value = value.trim().toLowerCase();
@@ -417,8 +596,10 @@ public class Instance {
                                        || "y".equals(value)) {
                                return true;
                        }
+
+                       return false;
                }
 
-               return false;
+               return null;
        }
 }