Skip to content

Microsoft 365

M365 Module to interact with the MS Graph API.

See also https://learn.microsoft.com/en-us/graph/

M365

Used to automate stettings in Microsoft 365 via the Graph API.

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
  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
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
class M365:
    """Used to automate stettings in Microsoft 365 via the Graph API."""

    logger: logging.Logger = default_logger

    _config: dict
    _access_token = None
    _user_access_token = None
    _http_object: HTTP | None = None

    def __init__(
        self,
        tenant_id: str,
        client_id: str,
        client_secret: str,
        domain: str,
        sku_id: str,
        teams_app_name: str,
        teams_app_external_id: str,
        sharepoint_app_root_site: str = "",
        sharepoint_app_client_id: str = "",
        sharepoint_app_client_secret: str = "",
        logger: logging.Logger = default_logger,
    ) -> None:
        """Initialize the M365 object.

        Args:
            tenant_id (str):
                The M365 Tenant ID.
            client_id (str):
                The M365 Client ID.
            client_secret (str):
                The M365 Client Secret.
            domain (str):
                The M365 domain.
            sku_id (str):
                License SKU for M365 users.
            teams_app_name (str):
                The name of the Extended ECM app for MS Teams.
            teams_app_external_id (str):
                The external ID of the Extended ECM app for MS Teams
            sharepoint_app_root_site (str):
                The URL to the SharePoint root site.
            sharepoint_app_client_id (str):
                The SharePoint App client ID.
            sharepoint_app_client_secret (str):
                The SharePoint App client secret.
            logger (logging.Logger, optional):
                The logging object to use for all log messages. Defaults to default_logger.

        """

        if logger != default_logger:
            self.logger = logger.getChild("m365")
            for logfilter in logger.filters:
                self.logger.addFilter(logfilter)

        m365_config = {}

        # Set the authentication endpoints and credentials
        m365_config["tenantId"] = tenant_id
        m365_config["clientId"] = client_id
        m365_config["clientSecret"] = client_secret
        m365_config["domain"] = domain
        m365_config["skuId"] = sku_id
        m365_config["teamsAppName"] = teams_app_name
        m365_config["teamsAppExternalId"] = teams_app_external_id  # this is the external App ID
        m365_config["teamsAppInternalId"] = None  # will be set later...
        m365_config["sharepointAppRootSite"] = sharepoint_app_root_site
        m365_config["sharepointAppClientId"] = sharepoint_app_client_id
        m365_config["sharepointAppClientSecret"] = sharepoint_app_client_secret
        m365_config["authenticationUrl"] = "https://login.microsoftonline.com/{}/oauth2/v2.0/token".format(tenant_id)
        m365_config["graphUrl"] = "https://graph.microsoft.com/v1.0/"
        m365_config["betaUrl"] = "https://graph.microsoft.com/beta/"
        m365_config["directoryObjects"] = m365_config["graphUrl"] + "directoryObjects"

        # Set the data for the token request
        m365_config["tokenData"] = {
            "client_id": client_id,
            "client_secret": client_secret,
            "grant_type": "client_credentials",
            "scope": "https://graph.microsoft.com/.default",
        }

        m365_config["meUrl"] = m365_config["graphUrl"] + "me"
        m365_config["groupsUrl"] = m365_config["graphUrl"] + "groups"
        m365_config["usersUrl"] = m365_config["graphUrl"] + "users"
        m365_config["teamsUrl"] = m365_config["graphUrl"] + "teams"
        m365_config["teamsTemplatesUrl"] = m365_config["graphUrl"] + "teamsTemplates"
        m365_config["teamsAppsUrl"] = m365_config["graphUrl"] + "appCatalogs/teamsApps"
        m365_config["directoryUrl"] = m365_config["graphUrl"] + "directory"
        m365_config["securityUrl"] = m365_config["betaUrl"] + "security"
        m365_config["applicationsUrl"] = m365_config["graphUrl"] + "applications"

        m365_config["sitesUrl"] = m365_config["betaUrl"] + "sites"

        self._config = m365_config
        self._http_object = HTTP(logger=self.logger)

    def config(self) -> dict:
        """Return the configuration dictionary.

        Returns:
            dict: Configuration dictionary

        """

        return self._config

    def credentials(self) -> dict:
        """Return the login credentials.

        Returns:
            dict:
                A dictionary with (admin) login credentials for M365.

        """

        return self.config()["tokenData"]

    def credentials_user(self, username: str, password: str, scope: str = "Files.ReadWrite") -> dict:
        """Get user credentials.

        In some cases MS Graph APIs cannot be called via
        application permissions (client_id, client_secret)
        but requires a token of a user authenticated
        with username + password. This is e.g. the case
        to upload a MS teams app to the catalog.

        See https://learn.microsoft.com/en-us/graph/api/teamsapp-publish

        Args:
            username (str):
                The M365 username.
            password (str):
                The password of the M365 user.
            scope (str):
                The scope of the delegated permission.
                It is important to provide a scope for the intended operation
                like "Files.ReadWrite".

        Returns:
            dict:
                A dictionary with the (user) credentials for M365.

        """

        # Use OAuth2 / ROPC (Resource Owner Password Credentials):
        credentials = {
            "client_id": self.config()["clientId"],
            "client_secret": self.config()["clientSecret"],
            "grant_type": "password",
            "username": username,
            "password": password,
            "scope": scope,
        }

        return credentials

    # end method definition

    def request_header(self, content_type: str = "application/json") -> dict:
        """Return the request header used for Application calls.

        Consists of Bearer access token and Content Type.

        Args:
            content_type (str, optional):
                The content type for the request. Default is "application/json".

        Returns:
            dict:
                The request header values.

        """

        request_header = {
            "Authorization": "Bearer {}".format(self._access_token),
            "Content-Type": content_type,
        }

        return request_header

    # end method definition

    def request_header_user(self, content_type: str = "application/json") -> dict:
        """Return the request header used for user specific calls.

        Consists of Bearer access token and Content Type.

        Args:
            content_type (str, optional):
                The content type for the request.

        Returns:
            dict:
                The request header values.

        """

        request_header = {
            "Content-Type": content_type,
        }

        if not self._user_access_token:
            self.logger.error("No M365 user is authenticated! Cannot include Bearer token in request header!")
        else:
            request_header["Authorization"] = "Bearer {}".format(self._user_access_token)

        return request_header

    # end method definition

    def do_request(
        self,
        url: str,
        method: str = "GET",
        headers: dict | None = None,
        data: dict | None = None,
        json_data: dict | None = None,
        files: dict | None = None,
        params: dict | None = None,
        timeout: float | None = REQUEST_TIMEOUT,
        show_error: bool = True,
        show_warning: bool = False,
        warning_message: str = "",
        failure_message: str = "",
        success_message: str = "",
        max_retries: int = REQUEST_MAX_RETRIES,
        retry_forever: bool = False,
        parse_request_response: bool = True,
        stream: bool = False,
    ) -> dict | None:
        """Call an M365 Graph API in a safe way.

        Args:
            url (str):
                URL to send the request to.
            method (str, optional):
                HTTP method (GET, POST, etc.). Defaults to "GET".
            headers (dict | None, optional):
                Request Headers. Defaults to None.
            data (dict | None, optional):
                Request payload. Defaults to None.
            json_data (dict | None, optional):
                Request payload for the JSON parameter. Defaults to None.
            files (dict | None, optional):
                Dictionary of {"name": file-tuple} for multipart encoding upload.
                file-tuple can be a 2-tuple ("filename", fileobj) or a 3-tuple ("filename", fileobj, "content_type")
            params (dict | None, optional):
                Add key-value pairs to the query string of the URL.
                When you use the params parameter, requests automatically appends
                the key-value pairs to the URL as part of the query string
            timeout (float | None, optional):
                Timeout for the request in seconds. Defaults to REQUEST_TIMEOUT.
            show_error (bool, optional):
                Whether or not an error should be logged in case of a failed REST call.
                If False, then only a warning is logged. Defaults to True.
            show_warning (bool, optional):
                Whether or not an warning should be logged in case of a
                failed REST call.
                If False, then only a warning is logged. Defaults to True.
            warning_message (str, optional):
                Specific warning message. Defaults to "". If not given the error_message will be used.
            failure_message (str, optional):
                Specific error message. Defaults to "".
            success_message (str, optional):
                Specific success message. Defaults to "".
            max_retries (int, optional):
                How many retries on Connection errors? Default is REQUEST_MAX_RETRIES.
            retry_forever (bool, optional):
                Eventually wait forever - without timeout. Defaults to False.
            parse_request_response (bool, optional):
                Defines whether the response.text should be interpreted as json and loaded into a dictionary.
                True is the default.
            stream (bool, optional):
                This parameter is used to control whether the response content should be immediately
                downloaded or streamed incrementally.

        Returns:
            dict | None:
                Response of M365 Graph REST API or None in case of an error.

        """

        if headers is None:
            self.logger.error(
                "Missing request header. Cannot send request to Microsoft M365 Graph API!",
            )
            return None

        # In case of an expired session we reauthenticate and
        # try 1 more time. Session expiration should not happen
        # twice in a row:
        retries = 0

        while True:
            try:
                response = requests.request(
                    method=method,
                    url=url,
                    data=data,
                    json=json_data,
                    files=files,
                    params=params,
                    headers=headers,
                    timeout=timeout,
                    stream=stream,
                )

                if response.ok:
                    if success_message:
                        self.logger.info(success_message)
                    if parse_request_response:
                        return self.parse_request_response(response)
                    else:
                        return response
                # Check if Session has expired - then re-authenticate and try once more
                elif response.status_code == 401 and retries == 0:
                    self.logger.debug("Session has expired - try to re-authenticate...")
                    self.authenticate(revalidate=True)
                    headers = self.request_header()
                    retries += 1
                elif response.status_code in [502, 503, 504] and retries < REQUEST_MAX_RETRIES:
                    self.logger.warning(
                        "M365 Graph API delivered server side error -> %s; retrying in %s seconds...",
                        response.status_code,
                        (retries + 1) * 60,
                    )
                    time.sleep((retries + 1) * 60)
                    retries += 1
                elif response.status_code in [404, 429] and retries < REQUEST_MAX_RETRIES:
                    self.logger.warning(
                        "M365 Graph API is too slow or throtteling calls -> %s; retrying in %s seconds...",
                        response.status_code,
                        (retries + 1) * 60,
                    )
                    time.sleep((retries + 1) * 60)
                    retries += 1
                else:
                    # Handle plain HTML responses to not pollute the logs
                    content_type = response.headers.get("content-type", None)
                    response_text = (
                        "HTML content (only printed in debug log)" if content_type == "text/html" else response.text
                    )

                    if show_error:
                        self.logger.error(
                            "%s; status -> %s/%s; error -> %s",
                            failure_message,
                            response.status_code,
                            HTTPStatus(response.status_code).phrase,
                            response_text,
                        )
                    elif show_warning:
                        self.logger.warning(
                            "%s; status -> %s/%s; warning -> %s",
                            warning_message if warning_message else failure_message,
                            response.status_code,
                            HTTPStatus(response.status_code).phrase,
                            response_text,
                        )
                    if content_type == "text/html":
                        self.logger.debug(
                            "%s; status -> %s/%s; warning -> %s",
                            failure_message,
                            response.status_code,
                            HTTPStatus(response.status_code).phrase,
                            response.text,
                        )
                    return None
            except requests.exceptions.Timeout:
                if retries <= max_retries:
                    self.logger.warning(
                        "Request timed out. Retrying in %s seconds...",
                        str(REQUEST_RETRY_DELAY),
                    )
                    retries += 1
                    time.sleep(REQUEST_RETRY_DELAY)  # Add a delay before retrying
                else:
                    self.logger.error(
                        "%s; timeout error!",
                        failure_message,
                    )
                    if retry_forever:
                        # If it fails after REQUEST_MAX_RETRIES retries we let it wait forever
                        self.logger.warning("Turn timeouts off and wait forever...")
                        timeout = None
                    else:
                        return None
            except requests.exceptions.ConnectionError:
                if retries <= max_retries:
                    self.logger.warning(
                        "Connection error. Retrying in %s seconds...",
                        str(REQUEST_RETRY_DELAY),
                    )
                    retries += 1
                    time.sleep(REQUEST_RETRY_DELAY)  # Add a delay before retrying
                else:
                    self.logger.error(
                        "%s; connection error!",
                        failure_message,
                    )
                    if retry_forever:
                        # If it fails after REQUEST_MAX_RETRIES retries we let it wait forever
                        self.logger.warning("Turn timeouts off and wait forever...")
                        timeout = None
                        time.sleep(REQUEST_RETRY_DELAY)  # Add a delay before retrying
                    else:
                        return None
            # end try
            self.logger.debug(
                "Retrying REST API %s call -> %s... (retry = %s)",
                method,
                url,
                str(retries),
            )
        # end while True

    # end method definition

    def parse_request_response(
        self,
        response_object: requests.Response,
        additional_error_message: str = "",
        show_error: bool = True,
    ) -> dict | None:
        """Convert the request response (JSon) to a Python dict in a safe way.

        It first tries to load the response.text via json.loads() that produces a
        dict output. Only if response.text is not set or is empty it just converts the
        response_object to a dict using the vars() built-in method.

        Args:
            response_object (object):
                This is reponse object delivered by the request call.
            additional_error_message (str, optional):
                Use a more specific error message in case of an error.
            show_error (bool, optional):
                True: write an error to the log file
                False: write a warning to the log file

        Returns:
            dict:
                API response information or None in case of an error.

        """

        if not response_object:
            return None

        try:
            dict_object = json.loads(response_object.text) if response_object.text else vars(response_object)
        except json.JSONDecodeError as exception:
            if additional_error_message:
                message = "Cannot decode response as JSon. {}; error -> {}".format(
                    additional_error_message,
                    exception,
                )
            else:
                message = "Cannot decode response as JSon; error -> {}".format(
                    exception,
                )
            if show_error:
                self.logger.error(message)
            else:
                self.logger.warning(message)
            return None
        else:
            return dict_object

    # end method definition

    def exist_result_item(
        self,
        response: dict | None,
        key: str,
        value: str,
        sub_dict_name: str = "",
    ) -> bool:
        """Check existence of key / value pair in the response properties of an MS Graph API call.

        Args:
            response (dict | None):
                REST response from an MS Graph REST Call.
            key (str):
                The property name (key).
            value (str):
                The value to find in the item with the matching key
            sub_dict_name (str, optional):
                Some MS Graph API calls include nested dict structures that can be requested
                with an "expand" query parameter. In such a case we use the sub_dict_name to
                access it.

        Returns:
            bool:
                True if the value was found, False otherwise

        """

        if not response:
            return False
        if "value" not in response:
            return False

        values = response["value"]
        if not values or not isinstance(values, list):
            return False

        if not sub_dict_name:
            for item in values:
                if value == item[key]:
                    return True
        else:
            for item in values:
                if sub_dict_name not in item:
                    return False
                if value == item[sub_dict_name][key]:
                    return True

        return False

    # end method definition

    def get_result_value(
        self,
        response: dict | None,
        key: str,
        index: int = 0,
        sub_dict_name: str = "",
    ) -> str | None:
        """Get value of a result property with a given key of an MS Graph API call.

        Args:
            response (dict | None):
                REST response from an MS Graph REST Call.
            key (str):
                The property name (key).
            index (int, optional):
                Index to use (1st element has index 0).
                Defaults to 0.
            sub_dict_name (str):
                Some MS Graph API calls include nested dict structures that can
                be requested with an "expand" query parameter. In such
                a case we use the sub_dict_name to access it.

        Returns:
            str | None:
                The value for the key, None otherwise.

        """

        if not response:
            return None
        if "value" not in response:  # If Graph APIs are called with specific IDs (and not name lookups)
            # they may not return a list of dicts calles "values" but a single dict directly
            if sub_dict_name and sub_dict_name in response:
                sub_structure = response[sub_dict_name]
                # also the substructure could be a list
                if isinstance(sub_structure, list):
                    sub_structure = sub_structure[index]
                return sub_structure[key]
            elif key in response:
                return response[key]
            else:
                return None

        values = response["value"]
        if not values or not isinstance(values, list) or len(values) - 1 < index:
            return None

        if not sub_dict_name:
            return values[index][key]
        else:
            sub_structure = values[index][sub_dict_name]
            if isinstance(sub_structure, list):
                # here we assume it is the first element of the
                # substructure. If really required for specific
                # use cases we may introduce a second index in
                # the future.
                sub_structure = sub_structure[0]
            return sub_structure[key]

    # end method definition

    def lookup_result_value(
        self,
        response: dict,
        key: str,
        value: str,
        return_key: str,
        sub_dict_name: str = "",
    ) -> str | None:
        """Look up a property value for a provided key-value pair of a REST response.

        Args:
            response (dict):
                The REST response from an OTCS REST call, containing property data.
            key (str):
                Property name (key) to match in the response.
            value (str):
                Value to find in the item with the matching key.
            return_key (str):
                Name of the dictionary key whose value should be returned.
            sub_dict_name (str):
                Some MS Graph API calls include nested dict structures that can
                be requested with an "expand" query parameter. In such
                a case we use the sub_dict_name to access it.

        Returns:
            str | None:
                The value of the property specified by "return_key" if found,
                or None if the lookup fails.

        """

        if not response:
            return None

        results = response.get("value", response)

        # check if results is a list or a dict (both is possible -
        # dependent on the actual REST API):
        if isinstance(results, dict):
            # result is a dict - we don't need index value:
            if sub_dict_name and sub_dict_name in results:
                results = results[sub_dict_name]
            if key in results and results[key] == value and return_key in results:
                return results[return_key]
            else:
                return None
        elif isinstance(results, list):
            # result is a list - we need index value
            for result in results:
                if sub_dict_name and sub_dict_name in result:
                    result = result[sub_dict_name]
                if key in result and result[key] == value and return_key in result:
                    return result[return_key]
            return None
        else:
            self.logger.error(
                "Result needs to be a list or dictionary but it is of type -> '%s'!",
                str(type(results)),
            )
            return None

    # end method definition

    def authenticate(self, revalidate: bool = False) -> str | None:
        """Authenticate at M365 Graph API with client ID and client secret.

        Args:
            revalidate (bool, optional):
                Determins if a re-athentication is enforced.
                (e.g. if session has timed out with 401 error)

        Returns:
            str | None:
                The access token. Also stores access token in self._access_token.
                None in case of an error.

        """

        # Already authenticated and session still valid?
        if self._access_token and not revalidate:
            self.logger.debug(
                "Session still valid - return existing access token -> %s",
                str(self._access_token),
            )
            return self._access_token

        request_url = self.config()["authenticationUrl"]
        request_header = request_login_headers

        self.logger.debug("Requesting M365 Access Token from -> %s", request_url)

        authenticate_post_body = self.credentials()
        authenticate_response = None

        try:
            authenticate_response = requests.post(
                request_url,
                data=authenticate_post_body,
                headers=request_header,
                timeout=REQUEST_TIMEOUT,
            )
        except requests.exceptions.ConnectionError as exception:
            self.logger.warning(
                "Unable to connect to -> %s : %s",
                self.config()["authenticationUrl"],
                str(exception),
            )
            return None

        if authenticate_response.ok:
            authenticate_dict = self.parse_request_response(authenticate_response)
            if not authenticate_dict:
                return None
            access_token = authenticate_dict["access_token"]
            self.logger.debug("Access Token -> %s", access_token)
        else:
            self.logger.error(
                "Failed to request an M365 Access Token; error -> %s",
                authenticate_response.text,
            )
            return None

        # Store authentication access_token:
        self._access_token = access_token

        return self._access_token

    # end method definition

    def authenticate_user(self, username: str, password: str, scope: str | None = None) -> str | None:
        """Authenticate at M365 Graph API with username and password.

        Args:
            username (str):
                The name (email) of the M365 user.
            password (str):
                The password of the M365 user.
            scope (str):
                The scope of the delegated permission. E.g. "Files.ReadWrite".
                Multiple delegated permissions should be separated by spaces.

        Returns:
            str | None:
                The access token for the user. Also stores access token in self._access_token.
                None in case of an error.

        """

        request_url = self.config()["authenticationUrl"]
        request_header = request_login_headers

        if not username:
            self.logger.error("Missing user name - cannot authenticate at M365!")
            return None
        if not password:
            self.logger.error(
                "Missing password for user -> '%s' - cannot authenticate at M365!",
                username,
            )
            return None

        self.logger.debug(
            "Requesting M365 Access Token for user -> %s from -> %s%s",
            username,
            request_url,
            " with scope -> '{}'".format(scope) if scope else "",
        )

        authenticate_post_body = self.credentials_user(username=username, password=password, scope=scope)
        authenticate_response = None

        try:
            authenticate_response = requests.post(
                request_url,
                data=authenticate_post_body,
                headers=request_header,
                timeout=REQUEST_TIMEOUT,
            )
        except requests.exceptions.ConnectionError as exception:
            self.logger.warning(
                "Unable to connect to -> %s with username -> %s: %s",
                self.config()["authenticationUrl"],
                username,
                str(exception),
            )
            return None

        if authenticate_response.ok:
            authenticate_dict = self.parse_request_response(authenticate_response)
            if not authenticate_dict:
                return None
            access_token = authenticate_dict["access_token"]
            self.logger.debug("User Access Token -> %s", access_token)
        else:
            self.logger.error(
                "Failed to request an M365 Access Token for user -> '%s'; error -> %s",
                username,
                authenticate_response.text,
            )
            return None

        # Store authentication access_token:
        self._user_access_token = access_token

        return self._user_access_token

    # end method definition

    def get_users(self, max_number: int = 250, next_page_url: str | None = None) -> dict | None:
        """Get list all all users in M365 tenant.

        Args:
            max_number (int, optional):
                The maximum result values (limit).
            next_page_url (str, optional):
                The MS Graph URL to retrieve the next page of M365 users (pagination).
                This is used for the iterator get_users_iterator() below.

        Returns:
            dict | None:
                Dictionary of all M365 users.

        """

        request_url = next_page_url if next_page_url else self.config()["usersUrl"]
        request_header = self.request_header()

        self.logger.debug(
            "Get list of all M365 users%s; calling -> %s",
            " (paged)" if next_page_url else "",
            request_url,
        )

        response = self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            params={"$top": str(max_number)} if not next_page_url else None,
            timeout=REQUEST_TIMEOUT,
            failure_message="Failed to get list of M365 users!",
        )

        return response

    # end method definition

    def get_users_iterator(
        self,
    ) -> iter:
        """Get an iterator object that can be used to traverse all M365 users.

        Returning a generator avoids loading a large number of nodes into memory at once. Instead you
        can iterate over the potential large list of users.

        Example usage:
            users = m365_object.get_users_iterator()
            for user in users:
                logger.info("Traversing M365 user -> '%s'...", user.get("displayName", "<undefined name>"))

        Returns:
            iter:
                A generator yielding one M365 user per iteration.
                If the REST API fails, returns no value.

        """

        next_page_url = None

        while True:
            response = self.get_users(
                next_page_url=next_page_url,
            )
            if not response or "value" not in response:
                # Don't return None! Plain return is what we need for iterators.
                # Natural Termination: If the generator does not yield, it behaves
                # like an empty iterable when used in a loop or converted to a list:
                return

            # Yield users one at a time:
            yield from response["value"]

            # See if we have an additional result page.
            # If not terminate the iterator and return
            # no value.
            next_page_url = response.get("@odata.nextLink", None)
            if not next_page_url:
                # Don't return None! Plain return is what we need for iterators.
                # Natural Termination: If the generator does not yield, it behaves
                # like an empty iterable when used in a loop or converted to a list:
                return

    # end method definition

    def get_user(self, user_email: str, user_id: str | None = None, show_error: bool = False) -> dict | None:
        """Get a M365 User based on its email or ID.

        Args:
            user_email (str):
                The M365 user email.
            user_id (str | None, optional):
                The ID of the M365 user (alternatively to user_email). Optional.
            show_error (bool):
                Whether or not an error should be displayed if the
                user is not found.

        Returns:
            dict:
                User information or None if the user couldn't be retrieved (e.g. because it doesn't exist
                or if there is a permission problem).

        Example:
            {
                '@odata.context': 'https://graph.microsoft.com/v1.0/$metadata#users/$entity',
                'businessPhones': [],
                'displayName': 'Bob Davis',
                'givenName': 'Bob',
                'id': '72c80809-094f-4e6e-98d4-25a736385d10',
                'jobTitle': None,
                'mail': 'bdavis@M365x61936377.onmicrosoft.com',
                'mobilePhone': None,
                'officeLocation': None,
                'preferredLanguage': None,
                'surname': 'Davis',
                'userPrincipalName': 'bdavis@M365x61936377.onmicrosoft.com'
            }

        """

        # Some sanity checks:
        if user_email and ("@" not in user_email or "." not in user_email):
            self.logger.error(
                "User email -> %s is not a valid email address!",
                user_email,
            )
            return None

        # if there's an alias in the E-Mail Adress we remove it as
        # MS Graph seems to not support an alias to lookup a user object.
        if user_email and "+" in user_email:
            self.logger.info(
                "Removing Alias from email address -> %s to determine M365 principal name...",
                user_email,
            )
            # Find the index of the '+' character
            alias_index = user_email.find("+")

            # Find the index of the '@' character
            domain_index = user_email.find("@")

            # Construct the email address without the alias
            user_email = user_email[:alias_index] + user_email[domain_index:]
            self.logger.info(
                "M365 user principal name -> '%s'.",
                user_email,
            )

        request_url = self.config()["usersUrl"] + "/" + str(user_email if user_email else user_id)
        request_header = self.request_header()

        self.logger.debug(
            "Get M365 user -> '%s'; calling -> %s",
            str(user_email if user_email else user_id),
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=REQUEST_TIMEOUT,
            failure_message="Failed to get M365 user -> '{}'".format(user_email if user_email else user_id),
            show_error=show_error,
        )

    # end method definition

    def add_user(
        self,
        email: str,
        password: str,
        first_name: str,
        last_name: str,
        location: str = "US",
        department: str = "",
        company_name: str = "Innovate",
    ) -> dict | None:
        """Add a M365 user.

        Args:
            email (str):
                The email address of the user. This is also the unique identifier.
            password (str):
                The password of the user.
            first_name (str):
                The first name of the user.
            last_name (str):
                The last name of the user.
            location (str, optional):
                The country ISO 3166-1 alpha-2 code (e.g. US, CA, FR, DE, CN, ...)
            department (str, optional):
                The department of the user.
            company_name (str):
                The name of the company the user works for.

        Returns:
            dict | None:
                User information or None if the user couldn't be created (e.g. because it exisits already
                or if a permission problem occurs).

        """

        user_post_body = {
            "accountEnabled": True,
            "displayName": first_name + " " + last_name,
            "givenName": first_name,
            "surname": last_name,
            "mailNickname": email.split("@")[0],
            "userPrincipalName": email,
            "passwordProfile": {
                "forceChangePasswordNextSignIn": False,
                "password": password,
            },
            "usageLocation": location,
        }
        if department:
            user_post_body["department"] = department
        if company_name:
            user_post_body["companyName"] = company_name

        request_url = self.config()["usersUrl"]
        request_header = self.request_header()

        self.logger.debug("Adding M365 user -> %s; calling -> %s", email, request_url)

        return self.do_request(
            url=request_url,
            method="POST",
            headers=request_header,
            data=json.dumps(user_post_body),
            timeout=REQUEST_TIMEOUT,
            failure_message="Failed to add M365 user -> '{}'".format(email),
        )

    # end method definition

    def update_user(self, user_id: str, updated_settings: dict) -> dict | None:
        """Update selected properties of an M365 user.

        Documentation on user properties is here: https://learn.microsoft.com/en-us/graph/api/user-update

        Args:
            user_id (str):
                The ID of the user (can also be email). This is also the unique identifier.
            updated_settings (dict):
                The new data to update the user with.

        Returns:
            dict | None:
                Response of the M365 Graph API  or None if the call fails.

        """

        request_url = self.config()["usersUrl"] + "/" + user_id
        request_header = self.request_header()

        self.logger.debug(
            "Updating M365 user with ID -> %s with -> %s; calling -> %s",
            user_id,
            str(updated_settings),
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="PATCH",
            headers=request_header,
            json_data=updated_settings,
            timeout=REQUEST_TIMEOUT,
            failure_message="Failed to update M365 user -> '{}' with -> {}".format(
                user_id,
                updated_settings,
            ),
        )

    # end method definition

    def get_user_licenses(self, user_id: str) -> dict | None:
        """Get the assigned license SKUs of a user.

        Args:
            user_id (str):
                The M365 GUID of the user (can also be the M365 email of the user).

        Returns:
            dict:
                A list of user licenses or None if request fails.

        Example:
            {
                '@odata.context': "https://graph.microsoft.com/v1.0/$metadata#users('a5875311-f0a5-486d-a746-bd7372b91115')/licenseDetails",
                'value': [
                    {
                        'id': '8DRPYHK6IUOra-Nq6L0A7GAn38eBLPdOtXhbU5K1cd8',
                        'skuId': 'c7df2760-2c81-4ef7-b578-5b5392b571df',
                        'skuPartNumber': 'ENTERPRISEPREMIUM',
                        'servicePlans': [{...}, {...}, {...}, {...}, {...}, {...}, {...}, {...}, {...}, ...]
                    }
                ]
            }

        """

        request_url = self.config()["usersUrl"] + "/" + user_id + "/licenseDetails"
        request_header = self.request_header()

        return self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=REQUEST_TIMEOUT,
            failure_message="Failed to get M365 licenses of M365 user -> {}".format(user_id),
        )

    # end method definition

    def assign_license_to_user(self, user_id: str, sku_id: str) -> dict | None:
        """Add an M365 license to a user (e.g. to use Office 365).

        Args:
            user_id (str):
                The M365 GUID of the user (can also be the M365 email of the user)
            sku_id (str):
                M365 GUID of the SKU.
                (e.g. c7df2760-2c81-4ef7-b578-5b5392b571df for E5 and
                6fd2c87f-b296-42f0-b197-1e91e994b900 for E3)

        Returns:
            dict:
                The API response or None if request fails.

        """

        request_url = self.config()["usersUrl"] + "/" + user_id + "/assignLicense"
        request_header = self.request_header()

        # Construct the request body for assigning the E5 license
        license_post_body = {
            "addLicenses": [
                {
                    "disabledPlans": [],
                    "skuId": sku_id,  # "c42b9cae-ea4f-4a69-9ca5-c53bd8779c42"
                },
            ],
            "removeLicenses": [],
        }

        self.logger.debug(
            "Assign M365 license -> %s to M365 user -> %s; calling -> %s",
            sku_id,
            user_id,
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="POST",
            headers=request_header,
            json_data=license_post_body,
            timeout=REQUEST_TIMEOUT,
            failure_message="Failed to assign M365 license -> {} to M365 user -> {}".format(
                sku_id,
                user_id,
            ),
        )

    # end method definition

    def get_user_photo(self, user_id: str, show_error: bool = True) -> bytes | None:
        """Get the photo of a M365 user.

        Args:
            user_id (str):
                The M365 GUID of the user (can also be the M365 email of the user).
            show_error (bool, optional):
                Whether or not an error should be logged if the user
                does not have a photo in M365.

        Returns:
            bytes:
                Image of the user photo or None if the user photo couldn't be retrieved.

        """

        request_url = self.config()["usersUrl"] + "/" + user_id + "/photo/$value"
        # Set image as content type:
        request_header = self.request_header("image/*")

        self.logger.debug(
            "Get photo of user -> %s; calling -> %s",
            user_id,
            request_url,
        )

        response = self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=REQUEST_TIMEOUT,
            failure_message="Failed to get photo of M365 user -> {}".format(user_id),
            warning_message="M365 User -> {} does not yet have a photo.".format(
                user_id,
            ),
            show_error=show_error,
            parse_request_response=False,  # the response is NOT JSON!
        )

        if response and response.ok and response.content:
            return response.content  # this is the actual image - not json!

        return None

    # end method definition

    def download_user_photo(self, user_id: str, photo_path: str) -> str | None:
        """Download the M365 user photo and save it to the local file system.

        Args:
            user_id (str):
                The M365 GUID of the user (can also be the M365 email of the user).
            photo_path (str):
                The directory where the photo should be saved.

        Returns:
            str:
                The name of the photo file in the file system (with full path) or None if
                the call of the REST API fails.

        """

        request_url = self.config()["usersUrl"] + "/" + user_id + "/photo/$value"
        request_header = self.request_header("application/json")

        self.logger.debug(
            "Downloading photo for M365 user with ID -> %s; calling -> %s",
            user_id,
            request_url,
        )

        response = self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=REQUEST_TIMEOUT,
            failure_message="Failed to download photo for M365 user with ID -> {}".format(
                user_id,
            ),
            stream=True,
            parse_request_response=False,
        )

        if response and response.ok:
            content_type = response.headers.get("Content-Type", "image/png")
            if content_type == "image/jpeg":
                file_extension = "jpg"
            elif content_type == "image/png":
                file_extension = "png"
            else:
                file_extension = "img"  # Default extension if type is unknown
            file_path = os.path.join(
                photo_path,
                "{}.{}".format(user_id, file_extension),
            )

            try:
                with open(file_path, "wb") as file:
                    file.writelines(response.iter_content(chunk_size=8192))
            except OSError:
                self.logger.error(
                    "Error saving photo for user with ID -> %s!",
                    user_id,
                )
            else:
                self.logger.info(
                    "Photo for M365 user with ID -> %s saved to -> '%s'.",
                    user_id,
                    file_path,
                )
                return file_path

        return None

    # end method definition

    def update_user_photo(self, user_id: str, photo_path: str) -> dict | None:
        """Update the M365 user photo.

        Args:
            user_id (str):
                The M365 GUID of the user (can also be the M365 email of the user).
            photo_path (str):
                The file system path with the location of the photo file.

        Returns:
            dict | None:
                Response of Graph REST API or None if the user photo couldn't be updated.

        """

        request_url = self.config()["usersUrl"] + "/" + user_id + "/photo/$value"
        # Set image as content type:
        request_header = self.request_header("image/*")

        # Check if the photo file exists
        if not os.path.isfile(photo_path):
            self.logger.error("Photo file -> %s not found!", photo_path)
            return None

        try:
            # Read the photo file as binary data
            with open(photo_path, "rb") as image_file:
                photo_data = image_file.read()
        except OSError:
            # Handle any errors that occurred while reading the photo file
            self.logger.error(
                "Error reading photo file -> %s!",
                photo_path,
            )
            return None

        data = photo_data

        self.logger.debug(
            "Update M365 user with ID -> %s with photo -> %s; calling -> %s",
            user_id,
            photo_path,
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="PUT",
            headers=request_header,
            data=data,
            timeout=REQUEST_TIMEOUT,
            failure_message="Failed to update M365 user with ID -> {} with photo -> '{}'".format(
                user_id,
                photo_path,
            ),
        )

    # end method definition

    def get_user_drive(self, user_id: str, me: bool = False) -> dict | None:
        """Get the mysite (OneDrive) of the user.

        It may be required to do this before certain other operations
        are possible. These operations may require that the mydrive
        is initialized for that user. If you get errors like
        "User's mysite not found." this may be the case.

        Args:
            user_id (str):
                The M365 GUID of the user (can also be the M365 email of the user).
            me (bool, optional):
                Should be True if the user itself is accessing the drive.

        Returns:
            dict:
                A list of user licenses or None if request fails.

        Example:
        {
            '@odata.context': 'https://graph.microsoft.com/v1.0/$metadata#drives/$entity',
            'createdDateTime': '2025-04-10T23:43:26Z',
            'description': '',
            'id': 'b!VsxYN1IbrEqbiwMiba_M7FCkNAhL5LRFnQEZpEYbxDAxvvcvUMAhSqfgWW_4eAUP',
            'lastModifiedDateTime': '2025-04-12T15:50:20Z',
            'name': 'OneDrive',
            'webUrl': 'https://ideateqa-my.sharepoint.com/personal/jbenham_qa_idea-te_eimdemo_com/Documents',
            'driveType': 'business',
            'createdBy': {
                'user': {
                    'displayName': 'System Account'
                }
            },
            'lastModifiedBy': {
                'user': {
                    'email': 'jbenham@qa.idea-te.eimdemo.com',
                    'id': '470060cc-4d9f-439e-8a6e-8d567c5bda80',
                    'displayName': 'Jeff Benham'
                }
            },
            'owner': {
                'user': {...}
            },
            'quota': {
                'deleted': 0,
                'remaining': 1099511518137,
                'state': 'normal',
                'total': 1099511627776,
                'used': 109639
            }
        }

        """

        request_url = self.config()["meUrl"] if me else self.config()["usersUrl"] + "/" + user_id
        request_url += "/drive"
        request_header = self.request_header_user() if me else self.request_header()

        return self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=REQUEST_TIMEOUT,
            failure_message="Failed to get mySite (drive) of M365 user -> {}".format(user_id),
        )

    # end method definition

    def get_groups(
        self,
        max_number: int = 250,
        next_page_url: str | None = None,
    ) -> dict | None:
        """Get list all all groups in M365 tenant.

        Args:
            max_number (int, optional):
                The maximum result values (limit).
            next_page_url (str, optional):
                The MS Graph URL to retrieve the next page of M365 groups (pagination).
                This is used for the iterator get_groups_iterator() below.

        Returns:
            dict:
                A dictionary of all groups or None in case of an error.

        """

        request_url = next_page_url if next_page_url else self.config()["groupsUrl"]
        request_header = self.request_header()

        self.logger.debug(
            "Get list of all M365 groups%s; calling -> %s",
            " (paged)" if next_page_url else "",
            request_url,
        )

        response = self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            params={"$top": str(max_number)} if not next_page_url else None,
            timeout=REQUEST_TIMEOUT,
            failure_message="Failed to get list of M365 groups",
        )

        return response

    # end method definition

    def get_groups_iterator(
        self,
    ) -> iter:
        """Get an iterator object that can be used to traverse all M365 groups.

        Returning a generator avoids loading a large number of nodes into memory at once. Instead you
        can iterate over the potential large list of groups.

        Example usage:
            groups = m365_object.get_groups_iterator()
            for group in groups:
                logger.info("Traversing M365 group -> '%s'...", group.get("displayName", "<undefined name>"))

        Returns:
            iter:
                A generator yielding one M365 group per iteration.
                If the REST API fails, returns no value.

        """

        next_page_url = None

        while True:
            response = self.get_groups(
                next_page_url=next_page_url,
            )
            if not response or "value" not in response:
                # Don't return None! Plain return is what we need for iterators.
                # Natural Termination: If the generator does not yield, it behaves
                # like an empty iterable when used in a loop or converted to a list:
                return

            # Yield users one at a time:
            yield from response["value"]

            # See if we have an additional result page.
            # If not terminate the iterator and return
            # no value.
            next_page_url = response.get("@odata.nextLink", None)
            if not next_page_url:
                # Don't return None! Plain return is what we need for iterators.
                # Natural Termination: If the generator does not yield, it behaves
                # like an empty iterable when used in a loop or converted to a list:
                return

    # end method definition

    def get_group(self, group_name: str, show_error: bool = False) -> dict | None:
        """Get a M365 Group based on its name.

        Args:
            group_name (str):
                The M365 Group name.
            show_error (bool):
                Should an error be logged if group is not found.

        Returns:
            dict:
                Group information or None if the group doesn't exist.

        Example:
            {
                '@odata.context': 'https://graph.microsoft.com/v1.0/$metadata#groups',
                'value': [
                    {
                        'id': 'b65f7dba-3ed1-49df-91bf-2bf99affcc8d',
                        'deletedDateTime': None,
                        'classification': None,
                        'createdDateTime': '2023-04-01T13:46:26Z',
                        'creationOptions': [],
                        'description': 'Engineering & Construction',
                        'displayName': 'Engineering & Construction',
                        'expirationDateTime': None,
                        'groupTypes': ['Unified'],
                        'isAssignableToRole': None,
                        'mail': 'Engineering&Construction@M365x61936377.onmicrosoft.com',
                        'mailEnabled': True,
                        'mailNickname': 'Engineering&Construction',
                        'membershipRule': None,
                        'membershipRuleProcessingState': None,
                        'onPremisesDomainName': None,
                        'onPremisesLastSyncDateTime': None,
                        'onPremisesNetBiosName': None,
                        'onPremisesSamAccountName': None,
                        'onPremisesSecurityIdentifier': None,
                        'onPremisesSyncEnabled': None,
                        'preferredDataLocation': None,
                        'preferredLanguage': None,
                        'proxyAddresses': ['SPO:SPO_d9deb3e7-c72f-4e8d-80fb-5d9411ca1458@SPO_604f34f0-ba72-4321-ab6b-e36ae8bd00ec', ...],
                        'renewedDateTime': '2023-04-01T13:46:26Z',
                        'resourceBehaviorOptions': [],
                        'resourceProvisioningOptions': [],
                        'securityEnabled': False,
                        'securityIdentifier': 'S-1-12-1-3059711418-1239367377-4180393873-2379022234',
                        'theme': None,
                        'visibility': 'Public',
                        'onPremisesProvisioningErrors': []
                    },
                    {
                        'id': '61359860-302e-4016-b5cc-abff2293dff1',
                        ...
                    }
                ]
            }

        """

        query = {"$filter": "displayName eq '" + group_name + "'"}
        encoded_query = urllib.parse.urlencode(query, doseq=True)

        request_url = self.config()["groupsUrl"] + "?" + encoded_query
        request_header = self.request_header()

        self.logger.debug(
            "Get M365 group -> '%s'; calling -> %s",
            group_name,
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=REQUEST_TIMEOUT,
            failure_message="Failed to get M365 group -> '{}'".format(group_name),
            show_error=show_error,
        )

    # end method definition

    def add_group(
        self,
        name: str,
        security_enabled: bool = False,
        mail_enabled: bool = True,
    ) -> dict | None:
        """Add a M365 Group.

        Args:
            name (str):
                The name of the group.
            security_enabled (bool, optional):
                Whether or not this group is used for permission management.
            mail_enabled (bool, optional):
                Whether or not this group is email enabled.

        Returns:
            dict | None:
                Group information or None if the group couldn't be created (e.g. because it exisits already).

        Example:
            {
                '@odata.context': 'https://graph.microsoft.com/v1.0/$metadata#groups/$entity',
                'id': '28906460-a69c-439e-84ca-c70becf37655',
                'deletedDateTime': None,
                'classification': None,
                'createdDateTime': '2023-04-01T11:40:13Z',
                'creationOptions': [],
                'description': None,
                'displayName': 'Test',
                'expirationDateTime': None,
                'groupTypes': ['Unified'],
                'isAssignableToRole': None,
                'mail': 'Diefenbruch@M365x61936377.onmicrosoft.com',
                'mailEnabled': True,
                'mailNickname': 'Test',
                'membershipRule': None,
                'membershipRuleProcessingState': None,
                'onPremisesDomainName': None,
                'onPremisesLastSyncDateTime': None,
                'onPremisesNetBiosName': None,
                'onPremisesSamAccountName': None,
                'onPremisesSecurityIdentifier': None,
                'onPremisesSyncEnabled': None,
                'onPremisesProvisioningErrors': [],
                'preferredDataLocation': None,
                'preferredLanguage': None,
                'proxyAddresses': ['SMTP:Test@M365x61936377.onmicrosoft.com'],
                'renewedDateTime': '2023-04-01T11:40:13Z',
                'resourceBehaviorOptions': [],
                'resourceProvisioningOptions': [],
                'securityEnabled': True,
                'securityIdentifier': 'S-1-12-1-680551520-1134470812-197642884-1433859052',
                'theme': None,
                'visibility': 'Public'
            }

        """

        group_post_body = {
            "displayName": name,
            "mailEnabled": mail_enabled,
            "mailNickname": name.replace(" ", ""),
            "securityEnabled": security_enabled,
            "groupTypes": ["Unified"],
        }

        request_url = self.config()["groupsUrl"]
        request_header = self.request_header()

        self.logger.debug("Adding M365 group -> '%s'; calling -> %s", name, request_url)
        self.logger.debug("M365 group attributes -> %s", str(group_post_body))

        return self.do_request(
            url=request_url,
            method="POST",
            headers=request_header,
            data=json.dumps(group_post_body),
            timeout=REQUEST_TIMEOUT,
            failure_message="Failed to add M365 group -> '{}'".format(name),
        )

    # end method definition

    def get_group_members(self, group_name: str) -> dict | None:
        """Get members (users and groups) of the specified group.

        Args:
            group_name (str):
                The name of the group.

        Returns:
            dict | None:
                Response of Graph REST API or None if the REST call fails.

        """

        response = self.get_group(group_name=group_name)
        group_id = self.get_result_value(response=response, key="id", index=0)
        if not group_id:
            self.logger.error(
                "M365 Group -> '%s' does not exist! Cannot retrieve group members.",
                group_name,
            )
            return None

        query = {"$select": "id,displayName,mail,userPrincipalName"}
        encoded_query = urllib.parse.urlencode(query, doseq=True)

        request_url = self.config()["groupsUrl"] + "/" + group_id + "/members?" + encoded_query
        request_header = self.request_header()

        self.logger.debug(
            "Get members of M365 group -> %s (%s); calling -> %s",
            group_name,
            group_id,
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=REQUEST_TIMEOUT,
            failure_message="Failed to get members of M365 group -> '{}' ({})".format(
                group_name,
                group_id,
            ),
        )

    # end method definition

    def add_group_member(self, group_id: str, member_id: str) -> dict | None:
        """Add a member (user or group) to a (parent) group.

        Args:
            group_id (str):
                The M365 GUID of the group.
            member_id (str):
                The M365 GUID of the new member.

        Returns:
            dict | None:
                Response of the MS Graph API call or None if the call fails.

        """

        request_url = self.config()["groupsUrl"] + "/" + group_id + "/members/$ref"
        request_header = self.request_header()

        group_member_post_body = {
            "@odata.id": self.config()["directoryObjects"] + "/" + member_id,
        }

        self.logger.debug(
            "Adding member -> %s to group -> %s; calling -> %s",
            member_id,
            group_id,
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="POST",
            headers=request_header,
            data=json.dumps(group_member_post_body),
            timeout=REQUEST_TIMEOUT,
            failure_message="Failed to add member -> {} to M365 group -> {}".format(
                member_id,
                group_id,
            ),
        )

    # end method definition

    def is_member(self, group_id: str, member_id: str, show_error: bool = True) -> bool:
        """Check whether a M365 user is already in a M365 group.

        Args:
            group_id (str):
                The M365 GUID of the group.
            member_id (str):
                The M365 GUID of the user (member).
            show_error (bool):
                Whether or not an error should be logged if the user
                is not a member of the group.

        Returns:
            bool:
                True if the user is in the group. False otherwise.

        """

        # don't encode this URL - this has not been working!!
        request_url = self.config()["groupsUrl"] + f"/{group_id}/members?$filter=id eq '{member_id}'"
        request_header = self.request_header()

        self.logger.debug(
            "Check if user -> %s is in group -> %s; calling -> %s",
            member_id,
            group_id,
            request_url,
        )

        response = self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=REQUEST_TIMEOUT,
            failure_message="Failed to check if M365 user -> {} is in M365 group -> {}".format(
                member_id,
                group_id,
            ),
            show_error=show_error,
        )

        return bool(response and response.get("value"))

    # end method definition

    def get_group_owners(self, group_name: str) -> dict | None:
        """Get owners (users) of the specified group.

        Args:
            group_name (str):
                The name of the group.

        Returns:
            dict | None:
                Response of Graph REST API or None if the REST call fails.

        """

        response = self.get_group(group_name=group_name)
        group_id = self.get_result_value(response=response, key="id", index=0)
        if not group_id:
            self.logger.error(
                "M365 Group -> %s does not exist! Cannot retrieve group owners.",
                group_name,
            )
            return None

        query = {"$select": "id,displayName,mail,userPrincipalName"}
        encoded_query = urllib.parse.urlencode(query, doseq=True)

        request_url = self.config()["groupsUrl"] + "/" + group_id + "/owners?" + encoded_query
        request_header = self.request_header()

        self.logger.debug(
            "Get owners of M365 group -> %s (%s); calling -> %s",
            group_name,
            group_id,
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=REQUEST_TIMEOUT,
            failure_message="Failed to get owners of M365 group -> '{}' ({})".format(
                group_name,
                group_id,
            ),
        )

    # end method definition

    def add_group_owner(self, group_id: str, owner_id: str) -> dict | None:
        """Add an owner (user) to a group.

        Args:
            group_id (str):
                The M365 GUID of the group.
            owner_id (str):
                The M365 GUID of the new member.

        Returns:
            dict | None:
                The response of the MS Graph API call or None if the call fails.

        """

        request_url = self.config()["groupsUrl"] + "/" + group_id + "/owners/$ref"
        request_header = self.request_header()

        group_member_post_body = {
            "@odata.id": self.config()["directoryObjects"] + "/" + owner_id,
        }

        self.logger.debug(
            "Adding owner -> %s to M365 group -> %s; calling -> %s",
            owner_id,
            group_id,
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="POST",
            headers=request_header,
            data=json.dumps(group_member_post_body),
            timeout=REQUEST_TIMEOUT,
            failure_message="Failed to add owner -> {} to M365 group -> {}".format(
                owner_id,
                group_id,
            ),
        )

    # end method definition

    def purge_deleted_items(self) -> None:
        """Purge all deleted users and groups.

        Purging users and groups requires administrative rights that typically
        are not provided in Contoso example org.
        """

        request_header = self.request_header()

        request_url = self.config()["directoryUrl"] + "/deletedItems/microsoft.graph.group"
        response = requests.get(
            request_url,
            headers=request_header,
            timeout=REQUEST_TIMEOUT,
        )
        deleted_groups = self.parse_request_response(response) or {}

        for group in deleted_groups.get("value", []):
            group_id = group["id"]
            response = self.purge_deleted_item(group_id)

        request_url = self.config()["directoryUrl"] + "/deletedItems/microsoft.graph.user"
        response = requests.get(
            request_url,
            headers=request_header,
            timeout=REQUEST_TIMEOUT,
        )
        deleted_users = self.parse_request_response(response) or {}

        for user in deleted_users.get("value", []):
            user_id = user["id"]
            response = self.purge_deleted_item(user_id)

    # end method definition

    def purge_deleted_item(self, item_id: str) -> dict | None:
        """Purge a single deleted user or group.

        This requires elevated permissions that are typically
        not available via Graph API.

        Args:
            item_id (str):
                The M365 GUID of the item to purge.

        Returns:
            dict | None:
                Response of the MS Graph API call or None if the call fails.

        """

        request_url = self.config()["directoryUrl"] + "/deletedItems/" + item_id
        request_header = self.request_header()

        self.logger.debug(
            "Purging deleted item -> %s; calling -> %s",
            item_id,
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="DELETE",
            headers=request_header,
            timeout=REQUEST_TIMEOUT,
            failure_message="Failed to purge deleted item -> {}".format(item_id),
        )

    # end method definition

    def has_team(self, group_name: str) -> bool:
        """Check if a M365 Group has a M365 Team connected or not.

        Args:
            group_name (str):
                The name of the M365 group.

        Returns:
            bool:
                Returns True if a Team is assigned and False otherwise.

        """

        response = self.get_group(group_name=group_name)
        group_id = self.get_result_value(response=response, key="id", index=0)
        if not group_id:
            self.logger.error(
                "M365 Group -> '%s' not found! Cannot check if it has a M365 Team.",
                group_name,
            )
            return False

        request_url = self.config()["groupsUrl"] + "/" + group_id + "/team"
        request_header = self.request_header()

        self.logger.debug(
            "Check if M365 Group -> %s has a M365 Team connected; calling -> %s",
            group_name,
            request_url,
        )

        response = self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=REQUEST_TIMEOUT,
            failure_message="Failed to check if M365 Group -> '{}' has a M365 Team connected".format(
                group_name,
            ),
            parse_request_response=False,
            show_error=False,
        )

        if response and response.status_code == 200:  # Group has a Team assigned!
            self.logger.debug("Group -> '%s' has a M365 Team connected.", group_name)
            return True
        elif not response or response.status_code == 404:  # Group does not have a Team assigned!
            self.logger.debug("Group -> '%s' has no M365 Team connected.", group_name)
            return False

        return False

    # end method definition

    def get_team(self, name: str) -> dict | None:
        """Get a M365 Team based on its name.

        Args:
            name (str):
                The name of the M365 Team.

        Returns:
            dict | None:
                Teams data structure (dictionary) or None if the request fails.

        Example:
            {
                '@odata.context': 'https://graph.microsoft.com/v1.0/$metadata#teams',
                '@odata.count': 1,
                'value': [
                    {
                        'id': '951bd036-c6fc-4da4-bb80-1860f5472a2f',
                        'createdDateTime': None,
                        'displayName': 'Procurement',
                        'description': 'Procurement',
                        'internalId': None,
                        'classification': None,
                        'specialization': None,
                        'visibility': 'public',
                        'webUrl': None, ...}]}
                        'isArchived': None,
                        'isMembershipLimitedToOwners': None,
                        'memberSettings': None,
                        'guestSettings': None,
                        'messagingSettings': None,
                        ...
                    }
                ]
            }

        """

        # The M365 Teams API has an issues with ampersand characters in team names (like "Engineering & Construction")
        # So we do a work-around here to first get the Team ID via the Group endpoint of the Graph API and
        # then fetch the M365 Team via its ID (which is identical to the underlying M365 Group ID)
        response = self.get_group(group_name=name)
        team_id = self.get_result_value(response=response, key="id", index=0)
        if not team_id:
            self.logger.error(
                "Failed to get the ID of the M365 Team -> '%s' via the M365 Group API!",
                name,
            )
            return None

        request_url = self.config()["teamsUrl"] + "/" + str(team_id)

        request_header = self.request_header()

        self.logger.debug(
            "Lookup Microsoft 365 Teams with name -> '%s'; calling -> %s",
            name,
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=REQUEST_TIMEOUT,
            failure_message="Failed to get M365 Team -> '{}'".format(name),
        )

    # end method definition

    def add_team(self, name: str, template_name: str = "standard") -> dict | None:
        """Add M365 Team based on an existing M365 Group.

        Args:
            name (str):
                The name of the team. It is assumed that a group with the same name does already exist!
            template_name (str, optional):
                The name of the team template. "standard" is the default value.

        Returns:
            dict:
                Team information (json - empty text!) or None if the team couldn't be created
                (e.g. because it exisits already).

        """

        response = self.get_group(group_name=name)
        group_id = self.get_result_value(response=response, key="id", index=0)
        if not group_id:
            self.logger.error(
                "M365 Group -> '%s' not found! It is required for creating a corresponding M365 Team.",
                name,
            )
            return None

        response = self.get_group_owners(group_name=name)
        if response is None or "value" not in response or not response["value"]:
            self.logger.warning(
                "M365 Group -> '%s' has no owners. This is required for creating a corresponding M365 Team.",
                name,
            )
            return None

        team_post_body = {
            "template@odata.bind": "{}('{}')".format(
                self.config()["teamsTemplatesUrl"],
                template_name,
            ),
            "group@odata.bind": "{}('{}')".format(self.config()["groupsUrl"], group_id),
        }

        request_url = self.config()["teamsUrl"]
        request_header = self.request_header()

        self.logger.debug("Adding M365 Team -> '%s'; calling -> %s", name, request_url)
        self.logger.debug("M365 Team attributes -> %s", str(team_post_body))

        return self.do_request(
            url=request_url,
            method="POST",
            data=json.dumps(team_post_body),
            headers=request_header,
            timeout=REQUEST_TIMEOUT,
            failure_message="Failed to add M365 Team -> '{}'".format(name),
        )

    # end method definition

    def delete_team(self, team_id: str) -> dict | None:
        """Delete Microsoft 365 Team with a specific ID.

        Args:
            team_id (str):
                The ID of the Microsoft 365 Team to delete.

        Returns:
            dict | None:
                Response dictionary if the team has been deleted, False otherwise.

        """

        request_url = self.config()["groupsUrl"] + "/" + team_id

        request_header = self.request_header()

        self.logger.debug(
            "Delete Microsoft 365 Teams with ID -> %s; calling -> %s",
            team_id,
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="DELETE",
            headers=request_header,
            timeout=REQUEST_TIMEOUT,
            failure_message="Failed to delete M365 Team with ID -> {}".format(team_id),
        )

    # end method definition

    def delete_teams(self, name: str) -> bool:
        """Delete Microsoft 365 Teams with a specific name.

        Microsoft 365 allows to have multiple teams with the same name. So this method may delete
        multiple teams if the have the same name. The Graph API we use here
        is the M365 Group API as deleting the group also deletes the associated team.

        Args:
            name (str):
                The name of the Microsoft 365 Team.

        Returns:
            bool:
                True if teams have been deleted, False otherwise.

        """

        # We need a special handling of team names with single quotes:
        escaped_group_name = name.replace("'", "''")
        encoded_group_name = quote(escaped_group_name, safe="")
        request_url = self.config()["groupsUrl"] + "?$filter=displayName eq '{}'".format(encoded_group_name)

        request_header = self.request_header()

        self.logger.debug(
            "Delete all Microsoft 365 Teams with name -> '%s'; calling -> %s",
            name,
            request_url,
        )

        existing_teams = self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=REQUEST_TIMEOUT,
            failure_message="Failed to get list of M365 Teams to delete",
        )

        if existing_teams:
            data = existing_teams.get("value")
            if data:
                counter = 0
                for team in data:
                    team_id = team.get("id")
                    response = self.delete_team(team_id)

                    if not response:
                        self.logger.error(
                            "Failed to delete M365 Team -> '%s' (%s)!",
                            name,
                            team_id,
                        )
                        continue
                    counter += 1

                self.logger.info(
                    "%s M365 Team%s with name -> '%s' %s been deleted.",
                    str(counter),
                    "s" if counter > 1 else "",
                    name,
                    "have" if counter > 1 else "has",
                )
                return True
            else:
                self.logger.info("No M365 Team with name -> '%s' found.", name)
                return False
        else:
            self.logger.error("Failed to retrieve M365 Teams with name -> '%s'!", name)
            return False

    # end method definition

    def delete_all_teams(self, exception_list: list, pattern_list: list) -> bool:
        """Delete all teams (groups) based on patterns and exceptions.

        Only delete MS Teams that are NOT on the exception list AND
        that are matching at least one of the patterns in the provided pattern list.

        This method is used for general cleanup of teams. Be aware that deleted teams
        are still listed under https://admin.microsoft.com/#/deletedgroups and it
        may take some days until M365 finally deletes them.

        Args:
            exception_list (list):
                A list of group names that should not be deleted.
            pattern_list (list):
                A list of patterns for group names to be deleted
                (regular expression).

        Returns:
            bool:
                True if teams have been deleted, False otherwise.

        """

        self.logger.info(
            "Delete existing M365 groups/teams matching delete pattern and not on exception list...",
        )

        # Get list of all existing M365 groups/teams:
        groups = self.get_groups_iterator()

        # Process all groups and check if they should be deleted:
        for group in groups:
            group_name = group.get("displayName", None)
            if not group_name:
                continue
            # Check if group is in exception list:
            if group_name in exception_list:
                self.logger.info(
                    "M365 Group name -> '%s' is on the exception list. Skipping...",
                    group_name,
                )
                continue
            # Check that at least one pattern is found that matches the group:
            for pattern in pattern_list:
                result = re.search(pattern, group_name)
                if result:
                    self.logger.info(
                        "M365 Group name -> '%s' is matching pattern -> '%s'. Deleting...",
                        group_name,
                        pattern,
                    )
                    self.delete_teams(name=group_name)
                    break
            else:
                self.logger.info(
                    "M365 Group name -> '%s' is not matching any delete pattern. Skipping...",
                    group_name,
                )
        return True

    # end method definition

    def get_team_channels(self, name: str) -> dict | None:
        """Get channels of a M365 Team based on the team name.

        Args:
            name (str):
                The name of the M365 team.

        Returns:
            dict:
                The channel data structure (dictionary) or None if the request fails.

        Example:
            {
                '@odata.context': "https://graph.microsoft.com/v1.0/$metadata#teams('951bd036-c6fc-4da4-bb80-1860f5472a2f')/channels",
                '@odata.count': 1,
                'value': [
                    {
                        'id': '19:yPmPnXoFtvs5jmgL7fG-iXNENVMLsB_WSrxYK-zKakY1@thread.tacv2',
                        'createdDateTime': '2023-08-11T14:11:35.986Z',
                        'displayName': 'General',
                        'description': 'Procurement',
                        'isFavoriteByDefault': None,
                        'email': None,
                        'tenantId': '417e6e3a-82e6-4aa0-9d47-a7734ca3daea',
                        'webUrl': 'https://teams.microsoft.com/l/channel/19%3AyPmPnXoFtvs5jmgL7fG-iXNENVMLsB_WSrxYK-zKakY1%40thread.tacv2/Procurement?groupId=951bd036-c6fc-4da4-bb80-1860f5472a2f&tenantId=417e6e3a-82e6-4aa0-9d47-a7734ca3daea&allowXTenantAccess=False',
                        'membershipType': 'standard'
                    }
                ]
            }

        """

        response = self.get_team(name=name)
        team_id = self.get_result_value(response=response, key="id", index=0)
        if not team_id:
            return None

        request_url = self.config()["teamsUrl"] + "/" + str(team_id) + "/channels"

        request_header = self.request_header()

        self.logger.debug(
            "Retrieve channels of Microsoft 365 Team -> '%s'; calling -> %s",
            name,
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=REQUEST_TIMEOUT,
            failure_message="Failed to get Channels for M365 Team -> '{}' ({})".format(
                name,
                team_id,
            ),
        )

    # end method definition

    def get_team_channel_tabs(self, team_name: str, channel_name: str) -> dict | None:
        """Get tabs of an M365 Team channel based on the team and channel names.

        Args:
            team_name (str):
                The name of the M365 Team.
            channel_name (str):
                The name of the M365 Team channel.

        Returns:
            dict | None:
                Tabs data structure (dictionary) or None if the request fails.

        Example:
            {
                '@odata.context': "https://graph.microsoft.com/v1.0/$metadata#teams('951bd036-c6fc-4da4-bb80-1860f5472a2f')/channels('19%3AyPmPnXoFtvs5jmgL7fG-iXNENVMLsB_WSrxYK-zKakY1%40thread.tacv2')/tabs",
                '@odata.count': 1,
                'value': [
                    {
                        'id': '66f44e9a-0741-49a4-9500-ec82cc120115',
                        'displayName': 'Procurement',
                        'webUrl': 'https://teams.microsoft.com/l/entity/2851980b-95dc-4118-a1f5-5ae1894eaaaf/_djb2_msteams_prefix_66f44e9a-0741-49a4-9500-ec82cc120115?webUrl=https%3a%2f%2fotcs.fqdn.tld.com%2fcssupport%2fxecmoffice%2fteamsapp.html%3fnodeId%3d13178%26type%3dcontainer%26parentId%3d2000%26target%3dcontent%26csurl%3dhttps%3a%2f%2fotcs.fqdn.tld.com%2fcs%2fcs%26appId%3da168b00d-3ad9-46ac-8798-578c1961e1ed%26showBW%3dtrue%26title%3dProcurement&label=Procurement&context=%7b%0d%0a++%22canvasUrl%22%3a+%22https%3a%2f%2fotcs.fqdn.tld.com%2fcssupport%2fxecmoffice%2fteamsapp.html%3fnodeId%3d13178%26type%3dcontainer%26parentId%3d2000%26target%3dcontent%26csurl%3dhttps%3a%2f%2fotcs.fqdn.tld.com%2fcs%2fcs%26appId%3da168b00d-3ad9-46ac-8798-578c1961e1ed%22%2c%0d%0a++%22channelId%22%3a+%2219%3ayPmPnXoFtvs5jmgL7fG-iXNENVMLsB_WSrxYK-zKakY1%40thread.tacv2%22%2c%0d%0a++%22subEntityId%22%3a+null%0d%0a%7d&groupId=951bd036-c6fc-4da4-bb80-1860f5472a2f&tenantId=417e6e3a-82e6-4aa0-9d47-a7734ca3daea',
                        'configuration':
                        {
                            'entityId': '13178',
                            'contentUrl': 'https://otcs.fqdn.tld.com/cssupport/xecmoffice/teamsapp.html?nodeId=13178&type=container&parentId=2000&target=content&csurl=https://otcs.fqdn.tld.com/cs/cs&appId=a168b00d-3ad9-46ac-8798-578c1961e1ed',
                            'removeUrl': None,
                            'websiteUrl': 'https://otcs.fqdn.tld.com/cssupport/xecmoffice/teamsapp.html?nodeId=13178&type=container&parentId=2000&target=content&csurl=https://otcs.fqdn.tld.com/cs/cs&appId=a168b00d-3ad9-46ac-8798-578c1961e1ed&showBW=true&title=Procurement',
                            'dateAdded': '2023-08-12T08:57:35.895Z'
                        }
                    }
                ]
            }

        """

        response = self.get_team(name=team_name)
        team_id = self.get_result_value(response=response, key="id", index=0)
        if not team_id:
            return None

        # Get the channels of the M365 Team:
        response = self.get_team_channels(name=team_name)
        if not response or not response["value"] or not response["value"][0]:
            return None

        # Look the channel by name and then retrieve its ID:
        channel = next(
            (item for item in response["value"] if item["displayName"] == channel_name),
            None,
        )
        if not channel:
            self.logger.error(
                "Cannot find Channel -> '%s' on M365 Team -> '%s'!",
                channel_name,
                team_name,
            )
            return None
        channel_id = channel["id"]

        request_url = self.config()["teamsUrl"] + "/" + str(team_id) + "/channels/" + str(channel_id) + "/tabs"

        request_header = self.request_header()

        self.logger.debug(
            "Retrieve Tabs of Microsoft 365 Teams -> %s and Channel -> %s; calling -> %s",
            team_name,
            channel_name,
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=REQUEST_TIMEOUT,
            failure_message="Failed to get Tabs for M365 Team -> '{}' ({}) and Channel -> '{}' ({})".format(
                team_name,
                team_id,
                channel_name,
                channel_id,
            ),
        )

    # end method definition

    def get_teams_apps(self, filter_expression: str = "") -> dict | None:
        """Get a list of MS Teams apps in catalog that match a given filter criterium.

        Args:
            filter_expression (str, optional):
                Filter string see https://learn.microsoft.com/en-us/graph/filter-query-parameter

        Returns:
            dict | None:
                Response of the MS Graph API call or None if the call fails.

        Example:
            {
                '@odata.context': 'https://graph.microsoft.com/v1.0/$metadata#appCatalogs/teamsApps(appDefinitions())',
                '@odata.count': 1,
                'value': [
                    {
                        'id': '2851980b-95dc-4118-a1f5-5ae1894eaaaf',
                        'externalId': 'dd4af790-d8ff-47a0-87ad-486318272c7a',
                        'displayName': 'OpenText Extended ECM',
                        'distributionMethod': 'organization',
                        'appDefinitions@odata.context': "https://graph.microsoft.com/v1.0/$metadata#appCatalogs/teamsApps('2851980b-95dc-4118-a1f5-5ae1894eaaaf')/appDefinitions",
                        'appDefinitions': [
                            {
                                'id': 'Mjg1MTk4MGItOTVkYy00MTE4LWExZjUtNWFlMTg5NGVhYWFmIyMyMi40IyNQdWJsaXNoZWQ=',
                                'teamsAppId': '2851980b-95dc-4118-a1f5-5ae1894eaaaf',
                                'displayName': 'OpenText Extended ECM',
                                'version': '22.4',
                                'publishingState': 'published',
                                'shortDescription': 'Add a tab for an Extended ECM business workspace.',
                                'description': 'View and interact with OpenText Extended ECM business workspaces',
                                'lastModifiedDateTime': None,
                                'createdBy': None,
                                'authorization': {
                                    'requiredPermissionSet': {...}
                                }
                            }
                        ]
                    }
                ]
            }

        """

        query = {"$expand": "AppDefinitions"}

        if filter_expression:
            query["$filter"] = filter_expression

        encoded_query = urllib.parse.urlencode(query, doseq=True)
        request_url = self.config()["teamsAppsUrl"] + "?" + encoded_query

        if filter_expression:
            self.logger.debug(
                "Get list of MS Teams Apps using filter -> %s; calling -> %s",
                filter_expression,
                request_url,
            )
            failure_message = "Failed to get list of M365 Teams apps using filter -> {}".format(
                filter_expression,
            )
        else:
            self.logger.debug(
                "Get list of all MS Teams Apps; calling -> %s",
                request_url,
            )
            failure_message = "Failed to get list of M365 Teams apps"

        request_header = self.request_header()

        return self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=REQUEST_TIMEOUT,
            failure_message=failure_message,
        )

    # end method definition

    def get_teams_app(self, app_id: str) -> dict | None:
        """Get a specific MS Teams app in catalog based on the known (internal) app ID.

        Args:
            app_id (str):
                ID of the app (this is NOT the external ID but the internal ID).

        Returns:
            dict | None:
                Response of the MS Graph API call or None if the call fails.

        Examle:
            {
                '@odata.context': 'https://graph.microsoft.com/v1.0/$metadata#appCatalogs/teamsApps(appDefinitions())/$entity',
                'id': 'ccabe3fb-316f-40e0-a486-1659682cb8cd',
                'externalId': 'dd4af790-d8ff-47a0-87ad-486318272c7a',
                'displayName': 'Extended ECM',
                'distributionMethod': 'organization',
                'appDefinitions@odata.context': "https://graph.microsoft.com/v1.0/$metadata#appCatalogs/teamsApps('ccabe3fb-316f-40e0-a486-1659682cb8cd')/appDefinitions",
                'appDefinitions': [
                    {
                        'id': 'Y2NhYmUzZmItMzE2Zi00MGUwLWE0ODYtMTY1OTY4MmNiOGNkIyMyNC4yLjAjI1B1Ymxpc2hlZA==',
                        'teamsAppId': 'ccabe3fb-316f-40e0-a486-1659682cb8cd',
                        'displayName': 'Extended ECM',
                        'version': '24.2.0',
                        'publishingState': 'published',
                        'shortDescription': 'Add a tab for an Extended ECM business workspace.',
                        'description': 'View and interact with OpenText Extended ECM business workspaces',
                        'lastModifiedDateTime': None,
                        'createdBy': None,
                        'authorization': {...}
                    }
                ]
            }

        """

        query = {"$expand": "AppDefinitions"}
        encoded_query = urllib.parse.urlencode(query, doseq=True)
        request_url = self.config()["teamsAppsUrl"] + "/" + app_id + "?" + encoded_query

        self.logger.debug(
            "Get M365 Teams App with ID -> %s; calling -> %s",
            app_id,
            request_url,
        )

        request_header = self.request_header()

        response = self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=REQUEST_TIMEOUT,
            failure_message="Failed to get M365 Teams app with ID -> {}".format(app_id),
        )

        return response

    # end method definition

    def get_teams_apps_of_user(
        self,
        user_id: str,
        filter_expression: str = "",
    ) -> dict | None:
        """Get a list of MS Teams apps of a user that match a given filter criterium.

        Args:
            user_id (str):
                The M365 GUID of the user (can also be the M365 email of the user)
            filter_expression (str, optional):
                Filter string see https://learn.microsoft.com/en-us/graph/filter-query-parameter

        Returns:
            dict | None:
                Response of the MS Graph API call or None if the call fails.

        """

        query = {"$expand": "teamsAppDefinition"}
        if filter_expression:
            query["$filter"] = filter_expression

        encoded_query = urllib.parse.urlencode(query, doseq=True)
        request_url = self.config()["usersUrl"] + "/" + user_id + "/teamwork/installedApps?" + encoded_query

        self.logger.debug(
            "Get list of M365 Teams Apps for user -> %s using query -> %s; calling -> %s",
            user_id,
            query,
            request_url,
        )

        request_header = self.request_header()

        response = self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=REQUEST_TIMEOUT,
            failure_message="Failed to get M365 Teams apps for user -> {}".format(
                user_id,
            ),
        )

        return response

    # end method definition

    def get_teams_apps_of_team(
        self,
        team_id: str,
        filter_expression: str = "",
    ) -> dict | None:
        """Get a list of MS Teams apps of a M365 team that match a given filter criterium.

        Args:
            team_id (str):
                The M365 ID of the team.
            filter_expression (str, optional):
                Filter string see https://learn.microsoft.com/en-us/graph/filter-query-parameter

        Returns:
            dict | None:
                Response of the MS Graph API call or None if the call fails.

        """

        query = {"$expand": "teamsAppDefinition"}
        if filter_expression:
            query["$filter"] = filter_expression

        encoded_query = urllib.parse.urlencode(query, doseq=True)
        request_url = self.config()["teamsUrl"] + "/" + team_id + "/installedApps?" + encoded_query

        self.logger.debug(
            "Get list of M365 Teams Apps for M365 Team -> %s using query -> %s; calling -> %s",
            team_id,
            query,
            request_url,
        )

        request_header = self.request_header()

        return self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=REQUEST_TIMEOUT,
            failure_message="Failed to get list of M365 Teams apps for M365 Team -> {}".format(
                team_id,
            ),
        )

    # end method definition

    def extract_version_from_app_manifest(self, app_path: str) -> str | None:
        """Extract the version number from the MS Teams app manifest file.

        This can be used to check if the app package includes a newer
        app version then the already installed one.

        Args:
            app_path (str):
                The file path (with directory) to the app package to extract
                the version from.

        Returns:
            str | None:
                The version number or None in case of an error.

        """

        with zipfile.ZipFile(app_path, "r") as zip_ref:
            manifest_data = zip_ref.read("manifest.json")
            manifest_json = json.loads(manifest_data)
            version = manifest_json.get("version")

            return version

    # end method definition

    def upload_teams_app(
        self,
        app_path: str,
        update_existing_app: bool = False,
        app_catalog_id: str = "",
    ) -> dict | None:
        """Upload a new app package to the catalog of MS Teams apps.

        This is not possible with client secret credentials
        but requires a token of a user authenticated with username + password.
        See https://learn.microsoft.com/en-us/graph/api/teamsapp-publish
        (permissions table on that page).

        For updates see: https://learn.microsoft.com/en-us/graph/api/teamsapp-update?view=graph-rest-1.0&tabs=http

        Args:
            app_path (str):
                The file path (with directory) to the app package to upload.
            update_existing_app (bool, optional):
                Whether or not to update an existing app with the same name.
            app_catalog_id (str, optional):
                The unique ID of the app. It is the ID the app has in
                the catalog - which is different from ID an app gets
                after installation (which is tenant specific).

        Returns:
            dict:
                Response of the MS GRAPH API REST call or None if the request fails
                The responses are different depending if it is an install or upgrade!!

        Example return for upgrades ("teamsAppId" is the "internal" ID of the app):
            {
                '@odata.context': "https://graph.microsoft.com/v1.0/$metadata#appCatalogs/teamsApps('3f749cca-8cb0-4925-9fa0-ba7aca2014af')/appDefinitions/$entity",
                'id': 'M2Y3NDljY2EtOGNiMC00OTI1LTlmYTAtYmE3YWNhMjAxNGFmIyMyNC4yLjAjI1B1Ymxpc2hlZA==',
                'teamsAppId': '3f749cca-8cb0-4925-9fa0-ba7aca2014af',
                'displayName': 'IDEA-TE - Extended ECM 24.2.0',
                'version': '24.2.0',
                'publishingState': 'published',
                'shortDescription': 'Add a tab for an Extended ECM business workspace.',
                'description': 'View and interact with OpenText Extended ECM business workspaces',
                'lastModifiedDateTime': None,
                'createdBy': None,
                'authorization': {
                    'requiredPermissionSet': {...}
                }
            }

            Example return for new installations ("id" is the "internal" ID of the app):
            {
                '@odata.context': 'https://graph.microsoft.com/v1.0/$metadata#appCatalogs/teamsApps/$entity',
                'id': '6c672afd-37fc-46c6-8365-d499aba3808b',
                'externalId': 'dd4af790-d8ff-47a0-87ad-486318272c7a',
                'displayName': 'OpenText Extended ECM',
                'distributionMethod': 'organization'
            }

        """

        if update_existing_app and not app_catalog_id:
            self.logger.error(
                "To update an existing M365 Teams app in the app catalog you need to provide the existing App catalog ID!",
            )
            return None

        if not os.path.exists(app_path):
            self.logger.error("M365 Teams app file -> %s does not exist!", app_path)
            return None

        # Ensure that the app file is a zip file
        if not app_path.endswith(".zip"):
            self.logger.error("M365 Teams app file -> %s must be a zip file!", app_path)
            return None

        request_url = self.config()["teamsAppsUrl"]
        # If we want to upgrade an existing app we add the app ID and
        # the specific endpoint:
        if update_existing_app:
            request_url += "/" + app_catalog_id + "/appDefinitions"

        # Here we need the credentials of an authenticated user!
        # (not the application credentials (client_id, client_secret))
        request_header = self.request_header_user(content_type="application/zip")

        with open(app_path, "rb") as f:
            app_data = f.read()

        with zipfile.ZipFile(app_path) as z:
            # Ensure that the app file contains a manifest.json file
            if "manifest.json" not in z.namelist():
                self.logger.error(
                    "M365 Teams app file -> '%s' does not contain a manifest.json file!",
                    app_path,
                )
                return None

        self.logger.debug(
            "Upload M365 Teams app -> '%s' to the MS Teams catalog; calling -> %s",
            app_path,
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="POST",
            headers=request_header,
            data=app_data,
            timeout=REQUEST_TIMEOUT,
            failure_message="Failed to update existing M365 Teams app -> '{}' (may be because it is not a new version)".format(
                app_path,
            ),
        )

    # end method definition

    def remove_teams_app(self, app_id: str) -> None:
        """Remove MS Teams App from the app catalog.

        Args:
            app_id (str):
                The Microsoft 365 GUID of the MS Teams app.

        """

        request_url = self.config()["teamsAppsUrl"] + "/" + app_id
        # Here we need the credentials of an authenticated user!
        # (not the application credentials (client_id, client_secret))
        request_header = self.request_header_user()

        # Make the DELETE request to remove the app from the app catalog
        response = requests.delete(
            request_url,
            headers=request_header,
            timeout=REQUEST_TIMEOUT,
        )

        # Check the status code of the response
        if response.status_code == 204:
            self.logger.debug(
                "The M365 Teams app with ID -> %s has been successfully removed from the app catalog.",
                app_id,
            )
        else:
            self.logger.error(
                "An error occurred while removing the M365 Teams app from the M365 app catalog. Status code -> %s. Error message -> %s",
                response.status_code,
                response.text,
            )

    # end method definition

    def assign_teams_app_to_user(
        self,
        user_id: str,
        app_name: str = "",
        app_internal_id: str = "",
        show_error: bool = False,
    ) -> dict | None:
        """Assign (add) a M365 Teams app to a M365 user.

        See: https://learn.microsoft.com/en-us/graph/api/userteamwork-post-installedapps?view=graph-rest-1.0&tabs=http

        Args:
            user_id (str):
                The M365 GUID of the user (can also be the M365 email of the user).
            app_name (str, optional):
                The exact name of the app. Not needed if app_internal_id is provided.
            app_internal_id (str, optional):
                The internal ID of the app. If not provided it will be derived from app_name.
            show_error (bool, optional):
                Whether or not an error should be displayed if the user is not found.

        Returns:
            dict | None:
                The response of the MS Graph API call or None if the call fails.

        """

        if not app_internal_id and not app_name:
            self.logger.error(
                "Either the internal App ID or the App name need to be provided!",
            )
            return None

        if not app_internal_id:
            response = self.get_teams_apps(
                filter_expression="contains(displayName, '{}')".format(app_name),
            )
            app_internal_id = self.get_result_value(
                response=response,
                key="id",
                index=0,
            )
            if not app_internal_id:
                self.logger.error(
                    "M365 Teams App -> '%s' not found! Cannot assign App to user -> %s.",
                    app_name,
                    user_id,
                )
                return None

        request_url = self.config()["usersUrl"] + "/" + user_id + "/teamwork/installedApps"
        request_header = self.request_header()

        post_body = {
            "teamsApp@odata.bind": self.config()["teamsAppsUrl"] + "/" + app_internal_id,
        }

        self.logger.debug(
            "Assign M365 Teams app -> '%s' (%s) to M365 user -> %s; calling -> %s",
            app_name,
            app_internal_id,
            user_id,
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="POST",
            headers=request_header,
            json_data=post_body,
            timeout=REQUEST_TIMEOUT,
            failure_message="Failed to assign M365 Teams app -> '{}' ({}) to M365 user -> {}".format(
                app_name,
                app_internal_id,
                user_id,
            ),
            warning_message="Failed to assign M365 Teams app -> '{}' ({}) to M365 user -> {} (could be the app is assigned organization-wide)".format(
                app_name,
                app_internal_id,
                user_id,
            ),
            show_error=show_error,
        )

    # end method definition

    def upgrade_teams_app_of_user(
        self,
        user_id: str,
        app_name: str,
        app_installation_id: str | None = None,
    ) -> dict | None:
        """Upgrade a MS teams app for a user.

        The call will fail if the user does not already have the app assigned.
        So this needs to be checked before calling this method.

        See: https://learn.microsoft.com/en-us/graph/api/userteamwork-teamsappinstallation-upgrade?view=graph-rest-1.0&tabs=http

        Args:
            user_id (str):
                The M365 GUID of the user (can also be the M365 email of the user).
            app_name (str):
                The exact name of the app.
            app_installation_id (str | None, optional):
                The ID of the app installation for the user. This is neither the internal nor
                external app ID. It is specific for each user and app.

        Returns:
            dict | None:
                Response of the MS Graph API call or None if the call fails.

        """

        if not app_installation_id:
            response = self.get_teams_apps_of_user(
                user_id=user_id,
                filter_expression="contains(teamsAppDefinition/displayName, '{}')".format(
                    app_name,
                ),
            )
            # Retrieve the installation specific App ID - this is different from thew App catalalog ID!!
            app_installation_id = self.get_result_value(response=response, key="id", index=0)
        if not app_installation_id:
            self.logger.error(
                "M365 Teams app -> '%s' not found for user with ID -> %s. Cannot upgrade app for this user!",
                app_name,
                user_id,
            )
            return None

        request_url = (
            self.config()["usersUrl"] + "/" + user_id + "/teamwork/installedApps/" + app_installation_id + "/upgrade"
        )
        request_header = self.request_header()

        self.logger.debug(
            "Upgrade M365 Teams app -> '%s' (%s) of M365 user with ID -> %s; calling -> %s",
            app_name,
            app_installation_id,
            user_id,
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="POST",
            headers=request_header,
            timeout=REQUEST_TIMEOUT,
            failure_message="Failed to upgrade M365 Teams app -> '{}' ({}) of M365 user -> {}".format(
                app_name,
                app_installation_id,
                user_id,
            ),
        )

    # end method definition

    def remove_teams_app_from_user(
        self,
        user_id: str,
        app_name: str,
        app_installation_id: str | None = None,
    ) -> dict | None:
        """Remove a M365 Teams app from a M365 user.

           See: https://learn.microsoft.com/en-us/graph/api/userteamwork-delete-installedapps?view=graph-rest-1.0&tabs=http

        Args:
            user_id (str):
                The M365 GUID of the user (can also be the M365 email of the user).
            app_name (str):
                The exact name of the app.
            app_installation_id (str | None):
                The installation ID of the app. Default is None.

        Returns:
            dict:
                Response of the MS Graph API call or None if the call fails.

        """

        if not app_installation_id:
            response = self.get_teams_apps_of_user(
                user_id=user_id,
                filter_expression="contains(teamsAppDefinition/displayName, '{}')".format(
                    app_name,
                ),
            )
            # Retrieve the installation specific App ID - this is different from thew App catalalog ID!!
            app_installation_id = self.get_result_value(response=response, key="id", index=0)
        if not app_installation_id:
            self.logger.error(
                "M365 Teams app -> '%s' not found for user with ID -> %s. Cannot remove app from this user!",
                app_name,
                user_id,
            )
            return None

        request_url = self.config()["usersUrl"] + "/" + user_id + "/teamwork/installedApps/" + app_installation_id
        request_header = self.request_header()

        self.logger.debug(
            "Remove M365 Teams app -> '%s' (%s) from M365 user with ID -> %s; calling -> %s",
            app_name,
            app_installation_id,
            user_id,
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="DELETE",
            headers=request_header,
            timeout=REQUEST_TIMEOUT,
            failure_message="Failed to remove M365 Teams app -> '{}' ({}) from M365 user -> {}".format(
                app_name,
                app_installation_id,
                user_id,
            ),
        )

    # end method definition

    def assign_teams_app_to_team(self, team_id: str, app_id: str) -> dict | None:
        """Assign (add) a MS Teams app to a M365 team.

        Afterwards the app can be added as a Tab in a M365 Teams Channel).

        Args:
            team_id (str):
                The ID of the Microsoft 365 Team.
            app_id (str):
                The ID of the M365 Team App.

        Returns:
            dict | None:
                API response or None if the Graph API call fails.

        """

        request_url = self.config()["teamsUrl"] + "/" + team_id + "/installedApps"
        request_header = self.request_header()

        post_body = {
            "teamsApp@odata.bind": self.config()["teamsAppsUrl"] + "/" + app_id,
        }

        self.logger.debug(
            "Assign M365 Teams app -> '%s' (%s) to M365 Team -> %s; calling -> %s",
            self.config()["teamsAppName"],
            app_id,
            team_id,
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="POST",
            headers=request_header,
            json_data=post_body,
            timeout=REQUEST_TIMEOUT,
            failure_message="Failed to assign M365 Teams app -> '{}' ({}) to M365 Team -> {}".format(
                self.config()["teamsAppName"],
                app_id,
                team_id,
            ),
        )

    # end method definition

    def upgrade_teams_app_of_team(self, team_id: str, app_name: str) -> dict | None:
        """Upgrade a MS teams app for a specific team.

        The call will fail if the team does not already have the app assigned.
        So this needs to be checked before calling this method.

        THIS IS CURRENTLY NOT WORKING AS EXPECTED.

        Args:
            team_id (str):
                M365 GUID of the user (can also be the M365 email of the user).
            app_name (str):
                The exact name of the app.

        Returns:
            dict:
                The response of the MS Graph API call or None if the call fails.

        """

        response = self.get_teams_apps_of_team(
            team_id=team_id,
            filter_expression="contains(teamsAppDefinition/displayName, '{}')".format(app_name),
        )
        # Retrieve the installation specific App ID - this is different from thew App catalalog ID!!
        app_installation_id = self.get_result_value(response=response, key="id", index=0)
        if not app_installation_id:
            self.logger.error(
                "M365 Teams app -> '%s' not found for M365 Team with ID -> %s. Cannot upgrade app for this team!",
                app_name,
                team_id,
            )
            return None

        request_url = self.config()["teamsUrl"] + "/" + team_id + "/installedApps/" + app_installation_id + "/upgrade"
        request_header = self.request_header()

        self.logger.debug(
            "Upgrade app -> '%s' (%s) of M365 team with ID -> %s; calling -> %s",
            app_name,
            app_installation_id,
            team_id,
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="POST",
            headers=request_header,
            timeout=REQUEST_TIMEOUT,
            failure_message="Failed to upgrade M365 Teams app -> '{}' ({}) of M365 team with ID -> {}".format(
                app_name,
                app_installation_id,
                team_id,
            ),
        )

    # end method definition

    def add_teams_app_to_channel(
        self,
        team_name: str,
        channel_name: str,
        app_id: str,
        tab_name: str,
        app_url: str,
        cs_node_id: int,
    ) -> dict | None:
        """Add tab for Extended ECM app to an M365 Team channel.

        Args:
            team_name (str):
                The name of the M365 Team
            channel_name (str):
                The name of the channel.
            app_id (str):
                ID of the MS Teams Application (e.g. the Extended ECM Teams App).
            tab_name (str):
                The name of the tab.
            app_url (str):
                The web URL of the app.
            cs_node_id (int):
                The node ID of the target workspace or container in Extended ECM.

        Returns:
            dict:
                Return data structure (dictionary) or None if the request fails.

            Example return data:

        """

        response = self.get_team(name=team_name)
        team_id = self.get_result_value(response=response, key="id", index=0)
        if not team_id:
            return None

        # Get the channels of the M365 Team:
        response = self.get_team_channels(name=team_name)
        if not response or not response["value"] or not response["value"][0]:
            return None

        # Look the channel by name and then retrieve its ID:
        channel = next(
            (item for item in response["value"] if item["displayName"] == channel_name),
            None,
        )
        if not channel:
            self.logger.error(
                "Cannot find Channel -> '%s' on M365 Team -> '%s'!",
                channel_name,
                team_name,
            )
            return None
        channel_id = channel["id"]

        request_url = self.config()["teamsUrl"] + "/" + str(team_id) + "/channels/" + str(channel_id) + "/tabs"

        request_header = self.request_header()

        # Create tab configuration payload:
        tab_config = {
            "teamsApp@odata.bind": f"https://graph.microsoft.com/v1.0/appCatalogs/teamsApps/{app_id}",
            "displayName": tab_name,
            "configuration": {
                "entityId": cs_node_id,  # Unique identifier for the tab
                "contentUrl": app_url,
                "removeUrl": "",
                "websiteUrl": app_url + "&showBW=true&title=" + tab_name,
            },
        }

        self.logger.debug(
            "Add Tab -> '%s' with App ID -> %s to Channel -> '%s' of Microsoft 365 Team -> '%s'; calling -> %s",
            tab_name,
            app_id,
            channel_name,
            team_name,
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="POST",
            headers=request_header,
            json_data=tab_config,
            timeout=REQUEST_TIMEOUT,
            failure_message="Failed to add Tab for M365 Team -> '{}' ({}) and Channel -> '{}' ({})".format(
                team_name,
                team_id,
                channel_name,
                channel_id,
            ),
        )

    # end method definition

    def update_teams_app_of_channel(
        self,
        team_name: str,
        channel_name: str,
        tab_name: str,
        app_url: str,
        cs_node_id: int,
    ) -> dict | None:
        """Update an existing tab for Extended ECM app in an M365 Team channel.

        Args:
            team_name (str):
                The name of the M365 Team.
            channel_name (str):
                The name of the channel.
            tab_name (str):
                The name of the tab.
            app_url (str):
                The web URL of the app.
            cs_node_id (int):
                The node ID of the target workspace or container in Content Server.

        Returns:
            dict:
                Return data structure (dictionary) or None if the request fails.

        """

        response = self.get_team(name=team_name)
        team_id = self.get_result_value(response=response, key="id", index=0)
        if not team_id:
            return None

        # Get the channels of the M365 Team:
        response = self.get_team_channels(name=team_name)
        if not response or not response["value"] or not response["value"][0]:
            return None

        # Look the channel by name and then retrieve its ID:
        channel = next(
            (item for item in response["value"] if item["displayName"] == channel_name),
            None,
        )
        if not channel:
            self.logger.error(
                "Cannot find Channel -> '%s' for M365 Team -> '%s'!",
                channel_name,
                team_name,
            )
            return None
        channel_id = channel["id"]

        # Get the tabs of the M365 Team channel:
        response = self.get_team_channel_tabs(team_name=team_name, channel_name=channel_name)
        if not response or not response["value"] or not response["value"][0]:
            return None

        # Look the tab by name and then retrieve its ID:
        tab = next(
            (item for item in response["value"] if item["displayName"] == tab_name),
            None,
        )
        if not tab:
            self.logger.error(
                "Cannot find Tab -> '%s' on M365 Team -> '%s' (%s) and Channel -> '%s' (%s)!",
                tab_name,
                team_name,
                team_id,
                channel_name,
                channel_id,
            )
            return None
        tab_id = tab["id"]

        request_url = (
            self.config()["teamsUrl"] + "/" + str(team_id) + "/channels/" + str(channel_id) + "/tabs/" + str(tab_id)
        )

        request_header = self.request_header()

        # Create tab configuration payload:
        tab_config = {
            "configuration": {
                "entityId": cs_node_id,  # Unique identifier for the tab
                "contentUrl": app_url,
                "removeUrl": "",
                "websiteUrl": app_url + "&showBW=true&title=" + tab_name,
            },
        }

        self.logger.debug(
            "Update Tab -> '%s' (%s) of Channel -> '%s' (%s) for Microsoft 365 Teams -> '%s' (%s) with configuration -> %s; calling -> %s",
            tab_name,
            tab_id,
            channel_name,
            channel_id,
            team_name,
            team_id,
            str(tab_config),
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="PATCH",
            headers=request_header,
            json_data=tab_config,
            timeout=REQUEST_TIMEOUT,
            failure_message="Failed to update Tab -> '{}' ({}) for M365 Team -> '{}' ({}) and Channel -> '{}' ({})".format(
                tab_name,
                tab_id,
                team_name,
                team_id,
                channel_name,
                channel_id,
            ),
        )

    # end method definition

    def delete_teams_app_from_channel(
        self,
        team_name: str,
        channel_name: str,
        tab_name: str,
    ) -> bool:
        """Delete an existing tab for Extended ECM app from an M365 Team channel.

        Args:
            team_name (str):
                The name of the M365 Team.
            channel_name (str):
                The name of the channel.
            tab_name (str):
                The name of the tab.

        Returns:
            bool:
                True = success, False = Error.

        """

        response = self.get_team(name=team_name)
        team_id = self.get_result_value(response=response, key="id", index=0)
        if not team_id:
            return False

        # Get the channels of the M365 Team:
        response = self.get_team_channels(team_name)
        if not response or not response["value"] or not response["value"][0]:
            return False

        # Look the channel by name and then retrieve its ID:
        channel = next(
            (item for item in response["value"] if item["displayName"] == channel_name),
            None,
        )
        if not channel:
            self.logger.error(
                "Cannot find Channel -> '%s' for M365 Team -> '%s'!",
                channel_name,
                team_name,
            )
            return False
        channel_id = channel["id"]

        # Get the tabs of the M365 Team channel:
        response = self.get_team_channel_tabs(team_name=team_name, channel_name=channel_name)
        if not response or not response["value"] or not response["value"][0]:
            return False

        # Lookup the tabs by name and then retrieve their IDs (in worst case it can
        # be multiple tabs / apps with same name if former cleanups did not work):
        tab_list = [item for item in response["value"] if item["displayName"] == tab_name]
        if not tab_list:
            self.logger.error(
                "Cannot find Tab -> '%s' on M365 Team -> '%s' (%s) and Channel -> '%s' (%s)!",
                tab_name,
                team_name,
                team_id,
                channel_name,
                channel_id,
            )
            return False

        for tab in tab_list:
            tab_id = tab["id"]

            request_url = (
                self.config()["teamsUrl"] + "/" + str(team_id) + "/channels/" + str(channel_id) + "/tabs/" + str(tab_id)
            )

            request_header = self.request_header()

            self.logger.debug(
                "Delete Tab -> '%s' (%s) from Channel -> '%s' (%s) of Microsoft 365 Teams -> '%s' (%s); calling -> %s",
                tab_name,
                tab_id,
                channel_name,
                channel_id,
                team_name,
                team_id,
                request_url,
            )

            response = self.do_request(
                url=request_url,
                method="DELETE",
                headers=request_header,
                timeout=REQUEST_TIMEOUT,
                failure_message="Failed to delete Tab -> '{}' ({}) for M365 Team -> '{}' ({}) and Channel -> '{}' ({})".format(
                    tab_name,
                    tab_id,
                    team_name,
                    team_id,
                    channel_name,
                    channel_id,
                ),
                parse_request_response=False,
            )

            if response and response.ok:
                break
            return False
        # end for tab in tab_list

        return True

    # end method definition

    def add_sensitivity_label(
        self,
        name: str,
        display_name: str,
        description: str = "",
        color: str = "red",
        enabled: bool = True,
        admin_description: str = "",
        user_description: str = "",
        enable_encryption: bool = False,
        enable_marking: bool = False,
    ) -> dict | None:
        """Create a new sensitivity label in M365.

        TODO: THIS IS CURRENTLY NOT WORKING!

        Args:
            name (str):
                The name of the label.
            display_name (str):
                The display name of the label.
            description (str, optional):
                Description of the label. Defaults to "".
            color (str, optional):
                Color of the label. Defaults to "red".
            enabled (bool, optional):
                Whether this label is enabled. Defaults to True.
            admin_description (str, optional):
                Description for administrators. Defaults to "".
            user_description (str, optional):
                Description for users. Defaults to "".
            enable_encryption (bool, optional):
                Enable encryption. Defaults to False.
            enable_marking (bool, optional):
                Enable marking. Defaults to False.

        Returns:
            Request reponse or None if the request fails.

        """

        # Prepare the request body
        payload = {
            "displayName": display_name,
            "description": description,
            "isEnabled": enabled,
            "labelColor": color,
            "adminDescription": admin_description,
            "userDescription": user_description,
            "encryptContent": enable_encryption,
            "contentMarking": enable_marking,
        }

        request_url = self.config()["securityUrl"] + "/sensitivityLabels"
        request_header = self.request_header()

        self.logger.debug(
            "Create M365 sensitivity label -> '%s'; calling -> %s",
            name,
            request_url,
        )

        # Send the POST request to create the label
        response = requests.post(
            request_url,
            headers=request_header,
            data=json.dumps(payload),
            timeout=REQUEST_TIMEOUT,
        )

        # Check the response status code
        if response.status_code == 201:
            self.logger.debug("Label -> '%s' has been created successfully!", name)
            return response
        else:
            self.logger.error(
                "Failed to create the M365 label -> '%s'! Response status code -> %s",
                name,
                response.status_code,
            )
            return None

    # end method definition

    def assign_sensitivity_label_to_user(self, user_email: str, label_name: str) -> dict | None:
        """Assign a existing sensitivity label to a user.

        TODO: THIS IS CURRENTLY NOT WORKING!

        Args:
            user_email (str):
                The email address of the user (as unique identifier).
            label_name (str):
                The name of the label (need to exist).

        Returns:
            dict | None:
                Return the request response or None if the request fails.

        """

        # Set up the request body with the label name
        body = {"labelName": label_name}

        request_url = self.config()["usersUrl"] + "/" + user_email + "/assignSensitivityLabels"
        request_header = self.request_header()

        self.logger.debug(
            "Assign label -> '%s' to user -> '%s'; calling -> %s",
            label_name,
            user_email,
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="POST",
            headers=request_header,
            json_data=body,
            timeout=REQUEST_TIMEOUT,
            failure_message="Failed to assign label -> '{}' to M365 user -> '{}'".format(
                label_name,
                user_email,
            ),
        )

    # end method definition

    def upload_outlook_app(
        self,
        app_path: str,
    ) -> dict | None:
        """Upload the M365 Outlook Add-In as "Integrated" App to M365 Admin Center.

        TODO: THIS IS CURRENTLY NOT IMPLEMENTED DUE TO MISSING MS GRAPH API SUPPORT!

        https://admin.microsoft.com/#/Settings/IntegratedApps

        Args:
            app_path (str):
                Path to manifest file in local file system. Needs to be
                downloaded before.

        Returns:
            dict | None:
                Response of the MS Graph API or None if the request fails.

        """

        self.logger.debug(
            "Install Outlook Add-in from -> '%s' (NOT IMPLEMENTED)",
            app_path,
        )

        response = None

        return response

    # end method definition

    def get_app_registration(
        self,
        app_registration_name: str,
    ) -> dict | None:
        """Find an Azure App Registration based on its name.

        Args:
            app_registration_name (str):
                Name of the App Registration.

        Returns:
            dict | None:
                App Registration data or None of the request fails.

        """

        request_url = self.config()["applicationsUrl"] + "?$filter=displayName eq '{}'".format(app_registration_name)
        request_header = self.request_header()

        self.logger.debug(
            "Get Azure App Registration -> '%s'; calling -> %s",
            app_registration_name,
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=REQUEST_TIMEOUT,
            failure_message="Cannot find Azure App Registration -> '{}'".format(
                app_registration_name,
            ),
        )

    # end method definition

    def add_app_registration(
        self,
        app_registration_name: str,
        description: str = "",
        api_permissions: list | None = None,
        supported_account_type: str = "AzureADMyOrg",
    ) -> dict:
        """Add an Azure App Registration.

        Args:
            app_registration_name (str):
                The name of the App Registration.
            description (str, optional):
                The description of the app.
            api_permissions (list | None, optional):
                The API permissions.
            supported_account_type (str, optional):
                The type of account that is supposed to use
                the App Registration.

        Returns:
            dict:
                App Registration data or None of the request fails.

            Example data:
            {
                'id': 'd70bee91-3689-4239-a626-30756968e99c',
                'deletedDateTime': None,
                'appId': 'd288ba5f-9313-4b38-b4a4-d7edcce089b0',
                'applicationTemplateId': None,
                'disabledByMicrosoftStatus': None,
                'createdDateTime': '2023-09-06T21:06:05Z',
                'displayName': 'Test 1',
                'description': None,
                'groupMembershipClaims': None,
                'identifierUris': [],
                'isDeviceOnlyAuthSupported': None,
                'isFallbackPublicClient': None,
                'notes': None,
                'publisherDomain': 'M365x41497014.onmicrosoft.com',
                'signInAudience': 'AzureADMyOrg',
                ...
                'requiredResourceAccess': [
                    {
                        'resourceAppId': '00000003-0000-0ff1-ce00-000000000000',
                        'resourceAccess': [
                            {
                                'id': '741f803b-c850-494e-b5df-cde7c675a1ca',
                                'type': 'Role'
                            },
                            {
                                'id': 'c8e3537c-ec53-43b9-bed3-b2bd3617ae97',
                                'type': 'Role'
                            },
                        ]
                    },
                ]
            }

        """

        # Define the request body to create the App Registration
        app_registration_data = {
            "displayName": app_registration_name,
            "signInAudience": supported_account_type,
        }
        if api_permissions:
            app_registration_data["requiredResourceAccess"] = api_permissions
        if description:
            app_registration_data["description"] = description

        request_url = self.config()["applicationsUrl"]
        request_header = self.request_header()

        return self.do_request(
            url=request_url,
            method="POST",
            headers=request_header,
            json_data=app_registration_data,
            timeout=REQUEST_TIMEOUT,
            failure_message="Cannot add App Registration -> '{}'".format(
                app_registration_name,
            ),
        )

    # end method definition

    def update_app_registration(
        self,
        app_registration_id: str,
        app_registration_name: str,
        api_permissions: list,
        supported_account_type: str = "AzureADMyOrg",
    ) -> dict:
        """Update an Azure App Registration.

        Args:
            app_registration_id (str):
                The ID of the existing App Registration.
            app_registration_name (str):
                The name of the App Registration.
            api_permissions (list):
                The API permissions.
            supported_account_type (str, optional):
                The type of account that is supposed to use
                the App Registration.

        Returns:
            dict:
                App Registration data or None of the request fails.

        """

        # Define the request body to create the App Registration
        app_registration_data = {
            "displayName": app_registration_name,
            "requiredResourceAccess": api_permissions,
            "signInAudience": supported_account_type,
        }

        request_url = self.config()["applicationsUrl"] + "/" + app_registration_id
        request_header = self.request_header()

        self.logger.debug(
            "Update App Registration -> '%s' (%s); calling -> %s",
            app_registration_name,
            app_registration_id,
            request_url,
        )

        return self.do_request(
            url=request_url,
            method="PATCH",
            headers=request_header,
            json_data=app_registration_data,
            timeout=REQUEST_TIMEOUT,
            failure_message="Cannot update App Registration -> '{}' ({})".format(
                app_registration_name,
                app_registration_id,
            ),
        )

    # end method definition

    def get_mail(
        self,
        user_id: str,
        sender: str,
        subject: str,
        num_emails: int | None = None,
        show_error: bool = False,
    ) -> dict | None:
        """Get email from inbox of a given user and a given sender (from).

        This requires Mail.Read Application permissions for the Azure App being used.

        Args:
            user_id (str):
                The M365 ID of the user.
            sender (str):
                The sender email address to filter for.
            subject (str):
                The subject to filter for.
            num_emails (int, optional):
                The number of matching emails to retrieve.
            show_error (bool, optional):
                Whether or not an error should be displayed if the
                user is not found.

        Returns:
            dict:
                Email or None of the request fails.

        """

        # Attention: you  can easily run in limitation of the MS Graph API. If selection + filtering
        # is too complex you can get this error: "The restriction or sort order is too complex for this operation."
        # that's why we first just do the ordering and then do the filtering on sender and subject
        # separately
        request_url = (
            self.config()["usersUrl"]
            + "/"
            + user_id
            #            + "/messages?$filter=from/emailAddress/address eq '{}' and contains(subject, '{}')&$orderby=receivedDateTime desc".format(
            + "/messages?$orderby=receivedDateTime desc"
        )
        if num_emails:
            request_url += "&$top={}".format(num_emails)

        request_header = self.request_header()

        self.logger.debug(
            "Get mails for user -> %s from -> '%s' with subject -> '%s'; calling -> %s",
            user_id,
            sender,
            subject,
            request_url,
        )

        response = self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=REQUEST_TIMEOUT,
            failure_message="Cannot retrieve emails for M365 user -> {}".format(user_id),
            show_error=show_error,
        )

        if response and "value" in response:
            messages = response["value"]

            # Filter the messages by sender and subject in code
            filtered_messages = [
                msg
                for msg in messages
                if msg.get("from", {}).get("emailAddress", {}).get("address") == sender
                and subject in msg.get("subject", "")
            ]
            response["value"] = filtered_messages
            return response

        return None

    # end method definition

    def get_mail_body(self, user_id: str, email_id: str) -> str | None:
        """Get full email body for a given email ID.

        This requires Mail.Read Application permissions for the Azure App being used.

        Args:
            user_id (str):
                The M365 ID of the user.
            email_id (str):
                The M365 ID of the email.

        Returns:
            str | None:
                Email body or None of the request fails.

        """

        request_url = self.config()["usersUrl"] + "/" + user_id + "/messages/" + email_id + "/$value"

        request_header = self.request_header()

        response = self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=REQUEST_TIMEOUT,
            failure_message="Cannot get email body for M365 user -> {} and email with ID -> {}".format(
                user_id,
                email_id,
            ),
            parse_request_response=False,
        )

        if response and response.ok and response.content:
            return response.content.decode("utf-8")

        return None

    # end method definition

    def extract_url_from_message_body(
        self,
        message_body: str,
        search_pattern: str,
        multi_line: bool = False,
        multi_line_end_marker: str = "%3D",
        line_end_marker: str = "=",
        replacements: list | None = None,
    ) -> str | None:
        """Parse the email body to extract (a potentially multi-line) URL from the body.

        Args:
            message_body (str):
                Text of the Email body.
            search_pattern (str):
                Pattern that needs to be in first line of the URL. This
                makes sure it is the right URL we are looking for.
            multi_line (bool, optional):
                Is the URL spread over multiple lines?. Defaults to False.
            multi_line_end_marker (str, optional):
                If it is a multi-line URL, what marks the end
                of the URL in the last line? Defaults to "%3D".
            line_end_marker (str, optional):
                What marks the end of lines 1-(n-1)? Defaults to "=".
            replacements (list, optional):
                A list of replacements.

        Returns:
            str | None:
                The URL text that has been extracted. None in case of an error.

        """

        if not message_body:
            return None

        # Split all the lines after a CRLF:
        lines = [line.strip() for line in message_body.split("\r\n")]

        # Filter out the complete URL from the extracted URLs
        found = False

        url = ""

        for line in lines:
            if found:
                # Remove line end marker - many times a "="
                if line.endswith(line_end_marker):
                    line = line[:-1]
                for replacement in replacements:
                    line = line.replace(replacement["from"], replacement["to"])
                # We consider an empty line after we found the URL to indicate the end of the URL:
                if line == "":
                    break
                url += line
            if multi_line and line.endswith(multi_line_end_marker):
                break
            if search_pattern not in line:
                continue
            # Fine https:// in the current line:
            index = line.find("https://")
            if index == -1:
                continue
            # If there's any text in front of https in that line cut it:
            line = line[index:]
            # Remove line end marker - many times a "="
            if line.endswith(line_end_marker):
                line = line[:-1]
            for replacement in replacements:
                line = line.replace(replacement["from"], replacement["to"])
            found = True
            url += line
            if not multi_line:
                break

        return url

    # end method definition

    def delete_mail(self, user_id: str, email_id: str) -> dict | None:
        """Delete email from inbox of a given user and a given email ID.

        This requires Mail.ReadWrite Application permissions for the Azure App being used.

        Args:
            user_id (str):
                The M365 ID of the user.
            email_id (str):
                The M365 ID of the email.

        Returns:
            dict | None:
                Email or None of the request fails.

        """

        request_url = self.config()["usersUrl"] + "/" + user_id + "/messages/" + email_id

        request_header = self.request_header()

        return self.do_request(
            url=request_url,
            method="DELETE",
            headers=request_header,
            timeout=REQUEST_TIMEOUT,
            failure_message="Cannot delete email with ID -> {} from inbox of M365 user -> {}".format(
                email_id,
                user_id,
            ),
        )

    # end method definition

    def email_verification(
        self,
        user_email: str,
        sender: str,
        subject: str,
        url_search_pattern: str,
        line_end_marker: str = "=",
        multi_line: bool = True,
        multi_line_end_marker: str = "%3D",
        replacements: list | None = None,
        max_retries: int = 6,
        use_browser_automation: bool = False,
        password: str = "",
        password_field_id: str = "",
        password_confirmation_field_id: str = "",
        password_submit_xpath: str = "",
        terms_of_service_xpath: str = "",
    ) -> bool:
        """Process email verification.

        Args:
            user_email (str):
                Email address of user recieving the verification mail.
            sender (str):
                Email sender (address)
            subject (str):
                Email subject to look for (can be substring)
            url_search_pattern (str):
                String the URL needs to contain to identify it.
            line_end_marker (str, optional):
                The character that marks line ends in the mail.
            multi_line (bool, optional):
                Whether or not this is a multi-line mail.
            multi_line_end_marker (str, optional):
                If the URL spans multiple lines this is the "end" marker for the last line.
            replacements (list, optional):
                If the URL needs some treatment these replacements can be applied.
            max_retries (int, optional):
                The number of retries in case of an error.
            use_browser_automation (bool, optional):
                If Selenium-based browser automation should be used or not. Default = False.
            password (str, optional):
                In case a password is required for browser automation. Default = "",
            password_field_id (str, optional):
                The password field name in the HTML page of a confirmation dialog. Default = "",
            password_confirmation_field_id (str, optional):
                The password confirmation field name in the HTML page of a confirmation dialog.
                Default = "".
            password_submit_xpath (str, optional):
                Default = "".
            terms_of_service_xpath (str, optional):
                Default = "".

        Returns:
            bool:
                True = Success, False = Failure.

        """

        # Determine the M365 user for the current user by
        # the email address:
        m365_user = self.get_user(user_email=user_email)
        m365_user_id = self.get_result_value(response=m365_user, key="id")
        if not m365_user_id:
            self.logger.warning("Cannot find M365 user -> %s", user_email)
            return False

        if replacements is None:
            replacements = [{"from": "=3D", "to": "="}]

        retries = 0
        while retries < max_retries:
            response = self.get_mail(
                user_id=m365_user_id,
                sender=sender,
                subject=subject,
                show_error=False,
            )
            if response and response["value"]:
                emails = response["value"]
                # potentially there may be multiple matching emails,
                # we want the most recent one (from today):
                latest_email = max(emails, key=lambda x: x["receivedDateTime"])
                # Extract just the date:
                latest_email_date = latest_email["receivedDateTime"].split("T")[0]
                # Get the current date (today):
                today_date = datetime.now(UTC).strftime("%Y-%m-%d")
                # We do a sanity check here: the verification mail should be from today,
                # otherwise we assume it is an old mail and we need to wait for the
                # new verification mail to yet arrive:
                if latest_email_date != today_date:
                    self.logger.info(
                        "Verification email not yet received (latest mail from -> %s). Waiting %s seconds...",
                        latest_email_date,
                        10 * (retries + 1),
                    )
                    time.sleep(10 * (retries + 1))
                    retries += 1
                    continue
                email_id = latest_email["id"]
                # The full email body needs to be loaded with a separate REST call:
                body_text = self.get_mail_body(user_id=m365_user_id, email_id=email_id)
                # Extract the verification URL.
                if body_text:
                    url = self.extract_url_from_message_body(
                        message_body=body_text,
                        search_pattern=url_search_pattern,
                        line_end_marker=line_end_marker,
                        multi_line=multi_line,
                        multi_line_end_marker=multi_line_end_marker,
                        replacements=replacements,
                    )
                else:
                    url = ""
                if not url:
                    self.logger.warning(
                        "Cannot find verification link in the email body!",
                    )
                    return False
                # Simulate a "click" on this URL:
                if use_browser_automation:
                    self.logger.info("Using browser automation for email verification...")
                    # Core Share needs a full browser:
                    try:
                        browser_automation_object = BrowserAutomation(
                            take_screenshots=True,
                            automation_name="email-verification",
                            logger=self.logger,
                        )
                    except Exception:
                        self.logger.error("Failed to create browser automation object. Bailing out...")
                        return False

                    self.logger.info(
                        "Open URL -> %s to verify account or email address change...",
                        url,
                    )
                    success = browser_automation_object.get_page(url=url)
                    if success:
                        user_interaction_required = False
                        self.logger.info(
                            "Successfully opened URL. Browser title is -> '%s'.",
                            browser_automation_object.get_title(),
                        )
                        if password_field_id:
                            password_field = browser_automation_object.find_elem(
                                selector=password_field_id,
                                show_error=False,
                            )
                            if password_field:
                                # The subsequent processing is only required if
                                # the returned page requests a password change:
                                user_interaction_required = True
                                self.logger.info(
                                    "Found password field on returned page - it seems email verification requests password entry!",
                                )
                                result = browser_automation_object.find_elem_and_set(
                                    selector=password_field_id,
                                    value=password,
                                    is_sensitive=True,
                                )
                                if not result:
                                    self.logger.error(
                                        "Failed to enter password in field -> '%s'!",
                                        password_field_id,
                                    )
                                    success = False
                            else:
                                self.logger.info(
                                    "No user interaction required (no password change or terms of service acceptance).",
                                )
                        if user_interaction_required and password_confirmation_field_id:
                            password_confirm_field = browser_automation_object.find_elem(
                                selector=password_confirmation_field_id,
                                show_error=False,
                            )
                            if password_confirm_field:
                                self.logger.info(
                                    "Found password confirmation field on returned page - it seems email verification requests consecutive password.",
                                )
                                result = browser_automation_object.find_elem_and_set(
                                    selector=password_confirmation_field_id,
                                    value=password,
                                    is_sensitive=True,
                                )
                                if not result:
                                    self.logger.error(
                                        "Failed to enter password in field -> '%s'!",
                                        password_confirmation_field_id,
                                    )
                                    success = False
                        if user_interaction_required and password_submit_xpath:
                            password_submit_button = browser_automation_object.find_elem(
                                selector=password_submit_xpath,
                                selector_type="xpath",
                                show_error=False,
                            )
                            if password_submit_button:
                                self.logger.info(
                                    "Submit password change dialog with button -> '%s' (found with XPath -> %s).",
                                    password_submit_button.inner_text(),
                                    password_submit_xpath,
                                )
                                result = browser_automation_object.find_elem_and_click(
                                    selector=password_submit_xpath,
                                    selector_type="xpath",
                                )
                                if not result:
                                    self.logger.error(
                                        "Failed to press submit button -> %s",
                                        password_submit_xpath,
                                    )
                                    success = False
                            # The Terms of service dialog has some weird animation
                            # which require a short wait time. It seems it is required!
                            time.sleep(1)
                            terms_accept_button = browser_automation_object.find_elem(
                                selector=terms_of_service_xpath,
                                selector_type="xpath",
                                show_error=False,
                            )
                            if terms_accept_button:
                                self.logger.info(
                                    "Accept terms of service with button -> '%s' (found with XPath -> %s).",
                                    terms_accept_button.inner_text(),
                                    terms_of_service_xpath,
                                )
                                result = browser_automation_object.find_elem_and_click(
                                    selector=terms_of_service_xpath,
                                    selector_type="xpath",
                                )
                                if not result:
                                    self.logger.error(
                                        "Failed to accept terms of service with button -> '%s'!",
                                        terms_accept_button.inner_text(),
                                    )
                                    success = False
                            else:
                                self.logger.info(
                                    "No Terms of Service acceptance required.",
                                )
                        # end if user_interaction_required and password_submit_xpath:
                    # end if success:
                # end if use_browser_automation
                else:
                    # Salesforce (other than Core Share) is OK with the simple HTTP GET request:
                    self.logger.info(
                        "Open URL -> %s to verify account or email change...",
                        url,
                    )
                    response = self._http_object.http_request(url=url, method="GET")
                    success = response and response.ok

                if success:
                    self.logger.info(
                        "Remove email from inbox of user -> %s...",
                        user_email,
                    )
                    response = self.delete_mail(user_id=m365_user_id, email_id=email_id)
                    if not response:
                        self.logger.warning(
                            "Couldn't remove the mail from the inbox of user -> %s!",
                            user_email,
                        )
                    # We have success now and can break from the while loop
                    return True
                else:
                    self.logger.error(
                        "Failed to process e-mail verification for user -> %s!",
                        user_email,
                    )
                    return False
            # end if response and response["value"]
            else:
                self.logger.info(
                    "Verification email not yet received (no mails with sender -> %s and subject -> '%s' found). Waiting %s seconds...",
                    sender,
                    subject,
                    10 * (retries + 1),
                )
                time.sleep(10 * (retries + 1))
                retries += 1
        # end while

        self.logger.warning(
            "Verification mail for user -> %s has not arrived in time.",
            user_email,
        )

        return False

    # end method definition

    def get_sharepoint_sites(
        self,
        search: str | None = None,
        filter_expression: str | None = None,
        select: str | None = None,
        limit: int = 50,
        next_page_url: str | None = None,
    ) -> dict | None:
        """Retrieve a list of SharePoint sites.

        Args:
            search (str, optional):
                A string to search for to filter the results. Default is None = no filtering.
            filter_expression (str | None, optional):
                Filter string to filter the results. Default is None = no filtering.
            select (str | None, optional):
                Fields to select. Make sure that all fields are selected that are used in filters.
                Otherwise you will get no results.
            limit (int, optional):
                The maximum number of sites to return in one call.
                Default is set to 50.
            next_page_url (str | None, optional):
                The MS Graph URL to retrieve the next page of SharePoint sites (pagination).
                This is used for the iterator get_sharepoint_sites_iterator() below.

        Returns:
            dict | None:
                A list of SharePoint sites embedded in a "value" key in the dictionary.

        Example response:
        {
            '@odata.context': 'https://graph.microsoft.com/beta/$metadata#sites',
            '@odata.nextLink': 'https://graph.microsoft.com/beta/sites?$top=50&$skiptoken=UGFnZWQ9VFJVRSZwX1RpbWVEZWxldGVkPSZwX0lEPTE5MDM4',
            'value': [
                {
                    'createdDateTime': '2025-02-11T12:11:49Z',
                    'id': 'ideatedev-my.sharepoint.com,eeed2961-91ba-46c1-abc2-159f0277130f,5aa8a98d-659d-4a52-8701-6b9a728092d8',
                    'name': 'Diane Conner',
                    'webUrl': 'https://ideatedev-my.sharepoint.com/personal/dconner_dev_idea-te_eimdemo_com',
                    'displayName': 'Diane Conner',
                    'isPersonalSite': True,
                    'siteCollection': {
                        'hostname': 'ideatedev-my.sharepoint.com'
                    },
                    'root': {}
                },
                {
                    'createdDateTime': '2025-02-06T07:44:44Z',
                    'id': 'ideatedev.sharepoint.com,570e67bc-1e69-4a62-89ea-994be9642b93,a1462b54-26f9-4a24-9660-2bc7859ce9af',
                    'name': 'SG325B - SEMI325B,ECM,PD,ExternalProcurement',
                    'webUrl': 'https://ideatedev.sharepoint.com/sites/SG325B-SEMI325BECMPDExternalProcurement698',
                    'displayName': 'SG325B - SEMI325B,ECM,PD,ExternalProcurement',
                    'isPersonalSite': False,
                    'siteCollection': {
                        'hostname': 'ideatedev.sharepoint.com'
                    },
                    'root': {}
                },
                ...
            ]
        ]

        """

        if not next_page_url:
            query = {}
            if select:
                query["$select"] = select
            if filter_expression:
                query["$filter"] = filter_expression
            if search:
                query["search"] = search
            if limit:
                query["$top"] = limit

            encoded_query = "?" + urllib.parse.urlencode(query, doseq=True) if query else ""
            request_url = self.config()["sitesUrl"] + encoded_query
        else:
            request_url = next_page_url
        request_header = self.request_header()

        response = self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=REQUEST_TIMEOUT,
            failure_message="Cannot get SharePoint sites",
        )

        return response

    # end method definition

    def get_sharepoint_root_sites(self) -> dict | None:
        """Get all SharePoint root sites.

        Returns:
            dict | None:
                Dictionary that includes a list of root sites in the "value" key.

        """

        response = self.get_sharepoint_sites(
            select="siteCollection,webUrl",
            filter_expression="siteCollection/root ne null",
        )

        return response

    # end method definition

    def get_sharepoint_sites_iterator(
        self,
        search: str | None = None,
        filter_expression: str | None = None,
        select: str | None = None,
        limit: int = 50,
    ) -> iter:
        """Get an iterator object that can be used to traverse all SharePoint sites matching the filter.

        Returning a generator avoids loading a large number of nodes into memory at once. Instead you
        can iterate over the potential large list of SharePoint sites.

        Example usage:
            sites = m365_object.get_sharepoint_sites_iterator(limit=10)
            for site in sites:
                logger.info("Traversing SharePoint site -> '%s'...", site.get("name", "<undefined name>"))

        Args:
            search (str | None, optional):
                A string to search for to filter the results. Default is None = no filtering.
            filter_expression (str | None, optional):
                Filter string to filter the results. Default is None = no filtering.
            select (str | None, optional):
                Fields to select. Make sure that all fields are selected that are used in filters.
                Otherwise you will get no results.
            limit (int, optional):
                The maximum number of sites to return in one call.
                Default is set to 50.

        Returns:
            iter:
                A generator yielding one SharePoint site per iteration.
                If the REST API fails, returns no value.

        """

        next_page_url = None

        while True:
            response = self.get_sharepoint_sites(
                search=search,
                filter_expression=filter_expression,
                select=select,
                limit=limit,
                next_page_url=next_page_url,
            )
            if not response or "value" not in response:
                # Don't return None! Plain return is what we need for iterators.
                # Natural Termination: If the generator does not yield, it behaves
                # like an empty iterable when used in a loop or converted to a list:
                return

            # Yield users one at a time:
            yield from response["value"]

            # See if we have an additional result page.
            # If not terminate the iterator and return
            # no value.
            next_page_url = response.get("@odata.nextLink", None)
            if not next_page_url:
                # Don't return None! Plain return is what we need for iterators.
                # Natural Termination: If the generator does not yield, it behaves
                # like an empty iterable when used in a loop or converted to a list:
                return

    # end method definition

    def get_sharepoint_site(self, site_id: str) -> dict | None:
        """Retrieve a SharePoint site by its ID.

        Args:
            site_id (str):
                The ID of the SharePoint site the to retrieve.

        Returns:
            dict | None:
                The data of the SharePoint site.

        Example:
        {
            '@odata.context': 'https://graph.microsoft.com/beta/$metadata#sites/$entity',
            'createdDateTime': '2025-02-06T07:41:53.41Z',
            'description': '',
            'id': 'ideatedev.sharepoint.com,9b203cbe-27ca-45b2-944a-663cc99e5e8f,a1462b54-26f9-4a24-9660-2bc7859ce9af',
            'lastModifiedDateTime': '2025-02-10T20:37:11Z',
            'name': 'TG11-Trad.Good11PDReg.Trading795',
            'webUrl': 'https://ideatedev.sharepoint.com/sites/TG11-Trad.Good11PDReg.Trading795',
            'displayName': 'TG11 - Trad.Good 11,PD,Reg.Trading',
            'root': {},
            'siteCollection': {
                'hostname': 'ideatedev.sharepoint.com'
            }
        }

        """

        request_url = self.config()["sitesUrl"] + "/" + site_id

        request_header = self.request_header()

        response = self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=REQUEST_TIMEOUT,
            failure_message="Cannot get SharePoint site with ID -> '{}'".format(site_id),
        )

        return response

    # end method definition

    def get_sharepoint_site_by_name(self, site_name: str) -> dict | None:
        """Retrieve a SharePoint site by its name.

        Args:
            site_name (str):
                The name of the SharePoint site to retrieve.

        Returns:
            dict | None:
                The data of the SharePoint site.

        Example:
        {
            '@odata.context': 'https://graph.microsoft.com/beta/$metadata#sites/$entity',
            'createdDateTime': '2025-02-06T07:41:53.41Z',
            'description': '',
            'id': 'ideatedev.sharepoint.com,9b203cbe-27ca-45b2-944a-663cc99e5e8f,a1462b54-26f9-4a24-9660-2bc7859ce9af',
            'lastModifiedDateTime': '2025-02-10T20:37:11Z',
            'name': 'TG11-Trad.Good11PDReg.Trading795',
            'webUrl': 'https://ideatedev.sharepoint.com/sites/TG11-Trad.Good11PDReg.Trading795',
            'displayName': 'TG11 - Trad.Good 11,PD,Reg.Trading',
            'root': {},
            'siteCollection': {
                'hostname': 'ideatedev.sharepoint.com'
            }
        }

        """

        request_url = self.config()["sitesUrl"] + "?search={}".format(site_name)

        request_header = self.request_header()

        response = self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=REQUEST_TIMEOUT,
            failure_message="Cannot get SharePoint site -> '{}'".format(site_name),
        )

        # As we lookup the site by search we could have multiple results.
        # The Graph API does not do an exact match. So we check the results
        # for an exact match:
        if response:
            results = response.get("value", [])
            for result in results:
                if result["displayName"] == site_name:
                    return result

        return None

    # end method definition

    def get_sharepoint_site_for_group(self, group_id: str) -> dict:
        """Retrieve a SharePoint site for a M365 group.

        Args:
            group_id (str):
                The ID of the M365 group the site should be retrieved for.

        Returns:
            dict:
                The data of the SharePoint site.

        Example:
        {
            '@odata.context': 'https://graph.microsoft.com/beta/$metadata#sites/$entity',
            'createdDateTime': '2025-02-06T07:41:53.41Z',
            'description': '',
            'id': 'ideatedev.sharepoint.com,9b203cbe-27ca-45b2-944a-663cc99e5e8f,a1462b54-26f9-4a24-9660-2bc7859ce9af',
            'lastModifiedDateTime': '2025-02-10T20:37:11Z',
            'name': 'TG11-Trad.Good11PDReg.Trading795',
            'webUrl': 'https://ideatedev.sharepoint.com/sites/TG11-Trad.Good11PDReg.Trading795',
            'displayName': 'TG11 - Trad.Good 11,PD,Reg.Trading',
            'root': {},
            'siteCollection': {
                'hostname': 'ideatedev.sharepoint.com'
            }
        }

        """

        request_url = self.config()["groupsUrl"] + "/" + group_id + "/sites/root"
        request_header = self.request_header()

        response = self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=REQUEST_TIMEOUT,
            failure_message="Cannot get SharePoint site for group with ID -> '{}'".format(group_id),
        )

        return response

    # end method definition

    def get_sharepoint_pages(self, site_id: str) -> dict:
        """Retrieve a list of SharePoint site pages accessible to the authenticated user.

        Args:
            site_id (str):
                The ID of the SharePoint site the pages should be retrieved for.

        Returns:
            dict:
                A dictionary including the list of SharePoint pages for a given page.
                The actual list is included inside the "value" key of the dictionary.

        Example:
        {
            '@odata.context': "https://graph.microsoft.com/beta/$metadata#sites('ideatedev.sharepoint.com%2C61c0f9cb-39d3-4c04-b60c-31576954a2ab%2Ca678aeab-68ac-46a1-bd95-28020c12de26')/pages",
            'value': [
                {
                    '@odata.type': '#microsoft.graph.sitePage',
                    '@odata.etag': '"{A546CE61-21E6-431D-B2CD-67D1F722BE5F},4"',
                    'createdDateTime': '2025-01-26T00:03:24Z',
                    'eTag': '"{A546CE61-21E6-431D-B2CD-67D1F722BE5F},4"',
                    'id': 'a546ce61-21e6-431d-b2cd-67d1f722be5f',
                    'lastModifiedDateTime': '2025-01-26T00:03:24Z',
                    'name': 'Home.aspx',
                    'webUrl': 'https://ideatedev.sharepoint.com/sites/TG11-Trad.Good11PDReg.Trading795/SitePages/Home.aspx',
                    'title': 'Home',
                    'pageLayout': 'home',
                    'promotionKind': 'page',
                    'showComments': False,
                    'showRecommendedPages': False,
                    'contentType': {
                        'id': '0x0101009D1CB255DA76424F860D91F20E6C411800813863BBF9FE6A408AE59965D98FE3DA',
                        'name': 'Site Page'
                    },
                    'createdBy': {'user': {'displayName': 'System Account'}},
                    'lastModifiedBy': {'user': {'displayName': 'Terrarium Admin', 'email': 'admin@dev.idea-te.eimdemo.com'}},
                    'parentReference': {'siteId': '61c0f9cb-39d3-4c04-b60c-31576954a2ab'},
                    'publishingState': {'level': 'published', 'versionId': '4.0'},
                    'reactions': {}
                },
                ...
            ]
        }

        """

        request_url = self.config()["sitesUrl"] + "/" + str(site_id) + "/pages"

        request_header = self.request_header()

        response = self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=REQUEST_TIMEOUT,
            failure_message="Cannot get pages of SharePoint site with ID -> '{}'".format(site_id),
        )

        return response

    # end method definition

    def get_sharepoint_page(self, site_id: str, page_id: str) -> dict | None:
        """Retrieve a page of a SharePoint site accessible to the authenticated user.

        Args:
            site_id (str):
                The ID of the SharePoint site the page should be get for.
            page_id (str):
                The ID of the page to be retrieved.

        Returns:
            dict | None:
                A SharePoint site page.

        Example:
        {
            '@odata.context': "https://graph.microsoft.com/beta/$metadata#sites('ideatedev.sharepoint.com%2C9b203cbe-27ca-45b2-944a-663cc99e5e8f%2Ca1462b54-26f9-4a24-9660-2bc7859ce9af')/pages/$entity",
            '@odata.type': '#microsoft.graph.sitePage',
            '@odata.etag': '"{A546CE61-21E6-431D-B2CD-67D1F722BE5F},4"',
            'createdDateTime': '2025-01-26T00:03:24Z',
            'eTag': '"{A546CE61-21E6-431D-B2CD-67D1F722BE5F},4"',
            'id': 'a546ce61-21e6-431d-b2cd-67d1f722be5f',
            'lastModifiedDateTime': '2025-01-26T00:03:24Z',
            'name': 'Home.aspx',
            'webUrl': 'https://ideatedev.sharepoint.com/sites/TG11-Trad.Good11PDReg.Trading795/SitePages/Home.aspx',
            'title': 'Home',
            'pageLayout': 'home',
            'promotionKind': 'page',
            'showComments': False,
            'showRecommendedPages': False,
            'contentType': {
                'id': '0x0101009D1CB255DA76424F860D91F20E6C4118003CD261A156017A45BA0F28B5923AE8F6',
                'name': 'Site Page'
            },
            'createdBy': {
                'user': {...}
            },
            'lastModifiedBy': {
                'user': {...}
            },
            'parentReference': {
                'siteId': '9b203cbe-27ca-45b2-944a-663cc99e5e8f'
            },
            'publishingState': {
                'level': 'published',
                'versionId': '1.0'
            },
            'reactions': {}
        }

        """

        request_url = self.config()["sitesUrl"] + "/" + site_id + "/pages/" + page_id

        request_header = self.request_header()

        response = self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=REQUEST_TIMEOUT,
            failure_message="Cannot get SharePoint page -> '{}' for site -> '{}'".format(page_id, site_id),
        )

        return response

    # end method definition

    def add_sharepoint_page(self, site_id: str, page_name: str, publish: bool = True) -> dict:
        """Add a new SharePoint site page using Microsoft Graph API.

        Args:
            site_id (str):
                The ID of the SharePoint site the page should be created on.
            page_name (str):
                The name/title of the new page.
            publish (bool, optional):
                If True, the page is immediately published.

        Returns:
            dict:
                Details of the created SharePoint page or an error response.

        """

        request_url = self.config()["sitesUrl"] + "/" + site_id + "/pages"
        request_header = self.request_header()

        # Page payload for a basic site page
        payload = {
            "@odata.type": "#microsoft.graph.sitePage",
            "name": page_name + ".aspx",
            "title": page_name,
            "publishingState": {
                "level": "published",
            },
        }

        response = self.do_request(
            url=request_url,
            method="POST",
            headers=request_header,
            json_data=payload,
            timeout=REQUEST_TIMEOUT,
            failure_message="Failed to create SharePoint page -> '{}' in SharePoint site -> '{}'".format(
                page_name,
                site_id,
            ),
        )

        # Check if the page should be directly published:
        if response and publish:
            page_id = self.get_result_value(response=response, key="id")
            self.publish_sharepoint_page(site_id=site_id, page_id=page_id)

        return response

    # end method definition

    def publish_sharepoint_page(self, site_id: str, page_id: str) -> bool:
        """Publish a page of a SharePoint site.

        Args:
            site_id (str):
                The ID of the SharePoint site the page should be published on.
            page_id (str):
                The ID of the page to be published.

        Returns:
            bool:
                True = Success, False = Error.

        """

        request_url = (
            self.config()["sitesUrl"] + "/" + site_id + "/pages/" + page_id + "/microsoft.graph.sitePage/publish"
        )

        request_header = self.request_header()

        response = self.do_request(
            url=request_url,
            method="POST",
            headers=request_header,
            timeout=REQUEST_TIMEOUT,
            failure_message="Cannot publish SharePoint page -> '{}' on SharePoint site -> '{}'".format(
                page_id,
                site_id,
            ),
            parse_request_response=False,
        )

        return bool(response.ok)

    # end method definition

    def get_sharepoint_sections(
        self,
        site_id: str,
        page_id: str,
        section_type: str = "horizontalSections",
        section_id: str | int | None = None,
        show_error: bool = True,
    ) -> dict:
        """Retrieve all sections SharePoint site page.

        Args:
            site_id (str):
                The ID of the SharePoint site.
            page_id (str):
                The ID of the SharePoint page containing the sections.
            section_type (str, optional):
                "horizontalSections" (note the plural!)
                "verticalSection" (note the singular!)
            section_id (str | int | None):
                The ID of the section. Only relevant for horizontal sections.
                Simple values like 1,2,3...
                Should be None for vertical section.
            show_error (bool, optional):
                Whether or not an error should be displayed if the
                section is not found.

        Returns:
            dict:
                A dictionary including the list of SharePoint sections for a given page.
                The actual list is included inside the "value" key of the dictionary.

        Example:
        {
            '@odata.context': "https://graph.microsoft.com/beta/$metadata#sites('ideatedev.sharepoint.com%2C61c0f9cb-39d3-4c04-b60c-31576954a2ab%2Ca678aeab-68ac-46a1-bd95-28020c12de26')/pages('ac7675ee-8891-43b9-b1b2-2d2ced8eb17e')/microsoft.graph.sitePage/canvasLayout/horizontalSections",
            'value': [
                {
                    'layout': 'fullWidth',
                    'id': '1',
                    'emphasis': 'none'
                },
                {
                    'layout': 'twoColumns',
                    'id': '2',
                    'emphasis': 'none'
                }
            ]
        }

        """

        request_url = (
            self.config()["sitesUrl"]
            + "/"
            + site_id
            + "/pages/"
            + page_id
            + "/microsoft.graph.sitePage/canvasLayout/"
            + section_type
        )

        if section_id is not None:
            request_url += "/" + str(section_id)

        request_header = self.request_header()

        response = self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=REQUEST_TIMEOUT,
            warning_message="Cannot find section{} for SharePoint page -> '{}' of SharePoint site -> '{}'".format(
                "s" if not section_id else " -> {}".format(section_id),
                page_id,
                site_id,
            ),
            failure_message="Cannot get section{} for SharePoint page -> '{}' of SharePoint site -> '{}'".format(
                "s" if not section_id else " -> {}".format(section_id),
                page_id,
                site_id,
            ),
            show_error=show_error,
        )

        return response

    # end method definition

    def get_sharepoint_section(
        self,
        site_id: str,
        page_id: str,
        section_type: str = "horizontalSections",
        section_id: int | str = 1,
        show_error: bool = True,
    ) -> dict:
        """Retrieve a section of a SharePoint site page.

        Args:
            site_id (str):
                The ID of the SharePoint site.
            page_id (str):
                The ID of the SharePoint page containing the section.
            section_type (str, optional):
                "horizontalSections" (note the plural!)
                "verticalSection" (note the singular!)
            section_id (int | str):
                The ID of the section. Only relevant for horizontal sections.
                Simple values like 1,2,3...
            show_error (bool, optional):
                Whether or not an error should be displayed if the
                section is not found.

        Returns:
            dict:
                A SharePoint site page section.

        Example:
        {
            '@odata.context': "https://graph.microsoft.com/beta/$metadata#sites('ideatedev.sharepoint.com%2C61c0f9cb-39d3-4c04-b60c-31576954a2ab%2Ca678aeab-68ac-46a1-bd95-28020c12de26')/pages('ac7675ee-8891-43b9-b1b2-2d2ced8eb17e')/microsoft.graph.sitePage/canvasLayout/horizontalSections/$entity",
            'layout': 'fullWidth',
            'id': '1',
            'emphasis': 'none'
        }

        """

        response = self.get_sharepoint_sections(
            site_id=site_id,
            page_id=page_id,
            section_type=section_type,
            section_id=section_id,
            show_error=show_error,
        )

        return response

    # end method definition

    def add_sharepoint_section(
        self,
        site_id: str,
        page_id: str,
        section_type: str = "horizontalSections",
        section_id: int | str = 1,
        columns: str = "oneColumn",
        emphasis: str = "none",
        republish: bool = True,
    ) -> dict | None:
        """Create a specific section (horizontal or vertical) on a SharePoint page.

        Args:
            site_id (str):
                The ID of the SharePoint site.
            page_id (str):
                The ID of the SharePoint page containing the web part.
            section_type (str, optional):
                "horizontalSections" (note the plural!)
                "verticalSection" (note the singular!)
            section_id (int | str):
                The ID of the section. Only relevant for horizontal sections.
                Simple values like 1,2,3...
            columns (str, optional):
                "fullWidth"
                "oneColumn"
                "twoColumns"
                "threeColumns"
            emphasis (str, optional):
                The emphasis for the section. Possible values:
                "none" (default)
                "neutral"
                "soft"
                "strong"
            republish (bool, optional):
                If True, the page is republished to make the section active.

        Returns:
            dict:
                The horizontal or vertical section.

        Example:
        {
            '@odata.context': "https://graph.microsoft.com/beta/$metadata#sites('ideatedev.sharepoint.com%2C61c0f9cb-39d3-4c04-b60c-31576954a2ab%2Ca678aeab-68ac-46a1-bd95-28020c12de26')/pages('ac7675ee-8891-43b9-b1b2-2d2ced8eb17e')/microsoft.graph.sitePage/canvasLayout/horizontalSections/$entity",
            'layout': 'fullWidth',
            'id': '2',
            'emphasis': 'none'
        }

        """

        request_url = (
            self.config()["sitesUrl"]
            + "/"
            + site_id
            + "/pages/"
            + page_id
            + "/microsoft.graph.sitePage/canvasLayout/"
            + section_type
        )
        request_header = self.request_header()

        # Construct the payload to update the specific property
        payload = {
            "@odata.type": "#microsoft.graph.{}".format(
                section_type.rstrip("s"),
            ),
        }
        if section_type == "horizontalSections":
            payload["layout"] = columns
            payload["emphasis"] = emphasis
            payload["id"] = str(section_id)

        response = self.do_request(
            url=request_url,
            method="POST",
            headers=request_header,
            json_data=payload,
            timeout=REQUEST_TIMEOUT,
            failure_message="Failed to create SharePoint section of type -> '{}' ({}) on SharePoint page -> '{}' in SharePoint site -> '{}'".format(
                section_type,
                columns,
                page_id,
                site_id,
            ),
        )

        # Check if the page should be republished:
        if response and republish:
            self.publish_sharepoint_page(site_id=site_id, page_id=page_id)

        return response

    # end method definition

    def delete_sharepoint_section(
        self,
        site_id: str,
        page_id: str,
        section_type: str = "horizontalSections",
        section_id: int | str = 1,
    ) -> dict | None:
        """Delete a specific section (horizontal or vertical) on a SharePoint page.

        Args:
            site_id (str):
                The ID of the SharePoint site.
            page_id (str):
                The ID of the SharePoint page containing the web part.
            section_type (str, optional):
                "horizontalSections" (note the plural!)
                "verticalSection" (note the singular!)
            section_id (int | str):
                The ID of the section. Only relevant for horizontal sections.
                Simple values like 1,2,3...

        Returns:
            dict:
                Empty response.

        Example:
        {
            '_content': b'',
            '_content_consumed': True,
            '_next': None,
            'status_code': 204,
            'headers': {
                'Cache-Control': 'no-store, no-cache',
                'Strict-Transport-Security': 'max-age=31536000',
                'request-id': 'bd21c7fa-751c-43ca-b290-12c30f50d7e1',
                'client-request-id': 'bd21c7fa-751c-43ca-b290-12c30f50d7e1',
                'x-ms-ags-diagnostic': '{"ServerInfo":{"DataCenter":"Germany West Central","Slice":"E","Ring":"4","ScaleUnit":"004","RoleInstance":"FR2PEPF00000393"}}', 'Date': 'Fri, 14 Feb 2025 20:40:06 GMT'},
                'raw': <urllib3.response.HTTPResponse object at 0x10f210d90>,
                'url': 'https://graph.microsoft.com/beta/sites/ideatedev.sharepoint.com,61c0f9cb-39d3-4c04-b60c-31576954a2ab,a678aeab-68ac-46a1-bd95-28020c12de26/pages/ac7675ee-8891-43b9-b1b2-2d2ced8eb17e/microsoft.graph.sitePage/canvasLayout/horizontalSections/1',
                'encoding': None,
                'history': [],
                'reason': 'No Content',
                'cookies': <RequestsCookieJar[]>,
                'elapsed': datetime.timedelta(microseconds=514597),
                'request': <PreparedRequest [DELETE]>,
                'connection': <requests.adapters.HTTPAdapter object at 0x11841d700>
            }

        """

        request_url = (
            self.config()["sitesUrl"]
            + "/"
            + site_id
            + "/pages/"
            + page_id
            + "/microsoft.graph.sitePage/canvasLayout/"
            + section_type
        )

        if section_type == "horizontalSections":
            request_url += "/" + str(section_id)

        request_header = self.request_header()

        response = self.do_request(
            url=request_url,
            method="DELETE",
            headers=request_header,
            timeout=REQUEST_TIMEOUT,
            failure_message="Failed to delete SharePoint section of type -> '{}' on SharePoint page -> '{}' in Sharepoint site -> '{}', ".format(
                section_type,
                page_id,
                site_id,
            ),
        )

        return response

    # end method definition

    def get_sharepoint_webparts(
        self,
        site_id: str,
        page_id: str,
        section_type: str | None = None,
        section_id: str | int = 1,
        column_id: int | str = 1,
    ) -> dict | None:
        """Retrieve the configured webparts on a SharePoint site page.

        Can retrieve all webparts on the page or the ones in a defined
        page section (like horizontal section or vertical section).

        OpenText WebPart Type IDs:
            Content Browser: 'cecfdba4-2e82-4538-9436-dbd1c4c01a80'
            Related Workspaces: 'e24d7154-4554-4db6-a44f-d306b6b3a5d4'
            Team members of Workspace: '635a2800-8833-410d-b1f1-f209b28ea2ad'

        Args:
            site_id (str):
                The ID of the SharePoint site.
            page_id (str):
                The ID of the SharePoint page containing the web part.
            section_type (str, optional):
                "horizontalSections" (note the plural!)
                "verticalSection" (note the singular!)
                Use None if you want to retrieve all webparts on page.
            section_id (str | int | None):
                The ID of the section. Only relevant for horizontal sections.
                Simple values like 1,2,3...
                Not relevant for vertical section or if you want to retrieve
                all webparts on the page.
            column_id (int | str, optional):
                For horizontalSections the column ID has to be provided.
                Defaults to 1.


        Returns:
            dict | None:
                A dictionary including the SharePoint webparts of a given page for a given site.
                The actual list is included inside the "value" key of the dictionary.

        Example:
        {
            '@odata.context': "https://graph.microsoft.com/beta/$metadata#sites('ideatedev.sharepoint.com%2C61c0f9cb-39d3-4c04-b60c-31576954a2ab%2Ca678aeab-68ac-46a1-bd95-28020c12de26')/pages('561c65b4-3418-4698-a4c3-7ca7f04812bb')/microsoft.graph.sitePage/webParts",
            'value': [
                {
                    '@odata.type': '#microsoft.graph.standardWebPart',
                    'id': '405b669e-3c09-45fe-822f-ff60ac7fffce',
                    'webPartType': 'c4bd7b2f-7b6e-4599-8485-16504575f590',
                    'data': {
                        'audiences': [],
                        'dataVersion': '1.5',
                        'description': 'Prominently display up to 5 pieces of content with links, images, pictures, videos, or photos in a highly visual layout.',
                        'title': 'Hero',
                        'properties': {
                            'heroLayoutThreshold': 640,
                            'carouselLayoutMaxWidth': 639,
                            'layoutCategory': 1,
                            'layout': 5,
                            'content@odata.type': '#Collection(graph.Json)',
                            'content': [
                                {
                                    'id': '20cb6611-c7cc-4ba7-91e1-65a6cb576025',
                                    'type': 'UrlLink',
                                    'color': 4,
                                    'description': '',
                                    'title': '',
                                    'showDescription': False,
                                    'showTitle': True,
                                    'alternateText': '',
                                    'imageDisplayOption': 1,
                                    'isDefaultImage': False,
                                    'showCallToAction': True,
                                    'isDefaultImageLoaded': False,
                                    'isCustomImageLoaded': False,
                                    'showFeatureText': False,
                                    'previewImage': {...}
                                },
                                {
                                    'id': '83133733-960b-4139-a73f-17ce2ca5f71c',
                                    'type': 'Image',
                                    'color': 4,
                                    'description': '',
                                    'title': '',
                                    'showDescription': False,
                                    'showTitle': True,
                                    'alternateText': '',
                                    'imageDisplayOption': 0,
                                    'isDefaultImage': False,
                                    'showCallToAction': False,
                                    'isDefaultImageLoaded': False,
                                    'isCustomImageLoaded': False,
                                    'showFeatureText': False
                                },
                                ...
                            ]
                        },
                        'serverProcessedContent': {
                            'htmlStrings': [...],
                            'searchablePlainTexts': [...],
                            'links': [...],
                            'imageSources': [...],
                            'componentDependencies': [...],
                            'customMetadata': [...]
                        }
                    }
                },
                {
                    '@odata.type': '#microsoft.graph.standardWebPart',
                    'id': 'f7bfdec9-09c5-4fb6-bc97-3ba225d35ad4',
                    'webPartType': '8c88f208-6c77-4bdb-86a0-0c47b4316588',
                    'data': {...}
                },
                {
                    '@odata.type': '#microsoft.graph.standardWebPart',
                    'id': 'f2a8650b-5ea0-4ac2-9cde-56e0fd0279b0',
                    'webPartType': 'eb95c819-ab8f-4689-bd03-0c2d65d47b1f',
                    'data': {...}
                },
                {
                    '@odata.type': '#microsoft.graph.standardWebPart',
                    'id': '418ba70b-4cf7-410a-a5fd-ea38386915ac',
                    'webPartType': 'c70391ea-0b10-4ee9-b2b4-006d3fcad0cd',
                    'data': {...}
                },
                {
                    '@odata.type': '#microsoft.graph.standardWebPart',
                    'id': '416a4c58-61fc-4166-aa19-1099fad50545',
                    'webPartType': 'f92bf067-bc19-489e-a556-7fe95f508720',
                    'data': {...}
                }
            ]
        }

        """

        request_url = self.config()["sitesUrl"] + "/" + site_id + "/pages/" + page_id + "/microsoft.graph.sitePage"
        if section_type:
            request_url += "/canvasLayout/" + section_type
        if section_type == "horizontalSections":
            request_url += "/" + str(section_id)
            request_url += "/columns/" + str(column_id)
        request_url += "/webparts"

        request_header = self.request_header()

        response = self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=REQUEST_TIMEOUT,
            failure_message="Cannot get webparts for page -> '{}' of SharePoint site -> '{}'".format(
                page_id,
                site_id,
            ),
        )

        return response

    # end method definition

    def get_sharepoint_webpart(self, site_id: str, page_id: str, webpart_id: str) -> dict | None:
        """Retrieve a page of a SharePoint site accessible to the authenticated user.

        Args:
            site_id (str):
                The ID of the SharePoint site.
            page_id (str):
                The ID of the SharePoint page containing the web part.
            webpart_id (str):
                The ID of the SharePoint web part to retrieve.

        Returns:
            dict | None:
                The data of the SharePoint web part.

        Example:
        {
            '@odata.context': "https://graph.microsoft.com/beta/$metadata#sites('ideatedev.sharepoint.com%2C9b203cbe-27ca-45b2-944a-663cc99e5e8f%2Ca1462b54-26f9-4a24-9660-2bc7859ce9af')/pages('a546ce61-21e6-431d-b2cd-67d1f722be5f')/microsoft.graph.sitePage/webParts/$entity",
            '@odata.type': '#microsoft.graph.standardWebPart',
            'id': '405b669e-3c09-45fe-822f-ff60ac7fffce',
            'webPartType': 'c4bd7b2f-7b6e-4599-8485-16504575f590',
            'data': {
                'audiences': [...],
                'dataVersion': '1.5',
                'description': 'Prominently display up to 5 pieces of content with links, images, pictures, videos, or photos in a highly visual layout.',
                'title': 'Hero',
                'properties': {
                    'heroLayoutThreshold': 640,
                    'carouselLayoutMaxWidth': 639,
                    'layoutCategory': 1,
                    'layout': 5,
                    'content@odata.type': '#Collection(graph.Json)',
                    'content': [
                        {
                            'id': '20cb6611-c7cc-4ba7-91e1-65a6cb576025',
                            'type': 'UrlLink',
                            'color': 4,
                            'description': '',
                            'title': '',
                            'showDescription': False,
                            'showTitle': True,
                            'alternateText': '',
                            'imageDisplayOption': 1,
                            'isDefaultImage': False,
                            'showCallToAction': True,
                            'isDefaultImageLoaded': False,
                            'isCustomImageLoaded': False,
                            'showFeatureText': False,
                            'previewImage': {
                                '@odata.type': '#graph.Json',
                                'zoomRatio': 1,
                                'resolvedUrl': '',
                                'imageUrl': '',
                                'widthFactor': 0.5,
                                'minCanvasWidth': 1
                            }
                        },
                        {...}
                    ]
                },
                'serverProcessedContent': {...}
            }
        }

        """

        request_url = (
            self.config()["sitesUrl"]
            + "/"
            + site_id
            + "/pages/"
            + page_id
            + "/microsoft.graph.sitePage/webparts/"
            + webpart_id
        )

        request_header = self.request_header()

        response = self.do_request(
            url=request_url,
            method="GET",
            headers=request_header,
            timeout=REQUEST_TIMEOUT,
            failure_message="Cannot get SharePoint webpart -> '{}' on SharePoint page -> '{}' in SharePoint site -> '{}'".format(
                webpart_id,
                page_id,
                site_id,
            ),
        )

        return response

    # end method definition

    def add_sharepoint_webpart(
        self,
        site_id: str,
        page_id: str,
        webpart_type_id: str,
        create_data: dict,
        section_type: str = "horizontalSections",
        section_id: int | str = 1,
        column_id: int | str = 1,
        republish: bool = True,
    ) -> dict | None:
        """Create a specific web part on a SharePoint page.

        Args:
            site_id (str):
                The ID of the SharePoint site.
            page_id (str):
                The ID of the SharePoint page containing the web part.
            webpart_type_id (str):
                The ID of the web part to create.
                Content Browser: 'cecfdba4-2e82-4538-9436-dbd1c4c01a80'
                Related Workspaces: 'e24d7154-4554-4db6-a44f-d306b6b3a5d4'
                Team members of Workspace: '635a2800-8833-410d-b1f1-f209b28ea2ad'
            create_data (dict):
                A dictionary with the webpart data items that will be used
                to update the "data" structure of the webpart.
            section_type (str, optional):
                "horizontalSections" (note the plural!)
                "verticalSection" (note the singular!)
            section_id (str | int):
                The ID of the section.Only relevant for horizontal sections.
                Simple values like 1,2,3...
                Defaults to 1.
            column_id (int | str, optional):
                For horizontalSections the column ID has to be provided.
                Defaults to 1.
            republish (bool, optional):
                If True, the page is republished to make the section active.

        Returns:
            dict:
                The updated web part.

        Example:
        {
            '@odata.context': "https://graph.microsoft.com/beta/$metadata#sites('ideatedev.sharepoint.com%2C61c0f9cb-39d3-4c04-b60c-31576954a2ab%2Ca678aeab-68ac-46a1-bd95-28020c12de26')/pages('ac7675ee-8891-43b9-b1b2-2d2ced8eb17e')/microsoft.graph.sitePage/canvasLayout/horizontalSections('1')/columns('1')/webparts/$entity",
            '@odata.type': '#microsoft.graph.standardWebPart',
            'id': '3df7fe9a-a1e0-4212-968c-73bd70ca3e31',
            'webPartType': 'eb95c819-ab8f-4689-bd03-0c2d65d47b1f',
            'data': {
                'audiences': [...],
                'dataVersion': '1.0',
                'title': 'Site activity',
                'properties': {'maxItems': 9},
                'serverProcessedContent': {
                    'htmlStrings': [],
                    'searchablePlainTexts': [],
                    'links': [],
                    'imageSources': []
                }
            }
        }

        """

        request_url = (
            self.config()["sitesUrl"]
            + "/"
            + site_id
            + "/pages/"
            + page_id
            + "/microsoft.graph.sitePage/canvasLayout/"
            + section_type
        )
        if section_type == "horizontalSections":
            request_url += "/" + str(section_id)
            request_url += "/columns/" + str(column_id)
        request_url += "/webparts"

        request_header = self.request_header()

        # Construct the payload to update the specific property
        payload = {
            "@odata.type": "#microsoft.graph.standardWebPart",  # likle "#microsoft.graph.standardWebPart" - this is mandatory!
            "webPartType": webpart_type_id,  # this is mandatory!
            "data": create_data,
        }

        response = self.do_request(
            url=request_url,
            method="POST",
            headers=request_header,
            json_data=payload,
            timeout=REQUEST_TIMEOUT,
            failure_message="Failed to create SharePoint webpart of type -> '{}' on SharePoint page -> '{}'{} in SharePoint site -> '{}', ".format(
                webpart_type_id,
                page_id,
                " (horizontal section -> {}, column -> {})".format(section_id, column_id)
                if section_type == "horizontalSections"
                else " (vertical section)",
                site_id,
            ),
        )

        # Check if the page should be republished:
        if response and republish:
            self.publish_sharepoint_page(site_id=site_id, page_id=page_id)

        return response

    # end method definition

    def update_sharepoint_webpart(
        self,
        site_id: str,
        page_id: str,
        webpart_id: str,
        update_data: dict,
        republish: bool = True,
    ) -> dict | None:
        """Update a data of a specific web part on a SharePoint page.

        Any data elements not provided for the update will remain unchanged!

        Args:
            site_id (str):
                The ID of the SharePoint site.
            page_id (str):
                The ID of the SharePoint page containing the web part.
            webpart_id (str):
                The ID of the web part to update.
            update_data (dict):
                A dictionary with the updated data items that will be used
                to update the "data" structure of the webpart.
            republish (bool, optional):
                If True, the page is republished to make the section active.

        Returns:
            dict | None:
                The updated web part. None in case of an error.

        """

        def deep_merge(source: dict, destination: dict) -> dict:
            """Recursively merges source dictionary into destination dictionary.

            If a key exists in both, the value from destination is kept unless
            both values are dictionaries, in which case they are merged recursively.

            Args:
                source (dict):
                    The dictionary with the current data values. Will be
                    used if not updated data is in update_data for the particular key.
                destination (dict):
                    The dictionary to merge into, which takes precedence.

            Returns:
                dict: The merged dictionary.

            """
            for key, value in source.items():
                if isinstance(value, dict) and key in destination and isinstance(destination[key], dict):
                    # Recursively merge dictionaries if both values are dictionaries
                    destination[key] = deep_merge(value, destination[key])
                else:
                    # If key does not exist in destination, use value from source
                    destination.setdefault(key, value)
            return destination

        # end deep_merge()

        webpart = self.get_sharepoint_webpart(site_id=site_id, page_id=page_id, webpart_id=webpart_id)
        if not webpart:
            self.logger.error(
                "Cannot find web part for site ID -> '%s', page -> '%s', webpart ID -> '%s'!",
                site_id,
                page_id,
                webpart_id,
            )
            return None
        webpart_type_id = webpart.get("webPartType")
        webpart_type_name = webpart.get("@odata.type")
        data = webpart.get("data")

        # Fill update_data with missing keys from data
        update_data = deep_merge(data, update_data)  # Merges, giving precedence to update_data

        # Construct the payload to update the specific property
        payload = {
            "@odata.type": webpart_type_name,  # likle "#microsoft.graph.standardWebPart" - this is mandatory!
            "webPartType": webpart_type_id,  # this is mandatory!
            "data": update_data,
        }

        request_url = (
            self.config()["sitesUrl"]
            + "/"
            + site_id
            + "/pages/"
            + page_id
            + "/microsoft.graph.sitePage/webparts/"
            + webpart_id
        )
        request_header = self.request_header()

        response = self.do_request(
            url=request_url,
            method="PATCH",
            json_data=payload,
            headers=request_header,
            timeout=REQUEST_TIMEOUT,
            failure_message="Cannot update SharePoint webpart -> '{}' on SharePoint page -> '{}' for Sharepoint site -> '{}', ".format(
                webpart_id,
                page_id,
                site_id,
            ),
        )
        # Check if the page should be republished:
        if response and republish:
            self.publish_sharepoint_page(site_id=site_id, page_id=page_id)

        return response

    # end method definition

    def follow_sharepoint_site(
        self,
        site_id: str,
        username: str | None = None,
        user_id: str | None = None,
    ) -> dict | None:
        """Let a user follow a particular SharePoint site.

        Args:
            site_id (str):
                The ID of the SharePoint site.
            username (str):
                The login name of the user. Only relevant if the user ID
                is not provided.
            user_id (str):
                The user ID. If it is not provied it will be derived from
                the username.

        Returns:
            dict:
                The Graph API response or None in case an error occured..

        Example:
        {
            '@odata.context': 'https://graph.microsoft.com/v1.0/$metadata#sites',
            'value': [
                {
                    'id': 'ideateqa.sharepoint.com,c605327f-8531-47da-8c85-9bb63845dda6,34b48533-af41-4743-8b41-185a21f0b80f',
                    'webUrl': 'https://ideateqa.sharepoint.com/sites/Procurement',
                    'displayName': 'Procurement',
                    'sharepointIds': {
                        'siteId': 'c605327f-8531-47da-8c85-9bb63845dda6',
                        'siteUrl': 'https://ideateqa.sharepoint.com/sites/Procurement',
                        'webId': '34b48533-af41-4743-8b41-185a21f0b80f'
                    },
                    'siteCollection': {
                        'hostname': 'ideateqa.sharepoint.com'
                    }
                }
            ]
        }

        """

        if not user_id and not username:
            self.logger.error("No user given to follow SharePoint site. Provide the user ID or its email address!")
            return None

        user = self.get_user(user_email=username, user_id=user_id)
        if not user_id:
            user_id = self.get_result_value(user, "id")
        if not username:
            username = self.get_result_value(user, "userPrincipalName")

        request_url = self.config()["usersUrl"] + "/" + str(user_id) + "/followedSites/add"
        request_header = self.request_header()

        # Construct the payload to update the specific property
        payload = {
            "value": [{"id": site_id}],
        }

        response = self.do_request(
            url=request_url,
            method="POST",
            headers=request_header,
            json_data=payload,
            timeout=REQUEST_TIMEOUT,
            warning_message="Failed to follow SharePoint site -> '{}' as user -> '{}'".format(
                site_id,
                username if username else user_id,
            ),
            show_error=False,
            show_warning=True,
        )

        return response

__init__(tenant_id, client_id, client_secret, domain, sku_id, teams_app_name, teams_app_external_id, sharepoint_app_root_site='', sharepoint_app_client_id='', sharepoint_app_client_secret='', logger=default_logger)

Initialize the M365 object.

Parameters:

Name Type Description Default
tenant_id str

The M365 Tenant ID.

required
client_id str

The M365 Client ID.

required
client_secret str

The M365 Client Secret.

required
domain str

The M365 domain.

required
sku_id str

License SKU for M365 users.

required
teams_app_name str

The name of the Extended ECM app for MS Teams.

required
teams_app_external_id str

The external ID of the Extended ECM app for MS Teams

required
sharepoint_app_root_site str

The URL to the SharePoint root site.

''
sharepoint_app_client_id str

The SharePoint App client ID.

''
sharepoint_app_client_secret str

The SharePoint App client secret.

''
logger Logger

The logging object to use for all log messages. Defaults to default_logger.

default_logger
Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def __init__(
    self,
    tenant_id: str,
    client_id: str,
    client_secret: str,
    domain: str,
    sku_id: str,
    teams_app_name: str,
    teams_app_external_id: str,
    sharepoint_app_root_site: str = "",
    sharepoint_app_client_id: str = "",
    sharepoint_app_client_secret: str = "",
    logger: logging.Logger = default_logger,
) -> None:
    """Initialize the M365 object.

    Args:
        tenant_id (str):
            The M365 Tenant ID.
        client_id (str):
            The M365 Client ID.
        client_secret (str):
            The M365 Client Secret.
        domain (str):
            The M365 domain.
        sku_id (str):
            License SKU for M365 users.
        teams_app_name (str):
            The name of the Extended ECM app for MS Teams.
        teams_app_external_id (str):
            The external ID of the Extended ECM app for MS Teams
        sharepoint_app_root_site (str):
            The URL to the SharePoint root site.
        sharepoint_app_client_id (str):
            The SharePoint App client ID.
        sharepoint_app_client_secret (str):
            The SharePoint App client secret.
        logger (logging.Logger, optional):
            The logging object to use for all log messages. Defaults to default_logger.

    """

    if logger != default_logger:
        self.logger = logger.getChild("m365")
        for logfilter in logger.filters:
            self.logger.addFilter(logfilter)

    m365_config = {}

    # Set the authentication endpoints and credentials
    m365_config["tenantId"] = tenant_id
    m365_config["clientId"] = client_id
    m365_config["clientSecret"] = client_secret
    m365_config["domain"] = domain
    m365_config["skuId"] = sku_id
    m365_config["teamsAppName"] = teams_app_name
    m365_config["teamsAppExternalId"] = teams_app_external_id  # this is the external App ID
    m365_config["teamsAppInternalId"] = None  # will be set later...
    m365_config["sharepointAppRootSite"] = sharepoint_app_root_site
    m365_config["sharepointAppClientId"] = sharepoint_app_client_id
    m365_config["sharepointAppClientSecret"] = sharepoint_app_client_secret
    m365_config["authenticationUrl"] = "https://login.microsoftonline.com/{}/oauth2/v2.0/token".format(tenant_id)
    m365_config["graphUrl"] = "https://graph.microsoft.com/v1.0/"
    m365_config["betaUrl"] = "https://graph.microsoft.com/beta/"
    m365_config["directoryObjects"] = m365_config["graphUrl"] + "directoryObjects"

    # Set the data for the token request
    m365_config["tokenData"] = {
        "client_id": client_id,
        "client_secret": client_secret,
        "grant_type": "client_credentials",
        "scope": "https://graph.microsoft.com/.default",
    }

    m365_config["meUrl"] = m365_config["graphUrl"] + "me"
    m365_config["groupsUrl"] = m365_config["graphUrl"] + "groups"
    m365_config["usersUrl"] = m365_config["graphUrl"] + "users"
    m365_config["teamsUrl"] = m365_config["graphUrl"] + "teams"
    m365_config["teamsTemplatesUrl"] = m365_config["graphUrl"] + "teamsTemplates"
    m365_config["teamsAppsUrl"] = m365_config["graphUrl"] + "appCatalogs/teamsApps"
    m365_config["directoryUrl"] = m365_config["graphUrl"] + "directory"
    m365_config["securityUrl"] = m365_config["betaUrl"] + "security"
    m365_config["applicationsUrl"] = m365_config["graphUrl"] + "applications"

    m365_config["sitesUrl"] = m365_config["betaUrl"] + "sites"

    self._config = m365_config
    self._http_object = HTTP(logger=self.logger)

add_app_registration(app_registration_name, description='', api_permissions=None, supported_account_type='AzureADMyOrg')

Add an Azure App Registration.

Parameters:

Name Type Description Default
app_registration_name str

The name of the App Registration.

required
description str

The description of the app.

''
api_permissions list | None

The API permissions.

None
supported_account_type str

The type of account that is supposed to use the App Registration.

'AzureADMyOrg'

Returns:

Name Type Description
dict dict

App Registration data or None of the request fails.

dict

Example data:

dict

{ 'id': 'd70bee91-3689-4239-a626-30756968e99c', 'deletedDateTime': None, 'appId': 'd288ba5f-9313-4b38-b4a4-d7edcce089b0', 'applicationTemplateId': None, 'disabledByMicrosoftStatus': None, 'createdDateTime': '2023-09-06T21:06:05Z', 'displayName': 'Test 1', 'description': None, 'groupMembershipClaims': None, 'identifierUris': [], 'isDeviceOnlyAuthSupported': None, 'isFallbackPublicClient': None, 'notes': None, 'publisherDomain': 'M365x41497014.onmicrosoft.com', 'signInAudience': 'AzureADMyOrg', ... 'requiredResourceAccess': [ { 'resourceAppId': '00000003-0000-0ff1-ce00-000000000000', 'resourceAccess': [ { 'id': '741f803b-c850-494e-b5df-cde7c675a1ca', 'type': 'Role' }, { 'id': 'c8e3537c-ec53-43b9-bed3-b2bd3617ae97', 'type': 'Role' }, ] }, ]

dict

}

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def add_app_registration(
    self,
    app_registration_name: str,
    description: str = "",
    api_permissions: list | None = None,
    supported_account_type: str = "AzureADMyOrg",
) -> dict:
    """Add an Azure App Registration.

    Args:
        app_registration_name (str):
            The name of the App Registration.
        description (str, optional):
            The description of the app.
        api_permissions (list | None, optional):
            The API permissions.
        supported_account_type (str, optional):
            The type of account that is supposed to use
            the App Registration.

    Returns:
        dict:
            App Registration data or None of the request fails.

        Example data:
        {
            'id': 'd70bee91-3689-4239-a626-30756968e99c',
            'deletedDateTime': None,
            'appId': 'd288ba5f-9313-4b38-b4a4-d7edcce089b0',
            'applicationTemplateId': None,
            'disabledByMicrosoftStatus': None,
            'createdDateTime': '2023-09-06T21:06:05Z',
            'displayName': 'Test 1',
            'description': None,
            'groupMembershipClaims': None,
            'identifierUris': [],
            'isDeviceOnlyAuthSupported': None,
            'isFallbackPublicClient': None,
            'notes': None,
            'publisherDomain': 'M365x41497014.onmicrosoft.com',
            'signInAudience': 'AzureADMyOrg',
            ...
            'requiredResourceAccess': [
                {
                    'resourceAppId': '00000003-0000-0ff1-ce00-000000000000',
                    'resourceAccess': [
                        {
                            'id': '741f803b-c850-494e-b5df-cde7c675a1ca',
                            'type': 'Role'
                        },
                        {
                            'id': 'c8e3537c-ec53-43b9-bed3-b2bd3617ae97',
                            'type': 'Role'
                        },
                    ]
                },
            ]
        }

    """

    # Define the request body to create the App Registration
    app_registration_data = {
        "displayName": app_registration_name,
        "signInAudience": supported_account_type,
    }
    if api_permissions:
        app_registration_data["requiredResourceAccess"] = api_permissions
    if description:
        app_registration_data["description"] = description

    request_url = self.config()["applicationsUrl"]
    request_header = self.request_header()

    return self.do_request(
        url=request_url,
        method="POST",
        headers=request_header,
        json_data=app_registration_data,
        timeout=REQUEST_TIMEOUT,
        failure_message="Cannot add App Registration -> '{}'".format(
            app_registration_name,
        ),
    )

add_group(name, security_enabled=False, mail_enabled=True)

Add a M365 Group.

Parameters:

Name Type Description Default
name str

The name of the group.

required
security_enabled bool

Whether or not this group is used for permission management.

False
mail_enabled bool

Whether or not this group is email enabled.

True

Returns:

Type Description
dict | None

dict | None: Group information or None if the group couldn't be created (e.g. because it exisits already).

Example

{ '@odata.context': 'https://graph.microsoft.com/v1.0/$metadata#groups/$entity', 'id': '28906460-a69c-439e-84ca-c70becf37655', 'deletedDateTime': None, 'classification': None, 'createdDateTime': '2023-04-01T11:40:13Z', 'creationOptions': [], 'description': None, 'displayName': 'Test', 'expirationDateTime': None, 'groupTypes': ['Unified'], 'isAssignableToRole': None, 'mail': 'Diefenbruch@M365x61936377.onmicrosoft.com', 'mailEnabled': True, 'mailNickname': 'Test', 'membershipRule': None, 'membershipRuleProcessingState': None, 'onPremisesDomainName': None, 'onPremisesLastSyncDateTime': None, 'onPremisesNetBiosName': None, 'onPremisesSamAccountName': None, 'onPremisesSecurityIdentifier': None, 'onPremisesSyncEnabled': None, 'onPremisesProvisioningErrors': [], 'preferredDataLocation': None, 'preferredLanguage': None, 'proxyAddresses': ['SMTP:Test@M365x61936377.onmicrosoft.com'], 'renewedDateTime': '2023-04-01T11:40:13Z', 'resourceBehaviorOptions': [], 'resourceProvisioningOptions': [], 'securityEnabled': True, 'securityIdentifier': 'S-1-12-1-680551520-1134470812-197642884-1433859052', 'theme': None, 'visibility': 'Public' }

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def add_group(
    self,
    name: str,
    security_enabled: bool = False,
    mail_enabled: bool = True,
) -> dict | None:
    """Add a M365 Group.

    Args:
        name (str):
            The name of the group.
        security_enabled (bool, optional):
            Whether or not this group is used for permission management.
        mail_enabled (bool, optional):
            Whether or not this group is email enabled.

    Returns:
        dict | None:
            Group information or None if the group couldn't be created (e.g. because it exisits already).

    Example:
        {
            '@odata.context': 'https://graph.microsoft.com/v1.0/$metadata#groups/$entity',
            'id': '28906460-a69c-439e-84ca-c70becf37655',
            'deletedDateTime': None,
            'classification': None,
            'createdDateTime': '2023-04-01T11:40:13Z',
            'creationOptions': [],
            'description': None,
            'displayName': 'Test',
            'expirationDateTime': None,
            'groupTypes': ['Unified'],
            'isAssignableToRole': None,
            'mail': 'Diefenbruch@M365x61936377.onmicrosoft.com',
            'mailEnabled': True,
            'mailNickname': 'Test',
            'membershipRule': None,
            'membershipRuleProcessingState': None,
            'onPremisesDomainName': None,
            'onPremisesLastSyncDateTime': None,
            'onPremisesNetBiosName': None,
            'onPremisesSamAccountName': None,
            'onPremisesSecurityIdentifier': None,
            'onPremisesSyncEnabled': None,
            'onPremisesProvisioningErrors': [],
            'preferredDataLocation': None,
            'preferredLanguage': None,
            'proxyAddresses': ['SMTP:Test@M365x61936377.onmicrosoft.com'],
            'renewedDateTime': '2023-04-01T11:40:13Z',
            'resourceBehaviorOptions': [],
            'resourceProvisioningOptions': [],
            'securityEnabled': True,
            'securityIdentifier': 'S-1-12-1-680551520-1134470812-197642884-1433859052',
            'theme': None,
            'visibility': 'Public'
        }

    """

    group_post_body = {
        "displayName": name,
        "mailEnabled": mail_enabled,
        "mailNickname": name.replace(" ", ""),
        "securityEnabled": security_enabled,
        "groupTypes": ["Unified"],
    }

    request_url = self.config()["groupsUrl"]
    request_header = self.request_header()

    self.logger.debug("Adding M365 group -> '%s'; calling -> %s", name, request_url)
    self.logger.debug("M365 group attributes -> %s", str(group_post_body))

    return self.do_request(
        url=request_url,
        method="POST",
        headers=request_header,
        data=json.dumps(group_post_body),
        timeout=REQUEST_TIMEOUT,
        failure_message="Failed to add M365 group -> '{}'".format(name),
    )

add_group_member(group_id, member_id)

Add a member (user or group) to a (parent) group.

Parameters:

Name Type Description Default
group_id str

The M365 GUID of the group.

required
member_id str

The M365 GUID of the new member.

required

Returns:

Type Description
dict | None

dict | None: Response of the MS Graph API call or None if the call fails.

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def add_group_member(self, group_id: str, member_id: str) -> dict | None:
    """Add a member (user or group) to a (parent) group.

    Args:
        group_id (str):
            The M365 GUID of the group.
        member_id (str):
            The M365 GUID of the new member.

    Returns:
        dict | None:
            Response of the MS Graph API call or None if the call fails.

    """

    request_url = self.config()["groupsUrl"] + "/" + group_id + "/members/$ref"
    request_header = self.request_header()

    group_member_post_body = {
        "@odata.id": self.config()["directoryObjects"] + "/" + member_id,
    }

    self.logger.debug(
        "Adding member -> %s to group -> %s; calling -> %s",
        member_id,
        group_id,
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="POST",
        headers=request_header,
        data=json.dumps(group_member_post_body),
        timeout=REQUEST_TIMEOUT,
        failure_message="Failed to add member -> {} to M365 group -> {}".format(
            member_id,
            group_id,
        ),
    )

add_group_owner(group_id, owner_id)

Add an owner (user) to a group.

Parameters:

Name Type Description Default
group_id str

The M365 GUID of the group.

required
owner_id str

The M365 GUID of the new member.

required

Returns:

Type Description
dict | None

dict | None: The response of the MS Graph API call or None if the call fails.

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def add_group_owner(self, group_id: str, owner_id: str) -> dict | None:
    """Add an owner (user) to a group.

    Args:
        group_id (str):
            The M365 GUID of the group.
        owner_id (str):
            The M365 GUID of the new member.

    Returns:
        dict | None:
            The response of the MS Graph API call or None if the call fails.

    """

    request_url = self.config()["groupsUrl"] + "/" + group_id + "/owners/$ref"
    request_header = self.request_header()

    group_member_post_body = {
        "@odata.id": self.config()["directoryObjects"] + "/" + owner_id,
    }

    self.logger.debug(
        "Adding owner -> %s to M365 group -> %s; calling -> %s",
        owner_id,
        group_id,
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="POST",
        headers=request_header,
        data=json.dumps(group_member_post_body),
        timeout=REQUEST_TIMEOUT,
        failure_message="Failed to add owner -> {} to M365 group -> {}".format(
            owner_id,
            group_id,
        ),
    )

add_sensitivity_label(name, display_name, description='', color='red', enabled=True, admin_description='', user_description='', enable_encryption=False, enable_marking=False)

Create a new sensitivity label in M365.

TODO: THIS IS CURRENTLY NOT WORKING!

Parameters:

Name Type Description Default
name str

The name of the label.

required
display_name str

The display name of the label.

required
description str

Description of the label. Defaults to "".

''
color str

Color of the label. Defaults to "red".

'red'
enabled bool

Whether this label is enabled. Defaults to True.

True
admin_description str

Description for administrators. Defaults to "".

''
user_description str

Description for users. Defaults to "".

''
enable_encryption bool

Enable encryption. Defaults to False.

False
enable_marking bool

Enable marking. Defaults to False.

False

Returns:

Type Description
dict | None

Request reponse or None if the request fails.

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def add_sensitivity_label(
    self,
    name: str,
    display_name: str,
    description: str = "",
    color: str = "red",
    enabled: bool = True,
    admin_description: str = "",
    user_description: str = "",
    enable_encryption: bool = False,
    enable_marking: bool = False,
) -> dict | None:
    """Create a new sensitivity label in M365.

    TODO: THIS IS CURRENTLY NOT WORKING!

    Args:
        name (str):
            The name of the label.
        display_name (str):
            The display name of the label.
        description (str, optional):
            Description of the label. Defaults to "".
        color (str, optional):
            Color of the label. Defaults to "red".
        enabled (bool, optional):
            Whether this label is enabled. Defaults to True.
        admin_description (str, optional):
            Description for administrators. Defaults to "".
        user_description (str, optional):
            Description for users. Defaults to "".
        enable_encryption (bool, optional):
            Enable encryption. Defaults to False.
        enable_marking (bool, optional):
            Enable marking. Defaults to False.

    Returns:
        Request reponse or None if the request fails.

    """

    # Prepare the request body
    payload = {
        "displayName": display_name,
        "description": description,
        "isEnabled": enabled,
        "labelColor": color,
        "adminDescription": admin_description,
        "userDescription": user_description,
        "encryptContent": enable_encryption,
        "contentMarking": enable_marking,
    }

    request_url = self.config()["securityUrl"] + "/sensitivityLabels"
    request_header = self.request_header()

    self.logger.debug(
        "Create M365 sensitivity label -> '%s'; calling -> %s",
        name,
        request_url,
    )

    # Send the POST request to create the label
    response = requests.post(
        request_url,
        headers=request_header,
        data=json.dumps(payload),
        timeout=REQUEST_TIMEOUT,
    )

    # Check the response status code
    if response.status_code == 201:
        self.logger.debug("Label -> '%s' has been created successfully!", name)
        return response
    else:
        self.logger.error(
            "Failed to create the M365 label -> '%s'! Response status code -> %s",
            name,
            response.status_code,
        )
        return None

add_sharepoint_page(site_id, page_name, publish=True)

Add a new SharePoint site page using Microsoft Graph API.

Parameters:

Name Type Description Default
site_id str

The ID of the SharePoint site the page should be created on.

required
page_name str

The name/title of the new page.

required
publish bool

If True, the page is immediately published.

True

Returns:

Name Type Description
dict dict

Details of the created SharePoint page or an error response.

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def add_sharepoint_page(self, site_id: str, page_name: str, publish: bool = True) -> dict:
    """Add a new SharePoint site page using Microsoft Graph API.

    Args:
        site_id (str):
            The ID of the SharePoint site the page should be created on.
        page_name (str):
            The name/title of the new page.
        publish (bool, optional):
            If True, the page is immediately published.

    Returns:
        dict:
            Details of the created SharePoint page or an error response.

    """

    request_url = self.config()["sitesUrl"] + "/" + site_id + "/pages"
    request_header = self.request_header()

    # Page payload for a basic site page
    payload = {
        "@odata.type": "#microsoft.graph.sitePage",
        "name": page_name + ".aspx",
        "title": page_name,
        "publishingState": {
            "level": "published",
        },
    }

    response = self.do_request(
        url=request_url,
        method="POST",
        headers=request_header,
        json_data=payload,
        timeout=REQUEST_TIMEOUT,
        failure_message="Failed to create SharePoint page -> '{}' in SharePoint site -> '{}'".format(
            page_name,
            site_id,
        ),
    )

    # Check if the page should be directly published:
    if response and publish:
        page_id = self.get_result_value(response=response, key="id")
        self.publish_sharepoint_page(site_id=site_id, page_id=page_id)

    return response

add_sharepoint_section(site_id, page_id, section_type='horizontalSections', section_id=1, columns='oneColumn', emphasis='none', republish=True)

Create a specific section (horizontal or vertical) on a SharePoint page.

Parameters:

Name Type Description Default
site_id str

The ID of the SharePoint site.

required
page_id str

The ID of the SharePoint page containing the web part.

required
section_type str

"horizontalSections" (note the plural!) "verticalSection" (note the singular!)

'horizontalSections'
section_id int | str

The ID of the section. Only relevant for horizontal sections. Simple values like 1,2,3...

1
columns str

"fullWidth" "oneColumn" "twoColumns" "threeColumns"

'oneColumn'
emphasis str

The emphasis for the section. Possible values: "none" (default) "neutral" "soft" "strong"

'none'
republish bool

If True, the page is republished to make the section active.

True

Returns:

Name Type Description
dict dict | None

The horizontal or vertical section.

Example: { '@odata.context': "https://graph.microsoft.com/beta/$metadata#sites('ideatedev.sharepoint.com%2C61c0f9cb-39d3-4c04-b60c-31576954a2ab%2Ca678aeab-68ac-46a1-bd95-28020c12de26')/pages('ac7675ee-8891-43b9-b1b2-2d2ced8eb17e')/microsoft.graph.sitePage/canvasLayout/horizontalSections/$entity", 'layout': 'fullWidth', 'id': '2', 'emphasis': 'none' }

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def add_sharepoint_section(
    self,
    site_id: str,
    page_id: str,
    section_type: str = "horizontalSections",
    section_id: int | str = 1,
    columns: str = "oneColumn",
    emphasis: str = "none",
    republish: bool = True,
) -> dict | None:
    """Create a specific section (horizontal or vertical) on a SharePoint page.

    Args:
        site_id (str):
            The ID of the SharePoint site.
        page_id (str):
            The ID of the SharePoint page containing the web part.
        section_type (str, optional):
            "horizontalSections" (note the plural!)
            "verticalSection" (note the singular!)
        section_id (int | str):
            The ID of the section. Only relevant for horizontal sections.
            Simple values like 1,2,3...
        columns (str, optional):
            "fullWidth"
            "oneColumn"
            "twoColumns"
            "threeColumns"
        emphasis (str, optional):
            The emphasis for the section. Possible values:
            "none" (default)
            "neutral"
            "soft"
            "strong"
        republish (bool, optional):
            If True, the page is republished to make the section active.

    Returns:
        dict:
            The horizontal or vertical section.

    Example:
    {
        '@odata.context': "https://graph.microsoft.com/beta/$metadata#sites('ideatedev.sharepoint.com%2C61c0f9cb-39d3-4c04-b60c-31576954a2ab%2Ca678aeab-68ac-46a1-bd95-28020c12de26')/pages('ac7675ee-8891-43b9-b1b2-2d2ced8eb17e')/microsoft.graph.sitePage/canvasLayout/horizontalSections/$entity",
        'layout': 'fullWidth',
        'id': '2',
        'emphasis': 'none'
    }

    """

    request_url = (
        self.config()["sitesUrl"]
        + "/"
        + site_id
        + "/pages/"
        + page_id
        + "/microsoft.graph.sitePage/canvasLayout/"
        + section_type
    )
    request_header = self.request_header()

    # Construct the payload to update the specific property
    payload = {
        "@odata.type": "#microsoft.graph.{}".format(
            section_type.rstrip("s"),
        ),
    }
    if section_type == "horizontalSections":
        payload["layout"] = columns
        payload["emphasis"] = emphasis
        payload["id"] = str(section_id)

    response = self.do_request(
        url=request_url,
        method="POST",
        headers=request_header,
        json_data=payload,
        timeout=REQUEST_TIMEOUT,
        failure_message="Failed to create SharePoint section of type -> '{}' ({}) on SharePoint page -> '{}' in SharePoint site -> '{}'".format(
            section_type,
            columns,
            page_id,
            site_id,
        ),
    )

    # Check if the page should be republished:
    if response and republish:
        self.publish_sharepoint_page(site_id=site_id, page_id=page_id)

    return response

add_sharepoint_webpart(site_id, page_id, webpart_type_id, create_data, section_type='horizontalSections', section_id=1, column_id=1, republish=True)

Create a specific web part on a SharePoint page.

Parameters:

Name Type Description Default
site_id str

The ID of the SharePoint site.

required
page_id str

The ID of the SharePoint page containing the web part.

required
webpart_type_id str

The ID of the web part to create. Content Browser: 'cecfdba4-2e82-4538-9436-dbd1c4c01a80' Related Workspaces: 'e24d7154-4554-4db6-a44f-d306b6b3a5d4' Team members of Workspace: '635a2800-8833-410d-b1f1-f209b28ea2ad'

required
create_data dict

A dictionary with the webpart data items that will be used to update the "data" structure of the webpart.

required
section_type str

"horizontalSections" (note the plural!) "verticalSection" (note the singular!)

'horizontalSections'
section_id str | int

The ID of the section.Only relevant for horizontal sections. Simple values like 1,2,3... Defaults to 1.

1
column_id int | str

For horizontalSections the column ID has to be provided. Defaults to 1.

1
republish bool

If True, the page is republished to make the section active.

True

Returns:

Name Type Description
dict dict | None

The updated web part.

Example: { '@odata.context': "https://graph.microsoft.com/beta/$metadata#sites('ideatedev.sharepoint.com%2C61c0f9cb-39d3-4c04-b60c-31576954a2ab%2Ca678aeab-68ac-46a1-bd95-28020c12de26')/pages('ac7675ee-8891-43b9-b1b2-2d2ced8eb17e')/microsoft.graph.sitePage/canvasLayout/horizontalSections('1')/columns('1')/webparts/$entity", '@odata.type': '#microsoft.graph.standardWebPart', 'id': '3df7fe9a-a1e0-4212-968c-73bd70ca3e31', 'webPartType': 'eb95c819-ab8f-4689-bd03-0c2d65d47b1f', 'data': { 'audiences': [...], 'dataVersion': '1.0', 'title': 'Site activity', 'properties': {'maxItems': 9}, 'serverProcessedContent': { 'htmlStrings': [], 'searchablePlainTexts': [], 'links': [], 'imageSources': [] } } }

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def add_sharepoint_webpart(
    self,
    site_id: str,
    page_id: str,
    webpart_type_id: str,
    create_data: dict,
    section_type: str = "horizontalSections",
    section_id: int | str = 1,
    column_id: int | str = 1,
    republish: bool = True,
) -> dict | None:
    """Create a specific web part on a SharePoint page.

    Args:
        site_id (str):
            The ID of the SharePoint site.
        page_id (str):
            The ID of the SharePoint page containing the web part.
        webpart_type_id (str):
            The ID of the web part to create.
            Content Browser: 'cecfdba4-2e82-4538-9436-dbd1c4c01a80'
            Related Workspaces: 'e24d7154-4554-4db6-a44f-d306b6b3a5d4'
            Team members of Workspace: '635a2800-8833-410d-b1f1-f209b28ea2ad'
        create_data (dict):
            A dictionary with the webpart data items that will be used
            to update the "data" structure of the webpart.
        section_type (str, optional):
            "horizontalSections" (note the plural!)
            "verticalSection" (note the singular!)
        section_id (str | int):
            The ID of the section.Only relevant for horizontal sections.
            Simple values like 1,2,3...
            Defaults to 1.
        column_id (int | str, optional):
            For horizontalSections the column ID has to be provided.
            Defaults to 1.
        republish (bool, optional):
            If True, the page is republished to make the section active.

    Returns:
        dict:
            The updated web part.

    Example:
    {
        '@odata.context': "https://graph.microsoft.com/beta/$metadata#sites('ideatedev.sharepoint.com%2C61c0f9cb-39d3-4c04-b60c-31576954a2ab%2Ca678aeab-68ac-46a1-bd95-28020c12de26')/pages('ac7675ee-8891-43b9-b1b2-2d2ced8eb17e')/microsoft.graph.sitePage/canvasLayout/horizontalSections('1')/columns('1')/webparts/$entity",
        '@odata.type': '#microsoft.graph.standardWebPart',
        'id': '3df7fe9a-a1e0-4212-968c-73bd70ca3e31',
        'webPartType': 'eb95c819-ab8f-4689-bd03-0c2d65d47b1f',
        'data': {
            'audiences': [...],
            'dataVersion': '1.0',
            'title': 'Site activity',
            'properties': {'maxItems': 9},
            'serverProcessedContent': {
                'htmlStrings': [],
                'searchablePlainTexts': [],
                'links': [],
                'imageSources': []
            }
        }
    }

    """

    request_url = (
        self.config()["sitesUrl"]
        + "/"
        + site_id
        + "/pages/"
        + page_id
        + "/microsoft.graph.sitePage/canvasLayout/"
        + section_type
    )
    if section_type == "horizontalSections":
        request_url += "/" + str(section_id)
        request_url += "/columns/" + str(column_id)
    request_url += "/webparts"

    request_header = self.request_header()

    # Construct the payload to update the specific property
    payload = {
        "@odata.type": "#microsoft.graph.standardWebPart",  # likle "#microsoft.graph.standardWebPart" - this is mandatory!
        "webPartType": webpart_type_id,  # this is mandatory!
        "data": create_data,
    }

    response = self.do_request(
        url=request_url,
        method="POST",
        headers=request_header,
        json_data=payload,
        timeout=REQUEST_TIMEOUT,
        failure_message="Failed to create SharePoint webpart of type -> '{}' on SharePoint page -> '{}'{} in SharePoint site -> '{}', ".format(
            webpart_type_id,
            page_id,
            " (horizontal section -> {}, column -> {})".format(section_id, column_id)
            if section_type == "horizontalSections"
            else " (vertical section)",
            site_id,
        ),
    )

    # Check if the page should be republished:
    if response and republish:
        self.publish_sharepoint_page(site_id=site_id, page_id=page_id)

    return response

add_team(name, template_name='standard')

Add M365 Team based on an existing M365 Group.

Parameters:

Name Type Description Default
name str

The name of the team. It is assumed that a group with the same name does already exist!

required
template_name str

The name of the team template. "standard" is the default value.

'standard'

Returns:

Name Type Description
dict dict | None

Team information (json - empty text!) or None if the team couldn't be created (e.g. because it exisits already).

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def add_team(self, name: str, template_name: str = "standard") -> dict | None:
    """Add M365 Team based on an existing M365 Group.

    Args:
        name (str):
            The name of the team. It is assumed that a group with the same name does already exist!
        template_name (str, optional):
            The name of the team template. "standard" is the default value.

    Returns:
        dict:
            Team information (json - empty text!) or None if the team couldn't be created
            (e.g. because it exisits already).

    """

    response = self.get_group(group_name=name)
    group_id = self.get_result_value(response=response, key="id", index=0)
    if not group_id:
        self.logger.error(
            "M365 Group -> '%s' not found! It is required for creating a corresponding M365 Team.",
            name,
        )
        return None

    response = self.get_group_owners(group_name=name)
    if response is None or "value" not in response or not response["value"]:
        self.logger.warning(
            "M365 Group -> '%s' has no owners. This is required for creating a corresponding M365 Team.",
            name,
        )
        return None

    team_post_body = {
        "template@odata.bind": "{}('{}')".format(
            self.config()["teamsTemplatesUrl"],
            template_name,
        ),
        "group@odata.bind": "{}('{}')".format(self.config()["groupsUrl"], group_id),
    }

    request_url = self.config()["teamsUrl"]
    request_header = self.request_header()

    self.logger.debug("Adding M365 Team -> '%s'; calling -> %s", name, request_url)
    self.logger.debug("M365 Team attributes -> %s", str(team_post_body))

    return self.do_request(
        url=request_url,
        method="POST",
        data=json.dumps(team_post_body),
        headers=request_header,
        timeout=REQUEST_TIMEOUT,
        failure_message="Failed to add M365 Team -> '{}'".format(name),
    )

add_teams_app_to_channel(team_name, channel_name, app_id, tab_name, app_url, cs_node_id)

Add tab for Extended ECM app to an M365 Team channel.

Parameters:

Name Type Description Default
team_name str

The name of the M365 Team

required
channel_name str

The name of the channel.

required
app_id str

ID of the MS Teams Application (e.g. the Extended ECM Teams App).

required
tab_name str

The name of the tab.

required
app_url str

The web URL of the app.

required
cs_node_id int

The node ID of the target workspace or container in Extended ECM.

required

Returns:

Name Type Description
dict dict | None

Return data structure (dictionary) or None if the request fails.

dict | None

Example return data:

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def add_teams_app_to_channel(
    self,
    team_name: str,
    channel_name: str,
    app_id: str,
    tab_name: str,
    app_url: str,
    cs_node_id: int,
) -> dict | None:
    """Add tab for Extended ECM app to an M365 Team channel.

    Args:
        team_name (str):
            The name of the M365 Team
        channel_name (str):
            The name of the channel.
        app_id (str):
            ID of the MS Teams Application (e.g. the Extended ECM Teams App).
        tab_name (str):
            The name of the tab.
        app_url (str):
            The web URL of the app.
        cs_node_id (int):
            The node ID of the target workspace or container in Extended ECM.

    Returns:
        dict:
            Return data structure (dictionary) or None if the request fails.

        Example return data:

    """

    response = self.get_team(name=team_name)
    team_id = self.get_result_value(response=response, key="id", index=0)
    if not team_id:
        return None

    # Get the channels of the M365 Team:
    response = self.get_team_channels(name=team_name)
    if not response or not response["value"] or not response["value"][0]:
        return None

    # Look the channel by name and then retrieve its ID:
    channel = next(
        (item for item in response["value"] if item["displayName"] == channel_name),
        None,
    )
    if not channel:
        self.logger.error(
            "Cannot find Channel -> '%s' on M365 Team -> '%s'!",
            channel_name,
            team_name,
        )
        return None
    channel_id = channel["id"]

    request_url = self.config()["teamsUrl"] + "/" + str(team_id) + "/channels/" + str(channel_id) + "/tabs"

    request_header = self.request_header()

    # Create tab configuration payload:
    tab_config = {
        "teamsApp@odata.bind": f"https://graph.microsoft.com/v1.0/appCatalogs/teamsApps/{app_id}",
        "displayName": tab_name,
        "configuration": {
            "entityId": cs_node_id,  # Unique identifier for the tab
            "contentUrl": app_url,
            "removeUrl": "",
            "websiteUrl": app_url + "&showBW=true&title=" + tab_name,
        },
    }

    self.logger.debug(
        "Add Tab -> '%s' with App ID -> %s to Channel -> '%s' of Microsoft 365 Team -> '%s'; calling -> %s",
        tab_name,
        app_id,
        channel_name,
        team_name,
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="POST",
        headers=request_header,
        json_data=tab_config,
        timeout=REQUEST_TIMEOUT,
        failure_message="Failed to add Tab for M365 Team -> '{}' ({}) and Channel -> '{}' ({})".format(
            team_name,
            team_id,
            channel_name,
            channel_id,
        ),
    )

add_user(email, password, first_name, last_name, location='US', department='', company_name='Innovate')

Add a M365 user.

Parameters:

Name Type Description Default
email str

The email address of the user. This is also the unique identifier.

required
password str

The password of the user.

required
first_name str

The first name of the user.

required
last_name str

The last name of the user.

required
location str

The country ISO 3166-1 alpha-2 code (e.g. US, CA, FR, DE, CN, ...)

'US'
department str

The department of the user.

''
company_name str

The name of the company the user works for.

'Innovate'

Returns:

Type Description
dict | None

dict | None: User information or None if the user couldn't be created (e.g. because it exisits already or if a permission problem occurs).

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def add_user(
    self,
    email: str,
    password: str,
    first_name: str,
    last_name: str,
    location: str = "US",
    department: str = "",
    company_name: str = "Innovate",
) -> dict | None:
    """Add a M365 user.

    Args:
        email (str):
            The email address of the user. This is also the unique identifier.
        password (str):
            The password of the user.
        first_name (str):
            The first name of the user.
        last_name (str):
            The last name of the user.
        location (str, optional):
            The country ISO 3166-1 alpha-2 code (e.g. US, CA, FR, DE, CN, ...)
        department (str, optional):
            The department of the user.
        company_name (str):
            The name of the company the user works for.

    Returns:
        dict | None:
            User information or None if the user couldn't be created (e.g. because it exisits already
            or if a permission problem occurs).

    """

    user_post_body = {
        "accountEnabled": True,
        "displayName": first_name + " " + last_name,
        "givenName": first_name,
        "surname": last_name,
        "mailNickname": email.split("@")[0],
        "userPrincipalName": email,
        "passwordProfile": {
            "forceChangePasswordNextSignIn": False,
            "password": password,
        },
        "usageLocation": location,
    }
    if department:
        user_post_body["department"] = department
    if company_name:
        user_post_body["companyName"] = company_name

    request_url = self.config()["usersUrl"]
    request_header = self.request_header()

    self.logger.debug("Adding M365 user -> %s; calling -> %s", email, request_url)

    return self.do_request(
        url=request_url,
        method="POST",
        headers=request_header,
        data=json.dumps(user_post_body),
        timeout=REQUEST_TIMEOUT,
        failure_message="Failed to add M365 user -> '{}'".format(email),
    )

assign_license_to_user(user_id, sku_id)

Add an M365 license to a user (e.g. to use Office 365).

Parameters:

Name Type Description Default
user_id str

The M365 GUID of the user (can also be the M365 email of the user)

required
sku_id str

M365 GUID of the SKU. (e.g. c7df2760-2c81-4ef7-b578-5b5392b571df for E5 and 6fd2c87f-b296-42f0-b197-1e91e994b900 for E3)

required

Returns:

Name Type Description
dict dict | None

The API response or None if request fails.

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def assign_license_to_user(self, user_id: str, sku_id: str) -> dict | None:
    """Add an M365 license to a user (e.g. to use Office 365).

    Args:
        user_id (str):
            The M365 GUID of the user (can also be the M365 email of the user)
        sku_id (str):
            M365 GUID of the SKU.
            (e.g. c7df2760-2c81-4ef7-b578-5b5392b571df for E5 and
            6fd2c87f-b296-42f0-b197-1e91e994b900 for E3)

    Returns:
        dict:
            The API response or None if request fails.

    """

    request_url = self.config()["usersUrl"] + "/" + user_id + "/assignLicense"
    request_header = self.request_header()

    # Construct the request body for assigning the E5 license
    license_post_body = {
        "addLicenses": [
            {
                "disabledPlans": [],
                "skuId": sku_id,  # "c42b9cae-ea4f-4a69-9ca5-c53bd8779c42"
            },
        ],
        "removeLicenses": [],
    }

    self.logger.debug(
        "Assign M365 license -> %s to M365 user -> %s; calling -> %s",
        sku_id,
        user_id,
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="POST",
        headers=request_header,
        json_data=license_post_body,
        timeout=REQUEST_TIMEOUT,
        failure_message="Failed to assign M365 license -> {} to M365 user -> {}".format(
            sku_id,
            user_id,
        ),
    )

assign_sensitivity_label_to_user(user_email, label_name)

Assign a existing sensitivity label to a user.

TODO: THIS IS CURRENTLY NOT WORKING!

Parameters:

Name Type Description Default
user_email str

The email address of the user (as unique identifier).

required
label_name str

The name of the label (need to exist).

required

Returns:

Type Description
dict | None

dict | None: Return the request response or None if the request fails.

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def assign_sensitivity_label_to_user(self, user_email: str, label_name: str) -> dict | None:
    """Assign a existing sensitivity label to a user.

    TODO: THIS IS CURRENTLY NOT WORKING!

    Args:
        user_email (str):
            The email address of the user (as unique identifier).
        label_name (str):
            The name of the label (need to exist).

    Returns:
        dict | None:
            Return the request response or None if the request fails.

    """

    # Set up the request body with the label name
    body = {"labelName": label_name}

    request_url = self.config()["usersUrl"] + "/" + user_email + "/assignSensitivityLabels"
    request_header = self.request_header()

    self.logger.debug(
        "Assign label -> '%s' to user -> '%s'; calling -> %s",
        label_name,
        user_email,
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="POST",
        headers=request_header,
        json_data=body,
        timeout=REQUEST_TIMEOUT,
        failure_message="Failed to assign label -> '{}' to M365 user -> '{}'".format(
            label_name,
            user_email,
        ),
    )

assign_teams_app_to_team(team_id, app_id)

Assign (add) a MS Teams app to a M365 team.

Afterwards the app can be added as a Tab in a M365 Teams Channel).

Parameters:

Name Type Description Default
team_id str

The ID of the Microsoft 365 Team.

required
app_id str

The ID of the M365 Team App.

required

Returns:

Type Description
dict | None

dict | None: API response or None if the Graph API call fails.

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def assign_teams_app_to_team(self, team_id: str, app_id: str) -> dict | None:
    """Assign (add) a MS Teams app to a M365 team.

    Afterwards the app can be added as a Tab in a M365 Teams Channel).

    Args:
        team_id (str):
            The ID of the Microsoft 365 Team.
        app_id (str):
            The ID of the M365 Team App.

    Returns:
        dict | None:
            API response or None if the Graph API call fails.

    """

    request_url = self.config()["teamsUrl"] + "/" + team_id + "/installedApps"
    request_header = self.request_header()

    post_body = {
        "teamsApp@odata.bind": self.config()["teamsAppsUrl"] + "/" + app_id,
    }

    self.logger.debug(
        "Assign M365 Teams app -> '%s' (%s) to M365 Team -> %s; calling -> %s",
        self.config()["teamsAppName"],
        app_id,
        team_id,
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="POST",
        headers=request_header,
        json_data=post_body,
        timeout=REQUEST_TIMEOUT,
        failure_message="Failed to assign M365 Teams app -> '{}' ({}) to M365 Team -> {}".format(
            self.config()["teamsAppName"],
            app_id,
            team_id,
        ),
    )

assign_teams_app_to_user(user_id, app_name='', app_internal_id='', show_error=False)

Assign (add) a M365 Teams app to a M365 user.

See: https://learn.microsoft.com/en-us/graph/api/userteamwork-post-installedapps?view=graph-rest-1.0&tabs=http

Parameters:

Name Type Description Default
user_id str

The M365 GUID of the user (can also be the M365 email of the user).

required
app_name str

The exact name of the app. Not needed if app_internal_id is provided.

''
app_internal_id str

The internal ID of the app. If not provided it will be derived from app_name.

''
show_error bool

Whether or not an error should be displayed if the user is not found.

False

Returns:

Type Description
dict | None

dict | None: The response of the MS Graph API call or None if the call fails.

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def assign_teams_app_to_user(
    self,
    user_id: str,
    app_name: str = "",
    app_internal_id: str = "",
    show_error: bool = False,
) -> dict | None:
    """Assign (add) a M365 Teams app to a M365 user.

    See: https://learn.microsoft.com/en-us/graph/api/userteamwork-post-installedapps?view=graph-rest-1.0&tabs=http

    Args:
        user_id (str):
            The M365 GUID of the user (can also be the M365 email of the user).
        app_name (str, optional):
            The exact name of the app. Not needed if app_internal_id is provided.
        app_internal_id (str, optional):
            The internal ID of the app. If not provided it will be derived from app_name.
        show_error (bool, optional):
            Whether or not an error should be displayed if the user is not found.

    Returns:
        dict | None:
            The response of the MS Graph API call or None if the call fails.

    """

    if not app_internal_id and not app_name:
        self.logger.error(
            "Either the internal App ID or the App name need to be provided!",
        )
        return None

    if not app_internal_id:
        response = self.get_teams_apps(
            filter_expression="contains(displayName, '{}')".format(app_name),
        )
        app_internal_id = self.get_result_value(
            response=response,
            key="id",
            index=0,
        )
        if not app_internal_id:
            self.logger.error(
                "M365 Teams App -> '%s' not found! Cannot assign App to user -> %s.",
                app_name,
                user_id,
            )
            return None

    request_url = self.config()["usersUrl"] + "/" + user_id + "/teamwork/installedApps"
    request_header = self.request_header()

    post_body = {
        "teamsApp@odata.bind": self.config()["teamsAppsUrl"] + "/" + app_internal_id,
    }

    self.logger.debug(
        "Assign M365 Teams app -> '%s' (%s) to M365 user -> %s; calling -> %s",
        app_name,
        app_internal_id,
        user_id,
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="POST",
        headers=request_header,
        json_data=post_body,
        timeout=REQUEST_TIMEOUT,
        failure_message="Failed to assign M365 Teams app -> '{}' ({}) to M365 user -> {}".format(
            app_name,
            app_internal_id,
            user_id,
        ),
        warning_message="Failed to assign M365 Teams app -> '{}' ({}) to M365 user -> {} (could be the app is assigned organization-wide)".format(
            app_name,
            app_internal_id,
            user_id,
        ),
        show_error=show_error,
    )

authenticate(revalidate=False)

Authenticate at M365 Graph API with client ID and client secret.

Parameters:

Name Type Description Default
revalidate bool

Determins if a re-athentication is enforced. (e.g. if session has timed out with 401 error)

False

Returns:

Type Description
str | None

str | None: The access token. Also stores access token in self._access_token. None in case of an error.

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def authenticate(self, revalidate: bool = False) -> str | None:
    """Authenticate at M365 Graph API with client ID and client secret.

    Args:
        revalidate (bool, optional):
            Determins if a re-athentication is enforced.
            (e.g. if session has timed out with 401 error)

    Returns:
        str | None:
            The access token. Also stores access token in self._access_token.
            None in case of an error.

    """

    # Already authenticated and session still valid?
    if self._access_token and not revalidate:
        self.logger.debug(
            "Session still valid - return existing access token -> %s",
            str(self._access_token),
        )
        return self._access_token

    request_url = self.config()["authenticationUrl"]
    request_header = request_login_headers

    self.logger.debug("Requesting M365 Access Token from -> %s", request_url)

    authenticate_post_body = self.credentials()
    authenticate_response = None

    try:
        authenticate_response = requests.post(
            request_url,
            data=authenticate_post_body,
            headers=request_header,
            timeout=REQUEST_TIMEOUT,
        )
    except requests.exceptions.ConnectionError as exception:
        self.logger.warning(
            "Unable to connect to -> %s : %s",
            self.config()["authenticationUrl"],
            str(exception),
        )
        return None

    if authenticate_response.ok:
        authenticate_dict = self.parse_request_response(authenticate_response)
        if not authenticate_dict:
            return None
        access_token = authenticate_dict["access_token"]
        self.logger.debug("Access Token -> %s", access_token)
    else:
        self.logger.error(
            "Failed to request an M365 Access Token; error -> %s",
            authenticate_response.text,
        )
        return None

    # Store authentication access_token:
    self._access_token = access_token

    return self._access_token

authenticate_user(username, password, scope=None)

Authenticate at M365 Graph API with username and password.

Parameters:

Name Type Description Default
username str

The name (email) of the M365 user.

required
password str

The password of the M365 user.

required
scope str

The scope of the delegated permission. E.g. "Files.ReadWrite". Multiple delegated permissions should be separated by spaces.

None

Returns:

Type Description
str | None

str | None: The access token for the user. Also stores access token in self._access_token. None in case of an error.

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def authenticate_user(self, username: str, password: str, scope: str | None = None) -> str | None:
    """Authenticate at M365 Graph API with username and password.

    Args:
        username (str):
            The name (email) of the M365 user.
        password (str):
            The password of the M365 user.
        scope (str):
            The scope of the delegated permission. E.g. "Files.ReadWrite".
            Multiple delegated permissions should be separated by spaces.

    Returns:
        str | None:
            The access token for the user. Also stores access token in self._access_token.
            None in case of an error.

    """

    request_url = self.config()["authenticationUrl"]
    request_header = request_login_headers

    if not username:
        self.logger.error("Missing user name - cannot authenticate at M365!")
        return None
    if not password:
        self.logger.error(
            "Missing password for user -> '%s' - cannot authenticate at M365!",
            username,
        )
        return None

    self.logger.debug(
        "Requesting M365 Access Token for user -> %s from -> %s%s",
        username,
        request_url,
        " with scope -> '{}'".format(scope) if scope else "",
    )

    authenticate_post_body = self.credentials_user(username=username, password=password, scope=scope)
    authenticate_response = None

    try:
        authenticate_response = requests.post(
            request_url,
            data=authenticate_post_body,
            headers=request_header,
            timeout=REQUEST_TIMEOUT,
        )
    except requests.exceptions.ConnectionError as exception:
        self.logger.warning(
            "Unable to connect to -> %s with username -> %s: %s",
            self.config()["authenticationUrl"],
            username,
            str(exception),
        )
        return None

    if authenticate_response.ok:
        authenticate_dict = self.parse_request_response(authenticate_response)
        if not authenticate_dict:
            return None
        access_token = authenticate_dict["access_token"]
        self.logger.debug("User Access Token -> %s", access_token)
    else:
        self.logger.error(
            "Failed to request an M365 Access Token for user -> '%s'; error -> %s",
            username,
            authenticate_response.text,
        )
        return None

    # Store authentication access_token:
    self._user_access_token = access_token

    return self._user_access_token

config()

Return the configuration dictionary.

Returns:

Name Type Description
dict dict

Configuration dictionary

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def config(self) -> dict:
    """Return the configuration dictionary.

    Returns:
        dict: Configuration dictionary

    """

    return self._config

credentials()

Return the login credentials.

Returns:

Name Type Description
dict dict

A dictionary with (admin) login credentials for M365.

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def credentials(self) -> dict:
    """Return the login credentials.

    Returns:
        dict:
            A dictionary with (admin) login credentials for M365.

    """

    return self.config()["tokenData"]

credentials_user(username, password, scope='Files.ReadWrite')

Get user credentials.

In some cases MS Graph APIs cannot be called via application permissions (client_id, client_secret) but requires a token of a user authenticated with username + password. This is e.g. the case to upload a MS teams app to the catalog.

See https://learn.microsoft.com/en-us/graph/api/teamsapp-publish

Parameters:

Name Type Description Default
username str

The M365 username.

required
password str

The password of the M365 user.

required
scope str

The scope of the delegated permission. It is important to provide a scope for the intended operation like "Files.ReadWrite".

'Files.ReadWrite'

Returns:

Name Type Description
dict dict

A dictionary with the (user) credentials for M365.

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def credentials_user(self, username: str, password: str, scope: str = "Files.ReadWrite") -> dict:
    """Get user credentials.

    In some cases MS Graph APIs cannot be called via
    application permissions (client_id, client_secret)
    but requires a token of a user authenticated
    with username + password. This is e.g. the case
    to upload a MS teams app to the catalog.

    See https://learn.microsoft.com/en-us/graph/api/teamsapp-publish

    Args:
        username (str):
            The M365 username.
        password (str):
            The password of the M365 user.
        scope (str):
            The scope of the delegated permission.
            It is important to provide a scope for the intended operation
            like "Files.ReadWrite".

    Returns:
        dict:
            A dictionary with the (user) credentials for M365.

    """

    # Use OAuth2 / ROPC (Resource Owner Password Credentials):
    credentials = {
        "client_id": self.config()["clientId"],
        "client_secret": self.config()["clientSecret"],
        "grant_type": "password",
        "username": username,
        "password": password,
        "scope": scope,
    }

    return credentials

delete_all_teams(exception_list, pattern_list)

Delete all teams (groups) based on patterns and exceptions.

Only delete MS Teams that are NOT on the exception list AND that are matching at least one of the patterns in the provided pattern list.

This method is used for general cleanup of teams. Be aware that deleted teams are still listed under https://admin.microsoft.com/#/deletedgroups and it may take some days until M365 finally deletes them.

Parameters:

Name Type Description Default
exception_list list

A list of group names that should not be deleted.

required
pattern_list list

A list of patterns for group names to be deleted (regular expression).

required

Returns:

Name Type Description
bool bool

True if teams have been deleted, False otherwise.

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def delete_all_teams(self, exception_list: list, pattern_list: list) -> bool:
    """Delete all teams (groups) based on patterns and exceptions.

    Only delete MS Teams that are NOT on the exception list AND
    that are matching at least one of the patterns in the provided pattern list.

    This method is used for general cleanup of teams. Be aware that deleted teams
    are still listed under https://admin.microsoft.com/#/deletedgroups and it
    may take some days until M365 finally deletes them.

    Args:
        exception_list (list):
            A list of group names that should not be deleted.
        pattern_list (list):
            A list of patterns for group names to be deleted
            (regular expression).

    Returns:
        bool:
            True if teams have been deleted, False otherwise.

    """

    self.logger.info(
        "Delete existing M365 groups/teams matching delete pattern and not on exception list...",
    )

    # Get list of all existing M365 groups/teams:
    groups = self.get_groups_iterator()

    # Process all groups and check if they should be deleted:
    for group in groups:
        group_name = group.get("displayName", None)
        if not group_name:
            continue
        # Check if group is in exception list:
        if group_name in exception_list:
            self.logger.info(
                "M365 Group name -> '%s' is on the exception list. Skipping...",
                group_name,
            )
            continue
        # Check that at least one pattern is found that matches the group:
        for pattern in pattern_list:
            result = re.search(pattern, group_name)
            if result:
                self.logger.info(
                    "M365 Group name -> '%s' is matching pattern -> '%s'. Deleting...",
                    group_name,
                    pattern,
                )
                self.delete_teams(name=group_name)
                break
        else:
            self.logger.info(
                "M365 Group name -> '%s' is not matching any delete pattern. Skipping...",
                group_name,
            )
    return True

delete_mail(user_id, email_id)

Delete email from inbox of a given user and a given email ID.

This requires Mail.ReadWrite Application permissions for the Azure App being used.

Parameters:

Name Type Description Default
user_id str

The M365 ID of the user.

required
email_id str

The M365 ID of the email.

required

Returns:

Type Description
dict | None

dict | None: Email or None of the request fails.

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def delete_mail(self, user_id: str, email_id: str) -> dict | None:
    """Delete email from inbox of a given user and a given email ID.

    This requires Mail.ReadWrite Application permissions for the Azure App being used.

    Args:
        user_id (str):
            The M365 ID of the user.
        email_id (str):
            The M365 ID of the email.

    Returns:
        dict | None:
            Email or None of the request fails.

    """

    request_url = self.config()["usersUrl"] + "/" + user_id + "/messages/" + email_id

    request_header = self.request_header()

    return self.do_request(
        url=request_url,
        method="DELETE",
        headers=request_header,
        timeout=REQUEST_TIMEOUT,
        failure_message="Cannot delete email with ID -> {} from inbox of M365 user -> {}".format(
            email_id,
            user_id,
        ),
    )

delete_sharepoint_section(site_id, page_id, section_type='horizontalSections', section_id=1)

Delete a specific section (horizontal or vertical) on a SharePoint page.

Parameters:

Name Type Description Default
site_id str

The ID of the SharePoint site.

required
page_id str

The ID of the SharePoint page containing the web part.

required
section_type str

"horizontalSections" (note the plural!) "verticalSection" (note the singular!)

'horizontalSections'
section_id int | str

The ID of the section. Only relevant for horizontal sections. Simple values like 1,2,3...

1

Returns:

Name Type Description
dict dict | None

Empty response.

Example: { '_content': b'', '_content_consumed': True, '_next': None, 'status_code': 204, 'headers': { 'Cache-Control': 'no-store, no-cache', 'Strict-Transport-Security': 'max-age=31536000', 'request-id': 'bd21c7fa-751c-43ca-b290-12c30f50d7e1', 'client-request-id': 'bd21c7fa-751c-43ca-b290-12c30f50d7e1', 'x-ms-ags-diagnostic': '{"ServerInfo":{"DataCenter":"Germany West Central","Slice":"E","Ring":"4","ScaleUnit":"004","RoleInstance":"FR2PEPF00000393"}}', 'Date': 'Fri, 14 Feb 2025 20:40:06 GMT'}, 'raw': , 'url': 'https://graph.microsoft.com/beta/sites/ideatedev.sharepoint.com,61c0f9cb-39d3-4c04-b60c-31576954a2ab,a678aeab-68ac-46a1-bd95-28020c12de26/pages/ac7675ee-8891-43b9-b1b2-2d2ced8eb17e/microsoft.graph.sitePage/canvasLayout/horizontalSections/1', 'encoding': None, 'history': [], 'reason': 'No Content', 'cookies': , 'elapsed': datetime.timedelta(microseconds=514597), 'request': , 'connection': }

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def delete_sharepoint_section(
    self,
    site_id: str,
    page_id: str,
    section_type: str = "horizontalSections",
    section_id: int | str = 1,
) -> dict | None:
    """Delete a specific section (horizontal or vertical) on a SharePoint page.

    Args:
        site_id (str):
            The ID of the SharePoint site.
        page_id (str):
            The ID of the SharePoint page containing the web part.
        section_type (str, optional):
            "horizontalSections" (note the plural!)
            "verticalSection" (note the singular!)
        section_id (int | str):
            The ID of the section. Only relevant for horizontal sections.
            Simple values like 1,2,3...

    Returns:
        dict:
            Empty response.

    Example:
    {
        '_content': b'',
        '_content_consumed': True,
        '_next': None,
        'status_code': 204,
        'headers': {
            'Cache-Control': 'no-store, no-cache',
            'Strict-Transport-Security': 'max-age=31536000',
            'request-id': 'bd21c7fa-751c-43ca-b290-12c30f50d7e1',
            'client-request-id': 'bd21c7fa-751c-43ca-b290-12c30f50d7e1',
            'x-ms-ags-diagnostic': '{"ServerInfo":{"DataCenter":"Germany West Central","Slice":"E","Ring":"4","ScaleUnit":"004","RoleInstance":"FR2PEPF00000393"}}', 'Date': 'Fri, 14 Feb 2025 20:40:06 GMT'},
            'raw': <urllib3.response.HTTPResponse object at 0x10f210d90>,
            'url': 'https://graph.microsoft.com/beta/sites/ideatedev.sharepoint.com,61c0f9cb-39d3-4c04-b60c-31576954a2ab,a678aeab-68ac-46a1-bd95-28020c12de26/pages/ac7675ee-8891-43b9-b1b2-2d2ced8eb17e/microsoft.graph.sitePage/canvasLayout/horizontalSections/1',
            'encoding': None,
            'history': [],
            'reason': 'No Content',
            'cookies': <RequestsCookieJar[]>,
            'elapsed': datetime.timedelta(microseconds=514597),
            'request': <PreparedRequest [DELETE]>,
            'connection': <requests.adapters.HTTPAdapter object at 0x11841d700>
        }

    """

    request_url = (
        self.config()["sitesUrl"]
        + "/"
        + site_id
        + "/pages/"
        + page_id
        + "/microsoft.graph.sitePage/canvasLayout/"
        + section_type
    )

    if section_type == "horizontalSections":
        request_url += "/" + str(section_id)

    request_header = self.request_header()

    response = self.do_request(
        url=request_url,
        method="DELETE",
        headers=request_header,
        timeout=REQUEST_TIMEOUT,
        failure_message="Failed to delete SharePoint section of type -> '{}' on SharePoint page -> '{}' in Sharepoint site -> '{}', ".format(
            section_type,
            page_id,
            site_id,
        ),
    )

    return response

delete_team(team_id)

Delete Microsoft 365 Team with a specific ID.

Parameters:

Name Type Description Default
team_id str

The ID of the Microsoft 365 Team to delete.

required

Returns:

Type Description
dict | None

dict | None: Response dictionary if the team has been deleted, False otherwise.

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def delete_team(self, team_id: str) -> dict | None:
    """Delete Microsoft 365 Team with a specific ID.

    Args:
        team_id (str):
            The ID of the Microsoft 365 Team to delete.

    Returns:
        dict | None:
            Response dictionary if the team has been deleted, False otherwise.

    """

    request_url = self.config()["groupsUrl"] + "/" + team_id

    request_header = self.request_header()

    self.logger.debug(
        "Delete Microsoft 365 Teams with ID -> %s; calling -> %s",
        team_id,
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="DELETE",
        headers=request_header,
        timeout=REQUEST_TIMEOUT,
        failure_message="Failed to delete M365 Team with ID -> {}".format(team_id),
    )

delete_teams(name)

Delete Microsoft 365 Teams with a specific name.

Microsoft 365 allows to have multiple teams with the same name. So this method may delete multiple teams if the have the same name. The Graph API we use here is the M365 Group API as deleting the group also deletes the associated team.

Parameters:

Name Type Description Default
name str

The name of the Microsoft 365 Team.

required

Returns:

Name Type Description
bool bool

True if teams have been deleted, False otherwise.

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def delete_teams(self, name: str) -> bool:
    """Delete Microsoft 365 Teams with a specific name.

    Microsoft 365 allows to have multiple teams with the same name. So this method may delete
    multiple teams if the have the same name. The Graph API we use here
    is the M365 Group API as deleting the group also deletes the associated team.

    Args:
        name (str):
            The name of the Microsoft 365 Team.

    Returns:
        bool:
            True if teams have been deleted, False otherwise.

    """

    # We need a special handling of team names with single quotes:
    escaped_group_name = name.replace("'", "''")
    encoded_group_name = quote(escaped_group_name, safe="")
    request_url = self.config()["groupsUrl"] + "?$filter=displayName eq '{}'".format(encoded_group_name)

    request_header = self.request_header()

    self.logger.debug(
        "Delete all Microsoft 365 Teams with name -> '%s'; calling -> %s",
        name,
        request_url,
    )

    existing_teams = self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=REQUEST_TIMEOUT,
        failure_message="Failed to get list of M365 Teams to delete",
    )

    if existing_teams:
        data = existing_teams.get("value")
        if data:
            counter = 0
            for team in data:
                team_id = team.get("id")
                response = self.delete_team(team_id)

                if not response:
                    self.logger.error(
                        "Failed to delete M365 Team -> '%s' (%s)!",
                        name,
                        team_id,
                    )
                    continue
                counter += 1

            self.logger.info(
                "%s M365 Team%s with name -> '%s' %s been deleted.",
                str(counter),
                "s" if counter > 1 else "",
                name,
                "have" if counter > 1 else "has",
            )
            return True
        else:
            self.logger.info("No M365 Team with name -> '%s' found.", name)
            return False
    else:
        self.logger.error("Failed to retrieve M365 Teams with name -> '%s'!", name)
        return False

delete_teams_app_from_channel(team_name, channel_name, tab_name)

Delete an existing tab for Extended ECM app from an M365 Team channel.

Parameters:

Name Type Description Default
team_name str

The name of the M365 Team.

required
channel_name str

The name of the channel.

required
tab_name str

The name of the tab.

required

Returns:

Name Type Description
bool bool

True = success, False = Error.

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def delete_teams_app_from_channel(
    self,
    team_name: str,
    channel_name: str,
    tab_name: str,
) -> bool:
    """Delete an existing tab for Extended ECM app from an M365 Team channel.

    Args:
        team_name (str):
            The name of the M365 Team.
        channel_name (str):
            The name of the channel.
        tab_name (str):
            The name of the tab.

    Returns:
        bool:
            True = success, False = Error.

    """

    response = self.get_team(name=team_name)
    team_id = self.get_result_value(response=response, key="id", index=0)
    if not team_id:
        return False

    # Get the channels of the M365 Team:
    response = self.get_team_channels(team_name)
    if not response or not response["value"] or not response["value"][0]:
        return False

    # Look the channel by name and then retrieve its ID:
    channel = next(
        (item for item in response["value"] if item["displayName"] == channel_name),
        None,
    )
    if not channel:
        self.logger.error(
            "Cannot find Channel -> '%s' for M365 Team -> '%s'!",
            channel_name,
            team_name,
        )
        return False
    channel_id = channel["id"]

    # Get the tabs of the M365 Team channel:
    response = self.get_team_channel_tabs(team_name=team_name, channel_name=channel_name)
    if not response or not response["value"] or not response["value"][0]:
        return False

    # Lookup the tabs by name and then retrieve their IDs (in worst case it can
    # be multiple tabs / apps with same name if former cleanups did not work):
    tab_list = [item for item in response["value"] if item["displayName"] == tab_name]
    if not tab_list:
        self.logger.error(
            "Cannot find Tab -> '%s' on M365 Team -> '%s' (%s) and Channel -> '%s' (%s)!",
            tab_name,
            team_name,
            team_id,
            channel_name,
            channel_id,
        )
        return False

    for tab in tab_list:
        tab_id = tab["id"]

        request_url = (
            self.config()["teamsUrl"] + "/" + str(team_id) + "/channels/" + str(channel_id) + "/tabs/" + str(tab_id)
        )

        request_header = self.request_header()

        self.logger.debug(
            "Delete Tab -> '%s' (%s) from Channel -> '%s' (%s) of Microsoft 365 Teams -> '%s' (%s); calling -> %s",
            tab_name,
            tab_id,
            channel_name,
            channel_id,
            team_name,
            team_id,
            request_url,
        )

        response = self.do_request(
            url=request_url,
            method="DELETE",
            headers=request_header,
            timeout=REQUEST_TIMEOUT,
            failure_message="Failed to delete Tab -> '{}' ({}) for M365 Team -> '{}' ({}) and Channel -> '{}' ({})".format(
                tab_name,
                tab_id,
                team_name,
                team_id,
                channel_name,
                channel_id,
            ),
            parse_request_response=False,
        )

        if response and response.ok:
            break
        return False
    # end for tab in tab_list

    return True

do_request(url, method='GET', headers=None, data=None, json_data=None, files=None, params=None, timeout=REQUEST_TIMEOUT, show_error=True, show_warning=False, warning_message='', failure_message='', success_message='', max_retries=REQUEST_MAX_RETRIES, retry_forever=False, parse_request_response=True, stream=False)

Call an M365 Graph API in a safe way.

Parameters:

Name Type Description Default
url str

URL to send the request to.

required
method str

HTTP method (GET, POST, etc.). Defaults to "GET".

'GET'
headers dict | None

Request Headers. Defaults to None.

None
data dict | None

Request payload. Defaults to None.

None
json_data dict | None

Request payload for the JSON parameter. Defaults to None.

None
files dict | None

Dictionary of {"name": file-tuple} for multipart encoding upload. file-tuple can be a 2-tuple ("filename", fileobj) or a 3-tuple ("filename", fileobj, "content_type")

None
params dict | None

Add key-value pairs to the query string of the URL. When you use the params parameter, requests automatically appends the key-value pairs to the URL as part of the query string

None
timeout float | None

Timeout for the request in seconds. Defaults to REQUEST_TIMEOUT.

REQUEST_TIMEOUT
show_error bool

Whether or not an error should be logged in case of a failed REST call. If False, then only a warning is logged. Defaults to True.

True
show_warning bool

Whether or not an warning should be logged in case of a failed REST call. If False, then only a warning is logged. Defaults to True.

False
warning_message str

Specific warning message. Defaults to "". If not given the error_message will be used.

''
failure_message str

Specific error message. Defaults to "".

''
success_message str

Specific success message. Defaults to "".

''
max_retries int

How many retries on Connection errors? Default is REQUEST_MAX_RETRIES.

REQUEST_MAX_RETRIES
retry_forever bool

Eventually wait forever - without timeout. Defaults to False.

False
parse_request_response bool

Defines whether the response.text should be interpreted as json and loaded into a dictionary. True is the default.

True
stream bool

This parameter is used to control whether the response content should be immediately downloaded or streamed incrementally.

False

Returns:

Type Description
dict | None

dict | None: Response of M365 Graph REST API or None in case of an error.

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def do_request(
    self,
    url: str,
    method: str = "GET",
    headers: dict | None = None,
    data: dict | None = None,
    json_data: dict | None = None,
    files: dict | None = None,
    params: dict | None = None,
    timeout: float | None = REQUEST_TIMEOUT,
    show_error: bool = True,
    show_warning: bool = False,
    warning_message: str = "",
    failure_message: str = "",
    success_message: str = "",
    max_retries: int = REQUEST_MAX_RETRIES,
    retry_forever: bool = False,
    parse_request_response: bool = True,
    stream: bool = False,
) -> dict | None:
    """Call an M365 Graph API in a safe way.

    Args:
        url (str):
            URL to send the request to.
        method (str, optional):
            HTTP method (GET, POST, etc.). Defaults to "GET".
        headers (dict | None, optional):
            Request Headers. Defaults to None.
        data (dict | None, optional):
            Request payload. Defaults to None.
        json_data (dict | None, optional):
            Request payload for the JSON parameter. Defaults to None.
        files (dict | None, optional):
            Dictionary of {"name": file-tuple} for multipart encoding upload.
            file-tuple can be a 2-tuple ("filename", fileobj) or a 3-tuple ("filename", fileobj, "content_type")
        params (dict | None, optional):
            Add key-value pairs to the query string of the URL.
            When you use the params parameter, requests automatically appends
            the key-value pairs to the URL as part of the query string
        timeout (float | None, optional):
            Timeout for the request in seconds. Defaults to REQUEST_TIMEOUT.
        show_error (bool, optional):
            Whether or not an error should be logged in case of a failed REST call.
            If False, then only a warning is logged. Defaults to True.
        show_warning (bool, optional):
            Whether or not an warning should be logged in case of a
            failed REST call.
            If False, then only a warning is logged. Defaults to True.
        warning_message (str, optional):
            Specific warning message. Defaults to "". If not given the error_message will be used.
        failure_message (str, optional):
            Specific error message. Defaults to "".
        success_message (str, optional):
            Specific success message. Defaults to "".
        max_retries (int, optional):
            How many retries on Connection errors? Default is REQUEST_MAX_RETRIES.
        retry_forever (bool, optional):
            Eventually wait forever - without timeout. Defaults to False.
        parse_request_response (bool, optional):
            Defines whether the response.text should be interpreted as json and loaded into a dictionary.
            True is the default.
        stream (bool, optional):
            This parameter is used to control whether the response content should be immediately
            downloaded or streamed incrementally.

    Returns:
        dict | None:
            Response of M365 Graph REST API or None in case of an error.

    """

    if headers is None:
        self.logger.error(
            "Missing request header. Cannot send request to Microsoft M365 Graph API!",
        )
        return None

    # In case of an expired session we reauthenticate and
    # try 1 more time. Session expiration should not happen
    # twice in a row:
    retries = 0

    while True:
        try:
            response = requests.request(
                method=method,
                url=url,
                data=data,
                json=json_data,
                files=files,
                params=params,
                headers=headers,
                timeout=timeout,
                stream=stream,
            )

            if response.ok:
                if success_message:
                    self.logger.info(success_message)
                if parse_request_response:
                    return self.parse_request_response(response)
                else:
                    return response
            # Check if Session has expired - then re-authenticate and try once more
            elif response.status_code == 401 and retries == 0:
                self.logger.debug("Session has expired - try to re-authenticate...")
                self.authenticate(revalidate=True)
                headers = self.request_header()
                retries += 1
            elif response.status_code in [502, 503, 504] and retries < REQUEST_MAX_RETRIES:
                self.logger.warning(
                    "M365 Graph API delivered server side error -> %s; retrying in %s seconds...",
                    response.status_code,
                    (retries + 1) * 60,
                )
                time.sleep((retries + 1) * 60)
                retries += 1
            elif response.status_code in [404, 429] and retries < REQUEST_MAX_RETRIES:
                self.logger.warning(
                    "M365 Graph API is too slow or throtteling calls -> %s; retrying in %s seconds...",
                    response.status_code,
                    (retries + 1) * 60,
                )
                time.sleep((retries + 1) * 60)
                retries += 1
            else:
                # Handle plain HTML responses to not pollute the logs
                content_type = response.headers.get("content-type", None)
                response_text = (
                    "HTML content (only printed in debug log)" if content_type == "text/html" else response.text
                )

                if show_error:
                    self.logger.error(
                        "%s; status -> %s/%s; error -> %s",
                        failure_message,
                        response.status_code,
                        HTTPStatus(response.status_code).phrase,
                        response_text,
                    )
                elif show_warning:
                    self.logger.warning(
                        "%s; status -> %s/%s; warning -> %s",
                        warning_message if warning_message else failure_message,
                        response.status_code,
                        HTTPStatus(response.status_code).phrase,
                        response_text,
                    )
                if content_type == "text/html":
                    self.logger.debug(
                        "%s; status -> %s/%s; warning -> %s",
                        failure_message,
                        response.status_code,
                        HTTPStatus(response.status_code).phrase,
                        response.text,
                    )
                return None
        except requests.exceptions.Timeout:
            if retries <= max_retries:
                self.logger.warning(
                    "Request timed out. Retrying in %s seconds...",
                    str(REQUEST_RETRY_DELAY),
                )
                retries += 1
                time.sleep(REQUEST_RETRY_DELAY)  # Add a delay before retrying
            else:
                self.logger.error(
                    "%s; timeout error!",
                    failure_message,
                )
                if retry_forever:
                    # If it fails after REQUEST_MAX_RETRIES retries we let it wait forever
                    self.logger.warning("Turn timeouts off and wait forever...")
                    timeout = None
                else:
                    return None
        except requests.exceptions.ConnectionError:
            if retries <= max_retries:
                self.logger.warning(
                    "Connection error. Retrying in %s seconds...",
                    str(REQUEST_RETRY_DELAY),
                )
                retries += 1
                time.sleep(REQUEST_RETRY_DELAY)  # Add a delay before retrying
            else:
                self.logger.error(
                    "%s; connection error!",
                    failure_message,
                )
                if retry_forever:
                    # If it fails after REQUEST_MAX_RETRIES retries we let it wait forever
                    self.logger.warning("Turn timeouts off and wait forever...")
                    timeout = None
                    time.sleep(REQUEST_RETRY_DELAY)  # Add a delay before retrying
                else:
                    return None
        # end try
        self.logger.debug(
            "Retrying REST API %s call -> %s... (retry = %s)",
            method,
            url,
            str(retries),
        )

download_user_photo(user_id, photo_path)

Download the M365 user photo and save it to the local file system.

Parameters:

Name Type Description Default
user_id str

The M365 GUID of the user (can also be the M365 email of the user).

required
photo_path str

The directory where the photo should be saved.

required

Returns:

Name Type Description
str str | None

The name of the photo file in the file system (with full path) or None if the call of the REST API fails.

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def download_user_photo(self, user_id: str, photo_path: str) -> str | None:
    """Download the M365 user photo and save it to the local file system.

    Args:
        user_id (str):
            The M365 GUID of the user (can also be the M365 email of the user).
        photo_path (str):
            The directory where the photo should be saved.

    Returns:
        str:
            The name of the photo file in the file system (with full path) or None if
            the call of the REST API fails.

    """

    request_url = self.config()["usersUrl"] + "/" + user_id + "/photo/$value"
    request_header = self.request_header("application/json")

    self.logger.debug(
        "Downloading photo for M365 user with ID -> %s; calling -> %s",
        user_id,
        request_url,
    )

    response = self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=REQUEST_TIMEOUT,
        failure_message="Failed to download photo for M365 user with ID -> {}".format(
            user_id,
        ),
        stream=True,
        parse_request_response=False,
    )

    if response and response.ok:
        content_type = response.headers.get("Content-Type", "image/png")
        if content_type == "image/jpeg":
            file_extension = "jpg"
        elif content_type == "image/png":
            file_extension = "png"
        else:
            file_extension = "img"  # Default extension if type is unknown
        file_path = os.path.join(
            photo_path,
            "{}.{}".format(user_id, file_extension),
        )

        try:
            with open(file_path, "wb") as file:
                file.writelines(response.iter_content(chunk_size=8192))
        except OSError:
            self.logger.error(
                "Error saving photo for user with ID -> %s!",
                user_id,
            )
        else:
            self.logger.info(
                "Photo for M365 user with ID -> %s saved to -> '%s'.",
                user_id,
                file_path,
            )
            return file_path

    return None

email_verification(user_email, sender, subject, url_search_pattern, line_end_marker='=', multi_line=True, multi_line_end_marker='%3D', replacements=None, max_retries=6, use_browser_automation=False, password='', password_field_id='', password_confirmation_field_id='', password_submit_xpath='', terms_of_service_xpath='')

Process email verification.

Parameters:

Name Type Description Default
user_email str

Email address of user recieving the verification mail.

required
sender str

Email sender (address)

required
subject str

Email subject to look for (can be substring)

required
url_search_pattern str

String the URL needs to contain to identify it.

required
line_end_marker str

The character that marks line ends in the mail.

'='
multi_line bool

Whether or not this is a multi-line mail.

True
multi_line_end_marker str

If the URL spans multiple lines this is the "end" marker for the last line.

'%3D'
replacements list

If the URL needs some treatment these replacements can be applied.

None
max_retries int

The number of retries in case of an error.

6
use_browser_automation bool

If Selenium-based browser automation should be used or not. Default = False.

False
password str

In case a password is required for browser automation. Default = "",

''
password_field_id str

The password field name in the HTML page of a confirmation dialog. Default = "",

''
password_confirmation_field_id str

The password confirmation field name in the HTML page of a confirmation dialog. Default = "".

''
password_submit_xpath str

Default = "".

''
terms_of_service_xpath str

Default = "".

''

Returns:

Name Type Description
bool bool

True = Success, False = Failure.

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def email_verification(
    self,
    user_email: str,
    sender: str,
    subject: str,
    url_search_pattern: str,
    line_end_marker: str = "=",
    multi_line: bool = True,
    multi_line_end_marker: str = "%3D",
    replacements: list | None = None,
    max_retries: int = 6,
    use_browser_automation: bool = False,
    password: str = "",
    password_field_id: str = "",
    password_confirmation_field_id: str = "",
    password_submit_xpath: str = "",
    terms_of_service_xpath: str = "",
) -> bool:
    """Process email verification.

    Args:
        user_email (str):
            Email address of user recieving the verification mail.
        sender (str):
            Email sender (address)
        subject (str):
            Email subject to look for (can be substring)
        url_search_pattern (str):
            String the URL needs to contain to identify it.
        line_end_marker (str, optional):
            The character that marks line ends in the mail.
        multi_line (bool, optional):
            Whether or not this is a multi-line mail.
        multi_line_end_marker (str, optional):
            If the URL spans multiple lines this is the "end" marker for the last line.
        replacements (list, optional):
            If the URL needs some treatment these replacements can be applied.
        max_retries (int, optional):
            The number of retries in case of an error.
        use_browser_automation (bool, optional):
            If Selenium-based browser automation should be used or not. Default = False.
        password (str, optional):
            In case a password is required for browser automation. Default = "",
        password_field_id (str, optional):
            The password field name in the HTML page of a confirmation dialog. Default = "",
        password_confirmation_field_id (str, optional):
            The password confirmation field name in the HTML page of a confirmation dialog.
            Default = "".
        password_submit_xpath (str, optional):
            Default = "".
        terms_of_service_xpath (str, optional):
            Default = "".

    Returns:
        bool:
            True = Success, False = Failure.

    """

    # Determine the M365 user for the current user by
    # the email address:
    m365_user = self.get_user(user_email=user_email)
    m365_user_id = self.get_result_value(response=m365_user, key="id")
    if not m365_user_id:
        self.logger.warning("Cannot find M365 user -> %s", user_email)
        return False

    if replacements is None:
        replacements = [{"from": "=3D", "to": "="}]

    retries = 0
    while retries < max_retries:
        response = self.get_mail(
            user_id=m365_user_id,
            sender=sender,
            subject=subject,
            show_error=False,
        )
        if response and response["value"]:
            emails = response["value"]
            # potentially there may be multiple matching emails,
            # we want the most recent one (from today):
            latest_email = max(emails, key=lambda x: x["receivedDateTime"])
            # Extract just the date:
            latest_email_date = latest_email["receivedDateTime"].split("T")[0]
            # Get the current date (today):
            today_date = datetime.now(UTC).strftime("%Y-%m-%d")
            # We do a sanity check here: the verification mail should be from today,
            # otherwise we assume it is an old mail and we need to wait for the
            # new verification mail to yet arrive:
            if latest_email_date != today_date:
                self.logger.info(
                    "Verification email not yet received (latest mail from -> %s). Waiting %s seconds...",
                    latest_email_date,
                    10 * (retries + 1),
                )
                time.sleep(10 * (retries + 1))
                retries += 1
                continue
            email_id = latest_email["id"]
            # The full email body needs to be loaded with a separate REST call:
            body_text = self.get_mail_body(user_id=m365_user_id, email_id=email_id)
            # Extract the verification URL.
            if body_text:
                url = self.extract_url_from_message_body(
                    message_body=body_text,
                    search_pattern=url_search_pattern,
                    line_end_marker=line_end_marker,
                    multi_line=multi_line,
                    multi_line_end_marker=multi_line_end_marker,
                    replacements=replacements,
                )
            else:
                url = ""
            if not url:
                self.logger.warning(
                    "Cannot find verification link in the email body!",
                )
                return False
            # Simulate a "click" on this URL:
            if use_browser_automation:
                self.logger.info("Using browser automation for email verification...")
                # Core Share needs a full browser:
                try:
                    browser_automation_object = BrowserAutomation(
                        take_screenshots=True,
                        automation_name="email-verification",
                        logger=self.logger,
                    )
                except Exception:
                    self.logger.error("Failed to create browser automation object. Bailing out...")
                    return False

                self.logger.info(
                    "Open URL -> %s to verify account or email address change...",
                    url,
                )
                success = browser_automation_object.get_page(url=url)
                if success:
                    user_interaction_required = False
                    self.logger.info(
                        "Successfully opened URL. Browser title is -> '%s'.",
                        browser_automation_object.get_title(),
                    )
                    if password_field_id:
                        password_field = browser_automation_object.find_elem(
                            selector=password_field_id,
                            show_error=False,
                        )
                        if password_field:
                            # The subsequent processing is only required if
                            # the returned page requests a password change:
                            user_interaction_required = True
                            self.logger.info(
                                "Found password field on returned page - it seems email verification requests password entry!",
                            )
                            result = browser_automation_object.find_elem_and_set(
                                selector=password_field_id,
                                value=password,
                                is_sensitive=True,
                            )
                            if not result:
                                self.logger.error(
                                    "Failed to enter password in field -> '%s'!",
                                    password_field_id,
                                )
                                success = False
                        else:
                            self.logger.info(
                                "No user interaction required (no password change or terms of service acceptance).",
                            )
                    if user_interaction_required and password_confirmation_field_id:
                        password_confirm_field = browser_automation_object.find_elem(
                            selector=password_confirmation_field_id,
                            show_error=False,
                        )
                        if password_confirm_field:
                            self.logger.info(
                                "Found password confirmation field on returned page - it seems email verification requests consecutive password.",
                            )
                            result = browser_automation_object.find_elem_and_set(
                                selector=password_confirmation_field_id,
                                value=password,
                                is_sensitive=True,
                            )
                            if not result:
                                self.logger.error(
                                    "Failed to enter password in field -> '%s'!",
                                    password_confirmation_field_id,
                                )
                                success = False
                    if user_interaction_required and password_submit_xpath:
                        password_submit_button = browser_automation_object.find_elem(
                            selector=password_submit_xpath,
                            selector_type="xpath",
                            show_error=False,
                        )
                        if password_submit_button:
                            self.logger.info(
                                "Submit password change dialog with button -> '%s' (found with XPath -> %s).",
                                password_submit_button.inner_text(),
                                password_submit_xpath,
                            )
                            result = browser_automation_object.find_elem_and_click(
                                selector=password_submit_xpath,
                                selector_type="xpath",
                            )
                            if not result:
                                self.logger.error(
                                    "Failed to press submit button -> %s",
                                    password_submit_xpath,
                                )
                                success = False
                        # The Terms of service dialog has some weird animation
                        # which require a short wait time. It seems it is required!
                        time.sleep(1)
                        terms_accept_button = browser_automation_object.find_elem(
                            selector=terms_of_service_xpath,
                            selector_type="xpath",
                            show_error=False,
                        )
                        if terms_accept_button:
                            self.logger.info(
                                "Accept terms of service with button -> '%s' (found with XPath -> %s).",
                                terms_accept_button.inner_text(),
                                terms_of_service_xpath,
                            )
                            result = browser_automation_object.find_elem_and_click(
                                selector=terms_of_service_xpath,
                                selector_type="xpath",
                            )
                            if not result:
                                self.logger.error(
                                    "Failed to accept terms of service with button -> '%s'!",
                                    terms_accept_button.inner_text(),
                                )
                                success = False
                        else:
                            self.logger.info(
                                "No Terms of Service acceptance required.",
                            )
                    # end if user_interaction_required and password_submit_xpath:
                # end if success:
            # end if use_browser_automation
            else:
                # Salesforce (other than Core Share) is OK with the simple HTTP GET request:
                self.logger.info(
                    "Open URL -> %s to verify account or email change...",
                    url,
                )
                response = self._http_object.http_request(url=url, method="GET")
                success = response and response.ok

            if success:
                self.logger.info(
                    "Remove email from inbox of user -> %s...",
                    user_email,
                )
                response = self.delete_mail(user_id=m365_user_id, email_id=email_id)
                if not response:
                    self.logger.warning(
                        "Couldn't remove the mail from the inbox of user -> %s!",
                        user_email,
                    )
                # We have success now and can break from the while loop
                return True
            else:
                self.logger.error(
                    "Failed to process e-mail verification for user -> %s!",
                    user_email,
                )
                return False
        # end if response and response["value"]
        else:
            self.logger.info(
                "Verification email not yet received (no mails with sender -> %s and subject -> '%s' found). Waiting %s seconds...",
                sender,
                subject,
                10 * (retries + 1),
            )
            time.sleep(10 * (retries + 1))
            retries += 1
    # end while

    self.logger.warning(
        "Verification mail for user -> %s has not arrived in time.",
        user_email,
    )

    return False

exist_result_item(response, key, value, sub_dict_name='')

Check existence of key / value pair in the response properties of an MS Graph API call.

Parameters:

Name Type Description Default
response dict | None

REST response from an MS Graph REST Call.

required
key str

The property name (key).

required
value str

The value to find in the item with the matching key

required
sub_dict_name str

Some MS Graph API calls include nested dict structures that can be requested with an "expand" query parameter. In such a case we use the sub_dict_name to access it.

''

Returns:

Name Type Description
bool bool

True if the value was found, False otherwise

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def exist_result_item(
    self,
    response: dict | None,
    key: str,
    value: str,
    sub_dict_name: str = "",
) -> bool:
    """Check existence of key / value pair in the response properties of an MS Graph API call.

    Args:
        response (dict | None):
            REST response from an MS Graph REST Call.
        key (str):
            The property name (key).
        value (str):
            The value to find in the item with the matching key
        sub_dict_name (str, optional):
            Some MS Graph API calls include nested dict structures that can be requested
            with an "expand" query parameter. In such a case we use the sub_dict_name to
            access it.

    Returns:
        bool:
            True if the value was found, False otherwise

    """

    if not response:
        return False
    if "value" not in response:
        return False

    values = response["value"]
    if not values or not isinstance(values, list):
        return False

    if not sub_dict_name:
        for item in values:
            if value == item[key]:
                return True
    else:
        for item in values:
            if sub_dict_name not in item:
                return False
            if value == item[sub_dict_name][key]:
                return True

    return False

extract_url_from_message_body(message_body, search_pattern, multi_line=False, multi_line_end_marker='%3D', line_end_marker='=', replacements=None)

Parse the email body to extract (a potentially multi-line) URL from the body.

Parameters:

Name Type Description Default
message_body str

Text of the Email body.

required
search_pattern str

Pattern that needs to be in first line of the URL. This makes sure it is the right URL we are looking for.

required
multi_line bool

Is the URL spread over multiple lines?. Defaults to False.

False
multi_line_end_marker str

If it is a multi-line URL, what marks the end of the URL in the last line? Defaults to "%3D".

'%3D'
line_end_marker str

What marks the end of lines 1-(n-1)? Defaults to "=".

'='
replacements list

A list of replacements.

None

Returns:

Type Description
str | None

str | None: The URL text that has been extracted. None in case of an error.

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def extract_url_from_message_body(
    self,
    message_body: str,
    search_pattern: str,
    multi_line: bool = False,
    multi_line_end_marker: str = "%3D",
    line_end_marker: str = "=",
    replacements: list | None = None,
) -> str | None:
    """Parse the email body to extract (a potentially multi-line) URL from the body.

    Args:
        message_body (str):
            Text of the Email body.
        search_pattern (str):
            Pattern that needs to be in first line of the URL. This
            makes sure it is the right URL we are looking for.
        multi_line (bool, optional):
            Is the URL spread over multiple lines?. Defaults to False.
        multi_line_end_marker (str, optional):
            If it is a multi-line URL, what marks the end
            of the URL in the last line? Defaults to "%3D".
        line_end_marker (str, optional):
            What marks the end of lines 1-(n-1)? Defaults to "=".
        replacements (list, optional):
            A list of replacements.

    Returns:
        str | None:
            The URL text that has been extracted. None in case of an error.

    """

    if not message_body:
        return None

    # Split all the lines after a CRLF:
    lines = [line.strip() for line in message_body.split("\r\n")]

    # Filter out the complete URL from the extracted URLs
    found = False

    url = ""

    for line in lines:
        if found:
            # Remove line end marker - many times a "="
            if line.endswith(line_end_marker):
                line = line[:-1]
            for replacement in replacements:
                line = line.replace(replacement["from"], replacement["to"])
            # We consider an empty line after we found the URL to indicate the end of the URL:
            if line == "":
                break
            url += line
        if multi_line and line.endswith(multi_line_end_marker):
            break
        if search_pattern not in line:
            continue
        # Fine https:// in the current line:
        index = line.find("https://")
        if index == -1:
            continue
        # If there's any text in front of https in that line cut it:
        line = line[index:]
        # Remove line end marker - many times a "="
        if line.endswith(line_end_marker):
            line = line[:-1]
        for replacement in replacements:
            line = line.replace(replacement["from"], replacement["to"])
        found = True
        url += line
        if not multi_line:
            break

    return url

extract_version_from_app_manifest(app_path)

Extract the version number from the MS Teams app manifest file.

This can be used to check if the app package includes a newer app version then the already installed one.

Parameters:

Name Type Description Default
app_path str

The file path (with directory) to the app package to extract the version from.

required

Returns:

Type Description
str | None

str | None: The version number or None in case of an error.

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def extract_version_from_app_manifest(self, app_path: str) -> str | None:
    """Extract the version number from the MS Teams app manifest file.

    This can be used to check if the app package includes a newer
    app version then the already installed one.

    Args:
        app_path (str):
            The file path (with directory) to the app package to extract
            the version from.

    Returns:
        str | None:
            The version number or None in case of an error.

    """

    with zipfile.ZipFile(app_path, "r") as zip_ref:
        manifest_data = zip_ref.read("manifest.json")
        manifest_json = json.loads(manifest_data)
        version = manifest_json.get("version")

        return version

follow_sharepoint_site(site_id, username=None, user_id=None)

Let a user follow a particular SharePoint site.

Parameters:

Name Type Description Default
site_id str

The ID of the SharePoint site.

required
username str

The login name of the user. Only relevant if the user ID is not provided.

None
user_id str

The user ID. If it is not provied it will be derived from the username.

None

Returns:

Name Type Description
dict dict | None

The Graph API response or None in case an error occured..

Example: { '@odata.context': 'https://graph.microsoft.com/v1.0/$metadata#sites', 'value': [ { 'id': 'ideateqa.sharepoint.com,c605327f-8531-47da-8c85-9bb63845dda6,34b48533-af41-4743-8b41-185a21f0b80f', 'webUrl': 'https://ideateqa.sharepoint.com/sites/Procurement', 'displayName': 'Procurement', 'sharepointIds': { 'siteId': 'c605327f-8531-47da-8c85-9bb63845dda6', 'siteUrl': 'https://ideateqa.sharepoint.com/sites/Procurement', 'webId': '34b48533-af41-4743-8b41-185a21f0b80f' }, 'siteCollection': { 'hostname': 'ideateqa.sharepoint.com' } } ] }

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def follow_sharepoint_site(
    self,
    site_id: str,
    username: str | None = None,
    user_id: str | None = None,
) -> dict | None:
    """Let a user follow a particular SharePoint site.

    Args:
        site_id (str):
            The ID of the SharePoint site.
        username (str):
            The login name of the user. Only relevant if the user ID
            is not provided.
        user_id (str):
            The user ID. If it is not provied it will be derived from
            the username.

    Returns:
        dict:
            The Graph API response or None in case an error occured..

    Example:
    {
        '@odata.context': 'https://graph.microsoft.com/v1.0/$metadata#sites',
        'value': [
            {
                'id': 'ideateqa.sharepoint.com,c605327f-8531-47da-8c85-9bb63845dda6,34b48533-af41-4743-8b41-185a21f0b80f',
                'webUrl': 'https://ideateqa.sharepoint.com/sites/Procurement',
                'displayName': 'Procurement',
                'sharepointIds': {
                    'siteId': 'c605327f-8531-47da-8c85-9bb63845dda6',
                    'siteUrl': 'https://ideateqa.sharepoint.com/sites/Procurement',
                    'webId': '34b48533-af41-4743-8b41-185a21f0b80f'
                },
                'siteCollection': {
                    'hostname': 'ideateqa.sharepoint.com'
                }
            }
        ]
    }

    """

    if not user_id and not username:
        self.logger.error("No user given to follow SharePoint site. Provide the user ID or its email address!")
        return None

    user = self.get_user(user_email=username, user_id=user_id)
    if not user_id:
        user_id = self.get_result_value(user, "id")
    if not username:
        username = self.get_result_value(user, "userPrincipalName")

    request_url = self.config()["usersUrl"] + "/" + str(user_id) + "/followedSites/add"
    request_header = self.request_header()

    # Construct the payload to update the specific property
    payload = {
        "value": [{"id": site_id}],
    }

    response = self.do_request(
        url=request_url,
        method="POST",
        headers=request_header,
        json_data=payload,
        timeout=REQUEST_TIMEOUT,
        warning_message="Failed to follow SharePoint site -> '{}' as user -> '{}'".format(
            site_id,
            username if username else user_id,
        ),
        show_error=False,
        show_warning=True,
    )

    return response

get_app_registration(app_registration_name)

Find an Azure App Registration based on its name.

Parameters:

Name Type Description Default
app_registration_name str

Name of the App Registration.

required

Returns:

Type Description
dict | None

dict | None: App Registration data or None of the request fails.

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def get_app_registration(
    self,
    app_registration_name: str,
) -> dict | None:
    """Find an Azure App Registration based on its name.

    Args:
        app_registration_name (str):
            Name of the App Registration.

    Returns:
        dict | None:
            App Registration data or None of the request fails.

    """

    request_url = self.config()["applicationsUrl"] + "?$filter=displayName eq '{}'".format(app_registration_name)
    request_header = self.request_header()

    self.logger.debug(
        "Get Azure App Registration -> '%s'; calling -> %s",
        app_registration_name,
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=REQUEST_TIMEOUT,
        failure_message="Cannot find Azure App Registration -> '{}'".format(
            app_registration_name,
        ),
    )

get_group(group_name, show_error=False)

Get a M365 Group based on its name.

Parameters:

Name Type Description Default
group_name str

The M365 Group name.

required
show_error bool

Should an error be logged if group is not found.

False

Returns:

Name Type Description
dict dict | None

Group information or None if the group doesn't exist.

Example

{ '@odata.context': 'https://graph.microsoft.com/v1.0/$metadata#groups', 'value': [ { 'id': 'b65f7dba-3ed1-49df-91bf-2bf99affcc8d', 'deletedDateTime': None, 'classification': None, 'createdDateTime': '2023-04-01T13:46:26Z', 'creationOptions': [], 'description': 'Engineering & Construction', 'displayName': 'Engineering & Construction', 'expirationDateTime': None, 'groupTypes': ['Unified'], 'isAssignableToRole': None, 'mail': 'Engineering&Construction@M365x61936377.onmicrosoft.com', 'mailEnabled': True, 'mailNickname': 'Engineering&Construction', 'membershipRule': None, 'membershipRuleProcessingState': None, 'onPremisesDomainName': None, 'onPremisesLastSyncDateTime': None, 'onPremisesNetBiosName': None, 'onPremisesSamAccountName': None, 'onPremisesSecurityIdentifier': None, 'onPremisesSyncEnabled': None, 'preferredDataLocation': None, 'preferredLanguage': None, 'proxyAddresses': ['SPO:SPO_d9deb3e7-c72f-4e8d-80fb-5d9411ca1458@SPO_604f34f0-ba72-4321-ab6b-e36ae8bd00ec', ...], 'renewedDateTime': '2023-04-01T13:46:26Z', 'resourceBehaviorOptions': [], 'resourceProvisioningOptions': [], 'securityEnabled': False, 'securityIdentifier': 'S-1-12-1-3059711418-1239367377-4180393873-2379022234', 'theme': None, 'visibility': 'Public', 'onPremisesProvisioningErrors': [] }, { 'id': '61359860-302e-4016-b5cc-abff2293dff1', ... } ] }

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def get_group(self, group_name: str, show_error: bool = False) -> dict | None:
    """Get a M365 Group based on its name.

    Args:
        group_name (str):
            The M365 Group name.
        show_error (bool):
            Should an error be logged if group is not found.

    Returns:
        dict:
            Group information or None if the group doesn't exist.

    Example:
        {
            '@odata.context': 'https://graph.microsoft.com/v1.0/$metadata#groups',
            'value': [
                {
                    'id': 'b65f7dba-3ed1-49df-91bf-2bf99affcc8d',
                    'deletedDateTime': None,
                    'classification': None,
                    'createdDateTime': '2023-04-01T13:46:26Z',
                    'creationOptions': [],
                    'description': 'Engineering & Construction',
                    'displayName': 'Engineering & Construction',
                    'expirationDateTime': None,
                    'groupTypes': ['Unified'],
                    'isAssignableToRole': None,
                    'mail': 'Engineering&Construction@M365x61936377.onmicrosoft.com',
                    'mailEnabled': True,
                    'mailNickname': 'Engineering&Construction',
                    'membershipRule': None,
                    'membershipRuleProcessingState': None,
                    'onPremisesDomainName': None,
                    'onPremisesLastSyncDateTime': None,
                    'onPremisesNetBiosName': None,
                    'onPremisesSamAccountName': None,
                    'onPremisesSecurityIdentifier': None,
                    'onPremisesSyncEnabled': None,
                    'preferredDataLocation': None,
                    'preferredLanguage': None,
                    'proxyAddresses': ['SPO:SPO_d9deb3e7-c72f-4e8d-80fb-5d9411ca1458@SPO_604f34f0-ba72-4321-ab6b-e36ae8bd00ec', ...],
                    'renewedDateTime': '2023-04-01T13:46:26Z',
                    'resourceBehaviorOptions': [],
                    'resourceProvisioningOptions': [],
                    'securityEnabled': False,
                    'securityIdentifier': 'S-1-12-1-3059711418-1239367377-4180393873-2379022234',
                    'theme': None,
                    'visibility': 'Public',
                    'onPremisesProvisioningErrors': []
                },
                {
                    'id': '61359860-302e-4016-b5cc-abff2293dff1',
                    ...
                }
            ]
        }

    """

    query = {"$filter": "displayName eq '" + group_name + "'"}
    encoded_query = urllib.parse.urlencode(query, doseq=True)

    request_url = self.config()["groupsUrl"] + "?" + encoded_query
    request_header = self.request_header()

    self.logger.debug(
        "Get M365 group -> '%s'; calling -> %s",
        group_name,
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=REQUEST_TIMEOUT,
        failure_message="Failed to get M365 group -> '{}'".format(group_name),
        show_error=show_error,
    )

get_group_members(group_name)

Get members (users and groups) of the specified group.

Parameters:

Name Type Description Default
group_name str

The name of the group.

required

Returns:

Type Description
dict | None

dict | None: Response of Graph REST API or None if the REST call fails.

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def get_group_members(self, group_name: str) -> dict | None:
    """Get members (users and groups) of the specified group.

    Args:
        group_name (str):
            The name of the group.

    Returns:
        dict | None:
            Response of Graph REST API or None if the REST call fails.

    """

    response = self.get_group(group_name=group_name)
    group_id = self.get_result_value(response=response, key="id", index=0)
    if not group_id:
        self.logger.error(
            "M365 Group -> '%s' does not exist! Cannot retrieve group members.",
            group_name,
        )
        return None

    query = {"$select": "id,displayName,mail,userPrincipalName"}
    encoded_query = urllib.parse.urlencode(query, doseq=True)

    request_url = self.config()["groupsUrl"] + "/" + group_id + "/members?" + encoded_query
    request_header = self.request_header()

    self.logger.debug(
        "Get members of M365 group -> %s (%s); calling -> %s",
        group_name,
        group_id,
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=REQUEST_TIMEOUT,
        failure_message="Failed to get members of M365 group -> '{}' ({})".format(
            group_name,
            group_id,
        ),
    )

get_group_owners(group_name)

Get owners (users) of the specified group.

Parameters:

Name Type Description Default
group_name str

The name of the group.

required

Returns:

Type Description
dict | None

dict | None: Response of Graph REST API or None if the REST call fails.

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def get_group_owners(self, group_name: str) -> dict | None:
    """Get owners (users) of the specified group.

    Args:
        group_name (str):
            The name of the group.

    Returns:
        dict | None:
            Response of Graph REST API or None if the REST call fails.

    """

    response = self.get_group(group_name=group_name)
    group_id = self.get_result_value(response=response, key="id", index=0)
    if not group_id:
        self.logger.error(
            "M365 Group -> %s does not exist! Cannot retrieve group owners.",
            group_name,
        )
        return None

    query = {"$select": "id,displayName,mail,userPrincipalName"}
    encoded_query = urllib.parse.urlencode(query, doseq=True)

    request_url = self.config()["groupsUrl"] + "/" + group_id + "/owners?" + encoded_query
    request_header = self.request_header()

    self.logger.debug(
        "Get owners of M365 group -> %s (%s); calling -> %s",
        group_name,
        group_id,
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=REQUEST_TIMEOUT,
        failure_message="Failed to get owners of M365 group -> '{}' ({})".format(
            group_name,
            group_id,
        ),
    )

get_groups(max_number=250, next_page_url=None)

Get list all all groups in M365 tenant.

Parameters:

Name Type Description Default
max_number int

The maximum result values (limit).

250
next_page_url str

The MS Graph URL to retrieve the next page of M365 groups (pagination). This is used for the iterator get_groups_iterator() below.

None

Returns:

Name Type Description
dict dict | None

A dictionary of all groups or None in case of an error.

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def get_groups(
    self,
    max_number: int = 250,
    next_page_url: str | None = None,
) -> dict | None:
    """Get list all all groups in M365 tenant.

    Args:
        max_number (int, optional):
            The maximum result values (limit).
        next_page_url (str, optional):
            The MS Graph URL to retrieve the next page of M365 groups (pagination).
            This is used for the iterator get_groups_iterator() below.

    Returns:
        dict:
            A dictionary of all groups or None in case of an error.

    """

    request_url = next_page_url if next_page_url else self.config()["groupsUrl"]
    request_header = self.request_header()

    self.logger.debug(
        "Get list of all M365 groups%s; calling -> %s",
        " (paged)" if next_page_url else "",
        request_url,
    )

    response = self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        params={"$top": str(max_number)} if not next_page_url else None,
        timeout=REQUEST_TIMEOUT,
        failure_message="Failed to get list of M365 groups",
    )

    return response

get_groups_iterator()

Get an iterator object that can be used to traverse all M365 groups.

Returning a generator avoids loading a large number of nodes into memory at once. Instead you can iterate over the potential large list of groups.

Example usage

groups = m365_object.get_groups_iterator() for group in groups: logger.info("Traversing M365 group -> '%s'...", group.get("displayName", ""))

Returns:

Name Type Description
iter iter

A generator yielding one M365 group per iteration. If the REST API fails, returns no value.

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def get_groups_iterator(
    self,
) -> iter:
    """Get an iterator object that can be used to traverse all M365 groups.

    Returning a generator avoids loading a large number of nodes into memory at once. Instead you
    can iterate over the potential large list of groups.

    Example usage:
        groups = m365_object.get_groups_iterator()
        for group in groups:
            logger.info("Traversing M365 group -> '%s'...", group.get("displayName", "<undefined name>"))

    Returns:
        iter:
            A generator yielding one M365 group per iteration.
            If the REST API fails, returns no value.

    """

    next_page_url = None

    while True:
        response = self.get_groups(
            next_page_url=next_page_url,
        )
        if not response or "value" not in response:
            # Don't return None! Plain return is what we need for iterators.
            # Natural Termination: If the generator does not yield, it behaves
            # like an empty iterable when used in a loop or converted to a list:
            return

        # Yield users one at a time:
        yield from response["value"]

        # See if we have an additional result page.
        # If not terminate the iterator and return
        # no value.
        next_page_url = response.get("@odata.nextLink", None)
        if not next_page_url:
            # Don't return None! Plain return is what we need for iterators.
            # Natural Termination: If the generator does not yield, it behaves
            # like an empty iterable when used in a loop or converted to a list:
            return

get_mail(user_id, sender, subject, num_emails=None, show_error=False)

Get email from inbox of a given user and a given sender (from).

This requires Mail.Read Application permissions for the Azure App being used.

Parameters:

Name Type Description Default
user_id str

The M365 ID of the user.

required
sender str

The sender email address to filter for.

required
subject str

The subject to filter for.

required
num_emails int

The number of matching emails to retrieve.

None
show_error bool

Whether or not an error should be displayed if the user is not found.

False

Returns:

Name Type Description
dict dict | None

Email or None of the request fails.

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def get_mail(
    self,
    user_id: str,
    sender: str,
    subject: str,
    num_emails: int | None = None,
    show_error: bool = False,
) -> dict | None:
    """Get email from inbox of a given user and a given sender (from).

    This requires Mail.Read Application permissions for the Azure App being used.

    Args:
        user_id (str):
            The M365 ID of the user.
        sender (str):
            The sender email address to filter for.
        subject (str):
            The subject to filter for.
        num_emails (int, optional):
            The number of matching emails to retrieve.
        show_error (bool, optional):
            Whether or not an error should be displayed if the
            user is not found.

    Returns:
        dict:
            Email or None of the request fails.

    """

    # Attention: you  can easily run in limitation of the MS Graph API. If selection + filtering
    # is too complex you can get this error: "The restriction or sort order is too complex for this operation."
    # that's why we first just do the ordering and then do the filtering on sender and subject
    # separately
    request_url = (
        self.config()["usersUrl"]
        + "/"
        + user_id
        #            + "/messages?$filter=from/emailAddress/address eq '{}' and contains(subject, '{}')&$orderby=receivedDateTime desc".format(
        + "/messages?$orderby=receivedDateTime desc"
    )
    if num_emails:
        request_url += "&$top={}".format(num_emails)

    request_header = self.request_header()

    self.logger.debug(
        "Get mails for user -> %s from -> '%s' with subject -> '%s'; calling -> %s",
        user_id,
        sender,
        subject,
        request_url,
    )

    response = self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=REQUEST_TIMEOUT,
        failure_message="Cannot retrieve emails for M365 user -> {}".format(user_id),
        show_error=show_error,
    )

    if response and "value" in response:
        messages = response["value"]

        # Filter the messages by sender and subject in code
        filtered_messages = [
            msg
            for msg in messages
            if msg.get("from", {}).get("emailAddress", {}).get("address") == sender
            and subject in msg.get("subject", "")
        ]
        response["value"] = filtered_messages
        return response

    return None

get_mail_body(user_id, email_id)

Get full email body for a given email ID.

This requires Mail.Read Application permissions for the Azure App being used.

Parameters:

Name Type Description Default
user_id str

The M365 ID of the user.

required
email_id str

The M365 ID of the email.

required

Returns:

Type Description
str | None

str | None: Email body or None of the request fails.

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def get_mail_body(self, user_id: str, email_id: str) -> str | None:
    """Get full email body for a given email ID.

    This requires Mail.Read Application permissions for the Azure App being used.

    Args:
        user_id (str):
            The M365 ID of the user.
        email_id (str):
            The M365 ID of the email.

    Returns:
        str | None:
            Email body or None of the request fails.

    """

    request_url = self.config()["usersUrl"] + "/" + user_id + "/messages/" + email_id + "/$value"

    request_header = self.request_header()

    response = self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=REQUEST_TIMEOUT,
        failure_message="Cannot get email body for M365 user -> {} and email with ID -> {}".format(
            user_id,
            email_id,
        ),
        parse_request_response=False,
    )

    if response and response.ok and response.content:
        return response.content.decode("utf-8")

    return None

get_result_value(response, key, index=0, sub_dict_name='')

Get value of a result property with a given key of an MS Graph API call.

Parameters:

Name Type Description Default
response dict | None

REST response from an MS Graph REST Call.

required
key str

The property name (key).

required
index int

Index to use (1st element has index 0). Defaults to 0.

0
sub_dict_name str

Some MS Graph API calls include nested dict structures that can be requested with an "expand" query parameter. In such a case we use the sub_dict_name to access it.

''

Returns:

Type Description
str | None

str | None: The value for the key, None otherwise.

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def get_result_value(
    self,
    response: dict | None,
    key: str,
    index: int = 0,
    sub_dict_name: str = "",
) -> str | None:
    """Get value of a result property with a given key of an MS Graph API call.

    Args:
        response (dict | None):
            REST response from an MS Graph REST Call.
        key (str):
            The property name (key).
        index (int, optional):
            Index to use (1st element has index 0).
            Defaults to 0.
        sub_dict_name (str):
            Some MS Graph API calls include nested dict structures that can
            be requested with an "expand" query parameter. In such
            a case we use the sub_dict_name to access it.

    Returns:
        str | None:
            The value for the key, None otherwise.

    """

    if not response:
        return None
    if "value" not in response:  # If Graph APIs are called with specific IDs (and not name lookups)
        # they may not return a list of dicts calles "values" but a single dict directly
        if sub_dict_name and sub_dict_name in response:
            sub_structure = response[sub_dict_name]
            # also the substructure could be a list
            if isinstance(sub_structure, list):
                sub_structure = sub_structure[index]
            return sub_structure[key]
        elif key in response:
            return response[key]
        else:
            return None

    values = response["value"]
    if not values or not isinstance(values, list) or len(values) - 1 < index:
        return None

    if not sub_dict_name:
        return values[index][key]
    else:
        sub_structure = values[index][sub_dict_name]
        if isinstance(sub_structure, list):
            # here we assume it is the first element of the
            # substructure. If really required for specific
            # use cases we may introduce a second index in
            # the future.
            sub_structure = sub_structure[0]
        return sub_structure[key]

get_sharepoint_page(site_id, page_id)

Retrieve a page of a SharePoint site accessible to the authenticated user.

Parameters:

Name Type Description Default
site_id str

The ID of the SharePoint site the page should be get for.

required
page_id str

The ID of the page to be retrieved.

required

Returns:

Type Description
dict | None

dict | None: A SharePoint site page.

Example: { '@odata.context': "https://graph.microsoft.com/beta/$metadata#sites('ideatedev.sharepoint.com%2C9b203cbe-27ca-45b2-944a-663cc99e5e8f%2Ca1462b54-26f9-4a24-9660-2bc7859ce9af')/pages/$entity", '@odata.type': '#microsoft.graph.sitePage', '@odata.etag': '"{A546CE61-21E6-431D-B2CD-67D1F722BE5F},4"', 'createdDateTime': '2025-01-26T00:03:24Z', 'eTag': '"{A546CE61-21E6-431D-B2CD-67D1F722BE5F},4"', 'id': 'a546ce61-21e6-431d-b2cd-67d1f722be5f', 'lastModifiedDateTime': '2025-01-26T00:03:24Z', 'name': 'Home.aspx', 'webUrl': 'https://ideatedev.sharepoint.com/sites/TG11-Trad.Good11PDReg.Trading795/SitePages/Home.aspx', 'title': 'Home', 'pageLayout': 'home', 'promotionKind': 'page', 'showComments': False, 'showRecommendedPages': False, 'contentType': { 'id': '0x0101009D1CB255DA76424F860D91F20E6C4118003CD261A156017A45BA0F28B5923AE8F6', 'name': 'Site Page' }, 'createdBy': { 'user': {...} }, 'lastModifiedBy': { 'user': {...} }, 'parentReference': { 'siteId': '9b203cbe-27ca-45b2-944a-663cc99e5e8f' }, 'publishingState': { 'level': 'published', 'versionId': '1.0' }, 'reactions': {} }

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def get_sharepoint_page(self, site_id: str, page_id: str) -> dict | None:
    """Retrieve a page of a SharePoint site accessible to the authenticated user.

    Args:
        site_id (str):
            The ID of the SharePoint site the page should be get for.
        page_id (str):
            The ID of the page to be retrieved.

    Returns:
        dict | None:
            A SharePoint site page.

    Example:
    {
        '@odata.context': "https://graph.microsoft.com/beta/$metadata#sites('ideatedev.sharepoint.com%2C9b203cbe-27ca-45b2-944a-663cc99e5e8f%2Ca1462b54-26f9-4a24-9660-2bc7859ce9af')/pages/$entity",
        '@odata.type': '#microsoft.graph.sitePage',
        '@odata.etag': '"{A546CE61-21E6-431D-B2CD-67D1F722BE5F},4"',
        'createdDateTime': '2025-01-26T00:03:24Z',
        'eTag': '"{A546CE61-21E6-431D-B2CD-67D1F722BE5F},4"',
        'id': 'a546ce61-21e6-431d-b2cd-67d1f722be5f',
        'lastModifiedDateTime': '2025-01-26T00:03:24Z',
        'name': 'Home.aspx',
        'webUrl': 'https://ideatedev.sharepoint.com/sites/TG11-Trad.Good11PDReg.Trading795/SitePages/Home.aspx',
        'title': 'Home',
        'pageLayout': 'home',
        'promotionKind': 'page',
        'showComments': False,
        'showRecommendedPages': False,
        'contentType': {
            'id': '0x0101009D1CB255DA76424F860D91F20E6C4118003CD261A156017A45BA0F28B5923AE8F6',
            'name': 'Site Page'
        },
        'createdBy': {
            'user': {...}
        },
        'lastModifiedBy': {
            'user': {...}
        },
        'parentReference': {
            'siteId': '9b203cbe-27ca-45b2-944a-663cc99e5e8f'
        },
        'publishingState': {
            'level': 'published',
            'versionId': '1.0'
        },
        'reactions': {}
    }

    """

    request_url = self.config()["sitesUrl"] + "/" + site_id + "/pages/" + page_id

    request_header = self.request_header()

    response = self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=REQUEST_TIMEOUT,
        failure_message="Cannot get SharePoint page -> '{}' for site -> '{}'".format(page_id, site_id),
    )

    return response

get_sharepoint_pages(site_id)

Retrieve a list of SharePoint site pages accessible to the authenticated user.

Parameters:

Name Type Description Default
site_id str

The ID of the SharePoint site the pages should be retrieved for.

required

Returns:

Name Type Description
dict dict

A dictionary including the list of SharePoint pages for a given page. The actual list is included inside the "value" key of the dictionary.

Example: { '@odata.context': "https://graph.microsoft.com/beta/$metadata#sites('ideatedev.sharepoint.com%2C61c0f9cb-39d3-4c04-b60c-31576954a2ab%2Ca678aeab-68ac-46a1-bd95-28020c12de26')/pages", 'value': [ { '@odata.type': '#microsoft.graph.sitePage', '@odata.etag': '"{A546CE61-21E6-431D-B2CD-67D1F722BE5F},4"', 'createdDateTime': '2025-01-26T00:03:24Z', 'eTag': '"{A546CE61-21E6-431D-B2CD-67D1F722BE5F},4"', 'id': 'a546ce61-21e6-431d-b2cd-67d1f722be5f', 'lastModifiedDateTime': '2025-01-26T00:03:24Z', 'name': 'Home.aspx', 'webUrl': 'https://ideatedev.sharepoint.com/sites/TG11-Trad.Good11PDReg.Trading795/SitePages/Home.aspx', 'title': 'Home', 'pageLayout': 'home', 'promotionKind': 'page', 'showComments': False, 'showRecommendedPages': False, 'contentType': { 'id': '0x0101009D1CB255DA76424F860D91F20E6C411800813863BBF9FE6A408AE59965D98FE3DA', 'name': 'Site Page' }, 'createdBy': {'user': {'displayName': 'System Account'}}, 'lastModifiedBy': {'user': {'displayName': 'Terrarium Admin', 'email': 'admin@dev.idea-te.eimdemo.com'}}, 'parentReference': {'siteId': '61c0f9cb-39d3-4c04-b60c-31576954a2ab'}, 'publishingState': {'level': 'published', 'versionId': '4.0'}, 'reactions': {} }, ... ] }

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def get_sharepoint_pages(self, site_id: str) -> dict:
    """Retrieve a list of SharePoint site pages accessible to the authenticated user.

    Args:
        site_id (str):
            The ID of the SharePoint site the pages should be retrieved for.

    Returns:
        dict:
            A dictionary including the list of SharePoint pages for a given page.
            The actual list is included inside the "value" key of the dictionary.

    Example:
    {
        '@odata.context': "https://graph.microsoft.com/beta/$metadata#sites('ideatedev.sharepoint.com%2C61c0f9cb-39d3-4c04-b60c-31576954a2ab%2Ca678aeab-68ac-46a1-bd95-28020c12de26')/pages",
        'value': [
            {
                '@odata.type': '#microsoft.graph.sitePage',
                '@odata.etag': '"{A546CE61-21E6-431D-B2CD-67D1F722BE5F},4"',
                'createdDateTime': '2025-01-26T00:03:24Z',
                'eTag': '"{A546CE61-21E6-431D-B2CD-67D1F722BE5F},4"',
                'id': 'a546ce61-21e6-431d-b2cd-67d1f722be5f',
                'lastModifiedDateTime': '2025-01-26T00:03:24Z',
                'name': 'Home.aspx',
                'webUrl': 'https://ideatedev.sharepoint.com/sites/TG11-Trad.Good11PDReg.Trading795/SitePages/Home.aspx',
                'title': 'Home',
                'pageLayout': 'home',
                'promotionKind': 'page',
                'showComments': False,
                'showRecommendedPages': False,
                'contentType': {
                    'id': '0x0101009D1CB255DA76424F860D91F20E6C411800813863BBF9FE6A408AE59965D98FE3DA',
                    'name': 'Site Page'
                },
                'createdBy': {'user': {'displayName': 'System Account'}},
                'lastModifiedBy': {'user': {'displayName': 'Terrarium Admin', 'email': 'admin@dev.idea-te.eimdemo.com'}},
                'parentReference': {'siteId': '61c0f9cb-39d3-4c04-b60c-31576954a2ab'},
                'publishingState': {'level': 'published', 'versionId': '4.0'},
                'reactions': {}
            },
            ...
        ]
    }

    """

    request_url = self.config()["sitesUrl"] + "/" + str(site_id) + "/pages"

    request_header = self.request_header()

    response = self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=REQUEST_TIMEOUT,
        failure_message="Cannot get pages of SharePoint site with ID -> '{}'".format(site_id),
    )

    return response

get_sharepoint_root_sites()

Get all SharePoint root sites.

Returns:

Type Description
dict | None

dict | None: Dictionary that includes a list of root sites in the "value" key.

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def get_sharepoint_root_sites(self) -> dict | None:
    """Get all SharePoint root sites.

    Returns:
        dict | None:
            Dictionary that includes a list of root sites in the "value" key.

    """

    response = self.get_sharepoint_sites(
        select="siteCollection,webUrl",
        filter_expression="siteCollection/root ne null",
    )

    return response

get_sharepoint_section(site_id, page_id, section_type='horizontalSections', section_id=1, show_error=True)

Retrieve a section of a SharePoint site page.

Parameters:

Name Type Description Default
site_id str

The ID of the SharePoint site.

required
page_id str

The ID of the SharePoint page containing the section.

required
section_type str

"horizontalSections" (note the plural!) "verticalSection" (note the singular!)

'horizontalSections'
section_id int | str

The ID of the section. Only relevant for horizontal sections. Simple values like 1,2,3...

1
show_error bool

Whether or not an error should be displayed if the section is not found.

True

Returns:

Name Type Description
dict dict

A SharePoint site page section.

Example: { '@odata.context': "https://graph.microsoft.com/beta/$metadata#sites('ideatedev.sharepoint.com%2C61c0f9cb-39d3-4c04-b60c-31576954a2ab%2Ca678aeab-68ac-46a1-bd95-28020c12de26')/pages('ac7675ee-8891-43b9-b1b2-2d2ced8eb17e')/microsoft.graph.sitePage/canvasLayout/horizontalSections/$entity", 'layout': 'fullWidth', 'id': '1', 'emphasis': 'none' }

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def get_sharepoint_section(
    self,
    site_id: str,
    page_id: str,
    section_type: str = "horizontalSections",
    section_id: int | str = 1,
    show_error: bool = True,
) -> dict:
    """Retrieve a section of a SharePoint site page.

    Args:
        site_id (str):
            The ID of the SharePoint site.
        page_id (str):
            The ID of the SharePoint page containing the section.
        section_type (str, optional):
            "horizontalSections" (note the plural!)
            "verticalSection" (note the singular!)
        section_id (int | str):
            The ID of the section. Only relevant for horizontal sections.
            Simple values like 1,2,3...
        show_error (bool, optional):
            Whether or not an error should be displayed if the
            section is not found.

    Returns:
        dict:
            A SharePoint site page section.

    Example:
    {
        '@odata.context': "https://graph.microsoft.com/beta/$metadata#sites('ideatedev.sharepoint.com%2C61c0f9cb-39d3-4c04-b60c-31576954a2ab%2Ca678aeab-68ac-46a1-bd95-28020c12de26')/pages('ac7675ee-8891-43b9-b1b2-2d2ced8eb17e')/microsoft.graph.sitePage/canvasLayout/horizontalSections/$entity",
        'layout': 'fullWidth',
        'id': '1',
        'emphasis': 'none'
    }

    """

    response = self.get_sharepoint_sections(
        site_id=site_id,
        page_id=page_id,
        section_type=section_type,
        section_id=section_id,
        show_error=show_error,
    )

    return response

get_sharepoint_sections(site_id, page_id, section_type='horizontalSections', section_id=None, show_error=True)

Retrieve all sections SharePoint site page.

Parameters:

Name Type Description Default
site_id str

The ID of the SharePoint site.

required
page_id str

The ID of the SharePoint page containing the sections.

required
section_type str

"horizontalSections" (note the plural!) "verticalSection" (note the singular!)

'horizontalSections'
section_id str | int | None

The ID of the section. Only relevant for horizontal sections. Simple values like 1,2,3... Should be None for vertical section.

None
show_error bool

Whether or not an error should be displayed if the section is not found.

True

Returns:

Name Type Description
dict dict

A dictionary including the list of SharePoint sections for a given page. The actual list is included inside the "value" key of the dictionary.

Example: { '@odata.context': "https://graph.microsoft.com/beta/$metadata#sites('ideatedev.sharepoint.com%2C61c0f9cb-39d3-4c04-b60c-31576954a2ab%2Ca678aeab-68ac-46a1-bd95-28020c12de26')/pages('ac7675ee-8891-43b9-b1b2-2d2ced8eb17e')/microsoft.graph.sitePage/canvasLayout/horizontalSections", 'value': [ { 'layout': 'fullWidth', 'id': '1', 'emphasis': 'none' }, { 'layout': 'twoColumns', 'id': '2', 'emphasis': 'none' } ] }

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def get_sharepoint_sections(
    self,
    site_id: str,
    page_id: str,
    section_type: str = "horizontalSections",
    section_id: str | int | None = None,
    show_error: bool = True,
) -> dict:
    """Retrieve all sections SharePoint site page.

    Args:
        site_id (str):
            The ID of the SharePoint site.
        page_id (str):
            The ID of the SharePoint page containing the sections.
        section_type (str, optional):
            "horizontalSections" (note the plural!)
            "verticalSection" (note the singular!)
        section_id (str | int | None):
            The ID of the section. Only relevant for horizontal sections.
            Simple values like 1,2,3...
            Should be None for vertical section.
        show_error (bool, optional):
            Whether or not an error should be displayed if the
            section is not found.

    Returns:
        dict:
            A dictionary including the list of SharePoint sections for a given page.
            The actual list is included inside the "value" key of the dictionary.

    Example:
    {
        '@odata.context': "https://graph.microsoft.com/beta/$metadata#sites('ideatedev.sharepoint.com%2C61c0f9cb-39d3-4c04-b60c-31576954a2ab%2Ca678aeab-68ac-46a1-bd95-28020c12de26')/pages('ac7675ee-8891-43b9-b1b2-2d2ced8eb17e')/microsoft.graph.sitePage/canvasLayout/horizontalSections",
        'value': [
            {
                'layout': 'fullWidth',
                'id': '1',
                'emphasis': 'none'
            },
            {
                'layout': 'twoColumns',
                'id': '2',
                'emphasis': 'none'
            }
        ]
    }

    """

    request_url = (
        self.config()["sitesUrl"]
        + "/"
        + site_id
        + "/pages/"
        + page_id
        + "/microsoft.graph.sitePage/canvasLayout/"
        + section_type
    )

    if section_id is not None:
        request_url += "/" + str(section_id)

    request_header = self.request_header()

    response = self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=REQUEST_TIMEOUT,
        warning_message="Cannot find section{} for SharePoint page -> '{}' of SharePoint site -> '{}'".format(
            "s" if not section_id else " -> {}".format(section_id),
            page_id,
            site_id,
        ),
        failure_message="Cannot get section{} for SharePoint page -> '{}' of SharePoint site -> '{}'".format(
            "s" if not section_id else " -> {}".format(section_id),
            page_id,
            site_id,
        ),
        show_error=show_error,
    )

    return response

get_sharepoint_site(site_id)

Retrieve a SharePoint site by its ID.

Parameters:

Name Type Description Default
site_id str

The ID of the SharePoint site the to retrieve.

required

Returns:

Type Description
dict | None

dict | None: The data of the SharePoint site.

Example: { '@odata.context': 'https://graph.microsoft.com/beta/$metadata#sites/$entity', 'createdDateTime': '2025-02-06T07:41:53.41Z', 'description': '', 'id': 'ideatedev.sharepoint.com,9b203cbe-27ca-45b2-944a-663cc99e5e8f,a1462b54-26f9-4a24-9660-2bc7859ce9af', 'lastModifiedDateTime': '2025-02-10T20:37:11Z', 'name': 'TG11-Trad.Good11PDReg.Trading795', 'webUrl': 'https://ideatedev.sharepoint.com/sites/TG11-Trad.Good11PDReg.Trading795', 'displayName': 'TG11 - Trad.Good 11,PD,Reg.Trading', 'root': {}, 'siteCollection': { 'hostname': 'ideatedev.sharepoint.com' } }

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def get_sharepoint_site(self, site_id: str) -> dict | None:
    """Retrieve a SharePoint site by its ID.

    Args:
        site_id (str):
            The ID of the SharePoint site the to retrieve.

    Returns:
        dict | None:
            The data of the SharePoint site.

    Example:
    {
        '@odata.context': 'https://graph.microsoft.com/beta/$metadata#sites/$entity',
        'createdDateTime': '2025-02-06T07:41:53.41Z',
        'description': '',
        'id': 'ideatedev.sharepoint.com,9b203cbe-27ca-45b2-944a-663cc99e5e8f,a1462b54-26f9-4a24-9660-2bc7859ce9af',
        'lastModifiedDateTime': '2025-02-10T20:37:11Z',
        'name': 'TG11-Trad.Good11PDReg.Trading795',
        'webUrl': 'https://ideatedev.sharepoint.com/sites/TG11-Trad.Good11PDReg.Trading795',
        'displayName': 'TG11 - Trad.Good 11,PD,Reg.Trading',
        'root': {},
        'siteCollection': {
            'hostname': 'ideatedev.sharepoint.com'
        }
    }

    """

    request_url = self.config()["sitesUrl"] + "/" + site_id

    request_header = self.request_header()

    response = self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=REQUEST_TIMEOUT,
        failure_message="Cannot get SharePoint site with ID -> '{}'".format(site_id),
    )

    return response

get_sharepoint_site_by_name(site_name)

Retrieve a SharePoint site by its name.

Parameters:

Name Type Description Default
site_name str

The name of the SharePoint site to retrieve.

required

Returns:

Type Description
dict | None

dict | None: The data of the SharePoint site.

Example: { '@odata.context': 'https://graph.microsoft.com/beta/$metadata#sites/$entity', 'createdDateTime': '2025-02-06T07:41:53.41Z', 'description': '', 'id': 'ideatedev.sharepoint.com,9b203cbe-27ca-45b2-944a-663cc99e5e8f,a1462b54-26f9-4a24-9660-2bc7859ce9af', 'lastModifiedDateTime': '2025-02-10T20:37:11Z', 'name': 'TG11-Trad.Good11PDReg.Trading795', 'webUrl': 'https://ideatedev.sharepoint.com/sites/TG11-Trad.Good11PDReg.Trading795', 'displayName': 'TG11 - Trad.Good 11,PD,Reg.Trading', 'root': {}, 'siteCollection': { 'hostname': 'ideatedev.sharepoint.com' } }

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def get_sharepoint_site_by_name(self, site_name: str) -> dict | None:
    """Retrieve a SharePoint site by its name.

    Args:
        site_name (str):
            The name of the SharePoint site to retrieve.

    Returns:
        dict | None:
            The data of the SharePoint site.

    Example:
    {
        '@odata.context': 'https://graph.microsoft.com/beta/$metadata#sites/$entity',
        'createdDateTime': '2025-02-06T07:41:53.41Z',
        'description': '',
        'id': 'ideatedev.sharepoint.com,9b203cbe-27ca-45b2-944a-663cc99e5e8f,a1462b54-26f9-4a24-9660-2bc7859ce9af',
        'lastModifiedDateTime': '2025-02-10T20:37:11Z',
        'name': 'TG11-Trad.Good11PDReg.Trading795',
        'webUrl': 'https://ideatedev.sharepoint.com/sites/TG11-Trad.Good11PDReg.Trading795',
        'displayName': 'TG11 - Trad.Good 11,PD,Reg.Trading',
        'root': {},
        'siteCollection': {
            'hostname': 'ideatedev.sharepoint.com'
        }
    }

    """

    request_url = self.config()["sitesUrl"] + "?search={}".format(site_name)

    request_header = self.request_header()

    response = self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=REQUEST_TIMEOUT,
        failure_message="Cannot get SharePoint site -> '{}'".format(site_name),
    )

    # As we lookup the site by search we could have multiple results.
    # The Graph API does not do an exact match. So we check the results
    # for an exact match:
    if response:
        results = response.get("value", [])
        for result in results:
            if result["displayName"] == site_name:
                return result

    return None

get_sharepoint_site_for_group(group_id)

Retrieve a SharePoint site for a M365 group.

Parameters:

Name Type Description Default
group_id str

The ID of the M365 group the site should be retrieved for.

required

Returns:

Name Type Description
dict dict

The data of the SharePoint site.

Example: { '@odata.context': 'https://graph.microsoft.com/beta/$metadata#sites/$entity', 'createdDateTime': '2025-02-06T07:41:53.41Z', 'description': '', 'id': 'ideatedev.sharepoint.com,9b203cbe-27ca-45b2-944a-663cc99e5e8f,a1462b54-26f9-4a24-9660-2bc7859ce9af', 'lastModifiedDateTime': '2025-02-10T20:37:11Z', 'name': 'TG11-Trad.Good11PDReg.Trading795', 'webUrl': 'https://ideatedev.sharepoint.com/sites/TG11-Trad.Good11PDReg.Trading795', 'displayName': 'TG11 - Trad.Good 11,PD,Reg.Trading', 'root': {}, 'siteCollection': { 'hostname': 'ideatedev.sharepoint.com' } }

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def get_sharepoint_site_for_group(self, group_id: str) -> dict:
    """Retrieve a SharePoint site for a M365 group.

    Args:
        group_id (str):
            The ID of the M365 group the site should be retrieved for.

    Returns:
        dict:
            The data of the SharePoint site.

    Example:
    {
        '@odata.context': 'https://graph.microsoft.com/beta/$metadata#sites/$entity',
        'createdDateTime': '2025-02-06T07:41:53.41Z',
        'description': '',
        'id': 'ideatedev.sharepoint.com,9b203cbe-27ca-45b2-944a-663cc99e5e8f,a1462b54-26f9-4a24-9660-2bc7859ce9af',
        'lastModifiedDateTime': '2025-02-10T20:37:11Z',
        'name': 'TG11-Trad.Good11PDReg.Trading795',
        'webUrl': 'https://ideatedev.sharepoint.com/sites/TG11-Trad.Good11PDReg.Trading795',
        'displayName': 'TG11 - Trad.Good 11,PD,Reg.Trading',
        'root': {},
        'siteCollection': {
            'hostname': 'ideatedev.sharepoint.com'
        }
    }

    """

    request_url = self.config()["groupsUrl"] + "/" + group_id + "/sites/root"
    request_header = self.request_header()

    response = self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=REQUEST_TIMEOUT,
        failure_message="Cannot get SharePoint site for group with ID -> '{}'".format(group_id),
    )

    return response

get_sharepoint_sites(search=None, filter_expression=None, select=None, limit=50, next_page_url=None)

Retrieve a list of SharePoint sites.

Parameters:

Name Type Description Default
search str

A string to search for to filter the results. Default is None = no filtering.

None
filter_expression str | None

Filter string to filter the results. Default is None = no filtering.

None
select str | None

Fields to select. Make sure that all fields are selected that are used in filters. Otherwise you will get no results.

None
limit int

The maximum number of sites to return in one call. Default is set to 50.

50
next_page_url str | None

The MS Graph URL to retrieve the next page of SharePoint sites (pagination). This is used for the iterator get_sharepoint_sites_iterator() below.

None

Returns:

Type Description
dict | None

dict | None: A list of SharePoint sites embedded in a "value" key in the dictionary.

Example response: { '@odata.context': 'https://graph.microsoft.com/beta/$metadata#sites', '@odata.nextLink': 'https://graph.microsoft.com/beta/sites?$top=50&$skiptoken=UGFnZWQ9VFJVRSZwX1RpbWVEZWxldGVkPSZwX0lEPTE5MDM4', 'value': [ { 'createdDateTime': '2025-02-11T12:11:49Z', 'id': 'ideatedev-my.sharepoint.com,eeed2961-91ba-46c1-abc2-159f0277130f,5aa8a98d-659d-4a52-8701-6b9a728092d8', 'name': 'Diane Conner', 'webUrl': 'https://ideatedev-my.sharepoint.com/personal/dconner_dev_idea-te_eimdemo_com', 'displayName': 'Diane Conner', 'isPersonalSite': True, 'siteCollection': { 'hostname': 'ideatedev-my.sharepoint.com' }, 'root': {} }, { 'createdDateTime': '2025-02-06T07:44:44Z', 'id': 'ideatedev.sharepoint.com,570e67bc-1e69-4a62-89ea-994be9642b93,a1462b54-26f9-4a24-9660-2bc7859ce9af', 'name': 'SG325B - SEMI325B,ECM,PD,ExternalProcurement', 'webUrl': 'https://ideatedev.sharepoint.com/sites/SG325B-SEMI325BECMPDExternalProcurement698', 'displayName': 'SG325B - SEMI325B,ECM,PD,ExternalProcurement', 'isPersonalSite': False, 'siteCollection': { 'hostname': 'ideatedev.sharepoint.com' }, 'root': {} }, ... ] ]

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def get_sharepoint_sites(
    self,
    search: str | None = None,
    filter_expression: str | None = None,
    select: str | None = None,
    limit: int = 50,
    next_page_url: str | None = None,
) -> dict | None:
    """Retrieve a list of SharePoint sites.

    Args:
        search (str, optional):
            A string to search for to filter the results. Default is None = no filtering.
        filter_expression (str | None, optional):
            Filter string to filter the results. Default is None = no filtering.
        select (str | None, optional):
            Fields to select. Make sure that all fields are selected that are used in filters.
            Otherwise you will get no results.
        limit (int, optional):
            The maximum number of sites to return in one call.
            Default is set to 50.
        next_page_url (str | None, optional):
            The MS Graph URL to retrieve the next page of SharePoint sites (pagination).
            This is used for the iterator get_sharepoint_sites_iterator() below.

    Returns:
        dict | None:
            A list of SharePoint sites embedded in a "value" key in the dictionary.

    Example response:
    {
        '@odata.context': 'https://graph.microsoft.com/beta/$metadata#sites',
        '@odata.nextLink': 'https://graph.microsoft.com/beta/sites?$top=50&$skiptoken=UGFnZWQ9VFJVRSZwX1RpbWVEZWxldGVkPSZwX0lEPTE5MDM4',
        'value': [
            {
                'createdDateTime': '2025-02-11T12:11:49Z',
                'id': 'ideatedev-my.sharepoint.com,eeed2961-91ba-46c1-abc2-159f0277130f,5aa8a98d-659d-4a52-8701-6b9a728092d8',
                'name': 'Diane Conner',
                'webUrl': 'https://ideatedev-my.sharepoint.com/personal/dconner_dev_idea-te_eimdemo_com',
                'displayName': 'Diane Conner',
                'isPersonalSite': True,
                'siteCollection': {
                    'hostname': 'ideatedev-my.sharepoint.com'
                },
                'root': {}
            },
            {
                'createdDateTime': '2025-02-06T07:44:44Z',
                'id': 'ideatedev.sharepoint.com,570e67bc-1e69-4a62-89ea-994be9642b93,a1462b54-26f9-4a24-9660-2bc7859ce9af',
                'name': 'SG325B - SEMI325B,ECM,PD,ExternalProcurement',
                'webUrl': 'https://ideatedev.sharepoint.com/sites/SG325B-SEMI325BECMPDExternalProcurement698',
                'displayName': 'SG325B - SEMI325B,ECM,PD,ExternalProcurement',
                'isPersonalSite': False,
                'siteCollection': {
                    'hostname': 'ideatedev.sharepoint.com'
                },
                'root': {}
            },
            ...
        ]
    ]

    """

    if not next_page_url:
        query = {}
        if select:
            query["$select"] = select
        if filter_expression:
            query["$filter"] = filter_expression
        if search:
            query["search"] = search
        if limit:
            query["$top"] = limit

        encoded_query = "?" + urllib.parse.urlencode(query, doseq=True) if query else ""
        request_url = self.config()["sitesUrl"] + encoded_query
    else:
        request_url = next_page_url
    request_header = self.request_header()

    response = self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=REQUEST_TIMEOUT,
        failure_message="Cannot get SharePoint sites",
    )

    return response

get_sharepoint_sites_iterator(search=None, filter_expression=None, select=None, limit=50)

Get an iterator object that can be used to traverse all SharePoint sites matching the filter.

Returning a generator avoids loading a large number of nodes into memory at once. Instead you can iterate over the potential large list of SharePoint sites.

Example usage

sites = m365_object.get_sharepoint_sites_iterator(limit=10) for site in sites: logger.info("Traversing SharePoint site -> '%s'...", site.get("name", ""))

Parameters:

Name Type Description Default
search str | None

A string to search for to filter the results. Default is None = no filtering.

None
filter_expression str | None

Filter string to filter the results. Default is None = no filtering.

None
select str | None

Fields to select. Make sure that all fields are selected that are used in filters. Otherwise you will get no results.

None
limit int

The maximum number of sites to return in one call. Default is set to 50.

50

Returns:

Name Type Description
iter iter

A generator yielding one SharePoint site per iteration. If the REST API fails, returns no value.

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def get_sharepoint_sites_iterator(
    self,
    search: str | None = None,
    filter_expression: str | None = None,
    select: str | None = None,
    limit: int = 50,
) -> iter:
    """Get an iterator object that can be used to traverse all SharePoint sites matching the filter.

    Returning a generator avoids loading a large number of nodes into memory at once. Instead you
    can iterate over the potential large list of SharePoint sites.

    Example usage:
        sites = m365_object.get_sharepoint_sites_iterator(limit=10)
        for site in sites:
            logger.info("Traversing SharePoint site -> '%s'...", site.get("name", "<undefined name>"))

    Args:
        search (str | None, optional):
            A string to search for to filter the results. Default is None = no filtering.
        filter_expression (str | None, optional):
            Filter string to filter the results. Default is None = no filtering.
        select (str | None, optional):
            Fields to select. Make sure that all fields are selected that are used in filters.
            Otherwise you will get no results.
        limit (int, optional):
            The maximum number of sites to return in one call.
            Default is set to 50.

    Returns:
        iter:
            A generator yielding one SharePoint site per iteration.
            If the REST API fails, returns no value.

    """

    next_page_url = None

    while True:
        response = self.get_sharepoint_sites(
            search=search,
            filter_expression=filter_expression,
            select=select,
            limit=limit,
            next_page_url=next_page_url,
        )
        if not response or "value" not in response:
            # Don't return None! Plain return is what we need for iterators.
            # Natural Termination: If the generator does not yield, it behaves
            # like an empty iterable when used in a loop or converted to a list:
            return

        # Yield users one at a time:
        yield from response["value"]

        # See if we have an additional result page.
        # If not terminate the iterator and return
        # no value.
        next_page_url = response.get("@odata.nextLink", None)
        if not next_page_url:
            # Don't return None! Plain return is what we need for iterators.
            # Natural Termination: If the generator does not yield, it behaves
            # like an empty iterable when used in a loop or converted to a list:
            return

get_sharepoint_webpart(site_id, page_id, webpart_id)

Retrieve a page of a SharePoint site accessible to the authenticated user.

Parameters:

Name Type Description Default
site_id str

The ID of the SharePoint site.

required
page_id str

The ID of the SharePoint page containing the web part.

required
webpart_id str

The ID of the SharePoint web part to retrieve.

required

Returns:

Type Description
dict | None

dict | None: The data of the SharePoint web part.

Example: { '@odata.context': "https://graph.microsoft.com/beta/$metadata#sites('ideatedev.sharepoint.com%2C9b203cbe-27ca-45b2-944a-663cc99e5e8f%2Ca1462b54-26f9-4a24-9660-2bc7859ce9af')/pages('a546ce61-21e6-431d-b2cd-67d1f722be5f')/microsoft.graph.sitePage/webParts/$entity", '@odata.type': '#microsoft.graph.standardWebPart', 'id': '405b669e-3c09-45fe-822f-ff60ac7fffce', 'webPartType': 'c4bd7b2f-7b6e-4599-8485-16504575f590', 'data': { 'audiences': [...], 'dataVersion': '1.5', 'description': 'Prominently display up to 5 pieces of content with links, images, pictures, videos, or photos in a highly visual layout.', 'title': 'Hero', 'properties': { 'heroLayoutThreshold': 640, 'carouselLayoutMaxWidth': 639, 'layoutCategory': 1, 'layout': 5, 'content@odata.type': '#Collection(graph.Json)', 'content': [ { 'id': '20cb6611-c7cc-4ba7-91e1-65a6cb576025', 'type': 'UrlLink', 'color': 4, 'description': '', 'title': '', 'showDescription': False, 'showTitle': True, 'alternateText': '', 'imageDisplayOption': 1, 'isDefaultImage': False, 'showCallToAction': True, 'isDefaultImageLoaded': False, 'isCustomImageLoaded': False, 'showFeatureText': False, 'previewImage': { '@odata.type': '#graph.Json', 'zoomRatio': 1, 'resolvedUrl': '', 'imageUrl': '', 'widthFactor': 0.5, 'minCanvasWidth': 1 } }, {...} ] }, 'serverProcessedContent': {...} } }

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def get_sharepoint_webpart(self, site_id: str, page_id: str, webpart_id: str) -> dict | None:
    """Retrieve a page of a SharePoint site accessible to the authenticated user.

    Args:
        site_id (str):
            The ID of the SharePoint site.
        page_id (str):
            The ID of the SharePoint page containing the web part.
        webpart_id (str):
            The ID of the SharePoint web part to retrieve.

    Returns:
        dict | None:
            The data of the SharePoint web part.

    Example:
    {
        '@odata.context': "https://graph.microsoft.com/beta/$metadata#sites('ideatedev.sharepoint.com%2C9b203cbe-27ca-45b2-944a-663cc99e5e8f%2Ca1462b54-26f9-4a24-9660-2bc7859ce9af')/pages('a546ce61-21e6-431d-b2cd-67d1f722be5f')/microsoft.graph.sitePage/webParts/$entity",
        '@odata.type': '#microsoft.graph.standardWebPart',
        'id': '405b669e-3c09-45fe-822f-ff60ac7fffce',
        'webPartType': 'c4bd7b2f-7b6e-4599-8485-16504575f590',
        'data': {
            'audiences': [...],
            'dataVersion': '1.5',
            'description': 'Prominently display up to 5 pieces of content with links, images, pictures, videos, or photos in a highly visual layout.',
            'title': 'Hero',
            'properties': {
                'heroLayoutThreshold': 640,
                'carouselLayoutMaxWidth': 639,
                'layoutCategory': 1,
                'layout': 5,
                'content@odata.type': '#Collection(graph.Json)',
                'content': [
                    {
                        'id': '20cb6611-c7cc-4ba7-91e1-65a6cb576025',
                        'type': 'UrlLink',
                        'color': 4,
                        'description': '',
                        'title': '',
                        'showDescription': False,
                        'showTitle': True,
                        'alternateText': '',
                        'imageDisplayOption': 1,
                        'isDefaultImage': False,
                        'showCallToAction': True,
                        'isDefaultImageLoaded': False,
                        'isCustomImageLoaded': False,
                        'showFeatureText': False,
                        'previewImage': {
                            '@odata.type': '#graph.Json',
                            'zoomRatio': 1,
                            'resolvedUrl': '',
                            'imageUrl': '',
                            'widthFactor': 0.5,
                            'minCanvasWidth': 1
                        }
                    },
                    {...}
                ]
            },
            'serverProcessedContent': {...}
        }
    }

    """

    request_url = (
        self.config()["sitesUrl"]
        + "/"
        + site_id
        + "/pages/"
        + page_id
        + "/microsoft.graph.sitePage/webparts/"
        + webpart_id
    )

    request_header = self.request_header()

    response = self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=REQUEST_TIMEOUT,
        failure_message="Cannot get SharePoint webpart -> '{}' on SharePoint page -> '{}' in SharePoint site -> '{}'".format(
            webpart_id,
            page_id,
            site_id,
        ),
    )

    return response

get_sharepoint_webparts(site_id, page_id, section_type=None, section_id=1, column_id=1)

Retrieve the configured webparts on a SharePoint site page.

Can retrieve all webparts on the page or the ones in a defined page section (like horizontal section or vertical section).

OpenText WebPart Type IDs

Content Browser: 'cecfdba4-2e82-4538-9436-dbd1c4c01a80' Related Workspaces: 'e24d7154-4554-4db6-a44f-d306b6b3a5d4' Team members of Workspace: '635a2800-8833-410d-b1f1-f209b28ea2ad'

Parameters:

Name Type Description Default
site_id str

The ID of the SharePoint site.

required
page_id str

The ID of the SharePoint page containing the web part.

required
section_type str

"horizontalSections" (note the plural!) "verticalSection" (note the singular!) Use None if you want to retrieve all webparts on page.

None
section_id str | int | None

The ID of the section. Only relevant for horizontal sections. Simple values like 1,2,3... Not relevant for vertical section or if you want to retrieve all webparts on the page.

1
column_id int | str

For horizontalSections the column ID has to be provided. Defaults to 1.

1

Returns:

Type Description
dict | None

dict | None: A dictionary including the SharePoint webparts of a given page for a given site. The actual list is included inside the "value" key of the dictionary.

Example: { '@odata.context': "https://graph.microsoft.com/beta/$metadata#sites('ideatedev.sharepoint.com%2C61c0f9cb-39d3-4c04-b60c-31576954a2ab%2Ca678aeab-68ac-46a1-bd95-28020c12de26')/pages('561c65b4-3418-4698-a4c3-7ca7f04812bb')/microsoft.graph.sitePage/webParts", 'value': [ { '@odata.type': '#microsoft.graph.standardWebPart', 'id': '405b669e-3c09-45fe-822f-ff60ac7fffce', 'webPartType': 'c4bd7b2f-7b6e-4599-8485-16504575f590', 'data': { 'audiences': [], 'dataVersion': '1.5', 'description': 'Prominently display up to 5 pieces of content with links, images, pictures, videos, or photos in a highly visual layout.', 'title': 'Hero', 'properties': { 'heroLayoutThreshold': 640, 'carouselLayoutMaxWidth': 639, 'layoutCategory': 1, 'layout': 5, 'content@odata.type': '#Collection(graph.Json)', 'content': [ { 'id': '20cb6611-c7cc-4ba7-91e1-65a6cb576025', 'type': 'UrlLink', 'color': 4, 'description': '', 'title': '', 'showDescription': False, 'showTitle': True, 'alternateText': '', 'imageDisplayOption': 1, 'isDefaultImage': False, 'showCallToAction': True, 'isDefaultImageLoaded': False, 'isCustomImageLoaded': False, 'showFeatureText': False, 'previewImage': {...} }, { 'id': '83133733-960b-4139-a73f-17ce2ca5f71c', 'type': 'Image', 'color': 4, 'description': '', 'title': '', 'showDescription': False, 'showTitle': True, 'alternateText': '', 'imageDisplayOption': 0, 'isDefaultImage': False, 'showCallToAction': False, 'isDefaultImageLoaded': False, 'isCustomImageLoaded': False, 'showFeatureText': False }, ... ] }, 'serverProcessedContent': { 'htmlStrings': [...], 'searchablePlainTexts': [...], 'links': [...], 'imageSources': [...], 'componentDependencies': [...], 'customMetadata': [...] } } }, { '@odata.type': '#microsoft.graph.standardWebPart', 'id': 'f7bfdec9-09c5-4fb6-bc97-3ba225d35ad4', 'webPartType': '8c88f208-6c77-4bdb-86a0-0c47b4316588', 'data': {...} }, { '@odata.type': '#microsoft.graph.standardWebPart', 'id': 'f2a8650b-5ea0-4ac2-9cde-56e0fd0279b0', 'webPartType': 'eb95c819-ab8f-4689-bd03-0c2d65d47b1f', 'data': {...} }, { '@odata.type': '#microsoft.graph.standardWebPart', 'id': '418ba70b-4cf7-410a-a5fd-ea38386915ac', 'webPartType': 'c70391ea-0b10-4ee9-b2b4-006d3fcad0cd', 'data': {...} }, { '@odata.type': '#microsoft.graph.standardWebPart', 'id': '416a4c58-61fc-4166-aa19-1099fad50545', 'webPartType': 'f92bf067-bc19-489e-a556-7fe95f508720', 'data': {...} } ] }

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def get_sharepoint_webparts(
    self,
    site_id: str,
    page_id: str,
    section_type: str | None = None,
    section_id: str | int = 1,
    column_id: int | str = 1,
) -> dict | None:
    """Retrieve the configured webparts on a SharePoint site page.

    Can retrieve all webparts on the page or the ones in a defined
    page section (like horizontal section or vertical section).

    OpenText WebPart Type IDs:
        Content Browser: 'cecfdba4-2e82-4538-9436-dbd1c4c01a80'
        Related Workspaces: 'e24d7154-4554-4db6-a44f-d306b6b3a5d4'
        Team members of Workspace: '635a2800-8833-410d-b1f1-f209b28ea2ad'

    Args:
        site_id (str):
            The ID of the SharePoint site.
        page_id (str):
            The ID of the SharePoint page containing the web part.
        section_type (str, optional):
            "horizontalSections" (note the plural!)
            "verticalSection" (note the singular!)
            Use None if you want to retrieve all webparts on page.
        section_id (str | int | None):
            The ID of the section. Only relevant for horizontal sections.
            Simple values like 1,2,3...
            Not relevant for vertical section or if you want to retrieve
            all webparts on the page.
        column_id (int | str, optional):
            For horizontalSections the column ID has to be provided.
            Defaults to 1.


    Returns:
        dict | None:
            A dictionary including the SharePoint webparts of a given page for a given site.
            The actual list is included inside the "value" key of the dictionary.

    Example:
    {
        '@odata.context': "https://graph.microsoft.com/beta/$metadata#sites('ideatedev.sharepoint.com%2C61c0f9cb-39d3-4c04-b60c-31576954a2ab%2Ca678aeab-68ac-46a1-bd95-28020c12de26')/pages('561c65b4-3418-4698-a4c3-7ca7f04812bb')/microsoft.graph.sitePage/webParts",
        'value': [
            {
                '@odata.type': '#microsoft.graph.standardWebPart',
                'id': '405b669e-3c09-45fe-822f-ff60ac7fffce',
                'webPartType': 'c4bd7b2f-7b6e-4599-8485-16504575f590',
                'data': {
                    'audiences': [],
                    'dataVersion': '1.5',
                    'description': 'Prominently display up to 5 pieces of content with links, images, pictures, videos, or photos in a highly visual layout.',
                    'title': 'Hero',
                    'properties': {
                        'heroLayoutThreshold': 640,
                        'carouselLayoutMaxWidth': 639,
                        'layoutCategory': 1,
                        'layout': 5,
                        'content@odata.type': '#Collection(graph.Json)',
                        'content': [
                            {
                                'id': '20cb6611-c7cc-4ba7-91e1-65a6cb576025',
                                'type': 'UrlLink',
                                'color': 4,
                                'description': '',
                                'title': '',
                                'showDescription': False,
                                'showTitle': True,
                                'alternateText': '',
                                'imageDisplayOption': 1,
                                'isDefaultImage': False,
                                'showCallToAction': True,
                                'isDefaultImageLoaded': False,
                                'isCustomImageLoaded': False,
                                'showFeatureText': False,
                                'previewImage': {...}
                            },
                            {
                                'id': '83133733-960b-4139-a73f-17ce2ca5f71c',
                                'type': 'Image',
                                'color': 4,
                                'description': '',
                                'title': '',
                                'showDescription': False,
                                'showTitle': True,
                                'alternateText': '',
                                'imageDisplayOption': 0,
                                'isDefaultImage': False,
                                'showCallToAction': False,
                                'isDefaultImageLoaded': False,
                                'isCustomImageLoaded': False,
                                'showFeatureText': False
                            },
                            ...
                        ]
                    },
                    'serverProcessedContent': {
                        'htmlStrings': [...],
                        'searchablePlainTexts': [...],
                        'links': [...],
                        'imageSources': [...],
                        'componentDependencies': [...],
                        'customMetadata': [...]
                    }
                }
            },
            {
                '@odata.type': '#microsoft.graph.standardWebPart',
                'id': 'f7bfdec9-09c5-4fb6-bc97-3ba225d35ad4',
                'webPartType': '8c88f208-6c77-4bdb-86a0-0c47b4316588',
                'data': {...}
            },
            {
                '@odata.type': '#microsoft.graph.standardWebPart',
                'id': 'f2a8650b-5ea0-4ac2-9cde-56e0fd0279b0',
                'webPartType': 'eb95c819-ab8f-4689-bd03-0c2d65d47b1f',
                'data': {...}
            },
            {
                '@odata.type': '#microsoft.graph.standardWebPart',
                'id': '418ba70b-4cf7-410a-a5fd-ea38386915ac',
                'webPartType': 'c70391ea-0b10-4ee9-b2b4-006d3fcad0cd',
                'data': {...}
            },
            {
                '@odata.type': '#microsoft.graph.standardWebPart',
                'id': '416a4c58-61fc-4166-aa19-1099fad50545',
                'webPartType': 'f92bf067-bc19-489e-a556-7fe95f508720',
                'data': {...}
            }
        ]
    }

    """

    request_url = self.config()["sitesUrl"] + "/" + site_id + "/pages/" + page_id + "/microsoft.graph.sitePage"
    if section_type:
        request_url += "/canvasLayout/" + section_type
    if section_type == "horizontalSections":
        request_url += "/" + str(section_id)
        request_url += "/columns/" + str(column_id)
    request_url += "/webparts"

    request_header = self.request_header()

    response = self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=REQUEST_TIMEOUT,
        failure_message="Cannot get webparts for page -> '{}' of SharePoint site -> '{}'".format(
            page_id,
            site_id,
        ),
    )

    return response

get_team(name)

Get a M365 Team based on its name.

Parameters:

Name Type Description Default
name str

The name of the M365 Team.

required

Returns:

Type Description
dict | None

dict | None: Teams data structure (dictionary) or None if the request fails.

Example

{ '@odata.context': 'https://graph.microsoft.com/v1.0/$metadata#teams', '@odata.count': 1, 'value': [ { 'id': '951bd036-c6fc-4da4-bb80-1860f5472a2f', 'createdDateTime': None, 'displayName': 'Procurement', 'description': 'Procurement', 'internalId': None, 'classification': None, 'specialization': None, 'visibility': 'public', 'webUrl': None, ...}]} 'isArchived': None, 'isMembershipLimitedToOwners': None, 'memberSettings': None, 'guestSettings': None, 'messagingSettings': None, ... } ] }

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def get_team(self, name: str) -> dict | None:
    """Get a M365 Team based on its name.

    Args:
        name (str):
            The name of the M365 Team.

    Returns:
        dict | None:
            Teams data structure (dictionary) or None if the request fails.

    Example:
        {
            '@odata.context': 'https://graph.microsoft.com/v1.0/$metadata#teams',
            '@odata.count': 1,
            'value': [
                {
                    'id': '951bd036-c6fc-4da4-bb80-1860f5472a2f',
                    'createdDateTime': None,
                    'displayName': 'Procurement',
                    'description': 'Procurement',
                    'internalId': None,
                    'classification': None,
                    'specialization': None,
                    'visibility': 'public',
                    'webUrl': None, ...}]}
                    'isArchived': None,
                    'isMembershipLimitedToOwners': None,
                    'memberSettings': None,
                    'guestSettings': None,
                    'messagingSettings': None,
                    ...
                }
            ]
        }

    """

    # The M365 Teams API has an issues with ampersand characters in team names (like "Engineering & Construction")
    # So we do a work-around here to first get the Team ID via the Group endpoint of the Graph API and
    # then fetch the M365 Team via its ID (which is identical to the underlying M365 Group ID)
    response = self.get_group(group_name=name)
    team_id = self.get_result_value(response=response, key="id", index=0)
    if not team_id:
        self.logger.error(
            "Failed to get the ID of the M365 Team -> '%s' via the M365 Group API!",
            name,
        )
        return None

    request_url = self.config()["teamsUrl"] + "/" + str(team_id)

    request_header = self.request_header()

    self.logger.debug(
        "Lookup Microsoft 365 Teams with name -> '%s'; calling -> %s",
        name,
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=REQUEST_TIMEOUT,
        failure_message="Failed to get M365 Team -> '{}'".format(name),
    )

get_team_channel_tabs(team_name, channel_name)

Get tabs of an M365 Team channel based on the team and channel names.

Parameters:

Name Type Description Default
team_name str

The name of the M365 Team.

required
channel_name str

The name of the M365 Team channel.

required

Returns:

Type Description
dict | None

dict | None: Tabs data structure (dictionary) or None if the request fails.

Example

{ '@odata.context': "https://graph.microsoft.com/v1.0/$metadata#teams('951bd036-c6fc-4da4-bb80-1860f5472a2f')/channels('19%3AyPmPnXoFtvs5jmgL7fG-iXNENVMLsB_WSrxYK-zKakY1%40thread.tacv2')/tabs", '@odata.count': 1, 'value': [ { 'id': '66f44e9a-0741-49a4-9500-ec82cc120115', 'displayName': 'Procurement', 'webUrl': 'https://teams.microsoft.com/l/entity/2851980b-95dc-4118-a1f5-5ae1894eaaaf/_djb2_msteams_prefix_66f44e9a-0741-49a4-9500-ec82cc120115?webUrl=https%3a%2f%2fotcs.fqdn.tld.com%2fcssupport%2fxecmoffice%2fteamsapp.html%3fnodeId%3d13178%26type%3dcontainer%26parentId%3d2000%26target%3dcontent%26csurl%3dhttps%3a%2f%2fotcs.fqdn.tld.com%2fcs%2fcs%26appId%3da168b00d-3ad9-46ac-8798-578c1961e1ed%26showBW%3dtrue%26title%3dProcurement&label=Procurement&context=%7b%0d%0a++%22canvasUrl%22%3a+%22https%3a%2f%2fotcs.fqdn.tld.com%2fcssupport%2fxecmoffice%2fteamsapp.html%3fnodeId%3d13178%26type%3dcontainer%26parentId%3d2000%26target%3dcontent%26csurl%3dhttps%3a%2f%2fotcs.fqdn.tld.com%2fcs%2fcs%26appId%3da168b00d-3ad9-46ac-8798-578c1961e1ed%22%2c%0d%0a++%22channelId%22%3a+%2219%3ayPmPnXoFtvs5jmgL7fG-iXNENVMLsB_WSrxYK-zKakY1%40thread.tacv2%22%2c%0d%0a++%22subEntityId%22%3a+null%0d%0a%7d&groupId=951bd036-c6fc-4da4-bb80-1860f5472a2f&tenantId=417e6e3a-82e6-4aa0-9d47-a7734ca3daea', 'configuration': { 'entityId': '13178', 'contentUrl': 'https://otcs.fqdn.tld.com/cssupport/xecmoffice/teamsapp.html?nodeId=13178&type=container&parentId=2000&target=content&csurl=https://otcs.fqdn.tld.com/cs/cs&appId=a168b00d-3ad9-46ac-8798-578c1961e1ed', 'removeUrl': None, 'websiteUrl': 'https://otcs.fqdn.tld.com/cssupport/xecmoffice/teamsapp.html?nodeId=13178&type=container&parentId=2000&target=content&csurl=https://otcs.fqdn.tld.com/cs/cs&appId=a168b00d-3ad9-46ac-8798-578c1961e1ed&showBW=true&title=Procurement', 'dateAdded': '2023-08-12T08:57:35.895Z' } } ] }

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def get_team_channel_tabs(self, team_name: str, channel_name: str) -> dict | None:
    """Get tabs of an M365 Team channel based on the team and channel names.

    Args:
        team_name (str):
            The name of the M365 Team.
        channel_name (str):
            The name of the M365 Team channel.

    Returns:
        dict | None:
            Tabs data structure (dictionary) or None if the request fails.

    Example:
        {
            '@odata.context': "https://graph.microsoft.com/v1.0/$metadata#teams('951bd036-c6fc-4da4-bb80-1860f5472a2f')/channels('19%3AyPmPnXoFtvs5jmgL7fG-iXNENVMLsB_WSrxYK-zKakY1%40thread.tacv2')/tabs",
            '@odata.count': 1,
            'value': [
                {
                    'id': '66f44e9a-0741-49a4-9500-ec82cc120115',
                    'displayName': 'Procurement',
                    'webUrl': 'https://teams.microsoft.com/l/entity/2851980b-95dc-4118-a1f5-5ae1894eaaaf/_djb2_msteams_prefix_66f44e9a-0741-49a4-9500-ec82cc120115?webUrl=https%3a%2f%2fotcs.fqdn.tld.com%2fcssupport%2fxecmoffice%2fteamsapp.html%3fnodeId%3d13178%26type%3dcontainer%26parentId%3d2000%26target%3dcontent%26csurl%3dhttps%3a%2f%2fotcs.fqdn.tld.com%2fcs%2fcs%26appId%3da168b00d-3ad9-46ac-8798-578c1961e1ed%26showBW%3dtrue%26title%3dProcurement&label=Procurement&context=%7b%0d%0a++%22canvasUrl%22%3a+%22https%3a%2f%2fotcs.fqdn.tld.com%2fcssupport%2fxecmoffice%2fteamsapp.html%3fnodeId%3d13178%26type%3dcontainer%26parentId%3d2000%26target%3dcontent%26csurl%3dhttps%3a%2f%2fotcs.fqdn.tld.com%2fcs%2fcs%26appId%3da168b00d-3ad9-46ac-8798-578c1961e1ed%22%2c%0d%0a++%22channelId%22%3a+%2219%3ayPmPnXoFtvs5jmgL7fG-iXNENVMLsB_WSrxYK-zKakY1%40thread.tacv2%22%2c%0d%0a++%22subEntityId%22%3a+null%0d%0a%7d&groupId=951bd036-c6fc-4da4-bb80-1860f5472a2f&tenantId=417e6e3a-82e6-4aa0-9d47-a7734ca3daea',
                    'configuration':
                    {
                        'entityId': '13178',
                        'contentUrl': 'https://otcs.fqdn.tld.com/cssupport/xecmoffice/teamsapp.html?nodeId=13178&type=container&parentId=2000&target=content&csurl=https://otcs.fqdn.tld.com/cs/cs&appId=a168b00d-3ad9-46ac-8798-578c1961e1ed',
                        'removeUrl': None,
                        'websiteUrl': 'https://otcs.fqdn.tld.com/cssupport/xecmoffice/teamsapp.html?nodeId=13178&type=container&parentId=2000&target=content&csurl=https://otcs.fqdn.tld.com/cs/cs&appId=a168b00d-3ad9-46ac-8798-578c1961e1ed&showBW=true&title=Procurement',
                        'dateAdded': '2023-08-12T08:57:35.895Z'
                    }
                }
            ]
        }

    """

    response = self.get_team(name=team_name)
    team_id = self.get_result_value(response=response, key="id", index=0)
    if not team_id:
        return None

    # Get the channels of the M365 Team:
    response = self.get_team_channels(name=team_name)
    if not response or not response["value"] or not response["value"][0]:
        return None

    # Look the channel by name and then retrieve its ID:
    channel = next(
        (item for item in response["value"] if item["displayName"] == channel_name),
        None,
    )
    if not channel:
        self.logger.error(
            "Cannot find Channel -> '%s' on M365 Team -> '%s'!",
            channel_name,
            team_name,
        )
        return None
    channel_id = channel["id"]

    request_url = self.config()["teamsUrl"] + "/" + str(team_id) + "/channels/" + str(channel_id) + "/tabs"

    request_header = self.request_header()

    self.logger.debug(
        "Retrieve Tabs of Microsoft 365 Teams -> %s and Channel -> %s; calling -> %s",
        team_name,
        channel_name,
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=REQUEST_TIMEOUT,
        failure_message="Failed to get Tabs for M365 Team -> '{}' ({}) and Channel -> '{}' ({})".format(
            team_name,
            team_id,
            channel_name,
            channel_id,
        ),
    )

get_team_channels(name)

Get channels of a M365 Team based on the team name.

Parameters:

Name Type Description Default
name str

The name of the M365 team.

required

Returns:

Name Type Description
dict dict | None

The channel data structure (dictionary) or None if the request fails.

Example

{ '@odata.context': "https://graph.microsoft.com/v1.0/$metadata#teams('951bd036-c6fc-4da4-bb80-1860f5472a2f')/channels", '@odata.count': 1, 'value': [ { 'id': '19:yPmPnXoFtvs5jmgL7fG-iXNENVMLsB_WSrxYK-zKakY1@thread.tacv2', 'createdDateTime': '2023-08-11T14:11:35.986Z', 'displayName': 'General', 'description': 'Procurement', 'isFavoriteByDefault': None, 'email': None, 'tenantId': '417e6e3a-82e6-4aa0-9d47-a7734ca3daea', 'webUrl': 'https://teams.microsoft.com/l/channel/19%3AyPmPnXoFtvs5jmgL7fG-iXNENVMLsB_WSrxYK-zKakY1%40thread.tacv2/Procurement?groupId=951bd036-c6fc-4da4-bb80-1860f5472a2f&tenantId=417e6e3a-82e6-4aa0-9d47-a7734ca3daea&allowXTenantAccess=False', 'membershipType': 'standard' } ] }

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def get_team_channels(self, name: str) -> dict | None:
    """Get channels of a M365 Team based on the team name.

    Args:
        name (str):
            The name of the M365 team.

    Returns:
        dict:
            The channel data structure (dictionary) or None if the request fails.

    Example:
        {
            '@odata.context': "https://graph.microsoft.com/v1.0/$metadata#teams('951bd036-c6fc-4da4-bb80-1860f5472a2f')/channels",
            '@odata.count': 1,
            'value': [
                {
                    'id': '19:yPmPnXoFtvs5jmgL7fG-iXNENVMLsB_WSrxYK-zKakY1@thread.tacv2',
                    'createdDateTime': '2023-08-11T14:11:35.986Z',
                    'displayName': 'General',
                    'description': 'Procurement',
                    'isFavoriteByDefault': None,
                    'email': None,
                    'tenantId': '417e6e3a-82e6-4aa0-9d47-a7734ca3daea',
                    'webUrl': 'https://teams.microsoft.com/l/channel/19%3AyPmPnXoFtvs5jmgL7fG-iXNENVMLsB_WSrxYK-zKakY1%40thread.tacv2/Procurement?groupId=951bd036-c6fc-4da4-bb80-1860f5472a2f&tenantId=417e6e3a-82e6-4aa0-9d47-a7734ca3daea&allowXTenantAccess=False',
                    'membershipType': 'standard'
                }
            ]
        }

    """

    response = self.get_team(name=name)
    team_id = self.get_result_value(response=response, key="id", index=0)
    if not team_id:
        return None

    request_url = self.config()["teamsUrl"] + "/" + str(team_id) + "/channels"

    request_header = self.request_header()

    self.logger.debug(
        "Retrieve channels of Microsoft 365 Team -> '%s'; calling -> %s",
        name,
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=REQUEST_TIMEOUT,
        failure_message="Failed to get Channels for M365 Team -> '{}' ({})".format(
            name,
            team_id,
        ),
    )

get_teams_app(app_id)

Get a specific MS Teams app in catalog based on the known (internal) app ID.

Parameters:

Name Type Description Default
app_id str

ID of the app (this is NOT the external ID but the internal ID).

required

Returns:

Type Description
dict | None

dict | None: Response of the MS Graph API call or None if the call fails.

Examle

{ '@odata.context': 'https://graph.microsoft.com/v1.0/$metadata#appCatalogs/teamsApps(appDefinitions())/$entity', 'id': 'ccabe3fb-316f-40e0-a486-1659682cb8cd', 'externalId': 'dd4af790-d8ff-47a0-87ad-486318272c7a', 'displayName': 'Extended ECM', 'distributionMethod': 'organization', 'appDefinitions@odata.context': "https://graph.microsoft.com/v1.0/$metadata#appCatalogs/teamsApps('ccabe3fb-316f-40e0-a486-1659682cb8cd')/appDefinitions", 'appDefinitions': [ { 'id': 'Y2NhYmUzZmItMzE2Zi00MGUwLWE0ODYtMTY1OTY4MmNiOGNkIyMyNC4yLjAjI1B1Ymxpc2hlZA==', 'teamsAppId': 'ccabe3fb-316f-40e0-a486-1659682cb8cd', 'displayName': 'Extended ECM', 'version': '24.2.0', 'publishingState': 'published', 'shortDescription': 'Add a tab for an Extended ECM business workspace.', 'description': 'View and interact with OpenText Extended ECM business workspaces', 'lastModifiedDateTime': None, 'createdBy': None, 'authorization': {...} } ] }

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def get_teams_app(self, app_id: str) -> dict | None:
    """Get a specific MS Teams app in catalog based on the known (internal) app ID.

    Args:
        app_id (str):
            ID of the app (this is NOT the external ID but the internal ID).

    Returns:
        dict | None:
            Response of the MS Graph API call or None if the call fails.

    Examle:
        {
            '@odata.context': 'https://graph.microsoft.com/v1.0/$metadata#appCatalogs/teamsApps(appDefinitions())/$entity',
            'id': 'ccabe3fb-316f-40e0-a486-1659682cb8cd',
            'externalId': 'dd4af790-d8ff-47a0-87ad-486318272c7a',
            'displayName': 'Extended ECM',
            'distributionMethod': 'organization',
            'appDefinitions@odata.context': "https://graph.microsoft.com/v1.0/$metadata#appCatalogs/teamsApps('ccabe3fb-316f-40e0-a486-1659682cb8cd')/appDefinitions",
            'appDefinitions': [
                {
                    'id': 'Y2NhYmUzZmItMzE2Zi00MGUwLWE0ODYtMTY1OTY4MmNiOGNkIyMyNC4yLjAjI1B1Ymxpc2hlZA==',
                    'teamsAppId': 'ccabe3fb-316f-40e0-a486-1659682cb8cd',
                    'displayName': 'Extended ECM',
                    'version': '24.2.0',
                    'publishingState': 'published',
                    'shortDescription': 'Add a tab for an Extended ECM business workspace.',
                    'description': 'View and interact with OpenText Extended ECM business workspaces',
                    'lastModifiedDateTime': None,
                    'createdBy': None,
                    'authorization': {...}
                }
            ]
        }

    """

    query = {"$expand": "AppDefinitions"}
    encoded_query = urllib.parse.urlencode(query, doseq=True)
    request_url = self.config()["teamsAppsUrl"] + "/" + app_id + "?" + encoded_query

    self.logger.debug(
        "Get M365 Teams App with ID -> %s; calling -> %s",
        app_id,
        request_url,
    )

    request_header = self.request_header()

    response = self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=REQUEST_TIMEOUT,
        failure_message="Failed to get M365 Teams app with ID -> {}".format(app_id),
    )

    return response

get_teams_apps(filter_expression='')

Get a list of MS Teams apps in catalog that match a given filter criterium.

Parameters:

Name Type Description Default
filter_expression str

Filter string see https://learn.microsoft.com/en-us/graph/filter-query-parameter

''

Returns:

Type Description
dict | None

dict | None: Response of the MS Graph API call or None if the call fails.

Example

{ '@odata.context': 'https://graph.microsoft.com/v1.0/$metadata#appCatalogs/teamsApps(appDefinitions())', '@odata.count': 1, 'value': [ { 'id': '2851980b-95dc-4118-a1f5-5ae1894eaaaf', 'externalId': 'dd4af790-d8ff-47a0-87ad-486318272c7a', 'displayName': 'OpenText Extended ECM', 'distributionMethod': 'organization', 'appDefinitions@odata.context': "https://graph.microsoft.com/v1.0/$metadata#appCatalogs/teamsApps('2851980b-95dc-4118-a1f5-5ae1894eaaaf')/appDefinitions", 'appDefinitions': [ { 'id': 'Mjg1MTk4MGItOTVkYy00MTE4LWExZjUtNWFlMTg5NGVhYWFmIyMyMi40IyNQdWJsaXNoZWQ=', 'teamsAppId': '2851980b-95dc-4118-a1f5-5ae1894eaaaf', 'displayName': 'OpenText Extended ECM', 'version': '22.4', 'publishingState': 'published', 'shortDescription': 'Add a tab for an Extended ECM business workspace.', 'description': 'View and interact with OpenText Extended ECM business workspaces', 'lastModifiedDateTime': None, 'createdBy': None, 'authorization': { 'requiredPermissionSet': {...} } } ] } ] }

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def get_teams_apps(self, filter_expression: str = "") -> dict | None:
    """Get a list of MS Teams apps in catalog that match a given filter criterium.

    Args:
        filter_expression (str, optional):
            Filter string see https://learn.microsoft.com/en-us/graph/filter-query-parameter

    Returns:
        dict | None:
            Response of the MS Graph API call or None if the call fails.

    Example:
        {
            '@odata.context': 'https://graph.microsoft.com/v1.0/$metadata#appCatalogs/teamsApps(appDefinitions())',
            '@odata.count': 1,
            'value': [
                {
                    'id': '2851980b-95dc-4118-a1f5-5ae1894eaaaf',
                    'externalId': 'dd4af790-d8ff-47a0-87ad-486318272c7a',
                    'displayName': 'OpenText Extended ECM',
                    'distributionMethod': 'organization',
                    'appDefinitions@odata.context': "https://graph.microsoft.com/v1.0/$metadata#appCatalogs/teamsApps('2851980b-95dc-4118-a1f5-5ae1894eaaaf')/appDefinitions",
                    'appDefinitions': [
                        {
                            'id': 'Mjg1MTk4MGItOTVkYy00MTE4LWExZjUtNWFlMTg5NGVhYWFmIyMyMi40IyNQdWJsaXNoZWQ=',
                            'teamsAppId': '2851980b-95dc-4118-a1f5-5ae1894eaaaf',
                            'displayName': 'OpenText Extended ECM',
                            'version': '22.4',
                            'publishingState': 'published',
                            'shortDescription': 'Add a tab for an Extended ECM business workspace.',
                            'description': 'View and interact with OpenText Extended ECM business workspaces',
                            'lastModifiedDateTime': None,
                            'createdBy': None,
                            'authorization': {
                                'requiredPermissionSet': {...}
                            }
                        }
                    ]
                }
            ]
        }

    """

    query = {"$expand": "AppDefinitions"}

    if filter_expression:
        query["$filter"] = filter_expression

    encoded_query = urllib.parse.urlencode(query, doseq=True)
    request_url = self.config()["teamsAppsUrl"] + "?" + encoded_query

    if filter_expression:
        self.logger.debug(
            "Get list of MS Teams Apps using filter -> %s; calling -> %s",
            filter_expression,
            request_url,
        )
        failure_message = "Failed to get list of M365 Teams apps using filter -> {}".format(
            filter_expression,
        )
    else:
        self.logger.debug(
            "Get list of all MS Teams Apps; calling -> %s",
            request_url,
        )
        failure_message = "Failed to get list of M365 Teams apps"

    request_header = self.request_header()

    return self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=REQUEST_TIMEOUT,
        failure_message=failure_message,
    )

get_teams_apps_of_team(team_id, filter_expression='')

Get a list of MS Teams apps of a M365 team that match a given filter criterium.

Parameters:

Name Type Description Default
team_id str

The M365 ID of the team.

required
filter_expression str

Filter string see https://learn.microsoft.com/en-us/graph/filter-query-parameter

''

Returns:

Type Description
dict | None

dict | None: Response of the MS Graph API call or None if the call fails.

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def get_teams_apps_of_team(
    self,
    team_id: str,
    filter_expression: str = "",
) -> dict | None:
    """Get a list of MS Teams apps of a M365 team that match a given filter criterium.

    Args:
        team_id (str):
            The M365 ID of the team.
        filter_expression (str, optional):
            Filter string see https://learn.microsoft.com/en-us/graph/filter-query-parameter

    Returns:
        dict | None:
            Response of the MS Graph API call or None if the call fails.

    """

    query = {"$expand": "teamsAppDefinition"}
    if filter_expression:
        query["$filter"] = filter_expression

    encoded_query = urllib.parse.urlencode(query, doseq=True)
    request_url = self.config()["teamsUrl"] + "/" + team_id + "/installedApps?" + encoded_query

    self.logger.debug(
        "Get list of M365 Teams Apps for M365 Team -> %s using query -> %s; calling -> %s",
        team_id,
        query,
        request_url,
    )

    request_header = self.request_header()

    return self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=REQUEST_TIMEOUT,
        failure_message="Failed to get list of M365 Teams apps for M365 Team -> {}".format(
            team_id,
        ),
    )

get_teams_apps_of_user(user_id, filter_expression='')

Get a list of MS Teams apps of a user that match a given filter criterium.

Parameters:

Name Type Description Default
user_id str

The M365 GUID of the user (can also be the M365 email of the user)

required
filter_expression str

Filter string see https://learn.microsoft.com/en-us/graph/filter-query-parameter

''

Returns:

Type Description
dict | None

dict | None: Response of the MS Graph API call or None if the call fails.

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def get_teams_apps_of_user(
    self,
    user_id: str,
    filter_expression: str = "",
) -> dict | None:
    """Get a list of MS Teams apps of a user that match a given filter criterium.

    Args:
        user_id (str):
            The M365 GUID of the user (can also be the M365 email of the user)
        filter_expression (str, optional):
            Filter string see https://learn.microsoft.com/en-us/graph/filter-query-parameter

    Returns:
        dict | None:
            Response of the MS Graph API call or None if the call fails.

    """

    query = {"$expand": "teamsAppDefinition"}
    if filter_expression:
        query["$filter"] = filter_expression

    encoded_query = urllib.parse.urlencode(query, doseq=True)
    request_url = self.config()["usersUrl"] + "/" + user_id + "/teamwork/installedApps?" + encoded_query

    self.logger.debug(
        "Get list of M365 Teams Apps for user -> %s using query -> %s; calling -> %s",
        user_id,
        query,
        request_url,
    )

    request_header = self.request_header()

    response = self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=REQUEST_TIMEOUT,
        failure_message="Failed to get M365 Teams apps for user -> {}".format(
            user_id,
        ),
    )

    return response

get_user(user_email, user_id=None, show_error=False)

Get a M365 User based on its email or ID.

Parameters:

Name Type Description Default
user_email str

The M365 user email.

required
user_id str | None

The ID of the M365 user (alternatively to user_email). Optional.

None
show_error bool

Whether or not an error should be displayed if the user is not found.

False

Returns:

Name Type Description
dict dict | None

User information or None if the user couldn't be retrieved (e.g. because it doesn't exist or if there is a permission problem).

Example

{ '@odata.context': 'https://graph.microsoft.com/v1.0/$metadata#users/$entity', 'businessPhones': [], 'displayName': 'Bob Davis', 'givenName': 'Bob', 'id': '72c80809-094f-4e6e-98d4-25a736385d10', 'jobTitle': None, 'mail': 'bdavis@M365x61936377.onmicrosoft.com', 'mobilePhone': None, 'officeLocation': None, 'preferredLanguage': None, 'surname': 'Davis', 'userPrincipalName': 'bdavis@M365x61936377.onmicrosoft.com' }

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def get_user(self, user_email: str, user_id: str | None = None, show_error: bool = False) -> dict | None:
    """Get a M365 User based on its email or ID.

    Args:
        user_email (str):
            The M365 user email.
        user_id (str | None, optional):
            The ID of the M365 user (alternatively to user_email). Optional.
        show_error (bool):
            Whether or not an error should be displayed if the
            user is not found.

    Returns:
        dict:
            User information or None if the user couldn't be retrieved (e.g. because it doesn't exist
            or if there is a permission problem).

    Example:
        {
            '@odata.context': 'https://graph.microsoft.com/v1.0/$metadata#users/$entity',
            'businessPhones': [],
            'displayName': 'Bob Davis',
            'givenName': 'Bob',
            'id': '72c80809-094f-4e6e-98d4-25a736385d10',
            'jobTitle': None,
            'mail': 'bdavis@M365x61936377.onmicrosoft.com',
            'mobilePhone': None,
            'officeLocation': None,
            'preferredLanguage': None,
            'surname': 'Davis',
            'userPrincipalName': 'bdavis@M365x61936377.onmicrosoft.com'
        }

    """

    # Some sanity checks:
    if user_email and ("@" not in user_email or "." not in user_email):
        self.logger.error(
            "User email -> %s is not a valid email address!",
            user_email,
        )
        return None

    # if there's an alias in the E-Mail Adress we remove it as
    # MS Graph seems to not support an alias to lookup a user object.
    if user_email and "+" in user_email:
        self.logger.info(
            "Removing Alias from email address -> %s to determine M365 principal name...",
            user_email,
        )
        # Find the index of the '+' character
        alias_index = user_email.find("+")

        # Find the index of the '@' character
        domain_index = user_email.find("@")

        # Construct the email address without the alias
        user_email = user_email[:alias_index] + user_email[domain_index:]
        self.logger.info(
            "M365 user principal name -> '%s'.",
            user_email,
        )

    request_url = self.config()["usersUrl"] + "/" + str(user_email if user_email else user_id)
    request_header = self.request_header()

    self.logger.debug(
        "Get M365 user -> '%s'; calling -> %s",
        str(user_email if user_email else user_id),
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=REQUEST_TIMEOUT,
        failure_message="Failed to get M365 user -> '{}'".format(user_email if user_email else user_id),
        show_error=show_error,
    )

get_user_drive(user_id, me=False)

Get the mysite (OneDrive) of the user.

It may be required to do this before certain other operations are possible. These operations may require that the mydrive is initialized for that user. If you get errors like "User's mysite not found." this may be the case.

Parameters:

Name Type Description Default
user_id str

The M365 GUID of the user (can also be the M365 email of the user).

required
me bool

Should be True if the user itself is accessing the drive.

False

Returns:

Name Type Description
dict dict | None

A list of user licenses or None if request fails.

Example: { '@odata.context': 'https://graph.microsoft.com/v1.0/$metadata#drives/$entity', 'createdDateTime': '2025-04-10T23:43:26Z', 'description': '', 'id': 'b!VsxYN1IbrEqbiwMiba_M7FCkNAhL5LRFnQEZpEYbxDAxvvcvUMAhSqfgWW_4eAUP', 'lastModifiedDateTime': '2025-04-12T15:50:20Z', 'name': 'OneDrive', 'webUrl': 'https://ideateqa-my.sharepoint.com/personal/jbenham_qa_idea-te_eimdemo_com/Documents', 'driveType': 'business', 'createdBy': { 'user': { 'displayName': 'System Account' } }, 'lastModifiedBy': { 'user': { 'email': 'jbenham@qa.idea-te.eimdemo.com', 'id': '470060cc-4d9f-439e-8a6e-8d567c5bda80', 'displayName': 'Jeff Benham' } }, 'owner': { 'user': {...} }, 'quota': { 'deleted': 0, 'remaining': 1099511518137, 'state': 'normal', 'total': 1099511627776, 'used': 109639 } }

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def get_user_drive(self, user_id: str, me: bool = False) -> dict | None:
    """Get the mysite (OneDrive) of the user.

    It may be required to do this before certain other operations
    are possible. These operations may require that the mydrive
    is initialized for that user. If you get errors like
    "User's mysite not found." this may be the case.

    Args:
        user_id (str):
            The M365 GUID of the user (can also be the M365 email of the user).
        me (bool, optional):
            Should be True if the user itself is accessing the drive.

    Returns:
        dict:
            A list of user licenses or None if request fails.

    Example:
    {
        '@odata.context': 'https://graph.microsoft.com/v1.0/$metadata#drives/$entity',
        'createdDateTime': '2025-04-10T23:43:26Z',
        'description': '',
        'id': 'b!VsxYN1IbrEqbiwMiba_M7FCkNAhL5LRFnQEZpEYbxDAxvvcvUMAhSqfgWW_4eAUP',
        'lastModifiedDateTime': '2025-04-12T15:50:20Z',
        'name': 'OneDrive',
        'webUrl': 'https://ideateqa-my.sharepoint.com/personal/jbenham_qa_idea-te_eimdemo_com/Documents',
        'driveType': 'business',
        'createdBy': {
            'user': {
                'displayName': 'System Account'
            }
        },
        'lastModifiedBy': {
            'user': {
                'email': 'jbenham@qa.idea-te.eimdemo.com',
                'id': '470060cc-4d9f-439e-8a6e-8d567c5bda80',
                'displayName': 'Jeff Benham'
            }
        },
        'owner': {
            'user': {...}
        },
        'quota': {
            'deleted': 0,
            'remaining': 1099511518137,
            'state': 'normal',
            'total': 1099511627776,
            'used': 109639
        }
    }

    """

    request_url = self.config()["meUrl"] if me else self.config()["usersUrl"] + "/" + user_id
    request_url += "/drive"
    request_header = self.request_header_user() if me else self.request_header()

    return self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=REQUEST_TIMEOUT,
        failure_message="Failed to get mySite (drive) of M365 user -> {}".format(user_id),
    )

get_user_licenses(user_id)

Get the assigned license SKUs of a user.

Parameters:

Name Type Description Default
user_id str

The M365 GUID of the user (can also be the M365 email of the user).

required

Returns:

Name Type Description
dict dict | None

A list of user licenses or None if request fails.

Example

{ '@odata.context': "https://graph.microsoft.com/v1.0/$metadata#users('a5875311-f0a5-486d-a746-bd7372b91115')/licenseDetails", 'value': [ { 'id': '8DRPYHK6IUOra-Nq6L0A7GAn38eBLPdOtXhbU5K1cd8', 'skuId': 'c7df2760-2c81-4ef7-b578-5b5392b571df', 'skuPartNumber': 'ENTERPRISEPREMIUM', 'servicePlans': [{...}, {...}, {...}, {...}, {...}, {...}, {...}, {...}, {...}, ...] } ] }

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def get_user_licenses(self, user_id: str) -> dict | None:
    """Get the assigned license SKUs of a user.

    Args:
        user_id (str):
            The M365 GUID of the user (can also be the M365 email of the user).

    Returns:
        dict:
            A list of user licenses or None if request fails.

    Example:
        {
            '@odata.context': "https://graph.microsoft.com/v1.0/$metadata#users('a5875311-f0a5-486d-a746-bd7372b91115')/licenseDetails",
            'value': [
                {
                    'id': '8DRPYHK6IUOra-Nq6L0A7GAn38eBLPdOtXhbU5K1cd8',
                    'skuId': 'c7df2760-2c81-4ef7-b578-5b5392b571df',
                    'skuPartNumber': 'ENTERPRISEPREMIUM',
                    'servicePlans': [{...}, {...}, {...}, {...}, {...}, {...}, {...}, {...}, {...}, ...]
                }
            ]
        }

    """

    request_url = self.config()["usersUrl"] + "/" + user_id + "/licenseDetails"
    request_header = self.request_header()

    return self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=REQUEST_TIMEOUT,
        failure_message="Failed to get M365 licenses of M365 user -> {}".format(user_id),
    )

get_user_photo(user_id, show_error=True)

Get the photo of a M365 user.

Parameters:

Name Type Description Default
user_id str

The M365 GUID of the user (can also be the M365 email of the user).

required
show_error bool

Whether or not an error should be logged if the user does not have a photo in M365.

True

Returns:

Name Type Description
bytes bytes | None

Image of the user photo or None if the user photo couldn't be retrieved.

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def get_user_photo(self, user_id: str, show_error: bool = True) -> bytes | None:
    """Get the photo of a M365 user.

    Args:
        user_id (str):
            The M365 GUID of the user (can also be the M365 email of the user).
        show_error (bool, optional):
            Whether or not an error should be logged if the user
            does not have a photo in M365.

    Returns:
        bytes:
            Image of the user photo or None if the user photo couldn't be retrieved.

    """

    request_url = self.config()["usersUrl"] + "/" + user_id + "/photo/$value"
    # Set image as content type:
    request_header = self.request_header("image/*")

    self.logger.debug(
        "Get photo of user -> %s; calling -> %s",
        user_id,
        request_url,
    )

    response = self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=REQUEST_TIMEOUT,
        failure_message="Failed to get photo of M365 user -> {}".format(user_id),
        warning_message="M365 User -> {} does not yet have a photo.".format(
            user_id,
        ),
        show_error=show_error,
        parse_request_response=False,  # the response is NOT JSON!
    )

    if response and response.ok and response.content:
        return response.content  # this is the actual image - not json!

    return None

get_users(max_number=250, next_page_url=None)

Get list all all users in M365 tenant.

Parameters:

Name Type Description Default
max_number int

The maximum result values (limit).

250
next_page_url str

The MS Graph URL to retrieve the next page of M365 users (pagination). This is used for the iterator get_users_iterator() below.

None

Returns:

Type Description
dict | None

dict | None: Dictionary of all M365 users.

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def get_users(self, max_number: int = 250, next_page_url: str | None = None) -> dict | None:
    """Get list all all users in M365 tenant.

    Args:
        max_number (int, optional):
            The maximum result values (limit).
        next_page_url (str, optional):
            The MS Graph URL to retrieve the next page of M365 users (pagination).
            This is used for the iterator get_users_iterator() below.

    Returns:
        dict | None:
            Dictionary of all M365 users.

    """

    request_url = next_page_url if next_page_url else self.config()["usersUrl"]
    request_header = self.request_header()

    self.logger.debug(
        "Get list of all M365 users%s; calling -> %s",
        " (paged)" if next_page_url else "",
        request_url,
    )

    response = self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        params={"$top": str(max_number)} if not next_page_url else None,
        timeout=REQUEST_TIMEOUT,
        failure_message="Failed to get list of M365 users!",
    )

    return response

get_users_iterator()

Get an iterator object that can be used to traverse all M365 users.

Returning a generator avoids loading a large number of nodes into memory at once. Instead you can iterate over the potential large list of users.

Example usage

users = m365_object.get_users_iterator() for user in users: logger.info("Traversing M365 user -> '%s'...", user.get("displayName", ""))

Returns:

Name Type Description
iter iter

A generator yielding one M365 user per iteration. If the REST API fails, returns no value.

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def get_users_iterator(
    self,
) -> iter:
    """Get an iterator object that can be used to traverse all M365 users.

    Returning a generator avoids loading a large number of nodes into memory at once. Instead you
    can iterate over the potential large list of users.

    Example usage:
        users = m365_object.get_users_iterator()
        for user in users:
            logger.info("Traversing M365 user -> '%s'...", user.get("displayName", "<undefined name>"))

    Returns:
        iter:
            A generator yielding one M365 user per iteration.
            If the REST API fails, returns no value.

    """

    next_page_url = None

    while True:
        response = self.get_users(
            next_page_url=next_page_url,
        )
        if not response or "value" not in response:
            # Don't return None! Plain return is what we need for iterators.
            # Natural Termination: If the generator does not yield, it behaves
            # like an empty iterable when used in a loop or converted to a list:
            return

        # Yield users one at a time:
        yield from response["value"]

        # See if we have an additional result page.
        # If not terminate the iterator and return
        # no value.
        next_page_url = response.get("@odata.nextLink", None)
        if not next_page_url:
            # Don't return None! Plain return is what we need for iterators.
            # Natural Termination: If the generator does not yield, it behaves
            # like an empty iterable when used in a loop or converted to a list:
            return

has_team(group_name)

Check if a M365 Group has a M365 Team connected or not.

Parameters:

Name Type Description Default
group_name str

The name of the M365 group.

required

Returns:

Name Type Description
bool bool

Returns True if a Team is assigned and False otherwise.

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def has_team(self, group_name: str) -> bool:
    """Check if a M365 Group has a M365 Team connected or not.

    Args:
        group_name (str):
            The name of the M365 group.

    Returns:
        bool:
            Returns True if a Team is assigned and False otherwise.

    """

    response = self.get_group(group_name=group_name)
    group_id = self.get_result_value(response=response, key="id", index=0)
    if not group_id:
        self.logger.error(
            "M365 Group -> '%s' not found! Cannot check if it has a M365 Team.",
            group_name,
        )
        return False

    request_url = self.config()["groupsUrl"] + "/" + group_id + "/team"
    request_header = self.request_header()

    self.logger.debug(
        "Check if M365 Group -> %s has a M365 Team connected; calling -> %s",
        group_name,
        request_url,
    )

    response = self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=REQUEST_TIMEOUT,
        failure_message="Failed to check if M365 Group -> '{}' has a M365 Team connected".format(
            group_name,
        ),
        parse_request_response=False,
        show_error=False,
    )

    if response and response.status_code == 200:  # Group has a Team assigned!
        self.logger.debug("Group -> '%s' has a M365 Team connected.", group_name)
        return True
    elif not response or response.status_code == 404:  # Group does not have a Team assigned!
        self.logger.debug("Group -> '%s' has no M365 Team connected.", group_name)
        return False

    return False

is_member(group_id, member_id, show_error=True)

Check whether a M365 user is already in a M365 group.

Parameters:

Name Type Description Default
group_id str

The M365 GUID of the group.

required
member_id str

The M365 GUID of the user (member).

required
show_error bool

Whether or not an error should be logged if the user is not a member of the group.

True

Returns:

Name Type Description
bool bool

True if the user is in the group. False otherwise.

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def is_member(self, group_id: str, member_id: str, show_error: bool = True) -> bool:
    """Check whether a M365 user is already in a M365 group.

    Args:
        group_id (str):
            The M365 GUID of the group.
        member_id (str):
            The M365 GUID of the user (member).
        show_error (bool):
            Whether or not an error should be logged if the user
            is not a member of the group.

    Returns:
        bool:
            True if the user is in the group. False otherwise.

    """

    # don't encode this URL - this has not been working!!
    request_url = self.config()["groupsUrl"] + f"/{group_id}/members?$filter=id eq '{member_id}'"
    request_header = self.request_header()

    self.logger.debug(
        "Check if user -> %s is in group -> %s; calling -> %s",
        member_id,
        group_id,
        request_url,
    )

    response = self.do_request(
        url=request_url,
        method="GET",
        headers=request_header,
        timeout=REQUEST_TIMEOUT,
        failure_message="Failed to check if M365 user -> {} is in M365 group -> {}".format(
            member_id,
            group_id,
        ),
        show_error=show_error,
    )

    return bool(response and response.get("value"))

lookup_result_value(response, key, value, return_key, sub_dict_name='')

Look up a property value for a provided key-value pair of a REST response.

Parameters:

Name Type Description Default
response dict

The REST response from an OTCS REST call, containing property data.

required
key str

Property name (key) to match in the response.

required
value str

Value to find in the item with the matching key.

required
return_key str

Name of the dictionary key whose value should be returned.

required
sub_dict_name str

Some MS Graph API calls include nested dict structures that can be requested with an "expand" query parameter. In such a case we use the sub_dict_name to access it.

''

Returns:

Type Description
str | None

str | None: The value of the property specified by "return_key" if found, or None if the lookup fails.

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def lookup_result_value(
    self,
    response: dict,
    key: str,
    value: str,
    return_key: str,
    sub_dict_name: str = "",
) -> str | None:
    """Look up a property value for a provided key-value pair of a REST response.

    Args:
        response (dict):
            The REST response from an OTCS REST call, containing property data.
        key (str):
            Property name (key) to match in the response.
        value (str):
            Value to find in the item with the matching key.
        return_key (str):
            Name of the dictionary key whose value should be returned.
        sub_dict_name (str):
            Some MS Graph API calls include nested dict structures that can
            be requested with an "expand" query parameter. In such
            a case we use the sub_dict_name to access it.

    Returns:
        str | None:
            The value of the property specified by "return_key" if found,
            or None if the lookup fails.

    """

    if not response:
        return None

    results = response.get("value", response)

    # check if results is a list or a dict (both is possible -
    # dependent on the actual REST API):
    if isinstance(results, dict):
        # result is a dict - we don't need index value:
        if sub_dict_name and sub_dict_name in results:
            results = results[sub_dict_name]
        if key in results and results[key] == value and return_key in results:
            return results[return_key]
        else:
            return None
    elif isinstance(results, list):
        # result is a list - we need index value
        for result in results:
            if sub_dict_name and sub_dict_name in result:
                result = result[sub_dict_name]
            if key in result and result[key] == value and return_key in result:
                return result[return_key]
        return None
    else:
        self.logger.error(
            "Result needs to be a list or dictionary but it is of type -> '%s'!",
            str(type(results)),
        )
        return None

parse_request_response(response_object, additional_error_message='', show_error=True)

Convert the request response (JSon) to a Python dict in a safe way.

It first tries to load the response.text via json.loads() that produces a dict output. Only if response.text is not set or is empty it just converts the response_object to a dict using the vars() built-in method.

Parameters:

Name Type Description Default
response_object object

This is reponse object delivered by the request call.

required
additional_error_message str

Use a more specific error message in case of an error.

''
show_error bool

True: write an error to the log file False: write a warning to the log file

True

Returns:

Name Type Description
dict dict | None

API response information or None in case of an error.

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def parse_request_response(
    self,
    response_object: requests.Response,
    additional_error_message: str = "",
    show_error: bool = True,
) -> dict | None:
    """Convert the request response (JSon) to a Python dict in a safe way.

    It first tries to load the response.text via json.loads() that produces a
    dict output. Only if response.text is not set or is empty it just converts the
    response_object to a dict using the vars() built-in method.

    Args:
        response_object (object):
            This is reponse object delivered by the request call.
        additional_error_message (str, optional):
            Use a more specific error message in case of an error.
        show_error (bool, optional):
            True: write an error to the log file
            False: write a warning to the log file

    Returns:
        dict:
            API response information or None in case of an error.

    """

    if not response_object:
        return None

    try:
        dict_object = json.loads(response_object.text) if response_object.text else vars(response_object)
    except json.JSONDecodeError as exception:
        if additional_error_message:
            message = "Cannot decode response as JSon. {}; error -> {}".format(
                additional_error_message,
                exception,
            )
        else:
            message = "Cannot decode response as JSon; error -> {}".format(
                exception,
            )
        if show_error:
            self.logger.error(message)
        else:
            self.logger.warning(message)
        return None
    else:
        return dict_object

publish_sharepoint_page(site_id, page_id)

Publish a page of a SharePoint site.

Parameters:

Name Type Description Default
site_id str

The ID of the SharePoint site the page should be published on.

required
page_id str

The ID of the page to be published.

required

Returns:

Name Type Description
bool bool

True = Success, False = Error.

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def publish_sharepoint_page(self, site_id: str, page_id: str) -> bool:
    """Publish a page of a SharePoint site.

    Args:
        site_id (str):
            The ID of the SharePoint site the page should be published on.
        page_id (str):
            The ID of the page to be published.

    Returns:
        bool:
            True = Success, False = Error.

    """

    request_url = (
        self.config()["sitesUrl"] + "/" + site_id + "/pages/" + page_id + "/microsoft.graph.sitePage/publish"
    )

    request_header = self.request_header()

    response = self.do_request(
        url=request_url,
        method="POST",
        headers=request_header,
        timeout=REQUEST_TIMEOUT,
        failure_message="Cannot publish SharePoint page -> '{}' on SharePoint site -> '{}'".format(
            page_id,
            site_id,
        ),
        parse_request_response=False,
    )

    return bool(response.ok)

purge_deleted_item(item_id)

Purge a single deleted user or group.

This requires elevated permissions that are typically not available via Graph API.

Parameters:

Name Type Description Default
item_id str

The M365 GUID of the item to purge.

required

Returns:

Type Description
dict | None

dict | None: Response of the MS Graph API call or None if the call fails.

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def purge_deleted_item(self, item_id: str) -> dict | None:
    """Purge a single deleted user or group.

    This requires elevated permissions that are typically
    not available via Graph API.

    Args:
        item_id (str):
            The M365 GUID of the item to purge.

    Returns:
        dict | None:
            Response of the MS Graph API call or None if the call fails.

    """

    request_url = self.config()["directoryUrl"] + "/deletedItems/" + item_id
    request_header = self.request_header()

    self.logger.debug(
        "Purging deleted item -> %s; calling -> %s",
        item_id,
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="DELETE",
        headers=request_header,
        timeout=REQUEST_TIMEOUT,
        failure_message="Failed to purge deleted item -> {}".format(item_id),
    )

purge_deleted_items()

Purge all deleted users and groups.

Purging users and groups requires administrative rights that typically are not provided in Contoso example org.

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def purge_deleted_items(self) -> None:
    """Purge all deleted users and groups.

    Purging users and groups requires administrative rights that typically
    are not provided in Contoso example org.
    """

    request_header = self.request_header()

    request_url = self.config()["directoryUrl"] + "/deletedItems/microsoft.graph.group"
    response = requests.get(
        request_url,
        headers=request_header,
        timeout=REQUEST_TIMEOUT,
    )
    deleted_groups = self.parse_request_response(response) or {}

    for group in deleted_groups.get("value", []):
        group_id = group["id"]
        response = self.purge_deleted_item(group_id)

    request_url = self.config()["directoryUrl"] + "/deletedItems/microsoft.graph.user"
    response = requests.get(
        request_url,
        headers=request_header,
        timeout=REQUEST_TIMEOUT,
    )
    deleted_users = self.parse_request_response(response) or {}

    for user in deleted_users.get("value", []):
        user_id = user["id"]
        response = self.purge_deleted_item(user_id)

remove_teams_app(app_id)

Remove MS Teams App from the app catalog.

Parameters:

Name Type Description Default
app_id str

The Microsoft 365 GUID of the MS Teams app.

required
Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def remove_teams_app(self, app_id: str) -> None:
    """Remove MS Teams App from the app catalog.

    Args:
        app_id (str):
            The Microsoft 365 GUID of the MS Teams app.

    """

    request_url = self.config()["teamsAppsUrl"] + "/" + app_id
    # Here we need the credentials of an authenticated user!
    # (not the application credentials (client_id, client_secret))
    request_header = self.request_header_user()

    # Make the DELETE request to remove the app from the app catalog
    response = requests.delete(
        request_url,
        headers=request_header,
        timeout=REQUEST_TIMEOUT,
    )

    # Check the status code of the response
    if response.status_code == 204:
        self.logger.debug(
            "The M365 Teams app with ID -> %s has been successfully removed from the app catalog.",
            app_id,
        )
    else:
        self.logger.error(
            "An error occurred while removing the M365 Teams app from the M365 app catalog. Status code -> %s. Error message -> %s",
            response.status_code,
            response.text,
        )

remove_teams_app_from_user(user_id, app_name, app_installation_id=None)

Remove a M365 Teams app from a M365 user.

See: https://learn.microsoft.com/en-us/graph/api/userteamwork-delete-installedapps?view=graph-rest-1.0&tabs=http

Parameters:

Name Type Description Default
user_id str

The M365 GUID of the user (can also be the M365 email of the user).

required
app_name str

The exact name of the app.

required
app_installation_id str | None

The installation ID of the app. Default is None.

None

Returns:

Name Type Description
dict dict | None

Response of the MS Graph API call or None if the call fails.

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def remove_teams_app_from_user(
    self,
    user_id: str,
    app_name: str,
    app_installation_id: str | None = None,
) -> dict | None:
    """Remove a M365 Teams app from a M365 user.

       See: https://learn.microsoft.com/en-us/graph/api/userteamwork-delete-installedapps?view=graph-rest-1.0&tabs=http

    Args:
        user_id (str):
            The M365 GUID of the user (can also be the M365 email of the user).
        app_name (str):
            The exact name of the app.
        app_installation_id (str | None):
            The installation ID of the app. Default is None.

    Returns:
        dict:
            Response of the MS Graph API call or None if the call fails.

    """

    if not app_installation_id:
        response = self.get_teams_apps_of_user(
            user_id=user_id,
            filter_expression="contains(teamsAppDefinition/displayName, '{}')".format(
                app_name,
            ),
        )
        # Retrieve the installation specific App ID - this is different from thew App catalalog ID!!
        app_installation_id = self.get_result_value(response=response, key="id", index=0)
    if not app_installation_id:
        self.logger.error(
            "M365 Teams app -> '%s' not found for user with ID -> %s. Cannot remove app from this user!",
            app_name,
            user_id,
        )
        return None

    request_url = self.config()["usersUrl"] + "/" + user_id + "/teamwork/installedApps/" + app_installation_id
    request_header = self.request_header()

    self.logger.debug(
        "Remove M365 Teams app -> '%s' (%s) from M365 user with ID -> %s; calling -> %s",
        app_name,
        app_installation_id,
        user_id,
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="DELETE",
        headers=request_header,
        timeout=REQUEST_TIMEOUT,
        failure_message="Failed to remove M365 Teams app -> '{}' ({}) from M365 user -> {}".format(
            app_name,
            app_installation_id,
            user_id,
        ),
    )

request_header(content_type='application/json')

Return the request header used for Application calls.

Consists of Bearer access token and Content Type.

Parameters:

Name Type Description Default
content_type str

The content type for the request. Default is "application/json".

'application/json'

Returns:

Name Type Description
dict dict

The request header values.

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def request_header(self, content_type: str = "application/json") -> dict:
    """Return the request header used for Application calls.

    Consists of Bearer access token and Content Type.

    Args:
        content_type (str, optional):
            The content type for the request. Default is "application/json".

    Returns:
        dict:
            The request header values.

    """

    request_header = {
        "Authorization": "Bearer {}".format(self._access_token),
        "Content-Type": content_type,
    }

    return request_header

request_header_user(content_type='application/json')

Return the request header used for user specific calls.

Consists of Bearer access token and Content Type.

Parameters:

Name Type Description Default
content_type str

The content type for the request.

'application/json'

Returns:

Name Type Description
dict dict

The request header values.

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def request_header_user(self, content_type: str = "application/json") -> dict:
    """Return the request header used for user specific calls.

    Consists of Bearer access token and Content Type.

    Args:
        content_type (str, optional):
            The content type for the request.

    Returns:
        dict:
            The request header values.

    """

    request_header = {
        "Content-Type": content_type,
    }

    if not self._user_access_token:
        self.logger.error("No M365 user is authenticated! Cannot include Bearer token in request header!")
    else:
        request_header["Authorization"] = "Bearer {}".format(self._user_access_token)

    return request_header

update_app_registration(app_registration_id, app_registration_name, api_permissions, supported_account_type='AzureADMyOrg')

Update an Azure App Registration.

Parameters:

Name Type Description Default
app_registration_id str

The ID of the existing App Registration.

required
app_registration_name str

The name of the App Registration.

required
api_permissions list

The API permissions.

required
supported_account_type str

The type of account that is supposed to use the App Registration.

'AzureADMyOrg'

Returns:

Name Type Description
dict dict

App Registration data or None of the request fails.

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def update_app_registration(
    self,
    app_registration_id: str,
    app_registration_name: str,
    api_permissions: list,
    supported_account_type: str = "AzureADMyOrg",
) -> dict:
    """Update an Azure App Registration.

    Args:
        app_registration_id (str):
            The ID of the existing App Registration.
        app_registration_name (str):
            The name of the App Registration.
        api_permissions (list):
            The API permissions.
        supported_account_type (str, optional):
            The type of account that is supposed to use
            the App Registration.

    Returns:
        dict:
            App Registration data or None of the request fails.

    """

    # Define the request body to create the App Registration
    app_registration_data = {
        "displayName": app_registration_name,
        "requiredResourceAccess": api_permissions,
        "signInAudience": supported_account_type,
    }

    request_url = self.config()["applicationsUrl"] + "/" + app_registration_id
    request_header = self.request_header()

    self.logger.debug(
        "Update App Registration -> '%s' (%s); calling -> %s",
        app_registration_name,
        app_registration_id,
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="PATCH",
        headers=request_header,
        json_data=app_registration_data,
        timeout=REQUEST_TIMEOUT,
        failure_message="Cannot update App Registration -> '{}' ({})".format(
            app_registration_name,
            app_registration_id,
        ),
    )

update_sharepoint_webpart(site_id, page_id, webpart_id, update_data, republish=True)

Update a data of a specific web part on a SharePoint page.

Any data elements not provided for the update will remain unchanged!

Parameters:

Name Type Description Default
site_id str

The ID of the SharePoint site.

required
page_id str

The ID of the SharePoint page containing the web part.

required
webpart_id str

The ID of the web part to update.

required
update_data dict

A dictionary with the updated data items that will be used to update the "data" structure of the webpart.

required
republish bool

If True, the page is republished to make the section active.

True

Returns:

Type Description
dict | None

dict | None: The updated web part. None in case of an error.

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def update_sharepoint_webpart(
    self,
    site_id: str,
    page_id: str,
    webpart_id: str,
    update_data: dict,
    republish: bool = True,
) -> dict | None:
    """Update a data of a specific web part on a SharePoint page.

    Any data elements not provided for the update will remain unchanged!

    Args:
        site_id (str):
            The ID of the SharePoint site.
        page_id (str):
            The ID of the SharePoint page containing the web part.
        webpart_id (str):
            The ID of the web part to update.
        update_data (dict):
            A dictionary with the updated data items that will be used
            to update the "data" structure of the webpart.
        republish (bool, optional):
            If True, the page is republished to make the section active.

    Returns:
        dict | None:
            The updated web part. None in case of an error.

    """

    def deep_merge(source: dict, destination: dict) -> dict:
        """Recursively merges source dictionary into destination dictionary.

        If a key exists in both, the value from destination is kept unless
        both values are dictionaries, in which case they are merged recursively.

        Args:
            source (dict):
                The dictionary with the current data values. Will be
                used if not updated data is in update_data for the particular key.
            destination (dict):
                The dictionary to merge into, which takes precedence.

        Returns:
            dict: The merged dictionary.

        """
        for key, value in source.items():
            if isinstance(value, dict) and key in destination and isinstance(destination[key], dict):
                # Recursively merge dictionaries if both values are dictionaries
                destination[key] = deep_merge(value, destination[key])
            else:
                # If key does not exist in destination, use value from source
                destination.setdefault(key, value)
        return destination

    # end deep_merge()

    webpart = self.get_sharepoint_webpart(site_id=site_id, page_id=page_id, webpart_id=webpart_id)
    if not webpart:
        self.logger.error(
            "Cannot find web part for site ID -> '%s', page -> '%s', webpart ID -> '%s'!",
            site_id,
            page_id,
            webpart_id,
        )
        return None
    webpart_type_id = webpart.get("webPartType")
    webpart_type_name = webpart.get("@odata.type")
    data = webpart.get("data")

    # Fill update_data with missing keys from data
    update_data = deep_merge(data, update_data)  # Merges, giving precedence to update_data

    # Construct the payload to update the specific property
    payload = {
        "@odata.type": webpart_type_name,  # likle "#microsoft.graph.standardWebPart" - this is mandatory!
        "webPartType": webpart_type_id,  # this is mandatory!
        "data": update_data,
    }

    request_url = (
        self.config()["sitesUrl"]
        + "/"
        + site_id
        + "/pages/"
        + page_id
        + "/microsoft.graph.sitePage/webparts/"
        + webpart_id
    )
    request_header = self.request_header()

    response = self.do_request(
        url=request_url,
        method="PATCH",
        json_data=payload,
        headers=request_header,
        timeout=REQUEST_TIMEOUT,
        failure_message="Cannot update SharePoint webpart -> '{}' on SharePoint page -> '{}' for Sharepoint site -> '{}', ".format(
            webpart_id,
            page_id,
            site_id,
        ),
    )
    # Check if the page should be republished:
    if response and republish:
        self.publish_sharepoint_page(site_id=site_id, page_id=page_id)

    return response

update_teams_app_of_channel(team_name, channel_name, tab_name, app_url, cs_node_id)

Update an existing tab for Extended ECM app in an M365 Team channel.

Parameters:

Name Type Description Default
team_name str

The name of the M365 Team.

required
channel_name str

The name of the channel.

required
tab_name str

The name of the tab.

required
app_url str

The web URL of the app.

required
cs_node_id int

The node ID of the target workspace or container in Content Server.

required

Returns:

Name Type Description
dict dict | None

Return data structure (dictionary) or None if the request fails.

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def update_teams_app_of_channel(
    self,
    team_name: str,
    channel_name: str,
    tab_name: str,
    app_url: str,
    cs_node_id: int,
) -> dict | None:
    """Update an existing tab for Extended ECM app in an M365 Team channel.

    Args:
        team_name (str):
            The name of the M365 Team.
        channel_name (str):
            The name of the channel.
        tab_name (str):
            The name of the tab.
        app_url (str):
            The web URL of the app.
        cs_node_id (int):
            The node ID of the target workspace or container in Content Server.

    Returns:
        dict:
            Return data structure (dictionary) or None if the request fails.

    """

    response = self.get_team(name=team_name)
    team_id = self.get_result_value(response=response, key="id", index=0)
    if not team_id:
        return None

    # Get the channels of the M365 Team:
    response = self.get_team_channels(name=team_name)
    if not response or not response["value"] or not response["value"][0]:
        return None

    # Look the channel by name and then retrieve its ID:
    channel = next(
        (item for item in response["value"] if item["displayName"] == channel_name),
        None,
    )
    if not channel:
        self.logger.error(
            "Cannot find Channel -> '%s' for M365 Team -> '%s'!",
            channel_name,
            team_name,
        )
        return None
    channel_id = channel["id"]

    # Get the tabs of the M365 Team channel:
    response = self.get_team_channel_tabs(team_name=team_name, channel_name=channel_name)
    if not response or not response["value"] or not response["value"][0]:
        return None

    # Look the tab by name and then retrieve its ID:
    tab = next(
        (item for item in response["value"] if item["displayName"] == tab_name),
        None,
    )
    if not tab:
        self.logger.error(
            "Cannot find Tab -> '%s' on M365 Team -> '%s' (%s) and Channel -> '%s' (%s)!",
            tab_name,
            team_name,
            team_id,
            channel_name,
            channel_id,
        )
        return None
    tab_id = tab["id"]

    request_url = (
        self.config()["teamsUrl"] + "/" + str(team_id) + "/channels/" + str(channel_id) + "/tabs/" + str(tab_id)
    )

    request_header = self.request_header()

    # Create tab configuration payload:
    tab_config = {
        "configuration": {
            "entityId": cs_node_id,  # Unique identifier for the tab
            "contentUrl": app_url,
            "removeUrl": "",
            "websiteUrl": app_url + "&showBW=true&title=" + tab_name,
        },
    }

    self.logger.debug(
        "Update Tab -> '%s' (%s) of Channel -> '%s' (%s) for Microsoft 365 Teams -> '%s' (%s) with configuration -> %s; calling -> %s",
        tab_name,
        tab_id,
        channel_name,
        channel_id,
        team_name,
        team_id,
        str(tab_config),
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="PATCH",
        headers=request_header,
        json_data=tab_config,
        timeout=REQUEST_TIMEOUT,
        failure_message="Failed to update Tab -> '{}' ({}) for M365 Team -> '{}' ({}) and Channel -> '{}' ({})".format(
            tab_name,
            tab_id,
            team_name,
            team_id,
            channel_name,
            channel_id,
        ),
    )

update_user(user_id, updated_settings)

Update selected properties of an M365 user.

Documentation on user properties is here: https://learn.microsoft.com/en-us/graph/api/user-update

Parameters:

Name Type Description Default
user_id str

The ID of the user (can also be email). This is also the unique identifier.

required
updated_settings dict

The new data to update the user with.

required

Returns:

Type Description
dict | None

dict | None: Response of the M365 Graph API or None if the call fails.

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def update_user(self, user_id: str, updated_settings: dict) -> dict | None:
    """Update selected properties of an M365 user.

    Documentation on user properties is here: https://learn.microsoft.com/en-us/graph/api/user-update

    Args:
        user_id (str):
            The ID of the user (can also be email). This is also the unique identifier.
        updated_settings (dict):
            The new data to update the user with.

    Returns:
        dict | None:
            Response of the M365 Graph API  or None if the call fails.

    """

    request_url = self.config()["usersUrl"] + "/" + user_id
    request_header = self.request_header()

    self.logger.debug(
        "Updating M365 user with ID -> %s with -> %s; calling -> %s",
        user_id,
        str(updated_settings),
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="PATCH",
        headers=request_header,
        json_data=updated_settings,
        timeout=REQUEST_TIMEOUT,
        failure_message="Failed to update M365 user -> '{}' with -> {}".format(
            user_id,
            updated_settings,
        ),
    )

update_user_photo(user_id, photo_path)

Update the M365 user photo.

Parameters:

Name Type Description Default
user_id str

The M365 GUID of the user (can also be the M365 email of the user).

required
photo_path str

The file system path with the location of the photo file.

required

Returns:

Type Description
dict | None

dict | None: Response of Graph REST API or None if the user photo couldn't be updated.

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def update_user_photo(self, user_id: str, photo_path: str) -> dict | None:
    """Update the M365 user photo.

    Args:
        user_id (str):
            The M365 GUID of the user (can also be the M365 email of the user).
        photo_path (str):
            The file system path with the location of the photo file.

    Returns:
        dict | None:
            Response of Graph REST API or None if the user photo couldn't be updated.

    """

    request_url = self.config()["usersUrl"] + "/" + user_id + "/photo/$value"
    # Set image as content type:
    request_header = self.request_header("image/*")

    # Check if the photo file exists
    if not os.path.isfile(photo_path):
        self.logger.error("Photo file -> %s not found!", photo_path)
        return None

    try:
        # Read the photo file as binary data
        with open(photo_path, "rb") as image_file:
            photo_data = image_file.read()
    except OSError:
        # Handle any errors that occurred while reading the photo file
        self.logger.error(
            "Error reading photo file -> %s!",
            photo_path,
        )
        return None

    data = photo_data

    self.logger.debug(
        "Update M365 user with ID -> %s with photo -> %s; calling -> %s",
        user_id,
        photo_path,
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="PUT",
        headers=request_header,
        data=data,
        timeout=REQUEST_TIMEOUT,
        failure_message="Failed to update M365 user with ID -> {} with photo -> '{}'".format(
            user_id,
            photo_path,
        ),
    )

upgrade_teams_app_of_team(team_id, app_name)

Upgrade a MS teams app for a specific team.

The call will fail if the team does not already have the app assigned. So this needs to be checked before calling this method.

THIS IS CURRENTLY NOT WORKING AS EXPECTED.

Parameters:

Name Type Description Default
team_id str

M365 GUID of the user (can also be the M365 email of the user).

required
app_name str

The exact name of the app.

required

Returns:

Name Type Description
dict dict | None

The response of the MS Graph API call or None if the call fails.

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def upgrade_teams_app_of_team(self, team_id: str, app_name: str) -> dict | None:
    """Upgrade a MS teams app for a specific team.

    The call will fail if the team does not already have the app assigned.
    So this needs to be checked before calling this method.

    THIS IS CURRENTLY NOT WORKING AS EXPECTED.

    Args:
        team_id (str):
            M365 GUID of the user (can also be the M365 email of the user).
        app_name (str):
            The exact name of the app.

    Returns:
        dict:
            The response of the MS Graph API call or None if the call fails.

    """

    response = self.get_teams_apps_of_team(
        team_id=team_id,
        filter_expression="contains(teamsAppDefinition/displayName, '{}')".format(app_name),
    )
    # Retrieve the installation specific App ID - this is different from thew App catalalog ID!!
    app_installation_id = self.get_result_value(response=response, key="id", index=0)
    if not app_installation_id:
        self.logger.error(
            "M365 Teams app -> '%s' not found for M365 Team with ID -> %s. Cannot upgrade app for this team!",
            app_name,
            team_id,
        )
        return None

    request_url = self.config()["teamsUrl"] + "/" + team_id + "/installedApps/" + app_installation_id + "/upgrade"
    request_header = self.request_header()

    self.logger.debug(
        "Upgrade app -> '%s' (%s) of M365 team with ID -> %s; calling -> %s",
        app_name,
        app_installation_id,
        team_id,
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="POST",
        headers=request_header,
        timeout=REQUEST_TIMEOUT,
        failure_message="Failed to upgrade M365 Teams app -> '{}' ({}) of M365 team with ID -> {}".format(
            app_name,
            app_installation_id,
            team_id,
        ),
    )

upgrade_teams_app_of_user(user_id, app_name, app_installation_id=None)

Upgrade a MS teams app for a user.

The call will fail if the user does not already have the app assigned. So this needs to be checked before calling this method.

See: https://learn.microsoft.com/en-us/graph/api/userteamwork-teamsappinstallation-upgrade?view=graph-rest-1.0&tabs=http

Parameters:

Name Type Description Default
user_id str

The M365 GUID of the user (can also be the M365 email of the user).

required
app_name str

The exact name of the app.

required
app_installation_id str | None

The ID of the app installation for the user. This is neither the internal nor external app ID. It is specific for each user and app.

None

Returns:

Type Description
dict | None

dict | None: Response of the MS Graph API call or None if the call fails.

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def upgrade_teams_app_of_user(
    self,
    user_id: str,
    app_name: str,
    app_installation_id: str | None = None,
) -> dict | None:
    """Upgrade a MS teams app for a user.

    The call will fail if the user does not already have the app assigned.
    So this needs to be checked before calling this method.

    See: https://learn.microsoft.com/en-us/graph/api/userteamwork-teamsappinstallation-upgrade?view=graph-rest-1.0&tabs=http

    Args:
        user_id (str):
            The M365 GUID of the user (can also be the M365 email of the user).
        app_name (str):
            The exact name of the app.
        app_installation_id (str | None, optional):
            The ID of the app installation for the user. This is neither the internal nor
            external app ID. It is specific for each user and app.

    Returns:
        dict | None:
            Response of the MS Graph API call or None if the call fails.

    """

    if not app_installation_id:
        response = self.get_teams_apps_of_user(
            user_id=user_id,
            filter_expression="contains(teamsAppDefinition/displayName, '{}')".format(
                app_name,
            ),
        )
        # Retrieve the installation specific App ID - this is different from thew App catalalog ID!!
        app_installation_id = self.get_result_value(response=response, key="id", index=0)
    if not app_installation_id:
        self.logger.error(
            "M365 Teams app -> '%s' not found for user with ID -> %s. Cannot upgrade app for this user!",
            app_name,
            user_id,
        )
        return None

    request_url = (
        self.config()["usersUrl"] + "/" + user_id + "/teamwork/installedApps/" + app_installation_id + "/upgrade"
    )
    request_header = self.request_header()

    self.logger.debug(
        "Upgrade M365 Teams app -> '%s' (%s) of M365 user with ID -> %s; calling -> %s",
        app_name,
        app_installation_id,
        user_id,
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="POST",
        headers=request_header,
        timeout=REQUEST_TIMEOUT,
        failure_message="Failed to upgrade M365 Teams app -> '{}' ({}) of M365 user -> {}".format(
            app_name,
            app_installation_id,
            user_id,
        ),
    )

upload_outlook_app(app_path)

Upload the M365 Outlook Add-In as "Integrated" App to M365 Admin Center.

TODO: THIS IS CURRENTLY NOT IMPLEMENTED DUE TO MISSING MS GRAPH API SUPPORT!

https://admin.microsoft.com/#/Settings/IntegratedApps

Parameters:

Name Type Description Default
app_path str

Path to manifest file in local file system. Needs to be downloaded before.

required

Returns:

Type Description
dict | None

dict | None: Response of the MS Graph API or None if the request fails.

Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def upload_outlook_app(
    self,
    app_path: str,
) -> dict | None:
    """Upload the M365 Outlook Add-In as "Integrated" App to M365 Admin Center.

    TODO: THIS IS CURRENTLY NOT IMPLEMENTED DUE TO MISSING MS GRAPH API SUPPORT!

    https://admin.microsoft.com/#/Settings/IntegratedApps

    Args:
        app_path (str):
            Path to manifest file in local file system. Needs to be
            downloaded before.

    Returns:
        dict | None:
            Response of the MS Graph API or None if the request fails.

    """

    self.logger.debug(
        "Install Outlook Add-in from -> '%s' (NOT IMPLEMENTED)",
        app_path,
    )

    response = None

    return response

upload_teams_app(app_path, update_existing_app=False, app_catalog_id='')

Upload a new app package to the catalog of MS Teams apps.

This is not possible with client secret credentials but requires a token of a user authenticated with username + password. See https://learn.microsoft.com/en-us/graph/api/teamsapp-publish (permissions table on that page).

For updates see: https://learn.microsoft.com/en-us/graph/api/teamsapp-update?view=graph-rest-1.0&tabs=http

Parameters:

Name Type Description Default
app_path str

The file path (with directory) to the app package to upload.

required
update_existing_app bool

Whether or not to update an existing app with the same name.

False
app_catalog_id str

The unique ID of the app. It is the ID the app has in the catalog - which is different from ID an app gets after installation (which is tenant specific).

''

Returns:

Name Type Description
dict dict | None

Response of the MS GRAPH API REST call or None if the request fails The responses are different depending if it is an install or upgrade!!

Example return for upgrades ("teamsAppId" is the "internal" ID of the app): { '@odata.context': "https://graph.microsoft.com/v1.0/$metadata#appCatalogs/teamsApps('3f749cca-8cb0-4925-9fa0-ba7aca2014af')/appDefinitions/$entity", 'id': 'M2Y3NDljY2EtOGNiMC00OTI1LTlmYTAtYmE3YWNhMjAxNGFmIyMyNC4yLjAjI1B1Ymxpc2hlZA==', 'teamsAppId': '3f749cca-8cb0-4925-9fa0-ba7aca2014af', 'displayName': 'IDEA-TE - Extended ECM 24.2.0', 'version': '24.2.0', 'publishingState': 'published', 'shortDescription': 'Add a tab for an Extended ECM business workspace.', 'description': 'View and interact with OpenText Extended ECM business workspaces', 'lastModifiedDateTime': None, 'createdBy': None, 'authorization': { 'requiredPermissionSet': {...} } }

Example return for new installations ("id" is the "internal" ID of the app):
{
    '@odata.context': 'https://graph.microsoft.com/v1.0/$metadata#appCatalogs/teamsApps/$entity',
    'id': '6c672afd-37fc-46c6-8365-d499aba3808b',
    'externalId': 'dd4af790-d8ff-47a0-87ad-486318272c7a',
    'displayName': 'OpenText Extended ECM',
    'distributionMethod': 'organization'
}
Source code in packages/pyxecm/src/pyxecm_customizer/m365.py
def upload_teams_app(
    self,
    app_path: str,
    update_existing_app: bool = False,
    app_catalog_id: str = "",
) -> dict | None:
    """Upload a new app package to the catalog of MS Teams apps.

    This is not possible with client secret credentials
    but requires a token of a user authenticated with username + password.
    See https://learn.microsoft.com/en-us/graph/api/teamsapp-publish
    (permissions table on that page).

    For updates see: https://learn.microsoft.com/en-us/graph/api/teamsapp-update?view=graph-rest-1.0&tabs=http

    Args:
        app_path (str):
            The file path (with directory) to the app package to upload.
        update_existing_app (bool, optional):
            Whether or not to update an existing app with the same name.
        app_catalog_id (str, optional):
            The unique ID of the app. It is the ID the app has in
            the catalog - which is different from ID an app gets
            after installation (which is tenant specific).

    Returns:
        dict:
            Response of the MS GRAPH API REST call or None if the request fails
            The responses are different depending if it is an install or upgrade!!

    Example return for upgrades ("teamsAppId" is the "internal" ID of the app):
        {
            '@odata.context': "https://graph.microsoft.com/v1.0/$metadata#appCatalogs/teamsApps('3f749cca-8cb0-4925-9fa0-ba7aca2014af')/appDefinitions/$entity",
            'id': 'M2Y3NDljY2EtOGNiMC00OTI1LTlmYTAtYmE3YWNhMjAxNGFmIyMyNC4yLjAjI1B1Ymxpc2hlZA==',
            'teamsAppId': '3f749cca-8cb0-4925-9fa0-ba7aca2014af',
            'displayName': 'IDEA-TE - Extended ECM 24.2.0',
            'version': '24.2.0',
            'publishingState': 'published',
            'shortDescription': 'Add a tab for an Extended ECM business workspace.',
            'description': 'View and interact with OpenText Extended ECM business workspaces',
            'lastModifiedDateTime': None,
            'createdBy': None,
            'authorization': {
                'requiredPermissionSet': {...}
            }
        }

        Example return for new installations ("id" is the "internal" ID of the app):
        {
            '@odata.context': 'https://graph.microsoft.com/v1.0/$metadata#appCatalogs/teamsApps/$entity',
            'id': '6c672afd-37fc-46c6-8365-d499aba3808b',
            'externalId': 'dd4af790-d8ff-47a0-87ad-486318272c7a',
            'displayName': 'OpenText Extended ECM',
            'distributionMethod': 'organization'
        }

    """

    if update_existing_app and not app_catalog_id:
        self.logger.error(
            "To update an existing M365 Teams app in the app catalog you need to provide the existing App catalog ID!",
        )
        return None

    if not os.path.exists(app_path):
        self.logger.error("M365 Teams app file -> %s does not exist!", app_path)
        return None

    # Ensure that the app file is a zip file
    if not app_path.endswith(".zip"):
        self.logger.error("M365 Teams app file -> %s must be a zip file!", app_path)
        return None

    request_url = self.config()["teamsAppsUrl"]
    # If we want to upgrade an existing app we add the app ID and
    # the specific endpoint:
    if update_existing_app:
        request_url += "/" + app_catalog_id + "/appDefinitions"

    # Here we need the credentials of an authenticated user!
    # (not the application credentials (client_id, client_secret))
    request_header = self.request_header_user(content_type="application/zip")

    with open(app_path, "rb") as f:
        app_data = f.read()

    with zipfile.ZipFile(app_path) as z:
        # Ensure that the app file contains a manifest.json file
        if "manifest.json" not in z.namelist():
            self.logger.error(
                "M365 Teams app file -> '%s' does not contain a manifest.json file!",
                app_path,
            )
            return None

    self.logger.debug(
        "Upload M365 Teams app -> '%s' to the MS Teams catalog; calling -> %s",
        app_path,
        request_url,
    )

    return self.do_request(
        url=request_url,
        method="POST",
        headers=request_header,
        data=app_data,
        timeout=REQUEST_TIMEOUT,
        failure_message="Failed to update existing M365 Teams app -> '{}' (may be because it is not a new version)".format(
            app_path,
        ),
    )