summaryrefslogtreecommitdiffstats
path: root/src/manager-lib/packagemanager.cpp
blob: 7e150a66675508507c754334c394a5f5a563b43f (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
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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
// Copyright (C) 2021 The Qt Company Ltd.
// Copyright (C) 2019 Luxoft Sweden AB
// Copyright (C) 2018 Pelagicore AG
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only

#include <QMetaMethod>
#include <QQmlEngine>
#include <QVersionNumber>
#include <QCoreApplication>
#include "packagemanager.h"
#include "packagedatabase.h"
#include "packagemanager_p.h"
#include "architecture.h"
#include "applicationinfo.h"
#include "intentinfo.h"
#include "package.h"
#include "logging.h"
#include "installationreport.h"
#include "exception.h"
#include "sudo.h"
#include "utilities.h"
#if QT_CONFIG(am_installer)
#  include "installationtask.h"
#  include "deinstallationtask.h"
#endif

#if defined(Q_OS_WIN)
#  include <windows.h>
#else
#  include <sys/stat.h>
#  include <errno.h>
#  if defined(Q_OS_ANDROID)
#    include <sys/vfs.h>
#    define statvfs statfs
#  else
#    include <sys/statvfs.h>
#  endif
#endif

#include <memory>

using namespace Qt::StringLiterals;


/*!
    \qmltype PackageManager
    \inqmlmodule QtApplicationManager.SystemUI
    \ingroup system-ui-singletons
    \brief The package installation/removal/update part of the application manager.

    The PackageManager singleton type handles the package installation
    part of the application manager. It provides both a DBus and QML APIs for
    all of its functionality.

    Please also see the \l{Package Installation} documentation for more in-depth information about
    package installations.

    \note Unlike the deprecated ApplicationInstaller class, the PackageManager singleton and its
          corresponding DBus API are always available. Disabling the installer functionality via the
          application manager's \l{Configuration} will just lead to package (de-) installations
          failing instantly.

    Please be aware that setting the \c{applications/installationDirMountPoint} configuration
    option might delay the initialization of the package database. In this case, make sure to check
    that the \l ready property is \c true before interacting with the PackageManager.

    The type is derived from \c QAbstractListModel, so it can be used directly as a model from QML.

    \target PackageManager Roles

    The following roles are available in this model:

    \table
    \header
        \li Role name
        \li Type
        \li Description
    \row
        \li \c packageId
        \li string
        \li The unique ID of a package, represented as a string (e.g. \c Browser or
            \c com.pelagicore.music)
    \row
        \li \c name
        \li string
        \li The name of the package. If possible, already translated to the current locale.
    \row
        \li \c icon
        \li string
        \li The URL of the package's icon.
    \row
        \li \c isBlocked
        \li bool
        \li A boolean value that gets set when the application manager needs to block any
            application within this package from running: this is normally only the case while an
            update is being applied.
    \row
        \li \c isUpdating
        \li bool
        \li A boolean value indicating whether the package is currently being installed or updated.
            If \c true, the \c updateProgress can be used to track the actual progress.
    \row
        \li \c isRemovable
        \li bool
        \li A boolean value indicating whether this package is user-removable; \c true for all
            dynamically installed third party packages and \c false for all system packages.
    \row
        \li \c updateProgress
        \li real
        \li While \c isUpdating is \c true, querying this role returns the actual progress as a
            floating-point value in the \c 0.0 to \c 1.0 range.
    \row
        \li \c categories
        \li list<string>
        \li The categories this package is registered for via its meta-data file.
    \row
        \li \c version
        \li string
        \li The currently installed version of this package.
    \row
        \li \c package
        \li PackageObject
        \li The underlying \l PackageObject for quick access to the properties outside of a
            model delegate.
            \note The name \c package is a reserved JavaScript keyword in \e strict mode, so
            you have to use the \c packageObject role instead if you need to define a
            \c {required property PackageObject package} in your delegate when using \e strict mode.
    \row
        \li \c packageObject
        \li PackageObject
        \li Exactly the same as \c package, but also works in JavaScript \e strict mode.
            This role was introduced in Qt version 6.6.
    \endtable

    \target Task States

    The following table describes all possible states that a background task could be in:

    \table
    \header
        \li Task State
        \li Description
    \row
        \li \c Queued
        \li The task was created and is now queued up for execution.
    \row
        \li \c Executing
        \li The task is being executed.
    \row
        \li \c Finished
        \li The task was executed successfully.
    \row
        \li \c Failed
        \li The task failed to execute successfully.
    \row
        \li \c AwaitingAcknowledge
        \li \e{Installation tasks only!} The task is currently halted, waiting for either
            acknowledgePackageInstallation() or cancelTask() to continue. See startPackageInstallation()
            for more information on the installation workflow.
    \row
        \li \c Installing
        \li \e{Installation tasks only!} The installation was acknowledged via acknowledgePackageInstallation()
            and the final installation phase is now running.
    \row
        \li \c CleaningUp
        \li \e{Installation tasks only!} The installation has finished, and previous installations as
            well as temporary files are being cleaned up.
    \endtable

    The normal workflow for tasks is: \c Queued \unicode{0x2192} \c Executing \unicode{0x2192} \c
    Finished. The task can enter the \c Failed state at any point though - either by being canceled via
    cancelTask() or simply by failing due to an error.

    Installation tasks are a bit more complex due to the acknowledgment: \c Queued \unicode{0x2192}
    \c Executing \unicode{0x2192} \c AwaitingAcknowledge (this state may be skipped if
    acknowledgePackageInstallation() was called already) \unicode{0x2192} \c Installing
    \unicode{0x2192} \c Cleanup \unicode{0x2192} \c Finished. Again, the task can fail at any point.
*/

/*!
    \qmlsignal PackageManager::taskStateChanged(string taskId, string newState)

    This signal is emitted when the state of the task identified by \a taskId changes. The
    new state is supplied in the parameter \a newState.

    \sa taskState()
*/

/*!
    \qmlsignal PackageManager::taskStarted(string taskId)

    This signal is emitted when the task identified by \a taskId enters the \c Executing state.

    \sa taskStateChanged()
*/

/*!
    \qmlsignal PackageManager::taskFinished(string taskId)

    This signal is emitted when the task identified by \a taskId enters the \c Finished state.

    \sa taskStateChanged()
*/

/*!
    \qmlsignal PackageManager::taskFailed(string taskId)

    This signal is emitted when the task identified by \a taskId enters the \c Failed state.

    \sa taskStateChanged()
*/

/*!
    \qmlsignal PackageManager::taskRequestingInstallationAcknowledge(string taskId, PackageObject package, object packageExtraMetaData, object packageExtraSignedMetaData)

    This signal is emitted when the installation task identified by \a taskId has received enough
    meta-data to be able to emit this signal. The task may be in either \c Executing or \c
    AwaitingAcknowledge state.

    A temporary PackageObject is supplied via \a package. Please note, that this object is just
    constructed on the fly for this signal emission and is not part of the PackageManager model.
    The package object is destroyed again after the signal callback returns. Another permanent
    PackageObject that is also part of the model will be constructed later in the installation
    process.

    In addition, the package's extra meta-data (signed and unsinged) is also supplied via \a
    packageExtraMetaData and \a packageExtraSignedMetaData respectively as JavaScript objects.
    Both these objects are optional and need to be explicitly either populated during an
    application's packaging step or added by an intermediary app-store server.
    By default, both will just be empty.

    Following this signal, either cancelTask() or acknowledgePackageInstallation() has to be called
    for this \a taskId, to either cancel the installation or try to complete it.

    The PackageManager has two convenience functions to help the System UI with verifying the
    meta-data: compareVersions() and, in case you are using reverse-DNS notation for application-ids,
    validateDnsName().

    \sa taskStateChanged(), startPackageInstallation()
*/

/*!
    \qmlsignal PackageManager::taskBlockingUntilInstallationAcknowledge(string taskId)

    This signal is emitted when the installation task identified by \a taskId cannot continue
    due to a missing acknowledgePackageInstallation() call for the task.

    \sa taskStateChanged(), acknowledgePackageInstallation()
*/

/*!
    \qmlsignal PackageManager::taskProgressChanged(string taskId, qreal progress)

    This signal is emitted whenever the task identified by \a taskId makes progress towards its
    completion. The \a progress is reported as a floating-point number ranging from \c 0.0 to \c 1.0.

    \sa taskStateChanged()
*/

QT_BEGIN_NAMESPACE_AM

enum PMRoles
{
    Id = Qt::UserRole,
    Name,
    Description,
    Icon,

    IsBlocked,
    IsUpdating,
    IsRemovable,

    UpdateProgress,

    Version,
    PackageItem,
    PackageObject, // needed, because "package" is a reserved JS keyword in "strict" mode
};

PackageManager *PackageManager::s_instance = nullptr;
QHash<int, QByteArray> PackageManager::s_roleNames;

PackageManager *PackageManager::createInstance(PackageDatabase *packageDatabase,
                                               const QString &documentPath)
{
    if (Q_UNLIKELY(s_instance))
        qFatal("PackageManager::createInstance() was called a second time.");

    Q_ASSERT(packageDatabase);

    std::unique_ptr<PackageManager> pm(new PackageManager(packageDatabase, documentPath));
    registerQmlTypes();

    return s_instance = pm.release();
}

PackageManager *PackageManager::instance()
{
    if (!s_instance)
        qFatal("PackageManager::instance() was called before createInstance().");
    return s_instance;
}

void PackageManager::enableInstaller()
{
    d->enableInstaller = QT_CONFIG(am_installer);
}

void PackageManager::registerPackages()
{
    qCDebug(LogSystem) << "Registering packages:";

    // collect all updates to builtin first, so we can avoid re-creating a lot of objects,
    // if we find an update to a builtin app later on
    QMap<QString, QPair<PackageInfo *, PackageInfo *>> pkgs;

    // map all the built-in packages first
    const auto builtinPackages = d->database->builtInPackages();
    for (auto packageInfo : builtinPackages) {
        auto existingPackageInfos = pkgs.value(packageInfo->id());
        if (existingPackageInfos.first) {
            throw Exception(Error::Package, "Found more than one built-in package with id '%1': here: %2 and there: %3")
                    .arg(packageInfo->id())
                    .arg(existingPackageInfos.first->manifestPath())
                    .arg(packageInfo->manifestPath());
        }
        pkgs.insert(packageInfo->id(), qMakePair(packageInfo, nullptr));
    }

    // next, map all the installed packages, making sure to detect updates to built-in ones
    const auto installedPackages = d->database->installedPackages();
    for (auto packageInfo : installedPackages) {
        auto existingPackageInfos = pkgs.value(packageInfo->id());
        if (existingPackageInfos.first) {
            if (existingPackageInfos.first->isBuiltIn()) { // update
                if (existingPackageInfos.second) { // but there already is an update applied!?
                    throw Exception(Error::Package, "Found more than one update for the built-in package with id '%1' here: %2 and there: %3")
                            .arg(packageInfo->id())
                            .arg(existingPackageInfos.second->manifestPath())
                            .arg(packageInfo->manifestPath());
                }
                pkgs[packageInfo->id()] = qMakePair(existingPackageInfos.first, packageInfo);

            } else {
                throw Exception(Error::Package, "Found more than one installed package with the same id '%1' here: %2 and there: %3")
                        .arg(packageInfo->id())
                        .arg(existingPackageInfos.first->manifestPath())
                        .arg(packageInfo->manifestPath());
            }
        } else {
            pkgs.insert(packageInfo->id(), qMakePair(packageInfo, nullptr));
        }
    }
    for (auto it = pkgs.constBegin(); it != pkgs.constEnd(); ++it)
        registerPackage(it.value().first, it.value().second);

    // now that we have a consistent pkg db, we can clean up the installed packages
    cleanupBrokenInstallations();

    emit readyChanged(d->cleanupBrokenInstallationsDone);

#if QT_CONFIG(am_installer)
    // something might have been queued already before the cleanup had finished
    triggerExecuteNextTask();
#endif
}

Package *PackageManager::registerPackage(PackageInfo *packageInfo, PackageInfo *updatedPackageInfo,
                                         bool currentlyBeingInstalled)
{
    auto *package = new Package(packageInfo, currentlyBeingInstalled ? Package::BeingInstalled
                                                                     : Package::Installed);
    if (updatedPackageInfo)
        package->setUpdatedInfo(updatedPackageInfo);

    QQmlEngine::setObjectOwnership(package, QQmlEngine::CppOwnership);

    if (currentlyBeingInstalled) {
        Q_ASSERT(package->isBlocked());

        beginInsertRows(QModelIndex(), int(d->packages.count()), int(d->packages.count()));
        qCDebug(LogSystem) << "Installing package:";
    }

    d->packages << package;

    qCDebug(LogSystem).nospace().noquote() << " + package: " << package->id() << " [at: "
                                           << QDir().relativeFilePath(package->info()->baseDir().path()) << "]";

    if (currentlyBeingInstalled) {
        endInsertRows();
        emitDataChanged(package);
    }

    emit packageAdded(package->id());

    if (!currentlyBeingInstalled)
        registerApplicationsAndIntentsOfPackage(package);

    return package;
}

void PackageManager::registerApplicationsAndIntentsOfPackage(Package *package)
{
    const auto appInfos = package->info()->applications();
    for (auto appInfo : appInfos) {
        try {
            emit internalSignals.registerApplication(appInfo, package);
        } catch (const Exception &e) {
            qCWarning(LogSystem) << "Cannot register application" << appInfo->id() << ":"
                                 << e.errorString();
        }
    }

    const auto intentInfos = package->info()->intents();
    for (auto intentInfo : intentInfos) {
        try {
            emit internalSignals.registerIntent(intentInfo, package);
        } catch (const Exception &e) {
            qCWarning(LogSystem) << "Cannot register intent" << intentInfo->id() << ":"
                                 << e.errorString();
        }
    }
}

void PackageManager::unregisterApplicationsAndIntentsOfPackage(Package *package)
{
    const auto intentInfos = package->info()->intents();
    for (auto intentInfo : intentInfos) {
        try {
            emit internalSignals.unregisterIntent(intentInfo, package); // not throwing ATM
        } catch (const Exception &e) {
            qCWarning(LogSystem) << "Cannot unregister intent" << intentInfo->id() << ":"
                                 << e.errorString();
        }
    }

    const auto appInfos = package->info()->applications();
    for (auto appInfo : appInfos) {
        try {
            emit internalSignals.unregisterApplication(appInfo, package); // not throwing ATM
        } catch (const Exception &e) {
            qCWarning(LogSystem) << "Cannot unregister application" << appInfo->id() << ":"
                                 << e.errorString();
        }
    }
}

QVector<Package *> PackageManager::packages() const
{
    return d->packages;
}

void PackageManager::registerQmlTypes()
{
    qRegisterMetaType<Package *>("Package*");

    s_roleNames.insert(PMRoles::Id, "packageId");
    s_roleNames.insert(PMRoles::Name, "name");
    s_roleNames.insert(PMRoles::Description, "description");
    s_roleNames.insert(PMRoles::Icon, "icon");
    s_roleNames.insert(PMRoles::IsBlocked, "isBlocked");
    s_roleNames.insert(PMRoles::IsUpdating, "isUpdating");
    s_roleNames.insert(PMRoles::IsRemovable, "isRemovable");
    s_roleNames.insert(PMRoles::UpdateProgress, "updateProgress");
    s_roleNames.insert(PMRoles::Version, "version");
    s_roleNames.insert(PMRoles::PackageItem, "package"); // "package" is a reserved JS keyword in "strict" mode
    s_roleNames.insert(PMRoles::PackageObject, "packageObject");
}

PackageManager::PackageManager(PackageDatabase *packageDatabase,
                               const QString &documentPath)
    : QAbstractListModel()
    , d(new PackageManagerPrivate())
{
    d->database = packageDatabase;
    d->installationPath = packageDatabase->installedPackagesDir();
    d->documentPath = documentPath;
}

PackageManager::~PackageManager()
{
    qDeleteAll(d->packages);
    delete d->database;
    delete d;
    s_instance = nullptr;
}

Package *PackageManager::fromId(const QString &id) const
{
    for (auto package : d->packages) {
        if (package->id() == id)
            return package;
    }
    return nullptr;
}

QVariantMap PackageManager::get(Package *package) const
{
    QVariantMap map;
    if (package) {
        QHash<int, QByteArray> roles = roleNames();
        for (auto it = roles.begin(); it != roles.end(); ++it)
            map.insert(QString::fromLatin1(it.value()), dataForRole(package, it.key()));
    }
    return map;
}

void PackageManager::emitDataChanged(Package *package, const QVector<int> &roles)
{
    qsizetype row = d->packages.indexOf(package);
    if (row >= 0) {
        emit dataChanged(index(int(row)), index(int(row)), roles);

        static const auto pkgChanged = QMetaMethod::fromSignal(&PackageManager::packageChanged);
        if (isSignalConnected(pkgChanged)) {
            QStringList stringRoles;
            stringRoles.reserve(roles.count());
            for (auto role : roles)
                stringRoles << QString::fromLatin1(s_roleNames[role]);
            emit packageChanged(package->id(), stringRoles);
        }
    }
}

// item model part

int PackageManager::rowCount(const QModelIndex &parent) const
{
    if (parent.isValid())
        return 0;
    return int(d->packages.count());
}

QVariant PackageManager::data(const QModelIndex &index, int role) const
{
    if (index.parent().isValid() || !index.isValid())
        return QVariant();

    Package *package = d->packages.at(index.row());
    return dataForRole(package, role);
}

QVariant PackageManager::dataForRole(Package *package, int role) const
{
    switch (role) {
    case PMRoles::Id:
        return package->id();
    case PMRoles::Name:
        return package->name();
    case PMRoles::Description:
        return package->description();
    case PMRoles::Icon:
        return package->icon();
    case PMRoles::IsBlocked:
        return package->isBlocked();
    case PMRoles::IsUpdating:
        return package->state() != Package::Installed;
    case PMRoles::UpdateProgress:
        return package->progress();
    case PMRoles::IsRemovable:
        return !package->isBuiltIn();
    case PMRoles::Version:
        return package->version();
    case PMRoles::PackageItem:
    case PMRoles::PackageObject:
        return QVariant::fromValue(package);
    default:
        return QVariant();
    }
}

QHash<int, QByteArray> PackageManager::roleNames() const
{
    return s_roleNames;
}

int PackageManager::count() const
{
    return rowCount();
}

/*!
    \qmlmethod object PackageManager::get(int index)

    Retrieves the model data at \a index as a JavaScript object. See the
    \l {PackageManager Roles}{role names} for the expected object fields.

    Returns an empty object if the specified \a index is invalid.

    \note This is very inefficient if you only want to access a single property from QML; use
          package() instead to access the PackageObject's properties directly.
*/
QVariantMap PackageManager::get(int index) const
{
    if (index < 0 || index >= count()) {
        qCWarning(LogSystem) << "PackageManager::get(index): invalid index:" << index;
        return QVariantMap();
    }
    return get(d->packages.at(index));
}

/*!
    \qmlmethod PackageObject PackageManager::package(int index)

    Returns the PackageObject corresponding to the given \a index in the model, or \c null if the
    index is invalid.

    \note The object ownership of the returned PackageObject stays with the application manager.
          If you want to store this pointer, you can use the PackageManager's QAbstractListModel
          signals or the packageAboutToBeRemoved signal to get notified if the object is about
          to be deleted on the C++ side.
*/
Package *PackageManager::package(int index) const
{
    if (index < 0 || index >= count()) {
        qCWarning(LogSystem) << "PackageManager::package(index): invalid index:" << index;
        return nullptr;
    }
    return d->packages.at(index);
}

/*!
    \qmlmethod PackageObject PackageManager::package(string id)

    Returns the PackageObject corresponding to the given package \a id, or \c null if the id does
    not exist.

    \note The object ownership of the returned PackageObject stays with the application manager.
          If you want to store this pointer, you can use the PackageManager's QAbstractListModel
          signals or the packageAboutToBeRemoved signal to get notified if the object is about
          to be deleted on the C++ side.
*/
Package *PackageManager::package(const QString &id) const
{
    auto index = indexOfPackage(id);
    return (index < 0) ? nullptr : package(index);
}

/*!
    \qmlmethod int PackageManager::indexOfPackage(string id)

    Maps the package \a id to its position within the model.

    Returns \c -1 if the specified \a id is invalid.
*/
int PackageManager::indexOfPackage(const QString &id) const
{
    for (int i = 0; i < d->packages.size(); ++i) {
        if (d->packages.at(i)->id() == id)
            return i;
    }
    return -1;
}

/*!
    \qmlproperty bool PackageManager::ready

    Loading the package database might be delayed at startup if the
    \c{applications/installationDirMountPoint} configuration option is set.

    If your system is relying on this behavior, you should always check if the \l ready property is
    \c true before accessing information about installed packages.
    \note Calls to startPackageInstallation() and removePackage() while ready is still \c false
          will be queued and executed once the package database is fully loaded.
*/
bool PackageManager::isReady() const
{
    return d->cleanupBrokenInstallationsDone;
}

/*!
    \qmlproperty bool PackageManager::developmentMode
    \readonly

    This readonly property reflects the \l{development-mode}{\c developmentMode} setting in the
    configuration file.
*/
bool PackageManager::developmentMode() const
{
    return d->developmentMode;
}

void PackageManager::setDevelopmentMode(bool enable)
{
    d->developmentMode = enable;
}

/*!
    \qmlproperty string PackageManager::allowInstallationOfUnsignedPackages
    \readonly

    This readonly property reflects the \l{allow-unsigned-packages}{\c allowUnsignedPackages}
    setting in the configuration file.
*/
bool PackageManager::allowInstallationOfUnsignedPackages() const
{
    return d->allowInstallationOfUnsignedPackages;
}

void PackageManager::setAllowInstallationOfUnsignedPackages(bool enable)
{
    d->allowInstallationOfUnsignedPackages = enable;
}

/*!
    \qmlproperty string PackageManager::hardwareId
    \readonly

    This property will return the \l{The Hardware ID}{hardware id} for the current system.

    Package repositories (like for example the appman-package-server) can use these hardware ids
    to limit the distribution of packages to specific devices via digital signatures.
*/
QString PackageManager::hardwareId() const
{
    return d->hardwareId;
}

void PackageManager::setHardwareId(const QString &hwId)
{
    d->hardwareId = hwId;
}

/*!
    \qmlproperty string PackageManager::architecture
    \readonly

    A unique string identifying the architecture of the current system.

    Package repositories (like for example the appman-package-server) can use these identifiers
    to support multiple architecture-specific builds of the same package.
*/
QString PackageManager::architecture() const
{
    return Architecture::identify(QCoreApplication::applicationFilePath());
}

QByteArrayList PackageManager::caCertificates() const
{
    return d->chainOfTrust;
}

void PackageManager::setCACertificates(const QByteArrayList &chainOfTrust)
{
    d->chainOfTrust = chainOfTrust;
}

static QVariantMap locationMap(const QString &path)
{
    QString cpath = QFileInfo(path).canonicalPath();
    quint64 bytesTotal = 0;
    quint64 bytesFree = 0;

#if defined(Q_OS_WIN)
    GetDiskFreeSpaceExW((LPCWSTR) cpath.utf16(), (ULARGE_INTEGER *) &bytesFree,
                        (ULARGE_INTEGER *) &bytesTotal, nullptr);

#else // Q_OS_UNIX
    int result;
    struct ::statvfs svfs;

    do {
        result = ::statvfs(cpath.toLocal8Bit(), &svfs);
        if (result == -1 && errno == EINTR)
            continue;
    } while (false);

    if (result == 0) {
        bytesTotal = quint64(svfs.f_frsize) * svfs.f_blocks;
        bytesFree = quint64(svfs.f_frsize) * svfs.f_bavail;
    }
#endif // Q_OS_WIN


    return QVariantMap {
        { u"path"_s, path },
        { u"deviceSize"_s, bytesTotal },
        { u"deviceFree"_s, bytesFree }
    };
}

/*!
    \qmlproperty object PackageManager::installationLocation

    Returns an object describing the location under which packages are installed in detail.

    The returned object has the following members:

    \table
    \header
        \li \c Name
        \li \c Type
        \li Description
    \row
        \li \c path
        \li \c string
        \li The absolute file-system path to the base directory.
    \row
        \li \c deviceSize
        \li \c int
        \li The size of the device holding \c path in bytes.
    \row
        \li \c deviceFree
        \li \c int
        \li The amount of bytes available on the device holding \c path.
    \endtable

    Returns an empty object in case the installer component is disabled.
*/
QVariantMap PackageManager::installationLocation() const
{
    return locationMap(d->installationPath);
}

/*!
    \qmlproperty object PackageManager::documentLocation

    Returns an object describing the location under which per-user document
    directories are created in detail.

    The returned object has the same members as described in PackageManager::installationLocation.
*/
QVariantMap PackageManager::documentLocation() const
{
    return d->documentPath.isEmpty() ? QVariantMap { } : locationMap(d->documentPath);
}

bool PackageManager::isPackageInstallationActive(const QString &packageId) const
{
#if QT_CONFIG(am_installer)
    for (const auto *t : std::as_const(d->installationTaskList)) {
        if (t->packageId() == packageId)
            return true;
    }
#else
    Q_UNUSED(packageId)
#endif
    return false;
}

void PackageManager::cleanupBrokenInstallations() noexcept(false)
{
    if (d->cleanupBrokenInstallationsDone)
        return;

#if QT_CONFIG(am_installer)
    // Check that everything in the app-db is available
    //    -> if not, remove from app-db

    // key: baseDirPath, value: subDirName/ or fileName
    QMultiMap<QString, QString> validPaths;
    if (!d->documentPath.isEmpty())
        validPaths.insert(d->documentPath, QString());
    if (!d->installationPath.isEmpty())
        validPaths.insert(d->installationPath, QString());

    for (Package *pkg : d->packages) { // we want to detach here!
        const InstallationReport *ir = pkg->info()->installationReport();
        if (ir) {
            bool valid = true;

            QString pkgDir = d->installationPath + QDir::separator() + pkg->id();
            QStringList checkDirs;
            QStringList checkFiles;

            checkFiles << pkgDir + u"/info.yaml"_s;
            checkFiles << pkgDir + u"/.installation-report.yaml"_s;
            checkDirs << pkgDir;

            for (const QString &checkFile : std::as_const(checkFiles)) {
                QFileInfo fi(checkFile);
                if (!fi.exists() || !fi.isFile() || !fi.isReadable()) {
                    valid = false;
                    qCDebug(LogInstaller) << "cleanup: uninstalling" << pkg->id() << "- file missing:" << checkFile;
                    break;
                }
            }
            for (const QString &checkDir : checkDirs) {
                QFileInfo fi(checkDir);
                if (!fi.exists() || !fi.isDir() || !fi.isReadable()) {
                    valid = false;
                    qCDebug(LogInstaller) << "cleanup: uninstalling" << pkg->id() << "- directory missing:" << checkDir;
                    break;
                }
            }

            if (valid) {
                validPaths.insert(d->installationPath, pkg->id() + QDir::separator());
                if (!d->documentPath.isEmpty())
                    validPaths.insert(d->documentPath, pkg->id() + QDir::separator());
            } else {
                if (startingPackageRemoval(pkg->id())) {
                    if (finishedPackageInstall(pkg->id()))
                        continue;
                }
                throw Exception(Error::Package, "could not remove broken installation of package %1 from database").arg(pkg->id());
            }
        }
    }

    // Remove everything that is not referenced from the app-db

    for (auto it = validPaths.cbegin(); it != validPaths.cend(); ) {
        const QString currentDir = it.key();

        // collect all values for the unique key currentDir
        QStringList validNames;
        for ( ; it != validPaths.cend() && it.key() == currentDir; ++it)
            validNames << it.value();

        const QFileInfoList &dirEntries = QDir(currentDir).entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot);

        // check if there is anything in the filesystem that is NOT listed in the validNames
        for (const QFileInfo &fi : dirEntries) {
            QString name = fi.fileName();
            if (fi.isDir())
                name.append(QDir::separator());

            if ((!fi.isDir() && !fi.isFile()) || !validNames.contains(name)) {
                qCDebug(LogInstaller) << "cleanup: removing unreferenced inode" << name;

                if (!removeRecursiveHelper(fi.absoluteFilePath())) {
                    throw Exception(Error::IO, "could not remove broken installation leftover %1 (maybe due to missing root privileges)")
                        .arg(fi.absoluteFilePath());
                }
            }
        }
    }
#endif // QT_CONFIG(am_installer)

    d->cleanupBrokenInstallationsDone = true;
}

