Search in sources :

Example 6 with UpdateInstaller

use of com.biglybt.pif.update.UpdateInstaller in project BiglyBT by BiglySoftware.

the class PlatformManagerUnixPlugin method checkStartupScript.

/**
 * @since 3.0.1.7
 */
private void checkStartupScript() {
    COConfigurationManager.setIntDefault("unix.script.lastaskversion", -1);
    int lastAskedVersion = COConfigurationManager.getIntParameter("unix.script.lastaskversion");
    String sVersion = System.getProperty(SystemProperties.SYSPROP_SCRIPT_VERSION, "0");
    int version = 0;
    try {
        version = Integer.parseInt(sVersion);
    } catch (Throwable t) {
    }
    Pattern pat = Pattern.compile("SCRIPT_VERSION=([0-9]+)", Pattern.CASE_INSENSITIVE);
    File oldFilePath;
    String sScriptFile = System.getProperty(SystemProperties.SYSPROP_APP_SCRIPT, null);
    if (sScriptFile != null && new File(sScriptFile).exists()) {
        oldFilePath = new File(sScriptFile);
    } else {
        oldFilePath = new File(SystemProperties.getApplicationPath(), Constants.APP_NAME.toLowerCase());
        if (!oldFilePath.exists()) {
            return;
        }
    }
    final String oldFilePathString = oldFilePath.getAbsolutePath();
    String oldStartupScript;
    try {
        oldStartupScript = FileUtil.readFileAsString(oldFilePath, 65535, "utf8");
    } catch (IOException e) {
        oldStartupScript = "";
    }
    // the second restart message
    if (version == 0) {
        Matcher matcher = pat.matcher(oldStartupScript);
        if (matcher.find()) {
            String sScriptVersion = matcher.group(1);
            try {
                version = Integer.parseInt(sScriptVersion);
            } catch (Throwable t) {
            }
        }
    }
    if (version <= lastAskedVersion) {
        return;
    }
    InputStream stream = getClass().getResourceAsStream("startupScript");
    try {
        String startupScript = FileUtil.readInputStreamAsString(stream, 65535, "utf8");
        Matcher matcher = pat.matcher(startupScript);
        if (matcher.find()) {
            String sScriptVersion = matcher.group(1);
            int latestVersion = 0;
            try {
                latestVersion = Integer.parseInt(sScriptVersion);
            } catch (Throwable t) {
            }
            if (latestVersion > version) {
                boolean autoUpdateScript = oldStartupScript.indexOf("AUTOUPDATE_SCRIPT=1") > 0;
                boolean bInformUserManual = true;
                if (autoUpdateScript) {
                    if (version >= 1) {
                        UpdateManager um = PluginInitializer.getDefaultInterface().getUpdateManager();
                        UpdateInstaller installer = um.createInstaller();
                        installer.addResource("biglybt.new", new ByteArrayInputStream(startupScript.getBytes()));
                        String target = new File(installer.getInstallDir(), "biglybt").getAbsolutePath();
                        installer.addMoveAction("biglybt.new", target);
                        installer.addChangeRightsAction("+x", target);
                        bInformUserManual = false;
                    } else {
                        // overwrite!
                        try {
                            FileUtil.writeBytesAsFile(oldFilePathString, startupScript.getBytes());
                            Runtime.getRuntime().exec(new String[] { findCommand("chmod"), "+x", oldStartupScript });
                            bInformUserManual = false;
                        } catch (Throwable t) {
                        }
                    }
                }
                if (bInformUserManual) {
                    final String newFilePath = new File(SystemProperties.getApplicationPath(), "biglybt.new").getAbsolutePath();
                    FileUtil.writeBytesAsFile(newFilePath, startupScript.getBytes());
                    showScriptManualUpdateDialog(newFilePath, oldFilePathString, latestVersion);
                } else {
                    showScriptAutoUpdateDialog();
                }
            }
        }
    } catch (Throwable t) {
        t.printStackTrace();
    } finally {
        try {
            stream.close();
        } catch (Throwable e) {
        }
    }
}
Also used : Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher) ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) UpdateInstaller(com.biglybt.pif.update.UpdateInstaller) UpdateManager(com.biglybt.pif.update.UpdateManager) IOException(java.io.IOException) File(java.io.File)

