-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
374 lines (310 loc) · 12.9 KB
/
server.js
File metadata and controls
374 lines (310 loc) · 12.9 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
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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
const express = require('express');
const axios = require('axios');
const FormData = require('form-data');
require('dotenv').config();
const app = express();
app.use(express.json({ limit: '50mb' }));
// Add request logging middleware
app.use((req, res, next) => {
console.log(`${new Date().toISOString()} - ${req.method} ${req.path}`);
if (req.method === 'POST') {
const logBody = { ...req.body };
if (logBody.image?.data) {
logBody.image.data = '[BASE64_IMAGE_DATA_TRUNCATED]';
}
if (logBody.facebook_access_token) {
logBody.facebook_access_token = '[ACCESS_TOKEN_HIDDEN]';
}
console.log('Request body:', JSON.stringify(logBody, null, 2));
}
next();
});
app.get('/health', (req, res) => {
console.log('Health check requested');
res.json({ status: 'OK', service: 'Facebook & Threads API Server' });
});
// Facebook endpoint
app.post('/api/facebook/post', async (req, res) => {
console.log('=== Facebook POST request received ===');
try {
const { content, hashtags, pageId, googleDriveFile, facebookEndpoint, usePhotosEndpoint } = req.body;
const userAccessToken = req.headers.authorization?.replace('Bearer ', '');
console.log('Parsed request data:', {
content: content ? `${content.substring(0, 50)}...` : 'MISSING',
hashtags: hashtags,
pageId: pageId,
hasToken: !!userAccessToken,
hasGoogleDriveFile: !!googleDriveFile,
requestedEndpoint: facebookEndpoint || (usePhotosEndpoint ? 'photos' : 'feed')
});
if (!content) {
console.log('ERROR: Content is missing');
return res.status(400).json({ error: 'Content is required' });
}
if (!userAccessToken) {
console.log('ERROR: Access token is missing');
return res.status(400).json({ error: 'Access token is required' });
}
// Use pageId from request if provided, otherwise fall back to environment variable
const targetPageId = pageId || process.env.FACEBOOK_PAGE_ID;
if (!targetPageId) {
console.log('ERROR: Page ID is missing');
return res.status(400).json({ error: 'Page ID is required (either in request or environment)' });
}
console.log('Target page ID:', targetPageId);
// Check if we have a Google Drive file to download and post
if (googleDriveFile && googleDriveFile.id && (facebookEndpoint === 'photos' || usePhotosEndpoint)) {
console.log('Processing image post - uploading photo first, then posting to feed...');
console.log(`Google Drive file: ${googleDriveFile.name} (${googleDriveFile.id})`);
// Download image from Google Drive
let imageBuffer;
try {
console.log(`Downloading image from Google Drive: ${googleDriveFile.id}`);
// Download the image directly from Google Drive using public URL
const downloadUrl = `https://drive.google.com/uc?export=download&id=${googleDriveFile.id}`;
const imageResponse = await axios.get(downloadUrl, {
responseType: 'arraybuffer',
timeout: 30000
});
imageBuffer = Buffer.from(imageResponse.data);
console.log(`Successfully downloaded image: ${imageBuffer.length} bytes`);
if (imageBuffer.length < 100) {
throw new Error(`Downloaded image too small: ${imageBuffer.length} bytes`);
}
} catch (error) {
console.error('Error downloading image from Google Drive:', error);
throw new Error(`Failed to download image from Google Drive: ${error.message}`);
}
// Step 1: Upload the photo to get a photo ID
console.log('Step 1: Uploading photo to Facebook...');
const photoFormData = new FormData();
photoFormData.append('access_token', userAccessToken);
photoFormData.append('published', 'false'); // Don't publish the photo directly
photoFormData.append('source', imageBuffer, {
filename: googleDriveFile.name || 'monkeyzoo_image.jpg',
contentType: googleDriveFile.mimeType || 'image/jpeg'
});
const photoResponse = await axios.post(
`https://graph.facebook.com/v18.0/${targetPageId}/photos`,
photoFormData,
{
headers: {
...photoFormData.getHeaders()
},
maxContentLength: Infinity,
maxBodyLength: Infinity,
timeout: 60000
}
);
console.log('Photo upload SUCCESS:', photoResponse.data);
const photoId = photoResponse.data.id;
// Step 2: Create a feed post with the uploaded photo
console.log('Step 2: Creating feed post with uploaded photo...');
// Prepare post text with hashtags
let postText = content;
if (hashtags && hashtags.length > 0) {
const hashtagText = hashtags.map(tag =>
tag.startsWith('#') ? tag : `#${tag}`
).join(' ');
postText = `${content}\n\n${hashtagText}`;
}
const feedFormData = new URLSearchParams();
feedFormData.append('message', postText);
feedFormData.append('attached_media[0]', `{"media_fbid":"${photoId}"}`);
feedFormData.append('access_token', userAccessToken);
const feedResponse = await axios.post(
`https://graph.facebook.com/v18.0/${targetPageId}/feed`,
feedFormData.toString(),
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
);
console.log('Feed post SUCCESS:', feedResponse.data);
res.json({
success: true,
post_id: feedResponse.data.id,
post_url: `https://facebook.com/${feedResponse.data.id}`,
platform: 'Facebook',
endpoint_used: 'feed_with_photo',
image_uploaded: true,
photo_id: photoId,
image_info: {
filename: googleDriveFile.name,
size: imageBuffer.length,
contentType: googleDriveFile.mimeType
}
});
} else {
console.log('Processing text-only post via /feed endpoint...');
// Prepare post text for text-only post
let postText = content;
if (hashtags && hashtags.length > 0) {
const hashtagText = hashtags.map(tag =>
tag.startsWith('#') ? tag : `#${tag}`
).join(' ');
postText = `${content}\n\n${hashtagText}`;
}
console.log('Final post text length:', postText.length);
// Create URLSearchParams object for proper form encoding
const formData = new URLSearchParams();
formData.append('message', postText);
formData.append('access_token', userAccessToken);
console.log('Form data prepared for /feed endpoint, making Facebook API request...');
// Post to Facebook page using properly form-encoded data
const response = await axios.post(
`https://graph.facebook.com/v18.0/${targetPageId}/feed`,
formData.toString(),
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
);
console.log('Facebook /feed API SUCCESS:', response.data);
res.json({
success: true,
post_id: response.data.id,
post_url: `https://facebook.com/${response.data.id}`,
platform: 'Facebook',
endpoint_used: 'feed',
image_uploaded: false
});
}
} catch (error) {
console.error('=== Facebook API Error ===');
console.error('Error message:', error.message);
console.error('Error response status:', error.response?.status);
console.error('Error response data:', error.response?.data);
console.error('Full error:', error);
res.status(500).json({
error: 'Failed to post to Facebook',
message: error.response?.data?.error?.message || error.message,
facebookError: error.response?.data?.error
});
}
});
// Threads endpoint
app.post('/api/threads/post', async (req, res) => {
console.log('=== Threads POST request received ===');
try {
const { characterName, content, imageFile } = req.body;
// For Threads, we'll use the same Facebook access token since Threads is owned by Meta
// You'll need to pass the access token in the Authorization header
const threadsAccessToken = req.headers.authorization?.replace('Bearer ', '');
console.log('Parsed Threads request data:', {
characterName: characterName,
content: content ? `${content.substring(0, 50)}...` : 'MISSING',
hasImageFile: !!imageFile,
hasToken: !!threadsAccessToken
});
if (!characterName) {
console.log('ERROR: Character name is missing');
return res.status(400).json({ error: 'Character name is required' });
}
if (!content) {
console.log('ERROR: Content is missing');
return res.status(400).json({ error: 'Content is required' });
}
if (!imageFile || !imageFile.id) {
console.log('ERROR: Image file information is missing');
return res.status(400).json({ error: 'Image file information is required' });
}
if (!threadsAccessToken) {
console.log('ERROR: Threads access token is missing');
return res.status(400).json({ error: 'Threads access token is required' });
}
console.log('Starting Threads posting process...');
console.log(`Character: ${characterName}`);
console.log(`Image file: ${imageFile.name} (${imageFile.id})`);
// Download image from Google Drive
let imageBuffer;
try {
console.log(`Downloading image from Google Drive: ${imageFile.id}`);
// Download the image directly from Google Drive using public URL
const downloadUrl = `https://drive.google.com/uc?export=download&id=${imageFile.id}`;
const imageResponse = await axios.get(downloadUrl, {
responseType: 'arraybuffer',
timeout: 30000
});
imageBuffer = Buffer.from(imageResponse.data);
console.log(`Successfully downloaded image: ${imageBuffer.length} bytes`);
if (imageBuffer.length < 100) {
throw new Error(`Downloaded image too small: ${imageBuffer.length} bytes`);
}
} catch (error) {
console.error('Error downloading image from Google Drive:', error);
throw new Error(`Failed to download image from Google Drive: ${error.message}`);
}
// Step 1: Create Threads media container
console.log('Step 1: Creating Threads media container...');
const mediaFormData = new URLSearchParams();
mediaFormData.append('image_url', `https://drive.google.com/uc?export=download&id=${imageFile.id}`);
mediaFormData.append('text', content);
mediaFormData.append('access_token', threadsAccessToken);
// Note: Threads uses a different user ID format - you'll need to get your Threads user ID
// For now, we'll use a placeholder and you'll need to provide your actual Threads user ID
const threadsUserId = process.env.THREADS_USER_ID || 'YOUR_THREADS_USER_ID';
const mediaResponse = await axios.post(
`https://graph.threads.net/v1.0/${threadsUserId}/threads`,
mediaFormData.toString(),
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
timeout: 60000
}
);
console.log('Threads media container SUCCESS:', mediaResponse.data);
const mediaContainerId = mediaResponse.data.id;
// Step 2: Publish the Threads media container
console.log('Step 2: Publishing Threads media container...');
const publishFormData = new URLSearchParams();
publishFormData.append('creation_id', mediaContainerId);
publishFormData.append('access_token', threadsAccessToken);
const publishResponse = await axios.post(
`https://graph.threads.net/v1.0/${threadsUserId}/threads_publish`,
publishFormData.toString(),
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
timeout: 30000
}
);
console.log('Threads publish SUCCESS:', publishResponse.data);
res.json({
success: true,
post_id: publishResponse.data.id,
post_url: `https://threads.net/@${characterName.toLowerCase()}/post/${publishResponse.data.id}`,
platform: 'Threads',
endpoint_used: 'threads_publish',
image_uploaded: true,
media_container_id: mediaContainerId,
threads_user_id: threadsUserId,
character_name: characterName,
content: content,
image_info: {
filename: imageFile.name,
google_drive_id: imageFile.id,
size: imageBuffer.length
}
});
} catch (error) {
console.error('=== Threads API Error ===');
console.error('Error message:', error.message);
console.error('Error response status:', error.response?.status);
console.error('Error response data:', error.response?.data);
console.error('Full error:', error);
res.status(500).json({
error: 'Failed to post to Threads',
message: error.response?.data?.error?.message || error.message,
threadsError: error.response?.data?.error
});
}
});
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`Facebook & Threads API Server running on port ${PORT}`);
});