/*!
    \qmlmethod list<string> PackageManager::packageIds()

    Returns a list of all available package ids. This can be used to further query for specific
    information via get().
*/
QStringList PackageManager::packageIds() const
{
    QStringList ids;
    ids.reserve(d->packages.size());
    for (int i = 0; i < d->packages.size(); ++i)
        ids << d->packages.at(i)->id();
    return ids;
}

/*!
    \qmlmethod object PackageManager::get(string packageId)

    Retrieves the model data for the package identified by \a packageId as a JavaScript object.
    See the \l {PackageManager Roles}{role names} for the expected object fields.

    Returns an empty object if the specified \a packageId is invalid.

    \note This is very inefficient if you only want to access a single property from QML; use
          package() instead to access the PackageObject's properties directly.
*/
QVariantMap PackageManager::get(const QString &packageId) const
{
    return get(package(packageId));
}

/*!
   \qmlmethod int PackageManager::installedPackageSize(string packageId)

   Returns the size in bytes that the package identified by \a packageId is occupying on the storage
   device.

   Returns \c -1 in case the package \a packageId is not valid, or the package is not installed.
*/
qint64 PackageManager::installedPackageSize(const QString &packageId) const
{
    if (Package *package = fromId(packageId)) {
        if (const InstallationReport *report = package->info()->installationReport())
            return static_cast<qint64>(report->diskSpaceUsed());
    }
    return -1;
}