Example 7 with UpdateInstaller

use of com.biglybt.pif.update.UpdateInstaller in project BiglyBT by BiglySoftware.

the class PlatformManagerUpdateChecker method installUpdate.

protected void installUpdate(UpdateChecker checker, Update update, ResourceDownloader rd, InputStream data) {
    ZipInputStream zip = null;
    try {
        data = update.verifyData(data, true);
        rd.reportActivity("Data verified successfully");
        UpdateInstaller installer = checker.createInstaller();
        zip = new ZipInputStream(data);
        ZipEntry entry = null;
        while ((entry = zip.getNextEntry()) != null) {
            String name = entry.getName();
            if (name.toLowerCase().startsWith("windows/")) {
                // win32 only files
                name = name.substring(8);
                if (name.length() > 0) {
                    rd.reportActivity("Adding update action for '" + name + "'");
                    if (Logger.isEnabled())
                        Logger.log(new LogEvent(LOGID, "PlatformManager:Win32 adding action for '" + name + "'"));
                    installer.addResource(name, zip, false);
                    installer.addMoveAction(name, installer.getInstallDir() + File.separator + name);
                }
            }
        }
        update.complete(true);
    } catch (Throwable e) {
        update.complete(false);
        rd.reportActivity("Update install failed:" + e.getMessage());
    } finally {
        if (zip != null) {
            try {
                zip.close();
            } catch (Throwable e) {
            }
        }
    }
}
Also used : ZipInputStream(java.util.zip.ZipInputStream) LogEvent(com.biglybt.core.logging.LogEvent) UpdateInstaller(com.biglybt.pif.update.UpdateInstaller) ZipEntry(java.util.zip.ZipEntry)

Example 8 with UpdateInstaller

use of com.biglybt.pif.update.UpdateInstaller in project BiglyBT by BiglySoftware.

the class ConfigSectionLogging method configSectionCreate.

