1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 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
use crate::black_list::contains;
use crate::configuration::{get_ua, Configuration};
use crate::packages::robotparser::parser::RobotFileParser;
use crate::page::{build, get_page_selectors, Page};
use crate::utils::log;
use crate::CaseInsensitiveString;
#[cfg(feature = "cron")]
use async_trait::async_trait;
use compact_str::CompactString;
#[cfg(feature = "budget")]
use hashbrown::HashMap;
use hashbrown::HashSet;
use reqwest::Client;
#[cfg(not(feature = "napi"))]
use std::io::{Error, ErrorKind};
use std::sync::atomic::{AtomicI8, Ordering};
use std::sync::Arc;
use std::time::Duration;
use tokio::runtime::Handle;
use tokio::sync::{broadcast, Semaphore};
use tokio::task;
use tokio::task::JoinSet;
use tokio_stream::StreamExt;
use url::Url;
#[cfg(feature = "napi")]
use napi::bindgen_prelude::*;
#[cfg(feature = "chrome")]
use crate::features::chrome::launch_browser;
#[cfg(not(feature = "decentralized"))]
lazy_static! {
static ref SEM: Semaphore = {
let logical = num_cpus::get();
let physical = num_cpus::get_physical();
let sem_limit = if logical > physical {
(logical) / (physical) as usize
} else {
logical
};
let (sem_limit, sem_max) = if logical == physical {
(sem_limit * physical, 50)
} else {
(sem_limit * 4, 25)
};
let sem_limit = if cfg!(feature = "chrome") {
sem_limit / 2
} else {
sem_limit
};
Semaphore::const_new(sem_limit.max(sem_max))
};
}
#[cfg(feature = "decentralized")]
lazy_static! {
static ref WORKERS: HashSet<String> = {
let mut set: HashSet<_> = HashSet::new();
for worker in std::env::var("SPIDER_WORKER_SCRAPER")
.unwrap_or_else(|_| "http://127.0.0.1:3031".to_string())
.split(",")
{
set.insert(worker.to_string());
}
for worker in std::env::var("SPIDER_WORKER")
.unwrap_or_else(|_| "http://127.0.0.1:3030".to_string())
.split(",")
{
set.insert(worker.to_string());
}
set
};
static ref SEM: Semaphore = {
let logical = num_cpus::get();
let physical = num_cpus::get_physical();
let sem_limit = if logical > physical {
(logical) / (physical) as usize
} else {
logical
};
let (sem_limit, sem_max) = if logical == physical {
(sem_limit * physical, 75)
} else {
(sem_limit * 4, 33)
};
let (sem_limit, sem_max) = { (sem_limit * WORKERS.len(), sem_max * WORKERS.len()) };
Semaphore::const_new(sem_limit.max(sem_max))
};
}
/// the active status of the crawl.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub enum CrawlStatus {
/// The crawl did not start yet.
#[default]
Start,
/// The crawl is idle and has completed.
Idle,
/// The crawl is active.
Active,
/// The crawl blocked from network ratelimit, firewall, etc.
Blocked,
/// The initial request ran without returning html.
Empty,
#[cfg(feature = "control")]
/// The crawl shutdown manually.
Shutdown,
#[cfg(feature = "control")]
/// The crawl paused manually.
Paused,
}
#[cfg(feature = "cron")]
/// The type of cron job to run
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub enum CronType {
#[default]
/// Crawl collecting links, page data, and etc.
Crawl,
/// Scrape collecting links, page data as bytes to store, and etc.
Scrape,
}
/// Represents a website to crawl and gather all links.
/// ```rust
/// use spider::website::Website;
/// let mut website = Website::new("http://example.com");
/// website.crawl();
/// // `Website` will be filled with `Pages` when crawled. To get them, just use
/// while let Some(page) = website.get_pages() {
/// // do something
/// }
/// ```
#[derive(Debug, Clone, Default)]
pub struct Website {
/// Configuration properties for website.
pub configuration: Box<Configuration>,
/// All URLs visited.
links_visited: Box<HashSet<CaseInsensitiveString>>,
/// Pages visited.
pages: Option<Box<Vec<Page>>>,
/// Robot.txt parser.
robot_file_parser: Option<Box<RobotFileParser>>,
/// Base root domain of the crawl.
domain: Box<CaseInsensitiveString>,
/// The domain url parsed.
domain_parsed: Option<Box<Url>>,
/// The callback when a link is found.
pub on_link_find_callback: Option<
fn(CaseInsensitiveString, Option<String>) -> (CaseInsensitiveString, Option<String>),
>,
/// Subscribe and broadcast changes.
channel: Option<Arc<(broadcast::Sender<Page>, broadcast::Receiver<Page>)>>,
/// The status of the active crawl.
status: CrawlStatus,
/// External domains to include in the crawl if found.
pub external_domains: Box<HashSet<String>>,
/// External domains to include case-insensitive.
external_domains_caseless: Box<HashSet<CaseInsensitiveString>>,
#[cfg(feature = "budget")]
/// Crawl budget for the paths. This helps prevent crawling extra pages and limiting the amount.
pub budget: Option<HashMap<CaseInsensitiveString, u32>>,
#[cfg(feature = "cookies")]
/// Cookie string to use for network requests ex: "foo=bar; Domain=blog.spider"
pub cookie_str: String,
#[cfg(feature = "cron")]
/// Cron string to perform crawls - use <https://crontab.guru/> to help generate a valid cron for needs.
pub cron_str: String,
#[cfg(feature = "cron")]
/// The type of cron to run either crawl or scrape
pub cron_type: CronType,
}
impl Website {
/// Initialize Website object with a start link to crawl.
pub fn new(domain: &str) -> Self {
Self {
configuration: Configuration::new().into(),
links_visited: Box::new(HashSet::new()),
pages: None,
robot_file_parser: None,
domain: CaseInsensitiveString::new(domain).into(),
domain_parsed: match url::Url::parse(domain) {
Ok(u) => Some(Box::new(crate::page::convert_abs_path(&u, "/"))),
_ => None,
},
on_link_find_callback: None,
channel: None,
status: CrawlStatus::Start,
..Default::default()
}
}
/// return `true` if URL:
///
/// - is not already crawled
/// - is not blacklisted
/// - is not forbidden in robot.txt file (if parameter is defined)
#[inline]
#[cfg(all(not(feature = "regex"), not(feature = "budget")))]
pub fn is_allowed(
&self,
link: &CaseInsensitiveString,
blacklist_url: &Box<Vec<CompactString>>,
) -> bool {
if self.links_visited.contains(link) {
false
} else {
self.is_allowed_default(&link.inner(), blacklist_url)
}
}
/// return `true` if URL:
///
/// - is not already crawled
/// - is not over crawl budget
/// - is not blacklisted
/// - is not forbidden in robot.txt file (if parameter is defined)
#[inline]
#[cfg(all(not(feature = "regex"), feature = "budget"))]
pub fn is_allowed(
&mut self,
link: &CaseInsensitiveString,
blacklist_url: &Box<Vec<CompactString>>,
) -> bool {
if self.links_visited.contains(link) {
false
} else if self.is_over_budget(&link) {
false
} else {
self.is_allowed_default(&link.inner(), blacklist_url)
}
}
/// return `true` if URL:
///
/// - is not already crawled
/// - is not blacklisted
/// - is not forbidden in robot.txt file (if parameter is defined)
#[inline]
#[cfg(all(feature = "regex", not(feature = "budget")))]
pub fn is_allowed(
&self,
link: &CaseInsensitiveString,
blacklist_url: &Box<regex::RegexSet>,
) -> bool {
if self.links_visited.contains(link) {
false
} else {
self.is_allowed_default(link, blacklist_url)
}
}
/// return `true` if URL:
///
/// - is not already crawled
/// - is not over crawl budget
/// - is not blacklisted
/// - is not forbidden in robot.txt file (if parameter is defined)
#[inline]
#[cfg(all(feature = "regex", feature = "budget"))]
pub fn is_allowed(
&mut self,
link: &CaseInsensitiveString,
blacklist_url: &Box<regex::RegexSet>,
) -> bool {
if self.links_visited.contains(link) {
false
} else if self.is_over_budget(&link) {
false
} else {
self.is_allowed_default(link, blacklist_url)
}
}
/// return `true` if URL:
///
/// - is not blacklisted
/// - is not forbidden in robot.txt file (if parameter is defined)
#[inline]
#[cfg(feature = "regex")]
pub fn is_allowed_default(
&self,
link: &CaseInsensitiveString,
blacklist_url: &Box<regex::RegexSet>,
) -> bool {
if !blacklist_url.is_empty() {
!contains(blacklist_url, &link.inner())
} else {
self.is_allowed_robots(&link.as_ref())
}
}
/// return `true` if URL:
///
/// - is not blacklisted
/// - is not forbidden in robot.txt file (if parameter is defined)
#[inline]
#[cfg(not(feature = "regex"))]
pub fn is_allowed_default(
&self,
link: &CompactString,
blacklist_url: &Box<Vec<CompactString>>,
) -> bool {
if contains(blacklist_url, &link) {
false
} else {
self.is_allowed_robots(&link)
}
}
/// return `true` if URL:
///
/// - is not forbidden in robot.txt file (if parameter is defined)
pub fn is_allowed_robots(&self, link: &str) -> bool {
if self.configuration.respect_robots_txt {
unsafe {
self.robot_file_parser
.as_ref()
.unwrap_unchecked()
.can_fetch("*", &link)
} // unwrap will always return
} else {
true
}
}
#[cfg(feature = "budget")]
/// Validate if url exceeds crawl budget and should not be handled.
pub fn is_over_budget(&mut self, link: &CaseInsensitiveString) -> bool {
if self.budget.is_some() {
match Url::parse(&link.inner()) {
Ok(r) => {
match self.budget.as_mut() {
Some(budget) => {
let wild = CaseInsensitiveString::from("*");
let has_wildpath = budget.contains_key(&wild);
let exceeded_wild_budget = if has_wildpath {
match budget.get_mut(&wild) {
Some(budget) => {
if budget.abs_diff(0) == 1 {
true
} else {
*budget -= 1;
false
}
}
_ => false,
}
} else {
false
};
// set this up prior to crawl to avoid checks per link
let skip_paths = has_wildpath && budget.len() == 1;
// check if paths pass
if !skip_paths && !exceeded_wild_budget {
match r.path_segments() {
Some(mut segments) => {
let mut joint_segment = String::new();
let mut over = false;
while let Some(seg) = segments.next() {
let next_segment = string_concat!(joint_segment, seg);
let caseless_segment =
CaseInsensitiveString::from(next_segment);
if budget.contains_key(&caseless_segment) {
match budget.get_mut(&caseless_segment) {
Some(budget) => {
if budget.abs_diff(0) == 0 {
over = true;
break;
} else {
*budget -= 1;
continue;
}
}
_ => (),
};
}
joint_segment = joint_segment;
}
over
}
_ => false,
}
} else {
exceeded_wild_budget
}
}
_ => false,
}
}
_ => false,
}
} else {
false
}
}
/// page getter
pub fn get_pages(&self) -> Option<&Box<Vec<Page>>> {
self.pages.as_ref()
}
/// links visited getter
pub fn get_links(&self) -> &HashSet<CaseInsensitiveString> {
&self.links_visited
}
/// domain parsed url getter
pub fn get_domain_parsed(&self) -> &Option<Box<Url>> {
&self.domain_parsed
}
/// domain name getter
pub fn get_domain(&self) -> &CaseInsensitiveString {
&self.domain
}
/// crawl delay getter
fn get_delay(&self) -> Duration {
Duration::from_millis(self.configuration.delay)
}
/// get the active crawl status
pub fn get_status(&self) -> &CrawlStatus {
&self.status
}
/// absolute base url of crawl
pub fn get_absolute_path(&self, domain: Option<&str>) -> Option<Url> {
if domain.is_some() {
match url::Url::parse(domain.unwrap_or_default()) {
Ok(u) => Some(crate::page::convert_abs_path(&u, "/")),
_ => None,
}
} else {
self.domain_parsed.as_deref().cloned()
}
}
/// configure the robots parser on initial crawl attempt and run.
pub async fn configure_robots_parser(&mut self, client: Client) -> Client {
if self.configuration.respect_robots_txt {
let robot_file_parser = self
.robot_file_parser
.get_or_insert_with(|| RobotFileParser::new());
if robot_file_parser.mtime() <= 4000 {
let host_str = match &self.domain_parsed {
Some(domain) => &*domain.as_str(),
_ => &self.domain.inner(),
};
if host_str.ends_with("/") {
robot_file_parser.read(&client, &host_str).await;
} else {
robot_file_parser
.read(&client, &string_concat!(host_str, "/"))
.await;
}
self.configuration.delay = robot_file_parser
.get_crawl_delay(&self.configuration.user_agent) // returns the crawl delay in seconds
.unwrap_or_else(|| self.get_delay())
.as_millis() as u64;
}
}
client
}
/// build the http client
#[cfg(not(feature = "decentralized"))]
fn configure_http_client_builder(&mut self) -> reqwest::ClientBuilder {
let host_str = self.domain_parsed.as_deref().cloned();
let default_policy = reqwest::redirect::Policy::default();
let policy = match host_str {
Some(host_s) => reqwest::redirect::Policy::custom(move |attempt| {
if attempt.url().host_str() != host_s.host_str() {
attempt.stop()
} else {
default_policy.redirect(attempt)
}
}),
_ => default_policy,
};
let client = Client::builder()
.user_agent(match &self.configuration.user_agent {
Some(ua) => ua.as_str(),
_ => &get_ua(),
})
.redirect(policy)
.tcp_keepalive(Duration::from_millis(500))
.pool_idle_timeout(None);
let client = if self.configuration.http2_prior_knowledge {
client.http2_prior_knowledge()
} else {
client
};
let client = match &self.configuration.headers {
Some(headers) => client.default_headers(*headers.to_owned()),
_ => client,
};
let mut client = match &self.configuration.request_timeout {
Some(t) => client.timeout(**t),
_ => client,
};
let client = match &self.configuration.proxies {
Some(proxies) => {
for proxie in proxies.iter() {
match reqwest::Proxy::all(proxie) {
Ok(proxy) => client = client.proxy(proxy),
_ => (),
}
}
client
}
_ => client,
};
client
}
/// configure http client
#[cfg(all(not(feature = "decentralized"), not(feature = "cookies")))]
pub fn configure_http_client(&mut self) -> Client {
let client = self.configure_http_client_builder();
// should unwrap using native-tls-alpn
unsafe { client.build().unwrap_unchecked() }
}
/// build the client with cookie configurations
#[cfg(all(not(feature = "decentralized"), feature = "cookies"))]
pub fn configure_http_client(&mut self) -> Client {
let client = self.configure_http_client_builder();
let client = client.cookie_store(true);
let client = if !self.cookie_str.is_empty() && self.domain_parsed.is_some() {
match self.domain_parsed.clone() {
Some(p) => {
let cookie_store = reqwest::cookie::Jar::default();
cookie_store.add_cookie_str(&self.cookie_str, &p);
client.cookie_provider(cookie_store.into())
}
_ => client,
}
} else {
client
};
// should unwrap using native-tls-alpn
unsafe { client.build().unwrap_unchecked() }
}
/// configure http client for decentralization
#[cfg(feature = "decentralized")]
pub fn configure_http_client(&mut self) -> Client {
use reqwest::header::HeaderMap;
use reqwest::header::HeaderValue;
let mut headers = HeaderMap::new();
let host_str = self.domain_parsed.take();
let default_policy = reqwest::redirect::Policy::default();
let policy = match host_str {
Some(host_s) => reqwest::redirect::Policy::custom(move |attempt| {
if attempt.url().host_str() != host_s.host_str() {
attempt.stop()
} else {
default_policy.redirect(attempt)
}
}),
_ => default_policy,
};
let mut client = Client::builder()
.user_agent(match &self.configuration.user_agent {
Some(ua) => ua.as_str(),
_ => &get_ua(),
})
.redirect(policy)
.tcp_keepalive(Duration::from_millis(500))
.pool_idle_timeout(None);
let referer = if self.configuration.tld && self.configuration.subdomains {
2
} else if self.configuration.tld {
2
} else if self.configuration.subdomains {
1
} else {
0
};
if referer > 0 {
// use expected http headers for providers that drop invalid headers
headers.insert(reqwest::header::REFERER, HeaderValue::from(referer));
}
match &self.configuration.headers {
Some(h) => headers.extend(*h.to_owned()),
_ => (),
};
match self.get_absolute_path(None) {
Some(domain_url) => {
let domain_url = domain_url.as_str();
let domain_host = if domain_url.ends_with("/") {
&domain_url[0..domain_url.len() - 1]
} else {
domain_url
};
match HeaderValue::from_str(domain_host) {
Ok(value) => {
headers.insert(reqwest::header::HOST, value);
}
_ => (),
}
}
_ => (),
}
for worker in WORKERS.iter() {
match reqwest::Proxy::all(worker) {
Ok(worker) => {
client = client.proxy(worker);
}
_ => (),
}
}
// should unwrap using native-tls-alpn
unsafe {
match &self.configuration.request_timeout {
Some(t) => client.timeout(**t),
_ => client,
}
.default_headers(headers)
.build()
.unwrap_unchecked()
}
}
/// setup atomic controller
#[cfg(feature = "control")]
fn configure_handler(&self) -> Arc<AtomicI8> {
use crate::utils::{Handler, CONTROLLER};
let paused = Arc::new(AtomicI8::new(0));
let handle = paused.clone();
let domain = self.domain.inner().clone();
tokio::spawn(async move {
let mut l = CONTROLLER.lock().await.1.to_owned();
while l.changed().await.is_ok() {
let n = &*l.borrow();
let (target, rest) = n;
if domain.eq_ignore_ascii_case(&target) {
if rest == &Handler::Resume {
paused.store(0, Ordering::Relaxed);
}
if rest == &Handler::Pause {
paused.store(1, Ordering::Relaxed);
}
if rest == &Handler::Shutdown {
paused.store(2, Ordering::Relaxed);
}
}
}
});
handle
}
/// setup config for crawl
#[cfg(feature = "control")]
async fn setup(&mut self) -> (Client, Option<Arc<AtomicI8>>) {
let client = self.configure_http_client();
// allow fresh crawls to run fully
if !self.links_visited.is_empty() {
self.links_visited.clear();
}
(
self.configure_robots_parser(client).await,
Some(self.configure_handler()),
)
}
/// setup config for crawl
#[cfg(not(feature = "control"))]
async fn setup<T>(&mut self) -> (Client, Option<T>) {
let client = self.configure_http_client();
// allow fresh crawls to run fully
if !self.links_visited.is_empty() {
self.links_visited.clear();
}
(self.configure_robots_parser(client).await, None)
}
/// setup selectors for handling link targets
fn setup_selectors(&self) -> Option<(CompactString, smallvec::SmallVec<[CompactString; 2]>)> {
get_page_selectors(
&self.domain.inner(),
self.configuration.subdomains,
self.configuration.tld,
)
}
/// setup shared concurrent configs
fn setup_crawl(
&mut self,
) -> (
std::pin::Pin<Box<tokio::time::Interval>>,
std::pin::Pin<Box<Duration>>,
) {
self.status = CrawlStatus::Active;
let interval = Box::pin(tokio::time::interval(Duration::from_millis(10)));
let throttle = Box::pin(self.get_delay());
(interval, throttle)
}
/// get base link for crawl establishing
#[cfg(feature = "regex")]
fn get_base_link(&self) -> &CaseInsensitiveString {
&self.domain
}
/// get base link for crawl establishing
#[cfg(not(feature = "regex"))]
fn get_base_link(&self) -> &CompactString {
self.domain.inner()
}
/// expand links for crawl
async fn _crawl_establish(
&mut self,
client: &Client,
base: &(CompactString, smallvec::SmallVec<[CompactString; 2]>),
_: bool,
) -> HashSet<CaseInsensitiveString> {
let links: HashSet<CaseInsensitiveString> = if self
.is_allowed_default(&self.get_base_link(), &self.configuration.get_blacklist())
{
let page = Page::new_page(&self.domain.inner(), &client).await;
if !self.external_domains.is_empty() {
self.external_domains_caseless = self
.external_domains
.iter()
.filter_map(|d| {
if d == "*" {
Some("*".into())
} else {
match Url::parse(d) {
Ok(d) => Some(d.host_str().unwrap_or_default().into()),
_ => None,
}
}
})
.collect::<HashSet<CaseInsensitiveString>>()
.into();
}
let links = if !page.is_empty() {
self.links_visited.insert(match self.on_link_find_callback {
Some(cb) => {
let c = cb(*self.domain.clone(), None);
c.0
}
_ => *self.domain.clone(),
});
let links = HashSet::from(page.links(&base).await);
links
} else {
self.status = CrawlStatus::Empty;
Default::default()
};
match &self.channel {
Some(c) => {
match c.0.send(page) {
_ => (),
};
}
_ => (),
};
links
} else {
HashSet::new()
};
links
}
/// expand links for crawl
#[cfg(all(
not(feature = "glob"),
not(feature = "decentralized"),
not(feature = "chrome")
))]
async fn crawl_establish(
&mut self,
client: &Client,
base: &(CompactString, smallvec::SmallVec<[CompactString; 2]>),
selector: bool,
) -> HashSet<CaseInsensitiveString> {
self._crawl_establish(&client, &base, selector).await
}
/// expand links for crawl
#[cfg(all(
not(feature = "glob"),
not(feature = "decentralized"),
feature = "chrome"
))]
async fn crawl_establish(
&mut self,
client: &Client,
base: &(CompactString, smallvec::SmallVec<[CompactString; 2]>),
_: bool,
page: &chromiumoxide::Page,
) -> HashSet<CaseInsensitiveString> {
let links: HashSet<CaseInsensitiveString> = if self
.is_allowed_default(&self.get_base_link(), &self.configuration.get_blacklist())
{
let page = Page::new(&self.domain.inner(), &client, &page).await;
if !self.external_domains.is_empty() {
self.external_domains_caseless = self
.external_domains
.iter()
.filter_map(|d| match Url::parse(d) {
Ok(d) => Some(d.host_str().unwrap_or_default().into()),
_ => None,
})
.collect::<HashSet<CaseInsensitiveString>>()
.into();
}
let links = if !page.is_empty() {
self.links_visited.insert(match self.on_link_find_callback {
Some(cb) => {
let c = cb(*self.domain.clone(), None);
c.0
}
_ => *self.domain.clone(),
});
let links = HashSet::from(page.links(&base).await);
links
} else {
self.status = CrawlStatus::Empty;
Default::default()
};
match &self.channel {
Some(c) => {
match c.0.send(page) {
_ => (),
};
}
_ => (),
};
links
} else {
HashSet::new()
};
links
}
/// expand links for crawl
#[cfg(all(not(feature = "glob"), feature = "decentralized"))]
async fn crawl_establish(
&mut self,
client: &Client,
_: &(CompactString, smallvec::SmallVec<[CompactString; 2]>),
http_worker: bool,
) -> HashSet<CaseInsensitiveString> {
// base_domain name passed here is for primary url determination and not subdomain.tld placement
let links: HashSet<CaseInsensitiveString> = if self
.is_allowed_default(&self.get_base_link(), &self.configuration.get_blacklist())
{
let link = self.domain.inner();
let page = Page::new(
&if http_worker && link.starts_with("https") {
link.replacen("https", "http", 1)
} else {
link.to_string()
},
&client,
)
.await;
self.links_visited.insert(match self.on_link_find_callback {
Some(cb) => {
let c = cb(*self.domain.to_owned(), None);
c.0
}
_ => *self.domain.to_owned(),
});
match &self.channel {
Some(c) => {
match c.0.send(page.clone()) {
_ => (),
};
}
_ => (),
};
let page_links = HashSet::from(page.links);
page_links
} else {
HashSet::new()
};
links
}
/// expand links for crawl
#[cfg(all(feature = "glob", feature = "decentralized"))]
async fn crawl_establish(
&mut self,
client: &Client,
_: &(CompactString, smallvec::SmallVec<[CompactString; 2]>),
http_worker: bool,
) -> HashSet<CaseInsensitiveString> {
let mut links: HashSet<CaseInsensitiveString> = HashSet::new();
let domain_name = self.domain.inner();
let mut expanded = crate::features::glob::expand_url(&domain_name.as_str());
if expanded.len() == 0 {
match self.get_absolute_path(Some(domain_name)) {
Some(u) => {
expanded.push(u.as_str().into());
}
_ => (),
};
};
let blacklist_url = self.configuration.get_blacklist();
for link in expanded {
if self.is_allowed_default(&link, &blacklist_url) {
let page = Page::new(
&if http_worker && link.as_ref().starts_with("https") {
link.inner().replacen("https", "http", 1).to_string()
} else {
link.inner().to_string()
},
&client,
)
.await;
let u = page.get_url();
let u = if u.is_empty() { link } else { u.into() };
let link_result = match self.on_link_find_callback {
Some(cb) => cb(u, None),
_ => (u, None),
};
self.links_visited.insert(link_result.0);
match &self.channel {
Some(c) => {
match c.0.send(page.clone()) {
_ => (),
};
}
_ => (),
};
let page_links = HashSet::from(page.links);
links.extend(page_links);
}
}
links
}
/// expand links for crawl
#[cfg(all(feature = "glob", not(feature = "decentralized")))]
async fn crawl_establish(
&mut self,
client: &Client,
base: &(CompactString, smallvec::SmallVec<[CompactString; 2]>),
_: bool,
) -> HashSet<CaseInsensitiveString> {
let mut links: HashSet<CaseInsensitiveString> = HashSet::new();
let domain_name = self.domain.inner();
let mut expanded = crate::features::glob::expand_url(&domain_name.as_str());
if expanded.len() == 0 {
match self.get_absolute_path(Some(domain_name)) {
Some(u) => {
expanded.push(u.as_str().into());
}
_ => (),
};
};
let blacklist_url = self.configuration.get_blacklist();
for link in expanded {
if self.is_allowed_default(&link.inner(), &blacklist_url) {
let page = Page::new(&link.inner(), &client).await;
if !page.is_empty() {
let u = page.get_url().into();
let link_result = match self.on_link_find_callback {
Some(cb) => cb(u, None),
_ => (u, None),
};
self.links_visited.insert(link_result.0);
let page_links = HashSet::from(page.links(&base).await);
links.extend(page_links);
} else {
self.status = CrawlStatus::Empty;
};
match &self.channel {
Some(c) => {
match c.0.send(page) {
_ => (),
};
}
_ => (),
};
}
}
links
}
#[cfg(not(feature = "sitemap"))]
/// Start to crawl website with async concurrency
pub async fn crawl(&mut self) {
let (client, handle) = self.setup().await;
self.crawl_concurrent(&client, &handle).await;
}
#[cfg(not(feature = "sitemap"))]
/// Start to crawl website with async concurrency using the base raw functionality. Useful when using the "chrome" feature and defaulting to the basic implementation.
pub async fn crawl_raw(&mut self) {
let (client, handle) = self.setup().await;
self.crawl_concurrent_raw(&client, &handle).await;
}
#[cfg(not(feature = "sitemap"))]
/// Start to scrape/download website with async concurrency
pub async fn scrape(&mut self) {
let (client, handle) = self.setup().await;
self.scrape_concurrent(&client, &handle).await;
}
#[cfg(feature = "sitemap")]
/// Start to crawl website and include sitemap links
pub async fn crawl(&mut self) {
let (client, handle) = self.setup().await;
self.crawl_concurrent(&client, &handle).await;
self.sitemap_crawl(&client, &handle, false).await;
}
#[cfg(feature = "sitemap")]
/// Start to crawl website and include sitemap links with async concurrency using the base raw functionality. Useful when using the "chrome" feature and defaulting to the basic implementation.
pub async fn crawl_raw(&mut self) {
let (client, handle) = self.setup().await;
self.crawl_concurrent_raw(&client, &handle).await;
self.sitemap_crawl(&client, &handle, false).await;
}
#[cfg(feature = "sitemap")]
/// Start to scrape/download website with async concurrency
pub async fn scrape(&mut self) {
let (client, handle) = self.setup().await;
self.scrape_concurrent(&client, &handle).await;
self.sitemap_crawl(&client, &handle, true).await;
}
/// Start to crawl website concurrently
async fn crawl_concurrent_raw(&mut self, client: &Client, handle: &Option<Arc<AtomicI8>>) {
match self.setup_selectors() {
Some(selector) => {
let (mut interval, throttle) = self.setup_crawl();
let blacklist_url = self.configuration.get_blacklist();
let on_link_find_callback = self.on_link_find_callback;
let shared = Arc::new((
client.to_owned(),
selector,
self.channel.clone(),
self.external_domains_caseless.clone(),
));
let mut links: HashSet<CaseInsensitiveString> =
self._crawl_establish(&shared.0, &shared.1, false).await;
if !links.is_empty() {
let mut set: JoinSet<HashSet<CaseInsensitiveString>> = JoinSet::new();
let chandle = Handle::current();
// crawl while links exists
loop {
let stream = tokio_stream::iter::<HashSet<CaseInsensitiveString>>(
links.drain().collect(),
)
.throttle(*throttle);
tokio::pin!(stream);
loop {
match stream.next().await {
Some(link) => {
match handle.as_ref() {
Some(handle) => {
while handle.load(Ordering::Relaxed) == 1 {
interval.tick().await;
}
if handle.load(Ordering::Relaxed) == 2 {
set.shutdown().await;
break;
}
}
None => (),
}
if !self.is_allowed(&link, &blacklist_url) {
continue;
}
log("fetch", &link);
self.links_visited.insert(link.clone());
let permit = SEM.acquire().await.unwrap();
let shared = shared.clone();
task::yield_now().await;
set.spawn_on(
async move {
let link_result = match on_link_find_callback {
Some(cb) => cb(link, None),
_ => (link, None),
};
let mut page =
Page::new_page(&link_result.0.as_ref(), &shared.0).await;
page.set_external(shared.3.to_owned());
let page_links = page.links(&shared.1).await;
match &shared.2 {
Some(c) => {
match c.0.send(page) {
_ => (),
};
}
_ => (),
};
drop(permit);
page_links
},
&chandle,
);
}
_ => break,
}
}
while let Some(res) = set.join_next().await {
match res {
Ok(msg) => {
links.extend(&msg - &self.links_visited);
}
_ => (),
};
}
if links.is_empty() {
break;
}
}
}
self.status = CrawlStatus::Idle;
}
_ => log("", "The domain should be a valid URL, refer to <https://www.w3.org/TR/2011/WD-html5-20110525/urls.html#valid-url>."),
}
}
/// Start to crawl website concurrently
#[cfg(all(not(feature = "decentralized"), feature = "chrome"))]
async fn crawl_concurrent(&mut self, client: &Client, handle: &Option<Arc<AtomicI8>>) {
let selectors = self.setup_selectors();
// crawl if valid selector
if selectors.is_some() {
let (mut interval, throttle) = self.setup_crawl();
let blacklist_url = self.configuration.get_blacklist();
let on_link_find_callback = self.on_link_find_callback;
match launch_browser(&self.configuration.proxies).await {
Some((mut browser, browser_handle)) => {
match browser.new_page("about:blank").await {
Ok(new_page) => {
if cfg!(feature = "chrome_stealth") {
let _ = new_page.enable_stealth_mode_with_agent(&if self
.configuration
.user_agent
.is_some()
{
&self.configuration.user_agent.as_ref().unwrap().as_str()
} else {
""
});
}
let shared = Arc::new((
client.to_owned(),
unsafe { selectors.unwrap_unchecked() },
self.channel.clone(),
new_page.clone(),
self.external_domains_caseless.clone(),
));
let mut links: HashSet<CaseInsensitiveString> = self
.crawl_establish(&shared.0, &shared.1, false, &shared.3)
.await;
if !links.is_empty() {
let mut set: JoinSet<HashSet<CaseInsensitiveString>> =
JoinSet::new();
let chandle = Handle::current();
// crawl while links exists
loop {
let stream =
tokio_stream::iter::<HashSet<CaseInsensitiveString>>(
links.drain().collect(),
)
.throttle(*throttle);
tokio::pin!(stream);
loop {
match stream.next().await {
Some(link) => {
match handle.as_ref() {
Some(handle) => {
while handle.load(Ordering::Relaxed) == 1 {
interval.tick().await;
}
if handle.load(Ordering::Relaxed) == 2 {
set.shutdown().await;
break;
}
}
None => (),
}
if !self.is_allowed(&link, &blacklist_url) {
continue;
}
log("fetch", &link);
self.links_visited.insert(link.clone());
let permit = SEM.acquire().await.unwrap();
let shared = shared.clone();
task::yield_now().await;
set.spawn_on(
async move {
let link_result =
match on_link_find_callback {
Some(cb) => cb(link, None),
_ => (link, None),
};
let mut page = Page::new(
&link_result.0.as_ref(),
&shared.0,
&shared.3,
)
.await;
page.set_external(shared.4.clone());
let page_links =
page.links(&shared.1).await;
match &shared.2 {
Some(c) => {
match c.0.send(page) {
_ => (),
};
}
_ => (),
};
drop(permit);
page_links
},
&chandle,
);
}
_ => break,
}
}
while let Some(res) = set.join_next().await {
match res {
Ok(msg) => links.extend(&msg - &self.links_visited),
_ => (),
};
}
if links.is_empty() {
break;
}
}
}
self.status = CrawlStatus::Idle;
if !std::env::var("CHROME_URL").is_ok() {
let _ = browser.close().await;
let _ = browser_handle.await;
} else {
let _ = new_page.close().await;
}
}
_ => log("", "Chrome failed to open page."),
}
}
_ => log("", "Chrome failed to start."),
}
}
}
/// Start to crawl website concurrently
#[cfg(all(not(feature = "decentralized"), not(feature = "chrome")))]
async fn crawl_concurrent(&mut self, client: &Client, handle: &Option<Arc<AtomicI8>>) {
// crawl if valid selector
match self.setup_selectors() {
Some(selector) => {
let (mut interval, throttle) = self.setup_crawl();
let blacklist_url = self.configuration.get_blacklist();
let on_link_find_callback = self.on_link_find_callback;
let shared = Arc::new((
client.to_owned(),
selector,
self.channel.clone(),
self.external_domains_caseless.clone(),
));
let mut links: HashSet<CaseInsensitiveString> =
self.crawl_establish(&shared.0, &shared.1, false).await;
if !links.is_empty() {
let mut set: JoinSet<HashSet<CaseInsensitiveString>> = JoinSet::new();
let chandle = Handle::current();
// crawl while links exists
loop {
let stream = tokio_stream::iter::<HashSet<CaseInsensitiveString>>(
links.drain().collect(),
)
.throttle(*throttle);
tokio::pin!(stream);
loop {
match stream.next().await {
Some(link) => {
match handle.as_ref() {
Some(handle) => {
while handle.load(Ordering::Relaxed) == 1 {
interval.tick().await;
}
if handle.load(Ordering::Relaxed) == 2 {
set.shutdown().await;
break;
}
}
None => (),
}
if !self.is_allowed(&link, &blacklist_url) {
continue;
}
log("fetch", &link);
self.links_visited.insert(link.clone());
let permit = SEM.acquire().await.unwrap();
let shared = shared.clone();
task::yield_now().await;
set.spawn_on(
async move {
let link_result = match on_link_find_callback {
Some(cb) => cb(link, None),
_ => (link, None),
};
let mut page =
Page::new(&link_result.0.as_ref(), &shared.0).await;
page.set_external(shared.3.to_owned());
let page_links = page.links(&shared.1).await;
match &shared.2 {
Some(c) => {
match c.0.send(page) {
_ => (),
};
}
_ => (),
};
drop(permit);
page_links
},
&chandle,
);
}
_ => break,
}
}
while let Some(res) = set.join_next().await {
match res {
Ok(msg) => {
links.extend(&msg - &self.links_visited);
}
_ => (),
};
}
if links.is_empty() {
break;
}
}
}
self.status = CrawlStatus::Idle;
}
_ => log("", "The domain should be a valid URL, refer to <https://www.w3.org/TR/2011/WD-html5-20110525/urls.html#valid-url>."),
}
}
/// Start to crawl website concurrently
#[cfg(feature = "decentralized")]
async fn crawl_concurrent(&mut self, client: &Client, handle: &Option<Arc<AtomicI8>>) {
match url::Url::parse(&self.domain.inner()) {
Ok(_) => {
let blacklist_url = self.configuration.get_blacklist();
let domain = self.domain.inner().as_str();
let mut interval = Box::pin(tokio::time::interval(Duration::from_millis(10)));
let throttle = Box::pin(self.get_delay());
let on_link_find_callback = self.on_link_find_callback;
// http worker verify
let http_worker = std::env::var("SPIDER_WORKER")
.unwrap_or_else(|_| "http:".to_string())
.starts_with("http:");
let mut links: HashSet<CaseInsensitiveString> = self
.crawl_establish(&client, &(domain.into(), Default::default()), http_worker)
.await;
let mut set: JoinSet<HashSet<CaseInsensitiveString>> = JoinSet::new();
let chandle = Handle::current();
// crawl while links exists
loop {
let stream = tokio_stream::iter::<HashSet<CaseInsensitiveString>>(
links.drain().collect(),
)
.throttle(*throttle);
tokio::pin!(stream);
loop {
match stream.next().await {
Some(link) => {
match handle.as_ref() {
Some(handle) => {
while handle.load(Ordering::Relaxed) == 1 {
interval.tick().await;
}
if handle.load(Ordering::Relaxed) == 2 {
set.shutdown().await;
break;
}
}
None => (),
}
if !self.is_allowed(&link, &blacklist_url) {
continue;
}
log("fetch", &link);
self.links_visited.insert(link.clone());
let permit = SEM.acquire().await.unwrap();
let client = client.clone();
task::yield_now().await;
set.spawn_on(
async move {
let link_results = match on_link_find_callback {
Some(cb) => cb(link, None),
_ => (link, None),
};
let link_results = link_results.0.as_ref();
let page = Page::new(
&if http_worker && link_results.starts_with("https") {
link_results
.replacen("https", "http", 1)
.to_string()
} else {
link_results.to_string()
},
&client,
)
.await;
drop(permit);
page.links
},
&chandle,
);
}
_ => break,
}
}
while let Some(res) = set.join_next().await {
match res {
Ok(msg) => {
links.extend(&msg - &self.links_visited);
}
_ => (),
};
}
if links.is_empty() {
break;
}
}
}
_ => (),
}
}
#[cfg(not(feature = "chrome"))]
/// Start to scape website concurrently and store html
async fn scrape_concurrent(&mut self, client: &Client, handle: &Option<Arc<AtomicI8>>) {
let selectors = get_page_selectors(
&self.domain.inner(),
self.configuration.subdomains,
self.configuration.tld,
);
if selectors.is_some() {
self.status = CrawlStatus::Active;
let blacklist_url = self.configuration.get_blacklist();
self.pages = Some(Box::new(Vec::new()));
let delay = self.configuration.delay;
let on_link_find_callback = self.on_link_find_callback;
let mut interval = tokio::time::interval(Duration::from_millis(10));
let selectors = Arc::new(unsafe { selectors.unwrap_unchecked() });
let throttle = Duration::from_millis(delay);
let mut links: HashSet<CaseInsensitiveString> = HashSet::from([*self.domain.clone()]);
let mut set: JoinSet<(CaseInsensitiveString, Page, HashSet<CaseInsensitiveString>)> =
JoinSet::new();
// crawl while links exists
loop {
let stream =
tokio_stream::iter::<HashSet<CaseInsensitiveString>>(links.drain().collect())
.throttle(throttle);
tokio::pin!(stream);
while let Some(link) = stream.next().await {
match handle.as_ref() {
Some(handle) => {
while handle.load(Ordering::Relaxed) == 1 {
interval.tick().await;
}
if handle.load(Ordering::Relaxed) == 2 {
set.shutdown().await;
break;
}
}
None => (),
}
if !self.is_allowed(&link, &blacklist_url) {
continue;
}
self.links_visited.insert(link.clone());
log("fetch", &link);
let permit = SEM.acquire().await.unwrap();
// these clones should move into a single arc
let client = client.clone();
let channel = self.channel.clone();
let selectors = selectors.clone();
let external_domains_caseless = self.external_domains_caseless.clone();
set.spawn(async move {
drop(permit);
let page_resource =
crate::utils::fetch_page_html(&link.as_ref(), &client).await;
let mut page = build(&link.as_ref(), page_resource);
let (link, _) = match on_link_find_callback {
Some(cb) => {
let c = cb(link, Some(page.get_html()));
c
}
_ => (link, None),
};
match &channel {
Some(c) => {
match c.0.send(page.clone()) {
_ => (),
};
}
_ => (),
};
page.set_external(external_domains_caseless);
let page_links = page.links(&*selectors).await;
(link, page, page_links)
});
}
task::yield_now().await;
if links.capacity() >= 1500 {
links.shrink_to_fit();
}
while let Some(res) = set.join_next().await {
match res {
Ok(msg) => {
let page = msg.1;
links.extend(&msg.2 - &self.links_visited);
task::yield_now().await;
match self.pages.as_mut() {
Some(p) => p.push(page.clone()),
_ => (),
};
}
_ => (),
};
}
task::yield_now().await;
if links.is_empty() {
break;
}
}
self.status = CrawlStatus::Idle;
}
}
#[cfg(feature = "chrome")]
/// Start to scape website concurrently and store html
async fn scrape_concurrent(&mut self, client: &Client, handle: &Option<Arc<AtomicI8>>) {
let selectors = get_page_selectors(
&self.domain.inner(),
self.configuration.subdomains,
self.configuration.tld,
);
if selectors.is_some() {
self.status = CrawlStatus::Active;
let blacklist_url = self.configuration.get_blacklist();
self.pages = Some(Box::new(Vec::new()));
let delay = self.configuration.delay;
let on_link_find_callback = self.on_link_find_callback;
let mut interval = tokio::time::interval(Duration::from_millis(10));
let selectors = Arc::new(unsafe { selectors.unwrap_unchecked() });
let throttle = Duration::from_millis(delay);
let mut links: HashSet<CaseInsensitiveString> = HashSet::from([*self.domain.clone()]);
let mut set: JoinSet<(CaseInsensitiveString, Page, HashSet<CaseInsensitiveString>)> =
JoinSet::new();
match launch_browser(&self.configuration.proxies).await {
Some((mut browser, _)) => {
match browser.new_page("about:blank").await {
Ok(new_page) => {
if cfg!(feature = "chrome_stealth") {
let _ = new_page.enable_stealth_mode_with_agent(&if self
.configuration
.user_agent
.is_some()
{
&self.configuration.user_agent.as_ref().unwrap().as_str()
} else {
""
});
}
let page = Arc::new(new_page.clone());
// crawl while links exists
loop {
let stream = tokio_stream::iter::<HashSet<CaseInsensitiveString>>(
links.drain().collect(),
)
.throttle(throttle);
tokio::pin!(stream);
while let Some(link) = stream.next().await {
match handle.as_ref() {
Some(handle) => {
while handle.load(Ordering::Relaxed) == 1 {
interval.tick().await;
}
if handle.load(Ordering::Relaxed) == 2 {
set.shutdown().await;
break;
}
}
None => (),
}
if !self.is_allowed(&link, &blacklist_url) {
continue;
}
self.links_visited.insert(link.clone());
log("fetch", &link);
let client = client.clone();
let permit = SEM.acquire().await.unwrap();
let channel = self.channel.clone();
let selectors = selectors.clone();
let page = page.clone();
let external_domains_caseless =
self.external_domains_caseless.clone();
set.spawn(async move {
drop(permit);
let page = crate::utils::fetch_page_html_chrome(
&link.as_ref(),
&client,
&page,
)
.await;
let mut page = build(&link.as_ref(), page);
let (link, _) = match on_link_find_callback {
Some(cb) => {
let c = cb(link, Some(page.get_html()));
c
}
_ => (link, None),
};
match &channel {
Some(c) => {
match c.0.send(page.clone()) {
_ => (),
};
}
_ => (),
};
page.set_external(external_domains_caseless);
let page_links = page.links(&*selectors).await;
(link, page, page_links)
});
}
task::yield_now().await;
if links.capacity() >= 1500 {
links.shrink_to_fit();
}
while let Some(res) = set.join_next().await {
match res {
Ok(msg) => {
let page = msg.1;
links.extend(&msg.2 - &self.links_visited);
task::yield_now().await;
match self.pages.as_mut() {
Some(p) => p.push(page.clone()),
_ => (),
};
}
_ => (),
};
}
task::yield_now().await;
if links.is_empty() {
break;
}
}
self.status = CrawlStatus::Idle;
if !std::env::var("CHROME_URL").is_ok() {
let _ = browser.close().await;
} else {
let _ = new_page.close().await;
}
}
_ => log("", "Chrome failed to open page."),
}
}
_ => log("", "Chrome failed to start."),
};
}
}
/// Sitemap crawl entire lists. Note: this method does not re-crawl the links of the pages found on the sitemap.
#[cfg(feature = "sitemap")]
pub async fn sitemap_crawl(
&mut self,
client: &Client,
handle: &Option<Arc<AtomicI8>>,
scrape: bool,
) {
use sitemap::reader::{SiteMapEntity, SiteMapReader};
use sitemap::structs::Location;
let domain = self.domain.inner().as_str();
let handle = handle.clone().unwrap_or_default();
let mut interval = tokio::time::interval(Duration::from_millis(15));
let (sitemap_path, needs_trailing) = match &self.configuration.sitemap_url {
Some(sitemap_path) => {
let sitemap_path = sitemap_path.as_str();
if domain.ends_with('/') && sitemap_path.starts_with('/') {
(&sitemap_path[1..], false)
} else if !domain.ends_with('/')
&& !sitemap_path.is_empty()
&& !sitemap_path.starts_with('/')
{
(sitemap_path, true)
} else {
(sitemap_path, false)
}
}
_ => ("sitemap.xml", !domain.ends_with("/")),
};
self.configuration.sitemap_url = Some(Box::new(
string_concat!(domain, if needs_trailing { "/" } else { "" }, sitemap_path).into(),
));
let blacklist_url = self.configuration.get_blacklist();
while let Some(site) = &self.configuration.sitemap_url {
if !handle.load(Ordering::Relaxed) == 2 {
break;
}
let mut sitemap_added = false;
let (tx, mut rx) = tokio::sync::mpsc::channel::<Page>(32);
let client = client.clone();
let channel = self.channel.clone();
let handles = tokio::spawn(async move {
let mut pages = Vec::new();
while let Some(page) = rx.recv().await {
if scrape {
pages.push(page.clone());
};
match &channel {
Some(c) => {
match c.0.send(page) {
_ => (),
};
}
_ => (),
};
}
pages
});
match client.get(site.as_str()).send().await {
Ok(response) => {
match response.text().await {
Ok(text) => {
// <html><head><title>Invalid request</title></head><body><p>Blocked by WAF</p><
let mut stream =
tokio_stream::iter(SiteMapReader::new(text.as_bytes()));
while let Some(entity) = stream.next().await {
while handle.load(Ordering::Relaxed) == 1 {
interval.tick().await;
}
// shutdown all links
if handle.load(Ordering::Relaxed) == 2 {
break;
}
match entity {
SiteMapEntity::Url(url_entry) => match url_entry.loc {
Location::Url(url) => {
let link: CaseInsensitiveString = url.as_str().into();
if !self.is_allowed(&link, &blacklist_url) {
continue;
}
self.links_visited.insert(link.clone());
let client = client.clone();
let tx = tx.clone();
tokio::spawn(async move {
let page = Page::new(&link.inner(), &client).await;
match tx.reserve().await {
Ok(permit) => {
permit.send(page);
}
_ => (),
}
});
}
Location::None | Location::ParseErr(_) => (),
},
SiteMapEntity::SiteMap(sitemap_entry) => {
match sitemap_entry.loc {
Location::Url(url) => {
self.configuration
.sitemap_url
.replace(Box::new(url.as_str().into()));
sitemap_added = true;
}
Location::None | Location::ParseErr(_) => (),
}
}
SiteMapEntity::Err(err) => {
log("incorrect sitemap error: ", err.msg())
}
};
}
}
Err(err) => log("http parse error: ", err.to_string()),
};
}
Err(err) => log("http network error: ", err.to_string()),
};
drop(tx);
if let Ok(handle) = handles.await {
match self.pages.as_mut() {
Some(p) => p.extend(handle),
_ => (),
};
}
if !sitemap_added {
self.configuration.sitemap_url = None;
};
}
}
/// Respect robots.txt file.
pub fn with_respect_robots_txt(&mut self, respect_robots_txt: bool) -> &mut Self {
self.configuration
.with_respect_robots_txt(respect_robots_txt);
self
}
/// Include subdomains detection.
pub fn with_subdomains(&mut self, subdomains: bool) -> &mut Self {
self.configuration.with_subdomains(subdomains);
self
}
/// Include tld detection.
pub fn with_tld(&mut self, tld: bool) -> &mut Self {
self.configuration.with_tld(tld);
self
}
/// Only use HTTP/2.
pub fn with_http2_prior_knowledge(&mut self, http2_prior_knowledge: bool) -> &mut Self {
self.configuration
.with_http2_prior_knowledge(http2_prior_knowledge);
self
}
/// Delay between request as ms.
pub fn with_delay(&mut self, delay: u64) -> &mut Self {
self.configuration.with_delay(delay);
self
}
/// Max time to wait for request.
pub fn with_request_timeout(&mut self, request_timeout: Option<Duration>) -> &mut Self {
self.configuration.with_request_timeout(request_timeout);
self
}
/// Add user agent to request.
pub fn with_user_agent(&mut self, user_agent: Option<&str>) -> &mut Self {
self.configuration.with_user_agent(user_agent);
self
}
#[cfg(feature = "sitemap")]
/// Add user agent to request.
pub fn with_sitemap(&mut self, sitemap_url: Option<&str>) -> &mut Self {
self.configuration.with_sitemap(sitemap_url);
self
}
/// Use proxies for request.
pub fn with_proxies(&mut self, proxies: Option<Vec<String>>) -> &mut Self {
self.configuration.with_proxies(proxies);
self
}
/// Add blacklist urls to ignore.
pub fn with_blacklist_url<T>(&mut self, blacklist_url: Option<Vec<T>>) -> &mut Self
where
Vec<CompactString>: From<Vec<T>>,
{
self.configuration.with_blacklist_url(blacklist_url);
self
}
/// Set HTTP headers for request using [reqwest::header::HeaderMap](https://docs.rs/reqwest/latest/reqwest/header/struct.HeaderMap.html).
pub fn with_headers(&mut self, headers: Option<reqwest::header::HeaderMap>) -> &mut Self {
self.configuration.with_headers(headers);
self
}
#[cfg(feature = "budget")]
/// Set a crawl budget per path with levels support /a/b/c or for all paths with "*".
pub fn with_budget(&mut self, budget: Option<HashMap<&str, u32>>) -> &mut Self {
self.budget = match budget {
Some(budget) => {
let mut crawl_budget: HashMap<CaseInsensitiveString, u32> = HashMap::new();
for b in budget.into_iter() {
crawl_budget.insert(CaseInsensitiveString::from(b.0), b.1);
}
Some(crawl_budget)
}
_ => None,
};
self
}
#[cfg(feature = "budget")]
/// Set the crawl budget directly.
pub fn set_crawl_budget(&mut self, budget: Option<HashMap<CaseInsensitiveString, u32>>) {
self.budget = budget;
}
/// Group external domains to treat the crawl as one. If None is passed this will clear all prior domains.
pub fn with_external_domains<'a, 'b>(
&mut self,
external_domains: Option<impl Iterator<Item = String> + 'a>,
) -> &mut Self {
match external_domains {
Some(external_domains) => {
self.external_domains_caseless = external_domains
.into_iter()
.filter_map(|d| match Url::parse(&d) {
Ok(d) => Some(d.host_str().unwrap_or_default().into()),
_ => None,
})
.collect::<HashSet<CaseInsensitiveString>>()
.into();
}
_ => self.external_domains_caseless.clear(),
}
self
}
/// Perform a callback to run on each link find.
pub fn with_on_link_find_callback(
&mut self,
on_link_find_callback: Option<
fn(CaseInsensitiveString, Option<String>) -> (CaseInsensitiveString, Option<String>),
>,
) -> &mut Self {
match on_link_find_callback {
Some(callback) => self.on_link_find_callback = Some(callback.into()),
_ => self.on_link_find_callback = None,
};
self
}
#[cfg(feature = "cron")]
/// Setup cron jobs to run
pub fn with_cron(&mut self, cron_str: &str, cron_type: CronType) -> &mut Self {
self.cron_str = cron_str.into();
self.cron_type = cron_type;
self
}
/// Build the website configuration when using with_builder
#[cfg(not(feature = "napi"))]
pub fn build(&self) -> Result<Self, Error> {
if self.domain_parsed.is_none() {
Err(ErrorKind::NotFound.into())
} else {
Ok(self.to_owned())
}
}
/// Build the website configuration when using with_builder with napi error handling
#[cfg(feature = "napi")]
pub fn build(&self) -> Result<Self, WebsiteBuilderError> {
if self.domain_parsed.is_none() {
Err(napi::Error::new(WebsiteBuilderError::ValidationError("domain cannot parse"), "incorrect domain name" ))
} else {
Ok(self.to_owned())
}
}
/// Setup subscription for data.
#[cfg(not(feature = "sync"))]
pub fn subscribe(
&mut self,
capacity: usize,
) -> Option<Arc<(broadcast::Sender<Page>, broadcast::Receiver<Page>)>> {
None
}
/// Setup subscription for data.
#[cfg(feature = "sync")]
pub fn subscribe(&mut self, capacity: usize) -> Option<broadcast::Receiver<Page>> {
let channel = self
.channel
.get_or_insert(Arc::new(broadcast::channel(capacity.max(1))));
let channel = channel.clone();
let rx2 = channel.0.subscribe();
Some(rx2)
}
#[cfg(feature = "cron")]
/// Start a cron job - if you use subscribe on another thread you need to abort the handle in conjuction with runner.stop.
pub async fn run_cron(&self) -> crate::features::cron::Runner {
crate::features::cron::Runner::new()
.add(Box::new(self.clone()))
.run()
.await
}
}
#[cfg(feature = "cron")]
/// Start a cron job taking ownership of the website
pub async fn run_cron(website: Website) -> crate::features::cron::Runner {
crate::features::cron::Runner::new()
.add(Box::new(website))
.run()
.await
}
#[cfg(feature = "cron")]
#[async_trait]
impl crate::features::cron::Job for Website {
fn schedule(&self) -> Option<cron::Schedule> {
match self.cron_str.parse() {
Ok(schedule) => Some(schedule),
Err(e) => {
log::error!("{:?}", e);
None
}
}
}
async fn handle(&mut self) {
log::info!(
"CRON: {} - cron job running {}",
self.get_domain().as_ref(),
self.now()
);
if self.cron_type == CronType::Crawl {
self.crawl().await;
} else {
self.scrape().await;
}
}
}
/// builder pattern error handling
#[cfg(feature = "napi")]
pub enum WebsiteBuilderError {
/// Uninitialized field
UninitializedField(&'static str),
/// Custom validation error
ValidationError(&'static str),
}
#[cfg(feature = "napi")]
impl AsRef<str> for WebsiteBuilderError {
fn as_ref(&self) -> &str {
match self {
Self::UninitializedField( s) => s,
Self::ValidationError( s) => s,
}
}
}
#[cfg(feature = "napi")]
impl std::fmt::Display for Website {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "`{}`", self)
}
}
#[cfg(feature = "napi")]
impl std::error::Error for Website {}
#[cfg(not(feature = "decentralized"))]
#[tokio::test]
async fn crawl() {
let url = "https://choosealicense.com";
let mut website: Website = Website::new(&url);
website.crawl().await;
assert!(
website
.links_visited
.contains::<CaseInsensitiveString>(&"https://choosealicense.com/licenses/".into()),
"{:?}",
website.links_visited
);
}
#[cfg(feature = "cron")]
#[tokio::test]
async fn crawl_cron() {
let url = "https://choosealicense.com";
let mut website: Website = Website::new(&url)
.with_cron("1/5 * * * * *", Default::default())
.build()
.unwrap();
let mut rx2 = website.subscribe(16).unwrap();
// handle an event on every cron
let join_handle = tokio::spawn(async move {
let mut links_visited = HashSet::new();
while let Ok(res) = rx2.recv().await {
let url = res.get_url();
links_visited.insert(CaseInsensitiveString::new(url));
}
assert!(
links_visited
.contains::<CaseInsensitiveString>(&"https://choosealicense.com/licenses/".into()),
"{:?}",
links_visited
);
});
let runner = website.run_cron().await;
log::debug!("Starting the Runner for 10 seconds");
tokio::time::sleep(Duration::from_secs(10)).await;
runner.stop().await;
join_handle.abort();
let _ = join_handle.await;
}
#[cfg(feature = "cron")]
#[tokio::test]
async fn crawl_cron_own() {
let url = "https://choosealicense.com";
let mut website: Website = Website::new(&url)
.with_cron("1/5 * * * * *", Default::default())
.build()
.unwrap();
let mut rx2 = website.subscribe(16).unwrap();
// handle an event on every cron
let join_handle = tokio::spawn(async move {
let mut links_visited = HashSet::new();
while let Ok(res) = rx2.recv().await {
let url = res.get_url();
links_visited.insert(CaseInsensitiveString::new(url));
}
assert!(
links_visited
.contains::<CaseInsensitiveString>(&"https://choosealicense.com/licenses/".into()),
"{:?}",
links_visited
);
});
let runner = run_cron(website).await;
log::debug!("Starting the Runner for 10 seconds");
tokio::time::sleep(Duration::from_secs(10)).await;
let _ = tokio::join!(runner.stop(), join_handle);
}
#[cfg(not(feature = "decentralized"))]
#[tokio::test]
async fn scrape() {
let mut website: Website = Website::new("https://choosealicense.com");
website.scrape().await;
assert!(
website
.links_visited
.contains::<CaseInsensitiveString>(&"https://choosealicense.com/licenses/".into()),
"{:?}",
website.links_visited
);
assert_eq!(website.get_pages().unwrap()[0].get_html().is_empty(), false);
}
#[tokio::test]
#[cfg(not(feature = "decentralized"))]
async fn crawl_invalid() {
let mut website: Website = Website::new("https://w.com");
website.crawl().await;
assert_eq!(website.links_visited.len() <= 1, true); // only the target url should exist
}
#[tokio::test]
#[cfg(feature = "decentralized")]
async fn crawl_invalid() {
let domain = "https://w.com";
let mut website: Website = Website::new(domain);
website.crawl().await;
let mut uniq: Box<HashSet<CaseInsensitiveString>> = Box::new(HashSet::new());
uniq.insert(format!("{}/", domain.to_string()).into()); // TODO: remove trailing slash mutate
assert_eq!(website.links_visited, uniq); // only the target url should exist
}
#[tokio::test]
async fn not_crawl_blacklist() {
let mut website: Website = Website::new("https://choosealicense.com");
website.configuration.blacklist_url = Some(Box::new(Vec::from([CompactString::from(
"https://choosealicense.com/licenses/",
)])));
website.crawl().await;
assert!(
!website
.links_visited
.contains::<CaseInsensitiveString>(&"https://choosealicense.com/licenses/".into()),
"{:?}",
website.links_visited
);
}
#[tokio::test]
#[cfg(feature = "regex")]
async fn not_crawl_blacklist_regex() {
let mut website: Website = Website::new("https://choosealicense.com");
website.with_blacklist_url(Some(Vec::from(["choosealicense.com".into()])));
website.crawl().await;
assert_eq!(website.links_visited.len(), 0);
}
#[test]
#[cfg(feature = "ua_generator")]
fn randomize_website_agent() {
assert_eq!(get_ua().is_empty(), false);
}
#[tokio::test]
#[cfg(not(feature = "decentralized"))]
async fn test_respect_robots_txt() {
let mut website: Website = Website::new("https://stackoverflow.com");
website.configuration.respect_robots_txt = true;
website.configuration.user_agent = Some(Box::new("*".into()));
let (client, _): (Client, Option<Arc<AtomicI8>>) = website.setup().await;
website.configure_robots_parser(client).await;
assert_eq!(website.configuration.delay, 0);
assert!(!&website.is_allowed(
&"https://stackoverflow.com/posts/".into(),
&Default::default()
));
// test match for bing bot
let mut website_second: Website = Website::new("https://www.mongodb.com");
website_second.configuration.respect_robots_txt = true;
website_second.configuration.user_agent = Some(Box::new("bingbot".into()));
let (client_second, _): (Client, Option<Arc<AtomicI8>>) = website_second.setup().await;
website_second.configure_robots_parser(client_second).await;
assert_eq!(website_second.configuration.delay, 60000); // should equal one minute in ms
// test crawl delay with wildcard agent [DOES not work when using set agent]
let mut website_third: Website = Website::new("https://www.mongodb.com");
website_third.configuration.respect_robots_txt = true;
let (client_third, _): (Client, Option<Arc<AtomicI8>>) = website_third.setup().await;
website_third.configure_robots_parser(client_third).await;
assert_eq!(website_third.configuration.delay, 10000); // should equal 10 seconds in ms
}
#[cfg(not(feature = "decentralized"))]
#[tokio::test]
async fn test_crawl_subdomains() {
let mut website: Website = Website::new("https://choosealicense.com");
website.configuration.subdomains = true;
website.crawl().await;
assert!(
website
.links_visited
.contains::<CaseInsensitiveString>(&"https://choosealicense.com/licenses/".into()),
"{:?}",
website.links_visited
);
}
#[tokio::test]
async fn test_with_configuration() {
let mut website = Website::new("https://choosealicense.com");
website
.with_respect_robots_txt(true)
.with_subdomains(true)
.with_tld(false)
.with_delay(0)
.with_request_timeout(None)
.with_http2_prior_knowledge(false)
.with_user_agent(Some("myapp/version".into()))
.with_headers(None)
.with_proxies(None);
website.crawl().await;
assert!(
website.links_visited.len() >= 1,
"{:?}",
website.links_visited
);
}
#[cfg(all(feature = "glob", not(feature = "decentralized")))]
#[tokio::test]
async fn test_crawl_glob() {
let mut website: Website =
Website::new("https://choosealicense.com/licenses/{mit,apache-2.0,mpl-2.0}/");
website.crawl().await;
// check for either https/http in collection
assert!(
website
.links_visited
.contains::<CaseInsensitiveString>(&"https://choosealicense.com/licenses/".into())
|| website
.links_visited
.contains::<CaseInsensitiveString>(&"http://choosealicense.com/licenses/".into()),
"{:?}",
website.links_visited
);
}
#[cfg(not(feature = "decentralized"))]
#[tokio::test]
async fn test_crawl_tld() {
let mut website: Website = Website::new("https://choosealicense.com");
website.configuration.tld = true;
website.crawl().await;
assert!(
website
.links_visited
.contains::<CaseInsensitiveString>(&"https://choosealicense.com/licenses/".into()),
"{:?}",
website.links_visited
);
}
#[tokio::test]
#[cfg(all(feature = "sync", not(feature = "decentralized")))]
async fn test_crawl_subscription() {
let mut website: Website = Website::new("https://choosealicense.com");
let mut rx2 = website.subscribe(100).unwrap();
let count = Arc::new(tokio::sync::Mutex::new(0));
let count1 = count.clone();
tokio::spawn(async move {
while let Ok(_) = rx2.recv().await {
let mut lock = count1.lock().await;
*lock += 1;
}
});
website.crawl().await;
let website_links = website.get_links().len();
let count = *count.lock().await;
// no subscription if did not fulfill. The root page is always captured in links.
assert!(count == website_links, "{:?}", true);
}
#[cfg(all(feature = "socks", not(feature = "decentralized")))]
#[tokio::test]
async fn test_crawl_proxy() {
let mut website: Website = Website::new("https://choosealicense.com");
website
.configuration
.proxies
.get_or_insert(Default::default())
.push("socks5://127.0.0.1:1080".into());
website.crawl().await;
let mut license_found = false;
for links_visited in website.links_visited.iter() {
// Proxy may return http or https in socks5 per platform.
// We may want to replace the protocol with the host of the platform regardless of proxy response.
if links_visited.as_ref().contains("/licenses/") {
license_found = true;
};
}
assert!(license_found, "{:?}", website.links_visited);
}
#[tokio::test]
async fn test_link_duplicates() {
fn has_unique_elements<T>(iter: T) -> bool
where
T: IntoIterator,
T::Item: Eq + std::hash::Hash,
{
let mut uniq = HashSet::new();
iter.into_iter().all(move |x| uniq.insert(x))
}
let mut website: Website = Website::new("http://0.0.0.0:8000");
website.crawl().await;
assert!(has_unique_elements(&*website.links_visited));
}
#[tokio::test]
#[cfg(feature = "budget")]
async fn test_crawl_budget() {
let mut website: Website = Website::new("https://choosealicense.com");
website.with_budget(Some(HashMap::from([("*", 1), ("/licenses", 1)])));
website.crawl().await;
assert!(website.links_visited.len() <= 1);
}
#[cfg(feature = "control")]
#[tokio::test]
#[ignore]
async fn test_crawl_pause_resume() {
use crate::utils::{pause, resume};
let domain = "https://choosealicense.com/";
let mut website: Website = Website::new(&domain);
let start = tokio::time::Instant::now();
tokio::spawn(async move {
pause(domain).await;
// static website test pause/resume - scan will never take longer than 5secs for target website choosealicense
tokio::time::sleep(Duration::from_millis(5000)).await;
resume(domain).await;
});
website.crawl().await;
let duration = start.elapsed();
assert!(duration.as_secs() > 5, "{:?}", duration);
assert!(
website
.links_visited
.contains::<CaseInsensitiveString>(&"https://choosealicense.com/licenses/".into()),
"{:?}",
website.links_visited
);
}
#[cfg(feature = "control")]
#[tokio::test]
#[ignore]
async fn test_crawl_shutdown() {
use crate::utils::shutdown;
// use target blog to prevent shutdown of prior crawler
let domain = "https://rsseau.fr/";
let mut website: Website = Website::new(&domain);
tokio::spawn(async move {
shutdown(domain).await;
});
website.crawl().await;
assert_eq!(website.links_visited.len(), 1);
}