https://1337x-to-search.pages.dev/

提交的 URL:
https://1337x-to-search.pages.dev/
报告完成时间:

链接 · 找到 3 个

链接文本
https://telegram.dog/HashHackerst.me/HashHackers
https://1337x.to1337x.to
https://web.scraper.zindex.eu.orgWeb Scraper API

JavaScript 变量 · 找到 26 个

名称类型
onbeforetoggleobject
documentPictureInPictureobject
onscrollendobject
$function
jQueryfunction
Popperobject
uidEventnumber
bootstrapobject
generateSHA256function
showSpinnerfunction

控制台日志消息 · 找到 3 条

HTML

<!DOCTYPE html><html lang="en"><head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>1337x Proxy Search | High Speed Torrent Search Engine</title>
      <meta name="description" content="1337x Proxy Search is a high speed torrent search engine that allows you to search and download torrents from 1337x.to.">
      <link rel="canonical" href="https://1337x-to-search.pages.dev">
      <link rel="shortcut icon" href="https://www.google.com/favicon.ico">
      <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/flatly/bootstrap.min.css">
      <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css">
      <style>
         .spinner {
         border: 4px solid rgba(0, 0, 0, 0.1);
         border-top: 4px solid #007bff;
         border-radius: 50%;
         width: 30px;
         height: 30px;
         animation: spin 1s linear infinite;
         position: absolute;
         top: 50%;
         left: 50%;
         transform: translateX(-50%);
         }
         @keyframes spin {
         0% { transform: rotate(0deg); }
         100% { transform: rotate(360deg); }
         }
         .no-results-box {
         border: 1px solid #ced4da;
         padding: 10px;
         margin-top: 10px;
         display: none;
         }
      </style>
   </head>
   <body>
      <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
         <div class="container-fluid">
            <a class="navbar-brand" href="/"><img border="0" alt="1337x" src="https://cdn.jsdelivr.net/gh/1337-to/[email protected]/images/logo.svg" height="40px"><img border="0" alt="Hash Hackers" src="https://cdn.jsdelivr.net/gh/1337-to/[email protected]/hashhackers.svg" height="15px"></a>
         </div>
      </nav>
      <div class="container my-5">
         <div class="input-group mb-3">
            <input type="text" class="form-control" id="searchInput" placeholder="Search...">
         </div>
         <div class="input-group mb-3">
            <select class="form-select" id="sortSelect">
               <option value="size_asc">Sort by Size Asc</option>
               <option value="size_desc">Sort by Size Desc</option>
               <option value="time_asc">Sort by Time Asc</option>
               <option value="time_desc" selected="">Sort by Time Desc</option>
               <option value="seeders_asc">Sort by Seeders Asc</option>
               <option value="seeders_desc">Sort by Seeders Desc</option>
               <option value="leechers_asc">Sort by Leechers Asc</option>
               <option value="leechers_desc">Sort by Leechers Desc</option>
            </select>
            <button class="btn btn-primary" type="button" id="searchButton">Search</button>
         </div>
         <div id="Top100ResultsBox" class="text-center" style="display: none; margin-bottom: 10px;">
            <div class="alert alert-warning alert-dismissible fade show" style="display: none;" role="alert">
               <strong>Top 100 Torrents</strong> are loaded. Search for more torrents using the search bar.
               <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
            <button class="btn btn-info me-2 mb-2" onclick="openUrl('/?top100=top-100-movies')">Top 100 Movies</button>
            <button class="btn btn-info me-2 mb-2" onclick="openUrl('/?top100=top-100-television')">Top 100 TV</button>
            <button class="btn btn-info me-2 mb-2" onclick="openUrl('/?top100=top-100-games')">Top 100 Games</button>
            <button class="btn btn-info me-2 mb-2" onclick="openUrl('/?top100=top-100-applications')">Top 100 Apps</button>
            <button class="btn btn-info me-2 mb-2" onclick="openUrl('/?top100=top-100-music')">Top 100 Music</button>
            <button class="btn btn-info me-2 mb-2" onclick="openUrl('/?top100=top-100-documentaries')">Top 100 Documentaries</button>
            <button class="btn btn-info me-2 mb-2" onclick="openUrl('/?top100=top-100-anime')">Top 100 Anime</button>
            <button class="btn btn-info me-2 mb-2" onclick="openUrl('/?top100=top-100-other')">Top 100 Other</button>
            <button class="btn btn-info me-2 mb-2" onclick="openUrl('/?top100=top-100-xxx')">Top 100 XXX</button>
         </div>
         <div class="alert alert-warning alert-dismissible fade show" id="noResultsBox" style="display: none;" role="alert">
            <strong>No results found!</strong> Please try a different search query.
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
         </div>
         <div id="itemList"></div>
         <div class="alert alert-warning alert-dismissible fade show" id="noMoreResultsBox" style="display: none;" role="alert">
            <strong>No More Results for this Query.</strong>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
         </div>
         <!-- Spinner card -->
         <div class="card my-2 mb-2 text-center" id="spinnerCard" style="display: block; height: 100px;">
            <div class="card-body">
               <div class="spinner"></div>
            </div>
         </div>
      </div>
      <p class="info text-center"><img src="https://hits.seeyoufarm.com/api/count/incr/badge.svg?url=https%3A%2F%2F1337x.search.zindex.eu.org&amp;count_bg=%2379C83D&amp;title_bg=%23555555&amp;icon=&amp;icon_color=%23E7E7E7&amp;title=Daily/All Views&amp;edge_flat=false"></p>
      <p class="info text-center">Made with ❤️ by <a href="https://telegram.dog/HashHackers" target="_blank">Hash Hackers</a></p>
      <p class="info text-center">This is a mirror of <a href="https://1337x.to" target="_blank">1337x.to</a> and uses <a href="https://web.scraper.zindex.eu.org" target="_blank">Web Scraper API</a> to fetch data.</p>
      <p class="info text-center">This website is not affiliated with 1337x.to in any way.</p>
      <p class="info text-center">If you have any issues, please report them to the developer at <a href="https://telegram.dog/HashHackers" target="_blank">t.me/HashHackers</a></p>
      <!-- Modal -->
      <div class="modal fade" id="torrentMagnetModal" tabindex="-1" aria-labelledby="torrentMagnetModalLabel" aria-hidden="true" data-bs-backdrop="static" data-bs-keyboard="false">
         <div class="modal-dialog">
            <div class="modal-content">
               <div class="modal-header">
                  <h5 class="modal-title" id="torrentMagnetModalLabel">Magnet Link</h5>
                  <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
               </div>
               <div class="modal-body text-center">
                  <div id="loadingSpinner" style="display: none;">
                     <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">Loading...</span>
                     </div>
                     <p class="mt-2">Fetching magnet link...</p>
                  </div>
                  <div id="magnetLinkContainer" style="display: none;">
                     <textarea class="form-control" id="magnetLinkInput" rows="10" readonly=""></textarea>
                     <button class="btn btn-primary mt-2" id="copyButton">Copy Magnet Link</button>
                  </div>
                  <p id="errorMessage" style="display: none; color: red;"></p>
               </div>
               <div class="modal-footer" id="modalFooter">
                  <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
               </div>
            </div>
         </div>
      </div>
      <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/2.11.6/umd/popper.min.js"></script>
      <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script>