@Override
public Composite configSectionCreate(final Composite parent) {
    ImageLoader imageLoader = ImageLoader.getInstance();
    Image imgOpenFolder = imageLoader.getImage("openFolderButton");
    GridData gridData;
    GridLayout layout;
    Composite gLogging = new Composite(parent, SWT.NULL);
    gridData = new GridData(GridData.VERTICAL_ALIGN_FILL | GridData.HORIZONTAL_ALIGN_FILL);
    Utils.setLayoutData(gLogging, gridData);
    layout = new GridLayout();
    layout.numColumns = 2;
    gLogging.setLayout(layout);
    int userMode = COConfigurationManager.getIntParameter("User Mode");
    BooleanParameter enable_logger = new BooleanParameter(gLogging, "Logger.Enabled", "ConfigView.section.logging.loggerenable");
    gridData = new GridData();
    gridData.horizontalSpan = 2;
    enable_logger.setLayoutData(gridData);
    // row
    final BooleanParameter enableLogging = new BooleanParameter(gLogging, "Logging Enable", "ConfigView.section.logging.enable");
    gridData = new GridData();
    gridData.horizontalSpan = 2;
    enableLogging.setLayoutData(gridData);
    Composite cArea = new Composite(gLogging, SWT.NULL);
    layout = new GridLayout();
    layout.marginHeight = 0;
    layout.marginWidth = 0;
    layout.numColumns = 3;
    cArea.setLayout(layout);
    gridData = new GridData(GridData.FILL_HORIZONTAL);
    gridData.horizontalSpan = 2;
    cArea.setLayoutData(gridData);
    // row
    Label lStatsPath = new Label(cArea, SWT.NULL);
    // $NON-NLS-1$
    Messages.setLanguageText(lStatsPath, "ConfigView.section.logging.logdir");
    gridData = new GridData();
    gridData.widthHint = 150;
    // $NON-NLS-1$ //$NON-NLS-2$
    final StringParameter pathParameter = new StringParameter(cArea, "Logging Dir");
    pathParameter.setLayoutData(gridData);
    Button browse = new Button(cArea, SWT.PUSH);
    browse.setImage(imgOpenFolder);
    imgOpenFolder.setBackground(browse.getBackground());
    browse.setToolTipText(MessageText.getString("ConfigView.button.browse"));
    browse.addListener(SWT.Selection, new Listener() {

        /* (non-Javadoc)
       * @see org.eclipse.swt.widgets.Listener#handleEvent(org.eclipse.swt.widgets.Event)
       */
        @Override
        public void handleEvent(Event event) {
            DirectoryDialog dialog = new DirectoryDialog(parent.getShell(), SWT.APPLICATION_MODAL);
            dialog.setFilterPath(pathParameter.getValue());
            // $NON-NLS-1$
            dialog.setText(MessageText.getString("ConfigView.section.logging.choosedefaultsavepath"));
            String path = dialog.open();
            if (path != null) {
                pathParameter.setValue(path);
            }
        }
    });
    Label lMaxLog = new Label(cArea, SWT.NULL);
    Messages.setLanguageText(lMaxLog, "ConfigView.section.logging.maxsize");
    final String[] lmLabels = new String[logFileSizes.length];
    final int[] lmValues = new int[logFileSizes.length];
    for (int i = 0; i < logFileSizes.length; i++) {
        int num = logFileSizes[i];
        lmLabels[i] = " " + num + " MB";
        lmValues[i] = num;
    }
    IntListParameter paramMaxSize = new IntListParameter(cArea, "Logging Max Size", lmLabels, lmValues);
    gridData = new GridData();
    gridData.horizontalSpan = 2;
    paramMaxSize.setLayoutData(gridData);
    if (userMode > 1) {
        Label timeStampLbl = new Label(cArea, SWT.NULL);
        Messages.setLanguageText(timeStampLbl, "ConfigView.section.logging.timestamp");
        Utils.setLayoutData(timeStampLbl, new GridData());
        StringParameter timeStamp = new StringParameter(cArea, "Logging Timestamp");
        gridData = new GridData();
        gridData.horizontalSpan = 2;
        gridData.widthHint = 150;
        timeStamp.setLayoutData(gridData);
    }
    /**
     * FileLogging filter, consisting of a List of types (info, warning, error)
     * and a checkbox Table of component IDs.
     */
    final String sFilterPrefix = "ConfigView.section.logging.filter";
    Group gLogIDs = new Group(gLogging, SWT.NULL);
    Messages.setLanguageText(gLogIDs, sFilterPrefix);
    layout = new GridLayout();
    layout.numColumns = 2;
    gLogIDs.setLayout(layout);
    gridData = new GridData(SWT.BEGINNING, SWT.BEGINNING, true, true);
    gridData.horizontalSpan = 2;
    Utils.setLayoutData(gLogIDs, gridData);
    final List listLogTypes = new List(gLogIDs, SWT.BORDER | SWT.SINGLE | SWT.V_SCROLL);
    gridData = new GridData(SWT.NULL, SWT.BEGINNING, false, false);
    listLogTypes.setLayoutData(gridData);
    final int[] logTypes = { LogEvent.LT_INFORMATION, LogEvent.LT_WARNING, LogEvent.LT_ERROR };
    for (int i = 0; i < logTypes.length; i++) listLogTypes.add(MessageText.getString("ConfigView.section.logging.log" + i + "type"));
    listLogTypes.select(0);
    final LogIDs[] logIDs = FileLogging.configurableLOGIDs;
    // Arrays.sort(logIDs);
    final Table tableLogIDs = new Table(gLogIDs, SWT.CHECK | SWT.BORDER | SWT.SINGLE | SWT.FULL_SELECTION);
    gridData = new GridData(GridData.FILL_BOTH);
    tableLogIDs.setLayoutData(gridData);
    tableLogIDs.setLinesVisible(false);
    tableLogIDs.setHeaderVisible(false);
    TableColumn column = new TableColumn(tableLogIDs, SWT.NONE);
    for (int i = 0; i < logIDs.length; i++) {
        TableItem item = new TableItem(tableLogIDs, SWT.NULL);
        item.setText(0, MessageText.getString(sFilterPrefix + "." + logIDs[i], logIDs[i].toString()));
        item.setData(logIDs[i]);
        boolean checked = COConfigurationManager.getBooleanParameter("bLog." + logTypes[0] + "." + logIDs[i], true);
        item.setChecked(checked);
    }
    column.pack();
    // Update table when list selection changes
    listLogTypes.addSelectionListener(new SelectionAdapter() {

        @Override
        public void widgetSelected(SelectionEvent e) {
            int index = listLogTypes.getSelectionIndex();
            if (index < 0 || index >= logTypes.length)
                return;
            TableItem[] items = tableLogIDs.getItems();
            for (int i = 0; i < items.length; i++) {
                boolean checked = COConfigurationManager.getBooleanParameter("bLog." + logTypes[index] + "." + items[i].getData(), true);
                items[i].setChecked(checked);
            }
        }
    });
    // Save config when checkbox is clicked
    tableLogIDs.addSelectionListener(new SelectionAdapter() {

        @Override
        public void widgetSelected(SelectionEvent e) {
            if (e.detail != SWT.CHECK)
                return;
            int index = listLogTypes.getSelectionIndex();
            if (index < 0 || index >= logTypes.length)
                return;
            TableItem item = (TableItem) e.item;
            COConfigurationManager.setParameter("bLog." + logTypes[index] + "." + item.getData(), item.getChecked());
        }
    });
    final Control[] controls_main = { cArea, gLogIDs };
    final ChangeSelectionActionPerformer perf2 = new ChangeSelectionActionPerformer(controls_main);
    enableLogging.setAdditionalActionPerformer(perf2);
    enable_logger.setAdditionalActionPerformer(new IAdditionalActionPerformer() {

        ChangeSelectionActionPerformer p1 = new ChangeSelectionActionPerformer(new Control[] { enableLogging.getControl() });

        @Override
        public void performAction() {
            p1.performAction();
        }

        @Override
        public void setSelected(boolean selected) {
            p1.setSelected(selected);
            if (!selected && enableLogging.isSelected())
                enableLogging.setSelected(false);
        }

        @Override
        public void setIntValue(int value) {
        /*nothing*/
        }

        @Override
        public void setStringValue(String value) {
        /*nothing*/
        }
    });
    if (userMode > 0) {
        Composite cDebugFiles = new Composite(gLogging, SWT.NULL);
        layout = new GridLayout();
        layout.marginHeight = 0;
        layout.marginWidth = 0;
        layout.numColumns = 3;
        cDebugFiles.setLayout(layout);
        gridData = new GridData(GridData.FILL_HORIZONTAL);
        gridData.horizontalSpan = 2;
        cDebugFiles.setLayoutData(gridData);
        Label l_debug_file_size = new Label(cDebugFiles, SWT.NULL);
        Messages.setLanguageText(l_debug_file_size, "ConfigView.section.logging.debugfilesize");
        l_debug_file_size.setLayoutData(new GridData());
        new IntParameter(cDebugFiles, "Logger.DebugFiles.SizeKB", 10, Integer.MAX_VALUE);
        new Label(cDebugFiles, SWT.NULL).setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
    }
    if (userMode > 1) {
        // advanced option
        Group cAO = new Group(gLogging, SWT.NULL);
        cAO.setText(MessageText.getString("dht.advanced.group"));
        layout = new GridLayout();
        layout.marginHeight = 0;
        layout.marginWidth = 0;
        layout.numColumns = 5;
        cAO.setLayout(layout);
        gridData = new GridData(GridData.FILL_HORIZONTAL);
        gridData.horizontalSpan = 2;
        cAO.setLayoutData(gridData);
        // name
        Label aoName = new Label(cAO, SWT.NULL);
        Messages.setLanguageText(aoName, "label.name");
        aoName.setLayoutData(new GridData());
        final StringParameter name = new StringParameter(cAO, "Advanced Option Name");
        gridData = new GridData();
        gridData.widthHint = 150;
        name.setLayoutData(gridData);
        // value
        Label aoValue = new Label(cAO, SWT.NULL);
        Messages.setLanguageText(aoValue, "label.value");
        aoName.setLayoutData(new GridData());
        final StringParameter value = new StringParameter(cAO, "Advanced Option Value");
        gridData = new GridData();
        gridData.widthHint = 150;
        value.setLayoutData(gridData);
        // set
        Button set_option = new Button(cAO, SWT.PUSH);
        Messages.setLanguageText(set_option, "Button.set");
        set_option.addListener(SWT.Selection, new Listener() {

            @Override
            public void handleEvent(Event event) {
                String key = name.getValue().trim();
                if ((key.startsWith("'") && key.endsWith("'")) || (key.startsWith("\"") && key.endsWith("\""))) {
                    key = key.substring(1, key.length() - 1);
                }
                if (key.length() > 0) {
                    if (key.startsWith("!")) {
                        key = key.substring(1);
                    } else {
                        key = "adv.setting." + key;
                    }
                    String val = value.getValue().trim();
                    boolean is_string = false;
                    if ((val.startsWith("'") && val.endsWith("'")) || (val.startsWith("\"") && val.endsWith("\""))) {
                        val = val.substring(1, val.length() - 1);
                        is_string = true;
                    }
                    if (val.length() == 0) {
                        COConfigurationManager.removeParameter(key);
                    } else {
                        if (is_string) {
                            COConfigurationManager.setParameter(key, val);
                        } else {
                            String lc_val = val.toLowerCase(Locale.US);
                            if (lc_val.equals("false") || lc_val.equals("true")) {
                                COConfigurationManager.setParameter(key, lc_val.startsWith("t"));
                            } else {
                                try {
                                    long l = Long.parseLong(val);
                                    COConfigurationManager.setParameter(key, l);
                                } catch (Throwable e) {
                                    COConfigurationManager.setParameter(key, val);
                                }
                            }
                        }
                    }
                    COConfigurationManager.save();
                }
            }
        });
    }
    // network diagnostics
    Label generate_net_info = new Label(gLogging, SWT.NULL);
    Messages.setLanguageText(generate_net_info, "ConfigView.section.logging.netinfo");
    Button generate_net_button = new Button(gLogging, SWT.PUSH);
    Messages.setLanguageText(generate_net_button, "ConfigView.section.logging.generatediagnostics");
    generate_net_button.addListener(SWT.Selection, new Listener() {

        @Override
        public void handleEvent(Event event) {
            new AEThread2("GenerateNetDiag", true) {

                @Override
                public void run() {
                    StringWriter sw = new StringWriter();
                    PrintWriter pw = new PrintWriter(sw);
                    IndentWriter iw = new IndentWriter(pw);
                    NetworkAdmin admin = NetworkAdmin.getSingleton();
                    admin.generateDiagnostics(iw);
                    pw.close();
                    final String info = sw.toString();
                    Logger.log(new LogEvent(LOGID, "Network Info:\n" + info));
                    Utils.execSWTThread(new Runnable() {

                        @Override
                        public void run() {
                            ClipboardCopy.copyToClipBoard(info);
                        }
                    });
                }
            }.start();
        }
    });
    // stats
    Label generate_stats_info = new Label(gLogging, SWT.NULL);
    Messages.setLanguageText(generate_stats_info, "ConfigView.section.logging.statsinfo");
    Button generate_stats_button = new Button(gLogging, SWT.PUSH);
    Messages.setLanguageText(generate_stats_button, "ConfigView.section.logging.generatediagnostics");
    generate_stats_button.addListener(SWT.Selection, new Listener() {

        @Override
        public void handleEvent(Event event) {
            java.util.Set types = new HashSet();
            types.add(CoreStats.ST_ALL);
            Map reply = CoreStats.getStats(types);
            Iterator it = reply.entrySet().iterator();
            StringBuilder buffer = new StringBuilder(16000);
            while (it.hasNext()) {
                Map.Entry entry = (Map.Entry) it.next();
                buffer.append(entry.getKey()).append(" -> ").append(entry.getValue()).append("\r\n");
            }
            String str = buffer.toString();
            ClipboardCopy.copyToClipBoard(str);
            Logger.log(new LogEvent(LOGID, "Stats Info:\n" + str));
        }
    });
    // diagnostics
    Label generate_info = new Label(gLogging, SWT.NULL);
    Messages.setLanguageText(generate_info, "ConfigView.section.logging.generatediagnostics.info");
    Button generate_button = new Button(gLogging, SWT.PUSH);
    Messages.setLanguageText(generate_button, "ConfigView.section.logging.generatediagnostics");
    generate_button.addListener(SWT.Selection, new Listener() {

        @Override
        public void handleEvent(Event event) {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            AEDiagnostics.generateEvidence(pw);
            pw.close();
            String evidence = sw.toString();
            ClipboardCopy.copyToClipBoard(evidence);
            Logger.log(new LogEvent(LOGID, "Evidence Generation:\n" + evidence));
        }
    });
    if (false) {
        Button test_button = new Button(gLogging, SWT.PUSH);
        test_button.setText("Test");
        test_button.addListener(SWT.Selection, new Listener() {

            @Override
            public void handleEvent(Event event) {
                try {
                    PluginInterface pi = CoreFactory.getSingleton().getPluginManager().getDefaultPluginInterface();
                    UpdateInstaller installer = pi.getUpdateManager().createInstaller();
                    installer.addMoveAction("C:\\temp\\file1", "C:\\temp\\file2");
                    installer.installNow(new UpdateInstallerListener() {

                        @Override
                        public void reportProgress(String str) {
                            System.out.println(str);
                        }

                        @Override
                        public void complete() {
                            System.out.println("complete");
                        }

                        @Override
                        public void failed(UpdateException e) {
                            System.out.println("failed");
                            e.printStackTrace();
                        }
                    });
                } catch (Throwable e) {
                    e.printStackTrace();
                }
            }
        });
    }
    return gLogging;
}
Also used : Image(org.eclipse.swt.graphics.Image) NetworkAdmin(com.biglybt.core.networkmanager.admin.NetworkAdmin) SelectionEvent(org.eclipse.swt.events.SelectionEvent) HashSet(java.util.HashSet) LogEvent(com.biglybt.core.logging.LogEvent) AEThread2(com.biglybt.core.util.AEThread2) UpdateInstaller(com.biglybt.pif.update.UpdateInstaller) Map(java.util.Map) IndentWriter(com.biglybt.core.util.IndentWriter) UpdateInstallerListener(com.biglybt.pif.update.UpdateInstallerListener) HashSet(java.util.HashSet) GridLayout(org.eclipse.swt.layout.GridLayout) StringWriter(java.io.StringWriter) Iterator(java.util.Iterator) UpdateException(com.biglybt.pif.update.UpdateException) PrintWriter(java.io.PrintWriter) SelectionAdapter(org.eclipse.swt.events.SelectionAdapter) PluginInterface(com.biglybt.pif.PluginInterface) LogIDs(com.biglybt.core.logging.LogIDs) UpdateInstallerListener(com.biglybt.pif.update.UpdateInstallerListener) GridData(org.eclipse.swt.layout.GridData) LogEvent(com.biglybt.core.logging.LogEvent) SelectionEvent(org.eclipse.swt.events.SelectionEvent) ImageLoader(com.biglybt.ui.swt.imageloader.ImageLoader)