/*!
   \qmlmethod var PackageManager::installedPackageExtraMetaData(string packageId)

   Returns a map of all extra metadata in the package header of the package identified by \a packageId.

   Returns an empty map in case the package \a packageId is not valid, or the package is not installed.
*/
QVariantMap PackageManager::installedPackageExtraMetaData(const QString &packageId) const
{
    if (Package *package = fromId(packageId)) {
        if (const InstallationReport *report = package->info()->installationReport())
            return report->extraMetaData();
    }
    return QVariantMap();
}

/*!
   \qmlmethod var PackageManager::installedPackageExtraSignedMetaData(string packageId)

   Returns a map of all signed extra metadata in the package header of the package identified
   by \a packageId.

   Returns an empty map in case the package \a packageId is not valid, or the package is not installed.
*/
QVariantMap PackageManager::installedPackageExtraSignedMetaData(const QString &packageId) const
{
    if (Package *package = fromId(packageId)) {
        if (const InstallationReport *report = package->info()->installationReport())
            return report->extraSignedMetaData();
    }
    return QVariantMap();
}

/*! \internal
  Type safe convenience function, since DBus does not like QUrl
*/
QString PackageManager::startPackageInstallation(const QUrl &sourceUrl)
{
    AM_TRACE(LogInstaller, sourceUrl)

#if QT_CONFIG(am_installer)
    if (d->enableInstaller)
        return enqueueTask(new InstallationTask(d->installationPath, d->documentPath, sourceUrl));
#endif
    return QString();
}