<script>

hideSpinner("spinnerCard");

async function generateSHA256(input) {
    console.info('Generating SHA-256 hash for:', input);
    // Encode the input as a Uint8Array
    const encoder = new TextEncoder();
    const data = encoder.encode(input);

    // Generate the hash using subtle.digest
    const hashBuffer = await crypto.subtle.digest('SHA-256', data);

    // Convert ArrayBuffer to Hex String for easier readability
    const hashArray = Array.from(new Uint8Array(hashBuffer));
    const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
    console.info('SHA-256 hash:', hashHex);
    return hashHex;
}

// Function to show spinner
function showSpinner(spinnerId) {
    var spinnerCard = document.getElementById(spinnerId);
    spinnerCard.style.display = "block";
}

// Function to hide spinner
function hideSpinner(spinnerId) {
    var spinnerCard = document.getElementById(spinnerId);
    spinnerCard.style.display = "none";
}

// handle id= searchButton
document.getElementById('searchInput').addEventListener('keypress', function(event) {
    if (event.key === 'Enter') {
        event.preventDefault(); // Prevent default form submission
        document.getElementById('searchButton').click(); // Manually trigger search button click
    }
});

document.getElementById('searchButton').addEventListener('click', function() {
    var searchQuery = document.getElementById('searchInput').value;
    var sortSelect = document.getElementById('sortSelect');
    if (searchQuery.trim() !== '') { // Use trim() to remove leading and trailing whitespace
        window.location.href = '/?search=' + encodeURIComponent(searchQuery) + '&sort=' + sortSelect.value;
    }
});


// Keep track of the current page number
var currentPage = 1;
// Flag to check if a request is in progress
var requestInProgress = false;

function openUrl(url) {
    window.location.href = url;
}