Aggregations

UpdateInstaller (com.biglybt.pif.update.UpdateInstaller)8 LogEvent (com.biglybt.core.logging.LogEvent)4 File (java.io.File)3 ZipEntry (java.util.zip.ZipEntry)3 ZipInputStream (java.util.zip.ZipInputStream)3 PluginInterface (com.biglybt.pif.PluginInterface)2 UpdateException (com.biglybt.pif.update.UpdateException)2 UpdateManager (com.biglybt.pif.update.UpdateManager)2 LogAlert (com.biglybt.core.logging.LogAlert)1 LogIDs (com.biglybt.core.logging.LogIDs)1 NetworkAdmin (com.biglybt.core.networkmanager.admin.NetworkAdmin)1 ClientRestarter (com.biglybt.core.update.ClientRestarter)1 AEThread2 (com.biglybt.core.util.AEThread2)1 IndentWriter (com.biglybt.core.util.IndentWriter)1 UpdateInstallerListener (com.biglybt.pif.update.UpdateInstallerListener)1 UIFunctions (com.biglybt.ui.UIFunctions)1 ImageLoader (com.biglybt.ui.swt.imageloader.ImageLoader)1 BufferedInputStream (java.io.BufferedInputStream)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 FileInputStream (java.io.FileInputStream)1