Debian Codegraph @

src/search/mainnet.cpp

raw symbols SCIP
1 // Copyright (C) 2014 Sacha Refshauge
2
3 // This program is free software: you can redistribute it and/or modify
4 // it under the terms of the GNU General Public License as published by
5 // the Free Software Foundation, version 3.0.
6
7 // This program is distributed in the hope that it will be useful,
8 // but WITHOUT ANY WARRANTY; without even the implied warranty of
9 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 // GNU General Public License 3.0 for more details.
11
12 // A copy of the GPL 3.0 should have been included with the program.
13 // If not, see http://www.gnu.org/licenses/
14
15 // Official GIT repository and contact information can be found at
16 // http://github.com/xsacha/Sachesi
17
18 #include "mainnet.h"
19 #include "splitter.h"
20 #include "ports.h"
21 #include <QStringList>
22 #include <QMessageBox>
23
24 MainNet::MainNet(InstallNet *installer, QObject* parent)
25 : QObject(parent)
26 , _i(installer)
27 , _scanning(0)
28 , _splitting(0)
29 , _splitProgress(0)
30 {
31 manager = new QNetworkAccessManager();
32 currentDownload = new DownloadInfo();
33 if (_i != nullptr)
34 connect(_i, SIGNAL(appListChanged()), this, SLOT(newDeviceConnected()));
35 }
36
37 MainNet::~MainNet()
38 {
39 }
40
41 void MainNet::splitConnectStart() {
42 connect(splitter, SIGNAL(finished()), splitThread, SLOT(quit()));
43 connect(splitter, SIGNAL(finished()), this, SLOT(cancelSplit()));
44 connect(splitter, SIGNAL(progressChanged(int)), this, SLOT(setSplitProgress(int)));
45 connect(splitThread, SIGNAL(finished()), splitter, SLOT(deleteLater()));
46 connect(splitThread, SIGNAL(finished()), splitThread, SLOT(deleteLater()));
47 splitThread->start();
48 }
49
50 void MainNet::splitAutoloader(QUrl url, int options) {
51 if (url.isEmpty())
52 return;
53 QString fileName = url.toLocalFile();
54 _options = options;
55
56 QFileInfo fileInfo(fileName);
57 _splitting = SplittingAuto; emit splittingChanged();
58 splitThread = new QThread();
59 splitter = new Splitter(fileName, _options);
60 splitter->moveToThread(splitThread);
61 if (fileInfo.suffix() == "exe")
62 connect(splitThread, SIGNAL(started()), splitter, SLOT(processSplitAutoloader()));
63 else
64 connect(splitThread, SIGNAL(started()), splitter, SLOT(processSplitBar()));
65 splitConnectStart();
66 }
67
68 void MainNet::combineAutoloader(QList<QUrl> selectedFiles)
69 {
70 // Download required files.
71 if (!QFileInfo(capPath()).exists())
72 {
73 QString capUrl = "http://ppsspp.mvdan.cc/cap3.11.0.11.exe";
74 _splitting = FetchingCap; emit splittingChanged();
75 QNetworkReply* reply = manager->get(QNetworkRequest(capUrl));
76 QObject::connect(reply, &QNetworkReply::readyRead, [=]() {
77 // Download to a temporary file first
78 QFile capFile(capPath(true));
79 capFile.open(QIODevice::WriteOnly | QIODevice::Append);
80 capFile.write(reply->readAll());
81 capFile.close();
82 });
83 QObject::connect(reply, &QNetworkReply::finished, [=]() {
84 // If the download was successful, copy it to the path we check. Some users quit before this happens!
85 QFile::rename(capPath(true), capPath());
86 splitThread = new QThread;
87 _splitting = CreatingAuto; emit splittingChanged();
88 splitter = new Splitter(selectedFiles);
89 splitter->moveToThread(splitThread);
90 connect(splitThread, SIGNAL(started()), splitter, SLOT(processCombine()));
91 splitConnectStart();
92 reply->deleteLater();
93 });
94 QObject::connect(reply, static_cast<void (QNetworkReply::*)(QNetworkReply::NetworkError)>(&QNetworkReply::error), [=]() {
95 // Some users may experience difficult downloading it at all, or the link may be outdated.
96 QMessageBox::information(NULL, "Error", "Was unable to download CAP, which is a component of Autoloaders.\nAs a workaround, you can provide your own CAP to " + capPath());
97 _splitting = SplittingIdle; emit splittingChanged();
98 splitThread->deleteLater();
99 splitter->deleteLater();
100 reply->deleteLater();
101 });
102
103 return;
104 } else {
105 splitThread = new QThread;
106 _splitting = CreatingAuto; emit splittingChanged();
107 splitter = new Splitter(selectedFiles);
108 splitter->moveToThread(splitThread);
109 connect(splitThread, SIGNAL(started()), splitter, SLOT(processCombine()));
110 splitConnectStart();
111 }
112 }
113
114 void MainNet::extractImage(int type, int options)
115 {
116 _options = options;
117 _type = type;
118 QString filter = "*.exe *.signed";
119 if (type == 0 && _options & 1)
120 filter += " *.rcfs";
121 if (type == 2 || (type == 0 && _options & 2))
122 filter += " *.qnx6";
123 if (type == 0 && _options & 4)
124 filter += " *.ifs";
125 QFileDialog* finder = selectFiles("Extract Image", getSaveDir(), "Filesystem Containers", filter);
126 if (finder->exec())
127 extractImageSlot(finder->selectedFiles());
128 finder->deleteLater();
129 }
130
131 void MainNet::extractImageSlot(const QStringList& selectedFiles)
132 {
133 if (selectedFiles.empty())
134 return;
135 // TODO: Actually detect file by inspection
136 QFileInfo fileInfo(selectedFiles.first());
137 if (_type == 2 && fileInfo.size() < 500 * 1024 * 1024) {
138 QString errorMsg = "You can only extract apps from debrick OS images.";
139 if (fileInfo.size() < 120 * 1024 * 1024)
140 errorMsg.append("\nThis appears to be a Radio file. Radios have no apps.");
141 QMessageBox::information(nullptr, "Warning", errorMsg, QMessageBox::Ok);
142 return;
143 }
144 _splitting = (_type == 2) ? ExtractingApps : ExtractingImage; emit splittingChanged();
145 splitThread = new QThread;
146 splitter = new Splitter(selectedFiles.first());
147 switch (_type) {
148 case 1:
149 splitter->extractImage = true;
150 break;
151 case 2:
152 splitter->extractApps = true;
153 break;
154 case 0:
155 default:
156 break;
157 }
158 splitter->extractTypes = _options;
159 splitter->moveToThread(splitThread);
160 // Wrapper should detect file type and deal extract everything inside, according to _options;
161 connect(splitThread, SIGNAL(started()), splitter, SLOT(processExtractWrapper()));
162 splitConnectStart();
163 }
164
165 void MainNet::cancelSplit()
166 {
167 _splitting = SplittingIdle;
168 emit splittingChanged();
169 }
170
171 void MainNet::abortSplit()
172 {
173 emit splitter->killSplit();
174 cancelSplit();
175 }
176
177 void MainNet::grabLinks(int downloadDevice)
178 {
179 _downloadDevice = downloadDevice;
180 writeDisplayFile("Updates", convertLinks("Links have been converted to work on your selected device.\n\n").toLocal8Bit());
181 }
182
183 QString MainNet::fixVariantName(QString name, QString replace, int type) {
184 if (type == 0) { // OS
185 QStringList urlSplit = name.split('/');
186 QStringList nameSplit = urlSplit.last().split('-');
187 if (nameSplit.first().endsWith(".desktop"))
188 nameSplit.first() = replace + ".desktop";
189 else
190 nameSplit.first() = replace;
191
192 urlSplit.last() = nameSplit.join('-');
193 return urlSplit.join('/');
194 } else if (type == 1) { // Radio
195 QStringList urlSplit = name.split('/');
196 QStringList nameSplit = urlSplit.last().split('-');
197 nameSplit.first() = replace;
198 urlSplit.last() = nameSplit.join('-');
199 return urlSplit.join('/');
200 }
201 return name;
202 }
203
204 // Permanently converts the currentDownload object apps to the current 'Download Device'
205 // Important not to change this object during the, rather large, download!
206 void MainNet::fixApps() {
207 if (_i != nullptr) {
208 QPair<QString,QString> results = _i->getConnected(_downloadDevice, _versionRelease.startsWith("10.3.0"));
209 if (results.first == "" && results.second == "")
210 return;
211
212 foreach (Apps* app, currentDownload->apps) {
213 if (results.first != "" && app->type() == "os") {
214 app->setUrl(fixVariantName(app->url(), results.first, 0));
215 app->setName(app->url().split("/").last());
216 app->setFriendlyName(QFileInfo(app->name()).completeBaseName());
217 currentDownload->verifyLink(app->url(), "OS", _downloadDevice == 0 && _i != nullptr && _i->device != nullptr);
218 } else if (results.second != "" && app->type() == "radio") {
219 app->setUrl(fixVariantName(app->url(), results.second, 1));
220 app->setName(app->url().split("/").last());
221 app->setFriendlyName(QFileInfo(app->name()).completeBaseName());
222 currentDownload->verifyLink(app->url(), "Radio", _downloadDevice == 0 && _i != nullptr && _i->device != nullptr);
223 }
224 }
225 // Refresh the names in QML
226 currentDownload->nextFile(0);
227 }
228 }
229
230
231 // Creates a string with a list of URLs based on current 'Search Device'
232 // and converted to current 'Download Device'
233 QString MainNet::convertLinks(QString prepend)
234 {
235 bool convert = true;
236 QPair<QString,QString> results;
237
238 if (_i != nullptr) {
239 results = _i->getConnected(_downloadDevice, _versionRelease.startsWith("10.3.0"));
240 if (results.first == "" && results.second == "")
241 convert = false;
242 }
243
244 QString updated;
245 foreach (Apps* app, _updateAppList) {
246 if (!app->isMarked())
247 continue;
248 QString item = app->url();
249 if (convert) {
250 if (results.first != "" && app->type() == "os")
251 item = fixVariantName(item, results.first, 0);
252 else if (results.second != "" && app->type() == "radio")
253 item = fixVariantName(item, results.second, 1);
254 }
255
256 updated.append(item + "\n");
257 }
258
259 if (convert)
260 updated.prepend(prepend);
261 return updated;
262 }
263
264 void MainNet::downloadLinks(int downloadDevice)
265 {
266 _downloadDevice = downloadDevice;
267 // Have we been here before? Starting but ids already generated. Maybe links were verified, so skip this
268 if (currentDownload->maxId == 0) {
269 currentDownload->setApps(_updateAppList, _versionRelease);
270 fixApps();
271 // Did we find any apps?
272 if (currentDownload->maxId == 0) {
273 currentDownload->reset();
274 return;
275 }
276 }
277 if (currentDownload->toVerify == 0) {
278 currentDownload->download(_downloadDevice == 0 && _i != nullptr && _i->device != nullptr);
279 }
280 }
281
282 QString MainNet::NPCFromLocale(int carrier, int country) {
283 QString homeNPC;
284 homeNPC.sprintf("%03d%03d%d", carrier, country, carrier ? 30 : 60);
285 return homeNPC;
286 }
287
288 QString MainNet::nameFromVariant(unsigned int device, unsigned int variant) {
289 Q_ASSERT(variantCount(device) > variant);
290 return dev[device*2][variant];
291 }
292 QString MainNet::hwidFromVariant(unsigned int device, unsigned int variant) {
293 Q_ASSERT(variantCount(device) > variant);
294 return dev[device*2+1][variant];
295 }
296 unsigned int MainNet::variantCount(unsigned int device) {
297 return dev[device*2].count();
298 }
299
300 void MainNet::updateDetailRequest(QString delta, QString carrier, QString country, int device, int variant, int mode)
301 {
302 QString up;
303 QString requestUrl = "https://cs.sl.blackberry.com/cse/updateDetails/2.2/";
304 QString version = "2.2.1";
305
306 // Blackberry doesn't return results on these servers anymore, so their usefulness is gone
307 /* switch (server)
308 {
309 case 4:
310 requestUrl = "https://alpha2.sl.eval.blackberry.com/slscse/updateDetails/";
311 break;
312 case 3:
313 requestUrl = "https://alpha.sl.eval.blackberry.com/slscse/updateDetails/";
314 break;
315 case 2:
316 requestUrl = "https://beta2.sl.eval.blackberry.com/slscse/updateDetails/";
317 break;
318 case 1:
319 requestUrl = "https://beta.sl.eval.blackberry.com/slscse/updateDetails/";
320 break;
321 case 0:
322 default:
323 requestUrl = "https://cs.sl.blackberry.com/cse/updateDetails/";
324 break;
325 }
326 // Alpha and Beta servers support newer API
327 QString version;
328 switch(server)
329 {
330 case 4:
331 case 3:
332 case 2:
333 case 1:
334 requestUrl += "2.2/"; // They support 2.3
335 version = "2.2.1"; // They support 2.3.0
336 break;
337 case 0:
338 default:
339 requestUrl += "2.2/";
340 version = "2.2.1";
341 break;
342 }*/
343
344 QString homeNPC = NPCFromLocale(carrier.toInt(), country.toInt());
345
346 switch (mode)
347 {
348 case 1:
349 up = "repair";
350 break;
351 case 0:
352 default:
353 up = "upgrade";
354 break;
355 }
356
357 // We either selected 'Any' (if there was more than one variant) or we picked a specific variant.
358 int start = (variant != 0) ? (variant - 1) : 0;
359 int end = (variant != 0) ? variant : variantCount(device);
360 setScanning((variant != 0) ? 1 : variantCount(device));
361 if (_scanning > 1)
362 setMultiscan(true);
363
364 for (int i = start; i < end; i++) {
365 QString query = QString("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
366 "<updateDetailRequest version=\"%1\" authEchoTS=\"%2\">"
367 "<clientProperties>"
368 "<hardware>"
369 "<pin>0x2FFFFFB3</pin><bsn>1128121361</bsn><imei>004401139269240</imei><id>0x%3</id>"
370 "</hardware>"
371 "<network>"
372 "<homeNPC>0x%4</homeNPC><iccid>89014104255505565333</iccid>"
373 "</network>"
374 "<software>"
375 "<currentLocale>en_US</currentLocale><legalLocale>en_US</legalLocale>"
376 "</software>"
377 "</clientProperties>"
378 "<updateDirectives><allowPatching type=\"REDBEND\">true</allowPatching><upgradeMode>%5</upgradeMode><provideDescriptions>false</provideDescriptions><provideFiles>true</provideFiles><queryType>NOTIFICATION_CHECK</queryType></updateDirectives>"
379 "<pollType>manual</pollType>"
380 "<resultPackageSetCriteria>"
381 "%6"
382 "<releaseIndependent><packageType operation=\"include\">application</packageType></releaseIndependent>"
383 "</resultPackageSetCriteria>"
384 "%7"
385 "</updateDetailRequest>")
386 .arg(version) // API Version
387 .arg(QDateTime::currentMSecsSinceEpoch()) // Current time, in case it cares one day
388 .arg(hwidFromVariant(device, i)) // Search Device HWID
389 .arg(homeNPC) // Country + Carrier
390 .arg(up) // Upgrade or Repair?
391 // 2.3.0 doesn't support 'latest'. Does this mean we need to do availableBundles lookup first?
392 .arg((version == "2.3.0") ? "" : "<softwareRelease softwareReleaseVersion=\"latest\" />")
393 .arg(delta); // User installed applications (to support REDBEND patching)
394
395 _error = ""; emit errorChanged();
396 // Pass the variant in the request so it can be retrieved out-of-order
397 QNetworkRequest request;
398 request.setRawHeader("Content-Type", "text/xml;charset=UTF-8");
399 request.setUrl(QUrl(requestUrl));
400 request.setAttribute(QNetworkRequest::CustomVerbAttribute, nameFromVariant(device, i));
401 QNetworkReply* reply = manager->post(request, query.toUtf8());
402 connect(reply, SIGNAL(error(QNetworkReply::NetworkError)),
403 this, SLOT(serverError(QNetworkReply::NetworkError)));
404 connect(reply, SIGNAL(finished()), this, SLOT(serverReply()));
405 }
406 }
407
408 void MainNet::serverReply()
409 {
410 QNetworkReply *reply = (QNetworkReply *)sender();
411 QByteArray data = reply->readAll();
412 //for (int i = 0; i < data.size(); i += 3000) qDebug() << data.mid(i, 3000);
413 showFirmwareData(data, reply->request().attribute(QNetworkRequest::CustomVerbAttribute).toString());
414 sender()->deleteLater();
415 }
416
417 void MainNet::showFirmwareData(QByteArray data, QString variant)
418 {
419 QXmlStreamReader xml(data);
420 QString ver = "";
421 QString os = "";
422 QString radio = "";
423 QString addr = "";
424 QString currentaddr = "";
425 QList<Apps*> newApps;
426 while(!xml.atEnd() && !xml.hasError()) {
427 if(xml.tokenType() == QXmlStreamReader::StartElement) {
428 if (xml.name() == "package")
429 {
430 Apps* newApp = new Apps();
431
432 // Remember: this name *can* change
433 newApp->setFriendlyName(xml.attributes().value("name").toString());
434 // Remember: this name *can* change
435 newApp->setName(xml.attributes().value("path").toString().split('/').last());
436 // Remember: this size *can* change
437 newApp->setSize(xml.attributes().value("downloadSize").toString().toInt());
438 newApp->setVersion(xml.attributes().value("version").toString());
439 newApp->setPackageId(xml.attributes().value("id").toString());
440 newApp->setChecksum(xml.attributes().value("checksum").toString());
441 QString type = xml.attributes().value("type").toString();
442 if (type == "system:os" || type == "system:desktop") {
443 os = newApp->version();
444 newApp->setType("os");
445 newApp->setIsMarked(true);
446 newApp->setIsAvailable(true);
447 if (_i != nullptr && _i->device != nullptr) {
448 newApp->setIsInstalled(isVersionNewer(_i->device->os, newApp->version(), true));
449 newApp->setInstalledVersion(_i->device->os);
450 }
451 } else if (type == "system:radio") {
452 radio = newApp->version();
453 newApp->setType("radio");
454 newApp->setIsMarked(true);
455 newApp->setIsAvailable(true);
456 if (_i != nullptr && _i->device != nullptr) {
457 newApp->setIsInstalled(isVersionNewer(_i->device->radio, newApp->version(), true));
458 newApp->setInstalledVersion(_i->device->radio);
459 }
460 } else {
461 newApp->setType("application");
462 if (_i != nullptr) {
463 foreach(Apps* app, _i->appQList()) {
464 bool isSameApp = newApp->packageId().compare(app->packageId()) == 0;
465 if (isSameApp) {
466 newApp->setIsInstalled(isVersionNewer(app->version(), newApp->version(), true));
467 newApp->setInstalledVersion(app->version());
468 break;
469 }
470 }
471 }
472 }
473 // For lack of a better name, the url
474 newApp->setUrl(currentaddr + "/" + newApp->name());
475 newApp->setName(newApp->name().split("/").last());
476
477 newApps.append(newApp);
478 }
479 else if (xml.name() == "friendlyMessage")
480 {
481 _error = xml.readElementText().split(QChar('.'))[0]; emit errorChanged();
482 }
483 else if (xml.name() == "fileSet")
484 {
485 currentaddr = xml.attributes().value("url").toString();
486 if (addr == "")
487 addr = currentaddr;
488 }
489 else if (xml.name() == "softwareReleaseMetadata")
490 {
491 ver = xml.attributes().value("softwareReleaseVersion").toString();
492 }
493 else if (xml.name() == "bundle")
494 {
495 QString newver = xml.attributes().value("version").toString();
496 if (ver == "" || (ver.split(".").last().toInt() < newver.split(".").last().toInt()))
497 ver = newver;
498 }
499 // No longer check for descriptions
500 /*else if (xml.name() == "description" && desc == "")
501 {
502 desc = xml.readElementText();
503 }*/
504 }
505 xml.readNext();
506 }
507 // Check if the version string is newer.
508 bool isNewer = (!_multiscan || _multiscanVersion == "");
509 if (!isNewer && ver != "") {
510 isNewer = isVersionNewer(ver, _multiscanVersion, false);
511 }
512 if (isNewer) {
513 // Update software release versions
514 if (_multiscan)
515 _multiscanVersion = ver;
516 _versionRelease = ver;
517 if (ver == "") {
518 _updateMessage = "";
519 } else {
520 // Delete old list
521 if (_updateAppList.count()) {
522 foreach (Apps* app, _updateAppList) {
523 app->disconnect(SIGNAL(isMarkedChanged()));
524 app->deleteLater();
525 }
526 _updateAppList.clear();
527 }
528 // Put this new list up for display
529 _updateAppList = newApps;
530 // Connect every isMarkedChanged to the list signal and check if it should be marked
531 foreach (Apps* app, _updateAppList) {
532 connect(app, SIGNAL(isMarkedChanged()), this, SIGNAL(updateCheckedCountChanged()));
533
534 // No need to check OS and Radio as they are variable
535 if (app->type() == "application") {
536 bool exists = QFile(getSaveDir() + "/" + _versionRelease + "/" + app->name()).size() == app->size();
537 app->setIsAvailable(!exists);
538 }
539 app->setIsMarked(app->isAvailable() && !app->isInstalled());
540 }
541 // Server uses some funny order.
542 // Put in order of largest to smallest with OS and Radio first and already downloaded last.
543 std::sort(_updateAppList.begin(), _updateAppList.end(),
544 [=](const Apps* i, const Apps* j) {
545 if (i->type() != "application" && j->type() == "application")
546 return true;
547 if (j->type() != "application" && i->type() == "application")
548 return false;
549 if (i->isMarked() != j->isMarked())
550 return i->isMarked();
551
552 return (i->size() > j->size());
553 }
554 );
555
556 _updateMessage = QString("<b>Update %1 available for %2!</b><br>%3 %4")
557 .arg(ver)
558 .arg(variant)
559 .arg(os != "" ? QString("<b> OS: %1</b>").arg(os) : "")
560 .arg(radio != "" ? QString("<b> Radio: %1</b>").arg(radio) : "");
561
562 _error = ""; emit errorChanged();
563 }
564 // TODO: Putting it here makes user see the values changed. However, putting it below crashes
565 emit updateMessageChanged();
566 emit updateCheckedCountChanged();
567 }
568 setScanning(_scanning-1);
569 // All scans complete
570 if (_scanning <= 0) {
571 setMultiscan(false);
572 }
573 }
574
575 void MainNet::newDeviceConnected()
576 {
577 foreach(Apps* newApp, _updateAppList) {
578 foreach(Apps* app, _i->appQList()) {
579 bool isSameApp = newApp->packageId().compare(app->packageId()) == 0;
580 if (isSameApp) {
581 newApp->setIsInstalled(isVersionNewer(app->version(), newApp->version(), true));
582 newApp->setInstalledVersion(app->version());
583 break;
584 } else {
585 newApp->setIsInstalled(false);
586 newApp->setInstalledVersion("");
587 }
588 }
589 }
590 }
591
592 void MainNet::serverError(QNetworkReply::NetworkError err)
593 {
594 setScanning(_scanning-1);
595 // Only show error if we are doing single scan or multiscan version is empty.
596 if (!_multiscan || (_multiscanVersion == "" && _scanning == 0)) {
597 QString errormsg = QString("Error %1 (%2)")
598 .arg(err)
599 .arg( ((QNetworkReply*)sender())->errorString() );
600 _error = errormsg;
601 emit errorChanged();
602 _updateMessage = ""; emit updateMessageChanged();
603 }
604 if (_scanning == 0)
605 setMultiscan(false);
606 }
607
608 void MainNet::setMultiscan(const bool &multiscan) {
609 _multiscan = multiscan; emit multiscanChanged();
610 _multiscanVersion = ""; emit updateMessageChanged();
611 }
612 void MainNet::setScanning(const int &scanning) { _scanning = scanning; emit scanningChanged(); }
613 void MainNet::setSplitProgress(const int &progress) { if (_splitProgress > 1000) _splitProgress = 0; else _splitProgress = progress; emit splitProgressChanged(); }