async function loadTop100(type = "top-100") {
    showSpinner("spinnerCard");

    // Prevent multiple concurrent requests
    if (requestInProgress) return;
    requestInProgress = true;

    try {
        // Construct the initial URL
        const baseUrl = "https://1337x.to/";
        const pageUrl = `${baseUrl}${type}`;
        
        // Generate SHA-256 hash for the page URL
        const sha256Hash = await generateSHA256(pageUrl);
        const cacheUrl = `https://1337x-r2-torrents-cache.zindex.eu.org/${sha256Hash}.txt`;

        // Check if the hashed URL exists
        const response = await fetch(cacheUrl, { method: "HEAD" });

        if (!response.ok) {
            let request_cdn_to_cache = await fetch(`https://1337x-d1-static-api.zindex.eu.org/r2-request-api?url=${btoa(pageUrl)}`);
            if (request_cdn_to_cache.ok) {
                let request_cdn_to_cache_json = await request_cdn_to_cache.json();
                console.log(`Request Result: ${request_cdn_to_cache_json.status} and URL: ${request_cdn_to_cache_json.message}`);
            } else {
                console.log(`Request failed to cache URL: ${pageUrl}`);
            }
        }

        const useCacheUrl = response.ok ? cacheUrl : pageUrl;

        // Construct the scraping URL
        const scrapingUrl = `https://web.scraper.zindex.eu.org/?url=${encodeURIComponent(useCacheUrl)}&selector=td.coll-1%2C+td.coll-2%2C+td.coll-3%2C+td.coll-date%2C+td.coll-4%2C+td.coll-5&scrape=text&spaced=true&pretty=true`;

        // Fetch the scraped data
        const scrapeResponse = await fetch(scrapingUrl);
        const data = await scrapeResponse.json();

        // Generate the item list
        generateItemList(data, 0, type);
        currentPage++; // Increment page for pagination

        // Show results and hide spinner
        document.getElementById('Top100ResultsBox').style.display = 'block';
    } catch (error) {
        console.error('Error fetching top 100:', error, ' Please report this issue to the developer at t.me/HashHackers');
    } finally {
        // Reset the request flag and hide spinner
        requestInProgress = false;
        hideSpinner("spinnerCard");
    }
}

async function fetchUserUploads(username, type) {
    showSpinner("spinnerCard");

    // Prevent multiple concurrent requests
    if (requestInProgress) return;
    requestInProgress = true;

    try {
        // Construct the initial URL
        const baseUrl = `https://1337x.to/${username}-torrents/${currentPage}/`;

        // Generate SHA-256 hash for the page URL
        const sha256Hash = await generateSHA256(baseUrl);
        const cacheUrl = `https://1337x-r2-torrents-cache.zindex.eu.org/${sha256Hash}.txt`;

        // Check if the hashed URL exists
        const response = await fetch(cacheUrl, { method: "HEAD" });

        if (!response.ok) {
            let request_cdn_to_cache = await fetch(`https://1337x-d1-static-api.zindex.eu.org/r2-request-api?url=${btoa(baseUrl)}`);
            if (request_cdn_to_cache.ok) {
                let request_cdn_to_cache_json = await request_cdn_to_cache.json();
                console.log(`Request Result: ${request_cdn_to_cache_json.status} and URL: ${request_cdn_to_cache_json.message}`);
            } else {
                console.log(`Request failed to cache URL: ${pageUrl}`);
            }
        }

        const useCacheUrl = response.ok ? cacheUrl : baseUrl;

        // Construct the scraping URL
        const scrapingUrl = `https://web.scraper.zindex.eu.org/?url=${encodeURIComponent(useCacheUrl)}&selector=td.coll-1%2C+td.coll-2%2C+td.coll-3%2C+td.coll-date%2C+td.coll-4%2C+td.coll-5&scrape=text&spaced=true&pretty=true`;

        // Fetch the scraped data
        const scrapeResponse = await fetch(scrapingUrl);
        const data = await scrapeResponse.json();

        // Generate the item list
        generateItemList(data, currentPage, type);
        currentPage++; // Increment page for pagination
    } catch (error) {
        console.error('Error fetching user uploads:', error, ' Please report this issue to the developer at t.me/HashHackers');
    } finally {
        // Reset the request flag and hide spinner
        requestInProgress = false;
        hideSpinner("spinnerCard");
    }
}

