reikernx commited on
Commit
1ad9ebc
Β·
verified Β·
1 Parent(s): 0ad926b

Update server.js

Browse files
Files changed (1) hide show
  1. server.js +45 -21
server.js CHANGED
@@ -8,7 +8,6 @@ const PORT = process.env.PORT || 7860;
8
 
9
  // Store browser instance to reuse
10
  let browser = null;
11
- let loggedInPage = null;
12
 
13
  // Middleware
14
  app.use(express.json());
@@ -26,8 +25,6 @@ async function initializeBrowser() {
26
  args: ["--no-sandbox", "--disable-setuid-sandbox"]
27
  });
28
 
29
- loggedInPage = await browser.newPage();
30
-
31
  console.log("βœ… Browser initialized successfully!");
32
 
33
  } catch (error) {
@@ -36,17 +33,29 @@ async function initializeBrowser() {
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 = '';
@@ -54,14 +63,20 @@ async function login() {
54
  });
55
 
56
  // Replace with your actual credentials
57
- await loggedInPage.type("#email", "reikernx@gmail.com", { delay: 50 });
58
- await loggedInPage.type("#password", "Ogombo12", { delay: 50 });
59
 
60
  await Promise.all([
61
- loggedInPage.click("input[type=submit]"),
62
- loggedInPage.waitForNavigation({ waitUntil: "networkidle2" })
63
  ]);
64
 
 
 
 
 
 
 
65
  console.log("βœ… Logged in successfully!");
66
  } catch (error) {
67
  console.error("❌ Failed to login:", error);
@@ -71,6 +86,7 @@ async function login() {
71
 
72
  // API endpoint to get messages for a phone number
73
  app.get('/api/messages', async (req, res) => {
 
74
  try {
75
  const { number } = req.query;
76
 
@@ -83,19 +99,22 @@ app.get('/api/messages', async (req, res) => {
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"
93
  });
94
 
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}`);
@@ -104,12 +123,12 @@ app.get('/api/messages', async (req, res) => {
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
 
@@ -137,9 +156,9 @@ app.get('/api/messages', async (req, res) => {
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
 
@@ -161,6 +180,11 @@ app.get('/api/messages', async (req, res) => {
161
  error: 'Failed to fetch messages',
162
  message: error.message
163
  });
 
 
 
 
 
164
  }
165
  });
166
 
 
8
 
9
  // Store browser instance to reuse
10
  let browser = null;
 
11
 
12
  // Middleware
13
  app.use(express.json());
 
25
  args: ["--no-sandbox", "--disable-setuid-sandbox"]
26
  });
27
 
 
 
28
  console.log("βœ… Browser initialized successfully!");
29
 
30
  } catch (error) {
 
33
  }
34
  }
35
 
36
+ // Login function for a given page
37
+ async function login(page) {
38
  try {
39
+ console.log('πŸ” Checking login status...');
40
 
41
+ await page.goto("https://getsms.cc/auth/login", {
42
  waitUntil: "networkidle2"
43
  });
44
 
45
+ // Check if we're already logged in by looking for the #email field
46
+ const isLoginPage = await page.evaluate(() => {
47
+ return !!document.querySelector('#email');
48
+ });
49
+
50
+ if (!isLoginPage) {
51
+ console.log('βœ… Already logged in, skipping login process.');
52
+ return;
53
+ }
54
+
55
+ console.log('πŸ” Performing login...');
56
+
57
  // Clear any existing form data
58
+ await page.evaluate(() => {
59
  const emailInput = document.querySelector('#email');
60
  const passwordInput = document.querySelector('#password');
61
  if (emailInput) emailInput.value = '';
 
63
  });
64
 
65
  // Replace with your actual credentials
66
+ await page.type("#email", "reikernx@gmail.com", { delay: 50 });
67
+ await page.type("#password", "Ogombo12", { delay: 50 });
68
 
69
  await Promise.all([
70
+ page.click("input[type=submit]"),
71
+ page.waitForNavigation({ waitUntil: "networkidle2" })
72
  ]);
73
 
74
+ // Verify login success
75
+ const finalUrl = page.url();
76
+ if (finalUrl.includes('/auth/login')) {
77
+ throw new Error('Login failed - still on login page');
78
+ }
79
+
80
  console.log("βœ… Logged in successfully!");
81
  } catch (error) {
82
  console.error("❌ Failed to login:", error);
 
86
 
87
  // API endpoint to get messages for a phone number
88
  app.get('/api/messages', async (req, res) => {
89
+ let page = null;
90
  try {
91
  const { number } = req.query;
92
 
 
99
 
100
  console.log(`πŸ“± Fetching messages for number: ${number}`);
101
 
102
+ // Create a new page for each request
103
+ page = await browser.newPage();
104
+
105
+ // Perform login or skip if already logged in
106
+ await login(page);
107
 
108
  // Navigate to the specific info page
109
  const url = `https://getsms.cc/info/${number}`;
110
+ await page.goto(url, {
111
  waitUntil: "networkidle2"
112
  });
113
 
114
  // Verify we didn't get redirected to login page
115
+ const finalUrl = page.url();
116
  if (finalUrl.includes('/auth/login')) {
117
+ throw new Error('Session invalid - redirected to login page');
118
  }
119
 
120
  console.log(`βœ… Successfully navigated to: ${finalUrl}`);
 
123
  await delay(2000);
124
 
125
  // Extract the latest 5 messages
126
+ const lastMessages = await page.evaluate(() => {
127
  const messageElements = document.querySelectorAll('.direct-chat-msg');
128
 
129
  // Double-check we're not seeing login messages
130
  const bodyText = document.body.textContent || '';
131
+ if (bodyText.includes('Login to view')) {
132
  return []; // Return empty array if still showing login message
133
  }
134
 
 
156
 
157
  // Check if we got empty results due to login requirement
158
  if (lastMessages.length === 0) {
159
+ const pageContent = await page.evaluate(() => document.body.textContent);
160
  if (pageContent.includes('Login to view')) {
161
+ throw new Error('Session invalid - still showing "Login to view"');
162
  }
163
  }
164
 
 
180
  error: 'Failed to fetch messages',
181
  message: error.message
182
  });
183
+ } finally {
184
+ // Close the page to avoid memory leaks
185
+ if (page) {
186
+ await page.close();
187
+ }
188
  }
189
  });
190