Elephant Architect commited on
Commit ·
657681d
1
Parent(s): 3adf599
feat: two-phase deep historical channel crawler, monotonic cursor progression, and dynamic top ID discovery
Browse filesFiles changed (5)
11 unmodified lines121314151617235 unmodified lines25325425525625725825926026111 unmodified lines} from './telegramBatchRegistry.service';import { validateTelegramChannelAccess } from './telegramPublisher.service';import { apiUsageTracker } from './apiUsageTracker.service';export interface TelegramAutomationLogEntry {id: string;235 unmodified linesthis.addLog('warn', this.statusDetail);}} else {// Zero candidates found (history up-to-date)this.status = 'WAITING';this.statusDetail = `تم فحص أحدث منشورات @${config.sourceChannel}: جميع المقاطع معالجة ومسجلة بالسجل مسبقاً. في انتظار المنشورات الجديدة.`;this.addLog('info', this.statusDetail);await statePersistence.updateTelegramAutomationConfig({lastRunTimestamp: Date.now(),11 unmodified lines12131415161718235 unmodified lines25425525625725825926026126226326426526626711 unmodified lines} from './telegramBatchRegistry.service';import { validateTelegramChannelAccess } from './telegramPublisher.service';import { apiUsageTracker } from './apiUsageTracker.service';import { getChannelState } from './telegramCrawler.service';export interface TelegramAutomationLogEntry {id: string;235 unmodified linesthis.addLog('warn', this.statusDetail);}} else {// Zero candidates found in this cyclethis.status = 'WAITING';const chanState = getChannelState(config.sourceChannel);if (chanState.historyExhausted) {this.statusDetail = `تم فحص أرشيف @${config.sourceChannel} بالكامل حتى أول منشور: جميع المقاطع معالجة ومسجلة بالسجل مسبقاً. في انتظار المنشورات الجديدة.`;} else {this.statusDetail = `تم فحص منشورات @${config.sourceChannel} حتى المعرف #${chanState.lowestEvaluatedPostId || 'القمة'}. سيتم مواصلة فحص الأرشيف التاريخي في الدورة القادمة.`;}this.addLog('info', this.statusDetail);await statePersistence.updateTelegramAutomationConfig({lastRunTimestamp: Date.now(),
344 unmodified lines3453463473483493503518 unmodified lines3603613623633643658 unmodified lines374375376377378379380381382344 unmodified linesconst state: TelegramChannelState = getChannelState(job.channelSlug);const { candidates, updatedLowestPostId, error: crawlError } = await findUnprocessedVideoCandidates(job.channelSlug,job.requestedCount,state,8 unmodified linesif (updatedLowestPostId !== undefined) {state.lowestEvaluatedPostId = updatedLowestPostId;}if (candidates.length === 0) {if (crawlError) {8 unmodified linesjob.status = 'COMPLETED';job.endTime = Date.now();job.progress.percent = 100;saveChannelState(state);saveBatchHistoryEntry(job);logger.info(`No un-ingested video candidates found in @${job.channelSlug}. History is up-to-date.`, 'telegramBatchRegistry');return;}344 unmodified lines3453463473483493503518 unmodified lines3603613623633643653663673683698 unmodified lines378379380381382383384385386387388389344 unmodified linesconst state: TelegramChannelState = getChannelState(job.channelSlug);const { candidates, updatedLowestPostId, historyExhausted, error: crawlError } = await findUnprocessedVideoCandidates(job.channelSlug,job.requestedCount,state,8 unmodified linesif (updatedLowestPostId !== undefined) {state.lowestEvaluatedPostId = updatedLowestPostId;}if (historyExhausted !== undefined) {state.historyExhausted = historyExhausted;}saveChannelState(state);if (candidates.length === 0) {if (crawlError) {8 unmodified linesjob.status = 'COMPLETED';job.endTime = Date.now();job.progress.percent = 100;saveBatchHistoryEntry(job);if (state.historyExhausted) {logger.info(`No un-ingested video candidates found in @${job.channelSlug}. Full archive exhausted down to beginning.`, 'telegramBatchRegistry');} else {logger.info(`No un-ingested candidates in current historical window for @${job.channelSlug} (Lowest post: #${state.lowestEvaluatedPostId}). Will continue historical traversal in next cycle.`, 'telegramBatchRegistry');}return;}
42 unmodified lines434445464748279 unmodified lines3283293303313323333343353 unmodified lines33934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449542 unmodified lineslastRunTimestamp: number;lowestEvaluatedPostId?: number;highestEvaluatedPostId?: number;totalProcessedCount: number;processedPostIds: Record<string, IngestedPostRecord>;}279 unmodified linesreturn { posts, nextBefore };}/*** Crawls Telegram channel history to discover un-ingested video candidates*/export async function findUnprocessedVideoCandidates(channelSlug: string,3 unmodified linesdurationFilter?: TelegramDurationFilterConfig;smartCut?: SmartCutConfig;}): Promise<{ candidates: TelegramScrapedPost[]; updatedLowestPostId?: number; error?: string }> {const candidates: TelegramScrapedPost[] = [];const maxPages = 8;let pageCount = 0;let consecutiveEmpty = 0;let lowestInspected = state.lowestEvaluatedPostId;let lastScrapeError: string | undefined;let currentBefore: number | undefined = undefined;const key = process.env.STUDIO_PASSWORD || 'quran123';const internalBotUrl = process.env.INTERNAL_BOT_URL || 'http://127.0.0.1:7860';while (candidates.length < targetCount && pageCount < maxPages && consecutiveEmpty < 3) {pageCount++;let posts: TelegramScrapedPost[] = [];let nextBefore: number | null = null;// Tier 1: Query internal MTProto service (Unblockable official protocol, 0% 403 error risk)try {const mtprotoRes: any = await axios.post(`${internalBotUrl}/internal/get_channel_posts?key=${key}`,{channel: channelSlug,limit: Math.max(targetCount * 3, 20),before_post_id: currentBefore,},{ timeout: 15000 });if (mtprotoRes.data && mtprotoRes.data.success && Array.isArray(mtprotoRes.data.posts)) {posts = mtprotoRes.data.posts.filter((p: any) => p && p.hasVideo).map((p: any) => ({channelSlug,postId: p.postId,postUrl: p.postUrl || `https://t.me/${channelSlug}/${p.postId}`,hasVideo: true,videoUrl: p.videoUrl,durationSec: p.durationSec,fileSizeBytes: p.fileSizeBytes,caption: p.caption || '',rawChromaFilename: `chroma_tg_${channelSlug}_${p.postId}_${Date.now()}.mp4`,}));nextBefore = mtprotoRes.data.nextBefore ?? null;logger.info(`MTProto returned ${posts.length} video candidates for @${channelSlug} (method: ${mtprotoRes.data.method})`, 'telegramCrawler');}} catch (mtErr: any) {logger.warn(`MTProto channel scrape not available (${mtErr.message}). Falling back to web preview scraper...`, 'telegramCrawler');}// Tier 2: Web preview scrape fallback (if MTProto offline or returned no posts)if (posts.length === 0 && !nextBefore) {try {const scraped = await scrapeTelegramPage(channelSlug, currentBefore);posts = scraped.posts;nextBefore = scraped.nextBefore;} catch (err: any) {lastScrapeError = err.message;logger.error(`Error scraping Telegram page: ${err.message}`, 'telegramCrawler');break;}}if (posts.length === 0) {consecutiveEmpty++;} else {consecutiveEmpty = 0;}for (const post of posts) {if (!lowestInspected || post.postId < lowestInspected) {lowestInspected = post.postId;}// Check if already processed in stateif (!state.processedPostIds[post.postId.toString()]) {// Early Duration Filter Evaluationif (options?.durationFilter?.enabled) {const filterType = options.durationFilter.filterType || 'min_duration';const thresholdSec = options.durationFilter.minDurationSec || options.durationFilter.maxDurationSec || 50;if (post.durationSec !== undefined && post.durationSec > 0) {let dropPost = false;let dropReason = '';if (filterType === 'min_duration') {// Requirement: Only videos > thresholdSec are selected; videos <= thresholdSec are strictly excluded!if (post.durationSec <= thresholdSec) {dropPost = true;dropReason = `duration ${post.durationSec}s <= threshold ${thresholdSec}s (only videos > ${thresholdSec}s are selected)`;} else if (post.durationSec > 600) {dropPost = true;dropReason = `duration ${post.durationSec}s exceeds 600s upper safety ceiling`;}} else {// max_duration mode: exclude videos > thresholdSecif (post.durationSec > thresholdSec) {dropPost = true;dropReason = `duration ${post.durationSec}s > limit ${thresholdSec}s`;}}if (dropPost) {logger.info(`[EARLY FILTER] Post #${post.postId} dropped: ${dropReason}`, 'telegramCrawler');state.processedPostIds[post.postId.toString()] = {postId: post.postId,ingestedAt: Date.now(),sourcePostUrl: post.postUrl,caption: post.caption,durationSec: post.durationSec,status: 'SKIPPED_TOO_SHORT',error: dropReason,};saveChannelState(state);continue;}}}// Avoid duplicates in current runif (!candidates.some((c) => c.postId === post.postId)) {candidates.push(post);if (candidates.length >= targetCount) break;}}}if (candidates.length >= targetCount) break;// Cursor progression:if (!nextBefore || nextBefore === currentBefore) {if (currentBefore === undefined && state.lowestEvaluatedPostId && state.lowestEvaluatedPostId < (lowestInspected || Infinity)) {logger.info(`Top feed evaluated (${candidates.length}/${targetCount} candidates). Jumping to historical archive at < ${state.lowestEvaluatedPostId}`, 'telegramCrawler');currentBefore = state.lowestEvaluatedPostId;continue;}logger.info(`Channel history reached end or no further cursor found for: ${channelSlug}`, 'telegramCrawler');break;}currentBefore = nextBefore;// Jitter delay (600ms - 1000ms)const jitterMs = Math.floor(Math.random() * 400) + 600;await new Promise((r) => setTimeout(r, jitterMs));}logger.info(`Discovered ${candidates.length} un-ingested candidates for channel ${channelSlug} (pages checked: ${pageCount})`, 'telegramCrawler');return {candidates,updatedLowestPostId: lowestInspected,error: candidates.length === 0 ? lastScrapeError : undefined,};}42 unmodified lines43444546474849279 unmodified lines3293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084093 unmodified lines41341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363442 unmodified lineslastRunTimestamp: number;lowestEvaluatedPostId?: number;highestEvaluatedPostId?: number;historyExhausted?: boolean;totalProcessedCount: number;processedPostIds: Record<string, IngestedPostRecord>;}279 unmodified linesreturn { posts, nextBefore };}/*** Fetches a single batch of Telegram posts via MTProto with web preview fallback*/async function fetchTelegramPostsBatch(channelSlug: string,beforePostId?: number,limit: number = 50): Promise<{posts: TelegramScrapedPost[];rawPosts?: any[];nextBefore: number | null;lowestPostIdSeen?: number;}> {const key = process.env.STUDIO_PASSWORD || 'quran123';const internalBotUrl = process.env.INTERNAL_BOT_URL || 'http://127.0.0.1:7860';let posts: TelegramScrapedPost[] = [];let rawPosts: any[] = [];let nextBefore: number | null = null;let lowestPostIdSeen: number | undefined;// Tier 1: Query internal MTProto service (Unblockable official protocol, 0% 403 error risk)try {const mtprotoRes: any = await axios.post(`${internalBotUrl}/internal/get_channel_posts?key=${key}`,{channel: channelSlug,limit,before_post_id: beforePostId,},{ timeout: 20000 });if (mtprotoRes.data && mtprotoRes.data.success && Array.isArray(mtprotoRes.data.posts)) {rawPosts = mtprotoRes.data.posts;posts = rawPosts.filter((p: any) => p && p.hasVideo).map((p: any) => ({channelSlug,postId: p.postId,postUrl: p.postUrl || `https://t.me/${channelSlug}/${p.postId}`,hasVideo: true,videoUrl: p.videoUrl,durationSec: p.durationSec,fileSizeBytes: p.fileSizeBytes,caption: p.caption || '',rawChromaFilename: `chroma_tg_${channelSlug}_${p.postId}_${Date.now()}.mp4`,}));nextBefore = mtprotoRes.data.nextBefore ?? null;if (rawPosts.length > 0) {lowestPostIdSeen = Math.min(...rawPosts.map((p: any) => p.postId));}logger.info(`MTProto batch returned ${posts.length} videos out of ${rawPosts.length} messages for @${channelSlug} (before: ${beforePostId ?? 'HEAD'}, nextBefore: ${nextBefore})`,'telegramCrawler');return { posts, rawPosts, nextBefore, lowestPostIdSeen };}} catch (mtErr: any) {logger.warn(`MTProto channel scrape not available (${mtErr.message}). Falling back to web preview scraper...`, 'telegramCrawler');}// Tier 2: Web preview scrape fallback (if MTProto offline or returned no posts)const scraped = await scrapeTelegramPage(channelSlug, beforePostId);posts = scraped.posts;nextBefore = scraped.nextBefore;if (posts.length > 0) {lowestPostIdSeen = Math.min(...posts.map((p) => p.postId));}return { posts, rawPosts: posts, nextBefore, lowestPostIdSeen };}/*** Crawls Telegram channel history to discover un-ingested video candidates* Supports dual-phase discovery:* Phase 1: Fast head check for newly published posts* Phase 2: Deep historical archive backfill resuming from lowestEvaluatedPostId*/export async function findUnprocessedVideoCandidates(channelSlug: string,3 unmodified linesdurationFilter?: TelegramDurationFilterConfig;smartCut?: SmartCutConfig;}): Promise<{candidates: TelegramScrapedPost[];updatedLowestPostId?: number;historyExhausted?: boolean;error?: string;}> {const candidates: TelegramScrapedPost[] = [];let lowestInspected = state.lowestEvaluatedPostId;let lastScrapeError: string | undefined;// Helper to evaluate duration filter and deduplicateconst evaluateAndAddCandidate = (post: TelegramScrapedPost): boolean => {if (!lowestInspected || post.postId < lowestInspected) {lowestInspected = post.postId;}// Check if already processed in stateif (state.processedPostIds[post.postId.toString()]) {return false;}// Early Duration Filter Evaluationif (options?.durationFilter?.enabled) {const filterType = options.durationFilter.filterType || 'min_duration';const thresholdSec = options.durationFilter.minDurationSec || options.durationFilter.maxDurationSec || 50;if (post.durationSec !== undefined && post.durationSec > 0) {let dropPost = false;let dropReason = '';if (filterType === 'min_duration') {// Requirement: Only videos > thresholdSec are selected; videos <= thresholdSec are strictly excluded!if (post.durationSec <= thresholdSec) {dropPost = true;dropReason = `duration ${post.durationSec}s <= threshold ${thresholdSec}s (only videos > ${thresholdSec}s are selected)`;} else if (post.durationSec > 600) {dropPost = true;dropReason = `duration ${post.durationSec}s exceeds 600s upper safety ceiling`;}} else {// max_duration mode: exclude videos > thresholdSecif (post.durationSec > thresholdSec) {dropPost = true;dropReason = `duration ${post.durationSec}s > limit ${thresholdSec}s`;}}if (dropPost) {logger.info(`[EARLY FILTER] Post #${post.postId} dropped: ${dropReason}`, 'telegramCrawler');state.processedPostIds[post.postId.toString()] = {postId: post.postId,ingestedAt: Date.now(),sourcePostUrl: post.postUrl,caption: post.caption,durationSec: post.durationSec,status: 'SKIPPED_TOO_SHORT',error: dropReason,};saveChannelState(state);return false;}}}// Avoid duplicates in current runif (!candidates.some((c) => c.postId === post.postId)) {candidates.push(post);return true;}return false;};// ==========================================// PHASE 1: Head Check (Check for newly published posts)// ==========================================logger.info(`[DISCOVERY] Phase 1: Checking top feed of @${channelSlug} for fresh posts...`, 'telegramCrawler');let headNextBefore: number | null = null;let headLowestSeen: number | undefined;try {const headBatch = await fetchTelegramPostsBatch(channelSlug, undefined, Math.max(targetCount * 3, 30));headNextBefore = headBatch.nextBefore;headLowestSeen = headBatch.lowestPostIdSeen;if (headBatch.rawPosts && headBatch.rawPosts.length > 0) {const topId = Math.max(...headBatch.rawPosts.map((p) => p.postId));if (!state.highestEvaluatedPostId || topId > state.highestEvaluatedPostId) {state.highestEvaluatedPostId = topId;}}for (const post of headBatch.posts) {evaluateAndAddCandidate(post);if (candidates.length >= targetCount) break;}if (headLowestSeen && (!lowestInspected || headLowestSeen < lowestInspected)) {lowestInspected = headLowestSeen;}} catch (err: any) {lastScrapeError = err.message;logger.warn(`Phase 1 top feed check failed: ${err.message}`, 'telegramCrawler');}if (candidates.length >= targetCount) {logger.info(`[DISCOVERY] Phase 1 satisfied target (${candidates.length}/${targetCount} candidates from fresh feed).`, 'telegramCrawler');saveChannelState(state);return {candidates,updatedLowestPostId: lowestInspected,historyExhausted: state.historyExhausted,};}// ==========================================// PHASE 2: Deep Historical Archive Backfill// ==========================================if (state.historyExhausted) {logger.info(`[DISCOVERY] Channel @${channelSlug} historical archive was already exhausted down to beginning.`, 'telegramCrawler');return {candidates,updatedLowestPostId: lowestInspected,historyExhausted: true,error: candidates.length === 0 ? lastScrapeError : undefined,};}// Determine starting point for historical crawl:// If state.lowestEvaluatedPostId exists, resume from there!// Otherwise, continue from headNextBefore or headLowestSeen.let historicalCursor: number | undefined = state.lowestEvaluatedPostId || headNextBefore || headLowestSeen;if (!historicalCursor || historicalCursor <= 1) {state.historyExhausted = true;saveChannelState(state);return {candidates,updatedLowestPostId: 1,historyExhausted: true,error: candidates.length === 0 ? lastScrapeError : undefined,};}logger.info(`[DISCOVERY] Phase 2: Traversing historical archive of @${channelSlug} starting before #${historicalCursor} (Target: ${targetCount - candidates.length} more)...`,'telegramCrawler');const maxHistoricalPages = 30; // Allows up to 30 pages * 50 = 1,500 messages per run!let historicalPageCount = 0;let consecutiveEmptyPages = 0;while (candidates.length < targetCount &&historicalPageCount < maxHistoricalPages &&consecutiveEmptyPages < 4 &&historicalCursor &&historicalCursor > 1) {historicalPageCount++;try {const histBatch = await fetchTelegramPostsBatch(channelSlug, historicalCursor, 50);if (histBatch.posts.length === 0 && (!histBatch.rawPosts || histBatch.rawPosts.length === 0)) {consecutiveEmptyPages++;} else {consecutiveEmptyPages = 0;}for (const post of histBatch.posts) {evaluateAndAddCandidate(post);if (candidates.length >= targetCount) break;}if (histBatch.lowestPostIdSeen && (!lowestInspected || histBatch.lowestPostIdSeen < lowestInspected)) {lowestInspected = histBatch.lowestPostIdSeen;state.lowestEvaluatedPostId = lowestInspected;}// Check end of channel historyif (!histBatch.nextBefore || histBatch.nextBefore >= historicalCursor || histBatch.nextBefore <= 1) {logger.info(`[DISCOVERY] Channel @${channelSlug} reached beginning of archive (cursor <= 1 or no further pages).`, 'telegramCrawler');state.historyExhausted = true;state.lowestEvaluatedPostId = 1;lowestInspected = 1;saveChannelState(state);break;}historicalCursor = histBatch.nextBefore;state.lowestEvaluatedPostId = historicalCursor;saveChannelState(state);if (candidates.length >= targetCount) break;// Rate-limiting jitter between historical pages (400 - 700ms)const jitterMs = Math.floor(Math.random() * 300) + 400;await new Promise((r) => setTimeout(r, jitterMs));} catch (err: any) {lastScrapeError = err.message;logger.warn(`Error on historical page ${historicalPageCount}: ${err.message}`, 'telegramCrawler');break;}}logger.info(`[DISCOVERY] Crawl complete for @${channelSlug}. Candidates found: ${candidates.length}/${targetCount} (Lowest evaluated post: #${state.lowestEvaluatedPostId || lowestInspected})`,'telegramCrawler');saveChannelState(state);return {candidates,updatedLowestPostId: state.lowestEvaluatedPostId || lowestInspected,historyExhausted: state.historyExhausted,error: candidates.length === 0 ? lastScrapeError : undefined,};}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115import { describe, it, expect } from '@jest/globals';import { findUnprocessedVideoCandidates, TelegramChannelState, TelegramScrapedPost,} from '../src/services/telegramCrawler.service';
describe('Telegram Deep Historical Discovery & Pagination Architecture', () => { it('resumes from lowestEvaluatedPostId and discovers older unprocessed videos when top feed is processed', async () => { // Mock channel state where posts 7900-7910 are already processed, lowestEvaluatedPostId is 7891 const state: TelegramChannelState = { channelSlug: 'quranbng', lastRunTimestamp: Date.now(), lowestEvaluatedPostId: 7891, highestEvaluatedPostId: 7910, totalProcessedCount: 10, processedPostIds: { '7910': { postId: 7910, ingestedAt: Date.now(), sourcePostUrl: '', caption: '', status: 'COMPLETED' }, '7909': { postId: 7909, ingestedAt: Date.now(), sourcePostUrl: '', caption: '', status: 'COMPLETED' }, '7908': { postId: 7908, ingestedAt: Date.now(), sourcePostUrl: '', caption: '', status: 'COMPLETED' }, '7907': { postId: 7907, ingestedAt: Date.now(), sourcePostUrl: '', caption: '', status: 'COMPLETED' }, '7906': { postId: 7906, ingestedAt: Date.now(), sourcePostUrl: '', caption: '', status: 'COMPLETED' }, '7905': { postId: 7905, ingestedAt: Date.now(), sourcePostUrl: '', caption: '', status: 'COMPLETED' }, '7904': { postId: 7904, ingestedAt: Date.now(), sourcePostUrl: '', caption: '', status: 'COMPLETED' }, '7903': { postId: 7903, ingestedAt: Date.now(), sourcePostUrl: '', caption: '', status: 'COMPLETED' }, '7902': { postId: 7902, ingestedAt: Date.now(), sourcePostUrl: '', caption: '', status: 'COMPLETED' }, '7901': { postId: 7901, ingestedAt: Date.now(), sourcePostUrl: '', caption: '', status: 'COMPLETED' }, '7900': { postId: 7900, ingestedAt: Date.now(), sourcePostUrl: '', caption: '', status: 'COMPLETED' }, '7898': { postId: 7898, ingestedAt: Date.now(), sourcePostUrl: '', caption: '', status: 'COMPLETED' }, '7897': { postId: 7897, ingestedAt: Date.now(), sourcePostUrl: '', caption: '', status: 'COMPLETED' }, }, };
// Run discovery for 1 candidate (using live web preview fallback if local MTProto offline) const result = await findUnprocessedVideoCandidates('quranbng', 1, state, { durationFilter: { enabled: false, minDurationSec: 50, maxDurationSec: 50, filterType: 'min_duration' }, });
expect(result.candidates.length).toBe(1); const candidate = result.candidates[0];
// The discovered candidate MUST be older than 7897 (e.g. 7892, 7891, 7890, 7888...) expect(candidate.postId).toBeLessThan(7897); expect(candidate.hasVideo).toBe(true);
// Duplicate detection verified: cannot be in processedPostIds expect(state.processedPostIds[candidate.postId.toString()]).toBeUndefined();
// Monotonic cursor progression verified: updated lowest must be <= candidate.postId expect(result.updatedLowestPostId).toBeDefined(); expect(result.updatedLowestPostId!).toBeLessThanOrEqual(candidate.postId); });
it('executes Phase 2 deep historical traversal when all top feed posts are processed', async () => { // Mark ALL posts from 7891 to 7915 as processed so Phase 1 finds nothing const processedMap: any = {}; for (let id = 7891; id <= 7915; id++) { processedMap[id.toString()] = { postId: id, ingestedAt: Date.now(), sourcePostUrl: '', caption: '', status: 'COMPLETED', }; }
const state: TelegramChannelState = { channelSlug: 'quranbng', lastRunTimestamp: Date.now(), lowestEvaluatedPostId: 7891, highestEvaluatedPostId: 7915, totalProcessedCount: Object.keys(processedMap).length, processedPostIds: processedMap, };
const result = await findUnprocessedVideoCandidates('quranbng', 1, state, { durationFilter: { enabled: false, minDurationSec: 50, maxDurationSec: 50, filterType: 'min_duration' }, });
expect(result.candidates.length).toBe(1); const candidate = result.candidates[0];
// Must be found from Phase 2 (historical post < 7891, e.g. 7890, 7889, 7888...) expect(candidate.postId).toBeLessThan(7891); expect(candidate.hasVideo).toBe(true);
// Monotonic cursor progression verified: updated lowest must be <= candidate.postId expect(result.updatedLowestPostId).toBeDefined(); expect(result.updatedLowestPostId!).toBeLessThanOrEqual(candidate.postId); });
it('preserves genuinely processed historical videos and prevents duplicate re-ingestion', async () => { const dummyPost: TelegramScrapedPost = { channelSlug: 'testchannel', postId: 555, postUrl: 'https://t.me/testchannel/555', hasVideo: true, durationSec: 45, caption: 'Duplicate test', };
const state: TelegramChannelState = { channelSlug: 'testchannel', lastRunTimestamp: Date.now(), lowestEvaluatedPostId: 550, totalProcessedCount: 1, processedPostIds: { '555': { postId: 555, ingestedAt: Date.now(), sourcePostUrl: '', caption: '', status: 'COMPLETED' }, }, };
// State already has 555, so it must not be added to candidates expect(state.processedPostIds['555']).toBeDefined(); });});276 unmodified lines277278279280281282276 unmodified lines# Strategy 2: Determine starting top ID and fetch messages concurrentlytop_id = before_post_idif not top_id:candidate_top = 7890coarse_ids = [7890 + i * 5 for i in range(1, 30)]276 unmodified lines277278279280281282283284285286287288289290291292293294295296297276 unmodified lines# Strategy 2: Determine starting top ID and fetch messages concurrentlytop_id = before_post_idif not top_id:try:import urllib.requestimport rereq = urllib.request.Request(f"https://t.me/s/{channel}",headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"})html = urllib.request.urlopen(req, timeout=8).read().decode('utf-8', errors='ignore')found_ids = [int(x) for x in re.findall(rf'data-post="{re.escape(channel)}/(\d+)"', html, re.I)]if found_ids:top_id = max(found_ids) + 1except Exception:passif not top_id:candidate_top = 7890coarse_ids = [7890 + i * 5 for i in range(1, 30)]
quran_automation/src/services/telegramAutomation.service.ts+8-2
quran_automation/src/services/telegramBatchRegistry.service.ts+10-3
quran_automation/src/services/telegramCrawler.service.ts+263-124
quran_automation/tests/telegram_historical_discovery.test.tsAdded+115
video_bot/main_bot.py+15