summaryrefslogtreecommitdiff
path: root/upgrade.py
blob: 4085b9834c9e83c41b3d608b2a56e4fb17744341 (plain)
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
# Copyright (C) 2017 Damon Lynch <damonlynch@gmail.com>

# This file is part of Rapid Photo Downloader.
#
# Rapid Photo Downloader 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
# (at your option) any later version.
#
# Rapid Photo Downloader 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 Rapid Photo Downloader.  If not,
# see <http://www.gnu.org/licenses/>.

"""
Helper program to upgrade Rapid Photo Downloader using pip
"""

__author__ = 'Damon Lynch'
__copyright__ = "Copyright 2017, Damon Lynch"


import sys
import os
import tarfile
import tempfile
import shutil
import re
from typing import List, Optional
import shlex
from subprocess import Popen, PIPE
from queue import Queue, Empty
import subprocess
import platform
from distutils.version import StrictVersion
from gettext import gettext as _

from PyQt5.QtCore import (pyqtSignal, pyqtSlot,  Qt, QThread, QObject, QTimer)
from PyQt5.QtGui import QIcon, QFontMetrics, QFont, QFontDatabase
from PyQt5.QtWidgets import (QApplication, QDialog, QPushButton, QVBoxLayout, QTextEdit,
                             QDialogButtonBox, QStackedWidget, QLabel)
from PyQt5.QtNetwork import QLocalSocket

import raphodo.qrc_resources as qrc_resources


q = Queue()


class RPDUpgrade(QObject):
    """
    Upgrade Rapid Photo Downloader using python's pip
    """

    message = pyqtSignal(str)
    upgradeFinished = pyqtSignal(bool)


    def make_pip_command(self, args: str) -> List[str]:
        return shlex.split('{} -m pip {}'.format(sys.executable, args))

    def pip_version(self) -> StrictVersion:
        import pip

        return StrictVersion(pip.__version__)

    @pyqtSlot(str)
    def start(self, installer: str) -> None:

        # explicitly uninstall any previous version installed with pip
        self.sendMessage("Uninstalling previous version installed with pip...\n")
        l_command_line = 'list --user --disable-pip-version-check'
        if self.pip_version() >= StrictVersion('9.0.0'):
            l_command_line = '{} --format=columns'.format(l_command_line)
        l_args = self.make_pip_command(l_command_line)

        u_command_line = 'uninstall --disable-pip-version-check -y rapid-photo-downloader'
        u_args = self.make_pip_command(u_command_line)
        while True:
            try:
                output = subprocess.check_output(l_args, universal_newlines=True)
                if 'rapid-photo-downloader' in output:
                    with Popen(
                            u_args, stdout=PIPE, stderr=PIPE, bufsize=1, universal_newlines=True
                    ) as p:
                        for line in p.stdout:
                            self.sendMessage(line, truncate=True)
                            cmd = self.checkForCmd()
                            if cmd is not None:
                                assert cmd == 'STOP'
                                self.failure('\nTermination requested')
                                return
                        p.wait()
                        i = p.returncode
                    if i != 0:
                        self.sendMessage(
                            "Encountered an error uninstalling previous version installed with "
                            "pip\n"
                        )
                else:
                    break
            except Exception:
                break
        self.sendMessage('...done uninstalling previous version.\n')

        name = os.path.basename(installer)
        name = name[:len('.tar.gz') * -1]

        rpath = os.path.join(name, 'requirements.txt')
        try:
            with tarfile.open(installer) as tar:
                with tar.extractfile(rpath) as requirements:
                    reqbytes = requirements.read()
                    if platform.machine() == 'x86_64' and platform.python_version_tuple()[1] in (
                            '5', '6'):
                        reqbytes = reqbytes.rstrip() + b'\nPyQt5'
                    with tempfile.NamedTemporaryFile(delete=False) as temp_requirements:
                        temp_requirements.write(reqbytes)
                        temp_requirements_name = temp_requirements.name
        except Exception:
            self.failure("Failed to extract application requirements")
            return

        self.sendMessage("Installing application requirements...\n")
        try:
            cmd = self.make_pip_command(
                'install --user --disable-pip-version-check -r {}'.format(temp_requirements.name)
            )
            with Popen(cmd, stdout=PIPE, stderr=PIPE, bufsize=1, universal_newlines=True) as p:
                for line in p.stdout:
                    self.sendMessage(line, truncate=True)
                    cmd = self.checkForCmd()
                    if cmd is not None:
                        assert cmd == 'STOP'
                        self.failure('\nTermination requested')
                        return
                p.wait()
                i = p.returncode
            os.remove(temp_requirements_name)
            if i != 0:
                self.failure("Failed to install application requirements: %i" % i)
                return
        except Exception:
            self.sendMessage(sys.exc_info())
            self.failure("Failed to install application requirements")
            return

        self.sendMessage("\nInstalling application...\n")
        try:
            cmd = self.make_pip_command(
                'install --user --disable-pip-version-check --no-deps {}'.format(installer)
            )
            with Popen(cmd, stdout=PIPE, stderr=PIPE, bufsize=1, universal_newlines=True) as p:
                for line in p.stdout:
                    self.sendMessage(line, truncate=True)
                    cmd = self.checkForCmd()
                    if cmd is not None:
                        assert cmd == 'STOP'
                        self.failure('\nTermination requested')
                        return
                p.wait()
                i = p.returncode
            if i != 0:
                self.failure("Failed to install application")
                return
        except Exception:
            self.failure("Failed to install application")
            return

        self.upgradeFinished.emit(True)

    def failure(self, message: str) -> None:
        self.sendMessage(message)
        self.upgradeFinished.emit(False)


    def sendMessage(self, message: str, truncate=False) -> None:
        if truncate:
            self.message.emit(message[:-1])
        else:
            self.message.emit(message)

    def checkForCmd(self) -> Optional[str]:
        try:
            return q.get(block=False)
        except Empty:
            return None