/*!
    \qmlmethod string PackageManager::startPackageInstallation(string sourceUrl)

    Downloads an application package from \a sourceUrl and installs it.

    The actual download and installation will happen asynchronously in the background. The
    PackageManager emits the signals \l taskStarted, \l taskProgressChanged, \l
    taskRequestingInstallationAcknowledge, \l taskFinished, \l taskFailed, and \l taskStateChanged
    for the returned taskId when applicable.

    \note Simply calling this function is not enough to complete a package installation: The
    taskRequestingInstallationAcknowledge() signal needs to be connected to a slot where the
    supplied package meta-data can be validated (either programmatically or by asking the user).
    If the validation is successful, the installation can be completed by calling
    acknowledgePackageInstallation() or, if the validation was unsuccessful, the installation should
    be canceled by calling cancelTask().
    Failing to do one or the other will leave an unfinished "zombie" installation.

    Returns a unique \c taskId. This can also be an empty string, if the task could not be
    created (in this case, no signals will be emitted).
*/
QString PackageManager::startPackageInstallation(const QString &sourceUrl)
{
    QUrl url(sourceUrl);
    if (url.scheme().isEmpty()
#if defined(Q_OS_WINDOWS)
        || (url.scheme().size() == 1) // "c:" is not a protocol
#endif
    ) {
        url = QUrl::fromLocalFile(sourceUrl);
    }
    return startPackageInstallation(url);
}

