reikernx commited on
Commit
bb8c78f
·
verified ·
1 Parent(s): b21c9a4

Update server.js

Browse files
Files changed (1) hide show
  1. server.js +37 -64
server.js CHANGED
@@ -16,10 +16,10 @@ app.use(express.json());
16
  // Delay function to replace waitForTimeout
17
  const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
18
 
19
- // Initialize browser and login once on startup
20
  async function initializeBrowser() {
21
  try {
22
- console.log('🚀 Initializing browser and logging in...');
23
 
24
  browser = await puppeteer.launch({
25
  headless: true, // Set to false for debugging
@@ -28,13 +28,33 @@ async function initializeBrowser() {
28
 
29
  loggedInPage = await browser.newPage();
30
 
31
- // Login process
 
 
 
 
 
 
 
 
 
 
 
 
32
  await loggedInPage.goto("https://getsms.cc/auth/login", {
33
  waitUntil: "networkidle2"
34
  });
35
 
 
 
 
 
 
 
 
 
36
  // Replace with your actual credentials
37
- await loggedInPage.type("#email", "reikernx@gmail.com", { delay: 50 });
38
  await loggedInPage.type("#password", "Ogombo12", { delay: 50 });
39
 
40
  await Promise.all([
@@ -42,10 +62,9 @@ async function initializeBrowser() {
42
  loggedInPage.waitForNavigation({ waitUntil: "networkidle2" })
43
  ]);
44
 
45
- console.log("✅ Browser initialized and logged in successfully!");
46
-
47
  } catch (error) {
48
- console.error("❌ Failed to initialize browser:", error);
49
  throw error;
50
  }
51
  }
@@ -64,11 +83,10 @@ app.get('/api/messages', async (req, res) => {
64
 
65
  console.log(`📱 Fetching messages for number: ${number}`);
66
 
67
- // Check if we're still logged in by checking for login indicators
68
- const currentUrl = loggedInPage.url();
69
- console.log(`Current page URL: ${currentUrl}`);
70
 
71
- // Navigate to the specific info page using the same logged-in page
72
  const url = `https://getsms.cc/info/${number}`;
73
  await loggedInPage.goto(url, {
74
  waitUntil: "networkidle2"
@@ -77,66 +95,21 @@ app.get('/api/messages', async (req, res) => {
77
  // Verify we didn't get redirected to login page
78
  const finalUrl = loggedInPage.url();
79
  if (finalUrl.includes('/auth/login')) {
80
- throw new Error('Session expired - redirected to login page');
81
  }
82
 
83
  console.log(`✅ Successfully navigated to: ${finalUrl}`);
84
 
85
- // Wait a moment for any dynamic content to load
86
  await delay(2000);
87
 
88
- // Check if we need to login (session expired)
89
- const needsLogin = await loggedInPage.evaluate(() => {
90
- // Check for "Login to view" text or similar indicators
91
- const bodyText = document.body.textContent || '';
92
- return bodyText.includes('Login to view') ||
93
- bodyText.includes('Please login') ||
94
- bodyText.includes('You need to login') ||
95
- document.querySelector('.login-required') !== null;
96
- });
97
-
98
- if (needsLogin) {
99
- console.log('🔄 Session expired, re-logging in...');
100
-
101
- // Re-login process
102
- await loggedInPage.goto("https://getsms.cc/auth/login", {
103
- waitUntil: "networkidle2"
104
- });
105
-
106
- // Clear any existing form data and re-enter credentials
107
- await loggedInPage.evaluate(() => {
108
- const emailInput = document.querySelector('#email');
109
- const passwordInput = document.querySelector('#password');
110
- if (emailInput) emailInput.value = '';
111
- if (passwordInput) passwordInput.value = '';
112
- });
113
-
114
- await loggedInPage.type("#email", "your@email.com", { delay: 50 });
115
- await loggedInPage.type("#password", "yourpassword", { delay: 50 });
116
-
117
- await Promise.all([
118
- loggedInPage.click("input[type=submit]"),
119
- loggedInPage.waitForNavigation({ waitUntil: "networkidle2" })
120
- ]);
121
-
122
- console.log("✅ Re-logged in successfully!");
123
-
124
- // Navigate back to the number page
125
- await loggedInPage.goto(url, {
126
- waitUntil: "networkidle2"
127
- });
128
-
129
- // Wait for content to load
130
- await delay(2000);
131
- }
132
-
133
- // Extract the last 3 messages
134
  const lastMessages = await loggedInPage.evaluate(() => {
135
  const messageElements = document.querySelectorAll('.direct-chat-msg');
136
 
137
  // Double-check we're not seeing login messages
138
  const bodyText = document.body.textContent || '';
139
- if (bodyText.includes('Login to view')) {
140
  return []; // Return empty array if still showing login message
141
  }
142
 
@@ -158,15 +131,15 @@ app.get('/api/messages', async (req, res) => {
158
  };
159
  }).filter(msg => msg !== null); // Remove null entries (ads)
160
 
161
- // Return last 3 messages
162
- return messages.slice(-3);
163
  });
164
 
165
  // Check if we got empty results due to login requirement
166
  if (lastMessages.length === 0) {
167
  const pageContent = await loggedInPage.evaluate(() => document.body.textContent);
168
  if (pageContent.includes('Login to view')) {
169
- throw new Error('Session expired and re-login failed - still showing "Login to view"');
170
  }
171
  }
172
 
@@ -206,7 +179,7 @@ app.get('/', (req, res) => {
206
  res.json({
207
  message: 'GetSMS Message Extraction API',
208
  endpoints: {
209
- 'GET /api/messages?number={phone_number}': 'Get last 3 messages for a phone number',
210
  'GET /api/health': 'Check API health status',
211
  'GET /': 'This help page'
212
  },
 
16
  // Delay function to replace waitForTimeout
17
  const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
18
 
19
+ // Initialize browser once on startup
20
  async function initializeBrowser() {
21
  try {
22
+ console.log('🚀 Initializing browser...');
23
 
24
  browser = await puppeteer.launch({
25
  headless: true, // Set to false for debugging
 
28
 
29
  loggedInPage = await browser.newPage();
30
 
31
+ console.log("✅ Browser initialized successfully!");
32
+
33
+ } catch (error) {
34
+ console.error("❌ Failed to initialize browser:", error);
35
+ throw error;
36
+ }
37
+ }
38
+
39
+ // Login function to be called for each request
40
+ async function login() {
41
+ try {
42
+ console.log('🔐 Logging in...');
43
+
44
  await loggedInPage.goto("https://getsms.cc/auth/login", {
45
  waitUntil: "networkidle2"
46
  });
47
 
48
+ // Clear any existing form data
49
+ await loggedInPage.evaluate(() => {
50
+ const emailInput = document.querySelector('#email');
51
+ const passwordInput = document.querySelector('#password');
52
+ if (emailInput) emailInput.value = '';
53
+ if (passwordInput) passwordInput.value = '';
54
+ });
55
+
56
  // Replace with your actual credentials
57
+ await loggedInPage.type("#email", "reikernx@email.com", { delay: 50 });
58
  await loggedInPage.type("#password", "Ogombo12", { delay: 50 });
59
 
60
  await Promise.all([
 
62
  loggedInPage.waitForNavigation({ waitUntil: "networkidle2" })
63
  ]);
64
 
65
+ console.log("✅ Logged in successfully!");
 
66
  } catch (error) {
67
+ console.error("❌ Failed to login:", error);
68
  throw error;
69
  }
70
  }
 
83
 
84
  console.log(`📱 Fetching messages for number: ${number}`);
85
 
86
+ // Perform fresh login for each request
87
+ await login();
 
88
 
89
+ // Navigate to the specific info page
90
  const url = `https://getsms.cc/info/${number}`;
91
  await loggedInPage.goto(url, {
92
  waitUntil: "networkidle2"
 
95
  // Verify we didn't get redirected to login page
96
  const finalUrl = loggedInPage.url();
97
  if (finalUrl.includes('/auth/login')) {
98
+ throw new Error('Login failed - redirected to login page');
99
  }
100
 
101
  console.log(`✅ Successfully navigated to: ${finalUrl}`);
102
 
103
+ // Wait for content to load
104
  await delay(2000);
105
 
106
+ // Extract the latest 5 messages
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107
  const lastMessages = await loggedInPage.evaluate(() => {
108
  const messageElements = document.querySelectorAll('.direct-chat-msg');
109
 
110
  // Double-check we're not seeing login messages
111
  const bodyText = document.body.textContent || '';
112
+ if (bodyText.includes('Communication operator requirements you need to register or login to the website before view SMS. We apologize for the inconvenience and thank you for your understanding')) {
113
  return []; // Return empty array if still showing login message
114
  }
115
 
 
131
  };
132
  }).filter(msg => msg !== null); // Remove null entries (ads)
133
 
134
+ // Return latest 5 messages
135
+ return messages.slice(0, 5);
136
  });
137
 
138
  // Check if we got empty results due to login requirement
139
  if (lastMessages.length === 0) {
140
  const pageContent = await loggedInPage.evaluate(() => document.body.textContent);
141
  if (pageContent.includes('Login to view')) {
142
+ throw new Error('Login failed - still showing "Login to view"');
143
  }
144
  }
145
 
 
179
  res.json({
180
  message: 'GetSMS Message Extraction API',
181
  endpoints: {
182
+ 'GET /api/messages?number={phone_number}': 'Get latest 5 messages for a phone number',
183
  'GET /api/health': 'Check API health status',
184
  'GET /': 'This help page'
185
  },