| const express = require('express'); |
| const puppeteer = require('puppeteer-extra'); |
| const StealthPlugin = require('puppeteer-extra-plugin-stealth'); |
| puppeteer.use(StealthPlugin()); |
|
|
| const app = express(); |
| const PORT = process.env.PORT || 7860; |
|
|
| |
| let browser = null; |
|
|
| |
| app.use(express.json()); |
|
|
| |
| const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms)); |
|
|
| |
| async function initializeBrowser() { |
| try { |
| console.log('🚀 Initializing browser...'); |
| |
| browser = await puppeteer.launch({ |
| headless: true, |
| args: ["--no-sandbox", "--disable-setuid-sandbox"] |
| }); |
|
|
| console.log("✅ Browser initialized successfully!"); |
| |
| } catch (error) { |
| console.error("❌ Failed to initialize browser:", error); |
| throw error; |
| } |
| } |
|
|
| |
| async function login(page) { |
| try { |
| console.log('🔐 Checking login status...'); |
| |
| await page.goto("https://getsms.cc/auth/login", { |
| waitUntil: "networkidle2" |
| }); |
|
|
| |
| const isLoginPage = await page.evaluate(() => { |
| return !!document.querySelector('#email'); |
| }); |
|
|
| if (!isLoginPage) { |
| console.log('✅ Already logged in, skipping login process.'); |
| return; |
| } |
|
|
| console.log('🔐 Performing login...'); |
|
|
| |
| await page.evaluate(() => { |
| const emailInput = document.querySelector('#email'); |
| const passwordInput = document.querySelector('#password'); |
| if (emailInput) emailInput.value = ''; |
| if (passwordInput) passwordInput.value = ''; |
| }); |
|
|
| |
| await page.type("#email", "reikernx@gmail.com", { delay: 50 }); |
| await page.type("#password", "Ogombo12", { delay: 50 }); |
|
|
| await Promise.all([ |
| page.click("input[type=submit]"), |
| page.waitForNavigation({ waitUntil: "networkidle2" }) |
| ]); |
|
|
| |
| const finalUrl = page.url(); |
| if (finalUrl.includes('/auth/login')) { |
| throw new Error('Login failed - still on login page'); |
| } |
|
|
| console.log("✅ Logged in successfully!"); |
| } catch (error) { |
| console.error("❌ Failed to login:", error); |
| throw error; |
| } |
| } |
|
|
| |
| app.get('/api/messages', async (req, res) => { |
| let page = null; |
| try { |
| const { number } = req.query; |
| |
| if (!number) { |
| return res.status(400).json({ |
| error: 'Phone number is required', |
| message: 'Please provide a phone number in the query parameter: ?number=447414848795' |
| }); |
| } |
|
|
| console.log(`📱 Fetching messages for number: ${number}`); |
|
|
| |
| page = await browser.newPage(); |
|
|
| |
| await login(page); |
|
|
| |
| const url = `https://getsms.cc/info/${number}`; |
| await page.goto(url, { |
| waitUntil: "networkidle2" |
| }); |
|
|
| |
| const finalUrl = page.url(); |
| if (finalUrl.includes('/auth/login')) { |
| throw new Error('Session invalid - redirected to login page'); |
| } |
|
|
| console.log(`✅ Successfully navigated to: ${finalUrl}`); |
|
|
| |
| await delay(2000); |
|
|
| |
| const lastMessages = await page.evaluate(() => { |
| const messageElements = document.querySelectorAll('.direct-chat-msg'); |
| |
| |
| const bodyText = document.body.textContent || ''; |
| if (bodyText.includes('Login to view')) { |
| return []; |
| } |
| |
| const messages = Array.from(messageElements).map(msg => { |
| const nameElement = msg.querySelector('.direct-chat-name'); |
| const timeElement = msg.querySelector('.direct-chat-timestamp'); |
| const textElement = msg.querySelector('.direct-chat-text'); |
| |
| |
| const text = textElement?.textContent?.trim() || ''; |
| if (text.includes('adsbygoogle') || text === '' || text.includes('Login to view')) { |
| return null; |
| } |
| |
| return { |
| sender: nameElement?.textContent?.trim() || 'Unknown', |
| time: timeElement?.textContent?.trim() || 'Unknown time', |
| message: text |
| }; |
| }).filter(msg => msg !== null); |
| |
| |
| return messages.slice(0, 5); |
| }); |
|
|
| |
| if (lastMessages.length === 0) { |
| const pageContent = await page.evaluate(() => document.body.textContent); |
| if (pageContent.includes('Login to view')) { |
| throw new Error('Session invalid - still showing "Login to view"'); |
| } |
| } |
|
|
| console.log(`✅ Found ${lastMessages.length} messages for ${number}`); |
|
|
| |
| res.json({ |
| success: true, |
| number: number, |
| timestamp: new Date().toISOString(), |
| messageCount: lastMessages.length, |
| messages: lastMessages |
| }); |
|
|
| } catch (error) { |
| console.error(`❌ Error fetching messages for ${req.query.number}:`, error); |
| res.status(500).json({ |
| success: false, |
| error: 'Failed to fetch messages', |
| message: error.message |
| }); |
| } finally { |
| |
| if (page) { |
| await page.close(); |
| } |
| } |
| }); |
|
|
| |
| app.get('/api/health', (req, res) => { |
| res.json({ |
| status: 'OK', |
| message: 'GetSMS API is running', |
| timestamp: new Date().toISOString(), |
| browserStatus: browser ? 'Connected' : 'Disconnected' |
| }); |
| }); |
|
|
| |
| app.get('/', (req, res) => { |
| res.json({ |
| message: 'GetSMS Message Extraction API', |
| endpoints: { |
| 'GET /api/messages?number={phone_number}': 'Get latest 5 messages for a phone number', |
| 'GET /api/health': 'Check API health status', |
| 'GET /': 'This help page' |
| }, |
| example: { |
| url: '/api/messages?number=447414848795', |
| description: 'Get messages for phone number 447414848795' |
| } |
| }); |
| }); |
|
|
| |
| process.on('SIGINT', async () => { |
| console.log('\n🔄 Shutting down gracefully...'); |
| if (browser) { |
| await browser.close(); |
| } |
| process.exit(0); |
| }); |
|
|
| process.on('SIGTERM', async () => { |
| console.log('\n🔄 Shutting down gracefully...'); |
| if (browser) { |
| await browser.close(); |
| } |
| process.exit(0); |
| }); |
|
|
| |
| async function startServer() { |
| try { |
| await initializeBrowser(); |
| |
| app.listen(PORT, () => { |
| console.log(`\n🌟 GetSMS API Server running on port ${PORT}`); |
| console.log(`📋 Available endpoints:`); |
| console.log(` GET http://localhost:${PORT}/api/messages?number=447414848795`); |
| console.log(` GET http://localhost:${PORT}/api/health`); |
| console.log(` GET http://localhost:${PORT}/`); |
| }); |
| } catch (error) { |
| console.error('❌ Failed to start server:', error); |
| process.exit(1); |
| } |
| } |
|
|
| |
| startServer(); |