/*!
    \qmlmethod void PackageManager::acknowledgePackageInstallation(string taskId)

    Calling this function enables the installer to complete the installation task identified by \a
    taskId. Normally, this function is called after receiving the taskRequestingInstallationAcknowledge()
    signal, and the user and/or the program logic decided to proceed with the installation.

    \sa startPackageInstallation()
 */
void PackageManager::acknowledgePackageInstallation(const QString &taskId)
{
    AM_TRACE(LogInstaller, taskId)

#if QT_CONFIG(am_installer)
    if (d->enableInstaller) {
        const auto allTasks = d->allTasks();

        for (AsynchronousTask *task : allTasks) {
            if (qobject_cast<InstallationTask *>(task) && (task->id() == taskId)) {
                static_cast<InstallationTask *>(task)->acknowledge();
                break;
            }
        }
    }
#endif
}

/*!
    \qmlmethod string PackageManager::removePackage(string packageId, bool keepDocuments, bool force)

    Uninstalls the package identified by \a packageId. Normally, the documents directory of the
    package is deleted on removal, but this can be prevented by setting \a keepDocuments to \c true.

    The actual removal will happen asynchronously in the background. The PackageManager will
    emit the signals \l taskStarted, \l taskProgressChanged, \l taskFinished, \l taskFailed and \l
    taskStateChanged for the returned \c taskId when applicable.

    Normally, \a force should only be set to \c true if a previous call to removePackage() failed.
    This may be necessary if the installation process was interrupted, or or has file-system issues.

    Returns a unique \c taskId. This can also be an empty string, if the task could not be created
    (in this case, no signals will be emitted).
*/
QString PackageManager::removePackage(const QString &packageId, bool keepDocuments, bool force)
{
    AM_TRACE(LogInstaller, packageId, keepDocuments, force)

#if QT_CONFIG(am_installer)
    if (d->enableInstaller) {
        if (fromId(packageId)) {
            return enqueueTask(new DeinstallationTask(packageId, d->installationPath,
                                                      d->documentPath, force, keepDocuments));
        }
    }
#endif
    return QString();
}


