File: Main.java

package info (click to toggle)
mediathekview 13.2.1-3
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid
  • size: 6,124 kB
  • sloc: java: 36,697; xml: 184; sh: 178; makefile: 3
file content (414 lines) | stat: -rw-r--r-- 15,610 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
/*
 * MediathekView
 * Copyright (C) 2008 W. Xaver
 * W.Xaver[at]googlemail.com
 * http://zdfmediathk.sourceforge.net/
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package mediathek;

import com.jidesoft.utils.SystemInfo;
import com.jidesoft.utils.ThreadCheckingRepaintManager;
import javafx.application.Platform;
import jiconfont.icons.FontAwesome;
import jiconfont.swing.IconFontSwing;
import mSearch.Config;
import mSearch.tool.Log;
import mSearch.tool.SingleInstance;
import mediathek.config.Daten;
import mediathek.config.Konstanten;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import static mediathek.tool.MVFunctionSys.startMeldungen;

public class Main {
    private static final String JAVAFX_CLASSNAME_APPLICATION_PLATFORM = "javafx.application.Platform";
    private static final String HTTP_PROXY_USER = "http.proxyUser";
    private static final String HTTP_PROXY_PW = "http.proxyPassword";
    private static final String LOG_TEXT_PROXY_AUTHENTICATION_SUCESSFUL = "Proxy Authentication: (%s)";
    private static final String LOG_TEXT_PROXY_AUTHENTICATION_NOT_CONFIGURED = "Proxy Authentication: not configured";
    private static final String LOG_TEXT_PROXY_PASSWORD_NOT_SET = "Proxy Authentication: Password is not set";
    private static final String LOG_TEXT_PROXY_AUTHENTICATION_CANNOT_ACCESS_PROXY_USER_PROXY_PW = "Proxy Authentication: cannot access proxyUser / proxyPassword";
    private static final String MAC_SYSTEM_PROPERTY_APPLE_LAF_USE_SCREEN_MENU_BAR = "apple.laf.useScreenMenuBar";
    private static final String LOG_TEXT_MEDIATHEK_VIEW_IS_ALREADY_RUNNING = "MediathekView wird bereits ausgeführt!";
    private static final String X11_AWT_APP_CLASS_NAME = "awtAppClassName";

    private static final Logger logger = LogManager.getLogger(Main.class);

    /**
     * Ensures that old film lists in .mediathek directory get deleted because they were moved to
     * ~/Library/Caches/MediathekView
     * In portable mode we MUST NOT delete the files.
     */
    private static void cleanupOsxFiles() {
        if (!Config.isPortableMode()) {
            try {
                Path oldFilmList = Paths.get(Daten.getSettingsDirectory_String(), Konstanten.JSON_DATEI_FILME);
                Files.deleteIfExists(oldFilmList);
            } catch (Exception ignored) {
            }
        }
    }

    /**
     * Tests if javafx is in the classpath by loading a well known class.
     */
    private static void checkForJavaFX() {
        final String message = "MediathekView benötigt ein installiertes JavaFX.";

        try {
            Class.forName(JAVAFX_CLASSNAME_APPLICATION_PLATFORM);
        } catch (ClassNotFoundException e) {
            logger.error("JavaFX was not found on system.", e);
            if (GraphicsEnvironment.isHeadless()) {
                System.err.println(message);
            } else {
                //we have a screen
                JOptionPane.showMessageDialog(null,
                        message,
                        "JavaFX nicht gefunden", JOptionPane.ERROR_MESSAGE);
            }
            System.exit(3);
        }
    }

    private static void printBanner() {
        if (!SystemInfo.isMacOSX()) {
            System.out.println();
            System.out.println();
            System.out.println();
            System.out.println();
            System.out.println();
            System.out.println("___  ___         _ _       _   _          _    _   _ _               ");
            System.out.println("|  \\/  |        | (_)     | | | |        | |  | | | (_)              ");
            System.out.println("| .  . | ___  __| |_  __ _| |_| |__   ___| | _| | | |_  _____      __");
            System.out.println("| |\\/| |/ _ \\/ _` | |/ _` | __| '_ \\ / _ \\ |/ / | | | |/ _ \\ \\ /\\ / /");
            System.out.println("| |  | |  __/ (_| | | (_| | |_| | | |  __/   <\\ \\_/ / |  __/\\ V  V / ");
            System.out.println("\\_|  |_/\\___|\\__,_|_|\\__,_|\\__|_| |_|\\___|_|\\_\\\\___/|_|\\___| \\_/\\_/  ");
            System.out.println();
            System.out.println();
        }
    }

    private static void printArguments(final String... aArguments) {
        for (String argument : aArguments) {
            logger.info("Startparameter: {}", argument);
        }
    }

    private static String readPfadFromArguments(final String... aArguments) {
        String pfad = "";
        if (aArguments != null && aArguments.length > 0) {
            for (String arg : aArguments) {
                if (!arg.startsWith("-")) {
                    if (!arg.endsWith(File.separator)) {
                        arg += File.separator;
                    }
                    pfad = arg;
                }
            }
        }

        return pfad;
    }

    private static void setupPortableMode(String... args) {
        printArguments(args);
        final String basePath = readPfadFromArguments(args);
        if (!basePath.isEmpty()) {
            Config.setPortableMode(true);
            logger.info("Portable Mode: true");
        } else
            logger.info("Portable Mode: false");

        //initialize Daten object now for database
        Daten.getInstance(basePath);
    }

    /**
     * @param args the command line arguments
     */
    public static void main(final String... args) {
        printBanner();

        setupPortableMode(args);

        checkMemoryRequirements();
        checkJava8Compatibility();

        IconFontSwing.register(FontAwesome.getIconFont());
        new Main().start(args);
    }

    private static void checkForOfficialOSXAppUse() {
        final String osxOfficialApp = System.getProperty("OSX_OFFICIAL_APP");
        if (osxOfficialApp == null || osxOfficialApp.isEmpty() || osxOfficialApp.equalsIgnoreCase("false")) {
            JOptionPane.showMessageDialog(null,
                    "Bitte nutzen Sie die offizielle macOS Applikation für das beste Nutzererlebnis.",
                    "Anwendungshinweis",
                    JOptionPane.WARNING_MESSAGE);
        }
    }

    private static void checkMemoryRequirements() {
        final long maxMem = Runtime.getRuntime().maxMemory();
        // more than 450MB avail...
        if (maxMem < 450 * 1024 * 1024) {
            if (GraphicsEnvironment.isHeadless()) {
                System.err.println("Die VM hat nicht genügend Arbeitsspeicher zugewiesen.");
                System.err.println("Nutzen Sie den Startparameter -Xmx512M für Minimumspeicher");
            } else {
                JOptionPane.showMessageDialog(null,
                        "MediathekView hat nicht genügend Arbeitsspeicher zugewiesen bekommen.",
                        "Speicherwarnung",
                        JOptionPane.ERROR_MESSAGE);
            }

            System.exit(3);
        }
    }

    private static void checkJava8Compatibility() {
        if (!SystemInfo.isJdk9Above()) {
            logger.error("JVM is not Java 11 or later");
            if (GraphicsEnvironment.isHeadless()) {
                System.err.println("MediathekView ist NUR mit Java 11 oder einer neueren Version kompatibel.");
                System.err.println("Bitte stellen Sie sicher das Sie Java 11 auf Ihrem System nutzen");
            } else {
                //we have a screen
                JOptionPane.showMessageDialog(null,
                        "MediathekView ist NUR mit Java 11 oder einer neueren Version kompatibel.",
                        "Falsche Java-Version", JOptionPane.ERROR_MESSAGE);
            }
            System.exit(3);
        }
    }

    private void start(String... args) {
        StartupMode startupMode = StartupMode.GUI;

        proxyAuthentication();

        if (args != null) {
            startupMode = processArgs(startupMode, args);
        }

        startUI(startupMode, args);
    }

    /*
     * Aufruf:
     * java -jar Mediathek [Pfad zur Konfigdatei, sonst homeverzeichnis] [Schalter]
     *
     * Programmschalter:
     *
     * -M Fenster maximiert starten
     * -A Automodus
     * -noGui ohne GUI starten und die Filmliste laden
     *
     * */

    private void startUI(StartupMode aStartupMode, final String... aArguments) {
        aStartupMode = switchToCLIModeIfNecessary(aStartupMode);
        switch (aStartupMode) {
            case AUTO:
                startAutoMode(aArguments);
                break;

            case FASTAUTO:
                startFastAutoMode(aArguments);
                break;

            case GUI:
                startGuiMode();
                break;
            default:
                startUI(StartupMode.GUI);
        }
    }

    private void startGuiMode() {
        EventQueue.invokeLater(() ->
        {
            if (SystemInfo.isMacOSX())
                checkForOfficialOSXAppUse();

            //JavaFX stuff
            Platform.setImplicitExit(false);

            if (SystemInfo.isMacOSX()) {
                System.setProperty(MAC_SYSTEM_PROPERTY_APPLE_LAF_USE_SCREEN_MENU_BAR, Boolean.TRUE.toString());
                cleanupOsxFiles();
            }

            if (Config.isDebuggingEnabled()) {
                // use for debugging EDT violations
                RepaintManager.setCurrentManager(new ThreadCheckingRepaintManager());
            }

            //prevent startup of multiple instances...
            SingleInstance singleInstanceWatcher = new SingleInstance();
            if (singleInstanceWatcher.isAppAlreadyActive()) {
                JOptionPane.showMessageDialog(null, LOG_TEXT_MEDIATHEK_VIEW_IS_ALREADY_RUNNING);
                System.exit(1);
            }


            getPlatformWindow().setVisible(true);
        });
    }

    private MediathekGui getPlatformWindow() {
        MediathekGui window;

        if (SystemInfo.isMacOSX()) {
            window = null;
        } else if (SystemInfo.isWindows()) {
            window = null;
        } else {
            if (SystemInfo.isUnix()) {
                setupX11WindowManagerClassName();
            }
            window = new MediathekGui();
        }

        return window;
    }

    /**
     * Setup the X11 window manager WM_CLASS hint.
     * Enables e.g. GNOME to determine application name and to enable app specific functionality.
     */
    private void setupX11WindowManagerClassName() {
        try {
            Toolkit xToolkit = Toolkit.getDefaultToolkit();
            java.lang.reflect.Field awtAppClassNameField = xToolkit.getClass().getDeclaredField(X11_AWT_APP_CLASS_NAME);
            awtAppClassNameField.setAccessible(true);
            awtAppClassNameField.set(xToolkit, Konstanten.PROGRAMMNAME);
        } catch (Exception ignored) {
            logger.warn("Could not set awtAppClassName");
        }
    }

    private void startFastAutoMode(final String[] args) {
        final MediathekAuto mvAuto = new MediathekAuto(args);
        mvAuto.setFastAuto(true);
        mvAuto.starten();
    }

    private void startAutoMode(final String[] args) {
        new MediathekAuto(args).starten();
    }

    private StartupMode switchToCLIModeIfNecessary(final StartupMode aState) {
    /*
     If user tries to start MV from command-line without proper options,
     instead of crashing while trying to open Swing windows, just change to CLI mode and warn the user.
     */
        if (GraphicsEnvironment.isHeadless() && (aState == StartupMode.GUI)) {
            logger.warn("Headless environment detected but -auto was not specified.");
            System.err.println("MediathekView wurde nicht als Kommandozeilenprogramm gestartet.");
            System.err.println("Startmodus wurde auf -auto geändert.");
            System.err.println();
            return StartupMode.AUTO;
        }
        return aState;
    }

    private StartupMode processArgs(final StartupMode aStartupMode, final String... aArguments) {
        StartupMode newStartupMode = null;
        for (String argument : aArguments) {
            argument = argument.toLowerCase();
            switch (argument) {
                case ProgramArguments.STARTUPMODE_AUTO:
                    newStartupMode = StartupMode.AUTO;
                    break;

                case ProgramArguments.STARTUPMODE_FASTAUTO:
                    newStartupMode = StartupMode.FASTAUTO;
                    break;

                case ProgramArguments.STARTUPMODE_VERBOSE:
                    EventQueue.invokeLater(() ->
                    {
                        startMeldungen();
                        logger.info("Systemmeldung");
                        Log.errorLog(100000000, "Fehlermeldung");
                        Log.endMsg();
                        System.exit(0);
                    });
                    break;

                case ProgramArguments.STARTUPMODE_DEBUG:
                    Config.enableDebugMode();
                    break;

                case ProgramArguments.STARTUPMODE_MAXIMIZED:
                    Daten.setStartMaximized(true);
                    break;
            }
        }

        return newStartupMode == null ? aStartupMode : newStartupMode;
    }

    private void proxyAuthentication() {
        //TODO remove if not used anymore by URLConnection
        try {
            final String prxUser = System.getProperty(HTTP_PROXY_USER, null);
            final String prxPassword = System.getProperty(HTTP_PROXY_PW, null);
            if (prxUser != null && prxPassword != null) {
                final PasswordAuthentication authenticator = new PasswordAuthentication(prxUser, prxPassword.toCharArray());
                Authenticator.setDefault(new Authenticator() {
                    @Override
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return authenticator;
                    }
                });
                logger.info(String.format(LOG_TEXT_PROXY_AUTHENTICATION_SUCESSFUL, prxUser));
            } else if (prxUser != null && prxPassword == null) {
                logger.info(LOG_TEXT_PROXY_PASSWORD_NOT_SET);
            } else {
                logger.info(LOG_TEXT_PROXY_AUTHENTICATION_NOT_CONFIGURED);
            }

        } catch (SecurityException se) {
            logger.warn(LOG_TEXT_PROXY_AUTHENTICATION_CANNOT_ACCESS_PROXY_USER_PROXY_PW + se.toString());
        }
    }

    private enum StartupMode {

        GUI, AUTO, FASTAUTO
    }

    private final class ProgramArguments {
        private static final String STARTUPMODE_AUTO = "-auto";
        private static final String STARTUPMODE_FASTAUTO = "-fastauto";
        private static final String STARTUPMODE_DEBUG = "-d";
        private static final String STARTUPMODE_MAXIMIZED = "-m";
        private static final String STARTUPMODE_VERBOSE = "-v";
    }
}