-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
189 lines (172 loc) · 5.31 KB
/
Copy pathserver.js
File metadata and controls
189 lines (172 loc) · 5.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
const express = require("express");
const { Builder, By, until } = require("selenium-webdriver");
const chrome = require("selenium-webdriver/chrome");
const app = express();
const port = 3000;
require('dotenv').config()
app.get("/", (req, res) => {
res.render("index.ejs");
});
// app.get("/", (req, res) => {
// res.send("Welcome to the Twitter automation API!");
// });
app.get("/login", async (req, res) => {
let driver;
let hasResponded = false;
try {
// Initialize driver with Chrome options
driver = await new Builder()
.forBrowser("chrome")
.setChromeOptions(new chrome.Options()
.addArguments("--no-sandbox")
.addArguments("--disable-dev-shm-usage")
.addArguments("--window-size=1920,1080"))
.build();
await driver.manage().setTimeouts({ implicit: 5000 });
await driver.get("https://twitter.com/login");
await driver.wait(until.elementLocated(By.css('body')), 10000);
// Login sequence
const loginSteps = [
{
action: "type",
locator: By.css('input[autocomplete="username"]'),
value: process.env.TWITTER_USERNAME
},
{
action: "click",
locator: By.xpath("//span[text()='Next']")
},
{
action: "conditional",
check: async () => {
try {
const emailInput = await driver.wait(until.elementLocated(By.xpath("//input[@name='text']")), 5000);
await emailInput.sendKeys(process.env.TWITTER_EMAIL);
await driver.findElement(By.xpath("//span[text()='Next']")).click();
return true;
} catch {
return false;
}
}
},
{
action: "type",
locator: By.css('input[type="password"]'),
value: process.env.TWITTER_PASSWORD
},
{
action: "click",
locator: By.xpath("//span[text()='Log in']")
}
];
// Execute login steps
for (const step of loginSteps) {
try {
if (step.action === "type") {
const element = await driver.wait(until.elementLocated(step.locator), 10000);
await driver.wait(until.elementIsEnabled(element), 10000);
await element.clear();
await element.sendKeys(step.value);
} else if (step.action === "click") {
const element = await driver.wait(until.elementLocated(step.locator), 10000);
await driver.wait(until.elementIsEnabled(element), 10000);
await element.click();
} else if (step.action === "conditional") {
await step.check();
}
} catch (error) {
console.log(`Step failed: ${step.action}`, error.message);
if (!step.optional) throw error;
}
}
// Wait for successful login
await driver.wait(until.urlContains("home"), 15000, "Login timeout");
// Find trending section using multiple methods
let trendingElement = null;
const findMethods = [
{
method: "css",
locator: By.css('div[aria-label="Timeline: Trending now"]')
},
{
method: "xpath",
locator: By.xpath('//div[@aria-label="Timeline: Trending now"]')
},
{
method: "javascript",
script: `return document.querySelector('div[aria-label="Timeline: Trending now"]');`
}
];
for (const method of findMethods) {
try {
if (method.method === "javascript") {
trendingElement = await driver.executeScript(method.script);
} else {
trendingElement = await driver.wait(until.elementLocated(method.locator), 10000);
}
if (trendingElement) break;
} catch (error) {
console.log(`${method.method} method failed, trying next...`);
}
}
if (trendingElement) {
const trendingText = await trendingElement.getText();
// Extract hashtags and their post counts
const lines = trendingText.split('\n');
const hashtags = lines
.filter(line => line.startsWith('#'))
.map(hashtag => ({
tag: hashtag,
posts: lines[lines.indexOf(hashtag) + 1]
}));
if (!hasResponded) {
hasResponded = true;
res.render("result.ejs", { hashtags: hashtags });
console.log(hashtags);
}
} else {
if (!hasResponded) {
hasResponded = true;
res.json({
status: "success",
message: "Successfully logged in, but trending timeline not found"
});
}
}
} catch (error) {
console.error("Error during automation:", error);
if (!hasResponded) {
hasResponded = true;
res.status(500).json({
status: "error",
message: error.message,
details: error.stack
});
}
} finally {
if (driver) {
try {
await driver.quit();
} catch (error) {
console.error("Error closing browser:", error);
}
}
}
});
// Error handling middleware
app.use((err, req, res, next) => {
console.error(err.stack);
if (!res.headersSent) {
res.status(500).json({
status: "error",
message: "Internal server error",
details: err.message
});
}
});
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled Rejection at:', promise, 'reason:', reason);
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});