def extract_version_number(installer: str) -> str:
    targz = os.path.basename(installer)
    parsed_version = targz[:targz.find('tar') - 1]

    first_digit = re.search("\d", parsed_version)
    return parsed_version[first_digit.start():]


class UpgradeDialog(QDialog):
    """
    Very simple dialog window that allows user to initiate
    Rapid Photo Downloader upgrade and shows output of that
    upgrade.
    """

    startUpgrade = pyqtSignal(str)
    def __init__(self, installer):
        super().__init__()

        self.installer = installer
        self.setWindowTitle(_('Upgrade Rapid Photo Downloader'))

        try:
            self.version_no = extract_version_number(installer=installer)
        except Exception:
            self.version_no = ''

        self.running = False

        self.textEdit = QTextEdit()
        self.textEdit.setReadOnly(True)

        fixed = QFontDatabase.systemFont(QFontDatabase.FixedFont)  # type: QFont
        fixed.setPointSize(fixed.pointSize() - 1)
        self.textEdit.setFont(fixed)

        font_height = QFontMetrics(fixed).height()

        height = font_height * 20

        width = QFontMetrics(fixed).boundingRect('a' * 90).width()

        self.textEdit.setMinimumSize(width, height)

        upgradeButtonBox = QDialogButtonBox(QDialogButtonBox.Cancel)
        upgradeButtonBox.rejected.connect(self.reject)
        upgradeButtonBox.accepted.connect(self.doUpgrade)
        self.startButton = upgradeButtonBox.addButton(_('&Upgrade'),
                                                 QDialogButtonBox.AcceptRole)  # QPushButton
        # self.startButton.setDefault(True)

        if self.version_no:
            self.explanation = QLabel(_('Click the Upgrade button to upgrade to '
                                        'version %s.') % self.version_no)
        else:
            self.explanation = QLabel(_('Click the Upgrade button to start the upgrade.'))

        finishButtonBox = QDialogButtonBox(QDialogButtonBox.Close)
        finishButtonBox.addButton(_('&Run'), QDialogButtonBox.AcceptRole)
        finishButtonBox.rejected.connect(self.reject)
        finishButtonBox.accepted.connect(self.runNewVersion)

        failedButtonBox = QDialogButtonBox(QDialogButtonBox.Close)
        failedButtonBox.rejected.connect(self.reject)

        self.stackedButtons = QStackedWidget()
        self.stackedButtons.addWidget(upgradeButtonBox)
        self.stackedButtons.addWidget(finishButtonBox)
        self.stackedButtons.addWidget(failedButtonBox)

        layout = QVBoxLayout()
        self.setLayout(layout)
        layout.addWidget(self.textEdit)
        layout.addWidget(self.explanation)
        layout.addWidget(self.stackedButtons)

        self.upgrade = RPDUpgrade()
        self.upgradeThread = QThread()
        self.startUpgrade.connect(self.upgrade.start)
        self.upgrade.message.connect(self.appendText)
        self.upgrade.upgradeFinished.connect(self.upgradeFinished)
        self.upgrade.moveToThread(self.upgradeThread)
        QTimer.singleShot(0, self.upgradeThread.start)

    @pyqtSlot()
    def doUpgrade(self) -> None:
        if self.rpdRunning():
            self.explanation.setText(_('Close Rapid Photo Downloader before running this upgrade'))
        else:
            self.running = True
            self.explanation.setText(_('Upgrade running...'))
            self.startButton.setEnabled(False)
            self.startUpgrade.emit(self.installer)

    def rpdRunning(self) -> bool:
        """
        Check to see if Rapid Photo Downloader is running
        :return: True if it is
        """

        # keep next value in sync with value in raphodo/rapid.py
        # can't import it
        appGuid = '8dbfb490-b20f-49d3-9b7d-2016012d2aa8'
        outSocket = QLocalSocket() # type: QLocalSocket
        outSocket.connectToServer(appGuid)
        isRunning = outSocket.waitForConnected()  # type: bool
        if outSocket:
            outSocket.disconnectFromServer()
        return isRunning

    @pyqtSlot(str)
    def appendText(self,text: str) -> None:
        self.textEdit.append(text)

    @pyqtSlot(bool)
    def upgradeFinished(self, success: bool) -> None:
        self.running = False

        if success:
            self.stackedButtons.setCurrentIndex(1)
        else:
            self.stackedButtons.setCurrentIndex(2)

        if success:
            if self.version_no:
                message = _('Successfully upgraded to %s. Click Close to exit, or Run to '
                            'start the program.' % self.version_no)
            else:
                message = _('Upgrade finished successfully. Click Close to exit, or Run to '
                            'start the program.')
        else:
            message = _('Upgrade failed. Click Close to exit.')

        self.explanation.setText(message)
        self.deleteTar()

    def deleteTar(self) -> None:
        temp_dir = os.path.dirname(self.installer)
        if temp_dir:
            shutil.rmtree(temp_dir, ignore_errors=True)

    def closeEvent(self, event) -> None:
        self.upgradeThread.quit()
        self.upgradeThread.wait()
        event.accept()

    @pyqtSlot()
    def reject(self) -> None:
        if self.running:
            # strangely, using zmq in this program causes a segfault :-/
            q.put('STOP')
        super().reject()

    @pyqtSlot()
    def runNewVersion(self) -> None:
        cmd = shutil.which('rapid-photo-downloader')
        subprocess.Popen(cmd)
        super().accept()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    app.setWindowIcon(QIcon(':/rapid-photo-downloader.svg'))
    widget = UpgradeDialog(sys.argv[1])
    widget.show()
    sys.exit(app.exec_())