/*!
    \qmlmethod enumeration PackageManager::taskState(string taskId)

    Returns the current state of the installation task identified by \a taskId.
    \l {Task States}{See here} for a list of valid task states.

    Returns \c PackageManager.Invalid if the \a taskId is invalid.
*/
AsynchronousTask::TaskState PackageManager::taskState(const QString &taskId) const
{
#if QT_CONFIG(am_installer)
    if (d->enableInstaller) {
        const auto allTasks = d->allTasks();

        for (const AsynchronousTask *task : allTasks) {
            if (task && (task->id() == taskId))
                return task->state();
        }
    }
#else
    Q_UNUSED(taskId)
#endif
    return AsynchronousTask::Invalid;
}

/*!
    \qmlmethod string PackageManager::taskPackageId(string taskId)

    Returns the package id associated with the task identified by \a taskId. The task may not
    have a valid package id at all times though and in this case the function will return an
    empty string (this will be the case for installations before the taskRequestingInstallationAcknowledge
    signal has been emitted).

    Returns an empty string if the \a taskId is invalid.
*/
QString PackageManager::taskPackageId(const QString &taskId) const
{
#if QT_CONFIG(am_installer)
    if (d->enableInstaller) {
        const auto allTasks = d->allTasks();

        for (const AsynchronousTask *task : allTasks) {
            if (task && (task->id() == taskId))
                return task->packageId();
        }
    }
#else
    Q_UNUSED(taskId)
#endif
    return QString();
}

/*!
    \qmlmethod list<string> PackageManager::activeTaskIds()

    Retuns a list of all currently active (as in not yet finished or failed) installation task ids.
*/
QStringList PackageManager::activeTaskIds() const
{
    QStringList result;
#if QT_CONFIG(am_installer)
    if (d->enableInstaller) {
        const auto allTasks = d->allTasks();
        result.reserve(allTasks.size());

        for (const AsynchronousTask *task : allTasks)
            result << task->id();
    }
#endif
    return result;
}

/*!
    \qmlmethod bool PackageManager::cancelTask(string taskId)

    Tries to cancel the installation task identified by \a taskId.

    Returns \c true if the task was canceled, \c false otherwise.
*/
bool PackageManager::cancelTask(const QString &taskId)
{
    AM_TRACE(LogInstaller, taskId)

#if QT_CONFIG(am_installer)
    if (d->enableInstaller) {
        // incoming tasks can be forcefully canceled right away
        for (AsynchronousTask *task : std::as_const(d->incomingTaskList)) {
            if (task->id() == taskId) {
                task->forceCancel();
                task->deleteLater();

                handleFailure(task);

                d->incomingTaskList.removeOne(task);
                triggerExecuteNextTask();
                return true;
            }
        }

        // the active task and async tasks might be in a state where cancellation is not possible,
        // so we have to ask them nicely
        if (d->activeTask && d->activeTask->id() == taskId)
            return d->activeTask->cancel();

        for (AsynchronousTask *task : std::as_const(d->installationTaskList)) {
            if (task->id() == taskId)
                return task->cancel();
        }
    }
#endif
    return false;
}

