
[php] Regex creator to parse (2025/08/29)
----------------------
<?php
$pageSource = '';
$urlValue = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['url'])) {
    $url = filter_var($_POST['url'], FILTER_VALIDATE_URL);
    if ($url) {
        $urlValue = $url;
        $pageSource = @file_get_contents($url);
        if ($pageSource === false) {
            $pageSource = "Failed to fetch the page.";
        } else {
            $pageSource = htmlspecialchars($pageSource);
        }
    } else {
        $pageSource = "Invalid URL";
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Page Source Parser Tool</title>
</head>
<body>

<h2>Fetch Page Source</h2>
<form method="POST">
    <input type="text" name="url" id="urlInput" placeholder="Enter URL" style="width:300px" value="<?php echo htmlspecialchars($urlValue); ?>" required>
    <button type="submit">Fetch</button>
    <button type="button" id="clearStorageBtn">Clear Storage</button>
</form>

<h3>Page Source:</h3>
<textarea id="pageSource" rows="15" cols="80"><?php echo $pageSource; ?></textarea>

<h2>Compare Text Snippet</h2>
<textarea id="textSnippet" rows="5" cols="80" placeholder="Paste text snippet here"></textarea>
<br>
<label><input type="checkbox" id="useDelim" checked> Use Delimiters</label>
<label><input type="checkbox" id="matchWhole"> Match Whole Snippet</label>
<label><input type="checkbox" id="captureGroup"> Capture Groups</label>
<label><input type="checkbox" id="smartCapture"> Smart Capture</label>
<br><button id="compareBtn">Compare</button>

<h3>Feedback:</h3>
<div id="feedback"></div>

<script>
// Save URL and page source to localStorage automatically
const urlInput = document.getElementById('urlInput');
const pageSourceTextarea = document.getElementById('pageSource');
if (pageSourceTextarea.value.trim() !== '' && urlInput.value.trim() !== '') {
    localStorage.setItem('savedURL', urlInput.value.trim());
    localStorage.setItem('pageSource', pageSourceTextarea.value);
}

// Preload saved URL and page source if present
window.addEventListener('DOMContentLoaded', () => {
    const savedURL = localStorage.getItem('savedURL');
    const savedSource = localStorage.getItem('pageSource');
    if (savedURL) urlInput.value = savedURL;
    if (savedSource) pageSourceTextarea.value = savedSource;
});

// Compare snippet and generate PHP parser with robust Smart Capture
document.getElementById('compareBtn').addEventListener('click', () => {
    const snippet = document.getElementById('textSnippet').value.trim();
    const source = localStorage.getItem('pageSource') || '';
    const savedURL = localStorage.getItem('savedURL') || 'URL_HERE';
    const useDelim = document.getElementById('useDelim').checked;
    const matchWhole = document.getElementById('matchWhole').checked;
    const captureGroup = document.getElementById('captureGroup').checked;
    const smartCapture = document.getElementById('smartCapture').checked;

    if (!snippet) {
        document.getElementById('feedback').textContent = 'Please enter a snippet to compare.';
        return;
    }

    if (!source.includes(snippet)) {
        document.getElementById('feedback').textContent = '❌ Snippet not found in page source.';
        return;
    }

    let phpPattern = '';
    let useCapture = captureGroup || smartCapture;
    let phpCode = '';

    if (matchWhole) {
        phpPattern = snippet.replace(/\\/g, '\\\\').replace(/'/g, "\\'").replace(/\//g, '\\/').replace(/\n/g, '\\n').replace(/\r/g, '');
        phpCode = `<code>
&lt;?php
$html = file_get_contents('${savedURL}');
$pattern = '/${phpPattern}/';
preg_match($pattern, $html, $matches);
if (!empty($matches)) {
    echo "✅ Match found:\\n";
    print_r($matches);
} else {
    echo "❌ No match found.\\n";
}
?&gt;
</code>`;
    } else if (useDelim) {
        const start = snippet.substring(0, 20).replace(/\\/g, '\\\\').replace(/\//g, '\\/').replace(/'/g, "\\'");
        const end = snippet.substring(snippet.length - 20).replace(/\\/g, '\\\\').replace(/\//g, '\\/').replace(/'/g, "\\'");
        phpPattern = start + (useCapture ? '(.*?)' : '') + end;
        phpCode = `<code>
&lt;?php
$html = file_get_contents('${savedURL}');
$pattern = '/${phpPattern}/s';
preg_match($pattern, $html, $matches);
if (!empty($matches)) {
    ${useCapture ? 'echo "✅ Match found: " . $matches[1] . "\\n";' : 'echo "✅ Match found:\\n"; print_r($matches);'}
} else {
    echo "❌ No match found.\\n";
    echo "Regex used: $pattern\\n";
}
?&gt;
</code>`;
    } else if (smartCapture) {
        let code = '';
        // Try to detect JSON block in page source
        code += `<code>
&lt;?php
$html = file_get_contents('${savedURL}');
`;
        // Simple heuristic: check if snippet contains URL
        const urlMatch = snippet.match(/https?:\/\/[^\s",]+/);
        if (urlMatch) {
            const urlStart = urlMatch[0].replace(/\\/g, '\\\\').replace(/\//g, '\\/').replace(/'/g, "\\'");
            code += `$pattern = '/${urlStart}/';
preg_match($pattern, $html, $matches);
if (!empty($matches)) {
    echo "✅ URL found: " . $matches[0] . "\\n";
} else {
    echo "❌ URL not found.\\n";
    echo "Regex used: $pattern\\n";
}
?&gt;
</code>`;
        } else {
            // Fallback to extracting JSON
            code += `preg_match('/<script type="application\\/json">(.*?)<\\/script>/s', $html, $matches);
if (!empty($matches)) {
    $data = json_decode($matches[1], true);
    echo "✅ JSON extracted. Example:\n";
    print_r(array_slice($data, 0, 3)); // show first 3 keys
} else {
    echo "❌ JSON not found.\\n";
}
?&gt;
</code>`;
        }
        phpCode = code;
    }

    document.getElementById('feedback').innerHTML = `✅ Snippet found in page source.<br>Generated PHP parser with debug:<br>${phpCode}`;
});

// Clear all localStorage entries
document.getElementById('clearStorageBtn').addEventListener('click', () => {
    localStorage.removeItem('savedURL');
    localStorage.removeItem('pageSource');
    document.getElementById('feedback').textContent = '✅ Local storage cleared.';
    urlInput.value = '';
    pageSourceTextarea.value = '';
    document.getElementById('textSnippet').value = '';
});
</script>

</body>
</html>



[python] Audio part splicer (for song reconstruction) (2025/08/09)
-------------

import tkinter as tk
from tkinterdnd2 import TkinterDnD, DND_FILES
import librosa
import numpy as np
from pydub import AudioSegment

# Helper function to load audio file using librosa
def load_audio(file_path):
    audio, sr = librosa.load(file_path, sr=None)
    return audio, sr

# Function to compute cross-correlation for overlap detection
def find_overlap(audio1, audio2, sr):
    # Compute cross-correlation
    correlation = np.correlate(audio1, audio2, mode='full')
    overlap_point = np.argmax(np.abs(correlation)) - len(audio1) + 1
    return overlap_point

# Function to stitch audio files based on overlap
def stitch_audio(file1, file2):
    # Load the audio files
    audio1, sr1 = load_audio(file1)
    audio2, sr2 = load_audio(file2)

    if sr1 != sr2:
        raise ValueError("Sample rates do not match!")

    # Find the overlap between the two audio files
    overlap_point = find_overlap(audio1, audio2, sr1)

    # Slice the overlapping part from audio2
    audio2_aligned = audio2[overlap_point:]
    
    # Combine the two audio clips
    combined_audio = np.concatenate([audio1, audio2_aligned])

    # Convert back to AudioSegment for export
    combined_audio_segment = AudioSegment(
        combined_audio.tobytes(), frame_rate=sr1, sample_width=combined_audio.itemsize, channels=1)

    return combined_audio_segment

# GUI setup using Tkinter
def create_gui():
    root = TkinterDnD.Tk()

    # Title and window size
    root.title("Audio Stitcher")
    root.geometry("500x400")

    # Label to display instructions
    label = tk.Label(root, text="Drag and drop audio files here", pady=20, padx=20)
    label.pack()

    # Function to handle file drop
    def handle_drop(event):
        files = event.data.split()
        if len(files) == 2:
            try:
                # Stitch the two audio files
                combined_audio = stitch_audio(files[0], files[1])

                # Save the output
                combined_audio.export("combined_output.wav", format="wav")
                label.config(text="Stitching complete! Output saved as 'combined_output.wav'.")
            except Exception as e:
                label.config(text=f"Error: {e}")
        else:
            label.config(text="Please drop exactly 2 audio files.")

    # Make the window a drop target for files
    root.drop_target_register(DND_FILES)
    root.dnd_bind('<<Drop>>', handle_drop)

    # Run the GUI loop
    root.mainloop()

# Start the GUI
create_gui()



[PHP&JS] Youtube Video Downloader (2025/06/23)
-------------------------------

Nice idea.
Get the cookies and ip from browser.
Feed to php, open youtubelink.
Fetch "" from json and get the downloadlinks in 360p,480p and 720p.
But alas. the cipher will change routinely and I can't even get this version to work.
Let's stick to notube.cc (webbrowser) and JDownloader2,yt-dl (Windows) instead.
They are maintaining and keepign up with Googles cat-n-mouse game.
I have better thing to do than waste my time on a giga corp.


YTDownload.php
--
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>YouTube Player JSON Extractor</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
        }
        .output {
            border: 1px solid #ccc;
            padding: 10px;
            margin-top: 10px;
            white-space: pre-wrap;
        }
    </style>
</head>
<body>

<h1>YouTube Player JSON Extractor</h1>
<form method="post">
    <label for="youtubeUrl">YouTube URL:</label><br>
    <input type="text" id="youtubeUrl" name="youtubeUrl" required><br><br>

    <label for="inputData">Paste Cookies and IP:</label><br>
    <textarea id="inputData" name="inputData" rows="10" cols="50" required></textarea><br><br>

    <input type="submit" value="Extract JSON">
</form>

<div class="output" id="cookiesOutput"><strong>Extracted Cookies:</strong><br></div>
<div class="output" id="ipOutput"><strong>Public IP Address:</strong><br></div>

<div class="output" id="jsonOutput">
    <?php
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $youtubeUrl = $_POST['youtubeUrl'];
        $inputData = $_POST['inputData'];

        $lines = explode("\n", $inputData);
        $cookies = [];
        $ip = '';

        foreach ($lines as $line) {
            $line = trim($line);
            if (strpos($line, 'PREF=') !== false || strpos($line, 'SID=') !== false) {
                $cookies[] = $line;
            } elseif (preg_match('/^(?:\d{1,3}\.){3}\d{1,3}$/', $line)) {
                $ip = $line;
            }
        }

        $cookieString = implode('; ', $cookies);

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $youtubeUrl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Cookie: ' . $cookieString,
            'X-Forwarded-For: ' . $ip,
            'User-Agent: Mozilla/5.0'
        ]);
        $response = curl_exec($ch);
        curl_close($ch);

        echo "<strong>Download Links:</strong><br>";

        if (preg_match('/ytInitialPlayerResponse\s*=\s*(\{.*?\});/s', $response, $matches)) {
            $jsonString = $matches[1];
            $jsonData = json_decode($jsonString, true);

            if (isset($jsonData['streamingData']['formats'])) {
                $formats = $jsonData['streamingData']['formats'];

                echo "<ul>";
                foreach ($formats as $format) {
                    if (isset($format['height']) && in_array($format['height'], [360, 480, 720])) {
                        $downloadUrl = '';

                        if (isset($format['url'])) {
                            $downloadUrl = $format['url'];
                        } elseif (isset($format['signatureCipher'])) {
                            parse_str($format['signatureCipher'], $cipher);
                            if (isset($cipher['url'])) {
                                $downloadUrl = $cipher['url'];
                                if (isset($cipher['sig'])) {
                                    $downloadUrl .= '&sig=' . $cipher['sig'];
                                } elseif (isset($cipher['s'])) {
                                    $downloadUrl .= '&s=' . $cipher['s']; // This may require deciphering
                                }
                            }
                        }

                        if ($downloadUrl) {
                            $safeUrl = htmlspecialchars($downloadUrl);
                            echo "<li>{$format['height']}p: <a href=\"$safeUrl\" target=\"_blank\">Download</a></li>";
                        } else {
                            echo "<li>{$format['height']}p: No direct link (possibly encrypted)</li>";
                        }
                    }
                }
                echo "</ul>";
            } else {
                echo "No video formats found.";
            }

            // Show raw JSON preview
            echo "<hr><strong>Initial Player JSON:</strong><br><pre>" . htmlspecialchars($jsonString) . "</pre>";
        } else {
            echo "Failed to extract player JSON.";
        }
    }
    ?>
</div>

<script>
    document.getElementById('inputData').addEventListener('input', function () {
        const inputData = this.value;
        const lines = inputData.split('\n');
        const cookies = [];
        let ip = '';

        lines.forEach(line => {
            line = line.trim();
            if (line.includes('PREF=') || line.includes('SID=')) {
                cookies.push(line);
            } else if (/^(?:\d{1,3}\.){3}\d{1,3}$/.test(line)) {
                ip = line;
            }
        });

        document.getElementById('cookiesOutput').innerHTML = '<strong>Extracted Cookies:</strong><br>' + (cookies.length ? cookies.join('<br>') : 'None found');
        document.getElementById('ipOutput').innerHTML = '<strong>Public IP Address:</strong><br>' + (ip || 'Not found');
    });
</script>

</body>
</html>


GetCookiesN-IP-Bookmarklet.txt
--
javascript:(function(){
  function getCookieString() {
    return document.cookie || "(no cookies)";
  }
  function getPublicIP(callback) {
    fetch('https://api.ipify.org?format=json')
      .then(response => response.json())
      .then(data => callback(data.ip))
      .catch(() => callback('Unable to fetch IP'));
  }
  function copyToClipboard(text) {
    navigator.clipboard.writeText(text).then(() => {
      alert("Copied to clipboard!");
    }, () => {
      alert("Copy failed");
    });
  }
  function createPopup(ip, cookies) {
    if(document.getElementById('cookie-ip-popup')) {
      document.getElementById('cookie-ip-popup').remove();
    }
    const popup = document.createElement('div');
    popup.id = 'cookie-ip-popup';
    popup.style.position = 'fixed';
    popup.style.bottom = '20px';
    popup.style.right = '20px';
    popup.style.backgroundColor = '#222';
    popup.style.color = '#eee';
    popup.style.padding = '15px';
    popup.style.borderRadius = '8px';
    popup.style.boxShadow = '0 0 10px rgba(0,0,0,0.5)';
    popup.style.zIndex = 999999;
    popup.style.maxWidth = '320px';
    popup.style.fontFamily = 'monospace';
    popup.style.fontSize = '12px';
    popup.style.whiteSpace = 'pre-wrap';
    const content = `Cookies:\n${cookies}\n\nPublic IP:\n${ip}`;
    popup.textContent = content;
    const btn = document.createElement('button');
    btn.textContent = 'Copy to Clipboard';
    btn.style.marginTop = '10px';
    btn.style.padding = '5px 10px';
    btn.style.cursor = 'pointer';
    btn.style.backgroundColor = '#4CAF50';
    btn.style.border = 'none';
    btn.style.borderRadius = '4px';
    btn.style.color = '#fff';
    btn.style.fontWeight = 'bold';
    btn.onclick = () => copyToClipboard(content);
    popup.appendChild(document.createElement('br'));
    popup.appendChild(btn);
    document.body.appendChild(popup);
  }
  getPublicIP(function(ip){
    createPopup(ip, getCookieString());
  });
})();