async function fetchData() {
    showSpinner("spinnerCard");

    // Prevent multiple concurrent requests
    if (requestInProgress) return;
    requestInProgress = true;

    try {
        // Extract search query and sort parameter from URL
        const searchQuery = new URLSearchParams(window.location.search).get('search');
        const sort = new URLSearchParams(window.location.search).get('sort');

        if (!searchQuery) {
            throw new Error('Search query is missing in the URL.');
        }

        // Construct the search path based on the sort parameter
        let constantForSearch;
        if (!sort) {
            constantForSearch = `search/${searchQuery.replace(' ', '+')}/${currentPage}`;
        } else {
            const sortMap = {
                size_asc: 'size/asc',
                size_desc: 'size/desc',
                time_asc: 'time/asc',
                time_desc: 'time/desc',
                seeders_asc: 'seeders/asc',
                seeders_desc: 'seeders/desc',
                leechers_asc: 'leechers/asc',
                leechers_desc: 'leechers/desc',
            };
            constantForSearch = `sort-search/${searchQuery.replace(' ', '+')}/${sortMap[sort]}/${currentPage}`;
        }

        // Construct the base URL
        const baseUrl = `https://1337x.to/${constantForSearch}/`;

        // Generate SHA-256 hash for the URL
        const sha256Hash = await generateSHA256(baseUrl);
        const cacheUrl = `https://1337x-r2-torrents-cache.zindex.eu.org/${sha256Hash}.txt`;

        // Check if the hashed URL exists
        const response = await fetch(cacheUrl, { method: "HEAD" });

        if (!response.ok) {
            let request_cdn_to_cache = await fetch(`https://1337x-d1-static-api.zindex.eu.org/r2-request-api?url=${btoa(baseUrl)}`);
            if (request_cdn_to_cache.ok) {
                let request_cdn_to_cache_json = await request_cdn_to_cache.json();
                console.log(`Request Result: ${request_cdn_to_cache_json.status} and URL: ${request_cdn_to_cache_json.message}`);
            } else {
                console.log(`Request failed to cache URL: ${pageUrl}`);
            }
        }

        const useCacheUrl = response.ok ? cacheUrl : baseUrl;

        // Construct the scraping URL
        const scrapingUrl = `https://web.scraper.zindex.eu.org/?url=${encodeURIComponent(useCacheUrl)}&selector=td.coll-1%2C+td.coll-2%2C+td.coll-3%2C+td.coll-date%2C+td.coll-4%2C+td.coll-5&scrape=text&spaced=true&pretty=true`;

        // Fetch the scraped data
        const scrapeResponse = await fetch(scrapingUrl);
        const data = await scrapeResponse.json();

        // Generate the item list
        generateItemList(data, currentPage, 'search');
        currentPage++; // Increment page for pagination
    } catch (error) {
        console.error('Error fetching search results:', error, ' Please report this issue to the developer at t.me/HashHackers');
    } finally {
        // Reset the request flag and hide spinner
        requestInProgress = false;
        hideSpinner("spinnerCard");
    }
}

// Generate item list from the fetched data
// Global scope variable to keep track of whether the event listener is added
let isEventListenerAdded = false;

function generateItemList(data, currentPage, type) {
    var itemList = document.getElementById('itemList');
    var results = data.result;

    if (results['td.coll-1'].length === 0) {
        // Show no results message
        document.getElementById('noMoreResultsBox').style.display = 'block';
        return;
    }

    var listContainer = document.createElement('ul');
    listContainer.className = 'list-group';

    for (var i = 0; i < results['td.coll-1'].length; i++) {
        var listItem = document.createElement('li');
        listItem.className = 'text-break list-group-item';
        listItem.setAttribute('data-magnet', 'true');

        // Extracting size value
        var sizeText = results['td.coll-4'][i];
        var size = sizeText.substring(0, sizeText.indexOf('B') + 1);

        // Get leeches and seeds count
        var leeches = parseInt(results['td.coll-3'][i]);
        var seeds = parseInt(results['td.coll-2'][i]);
        let details;
        if (type == 'user') {
            var username = new URLSearchParams(window.location.search).get('user');
            details = `<small class="d-block">Seeds (<span style="color: ${seeds > 0 ? 'green' : 'inherit'};">${seeds}</span>) Leecher (<span style="color: ${leeches > 0 ? 'red' : 'inherit'};">${leeches}</span>) by <a href="/?user=${username}">${username}</a> ${results['td.coll-5'][i]}</small>`;
        } else {
            details = `<small class="d-block">Seeds (<span style="color: ${seeds > 0 ? 'green' : 'inherit'};">${seeds}</span>) Leecher (<span style="color: ${leeches > 0 ? 'red' : 'inherit'};">${leeches}</span>) By <a href="/?user=${results['td.coll-5'][i]}">${results['td.coll-5'][i]}</a> on ${results['td.coll-date'][i]}</small>`;
        }

        var innerHTML = `
   <div class="d-flex align-items-center justify-content-between">
       <div style="width: 90%;">
           <a style="text-decoration: none; color: inherit;" class="clickable">${results['td.coll-1'][i]} - ${size}</a>
           ` + details + `
       </div>
       <button type="button" class="btn btn-link bi bi-box-arrow-up-right" onclick="goToSourcePage(${i}, ${currentPage}, '${type}')"></button>
   </div>
`;

        listItem.innerHTML = innerHTML;
        listContainer.appendChild(listItem);
    }

    itemList.appendChild(listContainer);

    // Adding event listener to handle clicking on the list item only once
    if (!isEventListenerAdded) {
        itemList.addEventListener('click', function(event) {
            var target = event.target;
            if (target.closest('.clickable') && target.closest('li').getAttribute('data-magnet') === 'true') {
                // Open magnet link
                var index = Array.from(target.closest('ul').children).indexOf(target.closest('li'));
                fetchMagnetLink(index, currentPage, type);
            }
        });
        isEventListenerAdded = true; // Set to true to prevent further additions
    }
}