QString PackageManager::enqueueTask(AsynchronousTask *task)
{
#if QT_CONFIG(am_installer)
    d->incomingTaskList.append(task);
    triggerExecuteNextTask();
    return task->id();
#else
    Q_UNUSED(task)
    Q_ASSERT_X(false, "PackageManager::enqueueTask", "Installer is disabled");
    return { };
#endif
}

void PackageManager::triggerExecuteNextTask()
{
#if QT_CONFIG(am_installer)
    if (!QMetaObject::invokeMethod(this, &PackageManager::executeNextTask, Qt::QueuedConnection))
        qCCritical(LogSystem) << "ERROR: failed to invoke method checkQueue";
#else
    Q_ASSERT_X(false, "PackageManager::triggerExecuteNextTask", "Installer is disabled");
#endif
}

void PackageManager::executeNextTask()
{
#if QT_CONFIG(am_installer)
    if (!d->cleanupBrokenInstallationsDone || d->activeTask || d->incomingTaskList.isEmpty())
        return;

    AsynchronousTask *task = d->incomingTaskList.takeFirst();

    if (task->state() == AsynchronousTask::Failed) {
        handleFailure(task);

        task->deleteLater();
        triggerExecuteNextTask();
        return;
    }

    connect(task, &AsynchronousTask::started, this, [this, task]() {
        emit taskStarted(task->id());
    });

    connect(task, &AsynchronousTask::stateChanged, this, [this, task](AsynchronousTask::TaskState newState) {
        emit taskStateChanged(task->id(), newState);
    });

    connect(task, &AsynchronousTask::progress, this, [this, task](qreal p) {
        emit taskProgressChanged(task->id(), p);

        Package *package = fromId(task->packageId());
        if (package && (package->state() != Package::Installed)) {
            package->setProgress(p);
            // Icon will be in a "+" suffixed directory during installation. So notify about a change on its
            // location as well.
            emitDataChanged(package, QVector<int> { PMRoles::Icon, PMRoles::UpdateProgress });
        }
    });

    connect(task, &AsynchronousTask::finished, this, [this, task]() {
        if (task->state() == AsynchronousTask::Failed) {
            handleFailure(task);
        } else {
            task->setState(AsynchronousTask::Finished);
            qCDebug(LogInstaller) << "emit finished" << task->id();
            emit taskFinished(task->id());
        }

        if (d->activeTask == task)
            d->activeTask = nullptr;
        d->installationTaskList.removeOne(task);

        delete task;
        triggerExecuteNextTask();
    });

    if (qobject_cast<InstallationTask *>(task)) {
        connect(static_cast<InstallationTask *>(task), &InstallationTask::finishedPackageExtraction, this, [this, task]() {
            qCDebug(LogInstaller) << "emit blockingUntilInstallationAcknowledge" << task->id();
            emit taskBlockingUntilInstallationAcknowledge(task->id());

            // we can now start the next download in parallel - the InstallationTask will take care
            // of serializing the final installation steps on its own as soon as it gets the
            // required acknowledge (or cancel).
            if (d->activeTask == task)
                d->activeTask = nullptr;
            d->installationTaskList.append(task);
            triggerExecuteNextTask();
        });
    }


    d->activeTask = task;
    task->setState(AsynchronousTask::Executing);
    task->start();
#else
    Q_ASSERT_X(false, "PackageManager::executeNextTask", "Installer is disabled");
#endif
}

void PackageManager::handleFailure(AsynchronousTask *task)
{
#if QT_CONFIG(am_installer)
    qCDebug(LogInstaller) << "emit failed" << task->id() << task->errorCode() << task->errorString();
    emit taskFailed(task->id(), int(task->errorCode()), task->errorString());
#else
    Q_UNUSED(task)
    Q_ASSERT_X(false, "PackageManager::handleFailure", "Installer is disabled");
#endif
}

Package *PackageManager::startingPackageInstallation(PackageInfo *info)
{
    // ownership of info is transferred to PackageManager
    std::unique_ptr<PackageInfo> newInfo(info);

    if (!newInfo || newInfo->id().isEmpty())
        return nullptr;

    Package *package = fromId(newInfo->id());

    if (package) { // update
        if (!package->block())
            return nullptr;

        // do not overwrite the base-info / update-info yet - only after a successful installation
        d->pendingPackageInfoUpdates.insert(package, newInfo.release());

        package->setState(Package::BeingUpdated);
        package->setProgress(0);
        emitDataChanged(package);
        return package;

    } else { // installation
        // add a new package to the model and block it
        return registerPackage(newInfo.release(), nullptr, true);
    }
}

bool PackageManager::startingPackageRemoval(const QString &id)
{
    Package *package = fromId(id);
    if (!package)
        return false;

    if (package->isBlocked() || (package->state() != Package::Installed))
        return false;

    if (package->isBuiltIn() && !package->builtInHasRemovableUpdate())
        return false;

    if (!package->block()) // this will implicitly stop all apps in this package (asynchronously)
        return false;

    package->setState(package->builtInHasRemovableUpdate() ? Package::BeingDowngraded
                                                           : Package::BeingRemoved);

    package->setProgress(0);
    emitDataChanged(package, QVector<int> { PMRoles::IsUpdating });
    return true;
}

