-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
253 lines (206 loc) · 7.51 KB
/
index.js
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
const axios = require('axios');
const { getDashboardData, getGoogleImages, getBaiduImages, getDetectedLanguage, getSearchImages, getSearchesByTerm, getSearchesFilter, getTranslation, postVote, saveImages, getSearchVoteCounts } = require('./server/fetch');
const postmark = require('postmark');
const serverConfig = require('./server/config');
const app = express();
app.use(bodyParser.json());
app.use((err, req, res, next) => {
console.error(err.stack)
res.status(500).send('Something broke!')
})
app.use(express.static(path.join(__dirname, "build")));
app.get('/dashboardData', async (req, res) => {
console.log('Received dashboardData request');
const data = await getDashboardData();
console.log('dashboardData:', data);
res.json(data);
});
app.get('/proxy-image', async (req, res) => {
console.log('Received proxy-image request:', req.query);
try {
const imageUrl = req.query.url;
if (!imageUrl || imageUrl === 'undefined' || imageUrl === 'null') {
console.error('No valid image URL provided');
return res.sendFile(path.join(__dirname, 'src/assets/icons/broken-image-placeholder.svg'));
}
// Basic URL validation
try {
new URL(imageUrl);
} catch (e) {
console.error('Invalid URL format:', imageUrl);
return res.sendFile(path.join(__dirname, 'src/assets/icons/broken-image-placeholder.svg'));
}
console.log('Fetching image from:', imageUrl);
const response = await axios({
url: imageUrl,
method: 'GET',
responseType: 'stream',
timeout: 10000, // 10 second timeout
headers: {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36'
}
});
// Validate content type is an image
const contentType = response.headers['content-type'];
if (!contentType || !contentType.startsWith('image/')) {
console.error('Invalid content type:', contentType);
return res.sendFile(path.join(__dirname, 'src/assets/icons/broken-image-placeholder.svg'));
}
console.log('Image fetch successful, content-type:', contentType);
// Set appropriate headers
res.set({
'Content-Type': contentType,
'Cache-Control': 'public, max-age=31536000',
'Access-Control-Allow-Origin': '*'
});
// Pipe the image stream to the response
response.data.pipe(res);
// Handle errors in the pipeline
response.data.on('error', (error) => {
console.error('Error in image stream:', error);
if (!res.headersSent) {
res.sendFile(path.join(__dirname, 'src/assets/icons/broken-image-placeholder.svg'));
}
});
} catch (error) {
console.error('Error proxying image:', error.message);
console.error('Error details:', error);
if (!res.headersSent) {
res.sendFile(path.join(__dirname, 'src/assets/icons/broken-image-placeholder.svg'));
}
}
});
app.get("*", (req, res) => {
res.sendFile(path.join(__dirname, "public/index.html"));
});
app.post("/searches/:search_id/images", async (req, res) => {
console.log('/searches/:search_id/images:', req.params);
console.log("trying to get images for search id", req.params.search_id);
const { search_id } = req.params;
const data = await getSearchImages(search_id);
res.json(data);
});
app.post('/images', async (req, res) => {
const data = {};
let langTo;
const { query, search_client_name } = req.body;
console.log('query', query)
try {
if (!query || query.trim() === '') {
throw new Error('Search query is required');
}
const { language: langFrom } = await getDetectedLanguage(encodeURIComponent(query));
console.log('langFrom', langFrom);
langTo = langFrom === 'en' ? 'zh-CN' : 'en';
const translatedQuery = await getTranslation(encodeURIComponent(query), langFrom, langTo);
const enQuery = langFrom === 'en' ? query : translatedQuery;
const cnQuery = langFrom !== 'en' ? translatedQuery : query;
const results = await Promise.all([
getGoogleImages(enQuery),
getBaiduImages(cnQuery),
]);
const { searchId } = await saveImages({
query,
google: results[0].slice(0, 9),
baidu: results[1].slice(0, 9),
langTo,
langFrom,
search_client_name,
translation: translatedQuery
});
data.searchId = searchId;
data.googleResults = results[0];
data.baiduResults = results[1];
data.translation = translatedQuery;
} catch (error) {
console.error('Error processing image search:', error);
return res.status(400).json({
error: error.message || 'Failed to process search request',
details: error.toString()
});
}
res.json(data);
});
app.post('/searches', async (req, res) => {
try {
console.log('/searches query params:', req.query);
const { query, page, page_size, ...otherFilters } = req.query;
if (req.query.cities) {
otherFilters.search_locations = req.query.cities;
}
// Ensure pagination parameters are numbers
const paginationParams = {
page: parseInt(page) || 1,
page_size: parseInt(page_size) || 25
};
let data;
if (query) {
console.log('Processing search by term:', query);
const decodedQuery = decodeURIComponent(query);
data = await getSearchesByTerm(decodedQuery, paginationParams);
} else {
console.log('Processing filter options:', { ...otherFilters, ...paginationParams });
data = await getSearchesFilter({ ...otherFilters, ...paginationParams });
}
console.log('Search results:', data.data.length);
res.json(data);
} catch (error) {
console.error('Error in /searches endpoint:', error);
console.error('Error stack:', error.stack);
res.status(400).json({
error: error.message || 'Failed to process search request',
details: error.toString(),
stack: error.stack
});
}
});
app.post('/vote', async (req, res) => {
console.log('/vote:', req.body);
try {
req.body.vote_ip_address = req.headers['x-forwarded-for'] || req.socket.remoteAddress;
const data = await postVote({ ...req.body });
res.json(data);
} catch (e) {
console.error(e);
}
});
app.post('/searches/votes/counts/:search_id', async (req, res) => {
try {
console.log('Getting vote counts for search:', req.params.search_id);
const data = await getSearchVoteCounts(req.params.search_id);
res.json(data);
} catch (error) {
console.error('Error getting vote counts:', error);
res.status(500).json({
error: error.message || 'Failed to get vote counts'
});
}
});
app.post('/send-email', async (req, res) => {
console.log('/send-email: trying!', req.body);
const { to, subject, text } = req.body;
const client = new postmark.ServerClient(serverConfig.postmarkApiKey);
try {
await client.sendEmail({
From: 'info@firewallcafe.com',
To: to,
Subject: subject,
TextBody: text
});
console.log('Email sent successfully:', { to, subject, text });
res.status(200).json({ message: 'Email sent successfully' });
} catch (error) {
console.error('Error sending email:', error);
res.status(500).json({ error: 'Failed to send email' });
}
});
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`Server listening at http://localhost:${PORT}`);
console.log(`Environment: ${process.env.NODE_ENV}`);
console.log(`Using API URL: ${serverConfig.apiUrl}`);
})
module.exports = app;