// Check if search query is present in URL and fetch data for the initial page
var urlParams = new URLSearchParams(window.location.search);
var searchQuery = urlParams.get('search');
var sort = urlParams.get('sort');
var top100_type = urlParams.get('top100');
var user = urlParams.get('user');
if (sort) {
    document.getElementById('sortSelect').value = sort;
}
if (searchQuery !== null && searchQuery !== '') {
    // put the query in the search input
    document.getElementById('searchInput').value = searchQuery;
    fetchData();
} else if (top100_type !== null && top100_type !== '') {
    loadTop100(top100_type);
} else if (user !== null && user !== '') {
    fetchUserUploads(user, "user");
} else {
    loadTop100("top-100");
}

// Detect scroll to bottom of the page for pagination
window.addEventListener('scroll', function() {
    // Buffer to start loading more data
    var buffer = 100;
    // Check if scroll is at the bottom and there are more results to fetch
    if ((window.innerHeight + window.scrollY + buffer) >= document.body.offsetHeight && !requestInProgress && searchQuery !== null && searchQuery !== '' && document.getElementById('noMoreResultsBox').style.display !== 'block') {
        fetchData();
    } else if ((window.innerHeight + window.scrollY + buffer) >= document.body.offsetHeight && !requestInProgress && user !== null && user !== '' && document.getElementById('noMoreResultsBox').style.display !== 'block') {
        fetchUserUploads(user, "user");
    }
});


async function goToSourcePage(index, currentPage, type) {
    try {
        const searchQuery = new URLSearchParams(window.location.search).get('search');
        let url;

        // Determine the URL based on type
        if (type !== 'search') {
            // Generate SHA-256 hash for the `type` URL
            const baseUrl = `https://1337x.to/${type}`;
            const sha256Hash = await generateSHA256(baseUrl);
            const cacheUrl = `https://1337x-r2-torrents-cache.zindex.eu.org/${sha256Hash}.txt`;

            // Check if the hashed URL exists
            const response = await fetch(cacheUrl, { method: "HEAD" });

            if (!response.ok) {
            let request_cdn_to_cache = await fetch(`https://1337x-d1-static-api.zindex.eu.org/r2-request-api?url=${btoa(baseUrl)}`);
            if (request_cdn_to_cache.ok) {
                let request_cdn_to_cache_json = await request_cdn_to_cache.json();
                console.log(`Request Result: ${request_cdn_to_cache_json.status} and URL: ${request_cdn_to_cache_json.message}`);
            } else {
                console.log(`Request failed to cache URL: ${pageUrl}`);
            }
        }

            const useCacheUrl = response.ok ? cacheUrl : baseUrl;

            // Construct the scraping URL using the cached or original URL
            url = `https://web.scraper.zindex.eu.org/?url=${encodeURIComponent(useCacheUrl)}&selector=td.coll-1+a:nth-child(2)&scrape=attr&attr=href[${index}]&pretty=true`;
        } else if (type === 'search') {
            if (!searchQuery) {
                throw new Error('Search query is missing in the URL.');
            }

            const sort = new URLSearchParams(window.location.search).get('sort');
            let constantForSearch;

            if (!sort) {
                constantForSearch = `search/${searchQuery.replace(' ', '+')}/${currentPage}`;
            } else {
                const sortMap = {
                    size_asc: 'size/asc',
                    size_desc: 'size/desc',
                    time_asc: 'time/asc',
                    time_desc: 'time/desc',
                    seeders_asc: 'seeders/asc',
                    seeders_desc: 'seeders/desc',
                    leechers_asc: 'leechers/asc',
                    leechers_desc: 'leechers/desc',
                };
                constantForSearch = `sort-search/${searchQuery.replace(' ', '+')}/${sortMap[sort]}/${currentPage}`;
            }

            const baseUrl = `https://1337x.to/${constantForSearch}/`;
            const sha256Hash = await generateSHA256(baseUrl);
            const cacheUrl = `https://1337x-r2-torrents-cache.zindex.eu.org/${sha256Hash}.txt`;

            // Check if the hashed URL exists
            const response = await fetch(cacheUrl, { method: "HEAD" });

            if (!response.ok) {
                let request_cdn_to_cache = await fetch(`https://1337x-d1-static-api.zindex.eu.org/r2-request-api?url=${btoa(baseUrl)}`);
                if (request_cdn_to_cache.ok) {
                    let request_cdn_to_cache_json = await request_cdn_to_cache.json();
                    console.log(`Request Result: ${request_cdn_to_cache_json.status} and URL: ${request_cdn_to_cache_json.message}`);
                } else {
                    console.log(`Request failed to cache URL: ${pageUrl}`);
                }
            }

            const useCacheUrl = response.ok ? cacheUrl : baseUrl;

            // Construct the scraping URL using the cached or original URL
            url = `https://web.scraper.zindex.eu.org/?url=${encodeURIComponent(useCacheUrl)}&selector=td.coll-1+a:nth-child(2)&scrape=attr&attr=href[${index}]&pretty=true`;
        }

        // Fetch the torrent URL
        const response = await fetch(url);
        const data = await response.json();

        if (!data.result) {
            throw new Error('Torrent URL not found in the response.');
        }

        const torrentUrl = data.result;
        const timestamp = new Date().getTime();

        // Open the torrent URL in a new tab
        window.open(`https://1337x-to.pages.dev/processor/?path=/${timestamp}/${torrentUrl}`, '_blank');
    } catch (error) {
        console.error('Error fetching torrent URL:', error, ' Please report this issue to the developer at t.me/HashHackers');
    }
}