bool PackageManager::finishedPackageInstall(const QString &id)
{
    Package *package = fromId(id);
    if (!package)
        return false;

    switch (package->state()) {
    case Package::Installed:
        return false;

    case Package::BeingUpdated:
    case Package::BeingInstalled:
    case Package::BeingDowngraded: {
        bool isUpdate = (package->state() == Package::BeingUpdated);
        bool isDowngrade = (package->state() == Package::BeingDowngraded);

        // figure out what the new info is
        PackageInfo *newPackageInfo;
        if (isUpdate)
            newPackageInfo = d->pendingPackageInfoUpdates.take(package);
        else if (isDowngrade)
            newPackageInfo = nullptr;
        else
            newPackageInfo = package->baseInfo();

        // attach the installation report (unless we're just downgrading a built-in)
        if (!isDowngrade) {
            QFile irfile(newPackageInfo->baseDir().absoluteFilePath(u".installation-report.yaml"_s));
            auto ir = std::make_unique<InstallationReport>(package->id());
            irfile.open(QFile::ReadOnly);
            try {
                ir->deserialize(&irfile);
            } catch (const Exception &e) {
                qCCritical(LogInstaller) << "Could not read the new installation-report for package"
                                         << package->id() << "at" << irfile.fileName() << ":"
                                         << e.errorString();
                return false;
            }
            newPackageInfo->setInstallationReport(ir.release());
        }

        if (isUpdate || isDowngrade) {
            // unregister all the old apps & intents
            unregisterApplicationsAndIntentsOfPackage(package);

            // update the correct base/updated info pointer
            PackageInfo *oldPackageInfo;
            if (package->isBuiltIn())
                oldPackageInfo = package->setUpdatedInfo(newPackageInfo);
            else
                oldPackageInfo = package->setBaseInfo(newPackageInfo);

            if (oldPackageInfo)
                d->database->removePackageInfo(oldPackageInfo);
        }

        // add the new info to the package db
        if (newPackageInfo)
            d->database->addPackageInfo(newPackageInfo);

        // register all the apps & intents
        registerApplicationsAndIntentsOfPackage(package);

        // boiler-plate cleanup code
        package->setState(Package::Installed);
        package->setProgress(0);
        emitDataChanged(package);
        package->unblock();
        emit package->bulkChange(); // not ideal, but icon and codeDir have changed
        break;
    }

    case Package::BeingRemoved: {
        // unregister all the apps & intents
        unregisterApplicationsAndIntentsOfPackage(package);

        // remove the package from the model
        qsizetype row = d->packages.indexOf(package);
        if (row >= 0) {
            emit packageAboutToBeRemoved(package->id());
            beginRemoveRows(QModelIndex(), int(row), int(row));
            d->packages.removeAt(row);
            endRemoveRows();
        }

        // cleanup
        package->unblock();

        // remove the package from the package db
        d->database->removePackageInfo(package->info());

        delete package;
        break;
    }
    }

    return true;
}

bool PackageManager::canceledPackageInstall(const QString &id)
{
    Package *package = fromId(id);
    if (!package)
        return false;

    switch (package->state()) {
    case Package::Installed:
        return false;

    case Package::BeingInstalled: {
        // remove the package from the model
        int row = int(d->packages.indexOf(package));
        if (row >= 0) {
            emit packageAboutToBeRemoved(package->id());
            beginRemoveRows(QModelIndex(), row, row);
            d->packages.removeAt(row);
            endRemoveRows();
        }

        // cleanup
        package->unblock();

        // it's not yet added to the package db, so we need to delete ourselves
        delete package->info();

        delete package;
        break;
    }
    case Package::BeingUpdated:
    case Package::BeingDowngraded:
    case Package::BeingRemoved:
        delete d->pendingPackageInfoUpdates.take(package);

        package->setState(Package::Installed);
        package->setProgress(0);
        emitDataChanged(package, QVector<int> { PMRoles::IsUpdating });

        package->unblock();
        break;
    }
    return true;
}


/*!
    \qmlmethod int PackageManager::compareVersions(string version1, string version2)

    Convenience method for app-store implementations or taskRequestingInstallationAcknowledge()
    callbacks for comparing version numbers, as the actual version comparison algorithm is not
    trivial.

    Returns \c -1, \c 0 or \c 1 if \a version1 is smaller than, equal to, or greater than \a
    version2 (similar to how \c strcmp() works).
*/
int PackageManager::compareVersions(const QString &version1, const QString &version2)
{
    qsizetype vn1Suffix = -1;
    qsizetype vn2Suffix = -1;
    QVersionNumber vn1 = QVersionNumber::fromString(version1, &vn1Suffix);
    QVersionNumber vn2 = QVersionNumber::fromString(version2, &vn2Suffix);

    int diff = QVersionNumber::compare(vn1, vn2);
    if (!diff)
        diff = QStringView{ version1 }.mid(vn1Suffix).compare(QStringView{ version2 }.mid(vn2Suffix));
    return diff < 0 ? -1 : (diff > 0 ? 1 : 0);
}

/*!
    \qmlmethod int PackageManager::validateDnsName(string name, int minimalPartCount)

    Convenience method for app-store implementations or taskRequestingInstallationAcknowledge()
    callbacks for checking if the given \a name is a valid DNS (or reverse-DNS) name according to
    RFC 1035/1123. If the optional parameter \a minimalPartCount is specified, this function will
    also check if \a name contains at least this amount of parts/sub-domains.

    Returns \c true if the name is a valid DNS name or \c false otherwise.
*/
bool PackageManager::validateDnsName(const QString &name, int minimalPartCount)
{
    try {
        // check if we have enough parts: e.g. "tld.company.app" would have 3 parts
        QStringList parts = name.split(u'.');
        if (parts.size() < minimalPartCount) {
            throw Exception(Error::Parse, "the minimum amount of parts (subdomains) is %1 (found %2)")
                .arg(minimalPartCount).arg(parts.size());
        }

        // standard RFC compliance tests (RFC 1035/1123)

        auto partCheck = [](const QString &part) {
            qsizetype len = part.length();

            if (len < 1 || len > 63)
                throw Exception(Error::Parse, "domain parts must consist of at least 1 and at most 63 characters (found %2 characters)").arg(len);

            for (qsizetype pos = 0; pos < len; ++pos) {
                ushort ch = part.at(pos).unicode();
                bool isFirst = (pos == 0);
                bool isLast  = (pos == (len - 1));
                bool isDash  = (ch == '-');
                bool isDigit = (ch >= '0' && ch <= '9');
                bool isLower = (ch >= 'a' && ch <= 'z');

                if ((isFirst || isLast || !isDash) && !isDigit && !isLower)
                    throw Exception(Error::Parse, "domain parts must consist of only the characters '0-9', 'a-z', and '-' (which cannot be the first or last character)");
            }
        };

        for (const QString &part : parts)
            partCheck(part);

        return true;
    } catch (const Exception &e) {
        qCDebug(LogInstaller).noquote() << "validateDnsName failed:" << e.errorString();
        return false;
    }
}

bool removeRecursiveHelper(const QString &path)
{
    if (SudoClient::instance())
        return SudoClient::instance()->removeRecursive(path);
    else
        return recursiveOperation(path, safeRemove);
}

QT_END_NAMESPACE_AM

#include "moc_packagemanager.cpp"