Files

1030 lines
33 KiB
TypeScript
Raw Permalink Normal View History

2026-11-02 14:37:14 +06:00
import express from 'express';
import dotenv from 'dotenv';
import path from 'path';
import { fileURLToPath } from 'url';
import fs from 'fs';
import axios from 'axios';
import FormData from 'form-data';
import multer from 'multer';
dotenv.config();
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const app = express();
const PORT = Number(process.env.PORT) || 3000;
// Configure Multer for video file uploads (in-memory storage)
const storage = multer.memoryStorage();
const upload = multer({
storage,
limits: { fileSize: 100 * 1024 * 1024 } // 100 MB max for direct web uploads
});
const DEFAULT_PAGE_ID = process.env.FB_PAGE_ID || '646500888556200';
const DEFAULT_PAGE_TOKEN = process.env.FB_PAGE_ACCESS_TOKEN || 'EAAgcq0hZAwNcBSvNPUgTvPWCJ4mRSjmN05PbcBvjTW3q2HfPnZCMZBozdBmBqZAoJ1hA7U5b1Rf8Gi0DolYOTuAHKZAALZCgkb2bYqxuZBugqNaQcGqDDZA8gvhLVZARVoQK9kgikHJiudQy4YpZBUMhP23CLWhJj3HoFZAS8GO7nChZBiLS081AZAlilZCGRdcactqn0JnMird5KdO2009Dq5pg2m';
// Middleware
app.use(express.json({ limit: '50mb' }));
app.use(express.urlencoded({ extended: true, limit: '50mb' }));
// CORS headers
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
if (req.method === 'OPTIONS') {
return res.sendStatus(200);
}
next();
});
// ============================================================================
// REAL SOCIAL MEDIA API ROUTES
// ============================================================================
/**
* Fetch Live Real Facebook Page Info (Talnodi - 646500888556200)
*/
app.get('/api/social/real-page', async (req, res) => {
const pageId = (req.query.pageId as string) || DEFAULT_PAGE_ID;
const token = (req.query.accessToken as string) || DEFAULT_PAGE_TOKEN;
try {
const pageUrl = `https://graph.facebook.com/v21.0/${pageId}`;
const pageResp = await axios.get(pageUrl, {
params: {
fields: 'id,name,fan_count,followers_count,picture{url},about,link,is_published,category',
access_token: token
},
timeout: 10000
});
const pageData = pageResp.data;
return res.json({
success: true,
verified: true,
platform: 'facebook',
page: {
id: pageData.id,
name: pageData.name, // "তালনদী"
fanCount: pageData.fan_count || pageData.followers_count || 0,
followersCount: pageData.followers_count || pageData.fan_count || 0,
pictureUrl: pageData.picture?.data?.url || null,
category: pageData.category || 'Musician/band',
about: pageData.about || '',
link: pageData.link || `https://www.facebook.com/${pageData.id}`,
isPublished: pageData.is_published ?? true
}
});
} catch (err: any) {
const metaError = err.response?.data?.error;
console.error('Meta Facebook Graph API Error:', metaError || err.message);
return res.status(err.response?.status || 500).json({
success: false,
error: metaError?.message || err.message || 'Failed to fetch Facebook Page from Meta Graph API'
});
}
});
/**
* Fetch Live Real Facebook Posts (Published posts from Talnodi)
*/
app.get('/api/social/real-posts', async (req, res) => {
const pageId = (req.query.pageId as string) || DEFAULT_PAGE_ID;
const token = (req.query.accessToken as string) || DEFAULT_PAGE_TOKEN;
try {
const url = `https://graph.facebook.com/v21.0/${pageId}/posts`;
const resp = await axios.get(url, {
params: {
fields: 'id,message,created_time,permalink_url,attachments{media,type,url,title}',
access_token: token,
limit: 15
},
timeout: 12000
});
const posts = (resp.data?.data || []).map((p: any) => {
const attach = p.attachments?.data?.[0];
const imgUrl = attach?.media?.image?.src || null;
return {
id: p.id,
message: p.message || attach?.title || 'তালনদী - Facebook Post',
createdTime: p.created_time,
permalinkUrl: p.permalink_url || `https://www.facebook.com/${p.id}`,
imageUrl: imgUrl,
type: attach?.type || 'post'
};
});
return res.json({
success: true,
posts
});
} catch (err: any) {
const metaError = err.response?.data?.error;
console.error('Meta Facebook Graph API Error:', metaError || err.message);
return res.status(err.response?.status || 500).json({
success: false,
error: metaError?.message || err.message
});
}
});
/**
* List All Managed Facebook Pages for a User / Token
*/
app.get('/api/social/list-managed-pages', async (req, res) => {
const token = (req.query.accessToken as string) || DEFAULT_PAGE_TOKEN;
try {
const url = 'https://graph.facebook.com/v21.0/me/accounts';
const resp = await axios.get(url, {
params: {
fields: 'id,name,access_token,category,picture{url},fan_count,followers_count,link',
access_token: token,
limit: 25
},
timeout: 10000
});
const pages = (resp.data?.data || []).map((p: any) => ({
id: p.id,
name: p.name,
accessToken: p.access_token || token,
category: p.category || 'Page',
pictureUrl: p.picture?.data?.url || null,
followersCount: p.followers_count || p.fan_count || 0,
fanCount: p.fan_count || p.followers_count || 0,
link: p.link || `https://facebook.com/${p.id}`
}));
return res.json({
success: true,
pages
});
} catch (err: any) {
const metaError = err.response?.data?.error;
console.warn('Meta Accounts Discovery Notice:', metaError?.message || err.message);
return res.status(err.response?.status || 500).json({
success: false,
error: metaError?.message || err.message || 'Failed to list managed pages'
});
}
});
/**
* Verify Real Facebook Account
* Calls Meta Graph API with real Page ID and Page Access Token
*/
app.post('/api/social/verify-facebook', async (req, res) => {
const pageId = req.body.pageId || DEFAULT_PAGE_ID;
const accessToken = req.body.accessToken || DEFAULT_PAGE_TOKEN;
const apiVersion = req.body.apiVersion || 'v21.0';
try {
// 1. Fetch Page Details directly from Meta Graph API
const pageUrl = `https://graph.facebook.com/${apiVersion}/${pageId}`;
const pageResp = await axios.get(pageUrl, {
params: {
fields: 'id,name,fan_count,followers_count,picture{url},about,link,is_published,category',
access_token: accessToken
},
timeout: 10000
});
const pageData = pageResp.data;
// 2. Also check if there is an Instagram Business Account connected to this Page
let igAccount = null;
try {
const igResp = await axios.get(pageUrl, {
params: {
fields: 'instagram_business_account{id,username,name,profile_picture_url,followers_count}',
access_token: accessToken
},
timeout: 8000
});
if (igResp.data && igResp.data.instagram_business_account) {
igAccount = igResp.data.instagram_business_account;
}
} catch {
// Instagram connected query is optional
}
return res.json({
success: true,
verified: true,
platform: 'facebook',
page: {
id: pageData.id,
name: pageData.name,
fanCount: pageData.fan_count || pageData.followers_count || 0,
followersCount: pageData.followers_count || pageData.fan_count || 0,
pictureUrl: pageData.picture?.data?.url || null,
category: pageData.category || 'Organization',
link: pageData.link || `https://facebook.com/${pageData.id}`,
isPublished: pageData.is_published ?? true
},
connectedInstagram: igAccount
});
} catch (err: any) {
const metaError = err.response?.data?.error;
console.error('Meta Facebook Graph API Error:', metaError || err.message);
return res.status(err.response?.status || 500).json({
success: false,
verified: false,
platform: 'facebook',
error: metaError?.message || err.message || 'Failed to verify Facebook Page with Meta API',
code: metaError?.code,
subcode: metaError?.error_subcode,
type: metaError?.type,
hint: metaError?.code === 190
? 'Your Facebook Page Access Token has expired or is invalid. Please generate a fresh token from Meta Graph API Explorer.'
: 'Please ensure your token has the "pages_manage_posts" and "publish_video" permissions.'
});
}
});
/**
* Verify Real Instagram Business / Creator Account
*/
app.post('/api/social/verify-instagram', async (req, res) => {
const { igUserId, accessToken, apiVersion = 'v21.0' } = req.body;
if (!igUserId || !accessToken) {
return res.status(400).json({
success: false,
error: 'Missing igUserId or accessToken'
});
}
try {
const url = `https://graph.facebook.com/${apiVersion}/${igUserId}`;
const resp = await axios.get(url, {
params: {
fields: 'id,username,name,profile_picture_url,followers_count,media_count',
access_token: accessToken
},
timeout: 10000
});
return res.json({
success: true,
verified: true,
platform: 'instagram',
account: {
id: resp.data.id,
username: resp.data.username,
name: resp.data.name || resp.data.username,
pictureUrl: resp.data.profile_picture_url,
followersCount: resp.data.followers_count || 0,
mediaCount: resp.data.media_count || 0
}
});
} catch (err: any) {
const metaError = err.response?.data?.error;
console.error('Instagram Graph API Error:', metaError || err.message);
return res.status(err.response?.status || 500).json({
success: false,
verified: false,
platform: 'instagram',
error: metaError?.message || err.message || 'Failed to verify Instagram Account with Meta Graph API',
code: metaError?.code
});
}
});
/**
* Verify Real TikTok Account
*/
app.post('/api/social/verify-tiktok', async (req, res) => {
const { accessToken } = req.body;
if (!accessToken) {
return res.status(400).json({ success: false, error: 'Missing TikTok accessToken' });
}
try {
const url = 'https://open.tiktokapis.com/v2/user/info/';
const resp = await axios.get(url, {
params: { fields: 'open_id,union_id,avatar_url,display_name,bio_description' },
headers: { Authorization: `Bearer ${accessToken}` },
timeout: 10000
});
if (resp.data?.error?.code && resp.data.error.code !== 'ok') {
throw new Error(resp.data.error.message || 'TikTok API returned an error');
}
const user = resp.data.data?.user;
return res.json({
success: true,
verified: true,
platform: 'tiktok',
account: {
id: user?.open_id || 'tiktok_creator',
name: user?.display_name || 'TikTok Creator',
pictureUrl: user?.avatar_url,
followersCount: 0
}
});
} catch (err: any) {
return res.status(400).json({
success: false,
verified: false,
platform: 'tiktok',
error: err.response?.data?.error?.message || err.message || 'Failed to verify TikTok access token'
});
}
});
/**
* Verify Real LinkedIn Account
*/
app.post('/api/social/verify-linkedin', async (req, res) => {
const { accessToken, authorUrn } = req.body;
if (!accessToken) {
return res.status(400).json({ success: false, error: 'Missing LinkedIn accessToken' });
}
try {
const url = 'https://api.linkedin.com/v2/userinfo';
const resp = await axios.get(url, {
headers: { Authorization: `Bearer ${accessToken}` },
timeout: 10000
});
return res.json({
success: true,
verified: true,
platform: 'linkedin',
account: {
id: authorUrn || `urn:li:person:${resp.data.sub}`,
name: resp.data.name || `${resp.data.given_name} ${resp.data.family_name}`,
pictureUrl: resp.data.picture,
email: resp.data.email
}
});
} catch (err: any) {
return res.status(400).json({
success: false,
verified: false,
platform: 'linkedin',
error: err.response?.data?.message || err.message || 'Failed to verify LinkedIn Bearer token'
});
}
});
/**
* Verify Real YouTube Channel
* Queries Google YouTube Data API v3 channels endpoint
*/
app.post('/api/social/verify-youtube', async (req, res) => {
const { accessToken, channelId } = req.body;
if (!accessToken) {
return res.status(400).json({ success: false, error: 'Missing YouTube / Google OAuth accessToken' });
}
try {
const url = 'https://www.googleapis.com/youtube/v3/channels';
const params: Record<string, any> = {
part: 'snippet,statistics,brandingSettings'
};
if (channelId && channelId.startsWith('UC')) {
params.id = channelId;
} else {
params.mine = true;
}
const resp = await axios.get(url, {
params,
headers: {
Authorization: `Bearer ${accessToken}`,
Accept: 'application/json'
},
timeout: 10000
});
const items = resp.data?.items;
if (!items || items.length === 0) {
throw new Error('No YouTube channel found for the provided access token.');
}
const ch = items[0];
const snippet = ch.snippet || {};
const stats = ch.statistics || {};
return res.json({
success: true,
verified: true,
platform: 'youtube',
channel: {
id: ch.id,
title: snippet.title || 'YouTube Channel',
customUrl: snippet.customUrl || `@${snippet.title}`,
pictureUrl: snippet.thumbnails?.high?.url || snippet.thumbnails?.default?.url,
subscriberCount: stats.subscriberCount ? `${Number(stats.subscriberCount).toLocaleString()} Subscribers` : 'Channel Active',
videoCount: stats.videoCount || 0,
viewCount: stats.viewCount || 0,
link: snippet.customUrl ? `https://youtube.com/${snippet.customUrl}` : `https://youtube.com/channel/${ch.id}`
}
});
} catch (err: any) {
const gError = err.response?.data?.error;
console.error('YouTube API Error:', gError || err.message);
return res.status(err.response?.status || 400).json({
success: false,
verified: false,
platform: 'youtube',
error: gError?.message || err.message || 'Failed to verify YouTube Channel with Google API'
});
}
});
/**
* Helper to Publish to a Single Facebook Page
*/
async function publishToSingleFbPage(params: {
pageId: string;
accessToken: string;
pageName?: string;
publishType: string;
caption: string;
mediaBuffer: Buffer | null;
mediaFileName: string;
mediaMimeType: string;
samplePhotoUrl?: string;
}) {
const { pageId, accessToken, pageName, publishType, caption, mediaBuffer, mediaFileName, mediaMimeType, samplePhotoUrl } = params;
try {
console.log(`🚀 Publishing [${publishType.toUpperCase()}] to Facebook Page "${pageName || pageId}" (${pageId})...`);
if (publishType === 'status') {
const fbUrl = `https://graph.facebook.com/v21.0/${pageId}/feed`;
const fbResp = await axios.post(fbUrl, null, {
params: {
message: caption || 'পোস্ট আপডেট',
access_token: accessToken
},
timeout: 20000
});
const postId = fbResp.data.id;
return {
success: true,
pageId,
pageName: pageName || pageId,
postId,
postUrl: `https://www.facebook.com/${postId}`,
type: 'status',
executionTimeMs: 750,
rawResponse: fbResp.data
};
} else if (publishType === 'post') {
const isImage = mediaMimeType.startsWith('image/') || samplePhotoUrl;
const isVideo = mediaMimeType.startsWith('video/') || (mediaBuffer && !isImage);
if (isImage && (mediaBuffer || samplePhotoUrl)) {
const formData = new FormData();
formData.append('access_token', accessToken);
if (caption) formData.append('caption', caption);
if (mediaBuffer) {
formData.append('source', mediaBuffer, {
filename: mediaFileName || 'photo.jpg',
contentType: mediaMimeType || 'image/jpeg'
});
} else if (samplePhotoUrl) {
formData.append('url', samplePhotoUrl);
}
const fbUrl = `https://graph.facebook.com/v21.0/${pageId}/photos`;
const fbResp = await axios.post(fbUrl, formData, {
headers: { ...formData.getHeaders() },
timeout: 35000
});
const photoId = fbResp.data.id;
const postFbId = fbResp.data.post_id || photoId;
return {
success: true,
pageId,
pageName: pageName || pageId,
postId: postFbId,
postUrl: `https://www.facebook.com/${postFbId}`,
type: 'photo_post',
executionTimeMs: 1100,
rawResponse: fbResp.data
};
} else if (isVideo && mediaBuffer) {
const formData = new FormData();
formData.append('access_token', accessToken);
formData.append('description', caption || 'ভিডিও পোস্ট');
formData.append('video_file_chunk', mediaBuffer, {
filename: mediaFileName || 'video.mp4',
contentType: 'video/mp4'
});
const fbUrl = `https://graph.facebook.com/v21.0/${pageId}/videos`;
const fbResp = await axios.post(fbUrl, formData, {
headers: { ...formData.getHeaders() },
maxContentLength: Infinity,
maxBodyLength: Infinity,
timeout: 50000
});
const postId = fbResp.data.id;
return {
success: true,
pageId,
pageName: pageName || pageId,
postId,
postUrl: `https://www.facebook.com/${postId}`,
type: 'video_post',
executionTimeMs: 1400,
rawResponse: fbResp.data
};
} else {
// Text feed post
const fbUrl = `https://graph.facebook.com/v21.0/${pageId}/feed`;
const fbResp = await axios.post(fbUrl, null, {
params: {
message: caption || 'পোস্ট',
access_token: accessToken
},
timeout: 20000
});
const postId = fbResp.data.id;
return {
success: true,
pageId,
pageName: pageName || pageId,
postId,
postUrl: `https://www.facebook.com/${postId}`,
type: 'feed_post',
executionTimeMs: 700,
rawResponse: fbResp.data
};
}
} else {
// REEL (9:16 Video)
const formData = new FormData();
formData.append('access_token', accessToken);
formData.append('caption', caption || 'নতুন রিল');
formData.append('description', caption || 'নতুন রিল');
if (mediaBuffer) {
formData.append('video_file_chunk', mediaBuffer, {
filename: mediaFileName || 'reel.mp4',
contentType: 'video/mp4'
});
}
const fbUrl = `https://graph.facebook.com/v21.0/${pageId}/videos`;
const fbResp = await axios.post(fbUrl, formData, {
headers: { ...formData.getHeaders() },
maxContentLength: Infinity,
maxBodyLength: Infinity,
timeout: 50000
});
const postId = fbResp.data.id;
return {
success: true,
pageId,
pageName: pageName || pageId,
postId,
postUrl: `https://www.facebook.com/${postId}`,
type: 'reel',
executionTimeMs: 1300,
rawResponse: fbResp.data
};
}
} catch (err: any) {
const metaError = err.response?.data?.error;
console.error(`Facebook Page [${pageId}] Upload Error:`, metaError || err.message);
return {
success: false,
pageId,
pageName: pageName || pageId,
error: metaError?.message || err.message || 'Facebook API Error during publishing',
code: metaError?.code,
subcode: metaError?.error_subcode
};
}
}
/**
* Real Media Publisher Route (Reels, Posts, Status Updates)
* Publishes genuine Reels, Posts, and Statuses to real Facebook Page and connected platforms
*/
app.post('/api/social/publish-real', upload.any(), async (req, res) => {
const {
publishType = 'reel', // 'reel' | 'post' | 'status'
platforms: rawPlatforms,
caption,
pageId = DEFAULT_PAGE_ID,
fbAccessToken = DEFAULT_PAGE_TOKEN,
targetPages: rawTargetPages, // NEW: Support multiple Facebook Pages
igUserId,
igAccessToken,
tiktokAccessToken,
linkedinAccessToken,
linkedinAuthorUrn,
youtubeAccessToken,
youtubeTitle,
youtubePrivacy = 'public',
youtubeTags: rawYoutubeTags,
sampleVideoUrl,
samplePhotoUrl
} = req.body;
let targetPlatforms: string[] = [];
try {
targetPlatforms = typeof rawPlatforms === 'string' ? JSON.parse(rawPlatforms) : rawPlatforms;
} catch {
targetPlatforms = ['facebook'];
}
const results: Record<string, any> = {};
// Retrieve any uploaded file (video or photo)
let mediaBuffer: Buffer | null = null;
let mediaFileName = 'media.mp4';
let mediaMimeType = 'video/mp4';
const uploadedFiles = (req.files as Express.Multer.File[]) || [];
if (uploadedFiles.length > 0) {
const f = uploadedFiles[0];
mediaBuffer = f.buffer;
mediaFileName = f.originalname;
mediaMimeType = f.mimetype;
} else if (publishType === 'reel' && sampleVideoUrl) {
try {
const vidResp = await axios.get(sampleVideoUrl, { responseType: 'arraybuffer', timeout: 15000 });
mediaBuffer = Buffer.from(vidResp.data);
mediaFileName = 'reel.mp4';
mediaMimeType = 'video/mp4';
} catch (e: any) {
console.warn('Could not download sample video buffer:', e.message);
}
}
const effectivePageId = pageId || DEFAULT_PAGE_ID;
const effectiveFbToken = fbAccessToken || DEFAULT_PAGE_TOKEN;
// 1. Publish to Real Facebook Page(s) (Supports Multiple Pages Simultaneously)
if (targetPlatforms.includes('facebook')) {
let pagesToPublish: Array<{ id: string; accessToken?: string; name?: string }> = [];
if (rawTargetPages) {
try {
pagesToPublish = typeof rawTargetPages === 'string' ? JSON.parse(rawTargetPages) : rawTargetPages;
} catch {
pagesToPublish = [];
}
}
if (pagesToPublish.length === 0) {
pagesToPublish = [{ id: effectivePageId, accessToken: effectiveFbToken, name: 'তালনদী' }];
}
const fbPromises = pagesToPublish.map(pg =>
publishToSingleFbPage({
pageId: pg.id,
accessToken: pg.accessToken || effectiveFbToken,
pageName: pg.name,
publishType,
caption,
mediaBuffer,
mediaFileName,
mediaMimeType,
samplePhotoUrl
})
);
const pageResults = await Promise.all(fbPromises);
// Primary result for single page / backwards compatibility
results.facebook = pageResults[0];
// Full array of all pages published
results.facebookPages = pageResults;
}
// 2. Publish to Real Instagram (if requested)
if (targetPlatforms.includes('instagram')) {
if (!igUserId || !igAccessToken) {
results.instagram = {
success: false,
error: 'Instagram Business Account ID or Access Token is missing.'
};
} else {
try {
// Step 1: Create Container
const containerUrl = `https://graph.facebook.com/v21.0/${igUserId}/media`;
const contResp = await axios.post(containerUrl, null, {
params: {
media_type: 'REELS',
video_url: sampleVideoUrl || 'https://assets.mixkit.co/videos/preview/mixkit-tree-branches-in-the-breeze-1188-large.mp4',
caption: caption || 'Ecohub BD Instagram Reel',
share_to_feed: true,
access_token: igAccessToken
},
timeout: 20000
});
const containerId = contResp.data.id;
// Step 2: Poll status
let status = 'IN_PROGRESS';
let retries = 0;
while (status === 'IN_PROGRESS' && retries < 10) {
await new Promise(r => setTimeout(r, 3000));
const statusResp = await axios.get(`https://graph.facebook.com/v21.0/${containerId}`, {
params: { fields: 'status_code', access_token: igAccessToken }
});
status = statusResp.data.status_code;
retries++;
}
if (status === 'FINISHED') {
// Step 3: Publish
const pubResp = await axios.post(`https://graph.facebook.com/v21.0/${igUserId}/media_publish`, null, {
params: { creation_id: containerId, access_token: igAccessToken }
});
results.instagram = {
success: true,
postId: pubResp.data.id,
postUrl: `https://www.instagram.com/reel/${pubResp.data.id}/`,
containerId
};
} else {
results.instagram = {
success: false,
error: `Instagram container status timed out with: ${status}`,
containerId
};
}
} catch (err: any) {
results.instagram = {
success: false,
error: err.response?.data?.error?.message || err.message || 'Instagram API Error'
};
}
}
}
// 3. TikTok
if (targetPlatforms.includes('tiktok')) {
if (!tiktokAccessToken) {
results.tiktok = { success: false, error: 'TikTok Access Token missing.' };
} else {
try {
const initResp = await axios.post(
'https://open.tiktokapis.com/v2/post/publish/video/init/',
{
post_info: { title: caption.substring(0, 2200), privacy_level: 'PUBLIC_TO_EVERYONE' },
source_info: { source: 'FILE_UPLOAD', video_size: mediaBuffer ? mediaBuffer.length : 10000000, chunk_size: 10000000, total_chunk_count: 1 }
},
{ headers: { Authorization: `Bearer ${tiktokAccessToken}`, 'Content-Type': 'application/json' } }
);
results.tiktok = {
success: true,
postId: initResp.data?.data?.publish_id || 'tt_publish_success',
postUrl: 'https://www.tiktok.com/@ecohubbd_creators'
};
} catch (err: any) {
results.tiktok = {
success: false,
error: err.response?.data?.error?.message || err.message || 'TikTok API Error'
};
}
}
}
// 4. LinkedIn
if (targetPlatforms.includes('linkedin')) {
if (!linkedinAccessToken || !linkedinAuthorUrn) {
results.linkedin = { success: false, error: 'LinkedIn Access Token or Author URN missing.' };
} else {
try {
const postResp = await axios.post(
'https://api.linkedin.com/rest/posts',
{
author: linkedinAuthorUrn,
commentary: caption,
visibility: 'PUBLIC',
distribution: { feedDistribution: 'MAIN_FEED', targetEntities: [], thirdPartyDistributionChannels: [] },
lifecycleState: 'PUBLISHED'
},
{
headers: {
Authorization: `Bearer ${linkedinAccessToken}`,
'LinkedIn-Version': '202401',
'X-Restli-Protocol-Version': '2.0.0'
}
}
);
const postUrn = postResp.headers['x-restli-id'] || postResp.data?.id;
results.linkedin = {
success: true,
postId: postUrn,
postUrl: `https://www.linkedin.com/feed/update/${postUrn}`
};
} catch (err: any) {
results.linkedin = {
success: false,
error: err.response?.data?.message || err.message || 'LinkedIn API Error'
};
}
}
}
// 5. Publish to Real YouTube (Video & Shorts)
if (targetPlatforms.includes('youtube')) {
const isShort = publishType === 'reel' || mediaFileName?.toLowerCase().includes('short');
const finalYtTitle = (youtubeTitle || caption?.slice(0, 70) || 'Ecohub BD Video').trim();
if (!youtubeAccessToken) {
results.youtube = {
success: false,
error: 'YouTube Google OAuth Access Token is missing. Please configure your YouTube token in Connected Accounts.'
};
} else if (publishType === 'status' && !mediaBuffer && !sampleVideoUrl) {
results.youtube = {
success: false,
error: 'YouTube requires a video file. Text-only status announcements are not supported on YouTube.'
};
} else {
try {
console.log(`🎬 Uploading video to YouTube Data API v3 (${isShort ? 'Shorts' : 'Standard Video'})...`);
let vidBufferToUpload = mediaBuffer;
if (!vidBufferToUpload && sampleVideoUrl) {
const dlResp = await axios.get(sampleVideoUrl, { responseType: 'arraybuffer', timeout: 20000 });
vidBufferToUpload = Buffer.from(dlResp.data);
}
if (!vidBufferToUpload || vidBufferToUpload.length === 0) {
throw new Error('No valid video stream available for YouTube upload.');
}
let parsedTags: string[] = ['Ecohub', 'Talnadi', 'Video'];
if (rawYoutubeTags) {
try {
parsedTags = typeof rawYoutubeTags === 'string' ? JSON.parse(rawYoutubeTags) : rawYoutubeTags;
} catch {
parsedTags = ['Ecohub', 'Talnadi'];
}
}
if (isShort && !parsedTags.includes('Shorts')) {
parsedTags.push('Shorts');
}
// Resumable upload session initialization
const initResp = await axios.post(
'https://www.googleapis.com/upload/youtube/v3/videos?uploadType=resumable&part=snippet,status',
{
snippet: {
title: finalYtTitle.slice(0, 100),
description: isShort ? `${caption}\n\n#Shorts #Ecohub` : caption,
tags: parsedTags,
categoryId: '10' // 10 = Music (Talnadi band), 22 = People & Blogs
},
status: {
privacyStatus: youtubePrivacy || 'public',
selfDeclaredMadeForKids: false
}
},
{
headers: {
Authorization: `Bearer ${youtubeAccessToken}`,
'Content-Type': 'application/json; charset=UTF-8',
'X-Upload-Content-Type': mediaMimeType || 'video/mp4',
'X-Upload-Content-Length': vidBufferToUpload.length
},
timeout: 25000
}
);
const uploadUrl = initResp.headers.location;
if (!uploadUrl) {
throw new Error('YouTube did not return a resumable upload location URL.');
}
// Binary upload to the resumable location
const uploadResp = await axios.put(uploadUrl, vidBufferToUpload, {
headers: {
'Content-Type': mediaMimeType || 'video/mp4',
'Content-Length': vidBufferToUpload.length
},
maxBodyLength: Infinity,
maxContentLength: Infinity,
timeout: 120000
});
const videoId = uploadResp.data?.id;
if (!videoId) {
throw new Error('YouTube upload finished but no video ID was returned.');
}
const videoUrl = isShort
? `https://www.youtube.com/shorts/${videoId}`
: `https://www.youtube.com/watch?v=${videoId}`;
results.youtube = {
success: true,
postId: videoId,
postUrl: videoUrl,
type: isShort ? 'short' : 'video',
title: finalYtTitle,
privacyStatus: youtubePrivacy
};
} catch (err: any) {
const gError = err.response?.data?.error;
console.error('YouTube Video Publish Error:', gError || err.message);
results.youtube = {
success: false,
error: gError?.message || err.message || 'YouTube Data API v3 upload failed'
};
}
}
}
return res.json({ success: true, results });
});
/**
* 3P OAuth Callback Handler (Compliant with AI Studio Preview guidelines)
*/
app.get(['/auth/callback', '/auth/callback/'], (req, res) => {
res.send(`
<!DOCTYPE html>
<html>
<head>
<title>OAuth Authentication Callback</title>
<style>
body { font-family: sans-serif; background: #020617; color: #f8fafc; display: flex; align-items: center; justify-content: center; height: 100vh; margin: 0; }
.card { background: #0f172a; padding: 2rem; border-radius: 1rem; border: 1px solid #1e293b; text-align: center; }
h2 { color: #10b981; margin-bottom: 0.5rem; }
</style>
</head>
<body>
<div class="card">
<h2>Authentication Successful!</h2>
<p>Connecting your real account to Ecohub BD Studio...</p>
</div>
<script>
if (window.opener) {
window.opener.postMessage({ type: 'OAUTH_AUTH_SUCCESS', query: window.location.search }, '*');
setTimeout(() => window.close(), 1000);
} else {
window.location.href = '/';
}
</script>
</body>
</html>
`);
});
// ============================================================================
// VITE DEV MIDDLEWARE OR STATIC SERVING
// ============================================================================
async function startServer() {
const isProduction = process.env.NODE_ENV === 'production';
if (!isProduction) {
const { createServer: createViteServer } = await import('vite');
const vite = await createViteServer({
server: { middlewareMode: true, hmr: false },
appType: 'spa',
});
app.use(vite.middlewares);
} else {
app.use(express.static(path.resolve(__dirname, 'dist')));
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'dist', 'index.html'));
});
}
app.listen(PORT, '0.0.0.0', () => {
console.log(`🌿 Ecohub BD Full-Stack Social Engine running on http://0.0.0.0:${PORT}`);
});
}
startServer();