/**
* IGCleaner. instagram.com sekmesinde, giriş yapmışken, DevTools konsoluna yapıştır.
* Sağda küçük bir panel açılır. Sayfanın geri kalanı tıklanabilir kalır.
* Menü: Mesaj sil, Kaydedilenler. Yapıştırınca hiçbir şey silinmez.
*
* Mesaj silmek sohbeti sadece senin kutundan kaldırır. Karşı tarafın kopyası durur.
* Kaydedilenleri kaldırmak gönderiyi silmez; sadece senin kaydından düşer.
* Şifre ve çerez sayfa dışına çıkmaz.
*
* Dil: IG_LANG "tr" veya "en". İlk açılışta bu kullanılır.
* Paneldeki TR | EN seçimi hatırlanır ve bir sonraki yapıştırmada bunu ezer.
*/
(() => {
"use strict";
const IG_BRAND = {
title: "IGCleaner",
handle: "@tahsingibi",
handleUrl: "https://x.com/tahsingibi/",
site: "sungur.dev",
siteUrl: "https://sungur.dev",
github: "github.com/tahsingibi/igcleaner",
githubUrl: "https://github.com/tahsingibi/igcleaner",
};
const IG_LANG = "tr";
const IG_TEXT = {
tr: {
scanIdle: "Hazır. Önce ayarları düzenleyebilir, ardından Taramayı başlat düğmesine basabilirsin.",
startScan: "Taramayı başlat",
rescan: "Yeniden tara",
notScanned: "Henüz tarama yapılmadı.",
cacheNotice: "Önceki tarama gösteriliyor · {time} · {n} kayıt. Liste güncel olmayabilir.",
cachePrivacy: "Tarama sonuçları bu Instagram hesabına özel olarak tarayıcıda 24 saat saklanır.",
clearCache: "Kayıtlı taramaları temizle",
cacheCleared: "Kayıtlı taramalar temizlendi.",
settingsTiming: "İstek temposu",
settingsData: "Kayıtlı taramalar",
settingsDone: "Tamam",
delayHint: "2–120 saniye · varsayılan 4,5",
batchHint: "1–20 istek · varsayılan 5",
restHint: "30–3600 saniye · varsayılan 300",
settings: "Ayarlar",
delaySeconds: "İstekler arası bekleme (saniye)",
batchEvery: "Kaç istekten sonra mola",
breakSeconds: "Mola süresi (saniye)",
resetSettings: "Varsayılanlara dön",
settingsNote: "Ayarlar bu tarayıcıda saklanır. Düşük süreler kısıtlama riskini artırır. İşlem sırasında değiştirilemez.",
riskWarning: "Uyarı: Otomatik işlemler hesabınızın kısıtlanmasına veya askıya alınmasına yol açabilir. Hiçbir bekleme süresi güvenlik garantisi vermez.",
safetyStopped: "İşlem güvenlik nedeniyle durduruldu. Yeni istek için en erken: {time}. Otomatik devam edilmez; Instagram uyarısını kontrol edin.",
cancelled: "İşlem durduruldu.",
busyOperation: "Başka bir işlem çalışıyor.",
breakWaiting: "İstek veya mola bekleniyor…",
wrongHost: "Bu kodu instagram.com sekmesinde çalıştır.",
preparing: "Hazırlanıyor…",
stop: "Durdur",
openInbox: "Gelen kutusunu aç",
searchChats: "İsim veya kullanıcı adı",
searchSaved: "Kullanıcı veya açıklama",
includeRequests: "Mesaj isteklerini de listele",
reload: "Yenile",
selectAll: "Tümünü seç",
clearSelection: "Seçimi kaldır",
reportOnly: "Sadece rapor",
wipeAll: "Tümünü sil",
wipeAllSaved: "Tümünü kaldır",
selectedCount: "{n} seçili",
selectedFiltered: "{n} seçili · aramada {m}",
deleteSelected: "Seçilenleri sil",
removeSelected: "Seçilenleri kaldır",
noteMessages: "Sadece rapor hiçbir şeyi silmez. Silmek sohbeti sadece senin kutundan kaldırır.",
noteSaved: "Sadece rapor kaydı kaldırmaz. Kaldırmak gönderiyi silmez, sadece senin kaydından düşer.",
yesDelete: "Sil",
yesRemove: "Kaldır",
cancel: "Vazgeç",
downloadJson: "JSON indir",
downloadXlsx: "Excel indir",
downloading: "İndiriliyor…",
minimize: "Küçült",
close: "Kapat",
menuMessages: "Mesaj sil",
menuSaved: "Kaydedilenler",
langTr: "Türkçe",
langEn: "İngilizce",
stepPage: "Sayfa",
stepList: "Liste",
stepPick: "Seç",
stepDelete: "Sil",
stepRemove: "Kaldır",
stepReport: "Rapor",
hintMsg0: "Gelen kutusu sekmesini aç.",
hintMsg1: "Sohbetler listeleniyor.",
hintMsg2: "Silmek istediklerini seç.",
hintMsg3: "Seçilenler senin kutundan siliniyor.",
hintMsg4: "Rapor hazır. JSON veya Excel indir.",
hintSaved0: "Kaydedilenler listeleniyor. Sayfa değiştirmen gerekmez.",
hintSaved1: "Kaldırmak istediklerini seç.",
hintSaved2: "Seçilenler kaydından kalkıyor. Gönderinin kendisi durur.",
hintSaved3: "Rapor hazır. JSON veya Excel indir.",
chatsListing: "Sohbetler listeleniyor…",
chatsProgress: "{n} sohbet listelendi{page}{tail}",
chatsCut: "{n} sohbet (liste yarıda kesildi){page}",
chatsReady: "{n} sohbet. Silmek için seç.{page}",
fromPage: " (sayfadaki listeden)",
fromPageSentence: " Sayfadaki listeden.",
stillGoing: ", devam ediyor…",
doneDeleted: "Bitti. {n} sohbet senin kutundan silindi.",
stopRequested: "Durdurma istendi…",
reportWritten: "{n} kayıt rapora yazıldı. Hiçbir şey silinmedi.",
pageOpening: "Sayfa açılıyor…",
pageFailed: "Sayfa açılmadı. Adresi elle açıp paneli olduğu yerde bırak.",
savedListing: "Kaydedilenler listeleniyor…",
savedProgress: "{n} kayıt listelendi{tail}",
savedCut: "{n} kayıt (liste yarıda kesildi)",
savedReady: "{n} kayıt. Kaldırmak için seç.",
busyListing: "Listeleniyor…",
busyListingCount: "Listeleniyor… {n}",
busyDeleting: "Siliniyor… {done}/{total}",
busyRemoving: "Kaldırılıyor… {done}/{total}",
savedLoading: "Kaydedilenler yükleniyor…",
savedEmpty: "Kayıtlı gönderi yok.",
chatsLoading: "Liste yükleniyor…",
chatsEmpty: "Sohbet yok.",
removed: "kaldırıldı",
error: "hata",
deleted: "silindi",
group: "grup",
request: "istek",
openPost: "Gönderiyi aç",
confirmWipeChats: "{n} sohbet sadece senin kutundan silinecek. Karşı tarafta durur. Bitince rapor iner.",
confirmDeleteChats: "{n} sohbet sadece senin kutundan silinecek. Karşı tarafta durur. Geri alınamaz.",
confirmWipeSaved: "{n} kayıt kaldırılacak. Gönderinin kendisi durur, sadece senin kaydından düşer. Bitince rapor iner.",
confirmRemoveSaved: "{n} kayıt kaldırılacak. Gönderinin kendisi durur, sadece senin kaydından düşer.",
confirmConsole: "{n} sohbet sadece senin kutundan silinecek. Karşı tarafta durur. Devam?",
summaryListSaved: "Rapor: {n} kayıt listelendi. Hiçbir şey silinmedi.",
summaryListChats: "Rapor: {n} sohbet listelendi. Hiçbir şey silinmedi.",
summaryUnsave: "Rapor: {n} kayıt kaldırıldı, {errors} hata{stopped}. Gönderinin kendisi duruyor.{first}",
summaryStopped: ", durduruldu",
summaryDelete: "Rapor: {n} silindi, {errors} hata, {skipped} atlandı. Karşı tarafın kopyası duruyor.",
firstError: " İlk hata: {text}",
notLoggedIn: "Giriş görünmüyor. instagram.com'da hesabın açık olsun, sayfayı yenile.",
noSession: "Oturum anahtarı okunamadı. Sayfayı yenileyip scripti tekrar yapıştır.",
noMailbox: "Mesaj kutusu kimliği okunamadı. Sayfayı yenileyip scripti tekrar yapıştır.",
rateLimit: "Instagram hız limiti koydu (429). 30-60 dakika bekleyip tekrar dene.",
inboxReadFailed: "Gelen kutusu okunamadı ({problem}). doc {doc}, değişken {n}.",
inboxReadFailedKeys: "Gelen kutusu okunamadı ({problem}). doc {doc}, değişken {n}. anahtarlar: {keys}.",
inboxUnread: "Gelen kutusu okunamadı.",
savedReadFailed: "Kaydedilenler okunamadı (HTTP {status}).",
savedReadFailedDetail: "Kaydedilenler okunamadı (HTTP {status}): {detail}.",
justNow: "az önce",
minutesAgo: "{n} dk",
hoursAgo: "{n} sa",
daysAgo: "{n} gün",
unnamedChat: "isimsiz sohbet",
post: "gönderi",
listed: "listelendi",
stopped: "durduruldu",
yes: "evet",
no: "hayır",
sourceInbox: "gelen kutusu",
sourceRequests: "istekler",
rowStopped: "döngü durduruldu, istek gitmedi",
rowFailStreak: "üst üste hata, istek gitmedi",
rowLimited: "limit veya oturum, istek gitmedi",
noReply: "yanıt yok",
emptyReply: "boş yanıt",
htmlReply: "HTML yanıtı",
gqlError: "graphql hatası",
badJson: "JSON okunamadı",
couldNotDelete: "silinemedi",
threadOpenFailed: "sohbet açılamadı",
noInfoButton: "sohbet bilgisi düğmesi yok",
noDeleteButton: "Sohbeti sil düğmesi yok",
noConfirmButton: "onay düğmesi yok",
sessionHttp: "oturum (HTTP {status})",
folderName: "klasör {folder}",
noteListSaved: "Sadece liste. Hiçbir kayıt kaldırılmadı.",
noteListChats: "Sadece liste. Hiçbir sohbet silinmedi.",
noteDelete: "Sohbetler sadece senin kutundan silindi. Karşı tarafın kopyası durur.",
noteUnsave: "Gönderiler sadece senin kaydedilenlerinden kalktı. Gönderinin kendisi durur.",
col_sonuc: "Sonuç",
col_kullanicilar: "Kullanıcılar",
col_isimler: "İsimler",
col_baslik: "Başlık",
col_grup: "Grup",
col_kaynak: "Kaynak",
col_son_mesaj: "Son mesaj",
col_thread_id: "Thread ID",
col_url: "URL",
col_http: "HTTP",
col_hata: "Hata",
col_zaman: "Zaman",
col_kullanici: "Kullanıcı",
col_aciklama: "Açıklama",
col_media_id: "Media ID",
col_thumb: "Küçük resim",
sheetReport: "Rapor",
fileMessages: "instagram-mesaj-raporu-",
fileSaved: "instagram-kaydedilen-raporu-",
previewLine: "Önizleme. Silinen bir şey yok. {n} sohbet silinir.",
helpText: "Panel sağda. Menü: Mesaj sil veya Kaydedilenler. Konsol: IG.stop() / await IG.preview() / await IG.unsave()",
panelOpened: "Panel açıldı. Menüden seç. Henüz hiçbir şey silinmedi.",
consoleReport: "Rapor IG.lastReport içinde.",
colChat: "sohbet",
colState: "durum",
willKeep: "korunacak",
willDelete: "silinecek",
},
en: {
scanIdle: "Ready. Adjust settings first, then press Start scan when you are ready.",
startScan: "Start scan",
rescan: "Scan again",
notScanned: "No scan has been run yet.",
cacheNotice: "Showing a previous scan · {time} · {n} items. The list may be outdated.",
cachePrivacy: "Scan results are stored in this browser for 24 hours, separately for each Instagram account.",
clearCache: "Clear saved scans",
cacheCleared: "Saved scans cleared.",
settingsTiming: "Request pacing",
settingsData: "Saved scans",
settingsDone: "Done",
delayHint: "2–120 seconds · default 4.5",
batchHint: "1–20 requests · default 5",
restHint: "30–3600 seconds · default 300",
settings: "Settings",
delaySeconds: "Delay between requests (seconds)",
batchEvery: "Requests between breaks",
breakSeconds: "Break duration (seconds)",
resetSettings: "Restore defaults",
settingsNote: "Settings are saved in this browser. Shorter delays increase restriction risk. Cannot change during a run.",
riskWarning: "Warning: Automated actions may restrict or suspend your account. No delay guarantees safety.",
safetyStopped: "Stopped for safety. No new requests before: {time}. No automatic resume; check the Instagram warning.",
cancelled: "Operation stopped.",
busyOperation: "Another operation is running.",
breakWaiting: "Waiting between requests or taking a break…",
wrongHost: "Run this on an instagram.com tab.",
preparing: "Getting ready…",
stop: "Stop",
openInbox: "Open inbox",
searchChats: "Name or username",
searchSaved: "Username or caption",
includeRequests: "Also list message requests",
reload: "Refresh",
selectAll: "Select all",
clearSelection: "Clear selection",
reportOnly: "Report only",
wipeAll: "Delete all",
wipeAllSaved: "Remove all",
selectedCount: "{n} selected",
selectedFiltered: "{n} selected · {m} in search",
deleteSelected: "Delete selected",
removeSelected: "Remove selected",
noteMessages: "Report only does not delete anything. Delete removes the chat from your inbox only.",
noteSaved: "Report only does not unsave anything. Remove does not delete the post. It only drops it from your saved list.",
yesDelete: "Delete",
yesRemove: "Remove",
cancel: "Cancel",
downloadJson: "Download JSON",
downloadXlsx: "Download Excel",
downloading: "Downloading…",
minimize: "Minimize",
close: "Close",
menuMessages: "Delete chats",
menuSaved: "Saved",
langTr: "Turkish",
langEn: "English",
stepPage: "Page",
stepList: "List",
stepPick: "Pick",
stepDelete: "Delete",
stepRemove: "Remove",
stepReport: "Report",
hintMsg0: "Open the inbox tab.",
hintMsg1: "Listing chats.",
hintMsg2: "Pick the ones to delete.",
hintMsg3: "Selected chats are being deleted from your inbox.",
hintMsg4: "Report is ready. Download JSON or Excel.",
hintSaved0: "Listing saved posts. You do not need to change pages.",
hintSaved1: "Pick the ones to remove.",
hintSaved2: "Selected saves are being removed. The post itself stays.",
hintSaved3: "Report is ready. Download JSON or Excel.",
chatsListing: "Listing chats…",
chatsProgress: "{n} chats listed{page}{tail}",
chatsCut: "{n} chats (list stopped early){page}",
chatsReady: "{n} chats. Pick some to delete.{page}",
fromPage: " (from the list on the page)",
fromPageSentence: " From the list on the page.",
stillGoing: ", still going…",
doneDeleted: "Done. {n} chats were deleted from your inbox.",
stopRequested: "Stop requested…",
reportWritten: "{n} rows written to the report. Nothing was deleted.",
pageOpening: "Opening the page…",
pageFailed: "The page did not open. Open the address yourself and leave the panel where it is.",
savedListing: "Listing saved posts…",
savedProgress: "{n} saved posts listed{tail}",
savedCut: "{n} saved posts (list stopped early)",
savedReady: "{n} saved posts. Pick some to remove.",
busyListing: "Listing…",
busyListingCount: "Listing… {n}",
busyDeleting: "Deleting… {done}/{total}",
busyRemoving: "Removing… {done}/{total}",
savedLoading: "Loading saved posts…",
savedEmpty: "No saved posts.",
chatsLoading: "Loading the list…",
chatsEmpty: "No chats.",
removed: "removed",
error: "error",
deleted: "deleted",
group: "group",
request: "request",
openPost: "Open post",
confirmWipeChats: "{n} chats will be deleted from your inbox only. They stay on the other side. A report downloads when it finishes.",
confirmDeleteChats: "{n} chats will be deleted from your inbox only. They stay on the other side. This cannot be undone.",
confirmWipeSaved: "{n} saves will be removed. The post itself stays. It only leaves your saved list. A report downloads when it finishes.",
confirmRemoveSaved: "{n} saves will be removed. The post itself stays. It only leaves your saved list.",
confirmConsole: "{n} chats will be deleted from your inbox only. They stay on the other side. Continue?",
summaryListSaved: "Report: {n} saved posts listed. Nothing was deleted.",
summaryListChats: "Report: {n} chats listed. Nothing was deleted.",
summaryUnsave: "Report: {n} removed, {errors} errors{stopped}. The post itself is still there.{first}",
summaryStopped: ", stopped",
summaryDelete: "Report: {n} deleted, {errors} errors, {skipped} skipped. The other person's copy is still there.",
firstError: " First error: {text}",
notLoggedIn: "You do not look signed in. Stay logged in on instagram.com and refresh the page.",
noSession: "Could not read the session key. Refresh the page and paste the script again.",
noMailbox: "Could not read the mailbox id. Refresh the page and paste the script again.",
rateLimit: "Instagram applied a rate limit (429). Wait 30-60 minutes and try again.",
inboxReadFailed: "Could not read the inbox ({problem}). doc {doc}, variables {n}.",
inboxReadFailedKeys: "Could not read the inbox ({problem}). doc {doc}, variables {n}. keys: {keys}.",
inboxUnread: "Could not read the inbox.",
savedReadFailed: "Could not read saved posts (HTTP {status}).",
savedReadFailedDetail: "Could not read saved posts (HTTP {status}): {detail}.",
justNow: "just now",
minutesAgo: "{n}m",
hoursAgo: "{n}h",
daysAgo: "{n}d",
unnamedChat: "unnamed chat",
post: "post",
listed: "listed",
stopped: "stopped",
yes: "yes",
no: "no",
sourceInbox: "inbox",
sourceRequests: "requests",
rowStopped: "stopped, request was not sent",
rowFailStreak: "repeated errors, request was not sent",
rowLimited: "rate limit or session, request was not sent",
noReply: "no response",
emptyReply: "empty response",
htmlReply: "HTML response",
gqlError: "graphql error",
badJson: "could not read JSON",
couldNotDelete: "could not delete",
threadOpenFailed: "could not open the chat",
noInfoButton: "conversation info button is missing",
noDeleteButton: "Delete chat button is missing",
noConfirmButton: "confirm button is missing",
sessionHttp: "session (HTTP {status})",
folderName: "folder {folder}",
noteListSaved: "List only. No saves were removed.",
noteListChats: "List only. No chats were deleted.",
noteDelete: "Chats were deleted from your inbox only. The other person's copy stays.",
noteUnsave: "Posts were removed from your saved list only. The post itself stays.",
col_sonuc: "Result",
col_kullanicilar: "Usernames",
col_isimler: "Names",
col_baslik: "Title",
col_grup: "Group",
col_kaynak: "Source",
col_son_mesaj: "Last message",
col_thread_id: "Thread ID",
col_url: "URL",
col_http: "HTTP",
col_hata: "Error",
col_zaman: "Time",
col_kullanici: "Username",
col_aciklama: "Caption",
col_media_id: "Media ID",
col_thumb: "Thumbnail",
sheetReport: "Report",
fileMessages: "instagram-message-report-",
fileSaved: "instagram-saved-report-",
previewLine: "Preview. Nothing was deleted. {n} chats would be deleted.",
helpText: "Panel is on the right. Menu: Delete chats or Saved. Console: IG.stop() / await IG.preview() / await IG.unsave()",
panelOpened: "Panel opened. Pick a menu item. Nothing has been deleted yet.",
consoleReport: "Report is in IG.lastReport.",
colChat: "chat",
colState: "state",
willKeep: "keep",
willDelete: "delete",
},
};
if (!/(^|\.)instagram\.com$/.test(location.hostname)) {
const pack = IG_TEXT[IG_LANG] || IG_TEXT.tr;
console.error(pack.wrongHost || IG_TEXT.tr.wrongHost);
return;
}
// Keep legacy keys and cleanup hook so upgrades preserve cooldowns and stop older copies.
window.__igtoolsCleanup?.();
const state = { stop: false, destroyed: false };
const controllers = new Set();
const DEFAULT_SETTINGS = { delay: 4500, batch: 5, rest: 300000 };
const storage = {
get(key) { try { return localStorage.getItem(key); } catch { return null; } },
set(key, value) { try { localStorage.setItem(key, value); } catch { /* storage unavailable */ } },
};
function normalizeSettings(value = {}) {
const number = (key, min, max) => Number.isFinite(Number(value[key]))
? Math.min(max, Math.max(min, Number(value[key]))) : DEFAULT_SETTINGS[key];
return { delay: number("delay", 2000, 120000), batch: Math.round(number("batch", 1, 20)), rest: number("rest", 30000, 3600000) };
}
let settings;
try { settings = normalizeSettings(JSON.parse(storage.get("igtools-settings-v1")) || {}); }
catch { settings = { ...DEFAULT_SETTINGS }; }
let blockedUntil = Number(storage.get("igtools-blocked-until")) || 0;
let requestCount = 0;
let nextRequestAt = 0;
let requestQueue = Promise.resolve();
function cancelRequests(destroy = false) {
state.stop = true;
if (destroy) state.destroyed = true;
for (const controller of controllers) controller.abort();
controllers.clear();
}
window.__igtoolsCleanup = () => {
cancelRequests(true);
document.getElementById("igc-root")?.remove();
document.getElementById("igc-style")?.remove();
};
function checkSafety() {
blockedUntil = Math.max(blockedUntil, Number(storage.get("igtools-blocked-until")) || 0);
if (Date.now() < blockedUntil) throw fail("safetyStopped", { time: new Date(blockedUntil).toLocaleString(lang === "en" ? "en-US" : "tr-TR") });
if (state.stop || state.destroyed) throw fail("cancelled");
}
async function interruptibleWait(ms) {
const end = Date.now() + ms;
while (Date.now() < end) {
checkSafety();
await sleep(Math.min(200, end - Date.now()));
}
checkSafety();
}
async function guardedRequest(input, init = {}) {
const previous = requestQueue;
let release;
requestQueue = new Promise(resolve => { release = resolve; });
await previous;
let controller;
try {
checkSafety();
const pacing = document.getElementById("igc-pacing");
if (pacing && nextRequestAt > Date.now()) pacing.textContent = t("breakWaiting") + " " + new Date(nextRequestAt).toLocaleTimeString(lang === "en" ? "en-US" : "tr-TR");
await interruptibleWait(Math.max(0, nextRequestAt - Date.now()));
if (pacing) pacing.textContent = "";
controller = new AbortController();
controllers.add(controller);
const response = await fetch(input, { ...init, signal: controller.signal });
const body = await response.clone().text();
checkSafety();
const url = new URL(input, location.origin);
const api = url.origin === location.origin && /\/api\//.test(url.pathname);
const problem = /feedback_required|checkpoint_required|challenge_required|login_required|require_login|action_blocked|rate_limit|please wait a few minutes|try again later|"spam"\s*:\s*true|"challenge"\s*:|"checkpoint_url"\s*:|"feedback_required"\s*:\s*true/i.test(body);
const redirected = /\/(challenge|checkpoint|accounts\/login)(\/|\?|$)/i.test(response.url);
const html = api && /^\s*( 0) {
const tail = text.slice(index + mark.length);
if (Object.prototype.hasOwnProperty.call(CELL, tail)) return text.slice(0, index) + mark + t(CELL[tail]);
}
return text;
}
function fill(key, vars) {
const resolved = {};
if (vars) {
for (const [name, value] of Object.entries(vars)) {
if (name.endsWith("Key")) {
resolved[name.slice(0, -3)] = value ? t(String(value)) : "";
} else if (name === "problem" || name === "detail") {
resolved[name] = showPhrase(value);
} else {
resolved[name] = value == null ? "" : String(value);
}
}
}
return t(key, resolved);
}
function fail(key, vars) {
const error = new Error(fill(key, vars));
error.i18nKey = key;
error.i18nVars = vars || {};
return error;
}
loadLang();
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const CACHE_TTL = 24 * 60 * 60 * 1000;
const scanAccount = cookie("ds_user_id");
const cacheMeta = { messages: null, saved: null };
function cacheKey(mode, pending = false) {
const account = cookie("ds_user_id");
return account && account === scanAccount && /^\d+$/.test(account) ? "igtools-scan-v1:" + account + ":" + mode + (mode === "messages" && pending ? ":requests" : "") : null;
}
function readScan(mode, pending = false) {
const key = cacheKey(mode, pending);
if (!key) return null;
try {
const value = JSON.parse(storage.get(key));
if (!value || !Number.isFinite(value.time) || value.time > Date.now() || Date.now() - value.time >= CACHE_TTL || !Array.isArray(value.rows)) return null;
const valid = value.rows.every(row => row && typeof row.id === "string" && typeof row.label === "string" && (mode === "saved" || ["usernames", "names", "users"].every(key => Array.isArray(row[key]))));
return valid ? value : null;
} catch { return null; }
}
function writeScan(mode, rows, pending = false, time = Date.now()) {
const key = cacheKey(mode, pending);
if (!key) return;
const clean = rows.filter(row => row.status !== "silindi" && row.status !== "kaldirildi").map(row => ({ ...row, status: "" }));
try { localStorage.setItem(key, JSON.stringify({ time, rows: clean })); }
catch { /* Keep the previous complete scan if storage is unavailable or full. */ }
}
function updateScanAfterAction(mode) {
// Update every cached variant, including entries changed before a run was interrupted.
const changed = new Set((mode === "messages" ? ui.threads : ui.savedPosts).filter(row => row.status === "silindi" || row.status === "kaldirildi").map(row => row.id));
for (const pending of mode === "messages" ? [false, true] : [false]) {
const cached = readScan(mode, pending);
if (cached) writeScan(mode, cached.rows.filter(row => !changed.has(row.id)), pending, cached.time);
}
}
function cookie(name) {
const match = document.cookie.match(new RegExp("(?:^|; )" + name + "=([^;]*)"));
return match ? decodeURIComponent(match[1]) : null;
}
// thread_id 2^53'ten büyük olabiliyor. JSON.parse bunu yuvarlar.
function parseSafe(text) {
const quoted = text.replace(/(:\s*)(-?\d{16,})(\s*[,}\]])/g, '$1"$2"$3');
return JSON.parse(quoted);
}
function pick(text, patterns) {
for (const pattern of patterns) {
const match = text.match(pattern);
if (match) return match[1];
}
return null;
}
function readTokens(text) {
return {
dtsg: pick(text, [
/"DTSGInitialData",\[\],\{"token":"([^"]+)"/,
/"DTSGInitData",\[\],\{"token":"([^"]+)"/,
/"dtsg":\{"token":"([^"]+)"/,
/"f":"(NAf[^"]+)"/,
]),
lsd: pick(text, [/"LSD",\[\],\{"token":"([^"]+)"/, /name="lsd" content="([^"]+)"/]),
mailbox: pick(text, [/"IG_USER_EIMU":"(\d+)"/, /"mailboxID":"(\d+)"/, /"mailbox_id":"(\d+)"/]),
appId: pick(text, [/"APP_ID":"(\d+)"/, /"X-IG-App-ID":"(\d+)"/]) || "936619743392459",
};
}
async function ensureSession() {
if (session && session.dtsg) return session;
if (!cookie("csrftoken") || !cookie("ds_user_id")) {
throw fail("notLoggedIn");
}
let tokens = readTokens(document.documentElement.innerHTML);
const lsdMeta = document.querySelector('meta[name="lsd"]');
if (!tokens.lsd && lsdMeta) tokens.lsd = lsdMeta.getAttribute("content");
if (!tokens.dtsg || !tokens.mailbox) {
const response = await guardedRequest("/direct/inbox/", { credentials: "include" });
const html = await response.text();
inboxHtml = html;
const fromHtml = readTokens(html);
tokens = {
dtsg: tokens.dtsg || fromHtml.dtsg,
lsd: tokens.lsd || fromHtml.lsd,
mailbox: tokens.mailbox || fromHtml.mailbox,
appId: fromHtml.appId || tokens.appId,
};
}
if (!tokens.dtsg) {
throw fail("noSession");
}
session = tokens;
return session;
}
function requireQuery(name) {
const req = window.require;
if (typeof req !== "function") return null;
for (const key of [name + ".graphql", name]) {
try {
const mod = req(key);
const params = (mod && (mod.params || (mod.default && mod.default.params))) || null;
if (params && params.id) return { name, id: String(params.id), params };
} catch {
/* modül bu sayfada yüklü değil */
}
}
return null;
}
function findDeleteQuery() {
const preferred = [
"IGDInboxInfoDeleteThreadDialogOffMsysMutation",
"IGDThreadDeleteDialogOffMsysMutation",
"IGDDeleteThreadDialogOffMsysMutation",
"IGDThreadDeleteOffMsysMutation",
"IGDDeleteThreadOffMsysMutation",
"IGDThreadDeleteMutation",
"IGDDeleteThreadMutation",
"IGDeleteThreadMutation",
"PolarisDirectThreadDeleteMutation",
"IGDeleteThread",
];
for (const name of preferred) {
const found = requireQuery(name);
if (found) return found;
}
const req = window.require;
const map = req && (req.m || req.modules);
if (!map) return null;
const seen = new Set(preferred);
for (const key of Object.keys(map)) {
if (!/delete/i.test(key) || !/thread/i.test(key) || /message|unsend/i.test(key)) continue;
const name = String(key).replace(/\.graphql$/, "");
if (seen.has(name)) continue;
seen.add(name);
const found = requireQuery(name);
if (found) return found;
}
return null;
}
function liveQuery(name, fallbackId) {
const required = requireQuery(name);
if (required) return required;
const html = document.documentElement.innerHTML;
let from = 0;
while (from < html.length) {
const at = html.indexOf('"' + name + '"', from);
if (at < 0) break;
const slice = html.slice(Math.max(0, at - 80), at + name.length + 140);
const match = slice.match(/\b(?:id|doc_id)"?\s*:\s*"(\d{10,})"/);
if (match && match[1] !== fallbackId) return { name, id: match[1], params: null };
from = at + name.length + 2;
}
return { name, id: fallbackId, params: null };
}
async function gql(name, docId, variables) {
const sess = await ensureSession();
const body = new URLSearchParams({
fb_dtsg: sess.dtsg,
fb_api_caller_class: "RelayModern",
fb_api_req_friendly_name: name,
server_timestamps: "true",
variables: JSON.stringify(variables),
doc_id: docId,
});
if (sess.lsd) body.set("lsd", sess.lsd);
const response = await guardedRequest("/api/graphql", {
method: "POST",
credentials: "include",
headers: {
"content-type": "application/x-www-form-urlencoded",
"x-csrftoken": cookie("csrftoken"),
"x-fb-friendly-name": name,
"x-ig-app-id": sess.appId,
...(sess.lsd ? { "x-fb-lsd": sess.lsd } : {}),
...(sessionStorage.getItem("www-claim-v2")
? { "x-ig-www-claim": sessionStorage.getItem("www-claim-v2") }
: {}),
},
body,
});
const text = await response.text();
const cleaned = text.replace(/^for\s*\(;;\);\s*/, "").trim();
let json = null;
if (cleaned.startsWith("{") || cleaned.startsWith("[")) {
try {
const parsed = parseSafe(cleaned);
json = Array.isArray(parsed)
? parsed.find((item) => item && (item.data || item.errors)) || parsed[0]
: parsed;
} catch {
json = null;
}
}
return { status: response.status, json, text: text.slice(0, 280) };
}
const LIST_NAME = "IGDThreadListOffMsysPaginationQuery";
const LIST_DOC = "28804933902495089";
const DELETE_NAME = "IGDInboxInfoDeleteThreadDialogOffMsysMutation";
const DELETE_DOC = "23915602751379354";
let listQuery = null;
function withProvided(query, variables) {
const provided = query && query.params && query.params.providedVariables;
const extra = {};
if (provided && typeof provided === "object") {
for (const [key, value] of Object.entries(provided)) {
try {
extra[key] = value && typeof value.get === "function" ? value.get() : value;
} catch {
/* sayfanın verdiği değişken okunamadı */
}
}
}
return { ...extra, ...variables };
}
function gqlProblem(result) {
if (!result) return "noReply";
if (result.status === 429) return "429";
if (result.status === 401 || result.status === 403) return "session:" + result.status;
const errors = result.json && result.json.errors;
if (Array.isArray(errors) && errors.length) {
return errors
.map((item) => item.message || item.summary || "gqlError")
.join("; ")
.slice(0, 240);
}
if (result.status !== 200) return "http:" + result.status;
if (!result.json) return "badJson";
return "";
}
function gqlOk(result) {
if (gqlProblem(result)) return false;
const data = result.json.data;
if (!data || typeof data !== "object") return false;
return Object.values(data).some((value) => value != null);
}
function relativeTime(date) {
if (!date) return "";
const sec = (Date.now() - date.getTime()) / 1000;
const locale = lang === "en" ? "en-US" : "tr-TR";
if (sec < 0) return date.toLocaleDateString(locale);
if (sec < 60) return t("justNow");
if (sec < 3600) return t("minutesAgo", { n: Math.floor(sec / 60) });
if (sec < 86400) return t("hoursAgo", { n: Math.floor(sec / 3600) });
if (sec < 86400 * 30) return t("daysAgo", { n: Math.floor(sec / 86400) });
return date.toLocaleDateString(locale);
}
function activityLabel(thread) {
if (thread.lastActivity) {
const date = new Date(thread.lastActivity);
if (!Number.isNaN(date.getTime())) return relativeTime(date);
}
return thread.lastActivityLabel || "";
}
function peopleFrom(thread) {
const raw = thread.usersWithoutViewer || thread.users || thread.participants || [];
const list = Array.isArray(raw)
? raw
: (raw.edges || []).map((edge) => edge && edge.node).filter(Boolean);
return list.map((user) => ({
username: user.username || user.instagram_username || "",
name: user.full_name || user.name || "",
id: String(user.pk || user.id || user.igid || ""),
}));
}
function activityFrom(raw) {
const value = Number(raw);
if (!value) return null;
const ms = value > 1e14 ? value / 1000 : value;
const date = new Date(ms);
return Number.isNaN(date.getTime()) ? null : date;
}
function normalizeThread(thread, source) {
const users = peopleFrom(thread);
const when = activityFrom(thread.last_activity_timestamp_ms || thread.last_activity_at);
const title = thread.thread_title || "";
const label =
title ||
users
.map((user) => user.username || user.name)
.filter(Boolean)
.join(", ") ||
"";
return {
id: String(thread.thread_fbid || thread.thread_id || ""),
title,
label,
group: Boolean(thread.is_group || thread.is_group_thread),
source: source || "inbox",
users,
usernames: users.map((user) => user.username).filter(Boolean),
names: users.map((user) => user.name).filter(Boolean),
lastActivity: when ? when.toISOString() : "",
lastActivityLabel: relativeTime(when),
status: "",
};
}
function haystack(thread) {
return [thread.label, thread.title, ...thread.usernames, ...thread.names]
.join(" ")
.toLowerCase();
}
function isKept(thread, keep) {
if (!keep.length) return false;
const blob = haystack(thread);
return keep.some((name) => blob.includes(name));
}
function relayFromProvided(params) {
const provided = params && params.providedVariables;
const extra = {};
if (!provided || typeof provided !== "object") return extra;
for (const [key, value] of Object.entries(provided)) {
try {
const read = value && typeof value.get === "function" ? value.get() : value;
extra[key] = read === undefined ? false : read;
} catch {
extra[key] = false;
}
}
return extra;
}
function queryFromModule(mod) {
if (!mod) return null;
const params = mod.params || (mod.default && mod.default.params) || null;
if (!params || !params.id) return null;
const relay = relayFromProvided(params);
return {
name: params.name || LIST_NAME,
id: String(params.id),
params,
relay,
ready: Object.keys(relay).length > 0,
};
}
function requireModule(name) {
const req = window.require;
if (typeof req !== "function") return null;
for (const key of [name + ".graphql", name]) {
try {
const mod = req(key);
if (mod) return mod;
} catch {
/* bu sayfada yüklü değil */
}
}
return null;
}
function requireMapKeys() {
const req = window.require;
const map = req && (req.m || req.modules);
return map ? Object.keys(map) : [];
}
function loadLazy(name) {
return new Promise((resolve) => {
const lazy = window.requireLazy;
if (typeof lazy !== "function") {
resolve(null);
return;
}
let settled = false;
const finish = (value) => {
if (settled) return;
settled = true;
resolve(value || null);
};
try {
lazy([name + ".graphql"], (mod) => finish(mod));
} catch {
finish(null);
}
setTimeout(() => finish(null), 5000);
});
}
function providerValue(provider) {
const req = window.require;
if (typeof req === "function") {
try {
const mod = req(provider + ".relayprovider") || req(provider);
if (mod && typeof mod.get === "function") {
const value = mod.get();
return value === undefined ? false : value;
}
} catch {
/* sağlayıcı yüklü değil */
}
}
return false;
}
function relayFromSource(text, name) {
const extra = {};
let id = null;
let from = 0;
let hits = 0;
while (from < text.length && hits < 6) {
const at = text.indexOf(name, from);
if (at < 0) break;
hits += 1;
const slice = text.slice(Math.max(0, at - 400), Math.min(text.length, at + 5000));
if (!id) {
const idMatch =
slice.match(/"(?:id|doc_id)"\s*:\s*"(\d{12,})"/) || slice.match(/\bexports\s*=\s*"(\d{12,})"/);
if (idMatch) id = idMatch[1];
}
for (const match of slice.matchAll(/"([A-Za-z0-9_]+)\.relayprovider"/g)) {
extra["__relay_internal__pv__" + match[1] + "relayprovider"] = providerValue(match[1]);
}
for (const match of slice.matchAll(/__relay_internal__pv__([A-Za-z0-9_]+)relayprovider/g)) {
const key = "__relay_internal__pv__" + match[1] + "relayprovider";
if (!(key in extra)) extra[key] = providerValue(match[1]);
}
from = at + name.length;
if (id && Object.keys(extra).length) break;
}
return { id, extra };
}
function scriptUrls(page) {
const urls = [];
const seen = new Set();
const add = (url) => {
const clean = String(url || "")
.replace(/\\\//g, "/")
.replace(/&/g, "&");
if (!clean.includes("rsrc.php") || !clean.endsWith(".js") || seen.has(clean)) return;
seen.add(clean);
urls.push(clean.startsWith("http") ? clean : location.origin + clean);
};
for (const match of page.matchAll(/https:\\\/\\\/static\.cdninstagram\.com\\\/rsrc\.php\\\/[^"'\\\s]+\.js/g)) {
add(match[0]);
}
for (const match of page.matchAll(/https:\/\/static\.cdninstagram\.com\/rsrc\.php\/[^"'\s]+\.js/g)) {
add(match[0]);
}
return urls;
}
async function relayFromBundles(name) {
const pages = [document.documentElement.innerHTML];
if (onInboxPage()) inboxHtml = document.documentElement.innerHTML;
if (!inboxHtml && !onInboxPage()) {
try {
const response = await guardedRequest("/direct/inbox/", { credentials: "include" });
inboxHtml = await response.text();
} catch {
/* gelen kutusu html'i alınamadı */
}
}
if (inboxHtml) pages.push(inboxHtml);
let merged = { id: null, extra: {} };
for (const page of pages) {
const parsed = relayFromSource(page, name);
merged = {
id: merged.id || parsed.id,
extra: { ...parsed.extra, ...merged.extra },
};
}
if (Object.keys(merged.extra).length) return merged;
const urls = [];
const seen = new Set();
const orderedPages = inboxHtml ? [inboxHtml, ...pages] : pages;
for (const page of orderedPages) {
for (const url of scriptUrls(page)) {
if (seen.has(url)) continue;
seen.add(url);
urls.push(url);
}
}
const queue = urls.slice(0, 40);
let cursor = 0;
let found = null;
async function worker() {
while (!found && cursor < queue.length) {
const url = queue[cursor];
cursor += 1;
try {
const response = await guardedRequest(url, { credentials: "omit" });
if (!response.ok) continue;
const text = await response.text();
if (!text.includes(name)) continue;
const parsed = relayFromSource(text, name);
if (parsed.id || Object.keys(parsed.extra).length) found = parsed;
} catch {
/* paket okunamadı */
}
}
}
await Promise.all([worker(), worker(), worker(), worker()]);
if (!found) return merged;
return { id: found.id || merged.id, extra: { ...merged.extra, ...found.extra } };
}
async function discoverListQuery() {
const direct = queryFromModule(requireModule(LIST_NAME));
if (direct && direct.ready) return direct;
for (const key of requireMapKeys()) {
if (!/threadlist|offmsyspagination/i.test(key)) continue;
try {
const parsed = queryFromModule(window.require(key));
if (parsed && parsed.ready) return { ...parsed, name: parsed.name || LIST_NAME };
} catch {
/* modül açılamadı */
}
}
const lazy = queryFromModule(await loadLazy(LIST_NAME));
if (lazy && lazy.ready) return lazy;
const scanned = await relayFromBundles(LIST_NAME);
const relay = {
...(scanned.extra || {}),
...((lazy && lazy.relay) || {}),
...((direct && direct.relay) || {}),
};
const id = (lazy && lazy.id) || (direct && direct.id) || scanned.id || LIST_DOC;
const query = {
name: LIST_NAME,
id: String(id),
params: (lazy && lazy.params) || (direct && direct.params) || null,
relay,
ready: Object.keys(relay).length > 0,
};
console.info("IGCleaner liste sorgusu", query.id, Object.keys(query.relay));
return query;
}
async function inboxQuery() {
if (listQuery) return listQuery;
if (listQueryCache) {
listQuery = listQueryCache;
return listQuery;
}
const found = await discoverListQuery();
listQueryCache = found;
listQuery = found;
return listQuery;
}
async function readFolderPage(folder, cursor) {
const query = await inboxQuery();
const sess = await ensureSession();
if (!sess.mailbox) throw fail("noMailbox");
const result = await gql(
query.name,
query.id,
withProvided(query, {
count: 20,
cursor: cursor || null,
folder,
newer_than_timestamp_ms: null,
id: sess.mailbox,
...(query.relay || {}),
})
);
if (result.status === 429) {
state.stop = true;
throw fail("rateLimit");
}
const data = result.json && result.json.data;
const conn = data && data.fetch__SlideMailbox && data.fetch__SlideMailbox.threads_by_folder;
if (!conn) {
const problem = gqlProblem(result) || "folder:" + folder;
const keys = data ? Object.keys(data).slice(0, 8).join(", ") : "";
const relayCount = query.relay ? Object.keys(query.relay).length : 0;
const error = fail(keys ? "inboxReadFailedKeys" : "inboxReadFailed", {
problem,
doc: query.id,
n: relayCount,
keys,
});
error.result = result;
throw error;
}
const source = folder === "PENDING" ? "requests" : "inbox";
const threads = (conn.edges || [])
.map((edge) => edge && edge.node && (edge.node.as_ig_direct_thread || edge.node))
.filter((thread) => thread && (thread.thread_fbid || thread.thread_id))
.map((thread) => normalizeThread(thread, source));
const page = conn.page_info || {};
return {
threads,
cursor: page.has_next_page ? page.end_cursor || null : null,
hasOlder: Boolean(page.has_next_page && page.end_cursor),
};
}
function folderNames(folders) {
const names = (folders || []).map((folder) => {
const value = String(folder || "").toLowerCase();
if (!value || value === "inbox") return "INBOX";
if (value === "requests" || value === "pending") return "PENDING";
return String(folder).toUpperCase();
});
const unique = [...new Set(names)].filter((name) => name !== "PENDING");
return unique.length ? unique : ["INBOX"];
}
function reachedLimit(found, limit) {
return Boolean(limit && found.filter((item) => !item.kept).length >= limit);
}
async function collectGraphql({ folders, includePending, limit, keep, pauseMs, onPage }) {
const found = [];
const seen = new Set();
let inboxError = null;
let opened = false;
async function walk(readPage) {
let cursor = null;
const seenCursors = new Set();
for (let page = 0; page < 500; page += 1) {
if (state.stop) return;
const batch = await readPage(cursor);
if (!batch) return;
for (const thread of batch.threads) {
if (!thread.id || seen.has(thread.id)) continue;
seen.add(thread.id);
thread.kept = isKept(thread, keep);
found.push(thread);
if (reachedLimit(found, limit)) {
if (onPage) onPage(found);
return;
}
}
if (onPage) onPage(found);
if (!batch.hasOlder || !batch.cursor || seenCursors.has(String(batch.cursor))) return;
seenCursors.add(String(batch.cursor));
cursor = batch.cursor;
await interruptibleWait(pauseMs);
}
}
for (const folder of folderNames(folders)) {
try {
await walk((cursor) => readFolderPage(folder, cursor));
opened = true;
} catch (error) {
inboxError = inboxError || error;
console.warn(folder, error);
if (state.stop) break;
if (folder === "INBOX" && !found.length) {
try {
await walk((cursor) => readFolderPage("GENERAL", cursor));
opened = true;
} catch (generalError) {
console.warn("GENERAL", generalError);
}
}
}
if (reachedLimit(found, limit)) break;
}
if (!opened && !found.length) throw inboxError || fail("inboxUnread");
if (includePending && !state.stop && !reachedLimit(found, limit)) {
try {
await walk((cursor) => readFolderPage("PENDING", cursor));
} catch (error) {
console.warn("PENDING", error);
}
}
return found;
}
function threadIdFromHref(href) {
const match = String(href || "").match(/\/direct\/t\/(\d+)/);
return match ? match[1] : "";
}
function scrapeVisibleThreads() {
const rows = [];
const seen = new Set();
for (const link of document.querySelectorAll('a[href*="/direct/t/"]')) {
if (link.closest("#igc-root")) continue;
const id = threadIdFromHref(link.getAttribute("href"));
if (!id || seen.has(id)) continue;
seen.add(id);
const lines = (link.innerText || "")
.split("\n")
.map((line) => line.trim())
.filter(Boolean);
const label = lines[0] || "";
rows.push({
id,
title: "",
label,
group: /grup|group/i.test(lines.join(" ")),
source: "inbox",
users: [],
usernames: [],
names: label ? [label] : [],
lastActivity: "",
lastActivityLabel: lines[1] || "",
status: "",
});
}
return rows;
}
function inboxScroller() {
const link = [...document.querySelectorAll('a[href*="/direct/t/"]')].find(
(item) => !item.closest("#igc-root")
);
let node = link && link.parentElement;
while (node && node !== document.body) {
const style = getComputedStyle(node);
const scrollable = style.overflowY === "auto" || style.overflowY === "scroll" || style.overflowY === "overlay";
if (scrollable && node.scrollHeight > node.clientHeight + 40) return node;
node = node.parentElement;
}
return document.scrollingElement || document.documentElement;
}
async function collectFromDom({ keep, onPage }) {
const found = [];
const seen = new Set();
let stable = 0;
let lastCount = -1;
for (let round = 0; round < 80 && !state.stop; round += 1) {
for (const thread of scrapeVisibleThreads()) {
if (seen.has(thread.id)) continue;
seen.add(thread.id);
thread.kept = isKept(thread, keep);
found.push(thread);
}
if (onPage) onPage(found);
if (found.length === lastCount) stable += 1;
else stable = 0;
lastCount = found.length;
if (stable >= 3 && found.length > 0) break;
if (stable >= 8) break;
inboxScroller().scrollTop = inboxScroller().scrollHeight;
await sleep(450);
}
return found;
}
async function collect(options) {
const keep = options.keep || [];
listFromPage = false;
try {
await ensureSession();
return await collectGraphql({ ...options, keep });
} catch (error) {
if (state.stop) throw error;
console.warn("GraphQL liste başarısız, sayfadaki sohbetler okunuyor.", error);
listFromPage = true;
const dom = await collectFromDom({ keep, onPage: options.onPage });
if (!dom.length) throw error;
return dom;
}
}
function okHide() {
return { status: 200, json: { status: "ok" }, text: "" };
}
function failHide(result, fallback) {
return {
status: result && result.status ? result.status : 0,
json: result && result.json,
text: gqlProblem(result) || (result && result.text) || fallback || "couldNotDelete",
};
}
function deleteVariables(threadId, key) {
if (key === "thread_id") {
return { thread_id: threadId, should_move_future_requests_to_spam: false };
}
return { thread_fbid: threadId, should_move_future_requests_to_spam: false };
}
function variableKey(query) {
let blob = "";
try {
blob = JSON.stringify(query && query.params);
} catch {
blob = "";
}
if (blob.includes("thread_id") && !blob.includes("thread_fbid")) return "thread_id";
return "thread_fbid";
}
function findControl(root, pattern) {
const scope = root || document;
for (const node of scope.querySelectorAll("button, a, [role='button'], [role='menuitem']")) {
if (node.closest("#igc-root")) continue;
const label = (node.getAttribute("aria-label") || node.innerText || "").replace(/\s+/g, " ").trim();
if (!label || !pattern.test(label)) continue;
const rect = node.getBoundingClientRect();
if (rect.width < 1 || rect.height < 1) continue;
return node;
}
return null;
}
async function openThread(threadId) {
checkSafety();
if (location.pathname.includes("/direct/t/" + threadId)) return true;
const existing = [...document.querySelectorAll('a[href*="/direct/t/"]')].find(
(link) => threadIdFromHref(link.getAttribute("href")) === threadId && !link.closest("#igc-root")
);
if (existing) existing.click();
else {
const link = document.createElement("a");
link.href = "/direct/t/" + threadId + "/";
link.style.display = "none";
document.body.appendChild(link);
link.click();
link.remove();
}
for (let i = 0; i < 30; i += 1) {
if (location.pathname.includes(threadId)) return true;
await sleep(200);
}
return false;
}
async function hideViaUi(threadId) {
checkSafety();
await interruptibleWait(Math.max(settings.delay, nextRequestAt - Date.now()));
const opened = await openThread(threadId);
if (!opened) return { status: 0, json: null, text: "threadOpenFailed" };
await interruptibleWait(700);
const details = document.querySelector('a[href*="/direct/t/' + threadId + '"][href*="details"]');
const info =
(details && !details.closest("#igc-root") && details) ||
findControl(document, /conversation information|sohbet bilgisi|sohbet bilgileri|thread details|^bilgi$|^details$/i);
if (!info) return { status: 0, json: null, text: "noInfoButton" };
info.click();
await interruptibleWait(500);
const remove = findControl(document, /sohbeti sil|delete chat|delete conversation/i);
if (!remove) return { status: 0, json: null, text: "noDeleteButton" };
remove.click();
await interruptibleWait(400);
const dialog = [...document.querySelectorAll("[role='dialog']")].find((node) => !node.closest("#igc-root"));
let yes = dialog && findControl(dialog, /^(sil|delete)$/i);
if (!yes) {
const matches = [...document.querySelectorAll("button, [role='button']")].filter((node) => {
if (node.closest("#igc-root")) return false;
const label = (node.innerText || "").replace(/\s+/g, " ").trim();
if (!/^(sil|delete)$/i.test(label)) return false;
const rect = node.getBoundingClientRect();
return rect.width > 0 && rect.height > 0;
});
yes = matches[matches.length - 1] || null;
}
if (!yes) return { status: 0, json: null, text: "noConfirmButton" };
checkSafety();
yes.click();
requestCount += 1;
nextRequestAt = Date.now() + settings.delay + (requestCount % settings.batch === 0 ? settings.rest : 0);
await interruptibleWait(800);
return okHide();
}
async function hideThread(threadId) {
if (deletePlan && deletePlan.kind === "ui") return hideViaUi(threadId);
try {
return await hideThreadRequest(threadId);
} catch (error) {
if (state.stop || (error && (error.i18nKey === "notLoggedIn" || error.i18nKey === "rateLimit" || /429/.test(error.message || "")))) {
throw error;
}
console.warn(error);
deletePlan = { kind: "ui" };
return hideViaUi(threadId);
}
}
async function hideThreadRequest(threadId) {
const finish = (result) => {
if (result.status === 429) state.stop = true;
return failHide(result);
};
if (!deletePlan) {
const query = findDeleteQuery() || liveQuery(DELETE_NAME, DELETE_DOC);
const key = variableKey(query);
const first = await gql(query.name, query.id, withProvided(query, deleteVariables(threadId, key)));
if (first.status === 429 || first.status === 401 || first.status === 403) return finish(first);
if (gqlOk(first)) {
deletePlan = { kind: "gql", query, key };
return okHide();
}
const alt = key === "thread_fbid" ? "thread_id" : "thread_fbid";
const second = await gql(query.name, query.id, withProvided(query, deleteVariables(threadId, alt)));
if (second.status === 429 || second.status === 401 || second.status === 403) return finish(second);
if (gqlOk(second)) {
deletePlan = { kind: "gql", query, key: alt };
return okHide();
}
console.warn("GraphQL silme olmadı, sitedeki Sohbeti sil kullanılacak.", failHide(first).text);
deletePlan = { kind: "ui" };
return hideViaUi(threadId);
}
const result = await gql(
deletePlan.query.name,
deletePlan.query.id,
withProvided(deletePlan.query, deleteVariables(threadId, deletePlan.key))
);
if (result.status === 429 || result.status === 401 || result.status === 403) return finish(result);
if (gqlOk(result)) return okHide();
return failHide(result);
}
function reportRow(thread, result, http, error) {
return {
sonuc: result,
kullanicilar: thread.usernames.join(" "),
isimler: thread.names.join(" "),
baslik: thread.title || thread.label,
grup: thread.group ? "evet" : "hayır",
kaynak: thread.source,
son_mesaj: thread.lastActivity,
thread_id: thread.id,
url: thread.id ? location.origin + "/direct/t/" + thread.id : "",
http: http || "",
hata: error || "",
zaman: new Date().toISOString(),
};
}
function listReport(mode) {
const now = new Date().toISOString();
if (mode === "saved") {
return {
tur: "kaydedilenler",
tur_islem: "liste",
baslama: now,
bitis: now,
silinen: 0,
hata: 0,
durdurulan: 0,
not: "noteListSaved",
kolonlar: ["sonuc", "kullanici", "aciklama", "url", "media_id", "thumb", "zaman"],
kayitlar: ui.savedPosts.map((post) => ({
sonuc: "listelendi",
kullanici: post.username || "",
aciklama: post.caption || "",
url: post.url || "",
media_id: post.id,
thumb: post.thumb || "",
zaman: now,
})),
};
}
return {
tur_islem: "liste",
baslama: now,
bitis: now,
silinen: 0,
hata: 0,
durdurulan: 0,
not: "noteListChats",
kolonlar: [
"sonuc",
"kullanicilar",
"isimler",
"baslik",
"grup",
"kaynak",
"son_mesaj",
"thread_id",
"url",
"zaman",
],
kayitlar: ui.threads.map((thread) => reportRow(thread, "listelendi", "", "")),
};
}
async function deleteThreads(threads, { pauseMs = 1500, onProgress } = {}) {
const rows = [];
let deleted = 0;
let failed = 0;
let consecutiveFails = 0;
const startedAt = new Date().toISOString();
for (const thread of threads) {
if (state.stop) {
rows.push(reportRow(thread, "durduruldu", "", "rowStopped"));
continue;
}
const result = await hideThread(thread.id);
const ok = result && result.status === 200 && result.json && result.json.status === "ok";
if (ok) {
deleted += 1;
consecutiveFails = 0;
thread.status = "silindi";
rows.push(reportRow(thread, "silindi", result.status, ""));
} else {
failed += 1;
consecutiveFails += 1;
thread.status = "hata";
rows.push(reportRow(thread, "hata", result && result.status, result && result.text));
if (result && (result.status === 429 || result.status === 401 || result.status === 403)) {
state.stop = true;
}
if (consecutiveFails >= 5) state.stop = true;
}
if (onProgress) onProgress({ deleted, failed, done: rows.length, total: threads.length, thread });
if (state.stop && consecutiveFails >= 5) {
// Kalanlara istek atmadan rapora yaz.
const rest = threads.slice(threads.indexOf(thread) + 1);
for (const pending of rest) {
rows.push(reportRow(pending, "durduruldu", "", "rowFailStreak"));
}
break;
}
if (state.stop && result && (result.status === 429 || result.status === 401 || result.status === 403)) {
const rest = threads.slice(threads.indexOf(thread) + 1);
for (const pending of rest) {
rows.push(reportRow(pending, "durduruldu", "", "rowLimited"));
}
break;
}
await interruptibleWait(pauseMs + Math.floor(Math.random() * 500));
}
const report = {
baslama: startedAt,
bitis: new Date().toISOString(),
silinen: deleted,
hata: failed,
durdurulan: rows.filter((row) => row.sonuc === "durduruldu").length,
not: "noteDelete",
kayitlar: rows,
};
window.IG.lastReport = report;
return report;
}
const CRC_TABLE = (() => {
const table = new Uint32Array(256);
for (let n = 0; n < 256; n += 1) {
let c = n;
for (let k = 0; k < 8; k += 1) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
table[n] = c >>> 0;
}
return table;
})();
function crc32(bytes) {
let crc = 0xffffffff;
for (let i = 0; i < bytes.length; i += 1) crc = CRC_TABLE[(crc ^ bytes[i]) & 255] ^ (crc >>> 8);
return (crc ^ 0xffffffff) >>> 0;
}
function u16(value) {
return Uint8Array.of(value & 255, (value >> 8) & 255);
}
function u32(value) {
return Uint8Array.of(value & 255, (value >> 8) & 255, (value >> 16) & 255, (value >>> 24) & 255);
}
function concatBytes(parts) {
let size = 0;
for (const part of parts) size += part.length;
const out = new Uint8Array(size);
let offset = 0;
for (const part of parts) {
out.set(part, offset);
offset += part.length;
}
return out;
}
function zipStore(files) {
const encoder = new TextEncoder();
const now = new Date();
const time = (now.getHours() << 11) | (now.getMinutes() << 5) | (now.getSeconds() >> 1);
const date = ((now.getFullYear() - 1980) << 9) | ((now.getMonth() + 1) << 5) | now.getDate();
const locals = [];
const centrals = [];
let offset = 0;
for (const file of files) {
const name = encoder.encode(file.name);
const data = typeof file.data === "string" ? encoder.encode(file.data) : file.data;
const crc = crc32(data);
const local = concatBytes([
u32(0x04034b50),
u16(20),
u16(0),
u16(0),
u16(time),
u16(date),
u32(crc),
u32(data.length),
u32(data.length),
u16(name.length),
u16(0),
name,
data,
]);
locals.push(local);
centrals.push(
concatBytes([
u32(0x02014b50),
u16(20),
u16(20),
u16(0),
u16(0),
u16(time),
u16(date),
u32(crc),
u32(data.length),
u32(data.length),
u16(name.length),
u16(0),
u16(0),
u16(0),
u16(0),
u32(0),
u32(offset),
name,
])
);
offset += local.length;
}
const centralDir = concatBytes(centrals);
const end = concatBytes([
u32(0x06054b50),
u16(0),
u16(0),
u16(files.length),
u16(files.length),
u32(centralDir.length),
u32(offset),
u16(0),
]);
return new Blob([concatBytes([...locals, centralDir, end])], {
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
});
}
function colName(index) {
let n = index + 1;
let name = "";
while (n > 0) {
const rem = (n - 1) % 26;
name = String.fromCharCode(65 + rem) + name;
n = Math.floor((n - 1) / 26);
}
return name;
}
function xmlText(value) {
return String(value ?? "")
.replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F]/g, "")
.slice(0, 32767)
.replace(/&/g, "&")
.replace(//g, ">")
.replace(/"/g, """);
}
function columnHeader(column) {
const key = "col_" + column;
const text = t(key);
return text === key ? column : text;
}
function translatedCell(column, value) {
if (value == null || value === "") return "";
if (column === "baslik" && value === "unnamed") return t("unnamedChat");
if (column === "sonuc" || column === "grup" || column === "kaynak" || column === "hata" || column === "not") {
return showPhrase(value);
}
return value;
}
function sheetTitle() {
return t("sheetReport").replace(/[\\/?*[\]:]/g, "").slice(0, 31) || "Report";
}
function reportForExport(report) {
const copy = JSON.parse(JSON.stringify(report));
copy.dil = lang === "en" ? "en" : "tr";
if (copy.not) copy.not = showPhrase(copy.not);
if (Array.isArray(copy.kayitlar)) {
copy.kayitlar = copy.kayitlar.map((row) => {
const next = { ...row };
for (const column of Object.keys(next)) next[column] = translatedCell(column, next[column]);
return next;
});
}
return copy;
}
function reportToXlsx(report) {
const columns = report.kolonlar || [
"sonuc",
"kullanicilar",
"isimler",
"baslik",
"grup",
"kaynak",
"son_mesaj",
"thread_id",
"http",
"hata",
"zaman",
];
const rows = [columns.map(columnHeader)];
for (const row of report.kayitlar || []) rows.push(columns.map((column) => translatedCell(column, row[column])));
const sheet = [
'',
'