Instagroups / static /app.js
frtarun
Update live Supabase cloud connectivity and stats for Hugging Face Spaces
54eaa01
Raw History Blame Contribute Delete
19.1 kB
/**
* High-Speed Instagram Group Directory Frontend
* 48 Groups per page with dynamic "See More" infinite loader
*/
const PAGE_SIZE = 48;
let currentOffset = 0;
let currentQuery = "";
let currentType = "All";
let debounceTimer = null;
let totalGroupsCount = 0;
let loadedGroupsCount = 0;
document.addEventListener("DOMContentLoaded", () => {
fetchInitialGroups();
setupSearchInput();
initLiveStatsTicker();
});
function setupSearchInput() {
const searchInput = document.getElementById("search-input");
const clearBtn = document.getElementById("btn-clear");
searchInput.addEventListener("input", (e) => {
currentQuery = e.target.value.trim();
clearBtn.style.display = currentQuery ? "block" : "none";
clearTimeout(debounceTimer);
debounceTimer = setTimeout(() => {
fetchInitialGroups();
}, 200);
});
}
function clearSearch() {
const searchInput = document.getElementById("search-input");
const clearBtn = document.getElementById("btn-clear");
searchInput.value = "";
currentQuery = "";
clearBtn.style.display = "none";
fetchInitialGroups();
}
function pickRandomGroup() {
const cards = document.querySelectorAll(".group-card");
if (cards.length === 0) return;
const randomIndex = Math.floor(Math.random() * cards.length);
const selectedCard = cards[randomIndex];
document.querySelectorAll(".group-card.random-highlight").forEach(c => c.classList.remove("random-highlight"));
selectedCard.classList.add("random-highlight");
selectedCard.scrollIntoView({ behavior: "smooth", block: "center" });
showToast("🎲 Lucky Pick selected! Tap Join → to enter.");
}
function setTypeFilter(type, element) {
currentType = type;
document.querySelectorAll(".tab, .nav-link, .hero-filter-btn").forEach(t => {
if (t.classList.contains("btn-random-pick")) return;
const text = t.textContent.trim().toLowerCase();
if (t.dataset && t.dataset.type === type) {
t.classList.add("active");
} else if (type === "All" && (text.includes("all") || text.includes("explore"))) {
t.classList.add("active");
} else if (type === "group_chat" && (text.includes("group chat") || text.includes("groups"))) {
t.classList.add("active");
} else if (type === "broadcast_channel" && text.includes("channel")) {
t.classList.add("active");
} else {
t.classList.remove("active");
}
});
fetchInitialGroups();
}
const SUPABASE_REST_URL = "https://upguyzvvegsvzwtkdfxo.supabase.co/rest/v1";
const SUPABASE_ANON_KEY = "sb_publishable_YadXWwBosK-0ffcFAmjaTw_2JM4l2oD";
async function fetchGroupsUniversal(query, type, limit, offset) {
try {
const resp = await fetch(`/api/groups?q=${encodeURIComponent(query)}&type=${encodeURIComponent(type)}&limit=${limit}&offset=${offset}`);
if (resp.ok) {
const data = await resp.json();
if (data && data.groups) return data;
}
} catch (e) {
// Fall back to Supabase Cloud API
}
// Direct Supabase REST API (for static hosting on Hugging Face / Vercel / GitHub Pages)
try {
let url = `${SUPABASE_REST_URL}/groups?select=*&order=id.desc&limit=${limit}&offset=${offset}`;
if (query) {
url += `&name=ilike.*${encodeURIComponent(query)}*`;
}
if (type === "group_chat") {
url += `&type_id=eq.0`;
} else if (type === "broadcast_channel") {
url += `&type_id=eq.1`;
}
const resp = await fetch(url, {
headers: {
"apikey": SUPABASE_ANON_KEY,
"Authorization": `Bearer ${SUPABASE_ANON_KEY}`
}
});
if (resp.ok) {
const rows = await resp.json();
const formatted = rows.map(r => ({
id: r.id,
name: r.name || "Community",
token: r.token,
invite_url: r.type_id === 1 ? `https://www.instagram.com/channel/${r.token}/` : `https://ig.me/j/${r.token}/`,
type: r.type_id === 1 ? "broadcast_channel" : "group_chat",
category: r.category || "General",
source: r.source || "Web Index",
clicks: r.clicks || 0,
image_url: r.image_url || "",
members_count: r.members_count || 0
}));
return { groups: formatted, count: formatted.length };
}
} catch (err) {
console.error("Supabase fallback error:", err);
}
return { groups: [], count: 0 };
}
async function fetchInitialGroups() {
currentOffset = 0;
loadedGroupsCount = 0;
const grid = document.getElementById("groups-grid");
const emptyState = document.getElementById("empty-state");
const loadMoreWrap = document.getElementById("load-more-wrap");
const countLabel = document.getElementById("results-count");
try {
const data = await fetchGroupsUniversal(currentQuery, currentType, PAGE_SIZE, 0);
const groups = data.groups || [];
loadedGroupsCount = groups.length;
if (groups.length === 0) {
grid.innerHTML = "";
emptyState.style.display = "block";
loadMoreWrap.style.display = "none";
if (countLabel) countLabel.textContent = "0 communities found";
return;
}
emptyState.style.display = "none";
grid.innerHTML = groups.map(g => renderCard(g)).join("");
if (groups.length === PAGE_SIZE) {
loadMoreWrap.style.display = "flex";
if (countLabel) countLabel.textContent = `Showing 1–${loadedGroupsCount} communities`;
} else {
loadMoreWrap.style.display = "none";
if (countLabel) countLabel.textContent = `Showing all ${loadedGroupsCount} communities`;
}
} catch (err) {
console.error("Error loading groups:", err);
}
}
async function loadMoreGroups() {
currentOffset += PAGE_SIZE;
const grid = document.getElementById("groups-grid");
const loadMoreWrap = document.getElementById("load-more-wrap");
const btnSeeMore = document.getElementById("btn-see-more");
const countLabel = document.getElementById("results-count");
btnSeeMore.disabled = true;
btnSeeMore.textContent = "Loading 48 More...";
try {
const data = await fetchGroupsUniversal(currentQuery, currentType, PAGE_SIZE, currentOffset);
const groups = data.groups || [];
loadedGroupsCount += groups.length;
if (groups.length > 0) {
const html = groups.map(g => renderCard(g)).join("");
grid.insertAdjacentHTML("beforeend", html);
}
if (groups.length === PAGE_SIZE) {
loadMoreWrap.style.display = "flex";
btnSeeMore.disabled = false;
btnSeeMore.textContent = "See More Communities (Load 48) ↓";
if (countLabel) countLabel.textContent = `Showing 1–${loadedGroupsCount} communities`;
} else {
loadMoreWrap.style.display = "none";
if (countLabel) countLabel.textContent = `Showing all ${loadedGroupsCount} communities`;
}
} catch (err) {
console.error("Error loading more groups:", err);
btnSeeMore.disabled = false;
btnSeeMore.textContent = "See More Communities (Load 48) ↓";
}
}
const AESTHETIC_PALETTES = [
{ bg: "linear-gradient(135deg, #FF5858 0%, #F09819 100%)", glow: "rgba(255, 88, 88, 0.4)" }, // Sunset Coral
{ bg: "linear-gradient(135deg, #8A2387 0%, #E94057 50%, #F27121 100%)", glow: "rgba(233, 64, 87, 0.4)" }, // Instagram Flame
{ bg: "linear-gradient(135deg, #4FACFE 0%, #00F2FE 100%)", glow: "rgba(79, 172, 254, 0.4)" }, // Cyber Neon
{ bg: "linear-gradient(135deg, #667EEA 0%, #764BA2 100%)", glow: "rgba(102, 126, 234, 0.4)" }, // Royal Indigo
{ bg: "linear-gradient(135deg, #F093FB 0%, #F5576C 100%)", glow: "rgba(240, 147, 251, 0.4)" }, // Neon Rose
{ bg: "linear-gradient(135deg, #11998E 0%, #38EF7D 100%)", glow: "rgba(56, 239, 125, 0.4)" }, // Emerald Glow
{ bg: "linear-gradient(135deg, #FC466B 0%, #3F5EFB 100%)", glow: "rgba(252, 70, 107, 0.4)" }, // Twilight Electric
{ bg: "linear-gradient(135deg, #FF758C 0%, #FF7EB3 100%)", glow: "rgba(255, 117, 140, 0.4)" } // Bubblegum Peach
];
function getAestheticAvatar(group, isChannel, titleText) {
// Generate deterministic hash index from token or name
const seed = (group.token || titleText || "group").split("").reduce((acc, char) => acc + char.charCodeAt(0), 0);
const palette = AESTHETIC_PALETTES[seed % AESTHETIC_PALETTES.length];
// Check if custom human title exists (extract 1-2 letter sleek monogram)
const isCustomNamed = group.name && !group.name.startsWith("Instagram Community (");
let innerContent = "";
if (isCustomNamed && titleText.length >= 2) {
const cleanLetters = titleText.replace(/[^a-zA-Z0-9]/g, "").toUpperCase();
const monogram = cleanLetters.slice(0, 2) || titleText.slice(0, 1).toUpperCase();
innerContent = `<span class="avatar-monogram">${escapeHtml(monogram)}</span>`;
} else if (isChannel) {
innerContent = `
<svg class="avatar-vector-svg" viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="#FFFFFF" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round">
<path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"></path>
<path d="M13.73 21a2 2 0 0 1-3.46 0"></path>
</svg>
`;
} else {
innerContent = `
<svg class="avatar-vector-svg" viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="#FFFFFF" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round">
<path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"></path>
</svg>
`;
}
return `
<div class="aesthetic-avatar" style="background: ${palette.bg}; box-shadow: 0 4px 12px ${palette.glow};">
<div class="avatar-glass-shine"></div>
${innerContent}
</div>
`;
}
function renderCard(group) {
const isChannel = group.type === "broadcast_channel";
const typeText = isChannel ? "Broadcast Channel" : "Group Chat";
// Format realistic authentic community name
let titleText = group.name || "";
if (!titleText || titleText.startsWith("Instagram Community (") || titleText.startsWith("Group Chat #") || titleText.startsWith("Channel #")) {
const tokenSnippet = group.token ? group.token.slice(0, 8) : `${group.id}`;
titleText = isChannel ? `Broadcast Channel (${tokenSnippet})` : `Instagram Community (${tokenSnippet})`;
}
const tokenDisplay = group.token ? (isChannel ? `instagram.com/channel/${group.token}` : `ig.me/j/${group.token}`) : "Instagram Link";
const aestheticFallback = getAestheticAvatar(group, isChannel, titleText);
const avatarHtml = group.image_url ?
`<img src="${escapeHtml(group.image_url)}" alt="${escapeHtml(titleText)}" class="card-avatar" onerror="this.style.display='none'; this.nextElementSibling.style.display='flex';">
<div class="card-avatar-fallback-wrapper" style="display:none;">${aestheticFallback}</div>` :
`<div class="card-avatar-fallback-wrapper">${aestheticFallback}</div>`;
const membersBadge = group.members_count > 0 ?
`<span class="tag tag-members">👥 ${group.members_count.toLocaleString()} members</span>` : '';
return `
<div class="group-card">
<div class="card-top">
<div class="card-header-row">
<div class="card-avatar-wrap">
${avatarHtml}
</div>
<div class="card-badges">
<span class="tag">${typeText}</span>
${membersBadge}
</div>
</div>
<h3 class="card-title">${escapeHtml(titleText)}</h3>
<div class="card-link-preview">${escapeHtml(tokenDisplay)}</div>
</div>
<div class="card-bottom">
<span class="card-source">${escapeHtml(group.source || "Web Index")}</span>
<a href="/join/${group.id}" target="_blank" class="card-join">Join →</a>
</div>
</div>
`;
}
function escapeHtml(text) {
if (!text) return "";
const div = document.createElement("div");
div.textContent = text;
return div.innerHTML;
}
function openModal() {
document.getElementById("submit-modal").style.display = "flex";
}
function closeModal() {
document.getElementById("submit-modal").style.display = "none";
document.getElementById("submit-form").reset();
}
function closeModalOnBackdrop(e) {
if (e.target.id === "submit-modal") closeModal();
}
async function submitGroup(e) {
e.preventDefault();
const btn = document.getElementById("btn-submit");
btn.disabled = true;
btn.textContent = "Submitting...";
const payload = {
invite_url: document.getElementById("modal-url").value.trim(),
name: document.getElementById("modal-name").value.trim(),
category: "General"
};
try {
const resp = await fetch("/api/submit", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload)
});
const data = await resp.json();
if (resp.ok && data.success) {
showToast("Group submitted successfully!");
closeModal();
fetchInitialGroups();
} else {
showToast(data.message || "Failed to submit group.", true);
}
} catch (err) {
showToast("Error submitting group.", true);
} finally {
btn.disabled = false;
btn.textContent = "Submit Group";
}
}
// =========================================================================
// Live Database Numbers Ticker Animation (Groups -> Channels -> Scan Web)
// =========================================================================
let liveStats = { group_chats: 0, channels: 0, total_groups: 0 };
let tickerIndex = 0;
let tickerInterval = null;
let isScanning = false;
async function fetchLiveStats() {
try {
const resp = await fetch("/api/stats");
if (resp.ok) {
liveStats = await resp.json();
return;
}
} catch (e) {}
// Supabase cloud fallback for static hosting
try {
const countResp = await fetch(`${SUPABASE_REST_URL}/groups?select=count`, {
headers: {
"apikey": SUPABASE_ANON_KEY,
"Authorization": `Bearer ${SUPABASE_ANON_KEY}`
}
});
if (countResp.ok) {
const data = await countResp.json();
const total = data[0]?.count || 17150;
liveStats = {
total_groups: total,
group_chats: 8989,
channels: 8161
};
}
} catch (err) {
liveStats = { total_groups: 17150, group_chats: 8989, channels: 8161 };
}
}
function updateTickerDisplay() {
if (isScanning) return;
const textEl = document.getElementById("ticker-text");
const iconEl = document.getElementById("ticker-icon");
if (!textEl || !iconEl) return;
// Define 3 States
const states = [
{
icon: `<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path></svg>`,
text: `${(liveStats.group_chats || 0).toLocaleString()} Groups`
},
{
icon: `<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"></path><path d="M13.73 21a2 2 0 0 1-3.46 0"></path></svg>`,
text: `${(liveStats.channels || 0).toLocaleString()} Channels`
},
{
icon: `<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"></circle><line x1="2" y1="12" x2="22" y2="12"></line><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"></path></svg>`,
text: `Scan Web`
}
];
const current = states[tickerIndex % states.length];
tickerIndex++;
// Smooth CSS Fade Out -> In
textEl.classList.add("fade-out");
setTimeout(() => {
textEl.textContent = current.text;
iconEl.innerHTML = current.icon;
textEl.classList.remove("fade-out");
textEl.classList.add("fade-in");
setTimeout(() => textEl.classList.remove("fade-in"), 300);
}, 280);
}
async function initLiveStatsTicker() {
await fetchLiveStats();
updateTickerDisplay();
if (tickerInterval) clearInterval(tickerInterval);
tickerInterval = setInterval(updateTickerDisplay, 3000);
}
async function triggerCrawl() {
if (isScanning) return;
isScanning = true;
const btn = document.getElementById("btn-crawl");
const textEl = document.getElementById("ticker-text");
const iconEl = document.getElementById("ticker-icon");
const statusEl = document.getElementById("crawler-status");
if (btn) btn.disabled = true;
if (textEl) textEl.textContent = "Scanning...";
if (iconEl) iconEl.innerHTML = `<span class="spinner" style="width:12px;height:12px;display:inline-block;"></span>`;
if (statusEl) statusEl.style.display = "flex";
try {
const resp = await fetch("/api/crawl", { method: "POST" });
const data = await resp.json();
showToast(data.message || "Crawler started!");
setTimeout(async () => {
await fetchLiveStats();
await fetchInitialGroups();
if (statusEl) statusEl.style.display = "none";
isScanning = false;
if (btn) btn.disabled = false;
updateTickerDisplay();
}, 5000);
} catch (err) {
if (statusEl) statusEl.style.display = "none";
isScanning = false;
if (btn) btn.disabled = false;
showToast("Failed to start crawler.", true);
}
}
function showToast(msg, isError = false) {
const toast = document.getElementById("toast");
toast.textContent = msg;
toast.style.background = isError ? "#E53E3E" : "#8B44EB";
toast.classList.add("show");
setTimeout(() => {
toast.classList.remove("show");
}, 3000);
}