feat(api): scheduled-post queue endpoints, and fix the template's slot race

GET /api/social/scheduled lists the caller's pending posts and
DELETE /api/social/scheduled/{job_id} cancels one. Upload-Post's own
schedule endpoint takes no profile filter and returns the whole managed
account, so both filter by the caller's profile server-side — the same
multi-tenant trap as the impressions endpoint, and the reason cancel
404s instead of 403s on someone else's job.

The template picked its next daily slot from n8n workflow static data,
which two approvals tapped seconds apart both read before either wrote,
booking the same slot and publishing together (seen in a live run). It
now derives the slot from the server-held queue, which is shared state
and cannot race with itself that way.
This commit is contained in:
juancarlos.cavero 2026-08-21 21:03:41 +02:00
parent 05c0238cc0
commit 149ca85831
3 changed files with 102 additions and 21 deletions

44
app.py
View file

@ -3981,6 +3981,50 @@ async def social_total_impressions(
return result return result
async def _scheduled_posts_for(api_key: str, profile: str) -> list:
"""The caller's pending scheduled posts.
Upload-Post's GET /uploadposts/schedule takes no profile filter and returns
everything the *account* has pending — with the managed key that is every
OpenShorts user's queue, so the filter below is what keeps one tenant from
seeing (or cancelling) another's. Same class of bug as the impressions
endpoint; do not "simplify" it away.
"""
data = await _upload_post_get(
api_key, "https://api.upload-post.com/api/uploadposts/schedule", {})
rows = data.get("scheduled_posts") or data.get("data") or []
return [r for r in rows
if isinstance(r, dict) and r.get("profile_username") == profile]
@app.get("/api/social/scheduled")
async def social_scheduled(request: Request, user: Optional[str] = None):
"""Pending scheduled posts for the caller's profile, soonest first."""
api_key, profile = await _social_analytics_auth(request, user)
rows = await _scheduled_posts_for(api_key, profile)
rows.sort(key=lambda r: r.get("scheduled_date") or "")
return {"profile_username": profile, "scheduled_posts": rows}
@app.delete("/api/social/scheduled/{job_id}")
async def social_cancel_scheduled(job_id: str, request: Request, user: Optional[str] = None):
"""Cancel one pending scheduled post, if it belongs to the caller."""
api_key, profile = await _social_analytics_auth(request, user)
rows = await _scheduled_posts_for(api_key, profile)
if not any(r.get("job_id") == job_id for r in rows):
# 404 rather than 403: never confirm that someone else's job exists.
raise HTTPException(status_code=404, detail="Scheduled post not found")
headers = {"Authorization": f"Apikey {api_key}"}
async with httpx.AsyncClient(timeout=30.0) as client:
resp = await client.delete(
f"https://api.upload-post.com/api/uploadposts/schedule/{job_id}",
headers=headers)
if resp.status_code not in (200, 202, 204):
raise HTTPException(status_code=resp.status_code,
detail=f"Vendor API Error: {resp.text}")
return {"success": True, "job_id": job_id}
# --- Thumbnail Studio Endpoints --- # --- Thumbnail Studio Endpoints ---
@app.post("/api/thumbnail/upload") @app.post("/api/thumbnail/upload")

View file

@ -49,7 +49,9 @@ changing the base URL (needs a GPU box, your own Gemini key, and your own
3. **Drip-publish** — each approved clip takes the next free daily slot and is 3. **Drip-publish** — each approved clip takes the next free daily slot and is
scheduled through `POST /api/social/post` to every account you connected in scheduled through `POST /api/social/post` to every account you connected in
OpenShorts (TikTok, Instagram, YouTube). Approve five clips today, fill five OpenShorts (TikTok, Instagram, YouTube). Approve five clips today, fill five
days of content. days of content. The slot comes from the queue the server actually holds
(`GET /api/social/scheduled`), so two clips approved seconds apart cannot
book the same one.
4. **Sunday digest** — the machine reads the analytics of what it published 4. **Sunday digest** — the machine reads the analytics of what it published
(`GET /api/social/analytics/*`) and reports total impressions, per-platform (`GET /api/social/analytics/*`) and reports total impressions, per-platform
split, and your best post of the week. split, and your best post of the week.
@ -64,9 +66,10 @@ Machine-specific setup, all inside sticky notes on the canvas:
- Connect your social accounts in your OpenShorts account page (Cloud) — the - Connect your social accounts in your OpenShorts account page (Cloud) — the
posting step uses them directly; no extra social credentials in n8n. posting step uses them directly; no extra social credentials in n8n.
Note: the machine remembers processed videos and scheduling slots in n8n Note: the machine remembers which videos it already processed in n8n workflow
workflow static data, which only persists for **production** executions — test static data, which only persists for **production** executions — test runs in
runs in the editor won't advance the state. the editor won't advance it. Scheduling deliberately does *not* use that
mechanism (see act 3).
## Webhook payload ## Webhook payload
@ -91,6 +94,8 @@ service). On the self-hosted edition the same workflow runs against
## Publishing and analytics API ## Publishing and analytics API
Direct posting: `POST /api/social/post` (accepts `scheduled_date`, ISO-8601). Direct posting: `POST /api/social/post` (accepts `scheduled_date`, ISO-8601).
Publishing queue: `GET /api/social/scheduled`, and
`DELETE /api/social/scheduled/{job_id}` to cancel one before it goes out.
Analytics of what you published: `GET /api/social/analytics` (profile totals), Analytics of what you published: `GET /api/social/analytics` (profile totals),
`GET /api/social/analytics/posts` (per-post metrics), `GET /api/social/analytics/posts` (per-post metrics),
`GET /api/social/analytics/impressions` (windowed totals, `period=last_week`). `GET /api/social/analytics/impressions` (windowed totals, `period=last_week`).

View file

@ -332,7 +332,7 @@
}, },
{ {
"parameters": { "parameters": {
"content": "## ACT 3 \u2014 Tap \u2705, it gets scheduled\n\nThe Telegram trigger listens for the approval buttons. Every approved clip is scheduled through OpenShorts (which posts to every social account you connected there \u2014 TikTok, Instagram, YouTube) at a rate of **one post per day**: approve five clips today and you just filled five days of content.\n\n**Setup**: none beyond the Telegram credential \u2014 the chat id comes from the button tap itself. Change the platforms list in *Schedule social post* if you want fewer networks.", "content": "## ACT 3 \u2014 Tap \u2705, it gets scheduled\n\nThe Telegram trigger listens for the approval buttons. Every approved clip is scheduled through OpenShorts (which posts to every social account you connected there) at a rate of **one post per day**: approve five clips today and you just filled five days of content.\n\nThe next free slot is computed from the **queue the server actually holds** (`GET /api/social/scheduled`), not from a counter inside n8n \u2014 two clips approved seconds apart would otherwise both book the same slot and go out together.\n\n**Setup**: none beyond the Telegram credential \u2014 the chat id comes from the button tap itself. Change the platforms list in *Schedule social post* if you want fewer networks.",
"height": 380, "height": 380,
"width": 400, "width": 400,
"color": 6 "color": 6
@ -415,14 +415,14 @@
}, },
{ {
"parameters": { "parameters": {
"jsCode": "// One post per day: each approval takes the next free daily slot, so a\n// batch of approvals turns into a steady drip instead of a burst.\nconst staticData = $getWorkflowStaticData('global');\nconst now = Date.now();\nconst last = staticData.lastScheduledAt || 0;\nconst slot = Math.max(now + 10 * 60 * 1000, last + 24 * 60 * 60 * 1000);\nstaticData.lastScheduledAt = slot;\nconst item = $input.first().json;\nreturn [{ json: { ...item, scheduled_date: new Date(slot).toISOString() } }];" "jsCode": "// One post per day, derived from the queue the server actually holds.\n// Workflow static data was the obvious place to remember the last slot, but\n// two approvals tapped seconds apart run as two executions that both read the\n// old value and book the SAME slot. The scheduled list is shared state, so\n// counting it cannot race with itself in that way.\nconst queue = $input.first().json.scheduled_posts || [];\nconst item = $('Parse button').first().json;\nconst DAY = 24 * 60 * 60 * 1000;\nconst taken = queue\n .map((p) => Date.parse(p.scheduled_date))\n .filter((t) => !Number.isNaN(t))\n .sort((a, b) => a - b);\nlet slot = Date.now() + 10 * 60 * 1000; // never schedule in the past\nfor (const t of taken) {\n if (Math.abs(t - slot) < DAY) slot = t + DAY;\n}\nreturn [{ json: { ...item, scheduled_date: new Date(slot).toISOString() } }];"
}, },
"id": "reserve-slot", "id": "reserve-slot",
"name": "Reserve daily slot", "name": "Pick next free slot",
"type": "n8n-nodes-base.code", "type": "n8n-nodes-base.code",
"typeVersion": 2, "typeVersion": 2,
"position": [ "position": [
580, 800,
840 840
] ]
}, },
@ -455,7 +455,7 @@
{ {
"parameters": { "parameters": {
"chatId": "={{ $('Parse button').first().json.chat_id }}", "chatId": "={{ $('Parse button').first().json.chat_id }}",
"text": "=\ud83d\udcc5 Scheduled! Going out to your connected accounts on {{ $('Reserve daily slot').first().json.scheduled_date.slice(0, 10) }}.", "text": "=\ud83d\udcc5 Scheduled! Going out to your connected accounts on {{ $('Pick next free slot').first().json.scheduled_date.slice(0, 10) }}.",
"additionalFields": {} "additionalFields": {}
}, },
"id": "tg-scheduled", "id": "tg-scheduled",
@ -647,6 +647,27 @@
"name": "Telegram bot" "name": "Telegram bot"
} }
} }
},
{
"parameters": {
"url": "https://api.openshorts.app/api/social/scheduled",
"authentication": "genericCredentialType",
"genericAuthType": "httpHeaderAuth",
"options": {}
},
"id": "read-queue",
"name": "Read publishing queue",
"type": "n8n-nodes-base.httpRequest",
"typeVersion": 4.2,
"position": [
580,
840
],
"credentials": {
"httpHeaderAuth": {
"name": "OpenShorts API key"
}
}
} }
], ],
"connections": { "connections": {
@ -790,7 +811,7 @@
"main": [ "main": [
[ [
{ {
"node": "Reserve daily slot", "node": "Read publishing queue",
"type": "main", "type": "main",
"index": 0 "index": 0
} }
@ -804,17 +825,6 @@
] ]
] ]
}, },
"Reserve daily slot": {
"main": [
[
{
"node": "Schedule social post",
"type": "main",
"index": 0
}
]
]
},
"Schedule social post": { "Schedule social post": {
"main": [ "main": [
[ [
@ -876,6 +886,28 @@
} }
] ]
] ]
},
"Read publishing queue": {
"main": [
[
{
"node": "Pick next free slot",
"type": "main",
"index": 0
}
]
]
},
"Pick next free slot": {
"main": [
[
{
"node": "Schedule social post",
"type": "main",
"index": 0
}
]
]
} }
}, },
"settings": { "settings": {