// Function to fetch magnet link based on selected item index
async function fetchMagnetLink(index, currentPage, type) {
    $('#torrentMagnetModal').modal('show');
    $('#loadingSpinner').show();
    $('#magnetLinkContainer').hide();
    $('#errorMessage').hide();

    const searchQuery = new URLSearchParams(window.location.search).get('search');
    let url;
    let url_1337x

    if (type === 'user') {
        const username = new URLSearchParams(window.location.search).get('user');
        url_1337x = `https://1337x.to/${username}-torrents/${currentPage}/`;
        url = `https://web.scraper.zindex.eu.org/?url=${url_1337x}&selector=td.coll-1+a:nth-child(2)&scrape=attr&attr=href[${index}]&pretty=true`;
        // Cache URL check block
        const sha256Hash = await generateSHA256(url_1337x);
        const cacheUrl = `https://1337x-r2-torrents-cache.zindex.eu.org/${sha256Hash}.txt`;

        const cacheResponse = await fetch(cacheUrl, { method: "HEAD" });

        if (cacheResponse.ok) {
            console.log(`Using cached URL: ${cacheUrl}`);
            // Use cached URL instead of scraping
            url = `https://web.scraper.zindex.eu.org/?url=${cacheUrl}&selector=td.coll-1+a:nth-child(2)&scrape=attr&attr=href[${index}]&pretty=true`;
        } else {
            let request_cdn_to_cache = await fetch(`https://1337x-d1-static-api.zindex.eu.org/r2-request-api?url=${btoa(url_1337x)}`);
            if (request_cdn_to_cache.ok) {
                let request_cdn_to_cache_json = await request_cdn_to_cache.json();
                console.log(`Request Result: ${request_cdn_to_cache_json.status} and URL: ${request_cdn_to_cache_json.message}`);
            } else {
                console.log(`Request failed to cache URL: ${url_1337x}`);
            }
            console.log(`Cache not found, using scraper URL: ${url}`);
            // Continue with the URL from the scraper
        }
    } else if (type === 'search') {
        const sort = new URLSearchParams(window.location.search).get('sort');
        const constantForSearch = sort === null
            ? `search/${searchQuery.replace(' ', '+')}/${currentPage}`
            : `sort-search/${searchQuery.replace(' ', '+')}/${sort.split('_')[0]}/${sort.split('_')[1]}/${currentPage}`;
        url_1337x = `https://1337x.to/${constantForSearch}/`
        url = `https://web.scraper.zindex.eu.org/?url=https://1337x.to/${constantForSearch}/&selector=td.coll-1+a:nth-child(2)&scrape=attr&attr=href[${index}]&pretty=true`;
        // Cache URL check block
        const sha256Hash = await generateSHA256(url_1337x);
        const cacheUrl = `https://1337x-r2-torrents-cache.zindex.eu.org/${sha256Hash}.txt`;

        const cacheResponse = await fetch(cacheUrl, { method: "HEAD" });

        if (cacheResponse.ok) {
            console.log(`Using cached URL: ${cacheUrl}`);
            // Use cached URL instead of scraping
            url = `https://web.scraper.zindex.eu.org/?url=${cacheUrl}&selector=td.coll-1+a:nth-child(2)&scrape=attr&attr=href[${index}]&pretty=true`;
        } else {
            let request_cdn_to_cache = await fetch(`https://1337x-d1-static-api.zindex.eu.org/r2-request-api?url=${btoa(url_1337x)}`);
            if (request_cdn_to_cache.ok) {
                let request_cdn_to_cache_json = await request_cdn_to_cache.json();
                console.log(`Request Result: ${request_cdn_to_cache_json.status} and URL: ${request_cdn_to_cache_json.message}`);
            } else {
                console.log(`Request failed to cache URL: ${url_1337x}`);
            }
            console.log(`Cache not found, using scraper URL: ${url}`);
            // Continue with the URL from the scraper
        }
    } else {
        url_1337x = `https://1337x.to/${type}`;
        url = `https://web.scraper.zindex.eu.org/?url=https://1337x.to/${type}&selector=td.coll-1+a:nth-child(2)&scrape=attr&attr=href[${index}]&pretty=true`;
        // Cache URL check block
        const sha256Hash = await generateSHA256(url_1337x);
        const cacheUrl = `https://1337x-r2-torrents-cache.zindex.eu.org/${sha256Hash}.txt`;

        const cacheResponse = await fetch(cacheUrl, { method: "HEAD" });

        if (cacheResponse.ok) {
            console.log(`Using cached URL: ${cacheUrl}`);
            // Use cached URL instead of scraping
            url = `https://web.scraper.zindex.eu.org/?url=${cacheUrl}&selector=td.coll-1+a:nth-child(2)&scrape=attr&attr=href[${index}]&pretty=true`;
        } else {
            let request_cdn_to_cache = await fetch(`https://1337x-d1-static-api.zindex.eu.org/r2-request-api?url=${btoa(url_1337x)}`);
            if (request_cdn_to_cache.ok) {
                let request_cdn_to_cache_json = await request_cdn_to_cache.json();
                console.log(`Request Result: ${request_cdn_to_cache_json.status} and URL: ${request_cdn_to_cache_json.message}`);
            } else {
                console.log(`Request failed to cache URL: ${url_1337x}`);
            }
            console.log(`Cache not found, using scraper URL: ${url}`);
            // Continue with the URL from the scraper
        }
    }


    try {
        const response = await fetch(url);
        const data = await response.json();
        let torrentUrl = data.result;

        // Cache URL check
        const sha256Hash = await generateSHA256("https://1337x.to" + torrentUrl);
        const cacheUrl = `https://1337x-r2-torrents-cache.zindex.eu.org/${sha256Hash}.txt`;
        let url_1337x = `https://1337x.to${torrentUrl}`;
        const cacheResponse = await fetch(cacheUrl, { method: "HEAD" });

        if (cacheResponse.ok) {
            console.log(`Using cache URL: ${cacheUrl}`);
            torrentUrl = cacheUrl; // Use the cached URL if found
            const fetchMagentfromCacheURL = await fetch(`https://web.scraper.zindex.eu.org/?url=${torrentUrl}&selector=div.no-top-radius+%3E+div+%3E+ul+%3E+li+%3E+a&scrape=attr&attr=href[0]&pretty=true`);
            let magnetLink;

            if (fetchMagentfromCacheURL.status === 200) {
                const data2 = await fetchMagentfromCacheURL.json();
                magnetLink = data2.result;
                if (magnetLink.startsWith('magnet:')) {
                    $('#magnetLinkInput').val(magnetLink);
                    $('#loadingSpinner').hide();
                    $('#magnetLinkContainer').show();
                    $('#modalFooter').show();
                } else {
                    $('#loadingSpinner').hide();
                    $('#errorMessage').text('Magnet link not found. Please report this issue to the developer at t.me/HashHackers');
                    $('#errorMessage').show();
                    $('#modalFooter').show();
                }
            } else {
              console.log(`Cache not found, something went wrong: ${torrentUrl}`);
            }
        } else {
            let request_cdn_to_cache = await fetch(`https://1337x-d1-static-api.zindex.eu.org/r2-request-api?url=${btoa(url_1337x)}`);
            if (request_cdn_to_cache.ok) {
                let request_cdn_to_cache_json = await request_cdn_to_cache.json();
                console.log(`Request Result: ${request_cdn_to_cache_json.status} and URL: ${request_cdn_to_cache_json.message}`);
            } else {
                console.log(`Request failed to cache URL: ${url_1337x}`);
            }
            console.log(`Cache not found, using original URL: ${torrentUrl}`);

            // Check CDN if cache is not available
            const fileCode = torrentUrl.split('/')[2];
            let githubRepoName;
            if (fileCode < 2000000) {
                githubRepoName = '1337x-torrents-1000000';
            } else if (fileCode >= 2000000 && fileCode < 3000000) {
                githubRepoName = '1337x-torrents-2000000';
            } else if (fileCode >= 3000000 && fileCode < 4000000) {
                githubRepoName = '1337x-torrents-3000000';
            } else if (fileCode >= 4000000 && fileCode < 5000000) {
                githubRepoName = '1337x-torrents-4000000';
            } else if (fileCode >= 5000000 && fileCode < 6000000) {
                githubRepoName = '1337x-torrents-5000000';
            } else if (fileCode >= 6000000 && fileCode < 7000000) {
                githubRepoName = '1337x-torrents-6000000';
            } else if (fileCode >= 7000000 && fileCode < 8000000) {
                githubRepoName = '1337x-torrents-7000000';
            } else if (fileCode >= 8000000 && fileCode < 9000000) {
                githubRepoName = '1337x-torrents-8000000';
            } else if (fileCode >= 9000000 && fileCode < 10000000) {
                githubRepoName = '1337x-torrents-9000000';
            } else if (fileCode >= 10000000) {
                githubRepoName = '1337x-torrents-10000000';
            }

            const checkCdn = await fetch(`https://${githubRepoName}.pages.dev/torrent/${fileCode}/?time=${new Date().getTime()}`);
            let urlForMagnetRequest;
            let magnetLink;

            if (checkCdn.status === 200) {
                const cdnContent = await checkCdn.text();
                if (cdnContent.startsWith('magnet')) {
                    console.log('Magnet link found in CDN');
                    magnetLink = cdnContent;
                } else {
                    const creationDate = cdnContent.match(/<meta name="creation_date" content="(\d+)" \/>/)[1];
                    console.log('Creation date:', creationDate);

                    if (new Date().getTime() - creationDate > 30 * 24 * 60 * 60 * 1000) {
                        fetch(`https://data-saver.1337x-api.hashhackersapi.workers.dev${torrentUrl}?force_update=true`);
                    }
                    urlForMagnetRequest = `https://${githubRepoName}.pages.dev/torrent/${fileCode}/?time=${new Date().getTime()}`;
                    const response2 = await fetch(`https://web.scraper.zindex.eu.org/?url=${urlForMagnetRequest}&selector=div.no-top-radius+%3E+div+%3E+ul+%3E+li+%3E+a&scrape=attr&attr=href[0]&pretty=true`);
                    const data2 = await response2.json();
                    magnetLink = data2.result;
                }
            } else {
                urlForMagnetRequest = `https://1337x.to${torrentUrl}`;
                fetch(`https://data-saver.1337x-api.hashhackersapi.workers.dev${torrentUrl}`);
                const response2 = await fetch(`https://web.scraper.zindex.eu.org/?url=${urlForMagnetRequest}&selector=div.no-top-radius+%3E+div+%3E+ul+%3E+li+%3E+a&scrape=attr&attr=href[0]&pretty=true`);
                const data2 = await response2.json();
                magnetLink = data2.result;
            }

            if (magnetLink.startsWith('magnet:')) {
                $('#magnetLinkInput').val(magnetLink);
                $('#loadingSpinner').hide();
                $('#magnetLinkContainer').show();
                $('#modalFooter').show();
            } else {
                $('#loadingSpinner').hide();
                $('#errorMessage').text('Magnet link not found. Please report this issue to the developer at t.me/HashHackers');
                $('#errorMessage').show();
                $('#modalFooter').show();
            }
        }
        // since cacheURL is now av
    } catch (error) {
        console.error('Error fetching magnet link or torrent URL:', error, ' Please report this issue to the developer at t.me/HashHackers');
        $('#loadingSpinner').hide();
        $('#errorMessage').text('Error fetching magnet link or torrent URL. Please report this issue to the developer at t.me/HashHackers');
        $('#errorMessage').show();
        $('#modalFooter').show();
    }
}



// Copy magnet link to clipboard
document.getElementById('copyButton').addEventListener('click', function() {
    var magnetLinkInput = document.getElementById('magnetLinkInput');
    magnetLinkInput.select();
    document.execCommand('copy');
});

document.addEventListener('click', function() {
    //handleImportantClick();
});
</script>
   <!-- Cloudflare Pages Analytics --><script defer="" src="https://static.cloudflareinsights.com/beacon.min.js" data-cf-beacon="{&quot;token&quot;: &quot;bee6f643c1624ba9a389c92d8ad76b20&quot;}"></script><!-- Cloudflare Pages Analytics -->
</body></html>