Skip to content

Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.

restructure the codebase

valzor9c4516639022
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..caec735
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 Valzor
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..fefe943
--- /dev/null
+++ b/README.md
@@ -0,0 +1,329 @@
+<div align="center">
+ <img src="frontend/public/logo.png" alt="Twiligent Logo" width="100" />
+
+ # Twiligent
+
+ **Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.**
+
+ [![Node.js](https://img.shields.io/badge/Node.js-18%2B-339933?style=flat-square&logo=node.js&logoColor=white)](https://nodejs.org)
+ [![React](https://img.shields.io/badge/React-19-61DAFB?style=flat-square&logo=react&logoColor=black)](https://react.dev)
+ [![MUI](https://img.shields.io/badge/MUI-v7-007FFF?style=flat-square&logo=mui&logoColor=white)](https://mui.com)
+ [![License](https://img.shields.io/badge/License-MIT-green?style=flat-square)](LICENSE)
+ [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen?style=flat-square)](CONTRIBUTING.md)
+
+</div>
+
+---
+
+No third-party service sitting between you and your numbers. No monthly fee. No sending your data somewhere you can't see. You plug in your YouTube Data API and Instagram Graph API keys. It pulls everything. Displays it clean in a dark-themed dashboard. That's it. Your data stays yours.
+The only time anything leaves your machine is when you schedule Instagram posts. That part runs through GitHub Actions. Everything else never moves Most people don't realize how much they're giving up just to see their own stats. This fixes that.
+
+---
+
+## Features
+
+- **Multi-account support** — add unlimited YouTube channels and Instagram Business/Creator accounts side by side
+- **YouTube analytics** — views, watch time, subscribers, revenue estimates, top videos, engagement rates, and shorts vs. long-form breakdown
+- **Instagram analytics** — reach, impressions, follower growth, best day/hour to post, consistency score, and per-reel stats
+- **Unified overview** — cross-platform totals and channel rankings at a glance
+- **Content explorer** — sortable, filterable tables for all videos, all shorts, and all reels
+- **Scheduled publishing** — schedule Instagram posts (image + caption + optional location) and let GitHub Actions publish them automatically every 15 minutes, even when your laptop is closed
+- **Cloudinary support** — upload media directly from the dashboard to Cloudinary, then schedule or publish immediately
+- **Token auto-refresh** — Instagram long-lived tokens refresh automatically every 24 hours so analytics never go stale
+- **Zero database** — all data lives as JSON files in `backend/data/` for easy backup and full control
+
+---
+
+## Screenshots
+
+<!-- Hero: Dashboard Overview -->
+<div align="center">
+ <img src="frontend/public/screenshots/Dashboard%20Overview.png" alt="Dashboard Overview" width="90%" />
+ <p><em>Unified overview — cross-platform stats, audience comparison, and channel rankings at a glance</em></p>
+</div>
+
+<br/>
+
+<!-- Row: YouTube + Instagram Analytics -->
+<table width="100%">
+ <tr>
+ <td width="50%" align="center">
+ <img src="frontend/public/screenshots/YouTube%20Account%20Overview.png" alt="YouTube Account Overview" width="100%" />
+ <br/><sub><b>YouTube Channel Analytics</b> — 20+ metrics, top videos with thumbnails, engagement deep-dive</sub>
+ </td>
+ <td width="50%" align="center">
+ <img src="frontend/public/screenshots/Instagram%20Account%20Overview.png" alt="Instagram Account Overview" width="100%" />
+ <br/><sub><b>Instagram Account Analytics</b> — follower growth, best post times, consistency score, engagement timeline</sub>
+ </td>
+ </tr>
+</table>
+
+<br/>
+
+<!-- Row: Content Explorers (3 columns) -->
+<table width="100%">
+ <tr>
+ <td width="33%" align="center">
+ <img src="frontend/public/screenshots/All%20Videos.png" alt="Video Explorer" width="100%" />
+ <br/><sub><b>Video Explorer</b> — browse and sort all YouTube videos</sub>
+ </td>
+ <td width="33%" align="center">
+ <img src="frontend/public/screenshots/All%20Shorts.png" alt="Shorts Explorer" width="100%" />
+ <br/><sub><b>Shorts Explorer</b> — dedicated view for YouTube Shorts</sub>
+ </td>
+ <td width="33%" align="center">
+ <img src="frontend/public/screenshots/IG%20Content%20Explorer.png" alt="IG Content Explorer" width="100%" />
+ <br/><sub><b>IG Content Explorer</b> — browse all reels and posts by performance</sub>
+ </td>
+ </tr>
+</table>
+
+<br/>
+
+<!-- Row: Management pages (3 columns) -->
+<table width="100%">
+ <tr>
+ <td width="33%" align="center">
+ <img src="frontend/public/screenshots/Manage%20Accounts.png" alt="Manage Accounts" width="100%" />
+ <br/><sub><b>Accounts</b> — add/remove YouTube channels and Instagram accounts</sub>
+ </td>
+ <td width="33%" align="center">
+ <img src="frontend/public/screenshots/Upload%20Content.png" alt="Upload & Publish" width="100%" />
+ <br/><sub><b>Publish</b> — upload to Cloudinary and schedule Instagram posts</sub>
+ </td>
+ <td width="33%" align="center">
+ <img src="frontend/public/screenshots/Settings.png" alt="Settings" width="100%" />
+ <br/><sub><b>Settings</b> — manage API keys and credentials in one place</sub>
+ </td>
+ </tr>
+</table>
+
+---
+
+## Quick Start
+
+### Prerequisites
+
+| Tool | Minimum version |
+|------|----------------|
+| Node.js | 18 |
+| npm | 9 |
+| A YouTube Data API v3 key | — |
+| An Instagram Graph API token | — |
+
+### 1. Clone the repository
+
+```bash
+git clone https://github.com/your-username/twiligent.git
+cd twiligent
+```
+
+### 2. Install dependencies
+
+```bash
+# Backend
+cd backend && npm install
+
+# Frontend (in a new terminal)
+cd frontend && npm install
+```
+
+### 3. Configure API keys
+
+Create `backend/data/api_keys.json`:
+
+```json
+{
+ "youtubeApiKey": "YOUR_YOUTUBE_DATA_API_V3_KEY",
+ "cloudinaryCloudName": "YOUR_CLOUDINARY_CLOUD_NAME",
+ "cloudinaryApiKey": "YOUR_CLOUDINARY_API_KEY",
+ "cloudinaryApiSecret": "YOUR_CLOUDINARY_API_SECRET"
+}
+```
+
+> Instagram tokens are added per-account through the **Accounts** page in the UI — no manual JSON editing required.
+
+### 4. Run
+
+```bash
+# Terminal 1 — backend (port 3001)
+cd backend && npm run dev
+
+# Terminal 2 — frontend (port 5173)
+cd frontend && npm run dev
+```
+
+Open [http://localhost:5173](http://localhost:5173) in your browser.
+
+---
+
+## Why Twiligent?
+
+Most analytics dashboards are either locked behind paywalls, share your data with third parties, or only support one platform. Twiligent is different:
+
+- **Self-hosted** — your credentials and content data never leave your machine
+- **Multi-platform** — YouTube and Instagram in one place, with a unified overview
+- **Extensible** — every data source is a plain JSON file; every API call is a readable service module
+- **Free to run** — uses only free API tiers and GitHub Actions free minutes (unlimited on public repos)
+
+---
+
+## Getting Your API Keys
+
+### YouTube Data API v3
+
+1. Go to [Google Cloud Console](https://console.cloud.google.com/)
+2. Create a project → **APIs & Services** → **Library** → search "YouTube Data API v3" → **Enable**
+3. **Credentials** → **Create Credentials** → **API key**
+4. (Optional) Restrict the key to the YouTube Data API v3 for security
+5. Paste the key into `backend/data/api_keys.json`
+
+### Instagram Graph API
+
+Instagram requires a Business or Creator account linked to a Facebook Page.
+
+1. Go to [Meta for Developers](https://developers.facebook.com/) → create an app of type **Business**
+2. Add the **Instagram Graph API** product
+3. Generate a **User Access Token** with scopes:
+ - `instagram_basic`
+ - `instagram_manage_insights`
+ - `pages_read_engagement`
+4. Exchange it for a **Long-Lived Token** (valid 60 days — Twiligent auto-refreshes it)
+5. In the Twiligent **Accounts** page, click **Add Instagram Account** and paste the token
+
+### Cloudinary (optional — required for scheduled publishing)
+
+1. Sign up at [cloudinary.com](https://cloudinary.com) (free tier: 25 GB storage, 25 GB bandwidth/month)
+2. Copy your **Cloud name**, **API Key**, and **API Secret** from the Cloudinary dashboard
+3. Paste them into `backend/data/api_keys.json`
+
+---
+
+## Scheduled Publishing with GitHub Actions
+
+Twiligent uses a GitHub Actions workflow to publish scheduled Instagram posts even when your machine is offline. The workflow runs every 15 minutes on GitHub's servers.
+
+### Setup
+
+**Step 1 — Push your repo to GitHub** (the `backend/data/accounts.json` file is gitignored to protect tokens)
+
+**Step 2 — Add the accounts secret**
+
+```bash
+# macOS / Linux
+cat backend/data/accounts.json | base64
+
+# Windows PowerShell
+[Convert]::ToBase64String([IO.File]::ReadAllBytes("backend\data\accounts.json"))
+```
+
+Go to your GitHub repo → **Settings** → **Secrets and variables** → **Actions** → **New repository secret**:
+
+| Name | Value |
+|------|-------|
+| `ACCOUNTS_JSON` | The base64 string from above |
+
+**Step 3 — Enable Actions**
+
+Go to your repo → **Actions** → enable workflows if prompted. The `Instagram Scheduled Publisher` workflow will trigger automatically on the cron schedule.
+
+> **Free tier note:** Public repos get unlimited GitHub Actions minutes. Private repos get 2,000 min/month — change the cron to `'*/30 * * * *'` in `.github/workflows/publish-scheduled.yml` to stay within the limit.
+
+### How it works
+
+1. You schedule a post through the **Publish** page in the UI
+2. The post is saved to `backend/data/scheduled_posts.json` and synced to GitHub via the Contents API
+3. Every 15 minutes, the GitHub Actions workflow checks for due posts
+4. Due posts are published to Instagram via the Graph API
+5. The workflow commits the updated `scheduled_posts.json` back to the repo (status changed to `published`)
+6. Next time your backend starts, it pulls the latest `scheduled_posts.json` from GitHub
+
+---
+
+## Project Structure
+
+```
+twiligent/
+├── backend/
+│ ├── data/ # JSON data files (gitignored: accounts.json)
+│ │ ├── api_keys.json # API credentials
+│ │ ├── scheduled_posts.json # Post schedule (synced via GitHub API)
+│ │ ├── videos_cache.json # YouTube video cache
+│ │ └── ig_cache.json # Instagram analytics cache
+│ ├── routes/ # Express route handlers
+│ │ ├── accounts.js # Add/remove/refresh accounts
+│ │ ├── analytics.js # Fetch channel analytics
+│ │ ├── publishing.js # Publish content to Instagram
+│ │ ├── scheduledPosts.js # CRUD for scheduled posts
+│ │ ├── github.js # GitHub sync endpoints
+│ │ └── keys.js # API key management
+│ ├── services/ # External API clients
+│ │ ├── youtube.js # YouTube Data API v3 integration
+│ │ └── instagram.js # Instagram Graph API integration
+│ ├── utils/
+│ │ ├── dataHelpers.js # JSON read/write utilities
+│ │ └── scheduler.js # Due-post processing logic
+│ └── server.js # Express entry point
+│
+├── frontend/
+│ ├── public/
+│ │ └── logo.png # App logo
+│ └── src/
+│ ├── features/ # Feature-based modules
+│ │ ├── analytics/
+│ │ │ ├── overview/ # Unified cross-platform overview
+│ │ │ ├── channel/ # YouTube channel deep-dive
+│ │ │ ├── videos/ # All videos explorer
+│ │ │ ├── shorts/ # All shorts explorer
+│ │ │ ├── instagram/ # Instagram account analytics
+│ │ │ └── reels/ # Reels / IG content explorer
+│ │ ├── accounts/ # Account management UI
+│ │ ├── publishing/ # Content upload + scheduler
+│ │ └── settings/ # App settings
+│ ├── layouts/
+│ │ └── Sidebar.jsx # Navigation sidebar
+│ ├── components/ui/ # Shared UI components
+│ │ ├── StatCard.jsx # Metric card with gradient icon
+│ │ └── Logo.jsx # App logo component
+│ ├── services/
+│ │ └── api.js # Frontend API client
+│ ├── utils/
+│ │ └── formatters.js # Number / date formatters
+│ ├── theme.js # MUI dark theme
+│ └── App.jsx # Root component + routing
+│
+├── scripts/
+│ └── publish-scheduled.js # GitHub Actions post publisher
+│
+├── .github/
+│ └── workflows/
+│ └── publish-scheduled.yml # Cron workflow (every 15 min)
+│
+└── README.md
+```
+
+---
+
+## Contributing
+
+Pull requests are welcome. For major changes, open an issue first to discuss what you'd like to change.
+
+1. Fork the repository
+2. Create a feature branch: `git checkout -b feature/your-feature`
+3. Commit your changes: `git commit -m 'Add your feature'`
+4. Push to the branch: `git push origin feature/your-feature`
+5. Open a pull request
+
+Please keep pull requests focused — one feature or fix per PR.
+
+---
+
+## License
+
+[MIT](LICENSE)
+
+---
+
+<div align="center">
+ Built with Express, React, and the YouTube + Instagram Graph APIs.
+</div>
diff --git a/backend/nodemon.json b/backend/nodemon.json
index 87b5a90..a6f3d31 100644
--- a/backend/nodemon.json
+++ b/backend/nodemon.json
@@ -1,10 +1,10 @@
{
"watch": [
- "server.js"
+ "."
],
"ignore": [
"data/*",
- "*.json"
+ "node_modules/*"
],
"ext": "js"
-}
\ No newline at end of file
+}
diff --git a/backend/routes/accounts.js b/backend/routes/accounts.js
new file mode 100644
index 0000000..2b0ab37
--- /dev/null
+++ b/backend/routes/accounts.js
@@ -0,0 +1,271 @@
+const router = require('express').Router();
+const { readJSON, writeJSON, ACCOUNTS_FILE, VIDEOS_CACHE_FILE, IG_CACHE_FILE, getAPIKey, getIGAppCredentials } = require('../utils/dataHelpers');
+const { syncEverythingToGitHub } = require('../services/github');
+const { fetchInstagramProfile, exchangeForLongLivedToken, refreshLongLivedToken } = require('../services/instagram');
+const { resolveChannelId, fetchChannelData } = require('../services/youtube');
+
+router.get('/accounts', async (req, res) => {
+ const accounts = await readJSON(ACCOUNTS_FILE) || [];
+ const safe = accounts.map(a => {
+ const copy = { ...a };
+ if (copy.accessToken) delete copy.accessToken;
+ return copy;
+ });
+ res.json(safe);
+});
+
+router.post('/resolve-channel', async (req, res) => {
+ try {
+ const { input } = req.body;
+ const apiKey = await getAPIKey();
+ if (!apiKey) return res.status(400).json({ success: false, message: 'YouTube API key not configured' });
+
+ const channelId = await resolveChannelId(input, apiKey);
+ const channelData = await fetchChannelData(channelId, apiKey);
+ res.json({ success: true, data: channelData });
+ } catch (err) {
+ res.status(400).json({ success: false, message: err.message });
+ }
+});
+
+router.post('/accounts', async (req, res) => {
+ try {
+ const { input } = req.body;
+ const apiKey = await getAPIKey();
+ if (!apiKey) return res.status(400).json({ success: false, message: 'YouTube API key not configured' });
+
+ const channelId = await resolveChannelId(input, apiKey);
+ const channelData = await fetchChannelData(channelId, apiKey);
+ const accounts = await readJSON(ACCOUNTS_FILE);
+
+ if (accounts.find(a => a.channelId === channelId)) {
+ return res.status(400).json({ success: false, message: 'This channel is already added' });
+ }
+
+ const newAccount = {
+ id: Date.now().toString(),
+ channelId: channelData.channelId,
+ title: channelData.title,
+ description: channelData.description,
+ customUrl: channelData.customUrl,
+ publishedAt: channelData.publishedAt,
+ country: channelData.country,
+ thumbnails: channelData.thumbnails,
+ subscriberCount: channelData.subscriberCount,
+ viewCount: channelData.viewCount,
+ videoCount: channelData.videoCount,
+ hiddenSubscriberCount: channelData.hiddenSubscriberCount,
+ uploadsPlaylistId: channelData.uploadsPlaylistId,
+ keywords: channelData.keywords,
+ topicCategories: channelData.topicCategories,
+ madeForKids: channelData.madeForKids,
+ addedAt: new Date().toISOString(),
+ lastUpdated: new Date().toISOString(),
+ };
+
+ accounts.push(newAccount);
+ await writeJSON(ACCOUNTS_FILE, accounts);
+ syncEverythingToGitHub().catch(() => { });
+
+ res.json({ success: true, account: newAccount });
+ } catch (err) {
+ res.status(400).json({ success: false, message: err.message });
+ }
+});
+
+router.post('/accounts/instagram', async (req, res) => {
+ try {
+ const { accessToken } = req.body;
+ if (!accessToken) return res.status(400).json({ success: false, message: 'Access token is required' });
+
+ const { appSecret } = await getIGAppCredentials();
+
+ let finalToken = accessToken;
+ let expiresIn = 0;
+ if (appSecret) {
+ try {
+ const longToken = await exchangeForLongLivedToken(accessToken, appSecret);
+ finalToken = longToken.accessToken;
+ expiresIn = longToken.expiresIn;
+ console.log('Token exchanged for long-lived token successfully');
+ } catch (err) {
+ console.log('Token exchange skipped (token may already be long-lived):', err.message);
+ }
+ } else {
+ console.log('No Instagram App Secret configured — using token as-is');
+ }
+
+ const profile = await fetchInstagramProfile(null, finalToken);
+
+ if (!profile.igUserId) {
+ throw new Error('Could not get Instagram User ID. Make sure the token has instagram_business_basic permission and is from a Business/Creator account.');
+ }
+
+ const accounts = await readJSON(ACCOUNTS_FILE);
+
+ if (accounts.find(a => a.platform === 'instagram' && a.igUserId === profile.igUserId)) {
+ return res.status(400).json({ success: false, message: 'This Instagram account is already added' });
+ }
+
+ const newAccount = {
+ id: Date.now().toString(),
+ platform: 'instagram',
+ igUserId: profile.igUserId,
+ username: profile.username,
+ title: profile.name || profile.username,
+ biography: profile.biography,
+ website: profile.website,
+ profilePictureUrl: profile.profilePictureUrl,
+ followersCount: profile.followersCount,
+ followsCount: profile.followsCount,
+ mediaCount: profile.mediaCount,
+ accessToken: finalToken,
+ tokenExpiresAt: expiresIn > 0
+ ? new Date(Date.now() + expiresIn * 1000).toISOString()
+ : null,
+ addedAt: new Date().toISOString(),
+ lastUpdated: new Date().toISOString(),
+ };
+
+ accounts.push(newAccount);
+ await writeJSON(ACCOUNTS_FILE, accounts);
+ syncEverythingToGitHub().catch(() => { });
+
+ const safeAccount = { ...newAccount };
+ delete safeAccount.accessToken;
+ res.json({ success: true, account: safeAccount });
+ } catch (err) {
+ res.status(400).json({ success: false, message: err.message });
+ }
+});
+
+router.post('/accounts/refresh-all', async (req, res) => {
+ try {
+ const apiKey = await getAPIKey();
+ const accounts = await readJSON(ACCOUNTS_FILE);
+ const results = [];
+
+ for (const account of accounts) {
+ try {
+ if (account.platform === 'instagram') {
+ if (!account.accessToken) throw new Error('No access token');
+ const profile = await fetchInstagramProfile(account.igUserId, account.accessToken);
+ account.followersCount = profile.followersCount;
+ account.followsCount = profile.followsCount;
+ account.mediaCount = profile.mediaCount;
+ account.title = profile.name || profile.username;
+ account.username = profile.username;
+ account.profilePictureUrl = profile.profilePictureUrl;
+ } else {
+ if (!apiKey) throw new Error('No YouTube API key');
+ const channelData = await fetchChannelData(account.channelId, apiKey);
+ account.subscriberCount = channelData.subscriberCount;
+ account.viewCount = channelData.viewCount;
+ account.videoCount = channelData.videoCount;
+ account.title = channelData.title;
+ account.thumbnails = channelData.thumbnails;
+ }
+ account.lastUpdated = new Date().toISOString();
+ results.push({ id: account.id, success: true });
+ } catch (err) {
+ results.push({ id: account.id, success: false, error: err.message });
+ }
+ }
+
+ await writeJSON(ACCOUNTS_FILE, accounts);
+ const safeAccounts = accounts.map(a => {
+ const safe = { ...a };
+ if (safe.accessToken) delete safe.accessToken;
+ return safe;
+ });
+ res.json({ success: true, accounts: safeAccounts, results, updatedAt: new Date().toISOString() });
+ } catch (err) {
+ res.status(500).json({ success: false, message: err.message });
+ }
+});
+
+router.post('/accounts/:id/refresh-ig-token', async (req, res) => {
+ try {
+ const accounts = await readJSON(ACCOUNTS_FILE);
+ const account = accounts.find(a => a.id === req.params.id && a.platform === 'instagram');
+ if (!account) return res.status(404).json({ success: false, message: 'Instagram account not found' });
+ if (!account.accessToken) return res.status(400).json({ success: false, message: 'No access token stored' });
+
+ const refreshed = await refreshLongLivedToken(account.accessToken);
+ account.accessToken = refreshed.accessToken;
+ account.tokenExpiresAt = new Date(Date.now() + (refreshed.expiresIn || 5184000) * 1000).toISOString();
+ await writeJSON(ACCOUNTS_FILE, accounts);
+ syncEverythingToGitHub().catch(() => { });
+ res.json({ success: true, message: 'Token refreshed for another 60 days', expiresAt: account.tokenExpiresAt });
+ } catch (err) {
+ res.status(400).json({ success: false, message: err.message });
+ }
+});
+
+router.post('/accounts/:id/refresh', async (req, res) => {
+ try {
+ const accounts = await readJSON(ACCOUNTS_FILE);
+ const account = accounts.find(a => a.id === req.params.id);
+ if (!account) return res.status(404).json({ success: false, message: 'Not found' });
+
+ if (account.platform === 'instagram') {
+ if (!account.accessToken) return res.status(400).json({ success: false, message: 'No access token' });
+ const profile = await fetchInstagramProfile(account.igUserId, account.accessToken);
+ account.followersCount = profile.followersCount;
+ account.followsCount = profile.followsCount;
+ account.mediaCount = profile.mediaCount;
+ account.title = profile.name || profile.username;
+ account.username = profile.username;
+ account.profilePictureUrl = profile.profilePictureUrl;
+ account.biography = profile.biography;
+ account.website = profile.website;
+ } else {
+ const apiKey = await getAPIKey();
+ if (!apiKey) return res.status(400).json({ success: false, message: 'No API key' });
+ const channelData = await fetchChannelData(account.channelId, apiKey);
+ account.subscriberCount = channelData.subscriberCount;
+ account.viewCount = channelData.viewCount;
+ account.videoCount = channelData.videoCount;
+ account.title = channelData.title;
+ account.description = channelData.description;
+ account.thumbnails = channelData.thumbnails;
+ account.customUrl = channelData.customUrl;
+ account.country = channelData.country;
+ account.keywords = channelData.keywords;
+ account.topicCategories = channelData.topicCategories;
+ }
+ account.lastUpdated = new Date().toISOString();
+ await writeJSON(ACCOUNTS_FILE, accounts);
+
+ const safeAccount = { ...account };
+ if (safeAccount.accessToken) delete safeAccount.accessToken;
+ res.json({ success: true, account: safeAccount });
+ } catch (err) {
+ res.status(400).json({ success: false, message: err.message });
+ }
+});
+
+router.delete('/accounts/:id', async (req, res) => {
+ try {
+ const accounts = await readJSON(ACCOUNTS_FILE);
+ const account = accounts.find(a => a.id === req.params.id);
+ if (!account) return res.status(404).json({ success: false, message: 'Not found' });
+ const filtered = accounts.filter(a => a.id !== req.params.id);
+ await writeJSON(ACCOUNTS_FILE, filtered);
+ syncEverythingToGitHub().catch(() => { });
+
+ const cache = await readJSON(VIDEOS_CACHE_FILE);
+ delete cache[req.params.id];
+ await writeJSON(VIDEOS_CACHE_FILE, cache);
+
+ const igCache = await readJSON(IG_CACHE_FILE) || {};
+ delete igCache[req.params.id];
+ await writeJSON(IG_CACHE_FILE, igCache);
+
+ res.json({ success: true });
+ } catch (err) {
+ res.status(500).json({ success: false, message: err.message });
+ }
+});
+
+module.exports = router;
diff --git a/backend/routes/analytics.js b/backend/routes/analytics.js
new file mode 100644
index 0000000..e68604b
--- /dev/null
+++ b/backend/routes/analytics.js
@@ -0,0 +1,245 @@
+const router = require('express').Router();
+const { readJSON, writeJSON, ACCOUNTS_FILE, VIDEOS_CACHE_FILE, IG_CACHE_FILE, getAPIKey } = require('../utils/dataHelpers');
+const { fetchAllVideos, fetchChannelData, computeVideoAnalytics } = require('../services/youtube');
+const { fetchInstagramProfile, fetchInstagramMedia, computeInstagramAnalytics } = require('../services/instagram');
+
+router.get('/accounts/:id/analytics', async (req, res) => {
+ try {
+ const apiKey = await getAPIKey();
+ if (!apiKey) return res.status(400).json({ success: false, message: 'No API key' });
+
+ const accounts = await readJSON(ACCOUNTS_FILE);
+ const account = accounts.find(a => a.id === req.params.id);
+ if (!account) return res.status(404).json({ success: false, message: 'Not found' });
+
+ const videos = await fetchAllVideos(account.uploadsPlaylistId, apiKey, 10);
+
+ const cache = await readJSON(VIDEOS_CACHE_FILE) || {};
+ cache[req.params.id] = { videos, fetchedAt: new Date().toISOString() };
+ await writeJSON(VIDEOS_CACHE_FILE, cache);
+
+ const analytics = computeVideoAnalytics(videos);
+
+ if (!account.publishedAt) {
+ try {
+ const channelData = await fetchChannelData(account.channelId, apiKey);
+ account.publishedAt = channelData.publishedAt;
+ account.subscriberCount = channelData.subscriberCount;
+ account.viewCount = channelData.viewCount;
+ account.videoCount = channelData.videoCount;
+ account.title = channelData.title;
+ account.thumbnails = channelData.thumbnails;
+ account.customUrl = channelData.customUrl;
+ account.country = channelData.country;
+ account.lastUpdated = new Date().toISOString();
+ await writeJSON(ACCOUNTS_FILE, accounts);
+ } catch (e) {
+ console.error('Failed to backfill channel data:', e.message);
+ }
+ }
+
+ const channelAge = account.publishedAt
+ ? Math.floor((Date.now() - new Date(account.publishedAt).getTime()) / 86400000)
+ : 365;
+ const viewsPerSub = account.subscriberCount > 0 ? (account.viewCount / account.subscriberCount).toFixed(1) : 0;
+ const subsPerView = account.viewCount > 0 ? (account.subscriberCount / account.viewCount * 100).toFixed(4) : 0;
+ const avgViewsPerVideo = account.videoCount > 0 ? Math.round(account.viewCount / account.videoCount) : 0;
+ const avgSubGainPerDay = channelAge > 0 ? Math.round(account.subscriberCount / channelAge) : 0;
+ const avgViewsPerDay = channelAge > 0 ? Math.round(account.viewCount / channelAge) : 0;
+
+ res.json({
+ success: true,
+ channel: {
+ ...account,
+ channelAge,
+ channelAgeYears: (channelAge / 365).toFixed(1),
+ viewsPerSubscriber: parseFloat(viewsPerSub),
+ subscriberToViewRatio: parseFloat(subsPerView),
+ avgViewsPerVideo,
+ avgSubGainPerDay,
+ avgViewsPerDay,
+ estimatedMonthlyViews: avgViewsPerDay * 30,
+ estimatedMonthlySubGain: avgSubGainPerDay * 30,
+ estimatedYearlyViews: avgViewsPerDay * 365,
+ estimatedYearlySubGain: avgSubGainPerDay * 365,
+ },
+ analytics,
+ videoCount: videos.length,
+ });
+ } catch (err) {
+ res.status(400).json({ success: false, message: err.message });
+ }
+});
+
+router.get('/accounts/:id/videos', async (req, res) => {
+ try {
+ const cache = await readJSON(VIDEOS_CACHE_FILE) || {};
+ const accountCache = cache[req.params.id];
+
+ if (accountCache && accountCache.videos) {
+ return res.json({ success: true, videos: accountCache.videos, fetchedAt: accountCache.fetchedAt });
+ }
+
+ const apiKey = await getAPIKey();
+ if (!apiKey) return res.status(400).json({ success: false, message: 'No API key' });
+
+ const accounts = await readJSON(ACCOUNTS_FILE);
+ const account = accounts.find(a => a.id === req.params.id);
+ if (!account) return res.status(404).json({ success: false, message: 'Not found' });
+
+ const videos = await fetchAllVideos(account.uploadsPlaylistId, apiKey, 10);
+ cache[req.params.id] = { videos, fetchedAt: new Date().toISOString() };
+ await writeJSON(VIDEOS_CACHE_FILE, cache);
+
+ res.json({ success: true, videos, fetchedAt: cache[req.params.id].fetchedAt });
+ } catch (err) {
+ res.status(400).json({ success: false, message: err.message });
+ }
+});
+
+router.get('/comparison', async (req, res) => {
+ try {
+ const accounts = await readJSON(ACCOUNTS_FILE);
+ if (accounts.length === 0) return res.json({ success: true, comparison: null });
+
+ const sorted = {
+ bySubscribers: [...accounts].sort((a, b) => b.subscriberCount - a.subscriberCount),
+ byViews: [...accounts].sort((a, b) => b.viewCount - a.viewCount),
+ byVideos: [...accounts].sort((a, b) => b.videoCount - a.videoCount),
+ };
+
+ const totals = accounts.reduce((acc, a) => ({
+ subscribers: acc.subscribers + a.subscriberCount,
+ views: acc.views + a.viewCount,
+ videos: acc.videos + a.videoCount,
+ }), { subscribers: 0, views: 0, videos: 0 });
+
+ res.json({
+ success: true,
+ comparison: {
+ rankings: sorted,
+ totals,
+ accountCount: accounts.length,
+ bestBySubscribers: sorted.bySubscribers[0] || null,
+ bestByViews: sorted.byViews[0] || null,
+ bestByVideos: sorted.byVideos[0] || null,
+ },
+ });
+ } catch (err) {
+ res.status(500).json({ success: false, message: err.message });
+ }
+});
+
+router.get('/accounts/:id/ig-analytics', async (req, res) => {
+ try {
+ const accounts = await readJSON(ACCOUNTS_FILE);
+ const account = accounts.find(a => a.id === req.params.id && a.platform === 'instagram');
+ if (!account) return res.status(404).json({ success: false, message: 'Instagram account not found' });
+ if (!account.accessToken) return res.status(400).json({ success: false, message: 'No access token stored' });
+
+ const profile = await fetchInstagramProfile(account.igUserId, account.accessToken);
+ const media = await fetchInstagramMedia(account.igUserId, account.accessToken, 500);
+
+ const igCache = await readJSON(IG_CACHE_FILE) || {};
+ igCache[req.params.id] = { media, fetchedAt: new Date().toISOString() };
+ await writeJSON(IG_CACHE_FILE, igCache);
+
+ const analytics = computeInstagramAnalytics(profile, media);
+
+ account.followersCount = profile.followersCount;
+ account.followsCount = profile.followsCount;
+ account.mediaCount = profile.mediaCount;
+ account.profilePictureUrl = profile.profilePictureUrl;
+ account.lastUpdated = new Date().toISOString();
+ await writeJSON(ACCOUNTS_FILE, accounts);
+
+ const safeAccount = { ...account };
+ delete safeAccount.accessToken;
+
+ res.json({
+ success: true,
+ profile: { ...profile },
+ account: safeAccount,
+ analytics,
+ mediaCount: media.length,
+ });
+ } catch (err) {
+ res.status(400).json({ success: false, message: err.message });
+ }
+});
+
+router.get('/accounts/:id/ig-media', async (req, res) => {
+ try {
+ const igCache = await readJSON(IG_CACHE_FILE) || {};
+ const cached = igCache[req.params.id];
+ if (cached && cached.media) {
+ return res.json({ success: true, media: cached.media, fetchedAt: cached.fetchedAt });
+ }
+
+ const accounts = await readJSON(ACCOUNTS_FILE);
+ const account = accounts.find(a => a.id === req.params.id && a.platform === 'instagram');
+ if (!account) return res.status(404).json({ success: false, message: 'Not found' });
+ if (!account.accessToken) return res.status(400).json({ success: false, message: 'No access token' });
+
+ const media = await fetchInstagramMedia(account.igUserId, account.accessToken, 500);
+ igCache[req.params.id] = { media, fetchedAt: new Date().toISOString() };
+ await writeJSON(IG_CACHE_FILE, igCache);
+
+ res.json({ success: true, media, fetchedAt: igCache[req.params.id].fetchedAt });
+ } catch (err) {
+ res.status(400).json({ success: false, message: err.message });
+ }
+});
+
+router.get('/videos/all', async (req, res) => {
+ try {
+ const { channelId, sort, order, search, minViews, maxViews } = req.query;
+ const cache = await readJSON(VIDEOS_CACHE_FILE) || {};
+ const accounts = await readJSON(ACCOUNTS_FILE) || [];
+
+ let allVideos = [];
+ for (const acct of accounts) {
+ if (channelId && acct.id !== channelId) continue;
+ const cached = cache[acct.id];
+ if (cached && cached.videos) {
+ allVideos.push(...cached.videos.map(v => ({
+ ...v,
+ channelTitle: acct.title || acct.name || acct.channelTitle,
+ channelId: acct.id,
+ channelThumbnail: acct.thumbnails?.default || acct.thumbnailUrl || '',
+ })));
+ }
+ }
+
+ if (search) {
+ const q = search.toLowerCase();
+ allVideos = allVideos.filter(v =>
+ v.title?.toLowerCase().includes(q) ||
+ (v.tags || []).some(t => t.toLowerCase().includes(q))
+ );
+ }
+
+ if (minViews) allVideos = allVideos.filter(v => (v.viewCount || 0) >= parseInt(minViews));
+ if (maxViews) allVideos = allVideos.filter(v => (v.viewCount || 0) <= parseInt(maxViews));
+
+ const sortField = sort || 'viewCount';
+ const sortOrder = order === 'asc' ? 1 : -1;
+ allVideos.sort((a, b) => {
+ const aVal = a[sortField] ?? 0;
+ const bVal = b[sortField] ?? 0;
+ if (typeof aVal === 'string') return sortOrder * aVal.localeCompare(bVal);
+ return sortOrder * (bVal - aVal);
+ });
+
+ res.json({
+ success: true,
+ videos: allVideos,
+ total: allVideos.length,
+ channels: accounts.map(a => ({ id: a.id, title: a.title || a.name })),
+ });
+ } catch (err) {
+ res.status(500).json({ success: false, message: err.message });
+ }
+});
+
+module.exports = router;
diff --git a/backend/routes/github.js b/backend/routes/github.js
new file mode 100644
index 0000000..705715a
--- /dev/null
+++ b/backend/routes/github.js
@@ -0,0 +1,24 @@
+const router = require('express').Router();
+const { readJSON, SCHEDULED_POSTS_FILE } = require('../utils/dataHelpers');
+const { syncEverythingToGitHub, pullScheduledPostsFromGitHub } = require('../services/github');
+
+router.post('/github-sync', async (req, res) => {
+ try {
+ await syncEverythingToGitHub();
+ res.json({ success: true, message: 'Synced all data files to GitHub' });
+ } catch (err) {
+ res.status(500).json({ success: false, message: err.message });
+ }
+});
+
+router.post('/github-pull', async (req, res) => {
+ try {
+ await pullScheduledPostsFromGitHub();
+ const posts = await readJSON(SCHEDULED_POSTS_FILE) || [];
+ res.json({ success: true, posts, message: 'Pulled from GitHub' });
+ } catch (err) {
+ res.status(500).json({ success: false, message: err.message });
+ }
+});
+
+module.exports = router;
diff --git a/backend/routes/keys.js b/backend/routes/keys.js
new file mode 100644
index 0000000..d2a1b5c
--- /dev/null
+++ b/backend/routes/keys.js
@@ -0,0 +1,54 @@
+const router = require('express').Router();
+const { readJSON, writeJSON, API_KEYS_FILE } = require('../utils/dataHelpers');
+
+router.get('/', async (req, res) => {
+ const keys = await readJSON(API_KEYS_FILE);
+ res.json({
+ youtube: keys?.youtube || '',
+ configured: !!keys?.youtube,
+ instagram: {
+ appId: keys?.instagram?.appId || '',
+ appSecret: keys?.instagram?.appSecret || '',
+ configured: !!(keys?.instagram?.appId && keys?.instagram?.appSecret),
+ },
+ cloudinary: {
+ cloudName: keys?.cloudinary?.cloudName || '',
+ uploadPreset: keys?.cloudinary?.uploadPreset || '',
+ configured: !!(keys?.cloudinary?.cloudName && keys?.cloudinary?.uploadPreset),
+ },
+ github: {
+ token: keys?.github?.token || '',
+ repo: keys?.github?.repo || '',
+ branch: keys?.github?.branch || 'main',
+ configured: !!(keys?.github?.token && keys?.github?.repo),
+ },
+ });
+});
+
+router.post('/', async (req, res) => {
+ const { youtube, instagram, cloudinary, github } = req.body;
+ const keys = await readJSON(API_KEYS_FILE) || {};
+
+ if (youtube !== undefined) keys.youtube = youtube;
+ if (instagram !== undefined) {
+ if (!keys.instagram) keys.instagram = {};
+ if (instagram.appId !== undefined) keys.instagram.appId = instagram.appId;
+ if (instagram.appSecret !== undefined) keys.instagram.appSecret = instagram.appSecret;
+ }
+ if (cloudinary !== undefined) {
+ if (!keys.cloudinary) keys.cloudinary = {};
+ if (cloudinary.cloudName !== undefined) keys.cloudinary.cloudName = cloudinary.cloudName;
+ if (cloudinary.uploadPreset !== undefined) keys.cloudinary.uploadPreset = cloudinary.uploadPreset;
+ }
+ if (github !== undefined) {
+ if (!keys.github) keys.github = { branch: 'main' };
+ if (github.token !== undefined) keys.github.token = github.token;
+ if (github.repo !== undefined) keys.github.repo = github.repo;
+ if (github.branch !== undefined) keys.github.branch = github.branch || 'main';
+ }
+
+ const ok = await writeJSON(API_KEYS_FILE, keys);
+ res.json({ success: ok, message: ok ? 'API keys saved' : 'Failed to save' });
+});
+
+module.exports = router;
diff --git a/backend/routes/publishing.js b/backend/routes/publishing.js
new file mode 100644
index 0000000..1ee90d5
--- /dev/null
+++ b/backend/routes/publishing.js
@@ -0,0 +1,142 @@
+const router = require('express').Router();
+const fetch = require('node-fetch');
+const { readJSON, ACCOUNTS_FILE, API_KEYS_FILE } = require('../utils/dataHelpers');
+
+router.get('/cloudinary-config', async (req, res) => {
+ const keys = await readJSON(API_KEYS_FILE);
+ const cloud = keys?.cloudinary || {};
+ if (!cloud.cloudName || !cloud.uploadPreset) {
+ return res.json({ success: false, message: 'Cloudinary not configured' });
+ }
+ res.json({ success: true, cloudName: cloud.cloudName, uploadPreset: cloud.uploadPreset });
+});
+
+router.get('/accounts/:id/ig-publishing-limit', async (req, res) => {
+ try {
+ const accounts = await readJSON(ACCOUNTS_FILE) || [];
+ const acct = accounts.find(a => a.id === req.params.id);
+ if (!acct || acct.platform !== 'instagram') {
+ return res.status(404).json({ success: false, message: 'Instagram account not found' });
+ }
+ const r = await fetch(
+ `https://graph.instagram.com/v25.0/${acct.igUserId}/content_publishing_limit?fields=quota_usage,config&access_token=${acct.accessToken}`
+ );
+ const data = await r.json();
+ if (data.error) throw new Error(data.error.message);
+ res.json({ success: true, ...data });
+ } catch (err) {
+ res.status(500).json({ success: false, message: err.message });
+ }
+});
+
+router.post('/accounts/:id/ig-publish', async (req, res) => {
+ try {
+ const accounts = await readJSON(ACCOUNTS_FILE) || [];
+ const acct = accounts.find(a => a.id === req.params.id);
+ if (!acct || acct.platform !== 'instagram') {
+ return res.status(404).json({ success: false, message: 'Instagram account not found' });
+ }
+
+ const {
+ mediaType, mediaUrl, caption, coverUrl, shareToFeed, collaborators,
+ audioName, thumbOffset, locationId, userTags, altText, children,
+ } = req.body;
+
+ const igId = acct.igUserId;
+ const token = acct.accessToken;
+ const params = { access_token: token };
+
+ if (mediaType === 'CAROUSEL') {
+ params.media_type = 'CAROUSEL';
+ if (caption) params.caption = caption;
+ if (children && children.length) params.children = children.join(',');
+ if (collaborators && collaborators.length) params.collaborators = JSON.stringify(collaborators);
+ if (locationId) params.location_id = locationId;
+ } else if (mediaType === 'CAROUSEL_ITEM_IMAGE') {
+ params.image_url = mediaUrl;
+ params.is_carousel_item = true;
+ } else if (mediaType === 'CAROUSEL_ITEM_VIDEO') {
+ params.media_type = 'VIDEO';
+ params.video_url = mediaUrl;
+ params.is_carousel_item = true;
+ } else if (mediaType === 'REELS') {
+ params.media_type = 'REELS';
+ params.video_url = mediaUrl;
+ if (caption) params.caption = caption;
+ if (shareToFeed !== undefined) params.share_to_feed = shareToFeed;
+ if (coverUrl) params.cover_url = coverUrl;
+ if (collaborators && collaborators.length) params.collaborators = JSON.stringify(collaborators);
+ if (audioName) params.audio_name = audioName;
+ if (thumbOffset != null) params.thumb_offset = thumbOffset;
+ if (locationId) params.location_id = locationId;
+ if (userTags && userTags.length) params.user_tags = JSON.stringify(userTags);
+ } else if (mediaType === 'STORIES') {
+ params.media_type = 'STORIES';
+ if (mediaUrl && (mediaUrl.match(/\.(mp4|mov|avi|webm)/i))) {
+ params.video_url = mediaUrl;
+ } else {
+ params.image_url = mediaUrl;
+ }
+ if (userTags && userTags.length) params.user_tags = JSON.stringify(userTags);
+ } else {
+ params.image_url = mediaUrl;
+ if (caption) params.caption = caption;
+ if (locationId) params.location_id = locationId;
+ if (userTags && userTags.length) params.user_tags = JSON.stringify(userTags);
+ if (altText) params.alt_text = altText;
+ }
+
+ const qs = new URLSearchParams(params).toString();
+ const r = await fetch(`https://graph.instagram.com/v25.0/${igId}/media?${qs}`, { method: 'POST' });
+ const data = await r.json();
+
+ if (data.error) throw new Error(data.error.message);
+ res.json({ success: true, containerId: data.id });
+ } catch (err) {
+ res.status(500).json({ success: false, message: err.message });
+ }
+});
+
+router.get('/ig-container/:containerId/status', async (req, res) => {
+ try {
+ const { containerId } = req.params;
+ const { accountId } = req.query;
+ const accounts = await readJSON(ACCOUNTS_FILE) || [];
+ const acct = accounts.find(a => a.id === accountId);
+ if (!acct) return res.status(404).json({ success: false, message: 'Account not found' });
+
+ const r = await fetch(
+ `https://graph.instagram.com/v25.0/${containerId}?fields=status_code,status&access_token=${acct.accessToken}`
+ );
+ const data = await r.json();
+ if (data.error) throw new Error(data.error.message);
+
+ res.json({ success: true, statusCode: data.status_code, status: data.status });
+ } catch (err) {
+ res.status(500).json({ success: false, message: err.message });
+ }
+});
+
+router.post('/accounts/:id/ig-media-publish', async (req, res) => {
+ try {
+ const accounts = await readJSON(ACCOUNTS_FILE) || [];
+ const acct = accounts.find(a => a.id === req.params.id);
+ if (!acct || acct.platform !== 'instagram') {
+ return res.status(404).json({ success: false, message: 'Instagram account not found' });
+ }
+
+ const { containerId } = req.body;
+ const r = await fetch(
+ `https://graph.instagram.com/v25.0/${acct.igUserId}/media_publish?creation_id=${containerId}&access_token=${acct.accessToken}`,
+ { method: 'POST' }
+ );
+ const data = await r.json();
+ if (data.error) throw new Error(data.error.message);
+
+ res.json({ success: true, mediaId: data.id });
+ } catch (err) {
+ res.status(500).json({ success: false, message: err.message });
+ }
+});
+
+module.exports = router;
diff --git a/backend/routes/scheduledPosts.js b/backend/routes/scheduledPosts.js
new file mode 100644
index 0000000..16d57ec
--- /dev/null
+++ b/backend/routes/scheduledPosts.js
@@ -0,0 +1,129 @@
+const router = require('express').Router();
+const { readJSON, writeJSON, SCHEDULED_POSTS_FILE } = require('../utils/dataHelpers');
+const { syncEverythingToGitHub } = require('../services/github');
+const { generateId, processScheduledPosts } = require('../utils/scheduler');
+
+router.get('/scheduled-posts', async (req, res) => {
+ try {
+ const posts = await readJSON(SCHEDULED_POSTS_FILE) || [];
+ res.json({ success: true, posts });
+ } catch (err) {
+ res.status(500).json({ success: false, message: err.message });
+ }
+});
+
+router.post('/scheduled-posts', async (req, res) => {
+ try {
+ const {
+ accountId, platform, mediaType, mediaUrl,
+ caption, coverUrl, shareToFeed, collaborators,
+ audioName, thumbOffset, locationId, userTags,
+ altText, scheduledAt,
+ } = req.body;
+
+ if (!accountId || !mediaUrl || !scheduledAt) {
+ return res.status(400).json({ success: false, message: 'accountId, mediaUrl, and scheduledAt are required' });
+ }
+
+ const scheduledDate = new Date(scheduledAt);
+ if (isNaN(scheduledDate.getTime()) || scheduledDate <= new Date()) {
+ return res.status(400).json({ success: false, message: 'scheduledAt must be a valid future date' });
+ }
+
+ const post = {
+ id: generateId(),
+ accountId,
+ platform: platform || 'instagram',
+ mediaType: mediaType || 'IMAGE',
+ mediaUrl,
+ caption: caption || '',
+ coverUrl: coverUrl || null,
+ shareToFeed: shareToFeed !== undefined ? shareToFeed : true,
+ collaborators: collaborators || [],
+ audioName: audioName || '',
+ thumbOffset: thumbOffset || null,
+ locationId: locationId || '',
+ userTags: userTags || [],
+ altText: altText || '',
+ scheduledAt: scheduledDate.toISOString(),
+ status: 'pending',
+ createdAt: new Date().toISOString(),
+ publishedMediaId: null,
+ error: null,
+ };
+
+ const posts = await readJSON(SCHEDULED_POSTS_FILE) || [];
+ posts.push(post);
+ await writeJSON(SCHEDULED_POSTS_FILE, posts);
+ syncEverythingToGitHub().catch(() => { });
+
+ res.json({ success: true, post });
+ } catch (err) {
+ res.status(500).json({ success: false, message: err.message });
+ }
+});
+
+router.put('/scheduled-posts/:id', async (req, res) => {
+ try {
+ const posts = await readJSON(SCHEDULED_POSTS_FILE) || [];
+ const idx = posts.findIndex(p => p.id === req.params.id);
+ if (idx === -1) return res.status(404).json({ success: false, message: 'Scheduled post not found' });
+ if (posts[idx].status !== 'pending' && posts[idx].status !== 'scheduled') {
+ return res.status(400).json({ success: false, message: 'Can only edit pending posts' });
+ }
+
+ const allowed = ['caption', 'scheduledAt', 'shareToFeed', 'collaborators', 'audioName',
+ 'thumbOffset', 'locationId', 'userTags', 'altText', 'coverUrl'];
+ for (const key of allowed) {
+ if (req.body[key] !== undefined) posts[idx][key] = req.body[key];
+ }
+ if (req.body.scheduledAt) posts[idx].scheduledAt = new Date(req.body.scheduledAt).toISOString();
+
+ await writeJSON(SCHEDULED_POSTS_FILE, posts);
+ syncEverythingToGitHub().catch(() => { });
+ res.json({ success: true, post: posts[idx] });
+ } catch (err) {
+ res.status(500).json({ success: false, message: err.message });
+ }
+});
+
+router.delete('/scheduled-posts', async (_req, res) => {
+ try {
+ let posts = await readJSON(SCHEDULED_POSTS_FILE) || [];
+ const publishing = posts.filter(p => p.status === 'publishing');
+ await writeJSON(SCHEDULED_POSTS_FILE, publishing);
+ syncEverythingToGitHub().catch(() => { });
+ res.json({ success: true, deleted: posts.length - publishing.length, kept: publishing.length });
+ } catch (err) {
+ res.status(500).json({ success: false, message: err.message });
+ }
+});
+
+router.delete('/scheduled-posts/:id', async (req, res) => {
+ try {
+ let posts = await readJSON(SCHEDULED_POSTS_FILE) || [];
+ const post = posts.find(p => p.id === req.params.id);
+ if (!post) return res.status(404).json({ success: false, message: 'Scheduled post not found' });
+ if (post.status === 'publishing') {
+ return res.status(400).json({ success: false, message: 'Cannot delete a post that is currently publishing' });
+ }
+ posts = posts.filter(p => p.id !== req.params.id);
+ await writeJSON(SCHEDULED_POSTS_FILE, posts);
+ syncEverythingToGitHub().catch(() => { });
+ res.json({ success: true, message: 'Scheduled post deleted' });
+ } catch (err) {
+ res.status(500).json({ success: false, message: err.message });
+ }
+});
+
+router.get('/process-scheduled', async (req, res) => {
+ const result = await processScheduledPosts();
+ res.json({ success: true, ...result, timestamp: new Date().toISOString() });
+});
+
+router.post('/process-scheduled', async (req, res) => {
+ const result = await processScheduledPosts();
+ res.json({ success: true, ...result, timestamp: new Date().toISOString() });
+});
+
+module.exports = router;
diff --git a/backend/server.js b/backend/server.js
index e52e8dc..44e99e9 100644
--- a/backend/server.js
+++ b/backend/server.js
@@ -1,9 +1,10 @@
const express = require('express');
const cors = require('cors');
-const fs = require('fs').promises;
-const path = require('path');
-const fetch = require('node-fetch');
-const sodium = require('libsodium-wrappers');
+
+const { initializeData, readJSON, SCHEDULED_POSTS_FILE } = require('./utils/dataHelpers');
+const { removeAccountsFileFromGitHub, pullScheduledPostsFromGitHub } = require('./services/github');
+const { autoRefreshInstagramTokens } = require('./services/instagram');
+const { processScheduledPosts } = require('./utils/scheduler');
const app = express();
const PORT = 3001;
@@ -11,2089 +12,24 @@ const PORT = 3001;
app.use(cors());
app.use(express.json());
-const DATA_DIR = path.join(__dirname, 'data');
-const ACCOUNTS_FILE = path.join(DATA_DIR, 'accounts.json');
-const API_KEYS_FILE = path.join(DATA_DIR, 'api_keys.json');
-const VIDEOS_CACHE_FILE = path.join(DATA_DIR, 'videos_cache.json');
-const IG_CACHE_FILE = path.join(DATA_DIR, 'ig_cache.json');
-const SCHEDULED_POSTS_FILE = path.join(DATA_DIR, 'scheduled_posts.json');
-
-// ─── Data Helpers ────────────────────────────────────────────────────────────
-
-async function initializeData() {
- try {
- await fs.mkdir(DATA_DIR, { recursive: true });
- const defaults = [
- [ACCOUNTS_FILE, []],
- [API_KEYS_FILE, { youtube: '', instagram: { appId: '', appSecret: '' }, cloudinary: { cloudName: '', uploadPreset: '' }, github: { token: '', repo: '', branch: 'main' } }],
- [VIDEOS_CACHE_FILE, {}],
- [IG_CACHE_FILE, {}],
- [SCHEDULED_POSTS_FILE, []],
- ];
- for (const [file, defaultData] of defaults) {
- try {
- await fs.access(file);
- } catch {
- await fs.writeFile(file, JSON.stringify(defaultData, null, 2));
- }
- }
- console.log('Data files initialized');
- } catch (err) {
- console.error('Init error:', err);
- }
-}
-
-async function readJSON(filePath) {
- try {
- return JSON.parse(await fs.readFile(filePath, 'utf8'));
- } catch {
- return null;
- }
-}
-
-async function writeJSON(filePath, data) {
- try {
- await fs.writeFile(filePath, JSON.stringify(data, null, 2));
- return true;
- } catch {
- return false;
- }
-}
-
-// ─── GitHub Sync (for GitHub Actions scheduling) ─────────────────────────────
-
-// Push a single file to GitHub (create or update). Returns true on success.
-async function pushFileToGitHub(gh, repoPath, jsonData, commitMessage) {
- const repo = gh.repo.replace(/^https?:\/\/github\.com\//, '').replace(/\.git$/, '').replace(/\/$/, '');
- const branch = gh.branch || 'main';
- const content = Buffer.from(JSON.stringify(jsonData, null, 2)).toString('base64');
- const headers = { Authorization: `token ${gh.token}`, 'Content-Type': 'application/json', 'User-Agent': 'SocialMediaDashboard' };
-
- // Fetch current SHA so GitHub accepts the update
- let sha;
- try {
- const r = await fetch(`https://api.github.com/repos/${repo}/contents/${repoPath}?ref=${branch}`, { headers });
- if (r.ok) sha = (await r.json()).sha;
- } catch { }
-
- const body = { message: commitMessage, content, branch };
- if (sha) body.sha = sha;
-
- const res = await fetch(`https://api.github.com/repos/${repo}/contents/${repoPath}`, {
- method: 'PUT', headers, body: JSON.stringify(body),
- });
-
- if (!res.ok) {
- const err = await res.json();
- throw new Error(`GitHub PUT ${repoPath}: ${err.message}`);
- }
- return true;
-}
-
-// Sync ALL data files to GitHub in one pass.
-// accounts.json is pushed with accessToken stripped (tokens stay in the encrypted secret).
-async function syncAllDataToGitHub() {
- try {
- const keys = await readJSON(API_KEYS_FILE) || {};
- const gh = keys.github;
- if (!gh?.token || !gh?.repo) return;
-
- // Only sync scheduled_posts.json as a plain file.
- // accounts.json is NEVER pushed as a file — tokens would be wiped on next git pull.
- // Accounts sync via the encrypted ACCOUNTS_JSON secret instead (syncAccountsSecretToGitHub).
- const posts = await readJSON(SCHEDULED_POSTS_FILE) || [];
- await pushFileToGitHub(gh, 'backend/data/scheduled_posts.json', posts, '📅 Sync scheduled posts');
- console.log(' ☁️ Synced scheduled posts to GitHub');
- } catch (err) {
- console.error(' ☁️ syncAllDataToGitHub error:', err.message);
- }
-}
-
-
-// Remove accounts.json from GitHub if it was mistakenly committed (it contains no tokens anyway).
-// Safe to call repeatedly — silently does nothing if the file doesn't exist on GitHub.
-async function removeAccountsFileFromGitHub() {
- try {
- const keys = await readJSON(API_KEYS_FILE) || {};
- const gh = keys.github;
- if (!gh?.token || !gh?.repo) return;
- const repo = gh.repo.replace(/^https?:\/\/github\.com\//, '').replace(/\.git$/, '').replace(/\/$/, '');
- const branch = gh.branch || 'main';
- const filePath = 'backend/data/accounts.json';
- const headers = { Authorization: `token ${gh.token}`, 'Content-Type': 'application/json', 'User-Agent': 'SocialMediaDashboard' };
-
- const r = await fetch(`https://api.github.com/repos/${repo}/contents/${filePath}?ref=${branch}`, { headers });
- if (!r.ok) return; // file doesn't exist — nothing to do
-
- const { sha } = await r.json();
- const res = await fetch(`https://api.github.com/repos/${repo}/contents/${filePath}`, {
- method: 'DELETE',
- headers,
- body: JSON.stringify({ message: '🔒 Remove accounts.json (sensitive — use secret instead)', sha, branch }),
- });
- if (res.ok) console.log(' ☁️ Removed accounts.json from GitHub (was mistakenly committed)');
- } catch { }
-}
-
-async function pullScheduledPostsFromGitHub() {
- try {
- const keys = await readJSON(API_KEYS_FILE) || {};
- const gh = keys.github;
- if (!gh?.token || !gh?.repo) return;
-
- // Normalize repo: accept full URL or owner/repo format
- const repo = gh.repo.replace(/^https?:\/\/github\.com\//, '').replace(/\.git$/, '').replace(/\/$/, '');
-
- const filePath = 'backend/data/scheduled_posts.json';
- const branch = gh.branch || 'main';
-
- const res = await fetch(`https://api.github.com/repos/${repo}/contents/${filePath}?ref=${branch}`, {
- headers: { Authorization: `token ${gh.token}`, 'User-Agent': 'SocialMediaDashboard' }
- });
- if (!res.ok) return;
-
- const data = await res.json();
- const remotePosts = JSON.parse(Buffer.from(data.content, 'base64').toString('utf8'));
- const localPosts = await readJSON(SCHEDULED_POSTS_FILE) || [];
-
- // Merge: remote published/failed status wins; local-only posts are kept
- const remoteMap = new Map(remotePosts.map(p => [p.id, p]));
- const localMap = new Map(localPosts.map(p => [p.id, p]));
- const merged = [];
-
- for (const rp of remotePosts) {
- const lp = localMap.get(rp.id);
- if (!lp || rp.status === 'published' || rp.status === 'failed') {
- merged.push(rp); // Remote version takes precedence for terminal states
- } else {
- merged.push(lp); // Local is more current otherwise
- }
- }
- // Add local-only posts (created while server was off & GH Actions hasn't synced)
- for (const lp of localPosts) {
- if (!remoteMap.has(lp.id)) merged.push(lp);
- }
-
- await writeJSON(SCHEDULED_POSTS_FILE, merged);
- console.log(` ☁️ Pulled ${remotePosts.length} post(s) from GitHub, merged to ${merged.length}`);
- } catch (err) {
- console.error(' ☁️ GitHub pull error:', err.message);
- }
-}
-
-// ─── GitHub Accounts Secret Sync ─────────────────────────────────────────────
-// Automatically updates ACCOUNTS_JSON secret in GitHub Actions whenever accounts change.
-// This means you never have to manually regenerate the base64 secret again.
-
-async function syncAccountsSecretToGitHub() {
- try {
- const keys = await readJSON(API_KEYS_FILE) || {};
- const gh = keys.github;
- if (!gh?.token || !gh?.repo) return;
-
- const repo = gh.repo.replace(/^https?:\/\/github\.com\//, '').replace(/\.git$/, '').replace(/\/$/, '');
- const accounts = await readJSON(ACCOUNTS_FILE) || [];
- const secretValue = Buffer.from(JSON.stringify(accounts, null, 2)).toString('base64');
-
- // Step 1: Get the repo's public key for encrypting secrets
- const pkRes = await fetch(`https://api.github.com/repos/${repo}/actions/secrets/public-key`, {
- headers: { Authorization: `token ${gh.token}`, 'User-Agent': 'SocialMediaDashboard' }
- });
- if (!pkRes.ok) {
- console.error(' ☁️ Failed to get GitHub public key:', (await pkRes.json()).message);
- return;
- }
- const { key: publicKey, key_id } = await pkRes.json();
-
- // Step 2: Encrypt the secret using libsodium sealed box
- await sodium.ready;
- const binKey = sodium.from_base64(publicKey, sodium.base64_variants.ORIGINAL);
- const binSecret = sodium.from_string(secretValue);
- const encrypted = sodium.crypto_box_seal(binSecret, binKey);
- const encryptedB64 = sodium.to_base64(encrypted, sodium.base64_variants.ORIGINAL);
-
- // Step 3: Update the secret
- const res = await fetch(`https://api.github.com/repos/${repo}/actions/secrets/ACCOUNTS_JSON`, {
- method: 'PUT',
- headers: {
- Authorization: `token ${gh.token}`,
- 'Content-Type': 'application/json',
- 'User-Agent': 'SocialMediaDashboard'
- },
- body: JSON.stringify({ encrypted_value: encryptedB64, key_id }),
- });
-
- if (res.status === 201 || res.status === 204) {
- console.log(' ☁️ Synced ACCOUNTS_JSON secret to GitHub');
- } else {
- const err = await res.json();
- console.error(' ☁️ GitHub secret sync error:', err.message);
- }
- } catch (err) {
- console.error(' ☁️ GitHub secret sync error:', err.message);
- }
-}
-
-// Push all data files + refresh encrypted secret in one shot.
-// Use this everywhere instead of calling the two functions separately.
-async function syncEverythingToGitHub() {
- await Promise.allSettled([syncAllDataToGitHub(), syncAccountsSecretToGitHub()]);
-}
-
-async function getAPIKey() {
- const keys = await readJSON(API_KEYS_FILE);
- return keys?.youtube || '';
-}
-
-async function getIGAppCredentials() {
- const keys = await readJSON(API_KEYS_FILE);
- return keys?.instagram || { appId: '', appSecret: '' };
-}
-
-// ─── Instagram Graph API Helpers (Instagram API with Instagram Login) ────────
-// Docs: https://developers.facebook.com/docs/instagram-platform/instagram-api-with-instagram-login
-// Uses graph.instagram.com (NOT graph.facebook.com)
-// Instagram App ID & App Secret come from App Dashboard > Instagram > API setup
-
-const IG_GRAPH_URL = 'https://graph.instagram.com';
-const IG_API_VERSION = 'v25.0';
-
-async function igFetch(endpoint, params = {}) {
- // Endpoints that start with /oauth, /access_token, /refresh_access_token are unversioned
- const needsVersion = !endpoint.startsWith('/oauth') &&
- !endpoint.startsWith('/access_token') &&
- !endpoint.startsWith('/refresh_access_token');
- const base = needsVersion ? `${IG_GRAPH_URL}/${IG_API_VERSION}` : IG_GRAPH_URL;
- const url = new URL(`${base}${endpoint}`);
- Object.entries(params).forEach(([k, v]) => url.searchParams.set(k, v));
- const res = await fetch(url.toString());
- const data = await res.json();
- if (data.error) throw new Error(data.error.message || data.error.error_message || JSON.stringify(data.error));
- if (data.error_message) throw new Error(data.error_message);
- return data;
-}
-
-// Exchange a short-lived Instagram token for a long-lived one (~60 days)
-// Endpoint: GET https://graph.instagram.com/access_token
-async function exchangeForLongLivedToken(shortToken, appSecret) {
- const data = await igFetch('/access_token', {
- grant_type: 'ig_exchange_token',
- client_secret: appSecret,
- access_token: shortToken,
- });
- if (!data.access_token) throw new Error('Failed to exchange token — check Instagram App Secret');
- return {
- accessToken: data.access_token,
- tokenType: data.token_type || 'bearer',
- expiresIn: data.expires_in || 5184000, // ~60 days
- };
-}
-
-// Auto-refresh Instagram long-lived tokens that expire within 15 days
-async function autoRefreshInstagramTokens() {
- try {
- const accounts = await readJSON(ACCOUNTS_FILE) || [];
- const igAccounts = accounts.filter(a => a.platform === 'instagram' && a.accessToken && a.tokenExpiresAt);
- if (igAccounts.length === 0) return;
-
- const fifteenDaysMs = 15 * 24 * 60 * 60 * 1000;
- const soon = new Date(Date.now() + fifteenDaysMs);
- const toRefresh = igAccounts.filter(a => new Date(a.tokenExpiresAt) <= soon);
-
- if (toRefresh.length === 0) return;
-
- console.log(`\n 🔑 Auto-refreshing ${toRefresh.length} Instagram token(s) expiring within 15 days...`);
- let changed = false;
- for (const account of toRefresh) {
- try {
- const refreshed = await refreshLongLivedToken(account.accessToken);
- account.accessToken = refreshed.accessToken;
- account.tokenExpiresAt = new Date(Date.now() + (refreshed.expiresIn || 5184000) * 1000).toISOString();
- console.log(` ✅ Token refreshed for @${account.username} — expires ${account.tokenExpiresAt}`);
- changed = true;
- } catch (err) {
- console.error(` ❌ Failed to refresh token for @${account.username}: ${err.message}`);
- }
- }
-
- if (changed) {
- await writeJSON(ACCOUNTS_FILE, accounts);
- syncEverythingToGitHub().catch(() => { });
- }
- } catch (err) {
- console.error(' ❌ autoRefreshInstagramTokens error:', err.message);
- }
-}
-
-// Refresh a long-lived token for another 60 days
-// Endpoint: GET https://graph.instagram.com/refresh_access_token
-async function refreshLongLivedToken(longToken) {
- const data = await igFetch('/refresh_access_token', {
- grant_type: 'ig_refresh_token',
- access_token: longToken,
- });
- if (!data.access_token) throw new Error('Failed to refresh token');
- return {
- accessToken: data.access_token,
- tokenType: data.token_type || 'bearer',
- expiresIn: data.expires_in || 5184000,
- };
-}
-
-// Get the Instagram user ID & profile using /me (no Facebook Pages needed)
-async function fetchInstagramProfile(igUserId, accessToken) {
- // If no igUserId provided, use /me to discover it
- const endpoint = igUserId ? `/${igUserId}` : '/me';
- const data = await igFetch(endpoint, {
- access_token: accessToken,
- fields: 'user_id,username,name,profile_picture_url,followers_count,follows_count,media_count,biography,website',
- });
- return {
- igUserId: data.user_id || data.id || igUserId,
- name: data.name || '',
- username: data.username || '',
- profilePictureUrl: data.profile_picture_url || '',
- followersCount: data.followers_count || 0,
- followsCount: data.follows_count || 0,
- mediaCount: data.media_count || 0,
- biography: data.biography || '',
- website: data.website || '',
- };
-}
-
-async function fetchInstagramMedia(igUserId, accessToken, limit = 500) {
- let allMedia = [];
- // Use the versioned IG Graph API for media — fetch up to 100 per page, paginate up to 10 pages
- let url = `${IG_GRAPH_URL}/${IG_API_VERSION}/${igUserId}/media?access_token=${accessToken}&fields=id,caption,media_type,media_url,thumbnail_url,permalink,timestamp,like_count,comments_count&limit=${Math.min(limit, 100)}`;
-
- let pages = 0;
- while (url && pages < 10 && allMedia.length < limit) {
- const res = await fetch(url);
- const data = await res.json();
- if (data.error) throw new Error(data.error.message || data.error.error_message);
- if (data.data) allMedia = allMedia.concat(data.data);
- url = data.paging?.next || null;
- pages++;
- }
-
- return allMedia.slice(0, limit).map(m => ({
- id: m.id,
- caption: m.caption || '',
- mediaType: m.media_type || 'IMAGE',
- mediaUrl: m.media_url || '',
- thumbnailUrl: m.thumbnail_url || m.media_url || '',
- permalink: m.permalink || '',
- timestamp: m.timestamp || '',
- likeCount: m.like_count || 0,
- commentsCount: m.comments_count || 0,
- }));
-}
-
-function computeInstagramAnalytics(profile, media) {
- const emptyAnalytics = {
- totalPosts: profile.mediaCount || 0, fetchedPosts: 0,
- totalLikes: 0, totalComments: 0, totalEngagement: 0,
- avgLikes: 0, avgComments: 0, avgEngagement: 0,
- medianLikes: 0, medianComments: 0,
- engagementRate: 0, likesPerFollower: 0, commentsPerFollower: 0,
- bestByLikes: null, bestByComments: null, worstByLikes: null,
- recentMedia: [], mediaTypeDistribution: {},
- postFrequency: { perWeek: 0, perMonth: 0 },
- topPosts: [], performanceByType: {},
- hashtagAnalysis: [], captionLengthCorrelation: [],
- postsByDayOfWeek: [], postsByHour: [],
- engagementTimeline: [], monthlyBreakdown: [],
- postsLast7Days: 0, postsLast30Days: 0, postsLast90Days: 0,
- viralityScore: 0, consistencyScore: 0,
- bestPostingDay: '', bestPostingHour: '',
- likesToCommentsRatio: 0,
- };
- if (!media || media.length === 0) return emptyAnalytics;
-
- const totalLikes = media.reduce((s, m) => s + m.likeCount, 0);
- const totalComments = media.reduce((s, m) => s + m.commentsCount, 0);
- const totalEngagement = totalLikes + totalComments;
- const avgLikes = Math.round(totalLikes / media.length);
- const avgComments = Math.round(totalComments / media.length);
- const avgEngagement = Math.round(totalEngagement / media.length);
- const engagementRate = profile.followersCount > 0
- ? parseFloat(((totalLikes + totalComments) / media.length / profile.followersCount * 100).toFixed(2))
- : 0;
- const likesPerFollower = profile.followersCount > 0
- ? parseFloat((totalLikes / media.length / profile.followersCount * 100).toFixed(2)) : 0;
- const commentsPerFollower = profile.followersCount > 0
- ? parseFloat((totalComments / media.length / profile.followersCount * 100).toFixed(2)) : 0;
-
- // Median
- const sortedLikes = [...media].map(m => m.likeCount).sort((a, b) => a - b);
- const sortedComments = [...media].map(m => m.commentsCount).sort((a, b) => a - b);
- const mid = Math.floor(sortedLikes.length / 2);
- const medianLikes = sortedLikes.length % 2 ? sortedLikes[mid] : Math.round((sortedLikes[mid - 1] + sortedLikes[mid]) / 2);
- const medianComments = sortedComments.length % 2 ? sortedComments[mid] : Math.round((sortedComments[mid - 1] + sortedComments[mid]) / 2);
-
- const byLikes = [...media].sort((a, b) => b.likeCount - a.likeCount);
- const byComments = [...media].sort((a, b) => b.commentsCount - a.commentsCount);
- const likesToCommentsRatio = totalComments > 0 ? parseFloat((totalLikes / totalComments).toFixed(1)) : 0;
-
- // Media type distribution + performance by type
- const mediaTypes = {};
- const typeStats = {};
- media.forEach(m => {
- const t = m.mediaType;
- mediaTypes[t] = (mediaTypes[t] || 0) + 1;
- if (!typeStats[t]) typeStats[t] = { likes: 0, comments: 0, count: 0 };
- typeStats[t].likes += m.likeCount;
- typeStats[t].comments += m.commentsCount;
- typeStats[t].count++;
- });
- const performanceByType = {};
- Object.entries(typeStats).forEach(([type, s]) => {
- performanceByType[type] = {
- count: s.count,
- avgLikes: Math.round(s.likes / s.count),
- avgComments: Math.round(s.comments / s.count),
- avgEngagement: Math.round((s.likes + s.comments) / s.count),
- totalLikes: s.likes,
- totalComments: s.comments,
- };
- });
-
- // Post frequency
- const dates = media.map(m => new Date(m.timestamp)).filter(d => !isNaN(d));
- let perWeek = 0, perMonth = 0;
- if (dates.length >= 2) {
- const newest = Math.max(...dates);
- const oldest = Math.min(...dates);
- const spanDays = Math.max(1, (newest - oldest) / 86400000);
- perWeek = parseFloat((media.length / spanDays * 7).toFixed(1));
- perMonth = parseFloat((media.length / spanDays * 30).toFixed(1));
- }
-
- // Posts by day of week
- const dayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
- const dayBuckets = Array(7).fill(null).map(() => ({ count: 0, likes: 0, comments: 0 }));
- dates.forEach((d, i) => {
- const day = d.getDay();
- dayBuckets[day].count++;
- dayBuckets[day].likes += media[i]?.likeCount || 0;
- dayBuckets[day].comments += media[i]?.commentsCount || 0;
- });
- const postsByDayOfWeek = dayBuckets.map((b, i) => ({
- day: dayNames[i], shortDay: dayNames[i].slice(0, 3),
- posts: b.count,
- avgLikes: b.count > 0 ? Math.round(b.likes / b.count) : 0,
- avgComments: b.count > 0 ? Math.round(b.comments / b.count) : 0,
- avgEngagement: b.count > 0 ? Math.round((b.likes + b.comments) / b.count) : 0,
- }));
- const bestDayObj = postsByDayOfWeek.reduce((best, d) => d.avgEngagement > best.avgEngagement ? d : best, postsByDayOfWeek[0]);
- const bestPostingDay = bestDayObj?.day || '';
-
- // Posts by hour
- const hourBuckets = Array(24).fill(null).map(() => ({ count: 0, likes: 0, comments: 0 }));
- dates.forEach((d, i) => {
- const h = d.getHours();
- hourBuckets[h].count++;
- hourBuckets[h].likes += media[i]?.likeCount || 0;
- hourBuckets[h].comments += media[i]?.commentsCount || 0;
- });
- const postsByHour = hourBuckets.map((b, i) => ({
- hour: i, label: `${i}:00`,
- posts: b.count,
- avgEngagement: b.count > 0 ? Math.round((b.likes + b.comments) / b.count) : 0,
- }));
- const bestHourObj = postsByHour.reduce((best, h) => h.avgEngagement > best.avgEngagement ? h : best, postsByHour[0]);
- const bestPostingHour = bestHourObj?.posts > 0 ? bestHourObj.label : '';
-
- // Monthly breakdown / engagement timeline
- const monthMap = {};
- media.forEach(m => {
- const d = new Date(m.timestamp);
- if (isNaN(d)) return;
- const key = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`;
- if (!monthMap[key]) monthMap[key] = { posts: 0, likes: 0, comments: 0 };
- monthMap[key].posts++;
- monthMap[key].likes += m.likeCount;
- monthMap[key].comments += m.commentsCount;
- });
- const monthlyBreakdown = Object.entries(monthMap)
- .sort(([a], [b]) => a.localeCompare(b))
- .map(([month, s]) => ({
- month,
- posts: s.posts,
- likes: s.likes, comments: s.comments,
- avgLikes: Math.round(s.likes / s.posts),
- avgComments: Math.round(s.comments / s.posts),
- engagement: s.likes + s.comments,
- }));
- const engagementTimeline = monthlyBreakdown; // alias
-
- // Recent activity
- const now = Date.now();
- const postsLast7Days = dates.filter(d => (now - d.getTime()) <= 7 * 86400000).length;
- const postsLast30Days = dates.filter(d => (now - d.getTime()) <= 30 * 86400000).length;
- const postsLast90Days = dates.filter(d => (now - d.getTime()) <= 90 * 86400000).length;
-
- // Hashtag analysis
- const hashtagMap = {};
- media.forEach(m => {
- const tags = (m.caption || '').match(/#[\w\u00C0-\u024F]+/g) || [];
- tags.forEach(tag => {
- const t = tag.toLowerCase();
- if (!hashtagMap[t]) hashtagMap[t] = { tag: t, count: 0, likes: 0, comments: 0 };
- hashtagMap[t].count++;
- hashtagMap[t].likes += m.likeCount;
- hashtagMap[t].comments += m.commentsCount;
- });
- });
- const hashtagAnalysis = Object.values(hashtagMap)
- .map(h => ({ ...h, avgEngagement: Math.round((h.likes + h.comments) / h.count) }))
- .sort((a, b) => b.count - a.count)
- .slice(0, 20);
-
- // Caption length correlation
- const captionBuckets = [
- { label: 'No caption', min: 0, max: 0 },
- { label: 'Short (1-50)', min: 1, max: 50 },
- { label: 'Medium (51-150)', min: 51, max: 150 },
- { label: 'Long (151-300)', min: 151, max: 300 },
- { label: 'Very Long (300+)', min: 301, max: Infinity },
- ];
- const captionLengthCorrelation = captionBuckets.map(bucket => {
- const posts = media.filter(m => {
- const len = (m.caption || '').length;
- return len >= bucket.min && len <= bucket.max;
- });
- return {
- label: bucket.label, count: posts.length,
- avgLikes: posts.length > 0 ? Math.round(posts.reduce((s, m) => s + m.likeCount, 0) / posts.length) : 0,
- avgComments: posts.length > 0 ? Math.round(posts.reduce((s, m) => s + m.commentsCount, 0) / posts.length) : 0,
- avgEngagement: posts.length > 0 ? Math.round(posts.reduce((s, m) => s + m.likeCount + m.commentsCount, 0) / posts.length) : 0,
- };
- }).filter(b => b.count > 0);
-
- // Top + worst posts
- const topPosts = [...media]
- .map(m => ({ ...m, engagement: m.likeCount + m.commentsCount }))
- .sort((a, b) => b.engagement - a.engagement)
- .slice(0, 10);
- const worstByLikes = byLikes.length > 0 ? byLikes[byLikes.length - 1] : null;
-
- // Virality score (best / avg)
- const bestEngagement = topPosts[0] ? topPosts[0].engagement : 0;
- const viralityScore = avgEngagement > 0 ? parseFloat((bestEngagement / avgEngagement).toFixed(1)) : 0;
-
- // Consistency score (0-100) based on std deviation of engagement
- let consistencyScore = 0;
- if (media.length >= 3) {
- const engagements = media.map(m => m.likeCount + m.commentsCount);
- const mean = engagements.reduce((s, v) => s + v, 0) / engagements.length;
- const variance = engagements.reduce((s, v) => s + Math.pow(v - mean, 2), 0) / engagements.length;
- const stdDev = Math.sqrt(variance);
- const cv = mean > 0 ? stdDev / mean : 1; // coefficient of variation
- consistencyScore = Math.max(0, Math.min(100, Math.round((1 - Math.min(cv, 1)) * 100)));
- }
-
- return {
- totalPosts: profile.mediaCount || media.length,
- fetchedPosts: media.length,
- totalLikes, totalComments, totalEngagement,
- avgLikes, avgComments, avgEngagement,
- medianLikes, medianComments,
- engagementRate, likesPerFollower, commentsPerFollower,
- likesToCommentsRatio,
- bestByLikes: byLikes[0] || null,
- bestByComments: byComments[0] || null,
- worstByLikes,
- recentMedia: media.slice(0, 20),
- mediaTypeDistribution: mediaTypes,
- performanceByType,
- postFrequency: { perWeek, perMonth },
- topPosts,
- postsByDayOfWeek, bestPostingDay,
- postsByHour, bestPostingHour,
- engagementTimeline, monthlyBreakdown,
- postsLast7Days, postsLast30Days, postsLast90Days,
- hashtagAnalysis,
- captionLengthCorrelation,
- viralityScore, consistencyScore,
- };
-}
-
-// ─── YouTube API Helpers ─────────────────────────────────────────────────────
-
-async function ytFetch(endpoint, params, apiKey) {
- const url = new URL(`https://www.googleapis.com/youtube/v3/${endpoint}`);
- params.key = apiKey;
- Object.entries(params).forEach(([k, v]) => url.searchParams.set(k, v));
- const res = await fetch(url.toString());
- const data = await res.json();
- if (data.error) throw new Error(data.error.message);
- return data;
-}
-
-function extractChannelId(input) {
- if (!input) return null;
- input = input.trim();
- // Direct channel ID
- if (/^UC[\w-]{22}$/.test(input)) return input;
- // URL patterns
- const patterns = [
- /youtube\.com\/channel\/(UC[\w-]{22})/,
- /youtube\.com\/@([\w.-]+)/,
- /youtube\.com\/c\/([\w.-]+)/,
- /youtube\.com\/user\/([\w.-]+)/,
- /youtube\.com\/([\w.-]+)/,
- ];
- for (const p of patterns) {
- const m = input.match(p);
- if (m) return m[1];
- }
- return input;
-}
-
-async function resolveChannelId(input, apiKey) {
- const extracted = extractChannelId(input);
- if (!extracted) throw new Error('Invalid input');
-
- // If it's already a channel ID
- if (/^UC[\w-]{22}$/.test(extracted)) return extracted;
-
- // Try as custom URL / username / handle
- // Search for channel by handle
- try {
- const data = await ytFetch('channels', { part: 'id', forHandle: extracted }, apiKey);
- if (data.items && data.items.length > 0) return data.items[0].id;
- } catch { }
-
- try {
- const data = await ytFetch('channels', { part: 'id', forUsername: extracted }, apiKey);
- if (data.items && data.items.length > 0) return data.items[0].id;
- } catch { }
-
- // Search as last resort
- try {
- const data = await ytFetch('search', { part: 'snippet', q: extracted, type: 'channel', maxResults: '1' }, apiKey);
- if (data.items && data.items.length > 0) return data.items[0].snippet.channelId;
- } catch { }
-
- throw new Error('Could not resolve channel. Please provide a valid Channel ID (starts with UC).');
-}
-
-async function fetchChannelData(channelId, apiKey) {
- const data = await ytFetch('channels', {
- part: 'snippet,statistics,contentDetails,brandingSettings,status,topicDetails',
- id: channelId,
- }, apiKey);
-
- if (!data.items || data.items.length === 0) throw new Error('Channel not found');
- const ch = data.items[0];
-
- return {
- channelId: ch.id,
- title: ch.snippet.title,
- description: ch.snippet.description,
- customUrl: ch.snippet.customUrl || '',
- publishedAt: ch.snippet.publishedAt,
- country: ch.snippet.country || 'Unknown',
- thumbnails: {
- default: ch.snippet.thumbnails?.default?.url || '',
- medium: ch.snippet.thumbnails?.medium?.url || '',
- high: ch.snippet.thumbnails?.high?.url || '',
- },
- subscriberCount: parseInt(ch.statistics.subscriberCount) || 0,
- viewCount: parseInt(ch.statistics.viewCount) || 0,
- videoCount: parseInt(ch.statistics.videoCount) || 0,
- hiddenSubscriberCount: ch.statistics.hiddenSubscriberCount || false,
- uploadsPlaylistId: ch.contentDetails?.relatedPlaylists?.uploads || '',
- keywords: ch.brandingSettings?.channel?.keywords || '',
- bannerUrl: ch.brandingSettings?.image?.bannerExternalUrl || '',
- madeForKids: ch.status?.madeForKids || false,
- topicCategories: ch.topicDetails?.topicCategories || [],
- isLinked: ch.status?.isLinked || false,
- };
-}
-
-async function fetchAllVideos(playlistId, apiKey, maxPages = 10) {
- let allVideos = [];
- let pageToken = '';
- let page = 0;
-
- while (page < maxPages) {
- const params = {
- part: 'snippet,contentDetails',
- playlistId,
- maxResults: '50',
- };
- if (pageToken) params.pageToken = pageToken;
-
- const data = await ytFetch('playlistItems', params, apiKey);
- if (!data.items || data.items.length === 0) break;
-
- const videoIds = data.items.map(i => i.snippet.resourceId.videoId).join(',');
-
- // Fetch detailed video stats
- const statsData = await ytFetch('videos', {
- part: 'statistics,contentDetails,snippet,status',
- id: videoIds,
- }, apiKey);
-
- if (statsData.items) {
- allVideos = allVideos.concat(statsData.items.map(v => ({
- videoId: v.id,
- title: v.snippet.title,
- description: v.snippet.description?.substring(0, 200) || '',
- publishedAt: v.snippet.publishedAt,
- channelTitle: v.snippet.channelTitle,
- thumbnails: {
- default: v.snippet.thumbnails?.default?.url || '',
- medium: v.snippet.thumbnails?.medium?.url || '',
- high: v.snippet.thumbnails?.high?.url || '',
- },
- tags: v.snippet.tags || [],
- categoryId: v.snippet.categoryId || '',
- liveBroadcastContent: v.snippet.liveBroadcastContent || 'none',
- defaultAudioLanguage: v.snippet.defaultAudioLanguage || '',
- duration: v.contentDetails.duration,
- dimension: v.contentDetails.dimension || '2d',
- definition: v.contentDetails.definition || 'hd',
- caption: v.contentDetails.caption === 'true',
- licensedContent: v.contentDetails.licensedContent || false,
- projection: v.contentDetails.projection || 'rectangular',
- viewCount: parseInt(v.statistics.viewCount) || 0,
- likeCount: parseInt(v.statistics.likeCount) || 0,
- commentCount: parseInt(v.statistics.commentCount) || 0,
- privacyStatus: v.status?.privacyStatus || 'public',
- embeddable: v.status?.embeddable || false,
- madeForKids: v.status?.madeForKids || false,
- })));
- }
-
- pageToken = data.nextPageToken || '';
- if (!pageToken) break;
- page++;
- }
-
- return allVideos;
-}
-
-function parseDuration(iso) {
- const m = iso.match(/PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?/);
- if (!m) return 0;
- return (parseInt(m[1] || 0) * 3600) + (parseInt(m[2] || 0) * 60) + parseInt(m[3] || 0);
-}
-
-function computeVideoAnalytics(videos) {
- if (!videos || videos.length === 0) {
- return {
- totalVideos: 0, totalViews: 0, totalLikes: 0, totalComments: 0,
- avgViews: 0, avgLikes: 0, avgComments: 0, medianViews: 0,
- totalEngagement: 0, overallEngagementRate: 0,
- avgDurationSeconds: 0, avgDurationFormatted: '0:00',
- totalDurationSeconds: 0, totalDurationFormatted: '0:00',
- bestByViews: null, bestByLikes: null, bestByComments: null,
- bestByEngagement: null, worstByViews: null,
- mostRecent: null, oldest: null,
- top10ByViews: [], top10ByLikes: [], top10ByComments: [], top10ByEngagement: [],
- shortsCount: 0, regularCount: 0,
- avgShortViews: 0, avgRegularViews: 0,
- hdCount: 0, sdCount: 0, hdPercentage: 0,
- captionCount: 0, captionPercentage: 0,
- licensedCount: 0, licensedPercentage: 0,
- madeForKidsCount: 0, embeddableCount: 0,
- publishDayDistribution: {}, publishHourDistribution: {},
- peakPublishDay: '', peakPublishHour: 0,
- durationDistribution: { short: 0, medium: 0, long: 0, veryLong: 0 },
- categoryDistribution: {},
- tagFrequency: [],
- videosLast7Days: 0, videosLast30Days: 0, videosLast90Days: 0, videosLast365Days: 0,
- uploadFrequencyPerWeek: 0, uploadFrequencyPerMonth: 0,
- consistencyScore: 0,
- viralityScore: 0,
- viewsDistribution: { ranges: [], counts: [] },
- engagementTrend: [],
- viewsTrend: [],
- likeRateTrend: [],
- };
- }
-
- const now = new Date();
- const durations = videos.map(v => parseDuration(v.duration));
- const totalDuration = durations.reduce((a, b) => a + b, 0);
- // Engagement rates — compute FIRST so all sorted arrays have the fields
- const withEngagement = videos.map(v => ({
- ...v,
- engagementRate: v.viewCount > 0 ? ((v.likeCount + v.commentCount) / v.viewCount) * 100 : 0,
- likeRate: v.viewCount > 0 ? (v.likeCount / v.viewCount) * 100 : 0,
- commentRate: v.viewCount > 0 ? (v.commentCount / v.viewCount) * 100 : 0,
- durationSeconds: parseDuration(v.duration),
- daysSinceUpload: Math.max(1, Math.floor((now - new Date(v.publishedAt)) / 86400000)),
- }));
- const viewsSorted = [...withEngagement].sort((a, b) => b.viewCount - a.viewCount);
- const likesSorted = [...withEngagement].sort((a, b) => b.likeCount - a.likeCount);
- const commentsSorted = [...withEngagement].sort((a, b) => b.commentCount - a.commentCount);
- const dateSorted = [...withEngagement].sort((a, b) => new Date(b.publishedAt) - new Date(a.publishedAt));
- const engagementSorted = [...withEngagement].sort((a, b) => b.engagementRate - a.engagementRate);
-
- const totalViews = videos.reduce((s, v) => s + v.viewCount, 0);
- const totalLikes = videos.reduce((s, v) => s + v.likeCount, 0);
- const totalComments = videos.reduce((s, v) => s + v.commentCount, 0);
- const avgViews = Math.round(totalViews / videos.length);
- const avgLikes = Math.round(totalLikes / videos.length);
- const avgComments = Math.round(totalComments / videos.length);
-
- // Median
- const sortedViews = [...videos].map(v => v.viewCount).sort((a, b) => a - b);
- const mid = Math.floor(sortedViews.length / 2);
- const medianViews = sortedViews.length % 2 ? sortedViews[mid] : Math.round((sortedViews[mid - 1] + sortedViews[mid]) / 2);
-
- // Shorts vs Regular
- const shorts = withEngagement.filter(v => v.durationSeconds <= 60);
- const regular = withEngagement.filter(v => v.durationSeconds > 60);
-
- // Duration distribution
- const durationDist = { short: 0, medium: 0, long: 0, veryLong: 0 };
- withEngagement.forEach(v => {
- if (v.durationSeconds <= 60) durationDist.short++;
- else if (v.durationSeconds <= 600) durationDist.medium++;
- else if (v.durationSeconds <= 3600) durationDist.long++;
- else durationDist.veryLong++;
- });
-
- // HD/SD, captions, licensed, etc.
- const hdCount = videos.filter(v => v.definition === 'hd').length;
- const captionCount = videos.filter(v => v.caption).length;
- const licensedCount = videos.filter(v => v.licensedContent).length;
- const madeForKidsCount = videos.filter(v => v.madeForKids).length;
- const embeddableCount = videos.filter(v => v.embeddable).length;
-
- // Publish day/hour distribution
- const dayDist = {};
- const hourDist = {};
- const dayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
- videos.forEach(v => {
- const d = new Date(v.publishedAt);
- const day = dayNames[d.getUTCDay()];
- const hour = d.getUTCHours();
- dayDist[day] = (dayDist[day] || 0) + 1;
- hourDist[hour] = (hourDist[hour] || 0) + 1;
- });
-
- const peakDay = Object.entries(dayDist).sort((a, b) => b[1] - a[1])[0];
- const peakHour = Object.entries(hourDist).sort((a, b) => b[1] - a[1])[0];
-
- // Category distribution
- const catDist = {};
- videos.forEach(v => {
- const cat = v.categoryId || 'Unknown';
- catDist[cat] = (catDist[cat] || 0) + 1;
- });
-
- // Tag frequency
- const tagMap = {};
- videos.forEach(v => {
- (v.tags || []).forEach(t => {
- const lower = t.toLowerCase();
- tagMap[lower] = (tagMap[lower] || 0) + 1;
- });
- });
- const tagFrequency = Object.entries(tagMap)
- .sort((a, b) => b[1] - a[1])
- .slice(0, 30)
- .map(([tag, count]) => ({ tag, count }));
-
- // Recent videos count
- const msDay = 86400000;
- const videosLast7 = videos.filter(v => (now - new Date(v.publishedAt)) < 7 * msDay).length;
- const videosLast30 = videos.filter(v => (now - new Date(v.publishedAt)) < 30 * msDay).length;
- const videosLast90 = videos.filter(v => (now - new Date(v.publishedAt)) < 90 * msDay).length;
- const videosLast365 = videos.filter(v => (now - new Date(v.publishedAt)) < 365 * msDay).length;
-
- // Upload frequency
- const oldestDate = new Date(dateSorted[dateSorted.length - 1]?.publishedAt || now);
- const totalWeeks = Math.max(1, (now - oldestDate) / (7 * msDay));
- const totalMonths = Math.max(1, totalWeeks / 4.33);
-
- // Consistency score (0-100) based on how regular uploads are
- const weeklyUploads = videos.reduce((acc, v) => {
- const weekNum = Math.floor((now - new Date(v.publishedAt)) / (7 * msDay));
- acc[weekNum] = (acc[weekNum] || 0) + 1;
- return acc;
- }, {});
- const weekValues = Object.values(weeklyUploads);
- const avgWeekly = weekValues.reduce((a, b) => a + b, 0) / Math.max(1, weekValues.length);
- const variance = weekValues.reduce((s, v) => s + Math.pow(v - avgWeekly, 2), 0) / Math.max(1, weekValues.length);
- const stdDev = Math.sqrt(variance);
- const consistencyScore = Math.max(0, Math.min(100, Math.round(100 - (stdDev / Math.max(0.01, avgWeekly)) * 25)));
-
- // Virality score
- const viralityScore = avgViews > 0 ? Math.round((viewsSorted[0]?.viewCount || 0) / avgViews * 10) / 10 : 0;
-
- // Views distribution for histogram
- const maxViews = viewsSorted[0]?.viewCount || 0;
- const step = Math.max(1, Math.ceil(maxViews / 10));
- const viewsRanges = [];
- const viewsCounts = [];
- for (let i = 0; i < 10; i++) {
- const low = i * step;
- const high = (i + 1) * step;
- viewsRanges.push(`${formatCompact(low)}-${formatCompact(high)}`);
- viewsCounts.push(videos.filter(v => v.viewCount >= low && v.viewCount < high).length);
- }
-
- // Trends (monthly aggregation for last 12 months)
- const monthlyData = {};
- withEngagement.forEach(v => {
- const d = new Date(v.publishedAt);
- const key = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`;
- if (!monthlyData[key]) monthlyData[key] = { views: 0, likes: 0, comments: 0, count: 0 };
- monthlyData[key].views += v.viewCount;
- monthlyData[key].likes += v.likeCount;
- monthlyData[key].comments += v.commentCount;
- monthlyData[key].count++;
- });
- const sortedMonths = Object.keys(monthlyData).sort();
- const viewsTrend = sortedMonths.map(m => ({ month: m, value: monthlyData[m].views, count: monthlyData[m].count }));
- const engagementTrend = sortedMonths.map(m => ({
- month: m,
- value: monthlyData[m].views > 0
- ? ((monthlyData[m].likes + monthlyData[m].comments) / monthlyData[m].views * 100).toFixed(2)
- : 0,
- }));
- const likeRateTrend = sortedMonths.map(m => ({
- month: m,
- value: monthlyData[m].views > 0 ? ((monthlyData[m].likes / monthlyData[m].views) * 100).toFixed(2) : 0,
- }));
-
- const formatVid = (v) => v ? {
- videoId: v.videoId, title: v.title, viewCount: v.viewCount,
- likeCount: v.likeCount, commentCount: v.commentCount,
- publishedAt: v.publishedAt,
- thumbnail: v.thumbnails?.medium || v.thumbnails?.default || '',
- engagementRate: v.engagementRate?.toFixed(2) || 0,
- durationSeconds: v.durationSeconds || parseDuration(v.duration),
- } : null;
-
- const formatDuration = (s) => {
- const h = Math.floor(s / 3600);
- const m = Math.floor((s % 3600) / 60);
- const sec = s % 60;
- return h > 0 ? `${h}h ${m}m` : `${m}m ${sec}s`;
- };
-
- return {
- totalVideos: videos.length,
- totalViews, totalLikes, totalComments,
- avgViews, avgLikes, avgComments, medianViews,
- totalEngagement: totalLikes + totalComments,
- overallEngagementRate: totalViews > 0 ? ((totalLikes + totalComments) / totalViews * 100).toFixed(2) : 0,
- avgDurationSeconds: Math.round(totalDuration / videos.length),
- avgDurationFormatted: formatDuration(Math.round(totalDuration / videos.length)),
- totalDurationSeconds: totalDuration,
- totalDurationFormatted: formatDuration(totalDuration),
- estimatedTotalWatchTimeHours: Math.round((totalDuration * totalViews) / 3600),
- bestByViews: formatVid(viewsSorted[0]),
- bestByLikes: formatVid(likesSorted[0]),
- bestByComments: formatVid(commentsSorted[0]),
- bestByEngagement: formatVid(engagementSorted[0]),
- worstByViews: formatVid(viewsSorted[viewsSorted.length - 1]),
- mostRecent: formatVid(dateSorted[0]),
- oldest: formatVid(dateSorted[dateSorted.length - 1]),
- top10ByViews: viewsSorted.slice(0, 10).map(formatVid),
- top10ByLikes: likesSorted.slice(0, 10).map(formatVid),
- top10ByComments: commentsSorted.slice(0, 10).map(formatVid),
- top10ByEngagement: engagementSorted.slice(0, 10).map(formatVid),
- shortsCount: shorts.length,
- regularCount: regular.length,
- avgShortViews: shorts.length > 0 ? Math.round(shorts.reduce((s, v) => s + v.viewCount, 0) / shorts.length) : 0,
- avgRegularViews: regular.length > 0 ? Math.round(regular.reduce((s, v) => s + v.viewCount, 0) / regular.length) : 0,
- avgShortLikes: shorts.length > 0 ? Math.round(shorts.reduce((s, v) => s + v.likeCount, 0) / shorts.length) : 0,
- avgRegularLikes: regular.length > 0 ? Math.round(regular.reduce((s, v) => s + v.likeCount, 0) / regular.length) : 0,
- hdCount, sdCount: videos.length - hdCount,
- hdPercentage: ((hdCount / videos.length) * 100).toFixed(1),
- captionCount, captionPercentage: ((captionCount / videos.length) * 100).toFixed(1),
- licensedCount, licensedPercentage: ((licensedCount / videos.length) * 100).toFixed(1),
- madeForKidsCount, embeddableCount,
- embeddablePercentage: ((embeddableCount / videos.length) * 100).toFixed(1),
- publishDayDistribution: dayDist,
- publishHourDistribution: hourDist,
- peakPublishDay: peakDay ? peakDay[0] : '',
- peakPublishHour: peakHour ? parseInt(peakHour[0]) : 0,
- durationDistribution: durationDist,
- categoryDistribution: catDist,
- tagFrequency,
- videosLast7Days: videosLast7,
- videosLast30Days: videosLast30,
- videosLast90Days: videosLast90,
- videosLast365Days: videosLast365,
- uploadFrequencyPerWeek: (videos.length / totalWeeks).toFixed(1),
- uploadFrequencyPerMonth: (videos.length / totalMonths).toFixed(1),
- consistencyScore,
- viralityScore,
- viewsDistribution: { ranges: viewsRanges, counts: viewsCounts },
- viewsTrend,
- engagementTrend,
- likeRateTrend,
- };
-}
-
-function formatCompact(n) {
- if (n >= 1e6) return (n / 1e6).toFixed(1) + 'M';
- if (n >= 1e3) return (n / 1e3).toFixed(1) + 'K';
- return n.toString();
-}
-
-// ─── API ROUTES ──────────────────────────────────────────────────────────────
-
-// API Keys
-app.get('/api/keys', async (req, res) => {
- const keys = await readJSON(API_KEYS_FILE);
- res.json({
- youtube: keys?.youtube || '',
- configured: !!keys?.youtube,
- instagram: {
- appId: keys?.instagram?.appId || '',
- appSecret: keys?.instagram?.appSecret || '',
- configured: !!(keys?.instagram?.appId && keys?.instagram?.appSecret),
- },
- cloudinary: {
- cloudName: keys?.cloudinary?.cloudName || '',
- uploadPreset: keys?.cloudinary?.uploadPreset || '',
- configured: !!(keys?.cloudinary?.cloudName && keys?.cloudinary?.uploadPreset),
- },
- github: {
- token: keys?.github?.token || '',
- repo: keys?.github?.repo || '',
- branch: keys?.github?.branch || 'main',
- configured: !!(keys?.github?.token && keys?.github?.repo),
- },
- });
-});
-
-app.post('/api/keys', async (req, res) => {
- const { youtube, instagram, cloudinary } = req.body;
- const keys = await readJSON(API_KEYS_FILE) || {};
- if (youtube !== undefined) keys.youtube = youtube;
- if (instagram !== undefined) {
- if (!keys.instagram) keys.instagram = {};
- if (instagram.appId !== undefined) keys.instagram.appId = instagram.appId;
- if (instagram.appSecret !== undefined) keys.instagram.appSecret = instagram.appSecret;
- }
- if (cloudinary !== undefined) {
- if (!keys.cloudinary) keys.cloudinary = {};
- if (cloudinary.cloudName !== undefined) keys.cloudinary.cloudName = cloudinary.cloudName;
- if (cloudinary.uploadPreset !== undefined) keys.cloudinary.uploadPreset = cloudinary.uploadPreset;
- }
- const { github } = req.body;
- if (github !== undefined) {
- if (!keys.github) keys.github = { branch: 'main' };
- if (github.token !== undefined) keys.github.token = github.token;
- if (github.repo !== undefined) keys.github.repo = github.repo;
- if (github.branch !== undefined) keys.github.branch = github.branch || 'main';
- }
- const ok = await writeJSON(API_KEYS_FILE, keys);
- res.json({ success: ok, message: ok ? 'API keys saved' : 'Failed to save' });
-});
-
-// Accounts
-app.get('/api/accounts', async (req, res) => {
- const accounts = await readJSON(ACCOUNTS_FILE) || [];
- // Mask access tokens in response
- const safe = accounts.map(a => {
- const copy = { ...a };
- if (copy.accessToken) delete copy.accessToken;
- return copy;
- });
- res.json(safe);
-});
-
-// Resolve channel from URL or ID
-app.post('/api/resolve-channel', async (req, res) => {
- try {
- const { input } = req.body;
- const apiKey = await getAPIKey();
- if (!apiKey) return res.status(400).json({ success: false, message: 'YouTube API key not configured' });
-
- const channelId = await resolveChannelId(input, apiKey);
- const channelData = await fetchChannelData(channelId, apiKey);
- res.json({ success: true, data: channelData });
- } catch (err) {
- res.status(400).json({ success: false, message: err.message });
- }
-});
-
-// Add account
-app.post('/api/accounts', async (req, res) => {
- try {
- const { input } = req.body;
- const apiKey = await getAPIKey();
- if (!apiKey) return res.status(400).json({ success: false, message: 'YouTube API key not configured' });
-
- const channelId = await resolveChannelId(input, apiKey);
- const channelData = await fetchChannelData(channelId, apiKey);
- const accounts = await readJSON(ACCOUNTS_FILE);
-
- // Prevent duplicates
- if (accounts.find(a => a.channelId === channelId)) {
- return res.status(400).json({ success: false, message: 'This channel is already added' });
- }
-
- const newAccount = {
- id: Date.now().toString(),
- channelId: channelData.channelId,
- title: channelData.title,
- description: channelData.description,
- customUrl: channelData.customUrl,
- publishedAt: channelData.publishedAt,
- country: channelData.country,
- thumbnails: channelData.thumbnails,
- subscriberCount: channelData.subscriberCount,
- viewCount: channelData.viewCount,
- videoCount: channelData.videoCount,
- hiddenSubscriberCount: channelData.hiddenSubscriberCount,
- uploadsPlaylistId: channelData.uploadsPlaylistId,
- keywords: channelData.keywords,
- topicCategories: channelData.topicCategories,
- madeForKids: channelData.madeForKids,
- addedAt: new Date().toISOString(),
- lastUpdated: new Date().toISOString(),
- };
-
- accounts.push(newAccount);
- await writeJSON(ACCOUNTS_FILE, accounts);
- syncEverythingToGitHub().catch(() => { });
-
- res.json({ success: true, account: newAccount });
- } catch (err) {
- res.status(400).json({ success: false, message: err.message });
- }
-});
-
-// Add Instagram account via access token
-// Uses Instagram API with Instagram Login — token from App Dashboard or Business Login flow
-app.post('/api/accounts/instagram', async (req, res) => {
- try {
- const { accessToken } = req.body;
- if (!accessToken) return res.status(400).json({ success: false, message: 'Access token is required' });
-
- const { appSecret } = await getIGAppCredentials();
-
- // Step 1: Try to exchange for long-lived token (if app secret is configured)
- // Tokens from App Dashboard are already long-lived (60 days)
- // Tokens from Business Login flow are short-lived (1 hour) and need exchange
- let finalToken = accessToken;
- let expiresIn = 0;
- if (appSecret) {
- try {
- const longToken = await exchangeForLongLivedToken(accessToken, appSecret);
- finalToken = longToken.accessToken;
- expiresIn = longToken.expiresIn;
- console.log('Token exchanged for long-lived token successfully');
- } catch (err) {
- // Token might already be long-lived (from App Dashboard) — use as-is
- console.log('Token exchange skipped (token may already be long-lived):', err.message);
- }
- } else {
- console.log('No Instagram App Secret configured — using token as-is (configure App Secret in Settings for long-lived tokens)');
- }
-
- // Step 2: Fetch profile using /me — no Facebook Pages discovery needed
- const profile = await fetchInstagramProfile(null, finalToken);
-
- if (!profile.igUserId) {
- throw new Error('Could not get Instagram User ID. Make sure the token has instagram_business_basic permission and is from a Business/Creator account.');
- }
-
- const accounts = await readJSON(ACCOUNTS_FILE);
-
- // Prevent duplicates
- if (accounts.find(a => a.platform === 'instagram' && a.igUserId === profile.igUserId)) {
- return res.status(400).json({ success: false, message: 'This Instagram account is already added' });
- }
-
- const newAccount = {
- id: Date.now().toString(),
- platform: 'instagram',
- igUserId: profile.igUserId,
- username: profile.username,
- title: profile.name || profile.username,
- biography: profile.biography,
- website: profile.website,
- profilePictureUrl: profile.profilePictureUrl,
- followersCount: profile.followersCount,
- followsCount: profile.followsCount,
- mediaCount: profile.mediaCount,
- accessToken: finalToken,
- tokenExpiresAt: expiresIn > 0
- ? new Date(Date.now() + expiresIn * 1000).toISOString()
- : null,
- addedAt: new Date().toISOString(),
- lastUpdated: new Date().toISOString(),
- };
-
- accounts.push(newAccount);
- await writeJSON(ACCOUNTS_FILE, accounts);
- syncEverythingToGitHub().catch(() => { });
-
- // Mask token in response
- const safeAccount = { ...newAccount };
- delete safeAccount.accessToken;
- res.json({ success: true, account: safeAccount });
- } catch (err) {
- res.status(400).json({ success: false, message: err.message });
- }
-});
-
-// Refresh Instagram token (extend long-lived token for another 60 days)
-// Uses: GET graph.instagram.com/refresh_access_token?grant_type=ig_refresh_token
-app.post('/api/accounts/:id/refresh-ig-token', async (req, res) => {
- try {
- const accounts = await readJSON(ACCOUNTS_FILE);
- const account = accounts.find(a => a.id === req.params.id && a.platform === 'instagram');
- if (!account) return res.status(404).json({ success: false, message: 'Instagram account not found' });
- if (!account.accessToken) return res.status(400).json({ success: false, message: 'No access token stored' });
-
- // Refresh long-lived token — must be at least 24 hours old and not expired
- const refreshed = await refreshLongLivedToken(account.accessToken);
-
- account.accessToken = refreshed.accessToken;
- account.tokenExpiresAt = new Date(Date.now() + (refreshed.expiresIn || 5184000) * 1000).toISOString();
- await writeJSON(ACCOUNTS_FILE, accounts);
- syncEverythingToGitHub().catch(() => { });
- res.json({ success: true, message: 'Token refreshed for another 60 days', expiresAt: account.tokenExpiresAt });
- } catch (err) {
- res.status(400).json({ success: false, message: err.message });
- }
-});
-
-// Delete account
-app.delete('/api/accounts/:id', async (req, res) => {
- try {
- const accounts = await readJSON(ACCOUNTS_FILE);
- const account = accounts.find(a => a.id === req.params.id);
- if (!account) return res.status(404).json({ success: false, message: 'Not found' });
- const filtered = accounts.filter(a => a.id !== req.params.id);
- await writeJSON(ACCOUNTS_FILE, filtered);
- syncEverythingToGitHub().catch(() => { });
-
- // Clean caches
- const cache = await readJSON(VIDEOS_CACHE_FILE);
- delete cache[req.params.id];
- await writeJSON(VIDEOS_CACHE_FILE, cache);
-
- const igCache = await readJSON(IG_CACHE_FILE) || {};
- delete igCache[req.params.id];
- await writeJSON(IG_CACHE_FILE, igCache);
-
- res.json({ success: true });
- } catch (err) {
- res.status(500).json({ success: false, message: err.message });
- }
-});
-
-// Update single account
-app.post('/api/accounts/:id/refresh', async (req, res) => {
- try {
- const accounts = await readJSON(ACCOUNTS_FILE);
- const account = accounts.find(a => a.id === req.params.id);
- if (!account) return res.status(404).json({ success: false, message: 'Not found' });
-
- if (account.platform === 'instagram') {
- // Refresh Instagram account
- if (!account.accessToken) return res.status(400).json({ success: false, message: 'No access token' });
- const profile = await fetchInstagramProfile(account.igUserId, account.accessToken);
- account.followersCount = profile.followersCount;
- account.followsCount = profile.followsCount;
- account.mediaCount = profile.mediaCount;
- account.title = profile.name || profile.username;
- account.username = profile.username;
- account.profilePictureUrl = profile.profilePictureUrl;
- account.biography = profile.biography;
- account.website = profile.website;
- account.lastUpdated = new Date().toISOString();
- } else {
- // Refresh YouTube account
- const apiKey = await getAPIKey();
- if (!apiKey) return res.status(400).json({ success: false, message: 'No API key' });
- const channelData = await fetchChannelData(account.channelId, apiKey);
- account.subscriberCount = channelData.subscriberCount;
- account.viewCount = channelData.viewCount;
- account.videoCount = channelData.videoCount;
- account.title = channelData.title;
- account.description = channelData.description;
- account.thumbnails = channelData.thumbnails;
- account.customUrl = channelData.customUrl;
- account.country = channelData.country;
- account.keywords = channelData.keywords;
- account.topicCategories = channelData.topicCategories;
- }
- account.lastUpdated = new Date().toISOString();
- await writeJSON(ACCOUNTS_FILE, accounts);
+// ─── Routes ──────────────────────────────────────────────────────────────────
- // Mask IG token in response
- const safeAccount = { ...account };
- if (safeAccount.accessToken) delete safeAccount.accessToken;
- res.json({ success: true, account: safeAccount });
- } catch (err) {
- res.status(400).json({ success: false, message: err.message });
- }
-});
-
-// Refresh all
-app.post('/api/accounts/refresh-all', async (req, res) => {
- try {
- const apiKey = await getAPIKey();
- const accounts = await readJSON(ACCOUNTS_FILE);
- const results = [];
-
- for (const account of accounts) {
- try {
- if (account.platform === 'instagram') {
- if (!account.accessToken) throw new Error('No access token');
- const profile = await fetchInstagramProfile(account.igUserId, account.accessToken);
- account.followersCount = profile.followersCount;
- account.followsCount = profile.followsCount;
- account.mediaCount = profile.mediaCount;
- account.title = profile.name || profile.username;
- account.username = profile.username;
- account.profilePictureUrl = profile.profilePictureUrl;
- } else {
- if (!apiKey) throw new Error('No YouTube API key');
- const channelData = await fetchChannelData(account.channelId, apiKey);
- account.subscriberCount = channelData.subscriberCount;
- account.viewCount = channelData.viewCount;
- account.videoCount = channelData.videoCount;
- account.title = channelData.title;
- account.thumbnails = channelData.thumbnails;
- }
- account.lastUpdated = new Date().toISOString();
- results.push({ id: account.id, success: true });
- } catch (err) {
- results.push({ id: account.id, success: false, error: err.message });
- }
- }
-
- await writeJSON(ACCOUNTS_FILE, accounts);
- // Mask IG tokens in response
- const safeAccounts = accounts.map(a => {
- const safe = { ...a };
- if (safe.accessToken) delete safe.accessToken;
- return safe;
- });
- res.json({ success: true, accounts: safeAccounts, results, updatedAt: new Date().toISOString() });
- } catch (err) {
- res.status(500).json({ success: false, message: err.message });
- }
-});
-
-// Get full analytics for an account
-app.get('/api/accounts/:id/analytics', async (req, res) => {
- try {
- const apiKey = await getAPIKey();
- if (!apiKey) return res.status(400).json({ success: false, message: 'No API key' });
-
- const accounts = await readJSON(ACCOUNTS_FILE);
- const account = accounts.find(a => a.id === req.params.id);
- if (!account) return res.status(404).json({ success: false, message: 'Not found' });
-
- // Fetch all videos (up to 500)
- const videos = await fetchAllVideos(account.uploadsPlaylistId, apiKey, 10);
-
- // Cache videos
- const cache = await readJSON(VIDEOS_CACHE_FILE) || {};
- cache[req.params.id] = { videos, fetchedAt: new Date().toISOString() };
- await writeJSON(VIDEOS_CACHE_FILE, cache);
-
- // Compute analytics
- const analytics = computeVideoAnalytics(videos);
-
- // If publishedAt is missing, fetch it
- if (!account.publishedAt) {
- try {
- const channelData = await fetchChannelData(account.channelId, apiKey);
- account.publishedAt = channelData.publishedAt;
- account.subscriberCount = channelData.subscriberCount;
- account.viewCount = channelData.viewCount;
- account.videoCount = channelData.videoCount;
- account.title = channelData.title;
- account.thumbnails = channelData.thumbnails;
- account.customUrl = channelData.customUrl;
- account.country = channelData.country;
- account.lastUpdated = new Date().toISOString();
- await writeJSON(ACCOUNTS_FILE, accounts);
- } catch (e) {
- console.error('Failed to backfill channel data:', e.message);
- }
- }
-
- // Channel-level computed metrics
- const channelAge = account.publishedAt
- ? Math.floor((Date.now() - new Date(account.publishedAt).getTime()) / 86400000)
- : 365;
- const viewsPerSub = account.subscriberCount > 0 ? (account.viewCount / account.subscriberCount).toFixed(1) : 0;
- const subsPerView = account.viewCount > 0 ? (account.subscriberCount / account.viewCount * 100).toFixed(4) : 0;
- const avgViewsPerVideo = account.videoCount > 0 ? Math.round(account.viewCount / account.videoCount) : 0;
- const avgSubGainPerDay = channelAge > 0 ? Math.round(account.subscriberCount / channelAge) : 0;
- const avgViewsPerDay = channelAge > 0 ? Math.round(account.viewCount / channelAge) : 0;
-
- res.json({
- success: true,
- channel: {
- ...account,
- channelAge,
- channelAgeYears: (channelAge / 365).toFixed(1),
- viewsPerSubscriber: parseFloat(viewsPerSub),
- subscriberToViewRatio: parseFloat(subsPerView),
- avgViewsPerVideo,
- avgSubGainPerDay,
- avgViewsPerDay,
- estimatedMonthlyViews: avgViewsPerDay * 30,
- estimatedMonthlySubGain: avgSubGainPerDay * 30,
- estimatedYearlyViews: avgViewsPerDay * 365,
- estimatedYearlySubGain: avgSubGainPerDay * 365,
- },
- analytics,
- videoCount: videos.length,
- });
- } catch (err) {
- res.status(400).json({ success: false, message: err.message });
- }
-});
-
-// Get cached videos
-app.get('/api/accounts/:id/videos', async (req, res) => {
- try {
- const cache = await readJSON(VIDEOS_CACHE_FILE) || {};
- const accountCache = cache[req.params.id];
-
- if (accountCache && accountCache.videos) {
- return res.json({ success: true, videos: accountCache.videos, fetchedAt: accountCache.fetchedAt });
- }
+app.use('/api/keys', require('./routes/keys'));
+app.use('/api', require('./routes/accounts'));
+app.use('/api', require('./routes/analytics'));
+app.use('/api', require('./routes/publishing'));
+app.use('/api', require('./routes/scheduledPosts'));
+app.use('/api', require('./routes/github'));
- // Fetch fresh if no cache
- const apiKey = await getAPIKey();
- if (!apiKey) return res.status(400).json({ success: false, message: 'No API key' });
-
- const accounts = await readJSON(ACCOUNTS_FILE);
- const account = accounts.find(a => a.id === req.params.id);
- if (!account) return res.status(404).json({ success: false, message: 'Not found' });
-
- const videos = await fetchAllVideos(account.uploadsPlaylistId, apiKey, 10);
- cache[req.params.id] = { videos, fetchedAt: new Date().toISOString() };
- await writeJSON(VIDEOS_CACHE_FILE, cache);
-
- res.json({ success: true, videos, fetchedAt: cache[req.params.id].fetchedAt });
- } catch (err) {
- res.status(400).json({ success: false, message: err.message });
- }
-});
-
-// Cross-account comparison
-app.get('/api/comparison', async (req, res) => {
- try {
- const accounts = await readJSON(ACCOUNTS_FILE);
- if (accounts.length === 0) return res.json({ success: true, comparison: null });
-
- const sorted = {
- bySubscribers: [...accounts].sort((a, b) => b.subscriberCount - a.subscriberCount),
- byViews: [...accounts].sort((a, b) => b.viewCount - a.viewCount),
- byVideos: [...accounts].sort((a, b) => b.videoCount - a.videoCount),
- };
-
- const totals = accounts.reduce((acc, a) => ({
- subscribers: acc.subscribers + a.subscriberCount,
- views: acc.views + a.viewCount,
- videos: acc.videos + a.videoCount,
- }), { subscribers: 0, views: 0, videos: 0 });
-
- res.json({
- success: true,
- comparison: {
- rankings: sorted,
- totals,
- accountCount: accounts.length,
- bestBySubscribers: sorted.bySubscribers[0] || null,
- bestByViews: sorted.byViews[0] || null,
- bestByVideos: sorted.byVideos[0] || null,
- },
- });
- } catch (err) {
- res.status(500).json({ success: false, message: err.message });
- }
-});
-
-// Instagram analytics
-app.get('/api/accounts/:id/ig-analytics', async (req, res) => {
- try {
- const accounts = await readJSON(ACCOUNTS_FILE);
- const account = accounts.find(a => a.id === req.params.id && a.platform === 'instagram');
- if (!account) return res.status(404).json({ success: false, message: 'Instagram account not found' });
- if (!account.accessToken) return res.status(400).json({ success: false, message: 'No access token stored' });
-
- // Fetch fresh profile
- const profile = await fetchInstagramProfile(account.igUserId, account.accessToken);
-
- // Fetch media (up to 500 for thorough analytics)
- const media = await fetchInstagramMedia(account.igUserId, account.accessToken, 500);
-
- // Cache media
- const igCache = await readJSON(IG_CACHE_FILE) || {};
- igCache[req.params.id] = { media, fetchedAt: new Date().toISOString() };
- await writeJSON(IG_CACHE_FILE, igCache);
-
- // Compute analytics
- const analytics = computeInstagramAnalytics(profile, media);
-
- // Update account with latest stats
- account.followersCount = profile.followersCount;
- account.followsCount = profile.followsCount;
- account.mediaCount = profile.mediaCount;
- account.profilePictureUrl = profile.profilePictureUrl;
- account.lastUpdated = new Date().toISOString();
- await writeJSON(ACCOUNTS_FILE, accounts);
-
- const safeAccount = { ...account };
- delete safeAccount.accessToken;
-
- res.json({
- success: true,
- profile: { ...profile },
- account: safeAccount,
- analytics,
- mediaCount: media.length,
- });
- } catch (err) {
- res.status(400).json({ success: false, message: err.message });
- }
-});
-
-// Instagram media list
-app.get('/api/accounts/:id/ig-media', async (req, res) => {
- try {
- // Check cache first
- const igCache = await readJSON(IG_CACHE_FILE) || {};
- const cached = igCache[req.params.id];
- if (cached && cached.media) {
- return res.json({ success: true, media: cached.media, fetchedAt: cached.fetchedAt });
- }
-
- const accounts = await readJSON(ACCOUNTS_FILE);
- const account = accounts.find(a => a.id === req.params.id && a.platform === 'instagram');
- if (!account) return res.status(404).json({ success: false, message: 'Not found' });
- if (!account.accessToken) return res.status(400).json({ success: false, message: 'No access token' });
-
- const media = await fetchInstagramMedia(account.igUserId, account.accessToken, 500);
- igCache[req.params.id] = { media, fetchedAt: new Date().toISOString() };
- await writeJSON(IG_CACHE_FILE, igCache);
-
- res.json({ success: true, media, fetchedAt: igCache[req.params.id].fetchedAt });
- } catch (err) {
- res.status(400).json({ success: false, message: err.message });
- }
-});
-
-// Health check
-app.get('/api/health', (req, res) => {
+app.get('/api/health', (_req, res) => {
res.json({ status: 'ok', timestamp: new Date().toISOString() });
});
-// Get ALL videos across all channels (or filter by channel)
-app.get('/api/videos/all', async (req, res) => {
- try {
- const { channelId, sort, order, search, minViews, maxViews } = req.query;
- const cache = await readJSON(VIDEOS_CACHE_FILE) || {};
- const accounts = await readJSON(ACCOUNTS_FILE) || [];
-
- let allVideos = [];
- for (const acct of accounts) {
- if (channelId && acct.id !== channelId) continue;
- const cached = cache[acct.id];
- if (cached && cached.videos) {
- allVideos.push(...cached.videos.map(v => ({
- ...v,
- channelTitle: acct.title || acct.name || acct.channelTitle,
- channelId: acct.id,
- channelThumbnail: acct.thumbnails?.default || acct.thumbnailUrl || '',
- })));
- }
- }
-
- // Search filter
- if (search) {
- const q = search.toLowerCase();
- allVideos = allVideos.filter(v =>
- v.title?.toLowerCase().includes(q) ||
- (v.tags || []).some(t => t.toLowerCase().includes(q))
- );
- }
-
- // Views range filter
- if (minViews) allVideos = allVideos.filter(v => (v.viewCount || 0) >= parseInt(minViews));
- if (maxViews) allVideos = allVideos.filter(v => (v.viewCount || 0) <= parseInt(maxViews));
-
- // Sort
- const sortField = sort || 'viewCount';
- const sortOrder = order === 'asc' ? 1 : -1;
- allVideos.sort((a, b) => {
- const aVal = a[sortField] ?? 0;
- const bVal = b[sortField] ?? 0;
- if (typeof aVal === 'string') return sortOrder * aVal.localeCompare(bVal);
- return sortOrder * (bVal - aVal);
- });
-
- res.json({
- success: true,
- videos: allVideos,
- total: allVideos.length,
- channels: accounts.map(a => ({ id: a.id, title: a.title || a.name })),
- });
- } catch (err) {
- res.status(500).json({ success: false, message: err.message });
- }
-});
-
-// ─── Start ───────────────────────────────────────────────────────────────────
-
-// ─── Instagram Content Publishing ────────────────────────────────────────────
-
-// Get Cloudinary config (for frontend)
-app.get('/api/cloudinary-config', async (req, res) => {
- const keys = await readJSON(API_KEYS_FILE);
- const cloud = keys?.cloudinary || {};
- if (!cloud.cloudName || !cloud.uploadPreset) {
- return res.json({ success: false, message: 'Cloudinary not configured' });
- }
- res.json({ success: true, cloudName: cloud.cloudName, uploadPreset: cloud.uploadPreset });
-});
-
-// Check publishing rate limit
-app.get('/api/accounts/:id/ig-publishing-limit', async (req, res) => {
- try {
- const accounts = await readJSON(ACCOUNTS_FILE) || [];
- const acct = accounts.find(a => a.id === req.params.id);
- if (!acct || acct.platform !== 'instagram') {
- return res.status(404).json({ success: false, message: 'Instagram account not found' });
- }
- const r = await fetch(
- `https://graph.instagram.com/v25.0/${acct.igUserId}/content_publishing_limit?fields=quota_usage,config&access_token=${acct.accessToken}`
- );
- const data = await r.json();
- if (data.error) throw new Error(data.error.message);
- res.json({ success: true, ...data });
- } catch (err) {
- res.status(500).json({ success: false, message: err.message });
- }
-});
-
-// Step 1: Create a media container on Instagram
-app.post('/api/accounts/:id/ig-publish', async (req, res) => {
- try {
- const accounts = await readJSON(ACCOUNTS_FILE) || [];
- const acct = accounts.find(a => a.id === req.params.id);
- if (!acct || acct.platform !== 'instagram') {
- return res.status(404).json({ success: false, message: 'Instagram account not found' });
- }
-
- const {
- mediaType, // 'IMAGE', 'REELS', 'STORIES', 'CAROUSEL'
- mediaUrl, // public URL of image or video (from Cloudinary)
- caption,
- coverUrl, // cover image URL for reels
- shareToFeed, // boolean for reels/stories
- collaborators,// array of usernames
- audioName, // custom audio name for reels
- thumbOffset, // thumbnail offset ms for reels
- locationId, // location page ID
- userTags, // array of {username, x, y}
- altText, // image alt text
- children, // array of container IDs for carousel
- } = req.body;
-
- const igId = acct.igUserId;
- const token = acct.accessToken;
- const params = { access_token: token };
-
- if (mediaType === 'CAROUSEL') {
- // Carousel container
- params.media_type = 'CAROUSEL';
- if (caption) params.caption = caption;
- if (children && children.length) params.children = children.join(',');
- if (collaborators && collaborators.length) params.collaborators = JSON.stringify(collaborators);
- if (locationId) params.location_id = locationId;
- } else if (mediaType === 'CAROUSEL_ITEM_IMAGE') {
- // Individual carousel item (image)
- params.image_url = mediaUrl;
- params.is_carousel_item = true;
- } else if (mediaType === 'CAROUSEL_ITEM_VIDEO') {
- // Individual carousel item (video)
- params.media_type = 'VIDEO';
- params.video_url = mediaUrl;
- params.is_carousel_item = true;
- } else if (mediaType === 'REELS') {
- params.media_type = 'REELS';
- params.video_url = mediaUrl;
- if (caption) params.caption = caption;
- if (shareToFeed !== undefined) params.share_to_feed = shareToFeed;
- if (coverUrl) params.cover_url = coverUrl;
- if (collaborators && collaborators.length) params.collaborators = JSON.stringify(collaborators);
- if (audioName) params.audio_name = audioName;
- if (thumbOffset != null) params.thumb_offset = thumbOffset;
- if (locationId) params.location_id = locationId;
- if (userTags && userTags.length) params.user_tags = JSON.stringify(userTags);
- } else if (mediaType === 'STORIES') {
- params.media_type = 'STORIES';
- // Determine if image or video stories
- if (mediaUrl && (mediaUrl.match(/\.(mp4|mov|avi|webm)/i))) {
- params.video_url = mediaUrl;
- } else {
- params.image_url = mediaUrl;
- }
- if (userTags && userTags.length) params.user_tags = JSON.stringify(userTags);
- } else {
- // Default: Image post
- params.image_url = mediaUrl;
- if (caption) params.caption = caption;
- if (locationId) params.location_id = locationId;
- if (userTags && userTags.length) params.user_tags = JSON.stringify(userTags);
- if (altText) params.alt_text = altText;
- }
-
- // Create container
- const qs = new URLSearchParams(params).toString();
- const r = await fetch(`https://graph.instagram.com/v25.0/${igId}/media?${qs}`, { method: 'POST' });
- const data = await r.json();
-
- if (data.error) throw new Error(data.error.message);
-
- res.json({ success: true, containerId: data.id });
- } catch (err) {
- res.status(500).json({ success: false, message: err.message });
- }
-});
-
-// Step 2: Check container status
-app.get('/api/ig-container/:containerId/status', async (req, res) => {
- try {
- const { containerId } = req.params;
- const { accountId } = req.query;
- const accounts = await readJSON(ACCOUNTS_FILE) || [];
- const acct = accounts.find(a => a.id === accountId);
- if (!acct) return res.status(404).json({ success: false, message: 'Account not found' });
-
- const r = await fetch(
- `https://graph.instagram.com/v25.0/${containerId}?fields=status_code,status&access_token=${acct.accessToken}`
- );
- const data = await r.json();
- if (data.error) throw new Error(data.error.message);
-
- res.json({ success: true, statusCode: data.status_code, status: data.status });
- } catch (err) {
- res.status(500).json({ success: false, message: err.message });
- }
-});
-
-// Step 3: Publish the container
-app.post('/api/accounts/:id/ig-media-publish', async (req, res) => {
- try {
- const accounts = await readJSON(ACCOUNTS_FILE) || [];
- const acct = accounts.find(a => a.id === req.params.id);
- if (!acct || acct.platform !== 'instagram') {
- return res.status(404).json({ success: false, message: 'Instagram account not found' });
- }
-
- const { containerId } = req.body;
- const r = await fetch(
- `https://graph.instagram.com/v25.0/${acct.igUserId}/media_publish?creation_id=${containerId}&access_token=${acct.accessToken}`,
- { method: 'POST' }
- );
- const data = await r.json();
- if (data.error) throw new Error(data.error.message);
-
- res.json({ success: true, mediaId: data.id });
- } catch (err) {
- res.status(500).json({ success: false, message: err.message });
- }
-});
-
-// ─── Scheduled Posts ─────────────────────────────────────────────────────────
-
-// Generate a simple unique ID
-function generateId() {
- return Date.now().toString(36) + Math.random().toString(36).substring(2, 8);
-}
-
-// Get all scheduled posts
-app.get('/api/scheduled-posts', async (req, res) => {
- try {
- const posts = await readJSON(SCHEDULED_POSTS_FILE) || [];
- res.json({ success: true, posts });
- } catch (err) {
- res.status(500).json({ success: false, message: err.message });
- }
-});
-
-// Create a scheduled post (saves Cloudinary URL + metadata for local scheduler to process)
-app.post('/api/scheduled-posts', async (req, res) => {
- try {
- const {
- accountId, platform, mediaType, mediaUrl,
- caption, coverUrl, shareToFeed, collaborators,
- audioName, thumbOffset, locationId, userTags,
- altText, scheduledAt,
- } = req.body;
-
- if (!accountId || !mediaUrl || !scheduledAt) {
- return res.status(400).json({ success: false, message: 'accountId, mediaUrl, and scheduledAt are required' });
- }
-
- const scheduledDate = new Date(scheduledAt);
- if (isNaN(scheduledDate.getTime()) || scheduledDate <= new Date()) {
- return res.status(400).json({ success: false, message: 'scheduledAt must be a valid future date' });
- }
-
- const post = {
- id: generateId(),
- accountId,
- platform: platform || 'instagram',
- mediaType: mediaType || 'IMAGE',
- mediaUrl,
- caption: caption || '',
- coverUrl: coverUrl || null,
- shareToFeed: shareToFeed !== undefined ? shareToFeed : true,
- collaborators: collaborators || [],
- audioName: audioName || '',
- thumbOffset: thumbOffset || null,
- locationId: locationId || '',
- userTags: userTags || [],
- altText: altText || '',
- scheduledAt: scheduledDate.toISOString(),
- status: 'pending', // pending | publishing | published | failed
- createdAt: new Date().toISOString(),
- publishedMediaId: null,
- error: null,
- };
-
- const posts = await readJSON(SCHEDULED_POSTS_FILE) || [];
- posts.push(post);
- await writeJSON(SCHEDULED_POSTS_FILE, posts);
-
- // Sync to GitHub (async, don't block response)
- syncEverythingToGitHub().catch(() => { });
-
- res.json({ success: true, post });
- } catch (err) {
- res.status(500).json({ success: false, message: err.message });
- }
-});
-
-// Update a scheduled post
-app.put('/api/scheduled-posts/:id', async (req, res) => {
- try {
- const posts = await readJSON(SCHEDULED_POSTS_FILE) || [];
- const idx = posts.findIndex(p => p.id === req.params.id);
- if (idx === -1) return res.status(404).json({ success: false, message: 'Scheduled post not found' });
- if (posts[idx].status !== 'pending' && posts[idx].status !== 'scheduled') {
- return res.status(400).json({ success: false, message: 'Can only edit pending posts' });
- }
-
- const allowed = ['caption', 'scheduledAt', 'shareToFeed', 'collaborators', 'audioName',
- 'thumbOffset', 'locationId', 'userTags', 'altText', 'coverUrl'];
- for (const key of allowed) {
- if (req.body[key] !== undefined) posts[idx][key] = req.body[key];
- }
- if (req.body.scheduledAt) posts[idx].scheduledAt = new Date(req.body.scheduledAt).toISOString();
-
- await writeJSON(SCHEDULED_POSTS_FILE, posts);
- syncEverythingToGitHub().catch(() => { });
- res.json({ success: true, post: posts[idx] });
- } catch (err) {
- res.status(500).json({ success: false, message: err.message });
- }
-});
-
-// Delete ALL scheduled posts (skips any currently publishing)
-app.delete('/api/scheduled-posts', async (_req, res) => {
- try {
- let posts = await readJSON(SCHEDULED_POSTS_FILE) || [];
- const publishing = posts.filter(p => p.status === 'publishing');
- await writeJSON(SCHEDULED_POSTS_FILE, publishing); // keep only in-flight ones
- syncEverythingToGitHub().catch(() => { });
- res.json({ success: true, deleted: posts.length - publishing.length, kept: publishing.length });
- } catch (err) {
- res.status(500).json({ success: false, message: err.message });
- }
-});
-
-// Delete a scheduled post
-app.delete('/api/scheduled-posts/:id', async (req, res) => {
- try {
- let posts = await readJSON(SCHEDULED_POSTS_FILE) || [];
- const post = posts.find(p => p.id === req.params.id);
- if (!post) return res.status(404).json({ success: false, message: 'Scheduled post not found' });
- if (post.status === 'publishing') {
- return res.status(400).json({ success: false, message: 'Cannot delete a post that is currently publishing' });
- }
- posts = posts.filter(p => p.id !== req.params.id);
- await writeJSON(SCHEDULED_POSTS_FILE, posts);
- syncEverythingToGitHub().catch(() => { });
- res.json({ success: true, message: 'Scheduled post deleted' });
- } catch (err) {
- res.status(500).json({ success: false, message: err.message });
- }
-});
-
-// ─── Scheduled Post Processor ────────────────────────────────────────────────
-// Runs locally via setInterval. Checks every 60 seconds for due posts.
-// On server startup, immediately processes any overdue posts.
-
-let isProcessing = false;
-
-async function processScheduledPosts() {
- if (isProcessing) return { processed: 0, message: 'Already processing' };
- isProcessing = true;
- let processed = 0;
- let errors = [];
-
- try {
- const posts = await readJSON(SCHEDULED_POSTS_FILE) || [];
- const accounts = await readJSON(ACCOUNTS_FILE) || [];
- const now = new Date();
-
- for (const post of posts) {
- if (post.status !== 'pending') continue;
- const scheduledDate = new Date(post.scheduledAt);
- if (scheduledDate > now) continue;
-
- // This post is due — publish it
- post.status = 'publishing';
- await writeJSON(SCHEDULED_POSTS_FILE, posts);
-
- try {
- const acct = accounts.find(a => a.id === post.accountId);
- if (!acct) throw new Error('Account not found: ' + post.accountId);
-
- // Step 1: Create container
- const igId = acct.igUserId;
- const token = acct.accessToken;
- const params = { access_token: token };
-
- if (post.mediaType === 'REELS') {
- params.media_type = 'REELS';
- params.video_url = post.mediaUrl;
- if (post.caption) params.caption = post.caption;
- if (post.shareToFeed !== undefined) params.share_to_feed = post.shareToFeed;
- if (post.coverUrl) params.cover_url = post.coverUrl;
- if (post.collaborators?.length) params.collaborators = JSON.stringify(post.collaborators);
- if (post.audioName) params.audio_name = post.audioName;
- if (post.thumbOffset != null) params.thumb_offset = post.thumbOffset;
- if (post.locationId) params.location_id = post.locationId;
- if (post.userTags?.length) params.user_tags = JSON.stringify(post.userTags);
- } else if (post.mediaType === 'STORIES') {
- params.media_type = 'STORIES';
- if (post.mediaUrl.match(/\.(mp4|mov|avi|webm)/i)) {
- params.video_url = post.mediaUrl;
- } else {
- params.image_url = post.mediaUrl;
- }
- if (post.userTags?.length) params.user_tags = JSON.stringify(post.userTags);
- } else {
- // IMAGE
- params.image_url = post.mediaUrl;
- if (post.caption) params.caption = post.caption;
- if (post.locationId) params.location_id = post.locationId;
- if (post.userTags?.length) params.user_tags = JSON.stringify(post.userTags);
- if (post.altText) params.alt_text = post.altText;
- }
-
- const qs = new URLSearchParams(params).toString();
- const createRes = await fetch(`https://graph.instagram.com/v25.0/${igId}/media?${qs}`, { method: 'POST' });
- const createData = await createRes.json();
- if (createData.error) throw new Error(createData.error.message);
-
- const containerId = createData.id;
-
- // Step 2: Wait for processing (poll up to 60 attempts, 3s apart = 3 min max)
- if (post.mediaType === 'REELS' || post.mediaType === 'STORIES') {
- for (let i = 0; i < 60; i++) {
- await new Promise(r => setTimeout(r, 3000));
- const statusRes = await fetch(
- `https://graph.instagram.com/v25.0/${containerId}?fields=status_code,status&access_token=${token}`
- );
- const statusData = await statusRes.json();
- if (statusData.status_code === 'FINISHED' || statusData.status_code === 'PUBLISHED') break;
- if (statusData.status_code === 'ERROR') throw new Error('Processing failed: ' + (statusData.status || ''));
- if (statusData.status_code === 'EXPIRED') throw new Error('Container expired');
- }
- } else {
- await new Promise(r => setTimeout(r, 2000));
- }
-
- // Step 3: Publish
- const pubRes = await fetch(
- `https://graph.instagram.com/v25.0/${igId}/media_publish?creation_id=${containerId}&access_token=${token}`,
- { method: 'POST' }
- );
- const pubData = await pubRes.json();
- if (pubData.error) throw new Error(pubData.error.message);
-
- post.status = 'published';
- post.publishedMediaId = pubData.id;
- post.publishedAt = new Date().toISOString();
- processed++;
- console.log(` ✓ Published scheduled post ${post.id} → media ${pubData.id}`);
-
- } catch (err) {
- post.status = 'failed';
- post.error = err.message;
- errors.push({ id: post.id, error: err.message });
- console.error(` ✗ Failed to publish scheduled post ${post.id}: ${err.message}`);
- }
-
- await writeJSON(SCHEDULED_POSTS_FILE, posts);
- }
- } catch (err) {
- console.error('Scheduler error:', err);
- } finally {
- isProcessing = false;
- }
-
- return { processed, errors };
-}
-
-// Manual trigger endpoint
-app.get('/api/process-scheduled', async (req, res) => {
- const result = await processScheduledPosts();
- res.json({ success: true, ...result, timestamp: new Date().toISOString() });
-});
-app.post('/api/process-scheduled', async (req, res) => {
- const result = await processScheduledPosts();
- res.json({ success: true, ...result, timestamp: new Date().toISOString() });
-});
-
-// GitHub sync test endpoint
-app.post('/api/github-sync', async (req, res) => {
- try {
- await syncEverythingToGitHub();
- res.json({ success: true, message: 'Synced all data files to GitHub' });
- } catch (err) {
- res.status(500).json({ success: false, message: err.message });
- }
-});
-
-app.post('/api/github-pull', async (req, res) => {
- try {
- await pullScheduledPostsFromGitHub();
- const posts = await readJSON(SCHEDULED_POSTS_FILE) || [];
- res.json({ success: true, posts, message: 'Pulled from GitHub' });
- } catch (err) {
- res.status(500).json({ success: false, message: err.message });
- }
-});
+// ─── Startup ─────────────────────────────────────────────────────────────────
initializeData().then(async () => {
- // Pull latest from GitHub on startup (picks up posts published by GH Actions while server was off)
await pullScheduledPostsFromGitHub();
- // Process any overdue posts on startup
const posts = await readJSON(SCHEDULED_POSTS_FILE) || [];
const overdue = posts.filter(p => p.status === 'pending' && new Date(p.scheduledAt) <= new Date());
if (overdue.length > 0) {
@@ -2101,7 +37,6 @@ initializeData().then(async () => {
await processScheduledPosts();
}
- // Check every 60 seconds for due posts
setInterval(async () => {
const posts = await readJSON(SCHEDULED_POSTS_FILE) || [];
const due = posts.filter(p => p.status === 'pending' && new Date(p.scheduledAt) <= new Date());
@@ -2111,10 +46,8 @@ initializeData().then(async () => {
}
}, 60000);
- // Remove accounts.json from GitHub if it was mistakenly committed
removeAccountsFileFromGitHub().catch(() => { });
- // Check Instagram token expiry once on startup, then every 24 hours
autoRefreshInstagramTokens();
setInterval(autoRefreshInstagramTokens, 24 * 60 * 60 * 1000);
diff --git a/backend/services/github.js b/backend/services/github.js
new file mode 100644
index 0000000..ba21610
--- /dev/null
+++ b/backend/services/github.js
@@ -0,0 +1,171 @@
+const fetch = require('node-fetch');
+const sodium = require('libsodium-wrappers');
+const { readJSON, writeJSON, API_KEYS_FILE, ACCOUNTS_FILE, SCHEDULED_POSTS_FILE } = require('../utils/dataHelpers');
+
+// Push a single file to GitHub (create or update). Returns true on success.
+async function pushFileToGitHub(gh, repoPath, jsonData, commitMessage) {
+ const repo = gh.repo.replace(/^https?:\/\/github\.com\//, '').replace(/\.git$/, '').replace(/\/$/, '');
+ const branch = gh.branch || 'main';
+ const content = Buffer.from(JSON.stringify(jsonData, null, 2)).toString('base64');
+ const headers = { Authorization: `token ${gh.token}`, 'Content-Type': 'application/json', 'User-Agent': 'SocialMediaDashboard' };
+
+ let sha;
+ try {
+ const r = await fetch(`https://api.github.com/repos/${repo}/contents/${repoPath}?ref=${branch}`, { headers });
+ if (r.ok) sha = (await r.json()).sha;
+ } catch { }
+
+ const body = { message: commitMessage, content, branch };
+ if (sha) body.sha = sha;
+
+ const res = await fetch(`https://api.github.com/repos/${repo}/contents/${repoPath}`, {
+ method: 'PUT', headers, body: JSON.stringify(body),
+ });
+
+ if (!res.ok) {
+ const err = await res.json();
+ throw new Error(`GitHub PUT ${repoPath}: ${err.message}`);
+ }
+ return true;
+}
+
+// Sync scheduled_posts.json to GitHub.
+// accounts.json is NEVER pushed as a plain file — tokens would be wiped on next git pull.
+// Accounts sync via the encrypted ACCOUNTS_JSON secret instead.
+async function syncAllDataToGitHub() {
+ try {
+ const keys = await readJSON(API_KEYS_FILE) || {};
+ const gh = keys.github;
+ if (!gh?.token || !gh?.repo) return;
+
+ const posts = await readJSON(SCHEDULED_POSTS_FILE) || [];
+ await pushFileToGitHub(gh, 'backend/data/scheduled_posts.json', posts, '📅 Sync scheduled posts');
+ console.log(' ☁️ Synced scheduled posts to GitHub');
+ } catch (err) {
+ console.error(' ☁️ syncAllDataToGitHub error:', err.message);
+ }
+}
+
+// Remove accounts.json from GitHub if it was mistakenly committed.
+// Safe to call repeatedly — silently does nothing if the file doesn't exist on GitHub.
+async function removeAccountsFileFromGitHub() {
+ try {
+ const keys = await readJSON(API_KEYS_FILE) || {};
+ const gh = keys.github;
+ if (!gh?.token || !gh?.repo) return;
+ const repo = gh.repo.replace(/^https?:\/\/github\.com\//, '').replace(/\.git$/, '').replace(/\/$/, '');
+ const branch = gh.branch || 'main';
+ const filePath = 'backend/data/accounts.json';
+ const headers = { Authorization: `token ${gh.token}`, 'Content-Type': 'application/json', 'User-Agent': 'SocialMediaDashboard' };
+
+ const r = await fetch(`https://api.github.com/repos/${repo}/contents/${filePath}?ref=${branch}`, { headers });
+ if (!r.ok) return;
+
+ const { sha } = await r.json();
+ const res = await fetch(`https://api.github.com/repos/${repo}/contents/${filePath}`, {
+ method: 'DELETE',
+ headers,
+ body: JSON.stringify({ message: '🔒 Remove accounts.json (sensitive — use secret instead)', sha, branch }),
+ });
+ if (res.ok) console.log(' ☁️ Removed accounts.json from GitHub (was mistakenly committed)');
+ } catch { }
+}
+
+async function pullScheduledPostsFromGitHub() {
+ try {
+ const keys = await readJSON(API_KEYS_FILE) || {};
+ const gh = keys.github;
+ if (!gh?.token || !gh?.repo) return;
+
+ const repo = gh.repo.replace(/^https?:\/\/github\.com\//, '').replace(/\.git$/, '').replace(/\/$/, '');
+ const filePath = 'backend/data/scheduled_posts.json';
+ const branch = gh.branch || 'main';
+
+ const res = await fetch(`https://api.github.com/repos/${repo}/contents/${filePath}?ref=${branch}`, {
+ headers: { Authorization: `token ${gh.token}`, 'User-Agent': 'SocialMediaDashboard' }
+ });
+ if (!res.ok) return;
+
+ const data = await res.json();
+ const remotePosts = JSON.parse(Buffer.from(data.content, 'base64').toString('utf8'));
+ const localPosts = await readJSON(SCHEDULED_POSTS_FILE) || [];
+
+ const remoteMap = new Map(remotePosts.map(p => [p.id, p]));
+ const localMap = new Map(localPosts.map(p => [p.id, p]));
+ const merged = [];
+
+ for (const rp of remotePosts) {
+ const lp = localMap.get(rp.id);
+ if (!lp || rp.status === 'published' || rp.status === 'failed') {
+ merged.push(rp);
+ } else {
+ merged.push(lp);
+ }
+ }
+ for (const lp of localPosts) {
+ if (!remoteMap.has(lp.id)) merged.push(lp);
+ }
+
+ await writeJSON(SCHEDULED_POSTS_FILE, merged);
+ console.log(` ☁️ Pulled ${remotePosts.length} post(s) from GitHub, merged to ${merged.length}`);
+ } catch (err) {
+ console.error(' ☁️ GitHub pull error:', err.message);
+ }
+}
+
+// Automatically updates ACCOUNTS_JSON secret in GitHub Actions whenever accounts change.
+async function syncAccountsSecretToGitHub() {
+ try {
+ const keys = await readJSON(API_KEYS_FILE) || {};
+ const gh = keys.github;
+ if (!gh?.token || !gh?.repo) return;
+
+ const repo = gh.repo.replace(/^https?:\/\/github\.com\//, '').replace(/\.git$/, '').replace(/\/$/, '');
+ const accounts = await readJSON(ACCOUNTS_FILE) || [];
+ const secretValue = Buffer.from(JSON.stringify(accounts, null, 2)).toString('base64');
+
+ const pkRes = await fetch(`https://api.github.com/repos/${repo}/actions/secrets/public-key`, {
+ headers: { Authorization: `token ${gh.token}`, 'User-Agent': 'SocialMediaDashboard' }
+ });
+ if (!pkRes.ok) {
+ console.error(' ☁️ Failed to get GitHub public key:', (await pkRes.json()).message);
+ return;
+ }
+ const { key: publicKey, key_id } = await pkRes.json();
+
+ await sodium.ready;
+ const binKey = sodium.from_base64(publicKey, sodium.base64_variants.ORIGINAL);
+ const binSecret = sodium.from_string(secretValue);
+ const encrypted = sodium.crypto_box_seal(binSecret, binKey);
+ const encryptedB64 = sodium.to_base64(encrypted, sodium.base64_variants.ORIGINAL);
+
+ const res = await fetch(`https://api.github.com/repos/${repo}/actions/secrets/ACCOUNTS_JSON`, {
+ method: 'PUT',
+ headers: { Authorization: `token ${gh.token}`, 'Content-Type': 'application/json', 'User-Agent': 'SocialMediaDashboard' },
+ body: JSON.stringify({ encrypted_value: encryptedB64, key_id }),
+ });
+
+ if (res.status === 201 || res.status === 204) {
+ console.log(' ☁️ Synced ACCOUNTS_JSON secret to GitHub');
+ } else {
+ const err = await res.json();
+ console.error(' ☁️ GitHub secret sync error:', err.message);
+ }
+ } catch (err) {
+ console.error(' ☁️ GitHub secret sync error:', err.message);
+ }
+}
+
+// Push all data files + refresh encrypted secret in one shot.
+async function syncEverythingToGitHub() {
+ await Promise.allSettled([syncAllDataToGitHub(), syncAccountsSecretToGitHub()]);
+}
+
+module.exports = {
+ pushFileToGitHub,
+ syncAllDataToGitHub,
+ removeAccountsFileFromGitHub,
+ pullScheduledPostsFromGitHub,
+ syncAccountsSecretToGitHub,
+ syncEverythingToGitHub,
+};
diff --git a/backend/services/instagram.js b/backend/services/instagram.js
new file mode 100644
index 0000000..25920c2
--- /dev/null
+++ b/backend/services/instagram.js
@@ -0,0 +1,357 @@
+const fetch = require('node-fetch');
+const { readJSON, writeJSON, ACCOUNTS_FILE } = require('../utils/dataHelpers');
+
+const IG_GRAPH_URL = 'https://graph.instagram.com';
+const IG_API_VERSION = 'v25.0';
+
+async function igFetch(endpoint, params = {}) {
+ const needsVersion = !endpoint.startsWith('/oauth') &&
+ !endpoint.startsWith('/access_token') &&
+ !endpoint.startsWith('/refresh_access_token');
+ const base = needsVersion ? `${IG_GRAPH_URL}/${IG_API_VERSION}` : IG_GRAPH_URL;
+ const url = new URL(`${base}${endpoint}`);
+ Object.entries(params).forEach(([k, v]) => url.searchParams.set(k, v));
+ const res = await fetch(url.toString());
+ const data = await res.json();
+ if (data.error) throw new Error(data.error.message || data.error.error_message || JSON.stringify(data.error));
+ if (data.error_message) throw new Error(data.error_message);
+ return data;
+}
+
+async function exchangeForLongLivedToken(shortToken, appSecret) {
+ const data = await igFetch('/access_token', {
+ grant_type: 'ig_exchange_token',
+ client_secret: appSecret,
+ access_token: shortToken,
+ });
+ if (!data.access_token) throw new Error('Failed to exchange token — check Instagram App Secret');
+ return {
+ accessToken: data.access_token,
+ tokenType: data.token_type || 'bearer',
+ expiresIn: data.expires_in || 5184000,
+ };
+}
+
+async function refreshLongLivedToken(longToken) {
+ const data = await igFetch('/refresh_access_token', {
+ grant_type: 'ig_refresh_token',
+ access_token: longToken,
+ });
+ if (!data.access_token) throw new Error('Failed to refresh token');
+ return {
+ accessToken: data.access_token,
+ tokenType: data.token_type || 'bearer',
+ expiresIn: data.expires_in || 5184000,
+ };
+}
+
+// Auto-refresh tokens expiring within 15 days. Called on startup and every 24h.
+async function autoRefreshInstagramTokens() {
+ try {
+ const accounts = await readJSON(ACCOUNTS_FILE) || [];
+ const igAccounts = accounts.filter(a => a.platform === 'instagram' && a.accessToken && a.tokenExpiresAt);
+ if (igAccounts.length === 0) return;
+
+ const fifteenDaysMs = 15 * 24 * 60 * 60 * 1000;
+ const soon = new Date(Date.now() + fifteenDaysMs);
+ const toRefresh = igAccounts.filter(a => new Date(a.tokenExpiresAt) <= soon);
+ if (toRefresh.length === 0) return;
+
+ console.log(`\n 🔑 Auto-refreshing ${toRefresh.length} Instagram token(s) expiring within 15 days...`);
+ let changed = false;
+ for (const account of toRefresh) {
+ try {
+ const refreshed = await refreshLongLivedToken(account.accessToken);
+ account.accessToken = refreshed.accessToken;
+ account.tokenExpiresAt = new Date(Date.now() + (refreshed.expiresIn || 5184000) * 1000).toISOString();
+ console.log(` ✅ Token refreshed for @${account.username} — expires ${account.tokenExpiresAt}`);
+ changed = true;
+ } catch (err) {
+ console.error(` ❌ Failed to refresh token for @${account.username}: ${err.message}`);
+ }
+ }
+
+ if (changed) {
+ await writeJSON(ACCOUNTS_FILE, accounts);
+ // Lazy-require to avoid circular dependency at module load time
+ const { syncEverythingToGitHub } = require('./github');
+ syncEverythingToGitHub().catch(() => { });
+ }
+ } catch (err) {
+ console.error(' ❌ autoRefreshInstagramTokens error:', err.message);
+ }
+}
+
+async function fetchInstagramProfile(igUserId, accessToken) {
+ const endpoint = igUserId ? `/${igUserId}` : '/me';
+ const data = await igFetch(endpoint, {
+ access_token: accessToken,
+ fields: 'user_id,username,name,profile_picture_url,followers_count,follows_count,media_count,biography,website',
+ });
+ return {
+ igUserId: data.user_id || data.id || igUserId,
+ name: data.name || '',
+ username: data.username || '',
+ profilePictureUrl: data.profile_picture_url || '',
+ followersCount: data.followers_count || 0,
+ followsCount: data.follows_count || 0,
+ mediaCount: data.media_count || 0,
+ biography: data.biography || '',
+ website: data.website || '',
+ };
+}
+
+async function fetchInstagramMedia(igUserId, accessToken, limit = 500) {
+ let allMedia = [];
+ let url = `${IG_GRAPH_URL}/${IG_API_VERSION}/${igUserId}/media?access_token=${accessToken}&fields=id,caption,media_type,media_url,thumbnail_url,permalink,timestamp,like_count,comments_count&limit=${Math.min(limit, 100)}`;
+
+ let pages = 0;
+ while (url && pages < 10 && allMedia.length < limit) {
+ const res = await fetch(url);
+ const data = await res.json();
+ if (data.error) throw new Error(data.error.message || data.error.error_message);
+ if (data.data) allMedia = allMedia.concat(data.data);
+ url = data.paging?.next || null;
+ pages++;
+ }
+
+ return allMedia.slice(0, limit).map(m => ({
+ id: m.id,
+ caption: m.caption || '',
+ mediaType: m.media_type || 'IMAGE',
+ mediaUrl: m.media_url || '',
+ thumbnailUrl: m.thumbnail_url || m.media_url || '',
+ permalink: m.permalink || '',
+ timestamp: m.timestamp || '',
+ likeCount: m.like_count || 0,
+ commentsCount: m.comments_count || 0,
+ }));
+}
+
+function computeInstagramAnalytics(profile, media) {
+ const emptyAnalytics = {
+ totalPosts: profile.mediaCount || 0, fetchedPosts: 0,
+ totalLikes: 0, totalComments: 0, totalEngagement: 0,
+ avgLikes: 0, avgComments: 0, avgEngagement: 0,
+ medianLikes: 0, medianComments: 0,
+ engagementRate: 0, likesPerFollower: 0, commentsPerFollower: 0,
+ bestByLikes: null, bestByComments: null, worstByLikes: null,
+ recentMedia: [], mediaTypeDistribution: {},
+ postFrequency: { perWeek: 0, perMonth: 0 },
+ topPosts: [], performanceByType: {},
+ hashtagAnalysis: [], captionLengthCorrelation: [],
+ postsByDayOfWeek: [], postsByHour: [],
+ engagementTimeline: [], monthlyBreakdown: [],
+ postsLast7Days: 0, postsLast30Days: 0, postsLast90Days: 0,
+ viralityScore: 0, consistencyScore: 0,
+ bestPostingDay: '', bestPostingHour: '',
+ likesToCommentsRatio: 0,
+ };
+ if (!media || media.length === 0) return emptyAnalytics;
+
+ const totalLikes = media.reduce((s, m) => s + m.likeCount, 0);
+ const totalComments = media.reduce((s, m) => s + m.commentsCount, 0);
+ const totalEngagement = totalLikes + totalComments;
+ const avgLikes = Math.round(totalLikes / media.length);
+ const avgComments = Math.round(totalComments / media.length);
+ const avgEngagement = Math.round(totalEngagement / media.length);
+ const engagementRate = profile.followersCount > 0
+ ? parseFloat(((totalLikes + totalComments) / media.length / profile.followersCount * 100).toFixed(2)) : 0;
+ const likesPerFollower = profile.followersCount > 0
+ ? parseFloat((totalLikes / media.length / profile.followersCount * 100).toFixed(2)) : 0;
+ const commentsPerFollower = profile.followersCount > 0
+ ? parseFloat((totalComments / media.length / profile.followersCount * 100).toFixed(2)) : 0;
+
+ const sortedLikes = [...media].map(m => m.likeCount).sort((a, b) => a - b);
+ const sortedComments = [...media].map(m => m.commentsCount).sort((a, b) => a - b);
+ const mid = Math.floor(sortedLikes.length / 2);
+ const medianLikes = sortedLikes.length % 2 ? sortedLikes[mid] : Math.round((sortedLikes[mid - 1] + sortedLikes[mid]) / 2);
+ const medianComments = sortedComments.length % 2 ? sortedComments[mid] : Math.round((sortedComments[mid - 1] + sortedComments[mid]) / 2);
+
+ const byLikes = [...media].sort((a, b) => b.likeCount - a.likeCount);
+ const byComments = [...media].sort((a, b) => b.commentsCount - a.commentsCount);
+ const likesToCommentsRatio = totalComments > 0 ? parseFloat((totalLikes / totalComments).toFixed(1)) : 0;
+
+ const mediaTypes = {};
+ const typeStats = {};
+ media.forEach(m => {
+ const t = m.mediaType;
+ mediaTypes[t] = (mediaTypes[t] || 0) + 1;
+ if (!typeStats[t]) typeStats[t] = { likes: 0, comments: 0, count: 0 };
+ typeStats[t].likes += m.likeCount;
+ typeStats[t].comments += m.commentsCount;
+ typeStats[t].count++;
+ });
+ const performanceByType = {};
+ Object.entries(typeStats).forEach(([type, s]) => {
+ performanceByType[type] = {
+ count: s.count,
+ avgLikes: Math.round(s.likes / s.count),
+ avgComments: Math.round(s.comments / s.count),
+ avgEngagement: Math.round((s.likes + s.comments) / s.count),
+ totalLikes: s.likes,
+ totalComments: s.comments,
+ };
+ });
+
+ const dates = media.map(m => new Date(m.timestamp)).filter(d => !isNaN(d));
+ let perWeek = 0, perMonth = 0;
+ if (dates.length >= 2) {
+ const newest = Math.max(...dates);
+ const oldest = Math.min(...dates);
+ const spanDays = Math.max(1, (newest - oldest) / 86400000);
+ perWeek = parseFloat((media.length / spanDays * 7).toFixed(1));
+ perMonth = parseFloat((media.length / spanDays * 30).toFixed(1));
+ }
+
+ const dayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
+ const dayBuckets = Array(7).fill(null).map(() => ({ count: 0, likes: 0, comments: 0 }));
+ dates.forEach((d, i) => {
+ const day = d.getDay();
+ dayBuckets[day].count++;
+ dayBuckets[day].likes += media[i]?.likeCount || 0;
+ dayBuckets[day].comments += media[i]?.commentsCount || 0;
+ });
+ const postsByDayOfWeek = dayBuckets.map((b, i) => ({
+ day: dayNames[i], shortDay: dayNames[i].slice(0, 3),
+ posts: b.count,
+ avgLikes: b.count > 0 ? Math.round(b.likes / b.count) : 0,
+ avgComments: b.count > 0 ? Math.round(b.comments / b.count) : 0,
+ avgEngagement: b.count > 0 ? Math.round((b.likes + b.comments) / b.count) : 0,
+ }));
+ const bestDayObj = postsByDayOfWeek.reduce((best, d) => d.avgEngagement > best.avgEngagement ? d : best, postsByDayOfWeek[0]);
+ const bestPostingDay = bestDayObj?.day || '';
+
+ const hourBuckets = Array(24).fill(null).map(() => ({ count: 0, likes: 0, comments: 0 }));
+ dates.forEach((d, i) => {
+ const h = d.getHours();
+ hourBuckets[h].count++;
+ hourBuckets[h].likes += media[i]?.likeCount || 0;
+ hourBuckets[h].comments += media[i]?.commentsCount || 0;
+ });
+ const postsByHour = hourBuckets.map((b, i) => ({
+ hour: i, label: `${i}:00`,
+ posts: b.count,
+ avgEngagement: b.count > 0 ? Math.round((b.likes + b.comments) / b.count) : 0,
+ }));
+ const bestHourObj = postsByHour.reduce((best, h) => h.avgEngagement > best.avgEngagement ? h : best, postsByHour[0]);
+ const bestPostingHour = bestHourObj?.posts > 0 ? bestHourObj.label : '';
+
+ const monthMap = {};
+ media.forEach(m => {
+ const d = new Date(m.timestamp);
+ if (isNaN(d)) return;
+ const key = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`;
+ if (!monthMap[key]) monthMap[key] = { posts: 0, likes: 0, comments: 0 };
+ monthMap[key].posts++;
+ monthMap[key].likes += m.likeCount;
+ monthMap[key].comments += m.commentsCount;
+ });
+ const monthlyBreakdown = Object.entries(monthMap)
+ .sort(([a], [b]) => a.localeCompare(b))
+ .map(([month, s]) => ({
+ month, posts: s.posts,
+ likes: s.likes, comments: s.comments,
+ avgLikes: Math.round(s.likes / s.posts),
+ avgComments: Math.round(s.comments / s.posts),
+ engagement: s.likes + s.comments,
+ }));
+ const engagementTimeline = monthlyBreakdown;
+
+ const now = Date.now();
+ const postsLast7Days = dates.filter(d => (now - d.getTime()) <= 7 * 86400000).length;
+ const postsLast30Days = dates.filter(d => (now - d.getTime()) <= 30 * 86400000).length;
+ const postsLast90Days = dates.filter(d => (now - d.getTime()) <= 90 * 86400000).length;
+
+ const hashtagMap = {};
+ media.forEach(m => {
+ const tags = (m.caption || '').match(/#[\w\u00C0-\u024F]+/g) || [];
+ tags.forEach(tag => {
+ const t = tag.toLowerCase();
+ if (!hashtagMap[t]) hashtagMap[t] = { tag: t, count: 0, likes: 0, comments: 0 };
+ hashtagMap[t].count++;
+ hashtagMap[t].likes += m.likeCount;
+ hashtagMap[t].comments += m.commentsCount;
+ });
+ });
+ const hashtagAnalysis = Object.values(hashtagMap)
+ .map(h => ({ ...h, avgEngagement: Math.round((h.likes + h.comments) / h.count) }))
+ .sort((a, b) => b.count - a.count)
+ .slice(0, 20);
+
+ const captionBuckets = [
+ { label: 'No caption', min: 0, max: 0 },
+ { label: 'Short (1-50)', min: 1, max: 50 },
+ { label: 'Medium (51-150)', min: 51, max: 150 },
+ { label: 'Long (151-300)', min: 151, max: 300 },
+ { label: 'Very Long (300+)', min: 301, max: Infinity },
+ ];
+ const captionLengthCorrelation = captionBuckets.map(bucket => {
+ const posts = media.filter(m => {
+ const len = (m.caption || '').length;
+ return len >= bucket.min && len <= bucket.max;
+ });
+ return {
+ label: bucket.label, count: posts.length,
+ avgLikes: posts.length > 0 ? Math.round(posts.reduce((s, m) => s + m.likeCount, 0) / posts.length) : 0,
+ avgComments: posts.length > 0 ? Math.round(posts.reduce((s, m) => s + m.commentsCount, 0) / posts.length) : 0,
+ avgEngagement: posts.length > 0 ? Math.round(posts.reduce((s, m) => s + m.likeCount + m.commentsCount, 0) / posts.length) : 0,
+ };
+ }).filter(b => b.count > 0);
+
+ const topPosts = [...media]
+ .map(m => ({ ...m, engagement: m.likeCount + m.commentsCount }))
+ .sort((a, b) => b.engagement - a.engagement)
+ .slice(0, 10);
+ const worstByLikes = byLikes.length > 0 ? byLikes[byLikes.length - 1] : null;
+
+ const bestEngagement = topPosts[0] ? topPosts[0].engagement : 0;
+ const viralityScore = avgEngagement > 0 ? parseFloat((bestEngagement / avgEngagement).toFixed(1)) : 0;
+
+ let consistencyScore = 0;
+ if (media.length >= 3) {
+ const engagements = media.map(m => m.likeCount + m.commentsCount);
+ const mean = engagements.reduce((s, v) => s + v, 0) / engagements.length;
+ const variance = engagements.reduce((s, v) => s + Math.pow(v - mean, 2), 0) / engagements.length;
+ const stdDev = Math.sqrt(variance);
+ // Social media engagement is inherently high-variance (viral posts skew cv >> 1).
+ // Use 100/(1+cv) so cv=0→100, cv=1→50, cv=2→33 — avoids always-zero for normal accounts.
+ const cv = mean > 0 ? stdDev / mean : (stdDev > 0 ? 10 : 0);
+ consistencyScore = Math.max(0, Math.min(100, Math.round(100 / (1 + cv))));
+ }
+
+ return {
+ totalPosts: profile.mediaCount || media.length,
+ fetchedPosts: media.length,
+ totalLikes, totalComments, totalEngagement,
+ avgLikes, avgComments, avgEngagement,
+ medianLikes, medianComments,
+ engagementRate, likesPerFollower, commentsPerFollower,
+ likesToCommentsRatio,
+ bestByLikes: byLikes[0] || null,
+ bestByComments: byComments[0] || null,
+ worstByLikes,
+ recentMedia: media.slice(0, 20),
+ mediaTypeDistribution: mediaTypes,
+ performanceByType,
+ postFrequency: { perWeek, perMonth },
+ topPosts,
+ postsByDayOfWeek, bestPostingDay,
+ postsByHour, bestPostingHour,
+ engagementTimeline, monthlyBreakdown,
+ postsLast7Days, postsLast30Days, postsLast90Days,
+ hashtagAnalysis,
+ captionLengthCorrelation,
+ viralityScore, consistencyScore,
+ };
+}
+
+module.exports = {
+ igFetch,
+ exchangeForLongLivedToken,
+ refreshLongLivedToken,
+ autoRefreshInstagramTokens,
+ fetchInstagramProfile,
+ fetchInstagramMedia,
+ computeInstagramAnalytics,
+};
diff --git a/backend/services/youtube.js b/backend/services/youtube.js
new file mode 100644
index 0000000..3bfbd70
--- /dev/null
+++ b/backend/services/youtube.js
@@ -0,0 +1,402 @@
+const fetch = require('node-fetch');
+
+async function ytFetch(endpoint, params, apiKey) {
+ const url = new URL(`https://www.googleapis.com/youtube/v3/${endpoint}`);
+ params.key = apiKey;
+ Object.entries(params).forEach(([k, v]) => url.searchParams.set(k, v));
+ const res = await fetch(url.toString());
+ const data = await res.json();
+ if (data.error) throw new Error(data.error.message);
+ return data;
+}
+
+function extractChannelId(input) {
+ if (!input) return null;
+ input = input.trim();
+ if (/^UC[\w-]{22}$/.test(input)) return input;
+ const patterns = [
+ /youtube\.com\/channel\/(UC[\w-]{22})/,
+ /youtube\.com\/@([\w.-]+)/,
+ /youtube\.com\/c\/([\w.-]+)/,
+ /youtube\.com\/user\/([\w.-]+)/,
+ /youtube\.com\/([\w.-]+)/,
+ ];
+ for (const p of patterns) {
+ const m = input.match(p);
+ if (m) return m[1];
+ }
+ return input;
+}
+
+async function resolveChannelId(input, apiKey) {
+ const extracted = extractChannelId(input);
+ if (!extracted) throw new Error('Invalid input');
+ if (/^UC[\w-]{22}$/.test(extracted)) return extracted;
+
+ try {
+ const data = await ytFetch('channels', { part: 'id', forHandle: extracted }, apiKey);
+ if (data.items && data.items.length > 0) return data.items[0].id;
+ } catch { }
+
+ try {
+ const data = await ytFetch('channels', { part: 'id', forUsername: extracted }, apiKey);
+ if (data.items && data.items.length > 0) return data.items[0].id;
+ } catch { }
+
+ try {
+ const data = await ytFetch('search', { part: 'snippet', q: extracted, type: 'channel', maxResults: '1' }, apiKey);
+ if (data.items && data.items.length > 0) return data.items[0].snippet.channelId;
+ } catch { }
+
+ throw new Error('Could not resolve channel. Please provide a valid Channel ID (starts with UC).');
+}
+
+async function fetchChannelData(channelId, apiKey) {
+ const data = await ytFetch('channels', {
+ part: 'snippet,statistics,contentDetails,brandingSettings,status,topicDetails',
+ id: channelId,
+ }, apiKey);
+
+ if (!data.items || data.items.length === 0) throw new Error('Channel not found');
+ const ch = data.items[0];
+
+ return {
+ channelId: ch.id,
+ title: ch.snippet.title,
+ description: ch.snippet.description,
+ customUrl: ch.snippet.customUrl || '',
+ publishedAt: ch.snippet.publishedAt,
+ country: ch.snippet.country || 'Unknown',
+ thumbnails: {
+ default: ch.snippet.thumbnails?.default?.url || '',
+ medium: ch.snippet.thumbnails?.medium?.url || '',
+ high: ch.snippet.thumbnails?.high?.url || '',
+ },
+ subscriberCount: parseInt(ch.statistics.subscriberCount) || 0,
+ viewCount: parseInt(ch.statistics.viewCount) || 0,
+ videoCount: parseInt(ch.statistics.videoCount) || 0,
+ hiddenSubscriberCount: ch.statistics.hiddenSubscriberCount || false,
+ uploadsPlaylistId: ch.contentDetails?.relatedPlaylists?.uploads || '',
+ keywords: ch.brandingSettings?.channel?.keywords || '',
+ bannerUrl: ch.brandingSettings?.image?.bannerExternalUrl || '',
+ madeForKids: ch.status?.madeForKids || false,
+ topicCategories: ch.topicDetails?.topicCategories || [],
+ isLinked: ch.status?.isLinked || false,
+ };
+}
+
+async function fetchAllVideos(playlistId, apiKey, maxPages = 10) {
+ let allVideos = [];
+ let pageToken = '';
+ let page = 0;
+
+ while (page < maxPages) {
+ const params = { part: 'snippet,contentDetails', playlistId, maxResults: '50' };
+ if (pageToken) params.pageToken = pageToken;
+
+ const data = await ytFetch('playlistItems', params, apiKey);
+ if (!data.items || data.items.length === 0) break;
+
+ const videoIds = data.items.map(i => i.snippet.resourceId.videoId).join(',');
+ const statsData = await ytFetch('videos', {
+ part: 'statistics,contentDetails,snippet,status',
+ id: videoIds,
+ }, apiKey);
+
+ if (statsData.items) {
+ allVideos = allVideos.concat(statsData.items.map(v => ({
+ videoId: v.id,
+ title: v.snippet.title,
+ description: v.snippet.description?.substring(0, 200) || '',
+ publishedAt: v.snippet.publishedAt,
+ channelTitle: v.snippet.channelTitle,
+ thumbnails: {
+ default: v.snippet.thumbnails?.default?.url || '',
+ medium: v.snippet.thumbnails?.medium?.url || '',
+ high: v.snippet.thumbnails?.high?.url || '',
+ },
+ tags: v.snippet.tags || [],
+ categoryId: v.snippet.categoryId || '',
+ liveBroadcastContent: v.snippet.liveBroadcastContent || 'none',
+ defaultAudioLanguage: v.snippet.defaultAudioLanguage || '',
+ duration: v.contentDetails.duration,
+ dimension: v.contentDetails.dimension || '2d',
+ definition: v.contentDetails.definition || 'hd',
+ caption: v.contentDetails.caption === 'true',
+ licensedContent: v.contentDetails.licensedContent || false,
+ projection: v.contentDetails.projection || 'rectangular',
+ viewCount: parseInt(v.statistics.viewCount) || 0,
+ likeCount: parseInt(v.statistics.likeCount) || 0,
+ commentCount: parseInt(v.statistics.commentCount) || 0,
+ privacyStatus: v.status?.privacyStatus || 'public',
+ embeddable: v.status?.embeddable || false,
+ madeForKids: v.status?.madeForKids || false,
+ })));
+ }
+
+ pageToken = data.nextPageToken || '';
+ if (!pageToken) break;
+ page++;
+ }
+
+ return allVideos;
+}
+
+function parseDuration(iso) {
+ const m = iso.match(/PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?/);
+ if (!m) return 0;
+ return (parseInt(m[1] || 0) * 3600) + (parseInt(m[2] || 0) * 60) + parseInt(m[3] || 0);
+}
+
+function formatCompact(n) {
+ if (n >= 1e6) return (n / 1e6).toFixed(1) + 'M';
+ if (n >= 1e3) return (n / 1e3).toFixed(1) + 'K';
+ return n.toString();
+}
+
+function computeVideoAnalytics(videos) {
+ if (!videos || videos.length === 0) {
+ return {
+ totalVideos: 0, totalViews: 0, totalLikes: 0, totalComments: 0,
+ avgViews: 0, avgLikes: 0, avgComments: 0, medianViews: 0,
+ totalEngagement: 0, overallEngagementRate: 0,
+ avgDurationSeconds: 0, avgDurationFormatted: '0:00',
+ totalDurationSeconds: 0, totalDurationFormatted: '0:00',
+ bestByViews: null, bestByLikes: null, bestByComments: null,
+ bestByEngagement: null, worstByViews: null,
+ mostRecent: null, oldest: null,
+ top10ByViews: [], top10ByLikes: [], top10ByComments: [], top10ByEngagement: [],
+ shortsCount: 0, regularCount: 0,
+ avgShortViews: 0, avgRegularViews: 0,
+ hdCount: 0, sdCount: 0, hdPercentage: 0,
+ captionCount: 0, captionPercentage: 0,
+ licensedCount: 0, licensedPercentage: 0,
+ madeForKidsCount: 0, embeddableCount: 0,
+ publishDayDistribution: {}, publishHourDistribution: {},
+ peakPublishDay: '', peakPublishHour: 0,
+ durationDistribution: { short: 0, medium: 0, long: 0, veryLong: 0 },
+ categoryDistribution: {},
+ tagFrequency: [],
+ videosLast7Days: 0, videosLast30Days: 0, videosLast90Days: 0, videosLast365Days: 0,
+ uploadFrequencyPerWeek: 0, uploadFrequencyPerMonth: 0,
+ consistencyScore: 0, viralityScore: 0,
+ viewsDistribution: { ranges: [], counts: [] },
+ engagementTrend: [], viewsTrend: [], likeRateTrend: [],
+ };
+ }
+
+ const now = new Date();
+ const durations = videos.map(v => parseDuration(v.duration));
+ const totalDuration = durations.reduce((a, b) => a + b, 0);
+
+ const withEngagement = videos.map(v => ({
+ ...v,
+ engagementRate: v.viewCount > 0 ? ((v.likeCount + v.commentCount) / v.viewCount) * 100 : 0,
+ likeRate: v.viewCount > 0 ? (v.likeCount / v.viewCount) * 100 : 0,
+ commentRate: v.viewCount > 0 ? (v.commentCount / v.viewCount) * 100 : 0,
+ durationSeconds: parseDuration(v.duration),
+ daysSinceUpload: Math.max(1, Math.floor((now - new Date(v.publishedAt)) / 86400000)),
+ }));
+
+ const viewsSorted = [...withEngagement].sort((a, b) => b.viewCount - a.viewCount);
+ const likesSorted = [...withEngagement].sort((a, b) => b.likeCount - a.likeCount);
+ const commentsSorted = [...withEngagement].sort((a, b) => b.commentCount - a.commentCount);
+ const dateSorted = [...withEngagement].sort((a, b) => new Date(b.publishedAt) - new Date(a.publishedAt));
+ const engagementSorted = [...withEngagement].sort((a, b) => b.engagementRate - a.engagementRate);
+
+ const totalViews = videos.reduce((s, v) => s + v.viewCount, 0);
+ const totalLikes = videos.reduce((s, v) => s + v.likeCount, 0);
+ const totalComments = videos.reduce((s, v) => s + v.commentCount, 0);
+ const avgViews = Math.round(totalViews / videos.length);
+ const avgLikes = Math.round(totalLikes / videos.length);
+ const avgComments = Math.round(totalComments / videos.length);
+
+ const sortedViews = [...videos].map(v => v.viewCount).sort((a, b) => a - b);
+ const mid = Math.floor(sortedViews.length / 2);
+ const medianViews = sortedViews.length % 2 ? sortedViews[mid] : Math.round((sortedViews[mid - 1] + sortedViews[mid]) / 2);
+
+ const shorts = withEngagement.filter(v => v.durationSeconds <= 60);
+ const regular = withEngagement.filter(v => v.durationSeconds > 60);
+
+ const durationDist = { short: 0, medium: 0, long: 0, veryLong: 0 };
+ withEngagement.forEach(v => {
+ if (v.durationSeconds <= 60) durationDist.short++;
+ else if (v.durationSeconds <= 600) durationDist.medium++;
+ else if (v.durationSeconds <= 3600) durationDist.long++;
+ else durationDist.veryLong++;
+ });
+
+ const hdCount = videos.filter(v => v.definition === 'hd').length;
+ const captionCount = videos.filter(v => v.caption).length;
+ const licensedCount = videos.filter(v => v.licensedContent).length;
+ const madeForKidsCount = videos.filter(v => v.madeForKids).length;
+ const embeddableCount = videos.filter(v => v.embeddable).length;
+
+ const dayDist = {};
+ const hourDist = {};
+ const dayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
+ videos.forEach(v => {
+ const d = new Date(v.publishedAt);
+ const day = dayNames[d.getUTCDay()];
+ const hour = d.getUTCHours();
+ dayDist[day] = (dayDist[day] || 0) + 1;
+ hourDist[hour] = (hourDist[hour] || 0) + 1;
+ });
+
+ const peakDay = Object.entries(dayDist).sort((a, b) => b[1] - a[1])[0];
+ const peakHour = Object.entries(hourDist).sort((a, b) => b[1] - a[1])[0];
+
+ const catDist = {};
+ videos.forEach(v => {
+ const cat = v.categoryId || 'Unknown';
+ catDist[cat] = (catDist[cat] || 0) + 1;
+ });
+
+ const tagMap = {};
+ videos.forEach(v => {
+ (v.tags || []).forEach(t => {
+ const lower = t.toLowerCase();
+ tagMap[lower] = (tagMap[lower] || 0) + 1;
+ });
+ });
+ const tagFrequency = Object.entries(tagMap)
+ .sort((a, b) => b[1] - a[1])
+ .slice(0, 30)
+ .map(([tag, count]) => ({ tag, count }));
+
+ const msDay = 86400000;
+ const videosLast7 = videos.filter(v => (now - new Date(v.publishedAt)) < 7 * msDay).length;
+ const videosLast30 = videos.filter(v => (now - new Date(v.publishedAt)) < 30 * msDay).length;
+ const videosLast90 = videos.filter(v => (now - new Date(v.publishedAt)) < 90 * msDay).length;
+ const videosLast365 = videos.filter(v => (now - new Date(v.publishedAt)) < 365 * msDay).length;
+
+ const oldestDate = new Date(dateSorted[dateSorted.length - 1]?.publishedAt || now);
+ const totalWeeks = Math.max(1, (now - oldestDate) / (7 * msDay));
+ const totalMonths = Math.max(1, totalWeeks / 4.33);
+
+ const weeklyUploads = videos.reduce((acc, v) => {
+ const weekNum = Math.floor((now - new Date(v.publishedAt)) / (7 * msDay));
+ acc[weekNum] = (acc[weekNum] || 0) + 1;
+ return acc;
+ }, {});
+ const weekValues = Object.values(weeklyUploads);
+ const avgWeekly = weekValues.reduce((a, b) => a + b, 0) / Math.max(1, weekValues.length);
+ const variance = weekValues.reduce((s, v) => s + Math.pow(v - avgWeekly, 2), 0) / Math.max(1, weekValues.length);
+ const stdDev = Math.sqrt(variance);
+ const consistencyScore = Math.max(0, Math.min(100, Math.round(100 - (stdDev / Math.max(0.01, avgWeekly)) * 25)));
+
+ const viralityScore = avgViews > 0 ? Math.round((viewsSorted[0]?.viewCount || 0) / avgViews * 10) / 10 : 0;
+
+ const maxViews = viewsSorted[0]?.viewCount || 0;
+ const step = Math.max(1, Math.ceil(maxViews / 10));
+ const viewsRanges = [];
+ const viewsCounts = [];
+ for (let i = 0; i < 10; i++) {
+ const low = i * step;
+ const high = (i + 1) * step;
+ viewsRanges.push(`${formatCompact(low)}-${formatCompact(high)}`);
+ viewsCounts.push(videos.filter(v => v.viewCount >= low && v.viewCount < high).length);
+ }
+
+ const monthlyData = {};
+ withEngagement.forEach(v => {
+ const d = new Date(v.publishedAt);
+ const key = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`;
+ if (!monthlyData[key]) monthlyData[key] = { views: 0, likes: 0, comments: 0, count: 0 };
+ monthlyData[key].views += v.viewCount;
+ monthlyData[key].likes += v.likeCount;
+ monthlyData[key].comments += v.commentCount;
+ monthlyData[key].count++;
+ });
+ const sortedMonths = Object.keys(monthlyData).sort();
+ const viewsTrend = sortedMonths.map(m => ({ month: m, value: monthlyData[m].views, count: monthlyData[m].count }));
+ const engagementTrend = sortedMonths.map(m => ({
+ month: m,
+ value: monthlyData[m].views > 0
+ ? ((monthlyData[m].likes + monthlyData[m].comments) / monthlyData[m].views * 100).toFixed(2)
+ : 0,
+ }));
+ const likeRateTrend = sortedMonths.map(m => ({
+ month: m,
+ value: monthlyData[m].views > 0 ? ((monthlyData[m].likes / monthlyData[m].views) * 100).toFixed(2) : 0,
+ }));
+
+ const formatDuration = (s) => {
+ const h = Math.floor(s / 3600);
+ const m = Math.floor((s % 3600) / 60);
+ const sec = s % 60;
+ return h > 0 ? `${h}h ${m}m` : `${m}m ${sec}s`;
+ };
+
+ const formatVid = (v) => v ? {
+ videoId: v.videoId, title: v.title, viewCount: v.viewCount,
+ likeCount: v.likeCount, commentCount: v.commentCount,
+ publishedAt: v.publishedAt,
+ thumbnail: v.thumbnails?.medium || v.thumbnails?.default || '',
+ engagementRate: v.engagementRate?.toFixed(2) || 0,
+ durationSeconds: v.durationSeconds || parseDuration(v.duration),
+ } : null;
+
+ return {
+ totalVideos: videos.length,
+ totalViews, totalLikes, totalComments,
+ avgViews, avgLikes, avgComments, medianViews,
+ totalEngagement: totalLikes + totalComments,
+ overallEngagementRate: totalViews > 0 ? ((totalLikes + totalComments) / totalViews * 100).toFixed(2) : 0,
+ avgDurationSeconds: Math.round(totalDuration / videos.length),
+ avgDurationFormatted: formatDuration(Math.round(totalDuration / videos.length)),
+ totalDurationSeconds: totalDuration,
+ totalDurationFormatted: formatDuration(totalDuration),
+ estimatedTotalWatchTimeHours: Math.round((totalDuration * totalViews) / 3600),
+ bestByViews: formatVid(viewsSorted[0]),
+ bestByLikes: formatVid(likesSorted[0]),
+ bestByComments: formatVid(commentsSorted[0]),
+ bestByEngagement: formatVid(engagementSorted[0]),
+ worstByViews: formatVid(viewsSorted[viewsSorted.length - 1]),
+ mostRecent: formatVid(dateSorted[0]),
+ oldest: formatVid(dateSorted[dateSorted.length - 1]),
+ top10ByViews: viewsSorted.slice(0, 10).map(formatVid),
+ top10ByLikes: likesSorted.slice(0, 10).map(formatVid),
+ top10ByComments: commentsSorted.slice(0, 10).map(formatVid),
+ top10ByEngagement: engagementSorted.slice(0, 10).map(formatVid),
+ shortsCount: shorts.length,
+ regularCount: regular.length,
+ avgShortViews: shorts.length > 0 ? Math.round(shorts.reduce((s, v) => s + v.viewCount, 0) / shorts.length) : 0,
+ avgRegularViews: regular.length > 0 ? Math.round(regular.reduce((s, v) => s + v.viewCount, 0) / regular.length) : 0,
+ avgShortLikes: shorts.length > 0 ? Math.round(shorts.reduce((s, v) => s + v.likeCount, 0) / shorts.length) : 0,
+ avgRegularLikes: regular.length > 0 ? Math.round(regular.reduce((s, v) => s + v.likeCount, 0) / regular.length) : 0,
+ hdCount, sdCount: videos.length - hdCount,
+ hdPercentage: ((hdCount / videos.length) * 100).toFixed(1),
+ captionCount, captionPercentage: ((captionCount / videos.length) * 100).toFixed(1),
+ licensedCount, licensedPercentage: ((licensedCount / videos.length) * 100).toFixed(1),
+ madeForKidsCount, embeddableCount,
+ embeddablePercentage: ((embeddableCount / videos.length) * 100).toFixed(1),
+ publishDayDistribution: dayDist,
+ publishHourDistribution: hourDist,
+ peakPublishDay: peakDay ? peakDay[0] : '',
+ peakPublishHour: peakHour ? parseInt(peakHour[0]) : 0,
+ durationDistribution: durationDist,
+ categoryDistribution: catDist,
+ tagFrequency,
+ videosLast7Days: videosLast7,
+ videosLast30Days: videosLast30,
+ videosLast90Days: videosLast90,
+ videosLast365Days: videosLast365,
+ uploadFrequencyPerWeek: (videos.length / totalWeeks).toFixed(1),
+ uploadFrequencyPerMonth: (videos.length / totalMonths).toFixed(1),
+ consistencyScore, viralityScore,
+ viewsDistribution: { ranges: viewsRanges, counts: viewsCounts },
+ viewsTrend, engagementTrend, likeRateTrend,
+ };
+}
+
+module.exports = {
+ ytFetch,
+ extractChannelId,
+ resolveChannelId,
+ fetchChannelData,
+ fetchAllVideos,
+ parseDuration,
+ computeVideoAnalytics,
+ formatCompact,
+};
diff --git a/backend/utils/dataHelpers.js b/backend/utils/dataHelpers.js
new file mode 100644
index 0000000..f256c1d
--- /dev/null
+++ b/backend/utils/dataHelpers.js
@@ -0,0 +1,73 @@
+const fs = require('fs').promises;
+const path = require('path');
+
+const DATA_DIR = path.join(__dirname, '..', 'data');
+const ACCOUNTS_FILE = path.join(DATA_DIR, 'accounts.json');
+const API_KEYS_FILE = path.join(DATA_DIR, 'api_keys.json');
+const VIDEOS_CACHE_FILE = path.join(DATA_DIR, 'videos_cache.json');
+const IG_CACHE_FILE = path.join(DATA_DIR, 'ig_cache.json');
+const SCHEDULED_POSTS_FILE = path.join(DATA_DIR, 'scheduled_posts.json');
+
+async function initializeData() {
+ try {
+ await fs.mkdir(DATA_DIR, { recursive: true });
+ const defaults = [
+ [ACCOUNTS_FILE, []],
+ [API_KEYS_FILE, { youtube: '', instagram: { appId: '', appSecret: '' }, cloudinary: { cloudName: '', uploadPreset: '' }, github: { token: '', repo: '', branch: 'main' } }],
+ [VIDEOS_CACHE_FILE, {}],
+ [IG_CACHE_FILE, {}],
+ [SCHEDULED_POSTS_FILE, []],
+ ];
+ for (const [file, defaultData] of defaults) {
+ try {
+ await fs.access(file);
+ } catch {
+ await fs.writeFile(file, JSON.stringify(defaultData, null, 2));
+ }
+ }
+ console.log('Data files initialized');
+ } catch (err) {
+ console.error('Init error:', err);
+ }
+}
+
+async function readJSON(filePath) {
+ try {
+ return JSON.parse(await fs.readFile(filePath, 'utf8'));
+ } catch {
+ return null;
+ }
+}
+
+async function writeJSON(filePath, data) {
+ try {
+ await fs.writeFile(filePath, JSON.stringify(data, null, 2));
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+async function getAPIKey() {
+ const keys = await readJSON(API_KEYS_FILE);
+ return keys?.youtube || '';
+}
+
+async function getIGAppCredentials() {
+ const keys = await readJSON(API_KEYS_FILE);
+ return keys?.instagram || { appId: '', appSecret: '' };
+}
+
+module.exports = {
+ DATA_DIR,
+ ACCOUNTS_FILE,
+ API_KEYS_FILE,
+ VIDEOS_CACHE_FILE,
+ IG_CACHE_FILE,
+ SCHEDULED_POSTS_FILE,
+ initializeData,
+ readJSON,
+ writeJSON,
+ getAPIKey,
+ getIGAppCredentials,
+};
diff --git a/backend/utils/scheduler.js b/backend/utils/scheduler.js
new file mode 100644
index 0000000..626c640
--- /dev/null
+++ b/backend/utils/scheduler.js
@@ -0,0 +1,117 @@
+const fetch = require('node-fetch');
+const { readJSON, writeJSON, SCHEDULED_POSTS_FILE, ACCOUNTS_FILE } = require('./dataHelpers');
+
+function generateId() {
+ return Date.now().toString(36) + Math.random().toString(36).substring(2, 8);
+}
+
+let isProcessing = false;
+
+async function processScheduledPosts() {
+ if (isProcessing) return { processed: 0, message: 'Already processing' };
+ isProcessing = true;
+ let processed = 0;
+ let errors = [];
+
+ try {
+ const posts = await readJSON(SCHEDULED_POSTS_FILE) || [];
+ const accounts = await readJSON(ACCOUNTS_FILE) || [];
+ const now = new Date();
+
+ for (const post of posts) {
+ if (post.status !== 'pending') continue;
+ const scheduledDate = new Date(post.scheduledAt);
+ if (scheduledDate > now) continue;
+
+ post.status = 'publishing';
+ await writeJSON(SCHEDULED_POSTS_FILE, posts);
+
+ try {
+ const acct = accounts.find(a => a.id === post.accountId);
+ if (!acct) throw new Error('Account not found: ' + post.accountId);
+
+ const igId = acct.igUserId;
+ const token = acct.accessToken;
+ const params = { access_token: token };
+
+ if (post.mediaType === 'REELS') {
+ params.media_type = 'REELS';
+ params.video_url = post.mediaUrl;
+ if (post.caption) params.caption = post.caption;
+ if (post.shareToFeed !== undefined) params.share_to_feed = post.shareToFeed;
+ if (post.coverUrl) params.cover_url = post.coverUrl;
+ if (post.collaborators?.length) params.collaborators = JSON.stringify(post.collaborators);
+ if (post.audioName) params.audio_name = post.audioName;
+ if (post.thumbOffset != null) params.thumb_offset = post.thumbOffset;
+ if (post.locationId) params.location_id = post.locationId;
+ if (post.userTags?.length) params.user_tags = JSON.stringify(post.userTags);
+ } else if (post.mediaType === 'STORIES') {
+ params.media_type = 'STORIES';
+ if (post.mediaUrl.match(/\.(mp4|mov|avi|webm)/i)) {
+ params.video_url = post.mediaUrl;
+ } else {
+ params.image_url = post.mediaUrl;
+ }
+ if (post.userTags?.length) params.user_tags = JSON.stringify(post.userTags);
+ } else {
+ params.image_url = post.mediaUrl;
+ if (post.caption) params.caption = post.caption;
+ if (post.locationId) params.location_id = post.locationId;
+ if (post.userTags?.length) params.user_tags = JSON.stringify(post.userTags);
+ if (post.altText) params.alt_text = post.altText;
+ }
+
+ const qs = new URLSearchParams(params).toString();
+ const createRes = await fetch(`https://graph.instagram.com/v25.0/${igId}/media?${qs}`, { method: 'POST' });
+ const createData = await createRes.json();
+ if (createData.error) throw new Error(createData.error.message);
+
+ const containerId = createData.id;
+
+ if (post.mediaType === 'REELS' || post.mediaType === 'STORIES') {
+ for (let i = 0; i < 60; i++) {
+ await new Promise(r => setTimeout(r, 3000));
+ const statusRes = await fetch(
+ `https://graph.instagram.com/v25.0/${containerId}?fields=status_code,status&access_token=${token}`
+ );
+ const statusData = await statusRes.json();
+ if (statusData.status_code === 'FINISHED' || statusData.status_code === 'PUBLISHED') break;
+ if (statusData.status_code === 'ERROR') throw new Error('Processing failed: ' + (statusData.status || ''));
+ if (statusData.status_code === 'EXPIRED') throw new Error('Container expired');
+ }
+ } else {
+ await new Promise(r => setTimeout(r, 2000));
+ }
+
+ const pubRes = await fetch(
+ `https://graph.instagram.com/v25.0/${igId}/media_publish?creation_id=${containerId}&access_token=${token}`,
+ { method: 'POST' }
+ );
+ const pubData = await pubRes.json();
+ if (pubData.error) throw new Error(pubData.error.message);
+
+ post.status = 'published';
+ post.publishedMediaId = pubData.id;
+ post.publishedAt = new Date().toISOString();
+ processed++;
+ console.log(` ✓ Published scheduled post ${post.id} → media ${pubData.id}`);
+
+ } catch (err) {
+ post.status = 'failed';
+ post.error = err.message;
+ errors.push({ id: post.id, error: err.message });
+ console.error(` ✗ Failed to publish scheduled post ${post.id}: ${err.message}`);
+ }
+
+ await writeJSON(SCHEDULED_POSTS_FILE, posts);
+ }
+ } catch (err) {
+ console.error('Scheduler error:', err);
+ } finally {
+ isProcessing = false;
+ }
+
+ return { processed, errors };
+}
+
+module.exports = { generateId, processScheduledPosts, get isProcessing() { return isProcessing; } };
diff --git a/frontend/index.html b/frontend/index.html
index 46528ac..3f1656e 100644
--- a/frontend/index.html
+++ b/frontend/index.html
@@ -3,9 +3,12 @@
<head>
<meta charset="UTF-8" />
- <link rel="icon" type="image/svg+xml" href="/logo.svg" />
+ <link rel="icon" type="image/png" href="/logo.png" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
- <title>YT Analytics Dashboard Pro</title>
+ <title>Twiligent</title>
+ <link rel="preconnect" href="https://fonts.googleapis.com" />
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
+ <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet" />
</head>
<body>
@@ -13,4 +16,4 @@
<script type="module" src="/src/main.jsx"></script>
</body>
-</html>
\ No newline at end of file
+</html>
diff --git a/frontend/public/logo.png b/frontend/public/logo.png
new file mode 100644
index 0000000..3a19296
Binary files /dev/null and b/frontend/public/logo.png differ
diff --git a/frontend/public/logo.svg b/frontend/public/logo.svg
deleted file mode 100644
index 4e31651..0000000
--- a/frontend/public/logo.svg
+++ /dev/null
@@ -1,26 +0,0 @@
-<svg width="120" height="120" viewBox="0 0 120 120" fill="none" xmlns="http://www.w3.org/2000/svg">
- <defs>
- <linearGradient id="logoBg" x1="0" y1="0" x2="120" y2="120" gradientUnits="userSpaceOnUse">
- <stop offset="0%" stop-color="#FF0000"/>
- <stop offset="100%" stop-color="#CC0000"/>
- </linearGradient>
- <linearGradient id="barGrad1" x1="0" y1="100" x2="0" y2="30" gradientUnits="userSpaceOnUse">
- <stop offset="0%" stop-color="#FFFFFF" stop-opacity="0.95"/>
- <stop offset="100%" stop-color="#FFFFFF" stop-opacity="0.7"/>
- </linearGradient>
- <linearGradient id="playGrad" x1="70" y1="20" x2="110" y2="55" gradientUnits="userSpaceOnUse">
- <stop offset="0%" stop-color="#FFFFFF"/>
- <stop offset="100%" stop-color="#FFD4D4"/>
- </linearGradient>
- </defs>
- <rect width="120" height="120" rx="28" fill="url(#logoBg)"/>
- <rect x="18" y="72" width="16" height="26" rx="4" fill="url(#barGrad1)" opacity="0.9"/>
- <rect x="40" y="52" width="16" height="46" rx="4" fill="url(#barGrad1)" opacity="0.95"/>
- <rect x="62" y="36" width="16" height="62" rx="4" fill="url(#barGrad1)"/>
- <path d="M26 68 L48 48 L70 32" stroke="#FFFFFF" stroke-width="4" stroke-linecap="round" stroke-linejoin="round" fill="none" opacity="0.6"/>
- <g transform="translate(82, 18)">
- <rect width="30" height="22" rx="5" fill="rgba(255,255,255,0.2)"/>
- <path d="M11 5 L23 11 L11 17Z" fill="url(#playGrad)"/>
- </g>
- <circle cx="70" cy="32" r="4" fill="#FFFFFF" opacity="0.9"/>
-</svg>
diff --git a/frontend/public/screenshots/All Shorts.png b/frontend/public/screenshots/All Shorts.png
new file mode 100644
index 0000000..d6ece5e
Binary files /dev/null and b/frontend/public/screenshots/All Shorts.png differ
diff --git a/frontend/public/screenshots/All Videos.png b/frontend/public/screenshots/All Videos.png
new file mode 100644
index 0000000..c769498
Binary files /dev/null and b/frontend/public/screenshots/All Videos.png differ
diff --git a/frontend/public/screenshots/Dashboard Overview.png b/frontend/public/screenshots/Dashboard Overview.png
new file mode 100644
index 0000000..8832c77
Binary files /dev/null and b/frontend/public/screenshots/Dashboard Overview.png differ
diff --git a/frontend/public/screenshots/IG Content Explorer.png b/frontend/public/screenshots/IG Content Explorer.png
new file mode 100644
index 0000000..2b61b78
Binary files /dev/null and b/frontend/public/screenshots/IG Content Explorer.png differ
diff --git a/frontend/public/screenshots/Instagram Account Overview.png b/frontend/public/screenshots/Instagram Account Overview.png
new file mode 100644
index 0000000..4f23c21
Binary files /dev/null and b/frontend/public/screenshots/Instagram Account Overview.png differ
diff --git a/frontend/public/screenshots/Manage Accounts.png b/frontend/public/screenshots/Manage Accounts.png
new file mode 100644
index 0000000..1149b29
Binary files /dev/null and b/frontend/public/screenshots/Manage Accounts.png differ
diff --git a/frontend/public/screenshots/Settings.png b/frontend/public/screenshots/Settings.png
new file mode 100644
index 0000000..9b43e66
Binary files /dev/null and b/frontend/public/screenshots/Settings.png differ
diff --git a/frontend/public/screenshots/Upload Content.png b/frontend/public/screenshots/Upload Content.png
new file mode 100644
index 0000000..4e541e5
Binary files /dev/null and b/frontend/public/screenshots/Upload Content.png differ
diff --git a/frontend/public/screenshots/YouTube Account Overview.png b/frontend/public/screenshots/YouTube Account Overview.png
new file mode 100644
index 0000000..8e2e9b8
Binary files /dev/null and b/frontend/public/screenshots/YouTube Account Overview.png differ
diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx
index a1529d8..0bf7584 100644
--- a/frontend/src/App.jsx
+++ b/frontend/src/App.jsx
@@ -1,16 +1,16 @@
import React, { useState, useEffect, useCallback } from 'react';
import { ThemeProvider, CssBaseline, Box, Snackbar, Alert } from '@mui/material';
import theme from './theme';
-import Sidebar from './components/Sidebar';
-import Overview from './components/Overview';
-import ChannelAnalytics from './components/ChannelAnalytics';
-import AccountManager from './components/AccountManager';
-import Settings from './components/Settings';
-import VideoExplorer from './components/VideoExplorer';
-import ShortsExplorer from './components/ShortsExplorer';
-import ReelsExplorer from './components/ReelsExplorer';
-import InstagramAnalytics from './components/InstagramAnalytics';
-import UploadContent from './components/UploadContent';
+import Sidebar from './layouts/Sidebar';
+import Overview from './features/analytics/overview/Overview';
+import ChannelAnalytics from './features/analytics/channel/ChannelAnalytics';
+import AccountManager from './features/accounts/AccountManager';
+import Settings from './features/settings/Settings';
+import VideoExplorer from './features/analytics/videos/VideoExplorer';
+import ShortsExplorer from './features/analytics/shorts/ShortsExplorer';
+import ReelsExplorer from './features/analytics/reels/ReelsExplorer';
+import InstagramAnalytics from './features/analytics/instagram/InstagramAnalytics';
+import UploadContent from './features/publishing/UploadContent';
import { api } from './services/api';
import { normalizeAccount } from './utils/formatters';
diff --git a/frontend/src/assets/react.svg b/frontend/src/assets/react.svg
deleted file mode 100644
index 6c87de9..0000000
--- a/frontend/src/assets/react.svg
+++ /dev/null
@@ -1 +0,0 @@
-<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>
\ No newline at end of file
diff --git a/frontend/src/components/Logo.jsx b/frontend/src/components/Logo.jsx
deleted file mode 100644
index 97d7144..0000000
--- a/frontend/src/components/Logo.jsx
+++ /dev/null
@@ -1,70 +0,0 @@
-import React from 'react';
-import { Box } from '@mui/material';
-
-export default function Logo({ size = 40 }) {
- return (
- <Box
- sx={{
- width: size,
- height: size,
- flexShrink: 0,
- position: 'relative',
- }}
- >
- <svg
- width={size}
- height={size}
- viewBox="0 0 120 120"
- fill="none"
- xmlns="http://www.w3.org/2000/svg"
- >
- {/* Background circle with gradient */}
- <defs>
- <linearGradient id="logoBg" x1="0" y1="0" x2="120" y2="120" gradientUnits="userSpaceOnUse">
- <stop offset="0%" stopColor="#FF0000" />
- <stop offset="100%" stopColor="#CC0000" />
- </linearGradient>
- <linearGradient id="barGrad1" x1="0" y1="100" x2="0" y2="30" gradientUnits="userSpaceOnUse">
- <stop offset="0%" stopColor="#FFFFFF" stopOpacity="0.95" />
- <stop offset="100%" stopColor="#FFFFFF" stopOpacity="0.7" />
- </linearGradient>
- <linearGradient id="playGrad" x1="70" y1="20" x2="110" y2="55" gradientUnits="userSpaceOnUse">
- <stop offset="0%" stopColor="#FFFFFF" />
- <stop offset="100%" stopColor="#FFD4D4" />
- </linearGradient>
- <filter id="shadow" x="-4" y="-2" width="128" height="128">
- <feDropShadow dx="0" dy="2" stdDeviation="3" floodColor="#000" floodOpacity="0.25" />
- </filter>
- </defs>
-
- {/* Main circle */}
- <rect width="120" height="120" rx="28" fill="url(#logoBg)" filter="url(#shadow)" />
-
- {/* Analytics bars */}
- <rect x="18" y="72" width="16" height="26" rx="4" fill="url(#barGrad1)" opacity="0.9" />
- <rect x="40" y="52" width="16" height="46" rx="4" fill="url(#barGrad1)" opacity="0.95" />
- <rect x="62" y="36" width="16" height="62" rx="4" fill="url(#barGrad1)" />
-
- {/* Upward trend line */}
- <path
- d="M26 68 L48 48 L70 32"
- stroke="#FFFFFF"
- strokeWidth="4"
- strokeLinecap="round"
- strokeLinejoin="round"
- fill="none"
- opacity="0.6"
- />
-
- {/* Play button triangle (YouTube) */}
- <g transform="translate(82, 18)">
- <rect width="30" height="22" rx="5" fill="rgba(255,255,255,0.2)" />
- <path d="M11 5 L23 11 L11 17Z" fill="url(#playGrad)" />
- </g>
-
- {/* Subtle dot accent */}
- <circle cx="70" cy="32" r="4" fill="#FFFFFF" opacity="0.9" />
- </svg>
- </Box>
- );
-}
diff --git a/frontend/src/components/Overview.jsx b/frontend/src/components/Overview.jsx
deleted file mode 100644
index a720604..0000000
--- a/frontend/src/components/Overview.jsx
+++ /dev/null
@@ -1,282 +0,0 @@
-import React from 'react';
-import {
- Box, Typography, Grid, Card, CardContent, Button, Avatar, Chip,
- LinearProgress, Table, TableBody, TableCell, TableContainer, TableHead, TableRow,
- IconButton, Tooltip, Paper, Divider,
-} from '@mui/material';
-import {
- Visibility, People, VideoLibrary, YouTube, Refresh, TrendingUp,
- EmojiEvents, OpenInNew, Speed, BarChart, Instagram, Favorite, Photo,
-} from '@mui/icons-material';
-import {
- BarChart as ReBarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip as ReTooltip,
- ResponsiveContainer, PieChart, Pie, Cell, Legend,
-} from 'recharts';
-import StatCard from './StatCard';
-import { fmtNum, fmtNumFull, fmtDate, timeAgo } from '../utils/formatters';
-
-const COLORS = ['#FF0000', '#3EA6FF', '#4CAF50', '#FF9800', '#AB47BC', '#26A69A', '#EC407A', '#5C6BC0'];
-
-export default function Overview({ accounts, onViewChannel, onRefreshAll, loading }) {
- const ytAccounts = accounts.filter(a => a.platform !== 'instagram');
- const igAccounts = accounts.filter(a => a.platform === 'instagram');
-
- const totals = accounts.reduce((acc, a) => {
- if (a.platform === 'instagram') {
- return {
- ...acc,
- followers: acc.followers + (a.followersCount || 0),
- posts: acc.posts + (a.mediaCount || 0),
- };
- }
- return {
- ...acc,
- subscribers: acc.subscribers + (a.subscriberCount || 0),
- views: acc.views + (a.viewCount || 0),
- videos: acc.videos + (a.videoCount || 0),
- };
- }, { subscribers: 0, views: 0, videos: 0, followers: 0, posts: 0 });
-
- const totalAudience = totals.subscribers + totals.followers;
-
- const sorted = {
- byAudience: [...accounts].sort((a, b) => (b.subscriberCount || b.followersCount || 0) - (a.subscriberCount || a.followersCount || 0)),
- byContent: [...accounts].sort((a, b) => (b.viewCount || b.mediaCount || 0) - (a.viewCount || a.mediaCount || 0)),
- };
-
- const chartData = accounts.map(a => ({
- name: a.title?.length > 20 ? a.title.substring(0, 20) + '...' : a.title,
- audience: a.subscriberCount || a.followersCount || 0,
- platform: a.platform || 'youtube',
- }));
-
- const pieData = accounts.map((a, i) => ({
- name: a.title?.length > 15 ? a.title.substring(0, 15) + '...' : a.title,
- value: a.subscriberCount || a.followersCount || 0,
- color: COLORS[i % COLORS.length],
- }));
-
- return (
- <Box>
- {/* Header */}
- <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', mb: 3 }}>
- <Box>
- <Typography variant="h4" sx={{ fontWeight: 700, mb: 0.5 }}>Dashboard Overview</Typography>
- <Typography variant="body2" sx={{ color: 'text.secondary' }}>
- Combined analytics across {accounts.length} account{accounts.length !== 1 ? 's' : ''}
- {ytAccounts.length > 0 && igAccounts.length > 0 && ` (${ytAccounts.length} YouTube, ${igAccounts.length} Instagram)`}
- </Typography>
- </Box>
- <Button variant="contained" startIcon={<Refresh />} onClick={onRefreshAll}
- disabled={loading || accounts.length === 0}
- sx={{ background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)' }}>
- {loading ? 'Refreshing...' : 'Refresh All'}
- </Button>
- </Box>
-
- {loading && <LinearProgress sx={{ mb: 2, borderRadius: 1 }} color="error" />}
-
- {/* KPI Cards */}
- <Grid container spacing={2.5} sx={{ mb: 3 }}>
- <Grid size={{ xs: 12, sm: 6, md: 3 }}>
- <StatCard icon={<People />} label="Total Audience" value={fmtNum(totalAudience)}
- subtitle={`${fmtNum(totals.subscribers)} subs + ${fmtNum(totals.followers)} followers`} gradient="green" />
- </Grid>
- <Grid size={{ xs: 12, sm: 6, md: 3 }}>
- <StatCard icon={<Visibility />} label="Total YT Views" value={fmtNum(totals.views)}
- subtitle={fmtNumFull(totals.views)} gradient="red" />
- </Grid>
- <Grid size={{ xs: 12, sm: 6, md: 3 }}>
- <StatCard icon={<VideoLibrary />} label="Total Content" value={fmtNum(totals.videos + totals.posts)}
- subtitle={`${fmtNum(totals.videos)} videos + ${fmtNum(totals.posts)} posts`} gradient="orange" />
- </Grid>
- <Grid size={{ xs: 12, sm: 6, md: 3 }}>
- <StatCard icon={<BarChart />} label="Accounts" value={accounts.length}
- subtitle={`${ytAccounts.length} YT · ${igAccounts.length} IG`} gradient="purple" />
- </Grid>
- </Grid>
-
- {accounts.length === 0 ? (
- <Card sx={{ p: 6, textAlign: 'center' }}>
- <People sx={{ fontSize: 64, color: 'text.secondary', mb: 2 }} />
- <Typography variant="h5" sx={{ mb: 1 }}>Welcome to Social Media Analytics</Typography>
- <Typography variant="body2" sx={{ color: 'text.secondary', mb: 2 }}>
- Add your first YouTube channel or Instagram account to start tracking analytics
- </Typography>
- </Card>
- ) : (
- <>
- {/* Charts Row */}
- <Grid container spacing={2.5} sx={{ mb: 3 }}>
- <Grid size={{ xs: 12, md: 8 }}>
- <Card>
- <CardContent>
- <Typography variant="h6" sx={{ mb: 2, fontWeight: 600 }}>
- <BarChart sx={{ verticalAlign: 'middle', mr: 1, color: 'primary.main' }} />
- Audience Comparison
- </Typography>
- <ResponsiveContainer width="100%" height={320}>
- <ReBarChart data={chartData}>
- <CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.06)" />
- <XAxis dataKey="name" tick={{ fill: '#aaa', fontSize: 12 }} />
- <YAxis tick={{ fill: '#aaa', fontSize: 12 }} tickFormatter={fmtNum} />
- <ReTooltip contentStyle={{ backgroundColor: '#1A1A1A', border: '1px solid rgba(255,255,255,0.1)', borderRadius: 8 }}
- formatter={(v) => fmtNumFull(v)} />
- <Bar dataKey="audience" fill="#667eea" radius={[6, 6, 0, 0]} name="Audience" />
- </ReBarChart>
- </ResponsiveContainer>
- </CardContent>
- </Card>
- </Grid>
- <Grid size={{ xs: 12, md: 4 }}>
- <Card sx={{ height: '100%' }}>
- <CardContent>
- <Typography variant="h6" sx={{ mb: 2, fontWeight: 600 }}>Audience Share</Typography>
- <ResponsiveContainer width="100%" height={280}>
- <PieChart>
- <Pie data={pieData} dataKey="value" nameKey="name" cx="50%" cy="50%"
- outerRadius={90} innerRadius={50} paddingAngle={3}>
- {pieData.map((entry, i) => (
- <Cell key={i} fill={entry.color} />
- ))}
- </Pie>
- <ReTooltip contentStyle={{ backgroundColor: '#1A1A1A', border: '1px solid rgba(255,255,255,0.1)', borderRadius: 8 }}
- formatter={(v) => fmtNumFull(v)} />
- <Legend />
- </PieChart>
- </ResponsiveContainer>
- </CardContent>
- </Card>
- </Grid>
- </Grid>
-
- {/* Account Rankings */}
- <Grid container spacing={2.5} sx={{ mb: 3 }}>
- {/* Top by Audience */}
- <Grid size={{ xs: 12, md: 6 }}>
- <Card>
- <CardContent>
- <Typography variant="h6" sx={{ mb: 2, fontWeight: 600, display: 'flex', alignItems: 'center', gap: 1 }}>
- <EmojiEvents sx={{ color: '#FFD700' }} /> Top by Audience
- </Typography>
- {sorted.byAudience.map((a, i) => {
- const isIG = a.platform === 'instagram';
- return (
- <Box key={a.id} sx={{ display: 'flex', alignItems: 'center', gap: 1.5, py: 1, cursor: 'pointer', '&:hover': { bgcolor: 'rgba(255,255,255,0.03)' }, borderRadius: 1, px: 1 }}
- onClick={() => onViewChannel(a)}>
- <Typography sx={{ width: 24, fontWeight: 700, color: i === 0 ? '#FFD700' : i === 1 ? '#C0C0C0' : i === 2 ? '#CD7F32' : 'text.secondary', fontSize: 16 }}>
- {i + 1}
- </Typography>
- <Avatar src={a.thumbnail || a.profilePictureUrl || a.thumbnails?.default} sx={{ width: 32, height: 32 }} />
- <Box sx={{ flex: 1, minWidth: 0 }}>
- <Typography variant="body2" noWrap sx={{ fontWeight: 500 }}>{a.title}</Typography>
- </Box>
- {isIG ? <Instagram sx={{ fontSize: 16, color: '#E1306C' }} /> : <YouTube sx={{ fontSize: 16, color: '#FF0000' }} />}
- <Chip label={fmtNum(isIG ? a.followersCount : a.subscriberCount)} size="small"
- sx={{ bgcolor: isIG ? 'rgba(225,48,108,0.15)' : 'rgba(76,175,80,0.15)', color: isIG ? '#E1306C' : '#4CAF50', fontWeight: 600 }} />
- </Box>
- );
- })}
- </CardContent>
- </Card>
- </Grid>
-
- {/* Top by Content */}
- <Grid size={{ xs: 12, md: 6 }}>
- <Card>
- <CardContent>
- <Typography variant="h6" sx={{ mb: 2, fontWeight: 600, display: 'flex', alignItems: 'center', gap: 1 }}>
- <TrendingUp sx={{ color: '#FF9800' }} /> Top by Content
- </Typography>
- {sorted.byContent.map((a, i) => {
- const isIG = a.platform === 'instagram';
- return (
- <Box key={a.id} sx={{ display: 'flex', alignItems: 'center', gap: 1.5, py: 1, cursor: 'pointer', '&:hover': { bgcolor: 'rgba(255,255,255,0.03)' }, borderRadius: 1, px: 1 }}
- onClick={() => onViewChannel(a)}>
- <Typography sx={{ width: 24, fontWeight: 700, color: i === 0 ? '#FFD700' : 'text.secondary', fontSize: 16 }}>
- {i + 1}
- </Typography>
- <Avatar src={a.thumbnail || a.profilePictureUrl || a.thumbnails?.default} sx={{ width: 32, height: 32 }} />
- <Box sx={{ flex: 1, minWidth: 0 }}>
- <Typography variant="body2" noWrap sx={{ fontWeight: 500 }}>{a.title}</Typography>
- </Box>
- {isIG ? <Instagram sx={{ fontSize: 16, color: '#E1306C' }} /> : <YouTube sx={{ fontSize: 16, color: '#FF0000' }} />}
- <Chip label={isIG ? `${fmtNum(a.mediaCount)} posts` : `${fmtNum(a.viewCount)} views`} size="small"
- sx={{ bgcolor: isIG ? 'rgba(138,58,185,0.15)' : 'rgba(255,0,0,0.15)', color: isIG ? '#8134AF' : '#FF4444', fontWeight: 600 }} />
- </Box>
- );
- })}
- </CardContent>
- </Card>
- </Grid>
- </Grid>
-
- {/* All Accounts Table */}
- <Card>
- <CardContent>
- <Typography variant="h6" sx={{ mb: 2, fontWeight: 600 }}>All Accounts</Typography>
- <TableContainer>
- <Table size="small">
- <TableHead>
- <TableRow>
- <TableCell>#</TableCell>
- <TableCell>Account</TableCell>
- <TableCell align="center">Platform</TableCell>
- <TableCell align="right">Audience</TableCell>
- <TableCell align="right">Content</TableCell>
- <TableCell align="right">Last Updated</TableCell>
- <TableCell align="center">Actions</TableCell>
- </TableRow>
- </TableHead>
- <TableBody>
- {sorted.byAudience.map((a, i) => {
- const isIG = a.platform === 'instagram';
- return (
- <TableRow key={a.id} hover sx={{ cursor: 'pointer' }} onClick={() => onViewChannel(a)}>
- <TableCell>{i + 1}</TableCell>
- <TableCell>
- <Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5 }}>
- <Avatar src={a.thumbnail || a.profilePictureUrl || a.thumbnails?.default} sx={{ width: 32, height: 32 }} />
- <Box>
- <Typography variant="body2" sx={{ fontWeight: 600 }}>{a.title}</Typography>
- <Typography variant="caption" sx={{ color: 'text.secondary' }}>
- {isIG ? `@${a.username || a.igUsername}` : (a.customUrl || a.channelId)}
- </Typography>
- </Box>
- </Box>
- </TableCell>
- <TableCell align="center">
- {isIG ? <Instagram sx={{ color: '#E1306C', fontSize: 20 }} /> : <YouTube sx={{ color: '#FF0000', fontSize: 20 }} />}
- </TableCell>
- <TableCell align="right" sx={{ fontWeight: 600 }}>
- {fmtNum(isIG ? a.followersCount : a.subscriberCount)}
- <Typography variant="caption" sx={{ display: 'block', color: 'text.secondary' }}>
- {isIG ? 'followers' : 'subscribers'}
- </Typography>
- </TableCell>
- <TableCell align="right">
- {isIG ? `${fmtNum(a.mediaCount)} posts` : `${fmtNum(a.viewCount)} views / ${fmtNum(a.videoCount)} videos`}
- </TableCell>
- <TableCell align="right">
- <Typography variant="caption" sx={{ color: 'text.secondary' }}>{timeAgo(a.lastUpdated)}</Typography>
- </TableCell>
- <TableCell align="center">
- <Tooltip title="View Analytics">
- <IconButton size="small" onClick={(e) => { e.stopPropagation(); onViewChannel(a); }}>
- <OpenInNew fontSize="small" />
- </IconButton>
- </Tooltip>
- </TableCell>
- </TableRow>
- );
- })}
- </TableBody>
- </Table>
- </TableContainer>
- </CardContent>
- </Card>
- </>
- )}
- </Box>
- );
-}
diff --git a/frontend/src/components/Sidebar.jsx b/frontend/src/components/Sidebar.jsx
deleted file mode 100644
index 6c51d15..0000000
--- a/frontend/src/components/Sidebar.jsx
+++ /dev/null
@@ -1,115 +0,0 @@
-import React from 'react';
-import {
- Drawer, Box, Typography, List, ListItemButton, ListItemIcon, ListItemText,
- Avatar, Divider, Chip,
-} from '@mui/material';
-import {
- Dashboard as DashboardIcon, YouTube as YouTubeIcon, ManageAccounts,
- Settings, TrendingUp, PlaylistPlay, ContentCut, Instagram, CloudUpload,
-} from '@mui/icons-material';
-import Logo from './Logo';
-
-const DRAWER_WIDTH = 260;
-
-const NAV = [
- { id: 'overview', label: 'Overview', icon: <DashboardIcon /> },
- { id: 'videos', label: 'All Videos', icon: <PlaylistPlay /> },
- { id: 'shorts', label: 'All Shorts', icon: <ContentCut /> },
- { id: 'reels', label: 'IG Content', icon: <Instagram /> },
- { id: 'upload', label: 'Upload', icon: <CloudUpload /> },
- { id: 'accounts', label: 'Accounts', icon: <ManageAccounts /> },
- { id: 'settings', label: 'Settings', icon: <Settings /> },
-];
-
-export default function Sidebar({ tab, setTab, accounts, onViewChannel }) {
- return (
- <Drawer variant="permanent" sx={{
- width: DRAWER_WIDTH, flexShrink: 0,
- '& .MuiDrawer-paper': { width: DRAWER_WIDTH, boxSizing: 'border-box' },
- }}>
- {/* Logo */}
- <Box sx={{ p: 2.5, display: 'flex', alignItems: 'center', gap: 1.5 }}>
- <Logo size={40} />
- <Box>
- <Typography variant="h6" sx={{ fontWeight: 700, fontSize: 16, lineHeight: 1.2, letterSpacing: '-0.3px' }}>
- Social Analytics
- </Typography>
- <Typography variant="caption" sx={{ color: 'text.secondary', fontSize: 10, letterSpacing: '0.5px' }}>
- Dashboard Pro
- </Typography>
- </Box>
- </Box>
-
- <Divider sx={{ borderColor: 'rgba(255,255,255,0.06)' }} />
-
- {/* Nav */}
- <List sx={{ px: 1.5, py: 2 }}>
- {NAV.map(item => (
- <ListItemButton key={item.id} selected={tab === item.id}
- onClick={() => setTab(item.id)}
- sx={{
- borderRadius: 2, mb: 0.5, py: 1.2,
- '&.Mui-selected': { bgcolor: 'rgba(255,0,0,0.08)', '&:hover': { bgcolor: 'rgba(255,0,0,0.12)' } },
- '&:hover': { bgcolor: 'rgba(255,255,255,0.04)' },
- }}>
- <ListItemIcon sx={{ minWidth: 40, color: tab === item.id ? 'primary.main' : 'text.secondary' }}>
- {item.icon}
- </ListItemIcon>
- <ListItemText primary={item.label}
- primaryTypographyProps={{ fontSize: 14, fontWeight: tab === item.id ? 600 : 400 }} />
- </ListItemButton>
- ))}
- </List>
-
- <Divider sx={{ borderColor: 'rgba(255,255,255,0.06)', mx: 2 }} />
-
- {/* Channels Quick Access */}
- <Box sx={{ px: 2, py: 1.5 }}>
- <Typography variant="overline" sx={{ color: 'text.secondary', fontSize: 10, letterSpacing: 1.5, fontWeight: 700 }}>
- Accounts
- </Typography>
- </Box>
- <List sx={{ px: 1.5, flex: 1, overflow: 'auto' }}>
- {accounts.length === 0 ? (
- <Typography variant="caption" sx={{ display: 'block', textAlign: 'center', color: 'text.secondary', py: 2, px: 1 }}>
- No accounts added yet
- </Typography>
- ) : (
- accounts.map(acc => (
- <ListItemButton key={acc.id}
- selected={tab === 'channel' || tab === 'ig-analytics'}
- onClick={() => onViewChannel(acc)}
- sx={{
- borderRadius: 2, mb: 0.5, py: 0.8,
- '&:hover': { bgcolor: 'rgba(255,255,255,0.04)' },
- }}>
- <ListItemIcon sx={{ minWidth: 36 }}>
- <Avatar src={acc.thumbnail || acc.thumbnails?.default || acc.thumbnailUrl || acc.profilePictureUrl || ''}
- sx={{ width: 28, height: 28 }}>
- {acc.platform === 'instagram' ? <Instagram sx={{ fontSize: 16 }} /> : <YouTubeIcon sx={{ fontSize: 16 }} />}
- </Avatar>
- </ListItemIcon>
- <ListItemText primary={acc.title}
- primaryTypographyProps={{ fontSize: 13, fontWeight: 500, noWrap: true }} />
- {acc.platform === 'instagram' && (
- <Instagram sx={{ fontSize: 14, color: '#DD2A7B', ml: 0.5 }} />
- )}
- </ListItemButton>
- ))
- )}
- </List>
-
- {/* Footer */}
- <Box sx={{ p: 2, borderTop: '1px solid rgba(255,255,255,0.06)' }}>
- <Box sx={{ display: 'flex', gap: 0.5 }}>
- <Chip icon={<YouTubeIcon />} label={`${accounts.filter(a => a.platform !== 'instagram').length} YT`}
- size="small" variant="outlined"
- sx={{ flex: 1, justifyContent: 'flex-start', borderColor: 'rgba(255,255,255,0.1)', fontSize: 11 }} />
- <Chip icon={<Instagram />} label={`${accounts.filter(a => a.platform === 'instagram').length} IG`}
- size="small" variant="outlined"
- sx={{ flex: 1, justifyContent: 'flex-start', borderColor: 'rgba(255,255,255,0.1)', fontSize: 11 }} />
- </Box>
- </Box>
- </Drawer>
- );
-}
diff --git a/frontend/src/components/StatCard.jsx b/frontend/src/components/StatCard.jsx
deleted file mode 100644
index cabb3a4..0000000
--- a/frontend/src/components/StatCard.jsx
+++ /dev/null
@@ -1,53 +0,0 @@
-import React from 'react';
-import { Card, CardContent, Box, Typography, Skeleton } from '@mui/material';
-
-const GRADIENTS = {
- red: 'linear-gradient(135deg, #FF0000 0%, #FF4444 100%)',
- green: 'linear-gradient(135deg, #2E7D32 0%, #4CAF50 100%)',
- blue: 'linear-gradient(135deg, #1565C0 0%, #42A5F5 100%)',
- orange: 'linear-gradient(135deg, #E65100 0%, #FF9800 100%)',
- purple: 'linear-gradient(135deg, #6A1B9A 0%, #AB47BC 100%)',
- teal: 'linear-gradient(135deg, #00695C 0%, #26A69A 100%)',
- pink: 'linear-gradient(135deg, #AD1457 0%, #EC407A 100%)',
- indigo: 'linear-gradient(135deg, #283593 0%, #5C6BC0 100%)',
- cyan: 'linear-gradient(135deg, #00838F 0%, #26C6DA 100%)',
- amber: 'linear-gradient(135deg, #FF6F00 0%, #FFCA28 100%)',
-};
-
-export default function StatCard({ icon, label, value, subtitle, gradient = 'blue', loading, small }) {
- return (
- <Card sx={{ height: '100%' }}>
- <CardContent sx={{ p: small ? 2 : 2.5, '&:last-child': { pb: small ? 2 : 2.5 } }}>
- <Box sx={{ display: 'flex', alignItems: 'flex-start', gap: 2 }}>
- <Box sx={{
- width: small ? 44 : 52, height: small ? 44 : 52, borderRadius: 2,
- background: GRADIENTS[gradient] || GRADIENTS.blue,
- display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
- }}>
- {React.cloneElement(icon, { sx: { color: '#fff', fontSize: small ? 22 : 26 } })}
- </Box>
- <Box sx={{ flex: 1, minWidth: 0 }}>
- <Typography variant="body2" sx={{ color: 'text.secondary', fontSize: small ? 12 : 13, fontWeight: 500, mb: 0.3 }}>
- {label}
- </Typography>
- {loading ? (
- <Skeleton width="60%" height={small ? 28 : 36} />
- ) : (
- <Typography variant={small ? 'h6' : 'h5'} sx={{
- fontWeight: 700, lineHeight: 1.2, letterSpacing: '-0.02em',
- fontSize: small ? '1.1rem' : undefined,
- }}>
- {value}
- </Typography>
- )}
- {subtitle && (
- <Typography variant="caption" sx={{ color: 'text.secondary', fontSize: 11 }}>
- {subtitle}
- </Typography>
- )}
- </Box>
- </Box>
- </CardContent>
- </Card>
- );
-}
diff --git a/frontend/src/components/ui/Logo.jsx b/frontend/src/components/ui/Logo.jsx
new file mode 100644
index 0000000..8d1b8ab
--- /dev/null
+++ b/frontend/src/components/ui/Logo.jsx
@@ -0,0 +1,18 @@
+import { Box } from '@mui/material';
+
+export default function Logo({ size = 40 }) {
+ return (
+ <Box
+ component="img"
+ src="/logo.png"
+ alt="Social Analytics"
+ sx={{
+ width: size,
+ height: size,
+ flexShrink: 0,
+ objectFit: 'contain',
+ borderRadius: 1.5,
+ }}
+ />
+ );
+}
diff --git a/frontend/src/components/ui/StatCard.jsx b/frontend/src/components/ui/StatCard.jsx
new file mode 100644
index 0000000..ee2de8f
--- /dev/null
+++ b/frontend/src/components/ui/StatCard.jsx
@@ -0,0 +1,109 @@
+import React from 'react';
+import { Card, CardContent, Box, Typography, Skeleton } from '@mui/material';
+
+const GRADIENTS = {
+ red: 'linear-gradient(135deg, #FF0000 0%, #FF4444 100%)',
+ green: 'linear-gradient(135deg, #16A34A 0%, #22C55E 100%)',
+ blue: 'linear-gradient(135deg, #1D4ED8 0%, #3B82F6 100%)',
+ orange: 'linear-gradient(135deg, #C2410C 0%, #F97316 100%)',
+ purple: 'linear-gradient(135deg, #7C3AED 0%, #A78BFA 100%)',
+ teal: 'linear-gradient(135deg, #0F766E 0%, #14B8A6 100%)',
+ pink: 'linear-gradient(135deg, #BE185D 0%, #EC4899 100%)',
+ indigo: 'linear-gradient(135deg, #3730A3 0%, #6366F1 100%)',
+ cyan: 'linear-gradient(135deg, #0E7490 0%, #22D3EE 100%)',
+ amber: 'linear-gradient(135deg, #B45309 0%, #F59E0B 100%)',
+};
+
+const GLOW = {
+ red: 'rgba(255,0,0,0.15)',
+ green: 'rgba(34,197,94,0.15)',
+ blue: 'rgba(59,130,246,0.15)',
+ orange: 'rgba(249,115,22,0.15)',
+ purple: 'rgba(167,139,250,0.15)',
+ teal: 'rgba(20,184,166,0.15)',
+ pink: 'rgba(236,72,153,0.15)',
+ indigo: 'rgba(99,102,241,0.15)',
+ cyan: 'rgba(34,211,238,0.15)',
+ amber: 'rgba(245,158,11,0.15)',
+};
+
+export default function StatCard({ icon, label, value, subtitle, gradient = 'blue', loading, small }) {
+ const grad = GRADIENTS[gradient] || GRADIENTS.blue;
+ const glow = GLOW[gradient] || GLOW.blue;
+
+ return (
+ <Card sx={{
+ height: '100%',
+ position: 'relative',
+ overflow: 'hidden',
+ '&::before': {
+ content: '""',
+ position: 'absolute',
+ top: 0, left: 0, right: 0,
+ height: '2px',
+ background: grad,
+ opacity: 0.8,
+ },
+ }}>
+ <CardContent sx={{ p: small ? 1.75 : 2.25, '&:last-child': { pb: small ? 1.75 : 2.25 } }}>
+ <Box sx={{ display: 'flex', alignItems: 'flex-start', gap: 1.75 }}>
+ <Box sx={{
+ width: small ? 40 : 48,
+ height: small ? 40 : 48,
+ borderRadius: '12px',
+ background: grad,
+ boxShadow: `0 4px 14px ${glow}`,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ flexShrink: 0,
+ }}>
+ {React.cloneElement(icon, { sx: { color: '#fff', fontSize: small ? 20 : 24 } })}
+ </Box>
+
+ <Box sx={{ flex: 1, minWidth: 0 }}>
+ <Typography sx={{
+ color: 'text.secondary',
+ fontSize: small ? 11 : 12,
+ fontWeight: 600,
+ letterSpacing: '0.04em',
+ textTransform: 'uppercase',
+ mb: 0.5,
+ lineHeight: 1,
+ }}>
+ {label}
+ </Typography>
+
+ {loading ? (
+ <Skeleton width="65%" height={small ? 26 : 34} sx={{ borderRadius: 1 }} />
+ ) : (
+ <Typography sx={{
+ fontWeight: 800,
+ fontSize: small ? '1.15rem' : '1.5rem',
+ lineHeight: 1.15,
+ letterSpacing: '-0.02em',
+ color: 'text.primary',
+ }}>
+ {value}
+ </Typography>
+ )}
+
+ {subtitle && (
+ <Typography sx={{
+ color: 'text.secondary',
+ fontSize: 11,
+ mt: 0.4,
+ lineHeight: 1.3,
+ overflow: 'hidden',
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ }}>
+ {subtitle}
+ </Typography>
+ )}
+ </Box>
+ </Box>
+ </CardContent>
+ </Card>
+ );
+}
diff --git a/frontend/src/components/AccountManager.jsx b/frontend/src/features/accounts/AccountManager.jsx
similarity index 99%
rename from frontend/src/components/AccountManager.jsx
rename to frontend/src/features/accounts/AccountManager.jsx
index 7883675..93a201f 100644
--- a/frontend/src/components/AccountManager.jsx
+++ b/frontend/src/features/accounts/AccountManager.jsx
@@ -8,8 +8,8 @@ import {
Add, Delete, Refresh, Search, YouTube, People, Visibility, VideoLibrary,
Link as LinkIcon, CheckCircle, Instagram, Favorite, Photo, Key,
} from '@mui/icons-material';
-import { api } from '../services/api';
-import { fmtNum, timeAgo } from '../utils/formatters';
+import { api } from '../../services/api';
+import { fmtNum, timeAgo } from '../../utils/formatters';
export default function AccountManager({ accounts, showToast, onRefresh }) {
const [dialogOpen, setDialogOpen] = useState(false);
diff --git a/frontend/src/components/ChannelAnalytics.jsx b/frontend/src/features/analytics/channel/ChannelAnalytics.jsx
similarity index 99%
rename from frontend/src/components/ChannelAnalytics.jsx
rename to frontend/src/features/analytics/channel/ChannelAnalytics.jsx
index a18dea0..a4b492b 100644
--- a/frontend/src/components/ChannelAnalytics.jsx
+++ b/frontend/src/features/analytics/channel/ChannelAnalytics.jsx
@@ -17,9 +17,9 @@ import {
ResponsiveContainer, LineChart, Line, PieChart, Pie, Cell, Legend,
AreaChart, Area, RadarChart, PolarGrid, PolarAngleAxis, PolarRadiusAxis, Radar,
} from 'recharts';
-import StatCard from './StatCard';
-import { api } from '../services/api';
-import { fmtNum, fmtNumFull, fmtDate, fmtPercent, fmtDuration, timeAgo, CATEGORY_MAP } from '../utils/formatters';
+import StatCard from '../../../components/ui/StatCard';
+import { api } from '../../../services/api';
+import { fmtNum, fmtNumFull, fmtDate, fmtPercent, fmtDuration, timeAgo, CATEGORY_MAP } from '../../../utils/formatters';
const COLORS = ['#FF0000', '#3EA6FF', '#4CAF50', '#FF9800', '#AB47BC', '#26A69A', '#EC407A', '#5C6BC0', '#FFCA28', '#00BCD4'];
diff --git a/frontend/src/components/InstagramAnalytics.jsx b/frontend/src/features/analytics/instagram/InstagramAnalytics.jsx
similarity index 95%
rename from frontend/src/components/InstagramAnalytics.jsx
rename to frontend/src/features/analytics/instagram/InstagramAnalytics.jsx
index 2a26ab9..5641f46 100644
--- a/frontend/src/components/InstagramAnalytics.jsx
+++ b/frontend/src/features/analytics/instagram/InstagramAnalytics.jsx
@@ -16,9 +16,9 @@ import {
ResponsiveContainer, PieChart, Pie, Cell, Legend, LineChart, Line,
AreaChart, Area,
} from 'recharts';
-import StatCard from './StatCard';
-import { fmtNum, fmtNumFull, fmtDate, timeAgo } from '../utils/formatters';
-import { api } from '../services/api';
+import StatCard from '../../../components/ui/StatCard';
+import { fmtNum, fmtNumFull, fmtDate, timeAgo } from '../../../utils/formatters';
+import { api } from '../../../services/api';
const IG_GRADIENT = 'linear-gradient(135deg, #F58529, #DD2A7B, #8134AF, #515BD4)';
const IG_COLORS = ['#F58529', '#DD2A7B', '#8134AF', '#515BD4', '#FEDA77', '#405DE6'];
@@ -234,26 +234,29 @@ export default function InstagramAnalytics({ account, showToast, onBack }) {
</Grid>
</Grid>
- {/* Best posting day & hour */}
- {(a.bestPostingDay || a.bestPostingHour) && (
- <Card sx={{ mb: 2.5, p: 2 }}>
- <Box sx={{ display: 'flex', gap: 3, flexWrap: 'wrap' }}>
+ {/* Best posting day & hour + Avg Engagement */}
+ <Card sx={{ mb: 2.5 }}>
+ <CardContent sx={{ py: 1.5, px: 2.5, '&:last-child': { pb: 1.5 } }}>
+ <Box sx={{ display: 'flex', gap: 1.5, flexWrap: 'wrap', alignItems: 'center' }}>
{a.bestPostingDay && (
- <Chip icon={<Star sx={{ color: '#FFD700 !important' }} />}
+ <Chip icon={<Star sx={{ color: '#F59E0B !important', fontSize: '16px !important' }} />}
label={`Best Day: ${a.bestPostingDay}`}
- sx={{ fontSize: 13, fontWeight: 600, height: 32 }} />
+ sx={{ fontSize: 12, fontWeight: 700, height: 30, bgcolor: 'rgba(245,158,11,0.1)', color: '#F59E0B', border: '1px solid rgba(245,158,11,0.2)' }} />
)}
{a.bestPostingHour && (
- <Chip icon={<Schedule sx={{ color: '#4CAF50 !important' }} />}
+ <Chip icon={<Schedule sx={{ color: '#22C55E !important', fontSize: '16px !important' }} />}
label={`Best Hour: ${a.bestPostingHour}`}
- sx={{ fontSize: 13, fontWeight: 600, height: 32 }} />
+ sx={{ fontSize: 12, fontWeight: 700, height: 30, bgcolor: 'rgba(34,197,94,0.1)', color: '#22C55E', border: '1px solid rgba(34,197,94,0.2)' }} />
)}
- <Chip icon={<TrendingUp sx={{ color: '#2196F3 !important' }} />}
+ <Chip icon={<TrendingUp sx={{ color: '#3B82F6 !important', fontSize: '16px !important' }} />}
label={`Avg Engagement: ${fmtNum(a.avgEngagement || 0)}/post`}
- sx={{ fontSize: 13, fontWeight: 600, height: 32 }} />
+ sx={{ fontSize: 12, fontWeight: 700, height: 30, bgcolor: 'rgba(59,130,246,0.1)', color: '#3B82F6', border: '1px solid rgba(59,130,246,0.2)' }} />
+ <Chip icon={<WorkspacePremium sx={{ color: '#A78BFA !important', fontSize: '16px !important' }} />}
+ label={`Consistency: ${a.consistencyScore || 0}/100`}
+ sx={{ fontSize: 12, fontWeight: 700, height: 30, bgcolor: 'rgba(167,139,250,0.1)', color: '#A78BFA', border: '1px solid rgba(167,139,250,0.2)' }} />
</Box>
- </Card>
- )}
+ </CardContent>
+ </Card>
{/* CHARTS ROW 1: Engagement Timeline + Content Mix */}
<Grid container spacing={2.5} sx={{ mb: 3 }}>
diff --git a/frontend/src/features/analytics/overview/Overview.jsx b/frontend/src/features/analytics/overview/Overview.jsx
new file mode 100644
index 0000000..1d2d8d3
--- /dev/null
+++ b/frontend/src/features/analytics/overview/Overview.jsx
@@ -0,0 +1,365 @@
+import React from 'react';
+import {
+ Box, Typography, Grid, Card, CardContent, Button, Avatar, Chip,
+ LinearProgress, Table, TableBody, TableCell, TableContainer,
+ TableHead, TableRow, IconButton, Tooltip,
+} from '@mui/material';
+import {
+ Visibility, People, VideoLibrary, YouTube, Refresh,
+ OpenInNew, BarChart, Instagram,
+} from '@mui/icons-material';
+import {
+ AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip as ReTooltip,
+ ResponsiveContainer, PieChart, Pie, Cell, Legend,
+} from 'recharts';
+import StatCard from '../../../components/ui/StatCard';
+import { fmtNum, fmtNumFull, timeAgo } from '../../../utils/formatters';
+
+const COLORS = ['#FF0000', '#3B82F6', '#22C55E', '#F59E0B', '#A78BFA', '#14B8A6', '#EC4899', '#6366F1'];
+
+const sectionLabel = (text) => (
+ <Typography sx={{
+ fontSize: 11, fontWeight: 700, letterSpacing: '0.08em',
+ textTransform: 'uppercase', color: 'text.secondary', mb: 2,
+ }}>
+ {text}
+ </Typography>
+);
+
+const chartTooltipStyle = {
+ backgroundColor: '#0E1420',
+ border: '1px solid rgba(255,255,255,0.1)',
+ borderRadius: 10,
+ fontSize: 13,
+ fontWeight: 500,
+};
+
+export default function Overview({ accounts, onViewChannel, onRefreshAll, loading }) {
+ const ytAccounts = accounts.filter(a => a.platform !== 'instagram');
+ const igAccounts = accounts.filter(a => a.platform === 'instagram');
+
+ const totals = accounts.reduce((acc, a) => {
+ if (a.platform === 'instagram') {
+ return { ...acc, followers: acc.followers + (a.followersCount || 0), posts: acc.posts + (a.mediaCount || 0) };
+ }
+ return {
+ ...acc,
+ subscribers: acc.subscribers + (a.subscriberCount || 0),
+ views: acc.views + (a.viewCount || 0),
+ videos: acc.videos + (a.videoCount || 0),
+ };
+ }, { subscribers: 0, views: 0, videos: 0, followers: 0, posts: 0 });
+
+ const totalAudience = totals.subscribers + totals.followers;
+
+ const sorted = {
+ byAudience: [...accounts].sort((a, b) => (b.subscriberCount || b.followersCount || 0) - (a.subscriberCount || a.followersCount || 0)),
+ byContent: [...accounts].sort((a, b) => (b.viewCount || b.mediaCount || 0) - (a.viewCount || a.mediaCount || 0)),
+ };
+
+ const chartData = accounts.map(a => ({
+ name: (a.title || '').length > 14 ? a.title.substring(0, 14) + '…' : a.title,
+ audience: a.subscriberCount || a.followersCount || 0,
+ platform: a.platform || 'youtube',
+ }));
+
+ const pieData = accounts.map((a, i) => ({
+ name: (a.title || '').length > 14 ? a.title.substring(0, 14) + '…' : a.title,
+ value: a.subscriberCount || a.followersCount || 0,
+ color: COLORS[i % COLORS.length],
+ }));
+
+ return (
+ <Box>
+ {/* ── Header ─────────────────────────────────────────────── */}
+ <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', mb: 3.5 }}>
+ <Box>
+ <Typography variant="h4" sx={{ fontWeight: 800, mb: 0.5, letterSpacing: '-0.03em' }}>
+ Dashboard Overview
+ </Typography>
+ <Typography variant="body2" sx={{ color: 'text.secondary' }}>
+ {accounts.length === 0
+ ? 'Add your first account to start tracking'
+ : `Tracking ${accounts.length} account${accounts.length !== 1 ? 's' : ''} · ${ytAccounts.length} YouTube · ${igAccounts.length} Instagram`}
+ </Typography>
+ </Box>
+ <Button
+ variant="contained"
+ startIcon={<Refresh sx={{ fontSize: 18 }} />}
+ onClick={onRefreshAll}
+ disabled={loading || accounts.length === 0}
+ sx={{
+ background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
+ px: 2.5, py: 1.1,
+ '&:hover': { background: 'linear-gradient(135deg, #7C8FF4 0%, #8A5BB8 100%)' },
+ }}
+ >
+ {loading ? 'Refreshing…' : 'Refresh All'}
+ </Button>
+ </Box>
+
+ {loading && (
+ <LinearProgress sx={{ mb: 3, borderRadius: 1, '& .MuiLinearProgress-bar': { background: 'linear-gradient(90deg, #667eea, #764ba2)' } }} />
+ )}
+
+ {/* ── KPI Cards ──────────────────────────────────────────── */}
+ <Grid container spacing={2.5} sx={{ mb: 3 }}>
+ <Grid size={{ xs: 12, sm: 6, md: 3 }}>
+ <StatCard icon={<People />} label="Total Audience" value={fmtNum(totalAudience)}
+ subtitle={`${fmtNum(totals.subscribers)} subs · ${fmtNum(totals.followers)} followers`} gradient="purple" />
+ </Grid>
+ <Grid size={{ xs: 12, sm: 6, md: 3 }}>
+ <StatCard icon={<Visibility />} label="Total YT Views" value={fmtNum(totals.views)}
+ subtitle={fmtNumFull(totals.views)} gradient="red" />
+ </Grid>
+ <Grid size={{ xs: 12, sm: 6, md: 3 }}>
+ <StatCard icon={<VideoLibrary />} label="Total Content" value={fmtNum(totals.videos + totals.posts)}
+ subtitle={`${fmtNum(totals.videos)} videos · ${fmtNum(totals.posts)} posts`} gradient="blue" />
+ </Grid>
+ <Grid size={{ xs: 12, sm: 6, md: 3 }}>
+ <StatCard icon={<BarChart />} label="Accounts" value={accounts.length}
+ subtitle={`${ytAccounts.length} YouTube · ${igAccounts.length} Instagram`} gradient="orange" />
+ </Grid>
+ </Grid>
+
+ {accounts.length === 0 ? (
+ <Card sx={{ p: 7, textAlign: 'center' }}>
+ <Box sx={{
+ width: 80, height: 80, borderRadius: '50%',
+ background: 'linear-gradient(135deg, rgba(102,126,234,0.15), rgba(118,75,162,0.15))',
+ display: 'flex', alignItems: 'center', justifyContent: 'center', mx: 'auto', mb: 3,
+ }}>
+ <People sx={{ fontSize: 40, color: '#667eea' }} />
+ </Box>
+ <Typography variant="h5" sx={{ mb: 1, fontWeight: 700 }}>Welcome to Social Analytics</Typography>
+ <Typography variant="body2" sx={{ color: 'text.secondary', maxWidth: 400, mx: 'auto' }}>
+ Add your first YouTube channel or Instagram account to start tracking analytics
+ </Typography>
+ </Card>
+ ) : (
+ <>
+ {/* ── Charts Row ─────────────────────────────────────── */}
+ <Grid container spacing={2.5} sx={{ mb: 2.5 }}>
+ {/* Audience Area Chart */}
+ <Grid size={{ xs: 12, md: 8 }}>
+ <Card sx={{ height: '100%' }}>
+ <CardContent sx={{ p: 2.5 }}>
+ <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2.5 }}>
+ <Box>
+ {sectionLabel('Audience Comparison')}
+ </Box>
+ </Box>
+ <ResponsiveContainer width="100%" height={280}>
+ <AreaChart data={chartData} margin={{ top: 4, right: 4, left: 0, bottom: 0 }}>
+ <defs>
+ <linearGradient id="audGrad" x1="0" y1="0" x2="0" y2="1">
+ <stop offset="5%" stopColor="#667eea" stopOpacity={0.35} />
+ <stop offset="95%" stopColor="#667eea" stopOpacity={0.02} />
+ </linearGradient>
+ </defs>
+ <CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.05)" vertical={false} />
+ <XAxis dataKey="name" tick={{ fill: '#64748B', fontSize: 12, fontWeight: 500 }} axisLine={false} tickLine={false} />
+ <YAxis tick={{ fill: '#64748B', fontSize: 12 }} tickFormatter={fmtNum} axisLine={false} tickLine={false} width={52} />
+ <ReTooltip
+ contentStyle={chartTooltipStyle}
+ formatter={(v) => [fmtNumFull(v), 'Audience']}
+ cursor={{ stroke: 'rgba(255,255,255,0.1)', strokeWidth: 1 }}
+ />
+ <Area type="monotone" dataKey="audience" stroke="#667eea" strokeWidth={2.5}
+ fill="url(#audGrad)" dot={{ fill: '#667eea', r: 4, strokeWidth: 0 }}
+ activeDot={{ r: 6, strokeWidth: 0 }} />
+ </AreaChart>
+ </ResponsiveContainer>
+ </CardContent>
+ </Card>
+ </Grid>
+
+ {/* Pie Chart */}
+ <Grid size={{ xs: 12, md: 4 }}>
+ <Card sx={{ height: '100%' }}>
+ <CardContent sx={{ p: 2.5 }}>
+ {sectionLabel('Audience Share')}
+ <ResponsiveContainer width="100%" height={280}>
+ <PieChart>
+ <Pie data={pieData} dataKey="value" nameKey="name"
+ cx="50%" cy="45%" outerRadius={95} innerRadius={52}
+ paddingAngle={3} strokeWidth={0}>
+ {pieData.map((entry, i) => (
+ <Cell key={i} fill={entry.color} />
+ ))}
+ </Pie>
+ <ReTooltip contentStyle={chartTooltipStyle} formatter={(v) => fmtNumFull(v)} />
+ <Legend iconType="circle" iconSize={8}
+ wrapperStyle={{ fontSize: 12, color: '#94A3B8', paddingTop: 8 }} />
+ </PieChart>
+ </ResponsiveContainer>
+ </CardContent>
+ </Card>
+ </Grid>
+ </Grid>
+
+ {/* ── Rankings ───────────────────────────────────────── */}
+ <Grid container spacing={2.5} sx={{ mb: 2.5 }}>
+ <Grid size={{ xs: 12, md: 6 }}>
+ <Card>
+ <CardContent sx={{ p: 2.5 }}>
+ {sectionLabel('Top by Audience')}
+ {sorted.byAudience.map((a, i) => {
+ const isIG = a.platform === 'instagram';
+ const medalColor = i === 0 ? '#F59E0B' : i === 1 ? '#94A3B8' : i === 2 ? '#CD7F32' : '#475569';
+ return (
+ <Box key={a.id} onClick={() => onViewChannel(a)} sx={{
+ display: 'flex', alignItems: 'center', gap: 1.5,
+ py: 1.1, px: 1.2, borderRadius: 2, cursor: 'pointer',
+ transition: 'background 0.15s',
+ '&:hover': { bgcolor: 'rgba(255,255,255,0.035)' },
+ }}>
+ <Typography sx={{ width: 22, fontWeight: 800, color: medalColor, fontSize: 15, lineHeight: 1 }}>
+ {i + 1}
+ </Typography>
+ <Avatar src={a.thumbnail || a.profilePictureUrl || a.thumbnails?.default}
+ sx={{ width: 34, height: 34, border: 'none' }} />
+ <Box sx={{ flex: 1, minWidth: 0 }}>
+ <Typography variant="body2" noWrap sx={{ fontWeight: 600, fontSize: 13 }}>{a.title}</Typography>
+ </Box>
+ {isIG ? <Instagram sx={{ fontSize: 15, color: '#E1306C' }} /> : <YouTube sx={{ fontSize: 15, color: '#FF0000' }} />}
+ <Chip
+ label={fmtNum(isIG ? a.followersCount : a.subscriberCount)}
+ size="small"
+ sx={{
+ bgcolor: isIG ? 'rgba(225,48,108,0.1)' : 'rgba(34,197,94,0.1)',
+ color: isIG ? '#EC4899' : '#22C55E',
+ fontWeight: 700, fontSize: 11, height: 22,
+ border: `1px solid ${isIG ? 'rgba(225,48,108,0.2)' : 'rgba(34,197,94,0.2)'}`,
+ }}
+ />
+ </Box>
+ );
+ })}
+ </CardContent>
+ </Card>
+ </Grid>
+
+ <Grid size={{ xs: 12, md: 6 }}>
+ <Card>
+ <CardContent sx={{ p: 2.5 }}>
+ {sectionLabel('Top by Content')}
+ {sorted.byContent.map((a, i) => {
+ const isIG = a.platform === 'instagram';
+ const medalColor = i === 0 ? '#F59E0B' : i === 1 ? '#94A3B8' : i === 2 ? '#CD7F32' : '#475569';
+ return (
+ <Box key={a.id} onClick={() => onViewChannel(a)} sx={{
+ display: 'flex', alignItems: 'center', gap: 1.5,
+ py: 1.1, px: 1.2, borderRadius: 2, cursor: 'pointer',
+ transition: 'background 0.15s',
+ '&:hover': { bgcolor: 'rgba(255,255,255,0.035)' },
+ }}>
+ <Typography sx={{ width: 22, fontWeight: 800, color: medalColor, fontSize: 15, lineHeight: 1 }}>
+ {i + 1}
+ </Typography>
+ <Avatar src={a.thumbnail || a.profilePictureUrl || a.thumbnails?.default}
+ sx={{ width: 34, height: 34, border: 'none' }} />
+ <Box sx={{ flex: 1, minWidth: 0 }}>
+ <Typography variant="body2" noWrap sx={{ fontWeight: 600, fontSize: 13 }}>{a.title}</Typography>
+ </Box>
+ {isIG ? <Instagram sx={{ fontSize: 15, color: '#E1306C' }} /> : <YouTube sx={{ fontSize: 15, color: '#FF0000' }} />}
+ <Chip
+ label={isIG ? `${fmtNum(a.mediaCount)} posts` : `${fmtNum(a.viewCount)} views`}
+ size="small"
+ sx={{
+ bgcolor: isIG ? 'rgba(161,122,204,0.1)' : 'rgba(255,0,0,0.1)',
+ color: isIG ? '#A78BFA' : '#FF4444',
+ fontWeight: 700, fontSize: 11, height: 22,
+ border: `1px solid ${isIG ? 'rgba(161,122,204,0.2)' : 'rgba(255,0,0,0.2)'}`,
+ }}
+ />
+ </Box>
+ );
+ })}
+ </CardContent>
+ </Card>
+ </Grid>
+ </Grid>
+
+ {/* ── All Accounts Table ─────────────────────────────── */}
+ <Card>
+ <CardContent sx={{ p: 2.5 }}>
+ {sectionLabel('All Accounts')}
+ <TableContainer>
+ <Table size="small">
+ <TableHead>
+ <TableRow>
+ <TableCell sx={{ width: 36 }}>#</TableCell>
+ <TableCell>Account</TableCell>
+ <TableCell align="center" sx={{ width: 80 }}>Platform</TableCell>
+ <TableCell align="right">Audience</TableCell>
+ <TableCell align="right">Content</TableCell>
+ <TableCell align="right">Updated</TableCell>
+ <TableCell align="center" sx={{ width: 60 }}></TableCell>
+ </TableRow>
+ </TableHead>
+ <TableBody>
+ {sorted.byAudience.map((a, i) => {
+ const isIG = a.platform === 'instagram';
+ return (
+ <TableRow key={a.id} onClick={() => onViewChannel(a)}
+ sx={{ cursor: 'pointer' }}>
+ <TableCell>
+ <Typography sx={{ fontWeight: 700, fontSize: 13, color: i < 3 ? '#F59E0B' : 'text.secondary' }}>
+ {i + 1}
+ </Typography>
+ </TableCell>
+ <TableCell>
+ <Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5 }}>
+ <Avatar src={a.thumbnail || a.profilePictureUrl || a.thumbnails?.default}
+ sx={{ width: 34, height: 34, border: 'none' }} />
+ <Box>
+ <Typography sx={{ fontWeight: 600, fontSize: 13, lineHeight: 1.3 }}>{a.title}</Typography>
+ <Typography sx={{ color: 'text.secondary', fontSize: 11 }}>
+ {isIG ? `@${a.username || ''}` : (a.customUrl || a.channelId || '')}
+ </Typography>
+ </Box>
+ </Box>
+ </TableCell>
+ <TableCell align="center">
+ {isIG
+ ? <Instagram sx={{ color: '#E1306C', fontSize: 18 }} />
+ : <YouTube sx={{ color: '#FF0000', fontSize: 18 }} />}
+ </TableCell>
+ <TableCell align="right">
+ <Typography sx={{ fontWeight: 700, fontSize: 13 }}>
+ {fmtNum(isIG ? a.followersCount : a.subscriberCount)}
+ </Typography>
+ <Typography sx={{ color: 'text.secondary', fontSize: 10 }}>
+ {isIG ? 'followers' : 'subscribers'}
+ </Typography>
+ </TableCell>
+ <TableCell align="right" sx={{ fontSize: 13 }}>
+ {isIG
+ ? `${fmtNum(a.mediaCount)} posts`
+ : `${fmtNum(a.viewCount)} views · ${fmtNum(a.videoCount)} videos`}
+ </TableCell>
+ <TableCell align="right">
+ <Typography sx={{ color: 'text.secondary', fontSize: 11 }}>{timeAgo(a.lastUpdated)}</Typography>
+ </TableCell>
+ <TableCell align="center">
+ <Tooltip title="View Analytics">
+ <IconButton size="small" onClick={(e) => { e.stopPropagation(); onViewChannel(a); }}
+ sx={{ color: 'text.secondary', '&:hover': { color: 'text.primary' } }}>
+ <OpenInNew sx={{ fontSize: 15 }} />
+ </IconButton>
+ </Tooltip>
+ </TableCell>
+ </TableRow>
+ );
+ })}
+ </TableBody>
+ </Table>
+ </TableContainer>
+ </CardContent>
+ </Card>
+ </>
+ )}
+ </Box>
+ );
+}
diff --git a/frontend/src/components/ReelsExplorer.jsx b/frontend/src/features/analytics/reels/ReelsExplorer.jsx
similarity index 99%
rename from frontend/src/components/ReelsExplorer.jsx
rename to frontend/src/features/analytics/reels/ReelsExplorer.jsx
index fef3ce5..1b5a19e 100644
--- a/frontend/src/components/ReelsExplorer.jsx
+++ b/frontend/src/features/analytics/reels/ReelsExplorer.jsx
@@ -8,8 +8,8 @@ import {
Search, Visibility, FavoriteBorder, ChatBubbleOutline, PlayCircleOutline,
Instagram, MovieFilter, Photo, Collections, ViewCarousel,
} from '@mui/icons-material';
-import { api } from '../services/api';
-import { fmtNum, fmtDate, timeAgo } from '../utils/formatters';
+import { api } from '../../../services/api';
+import { fmtNum, fmtDate, timeAgo } from '../../../utils/formatters';
const ITEMS_PER_PAGE = 24;
diff --git a/frontend/src/components/ShortsExplorer.jsx b/frontend/src/features/analytics/shorts/ShortsExplorer.jsx
similarity index 99%
rename from frontend/src/components/ShortsExplorer.jsx
rename to frontend/src/features/analytics/shorts/ShortsExplorer.jsx
index ccbbbf2..adc7c0d 100644
--- a/frontend/src/components/ShortsExplorer.jsx
+++ b/frontend/src/features/analytics/shorts/ShortsExplorer.jsx
@@ -7,8 +7,8 @@ import {
import {
Search, Visibility, ThumbUp, Comment, PlayCircleOutline, YouTube,
} from '@mui/icons-material';
-import { api } from '../services/api';
-import { fmtNum, fmtDate, fmtDuration, fmtPercent, timeAgo } from '../utils/formatters';
+import { api } from '../../../services/api';
+import { fmtNum, fmtDate, fmtDuration, fmtPercent, timeAgo } from '../../../utils/formatters';
const ITEMS_PER_PAGE = 24;
diff --git a/frontend/src/components/VideoExplorer.jsx b/frontend/src/features/analytics/videos/VideoExplorer.jsx
similarity index 99%
rename from frontend/src/components/VideoExplorer.jsx
rename to frontend/src/features/analytics/videos/VideoExplorer.jsx
index 304c36e..350386b 100644
--- a/frontend/src/components/VideoExplorer.jsx
+++ b/frontend/src/features/analytics/videos/VideoExplorer.jsx
@@ -11,8 +11,8 @@ import {
ViewList, ViewModule, Sort, PlayCircleOutline, TrendingUp,
Schedule, Speed, YouTube,
} from '@mui/icons-material';
-import { api } from '../services/api';
-import { fmtNum, fmtNumFull, fmtDate, fmtDuration, fmtPercent, timeAgo } from '../utils/formatters';
+import { api } from '../../../services/api';
+import { fmtNum, fmtNumFull, fmtDate, fmtDuration, fmtPercent, timeAgo } from '../../../utils/formatters';
const ITEMS_PER_PAGE = 25;
diff --git a/frontend/src/components/UploadContent.jsx b/frontend/src/features/publishing/UploadContent.jsx
similarity index 99%
rename from frontend/src/components/UploadContent.jsx
rename to frontend/src/features/publishing/UploadContent.jsx
index bb5b71d..f06a971 100644
--- a/frontend/src/components/UploadContent.jsx
+++ b/frontend/src/features/publishing/UploadContent.jsx
@@ -16,7 +16,7 @@ import {
DriveFolderUpload, PlaylistAdd, SkipNext, Stop, Pause,
ContentCopy, DragIndicator, EditNote, DeleteSweep, OpenInNew,
} from '@mui/icons-material';
-import { api } from '../services/api';
+import { api } from '../../services/api';
const IG_GRADIENT = 'linear-gradient(135deg, #F58529, #DD2A7B, #8134AF, #515BD4)';
diff --git a/frontend/src/components/Settings.jsx b/frontend/src/features/settings/Settings.jsx
similarity index 99%
rename from frontend/src/components/Settings.jsx
rename to frontend/src/features/settings/Settings.jsx
index 629cf2e..009d3db 100644
--- a/frontend/src/components/Settings.jsx
+++ b/frontend/src/features/settings/Settings.jsx
@@ -7,7 +7,7 @@ import {
Key, Save, Visibility, VisibilityOff, CheckCircle, Error as ErrorIcon,
Refresh, Info, GitHub, Code, Instagram, Cloud, Sync, Schedule,
} from '@mui/icons-material';
-import { api } from '../services/api';
+import { api } from '../../services/api';
export default function Settings({ showToast, onRefresh }) {
const [apiKey, setApiKey] = useState('');
diff --git a/frontend/src/layouts/Sidebar.jsx b/frontend/src/layouts/Sidebar.jsx
new file mode 100644
index 0000000..635a60c
--- /dev/null
+++ b/frontend/src/layouts/Sidebar.jsx
@@ -0,0 +1,173 @@
+import React from 'react';
+// React is used for React.cloneElement in NAV item icon rendering
+import {
+ Drawer, Box, Typography, List, ListItemButton, ListItemIcon, ListItemText,
+ Avatar, Divider, Chip,
+} from '@mui/material';
+import {
+ Dashboard as DashboardIcon, YouTube as YouTubeIcon, ManageAccounts,
+ Settings, PlaylistPlay, ContentCut, Instagram, CloudUpload,
+} from '@mui/icons-material';
+import Logo from '../components/ui/Logo';
+
+const DRAWER_WIDTH = 256;
+
+const NAV = [
+ { id: 'overview', label: 'Overview', icon: <DashboardIcon /> },
+ { id: 'videos', label: 'All Videos', icon: <PlaylistPlay /> },
+ { id: 'shorts', label: 'All Shorts', icon: <ContentCut /> },
+ { id: 'reels', label: 'IG Content', icon: <Instagram /> },
+ { id: 'upload', label: 'Publish', icon: <CloudUpload /> },
+ { id: 'accounts', label: 'Accounts', icon: <ManageAccounts /> },
+ { id: 'settings', label: 'Settings', icon: <Settings /> },
+];
+
+export default function Sidebar({ tab, setTab, accounts, onViewChannel }) {
+ return (
+ <Drawer variant="permanent" sx={{
+ width: DRAWER_WIDTH, flexShrink: 0,
+ '& .MuiDrawer-paper': { width: DRAWER_WIDTH, boxSizing: 'border-box', overflowX: 'hidden' },
+ }}>
+ {/* Logo + Brand */}
+ <Box sx={{ px: 2.5, pt: 2.5, pb: 2, display: 'flex', alignItems: 'center', gap: 1.5 }}>
+ <Logo size={36} />
+ <Typography sx={{ fontWeight: 800, fontSize: 15, letterSpacing: '-0.4px', color: 'text.primary' }}>
+ Twiligent
+ </Typography>
+ </Box>
+
+ <Divider sx={{ mx: 2, mb: 1 }} />
+
+ {/* Navigation */}
+ <Box sx={{ px: 1.5, py: 1 }}>
+ <Typography sx={{ px: 1, mb: 1, fontSize: 10, fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'text.secondary' }}>
+ Menu
+ </Typography>
+ <List disablePadding sx={{ display: 'flex', flexDirection: 'column', gap: 0.3 }}>
+ {NAV.map(item => {
+ const active = tab === item.id;
+ return (
+ <ListItemButton
+ key={item.id}
+ selected={active}
+ onClick={() => setTab(item.id)}
+ sx={{
+ borderRadius: 2, py: 1.1,
+ background: active
+ ? 'linear-gradient(135deg, rgba(255,0,0,0.18) 0%, rgba(255,68,68,0.08) 100%)'
+ : 'transparent',
+ border: active ? '1px solid rgba(255,0,0,0.2)' : '1px solid transparent',
+ '&:hover': {
+ background: active
+ ? 'linear-gradient(135deg, rgba(255,0,0,0.22) 0%, rgba(255,68,68,0.12) 100%)'
+ : 'rgba(255,255,255,0.04)',
+ },
+ transition: 'all 0.15s ease',
+ }}>
+ <ListItemIcon sx={{
+ minWidth: 38,
+ color: active ? '#FF4444' : '#64748B',
+ transition: 'color 0.15s',
+ }}>
+ {React.cloneElement(item.icon, { sx: { fontSize: 20 } })}
+ </ListItemIcon>
+ <ListItemText
+ primary={item.label}
+ primaryTypographyProps={{
+ fontSize: 13.5,
+ fontWeight: active ? 700 : 500,
+ color: active ? 'text.primary' : '#94A3B8',
+ letterSpacing: '-0.01em',
+ }}
+ />
+ {active && (
+ <Box sx={{
+ width: 6, height: 6, borderRadius: '50%',
+ background: '#FF0000',
+ boxShadow: '0 0 8px rgba(255,0,0,0.7)',
+ }} />
+ )}
+ </ListItemButton>
+ );
+ })}
+ </List>
+ </Box>
+
+ <Divider sx={{ mx: 2, my: 1.5 }} />
+
+ {/* Accounts Quick Access */}
+ <Box sx={{ px: 2, mb: 1 }}>
+ <Typography sx={{ fontSize: 10, fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'text.secondary' }}>
+ Accounts
+ </Typography>
+ </Box>
+
+ <List sx={{ px: 1.5, flex: 1, overflow: 'auto' }} disablePadding>
+ {accounts.length === 0 ? (
+ <Box sx={{ textAlign: 'center', py: 3, px: 2 }}>
+ <Typography sx={{ fontSize: 12, color: 'text.secondary', lineHeight: 1.5 }}>
+ No accounts added yet
+ </Typography>
+ </Box>
+ ) : (
+ accounts.map(acc => {
+ const isIG = acc.platform === 'instagram';
+ return (
+ <ListItemButton
+ key={acc.id}
+ onClick={() => onViewChannel(acc)}
+ sx={{
+ borderRadius: 2, mb: 0.4, py: 0.9,
+ '&:hover': { bgcolor: 'rgba(255,255,255,0.04)' },
+ }}>
+ <ListItemIcon sx={{ minWidth: 36 }}>
+ <Box sx={{ position: 'relative' }}>
+ <Avatar
+ src={acc.thumbnail || acc.thumbnails?.default || acc.thumbnailUrl || acc.profilePictureUrl || ''}
+ sx={{ width: 28, height: 28, border: 'none' }}>
+ {isIG ? <Instagram sx={{ fontSize: 14 }} /> : <YouTubeIcon sx={{ fontSize: 14 }} />}
+ </Avatar>
+ <Box sx={{
+ position: 'absolute', bottom: -2, right: -2,
+ width: 12, height: 12, borderRadius: '50%',
+ bgcolor: isIG ? '#E1306C' : '#FF0000',
+ border: '1.5px solid #060910',
+ display: 'flex', alignItems: 'center', justifyContent: 'center',
+ }}>
+ {isIG
+ ? <Instagram sx={{ fontSize: 7, color: '#fff' }} />
+ : <YouTubeIcon sx={{ fontSize: 7, color: '#fff' }} />}
+ </Box>
+ </Box>
+ </ListItemIcon>
+ <ListItemText
+ primary={acc.title}
+ primaryTypographyProps={{ fontSize: 12.5, fontWeight: 500, noWrap: true, color: '#CBD5E1' }}
+ />
+ </ListItemButton>
+ );
+ })
+ )}
+ </List>
+
+ {/* Footer summary */}
+ <Box sx={{ p: 2, pt: 1.5 }}>
+ <Divider sx={{ mb: 1.5 }} />
+ <Box sx={{ display: 'flex', gap: 1 }}>
+ <Chip
+ icon={<YouTubeIcon sx={{ fontSize: '14px !important' }} />}
+ label={`${accounts.filter(a => a.platform !== 'instagram').length} YT`}
+ size="small" variant="outlined"
+ sx={{ flex: 1, justifyContent: 'flex-start', borderColor: 'rgba(255,0,0,0.25)', color: '#FF4444', fontSize: 11, fontWeight: 600 }}
+ />
+ <Chip
+ icon={<Instagram sx={{ fontSize: '14px !important' }} />}
+ label={`${accounts.filter(a => a.platform === 'instagram').length} IG`}
+ size="small" variant="outlined"
+ sx={{ flex: 1, justifyContent: 'flex-start', borderColor: 'rgba(225,48,108,0.25)', color: '#E1306C', fontSize: 11, fontWeight: 600 }}
+ />
+ </Box>
+ </Box>
+ </Drawer>
+ );
+}
diff --git a/frontend/src/theme.js b/frontend/src/theme.js
index 46f8383..91fe330 100644
--- a/frontend/src/theme.js
+++ b/frontend/src/theme.js
@@ -5,33 +5,37 @@ const theme = createTheme({
mode: 'dark',
primary: { main: '#FF0000', light: '#FF4444', dark: '#CC0000' },
secondary: { main: '#3EA6FF', light: '#6EC6FF', dark: '#0078D4' },
- background: { default: '#0F0F0F', paper: '#1A1A1A' },
- success: { main: '#2E7D32', light: '#4CAF50' },
- warning: { main: '#FF9800', light: '#FFB74D' },
- error: { main: '#F44336', light: '#EF5350' },
- text: { primary: '#FFFFFF', secondary: '#AAAAAA' },
- divider: 'rgba(255,255,255,0.08)',
- youtube: { main: '#FF0000', dark: '#CC0000', contrastText: '#fff' },
+ background: { default: '#080B14', paper: '#0E1420' },
+ success: { main: '#22C55E', light: '#4ADE80', dark: '#16A34A' },
+ warning: { main: '#F59E0B', light: '#FCD34D' },
+ error: { main: '#EF4444', light: '#F87171' },
+ text: { primary: '#F1F5F9', secondary: '#94A3B8' },
+ divider: 'rgba(255,255,255,0.07)',
},
typography: {
fontFamily: '"Inter", "Roboto", "Helvetica", "Arial", sans-serif',
- h3: { fontWeight: 700, letterSpacing: '-0.02em' },
- h4: { fontWeight: 700, letterSpacing: '-0.02em' },
- h5: { fontWeight: 600, letterSpacing: '-0.01em' },
- h6: { fontWeight: 600 },
- subtitle1: { color: '#AAAAAA' },
- body2: { color: '#AAAAAA' },
+ h3: { fontWeight: 800, letterSpacing: '-0.03em' },
+ h4: { fontWeight: 800, letterSpacing: '-0.02em' },
+ h5: { fontWeight: 700, letterSpacing: '-0.01em' },
+ h6: { fontWeight: 600, letterSpacing: '-0.01em' },
+ subtitle1: { color: '#94A3B8', fontWeight: 500 },
+ body2: { color: '#94A3B8' },
+ caption: { color: '#64748B' },
},
- shape: { borderRadius: 12 },
+ shape: { borderRadius: 14 },
components: {
MuiCard: {
styleOverrides: {
root: {
backgroundImage: 'none',
- backgroundColor: '#1A1A1A',
- border: '1px solid rgba(255,255,255,0.06)',
- transition: 'all 0.2s ease',
- '&:hover': { borderColor: 'rgba(255,255,255,0.12)' },
+ backgroundColor: '#0E1420',
+ border: '1px solid rgba(255,255,255,0.07)',
+ boxShadow: '0 4px 24px rgba(0,0,0,0.4)',
+ transition: 'border-color 0.2s, box-shadow 0.2s',
+ '&:hover': {
+ borderColor: 'rgba(255,255,255,0.13)',
+ boxShadow: '0 8px 32px rgba(0,0,0,0.5)',
+ },
},
},
},
@@ -42,19 +46,29 @@ const theme = createTheme({
},
MuiButton: {
styleOverrides: {
- root: { textTransform: 'none', fontWeight: 600, borderRadius: 8 },
+ root: {
+ textTransform: 'none',
+ fontWeight: 600,
+ borderRadius: 10,
+ letterSpacing: '-0.01em',
+ },
+ contained: {
+ boxShadow: '0 4px 14px rgba(0,0,0,0.4)',
+ '&:hover': { boxShadow: '0 6px 20px rgba(0,0,0,0.5)' },
+ },
},
},
MuiChip: {
styleOverrides: {
- root: { fontWeight: 500 },
+ root: { fontWeight: 600, borderRadius: 8 },
},
},
MuiDrawer: {
styleOverrides: {
paper: {
- backgroundColor: '#0A0A0A',
+ backgroundColor: '#060910',
borderRight: '1px solid rgba(255,255,255,0.06)',
+ backgroundImage: 'none',
},
},
},
@@ -62,7 +76,11 @@ const theme = createTheme({
styleOverrides: {
root: {
'& .MuiOutlinedInput-root': {
- borderRadius: 8,
+ borderRadius: 10,
+ backgroundColor: 'rgba(255,255,255,0.03)',
+ '& fieldset': { borderColor: 'rgba(255,255,255,0.1)' },
+ '&:hover fieldset': { borderColor: 'rgba(255,255,255,0.18)' },
+ '&.Mui-focused fieldset': { borderColor: 'rgba(255,0,0,0.5)' },
},
},
},
@@ -70,20 +88,72 @@ const theme = createTheme({
MuiDialog: {
styleOverrides: {
paper: {
- backgroundColor: '#1A1A1A',
+ backgroundColor: '#0E1420',
backgroundImage: 'none',
- borderRadius: 16,
+ borderRadius: 18,
+ border: '1px solid rgba(255,255,255,0.08)',
+ boxShadow: '0 25px 60px rgba(0,0,0,0.7)',
},
},
},
MuiTooltip: {
styleOverrides: {
- tooltip: { backgroundColor: '#333', fontSize: 13 },
+ tooltip: {
+ backgroundColor: '#1E2A3A',
+ border: '1px solid rgba(255,255,255,0.1)',
+ fontSize: 12,
+ fontWeight: 500,
+ borderRadius: 8,
+ padding: '6px 12px',
+ },
},
},
MuiLinearProgress: {
styleOverrides: {
- root: { borderRadius: 4, height: 6 },
+ root: { borderRadius: 6, height: 6, backgroundColor: 'rgba(255,255,255,0.06)' },
+ },
+ },
+ MuiTableHead: {
+ styleOverrides: {
+ root: {
+ '& .MuiTableCell-head': {
+ backgroundColor: 'rgba(255,255,255,0.03)',
+ color: '#64748B',
+ fontWeight: 700,
+ fontSize: 11,
+ textTransform: 'uppercase',
+ letterSpacing: '0.08em',
+ borderBottom: '1px solid rgba(255,255,255,0.07)',
+ },
+ },
+ },
+ },
+ MuiTableRow: {
+ styleOverrides: {
+ root: {
+ '&:hover': { backgroundColor: 'rgba(255,255,255,0.025) !important' },
+ '& .MuiTableCell-root': {
+ borderBottom: '1px solid rgba(255,255,255,0.05)',
+ color: '#CBD5E1',
+ },
+ },
+ },
+ },
+ MuiDivider: {
+ styleOverrides: {
+ root: { borderColor: 'rgba(255,255,255,0.07)' },
+ },
+ },
+ MuiListItemButton: {
+ styleOverrides: {
+ root: { borderRadius: 10, transition: 'all 0.15s ease' },
+ },
+ },
+ MuiAvatar: {
+ styleOverrides: {
+ root: {
+ border: '2px solid rgba(255,255,255,0.08)',
+ },
},
},
},