// ==UserScript==
// @name Siftstrym Delete
// @namespace http://tampermonkey.net/
// @version 4.0
// @description Safely and efficiently bulk delete X.com posts and bookmarks with rate limit evasion and native UI.
// @author mkhairulhan
// @match https://x.com/*
// @match https://twitter.com/*
// @icon https://abs.twimg.com/favicons/twitter.3.ico
// @grant GM_setValue
// @grant GM_getValue
// @updateURL https://raw.githubusercontent.com/mkhairulhan/sift-delete/main/sift_delete.user.js
// @downloadURL https://raw.githubusercontent.com/mkhairulhan/sift-delete/main/sift_delete.user.js
// @run-at document-idle
// ==/UserScript==
(function() {
'use strict';
// --- Core State & Persistence ---
let isUIOpen = false;
let running = false;
let mode = "";
let stats = { scanned: 0, targeted: 0, limits: 0 };
let isDryRun = true; // Default to safe mode
// Load previously processed IDs from Tampermonkey secure storage
let processedIds = JSON.parse(GM_getValue("x_processed_ids", "[]"));
let processed = new Set(processedIds);
const saveState = () => {
GM_setValue("x_processed_ids", JSON.stringify(Array.from(processed)));
};
const sleep = (ms) => new Promise(r => setTimeout(r, ms));
const randomJitter = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
// --- Auth Harvesting ---
const getCsrf = () => {
const match = document.cookie.match(/ct0=([^;]+)/);
return match ? match[1] : null;
};
const BEARER = "AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA";
// --- Sidebar Injection (Native Integration) ---
const injectSidebarTrigger = () => {
if (document.getElementById("x-deleter-trigger-btn")) return;
// X's primary navigation role is 'banner' or aria-label 'Primary'
const nav = document.querySelector('nav[aria-label="Primary"]') || document.querySelector('[role="banner"] nav');
if (!nav) return;
const btn = document.createElement("a");
btn.id = "x-deleter-trigger-btn";
btn.role = "link";
btn.style.cssText = "display: flex; align-items: center; justify-content: flex-start; padding: 12px; margin: 4px 0; border-radius: 9999px; cursor: pointer; transition: background-color 0.2s; color: #e7e9ea; text-decoration: none;";
// Mimic X's native hover state
btn.addEventListener("mouseover", () => btn.style.backgroundColor = "rgba(231, 233, 234, 0.1)");
btn.addEventListener("mouseout", () => btn.style.backgroundColor = "transparent");
btn.innerHTML = `
Select target payload:
๐พ Local Cache: ${processed.size} items skipped
Scanned
0
Actioned
0
Limits Hit
0
Ready to initialize...
`;
document.body.appendChild(ui);
// --- Draggable Logic (GPU Accelerated) ---
const dragHandle = document.getElementById("x-drag-handle");
let isDragging = false;
let currentX, currentY, initialX, initialY;
let xOffset = 0, yOffset = 0;
const dragStart = (e) => {
if (e.target.id === "x-close") return;
initialX = e.clientX - xOffset;
initialY = e.clientY - yOffset;
isDragging = true;
};
const drag = (e) => {
if (isDragging) {
e.preventDefault();
currentX = e.clientX - initialX;
currentY = e.clientY - initialY;
xOffset = currentX;
yOffset = currentY;
ui.style.transform = `translate3d(calc(-50% + ${currentX}px), ${currentY}px, 0)`;
}
};
const dragEnd = () => { initialX = currentX; initialY = currentY; isDragging = false; };
dragHandle.addEventListener("mousedown", dragStart);
document.addEventListener("mousemove", drag);
document.addEventListener("mouseup", dragEnd);
// --- UI Controllers ---
const updatePulse = (state) => {
const p = document.getElementById("x-pulse-indicator");
if(p) p.className = `x-pulse ${state}`;
};
const updateStats = (scannedMod = 0, targetedMod = 0, limitsMod = 0) => {
stats.scanned += scannedMod;
stats.targeted += targetedMod;
stats.limits += limitsMod;
document.getElementById("x-stat-scanned").textContent = stats.scanned;
document.getElementById("x-stat-targeted").textContent = stats.targeted;
document.getElementById("x-stat-limits").textContent = stats.limits;
};
const updateStatus = (text, color = "#8b949e") => {
const statusEl = document.getElementById("x-status");
if(statusEl) {
statusEl.textContent = text;
statusEl.style.color = color;
}
};
document.getElementById("x-close").onclick = () => {
running = false;
isUIOpen = false;
ui.remove();
document.getElementById("x-cleanup-styles")?.remove();
};
document.getElementById("x-back").onclick = () => {
running = false;
document.getElementById("x-step1").style.display = "block";
document.getElementById("x-step2").style.display = "none";
updatePulse("stopped");
updateStatus("Ready to initialize...", "#8b949e");
document.getElementById("x-run").disabled = false;
document.getElementById("x-stop").disabled = true;
};
document.getElementById("x-clear-cache").onclick = () => {
if (confirm("Clear local memory cache? This forces the script to re-scan tweets it previously skipped.")) {
processed.clear();
saveState();
document.getElementById("x-clear-cache").innerHTML = `๐พ Local Cache: 0 items skipped`;
}
};
const showStep2 = (m) => {
mode = m;
stats = { scanned: 0, targeted: 0, limits: 0 };
updateStats(0,0,0);
document.getElementById("x-step1").style.display = "none";
document.getElementById("x-step2").style.display = "block";
document.getElementById("x-mode-label").innerHTML = m === "post" ? "๐ Targeting: Posts & Retweets" : "๐ Targeting: Saved Bookmarks";
};
document.getElementById("x-select-post").onclick = () => showStep2("post");
document.getElementById("x-select-bm").onclick = () => showStep2("bookmark");
// --- Core Logic ---
const inRange = (datetime) => {
const sv = document.getElementById("x-start").value;
const ev = document.getElementById("x-end").value;
if (!sv && !ev) return true;
const d = new Date(datetime);
if (sv) {
const s = new Date(sv);
s.setHours(0, 0, 0, 0);
if (d < s) return false;
}
if (ev) {
const e = new Date(ev);
e.setHours(23, 59, 59, 999);
if (d > e) return false;
}
return true;
};
const fetchWithRetry = async (url, options) => {
let backoff = 10000;
let maxRetries = 5;
for (let i = 0; i < maxRetries; i++) {
if (!running) return null;
updatePulse("active");
const res = await fetch(url, options);
if (res.status === 429) {
updateStats(0, 0, 1);
updatePulse("rate-limit");
const resetHeader = res.headers.get('x-rate-limit-reset');
let waitTime = backoff;
if (resetHeader) {
const resetMs = parseInt(resetHeader) * 1000;
waitTime = Math.max(resetMs - Date.now(), 5000) + 2000;
const resetTime = new Date(resetMs).toLocaleTimeString();
updateStatus(`HTTP 429: API Limit Exceeded. Paused until ${resetTime}.`, "#f85149");
} else {
updateStatus(`HTTP 429: API Limit. Backoff initiated (${waitTime/1000}s)...`, "#f85149");
backoff *= 2;
}
await sleep(waitTime);
updateStatus(`Resuming operation...`, "#d29922");
continue;
}
return res;
}
throw new Error("Max retries exceeded for rate limit.");
};
const removeBookmarks = async () => {
const articles = document.querySelectorAll("article");
let cycleTargeted = 0;
for (let i = 0; i < articles.length; i++) {
if (!running) break;
const article = articles[i];
// Skip previously scanned bookmarks (rudimentary cache via text content)
const cacheKey = "bm_" + (article.textContent.substring(0, 50).replace(/\s/g, ''));
if (processed.has(cacheKey)) continue;
const timeEl = article.querySelector("time");
const datetime = timeEl ? timeEl.getAttribute("datetime") : null;
const btn = article.querySelector('[data-testid="removeBookmark"]') || article.querySelector('[aria-label="Bookmarked"]');
if (!btn) continue;
updateStats(1, 0, 0);
if (datetime && !inRange(datetime)) {
processed.add(cacheKey);
continue;
}
processed.add(cacheKey);
if (isDryRun) {
cycleTargeted++;
updateStats(0, 1, 0);
updateStatus(`[DRY RUN] Identified bookmark for deletion.`, "#58a6ff");
await sleep(100 + randomJitter(50, 100));
continue;
}
updatePulse("active");
btn.click();
cycleTargeted++;
updateStats(0, 1, 0);
updateStatus(`Removing bookmark...`, "#c9d1d9");
await sleep(600 + randomJitter(200, 600));
const conf = document.querySelector('[data-testid="confirmationSheetConfirm"]');
if (conf) {
conf.click();
await sleep(400 + randomJitter(100, 300));
}
updatePulse("stopped");
}
saveState();
return cycleTargeted;
};
const removePosts = async () => {
const arts = Array.from(document.querySelectorAll('article[data-testid="tweet"]'));
let cycleTargeted = 0;
for (let i = 0; i < arts.length; i++) {
if (!running) break;
const a = arts[i];
const tEl = a.querySelector("time");
const link = a.querySelector('a[href*="/status/"]');
if (!link || !tEl) continue;
const m = link.href.match(/\/status\/(\d+)/);
if (!m) continue;
const id = m[1];
if (!id || processed.has(id)) continue;
updateStats(1, 0, 0);
const datetime = tEl.getAttribute("datetime");
if (!inRange(datetime)) {
processed.add(id);
continue;
}
processed.add(id);
const isRT = !!a.querySelector('[data-testid="unretweet"]');
const op = isRT ? "Unretweet" : "DeleteTweet";
if (isDryRun) {
cycleTargeted++;
updateStats(0, 1, 0);
updateStatus(`[DRY RUN] Would ${isRT ? "Un-RT" : "Delete"} ID: ${id}`, "#58a6ff");
await sleep(100 + randomJitter(50, 100));
continue;
}
const qid = isRT ? "iQtK4v9v8vT8zVO9gU90xw" : "VaenaVgh5q5ih7kvyVjgtg";
const csrf = getCsrf();
updateStatus(`${isRT ? "Un-RTing" : "Deleting"} payload...`, "#c9d1d9");
try {
const url = "https://x.com/i/api/graphql/" + qid + "/" + op;
const payload = {
method: "POST",
headers: {
"authorization": "Bearer " + BEARER,
"x-csrf-token": csrf,
"content-type": "application/json",
"x-twitter-active-user": "yes"
},
body: JSON.stringify({
variables: { [isRT ? "source_tweet_id" : "tweet_id"]: id, dark_request: false },
queryId: qid
})
};
const res = await fetchWithRetry(url, payload);
if (res && res.ok) {
cycleTargeted++;
updateStats(0, 1, 0);
updateStatus(`Successfully processed payload.`, "#3fb950");
updatePulse("stopped");
await sleep(2000 + randomJitter(500, 1500));
}
} catch (e) {
console.error("X Bulk Deleter API Error:", e);
}
}
saveState();
return cycleTargeted;
};
// --- Execution Controls ---
document.getElementById("x-stop").onclick = () => {
running = false;
document.getElementById("x-stop").disabled = true;
updatePulse("stopped");
updateStatus(`Operation halted by user.`, "#d29922");
};
document.getElementById("x-run").onclick = async () => {
if (!getCsrf() && mode === "post") {
alert("Auth Error: Please log in to X and open your profile page.");
return;
}
isDryRun = document.getElementById("x-dry-run").checked;
running = true;
document.getElementById("x-run").disabled = true;
document.getElementById("x-stop").disabled = false;
updateStatus("Initializing payload sweep...", isDryRun ? "#58a6ff" : "#3fb950");
let noNewCount = 0;
while (running) {
let cycleTargeted = mode === "post" ? await removePosts() : await removeBookmarks();
if (cycleTargeted > 0) {
noNewCount = 0;
await sleep(800 + randomJitter(200, 500));
} else {
updateStatus("Sweeping timeline... scrolling down.", "#8b949e");
window.scrollBy(0, 1500);
await sleep(1500 + randomJitter(300, 800));
noNewCount++;
}
// Stop if we scroll 6 times and find absolutely nothing new
if (noNewCount >= 6) {
running = false;
break;
}
}
document.getElementById("x-run").disabled = false;
document.getElementById("x-stop").disabled = true;
updatePulse("stopped");
updateStatus(`โ
Operation Complete. ${stats.targeted} items actioned.`, isDryRun ? "#58a6ff" : "#3fb950");
};
};
})();