aboutsummaryrefslogtreecommitdiff
path: root/installer/process/installworker.cpp
blob: e1c0dbc53f9806ca3fedfdb87354d955393f3b7f (plain) (blame)
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
#include "installworker.h"

#include <unknwn.h>
#include <winrt/base.h>
#include <winrt/Windows.Foundation.h>
#include <propkey.h>
#include <propsys.h>
#include <propvarutil.h>
#include <shlobj.h>
#include <objidl.h>


extern QString calculateSize(quint64 size);

InstallWorker::InstallWorker(QObject *parent) : QObject(parent)
{
}

bool InstallWorker::startWork() {
    QLocalSocket* sock = new QLocalSocket();
    QString vendor, name, url, destPath, executable, clsid;
    bool isStableStream = true, isGlobalInstall = true;

    QString previousToken;
    for (QString arg : QApplication::arguments()) {
        if (previousToken != "") {
            if (previousToken == "--socket") {
                sock->setServerName(arg);
            } else if (previousToken == "--vendor") {
                vendor = arg;
            } else if (previousToken == "--name") {
                name = arg;
            } else if (previousToken == "--url") {
                url = arg;
            } else if (previousToken == "--destdir") {
                destPath = arg;
            } else if (previousToken == "--executable") {
                executable = arg;
            } else if (previousToken == "--clsid") {
                clsid = arg;
            }
            previousToken = "";
        } else {
            if (arg == "--socket" || arg == "--vendor" || arg == "--name" || arg == "--url" || arg == "--destdir" || arg == "--executable" || arg == "--clsid") {
                previousToken = arg;
            } else if (arg == "--blueprint") {
                isStableStream = false;
            } else if (arg == "--stable") {
                isStableStream = true;
            } else if (arg == "--local") {
                isGlobalInstall = false;
            } else if (arg == "--global") {
                isGlobalInstall = true;
            }
        }
    }

    if (sock->serverName() == "") {
        qDebug() << "Required argument --socket missing";
        return false;
    }

    qDebug() << "Connecting to socket server...";
    sock->connectToServer();
    if (!sock->waitForConnected()) {
        qDebug() << "Failed to connect to socket server";
        return false;
    }
    connect(sock, &QLocalSocket::disconnected, [=] {
        qDebug() << "Socket closed";
        QApplication::exit(1);
    });
    connect(sock, &QLocalSocket::readyRead, [=] {
        QStringList lines = QString(sock->readAll()).split("\n");
        for (QString line : lines) {
            QStringList parts = line.split(" ");
            if (parts.at(0) == "CANCEL") {
                if (currentlyCancelable) {
                    QApplication::exit(0);
                }
            }
        }
    });

    if (!packageFile.open() || !packageTemporaryDir.isValid()) {
        return false;
    }
    sock->write(QString("STATUS ").append(tr("Downloading %1...").arg(name)).append("\n").toUtf8());
    sock->write(QString("DEBUG %1").arg(packageFile.fileName()).toUtf8());

    QTimer* flipper = new QTimer();
    flipper->setInterval(5000);
    connect(flipper, &QTimer::timeout, [=] {
        emitStatus = !emitStatus;
    });
    flipper->start();

    QNetworkRequest req(QUrl((QString) url));
    req.setAttribute(QNetworkRequest::FollowRedirectsAttribute, true);
    req.setHeader(QNetworkRequest::UserAgentHeader, "theInstaller/1.0");
    QNetworkReply* reply = mgr.get(req);

    lastBytesReceived = 0;
    lastTimeUpdate = QDateTime::fromMSecsSinceEpoch(0);
    connect(reply, &QNetworkReply::finished, [=] {
        if (reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt() != 200) {
            QApplication::exit(1);
            return;
        }
        packageFile.flush();
        packageFile.seek(0);

        flipper->stop();

        currentlyCancelable = false;
        sock->write(QString("STOPCANCEL\n").toUtf8());
        sock->write(QString("STATUS ").append(tr("Unpacking %1...").arg(name)).append("\n").toUtf8());
        sock->write("PROGRESS 0 0\n");
        sock->write(QString("DEBUG %1").arg(packageTemporaryDir.path()).toUtf8());

        if (QDir(destPath).exists()) {
            QDir(destPath).removeRecursively();
        }
        QDir::root().mkpath(destPath);
        QDir dest(destPath);

        QStringList extracted = JlCompress::extractDir(packageFile.fileName(), destPath);
        if (extracted.length() == 0) {
            //Error occurred
            QApplication::exit(1);
            return;
        }

        sock->write(QString("STATUS ").append(tr("Configuring %1...").arg(name)).append("\n").toUtf8());

        QDir startMenu;
        if (isGlobalInstall) {
            startMenu = QDir("C:/ProgramData/Microsoft/Windows/Start Menu/Programs");
        } else {
            startMenu = QDir(QStandardPaths::writableLocation(QStandardPaths::ApplicationsLocation));
        }
        startMenu.mkpath(vendor + "/" + name);
        startMenu.cd(vendor + "/" + name);

        QFileInfo executableFile(destPath + "/" + executable);
        QString linkFile = startMenu.absoluteFilePath(executableFile.completeBaseName() + ".lnk");
        if (QFile::exists(linkFile)) {
            QFile::remove(linkFile);
        }
        QFile::copy(QApplication::applicationFilePath(), dest.absoluteFilePath("uninstall.exe"));

        bool shouldUseQFileLink = false;
        if (!clsid.isEmpty()) {
            QString appUMID = QStringLiteral("%1.%2").arg(vendor.toLower()).arg(name.toLower());
            QSettings* comServer;
            if (isGlobalInstall) {
                comServer = new QSettings(QStringLiteral("HKEY_LOCAL_MACHINE\\SOFTWARE\\Classes\\CLSID\\%1\\LocalServer32").arg(clsid), QSettings::NativeFormat);
            } else {
                comServer = new QSettings(QStringLiteral("HKEY_CURRENT_USER\\SOFTWARE\\Classes\\CLSID\\%1\\LocalServer32").arg(clsid), QSettings::NativeFormat);
            }

            comServer->setValue(".", "\"" + executableFile.absoluteFilePath() + "\" -ToastActivated");

            comServer->deleteLater();

            try {
                auto link{ winrt::create_instance<IShellLink>(CLSID_ShellLink) };
                winrt::check_hresult(link->SetPath(executableFile.absoluteFilePath().toStdWString().c_str()));

                auto store = link.as<IPropertyStore>();
                PROPVARIANT value;
                winrt::check_hresult(::InitPropVariantFromString(appUMID.toStdWString().c_str(), &value));
                winrt::check_hresult(store->SetValue(PKEY_AppUserModel_ID, value));
                ::PropVariantClear(&value);

                CLSID clsidVar;
                winrt::check_hresult(::CLSIDFromString(clsid.toStdWString().c_str(), &clsidVar));
                winrt::check_hresult(::InitPropVariantFromCLSID(clsidVar, &value));
                winrt::check_hresult(store->SetValue(PKEY_AppUserModel_ToastActivatorCLSID, value));

                auto file{ store.as<IPersistFile>() };
                winrt::check_hresult(file->Save(linkFile.toStdWString().c_str(), TRUE));

                ::PropVariantClear(&value);
            } catch (...) {
                sock->write(QString("DEBUG Error while creating link; falling back to QFile::link\n").toUtf8());

                shouldUseQFileLink = true;
            }
        } else {
            shouldUseQFileLink = true;
        }

        if (shouldUseQFileLink) {
            QFile::link(executableFile.absoluteFilePath(), linkFile);
        }

        QJsonObject dataRoot;
        dataRoot.insert("vendor", vendor);
        dataRoot.insert("name", name);
        dataRoot.insert("installPath", destPath);
        dataRoot.insert("global", isGlobalInstall);
        dataRoot.insert("appurl", url);
        dataRoot.insert("stream", isStableStream);
        dataRoot.insert("registryUuid", name);

        if (!clsid.isEmpty()) {
            dataRoot.insert("clsid", clsid);
        }

        QSettings* settings;
        if (isGlobalInstall) {
            settings = new QSettings("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\" + name, QSettings::NativeFormat);
        } else {
            settings = new QSettings("HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\" + name, QSettings::NativeFormat);
        }

        settings->clear();
        settings->setValue("DisplayName", name);
        settings->setValue("Publisher", vendor);
        settings->setValue("Contact", vendor);
        settings->setValue("ModifyPath", "\"" + dest.absoluteFilePath("uninstall.exe").replace("/", "\\") + "\"");
        settings->setValue("UninstallString", "\"" + dest.absoluteFilePath("uninstall.exe").replace("/", "\\") + "\"");
        settings->setValue("InstallDate", QDateTime::currentDateTime().toString("yyyyMMdd"));
        settings->setValue("InstallLocation", dest.path());
        settings->setValue("DisplayIcon", executableFile.absoluteFilePath() + ",0");
        settings->sync();
        settings->deleteLater();

        QFile uninstallDataFile(dest.absoluteFilePath("uninstall.json"));
        uninstallDataFile.open(QFile::WriteOnly);
        uninstallDataFile.write(QJsonDocument(dataRoot).toJson());

        sock->write("COMPLETE\n");
        sock->flush();
        sock->waitForBytesWritten();
        QApplication::exit(0);
    });
    connect(reply, &QNetworkReply::readyRead, [=] {
        packageFile.write(reply->readAll());
    });
    connect(reply, &QNetworkReply::downloadProgress, [=](qint64 bytesReceived, qint64 bytesTotal) {
        sock->write(QString("PROGRESS %1 %2\n").arg(QString::number(bytesReceived), QString::number(bytesTotal)).toUtf8());

        if (lastTimeUpdate.toMSecsSinceEpoch() == 0) lastTimeUpdate = QDateTime::currentDateTimeUtc();

        if (emitStatus) {
            sock->write(QString("STATUS ").append(tr("Downloading %1...").arg(name)).append("\n").toUtf8());
        } else {
            QDateTime current = QDateTime::currentDateTimeUtc();

            float speed = (float) bytesReceived / (float) (current.toSecsSinceEpoch() - lastTimeUpdate.toSecsSinceEpoch()); //bytes per second

            qint64 bytesToGo = bytesTotal - bytesReceived;
            int secondsToGo = bytesToGo / speed;

            QString downloaded = tr("%1 of %2").arg(calculateSize(bytesReceived), calculateSize(bytesTotal));
            QString currentSpeed = calculateSize(speed) + "/s";
            QString remainingTime;

            int minutes = secondsToGo / 60;
            int seconds = secondsToGo % 60;
            int hours = minutes / 60;
            minutes = minutes % 60;
            int days = hours / 24;
            hours = hours % 24;

            if (days > 0) {
                remainingTime = tr("%n days remaining", nullptr, days);
            } else if (hours > 0) {
                remainingTime = tr("%n hours remaining", nullptr, hours);
            } else if (minutes > 0) {
                remainingTime = tr("%n minutes remaining", nullptr, minutes);
            } else {
                remainingTime = tr("%n seconds remaining", nullptr, seconds);
            }

            sock->write(QString("STATUS ").append(downloaded + " - " + currentSpeed + " - " + remainingTime).append("\n").toUtf8());
        }
    });

    return true;
}