[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7EVKBW5D2H8P2TQ8NY9VKY4":3,"skill-same:01M7EVKBW5D2H8P2TQ8NY9VKY4":83},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":39,"commitSha":40,"skillDirectory":41,"forksCount":42,"repositoryHtmlUrl":43,"repositoryHomepageUrl":6,"ownerHtmlUrl":44,"ownerBlogUrl":6,"ownerDescription":45,"updatedAt":46,"install":47,"resources":60},"01M7EVKBW5D2H8P2TQ8NY9VKY4","youtube-api",null,"Use when wiring code to a real YouTube channel: user OAuth 2.0, resumable videos.insert uploads, editing metadata after publish, pulling views\u002Fwatch time\u002Fretention\u002Ftraffic from the Analytics API v2 into a dated 02-DOCS\u002Fwiki\u002Fyoutube\u002F feedback log. NOT what to publish or how to title and thumbnail it (that is youtube-strategy \u002F youtube-packaging).","lza6\u002FArmor-piercing-system-prompts","lza6","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F128880206?v=4","01M7EB3K7WPX5T28EJ2NVHE6EG","Chinese-tingfeng","01M7EB3K97E1KQ16QWKJMFNGX8",11,"MIT","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F04-安全渗透\u002Fyoutube-api\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: youtube-api\ndescription: \"Use when wiring code to a real YouTube channel: user OAuth 2.0, resumable videos.insert uploads, editing metadata after publish, pulling views\u002Fwatch time\u002Fretention\u002Ftraffic from the Analytics API v2 into a dated 02-DOCS\u002Fwiki\u002Fyoutube\u002F feedback log. NOT what to publish or how to title and thumbnail it (that is youtube-strategy \u002F youtube-packaging).\"\ntags: [youtube, youtube-data-api, youtube-analytics-api, oauth2, resumable-upload, video-metadata, audience-retention, channel-feedback-log]\nrecommends: [social-publisher, api-connector-builder, automation-flows, knowledge-ops]\norigin: risco\n---\n\n# YouTube API — Transport + Ingestion for a Real Channel\n\n*You own the wire: authenticate to a YouTube channel, upload and edit videos, pull the numbers, and write those numbers into the wiki as a durable feedback log. You do not decide what to make or how to title it — that is the strategy\u002Fpackaging family. Deliver clean transport and a queryable log; let the siblings interpret.*\n\nYouTube has **two separate APIs** and you will touch both:\n\n- **Data API v3** — `https:\u002F\u002Fwww.googleapis.com\u002Fyoutube\u002Fv3` — the *write* side: `videos.insert` (upload), `videos.update` (edit metadata), `thumbnails.set`. Default quota: a shared 10,000 units\u002Fday pool *plus* separate per-day caps of ~100 uploads and ~100 `search.list` calls (see §7).\n- **Analytics API v2** — `https:\u002F\u002Fyoutubeanalytics.googleapis.com\u002Fv2\u002Freports` — the *read* side: views, watch time, retention, traffic sources. Separate scopes, separate quota.\n\nAuth is **user OAuth 2.0, not a service account.** A human owns the channel; you act on their behalf with a refresh token. A service account cannot own a YouTube channel — if you reach for one, stop. (Service-account Google auth for Gmail\u002FDrive\u002FSheets is `google-workspace`, a different model.)\n\nRoute elsewhere when the job is not transport:\n\n| You actually want | Go to |\n| --- | --- |\n| What videos to make \u002F niche \u002F cadence \u002F growth plan | `..\u002Fyoutube-strategy\u002FSKILL.md` |\n| Video ideas, hooks, a topic backlog | `..\u002Fyoutube-ideation\u002FSKILL.md` |\n| Title + thumbnail packaging, CTR copy, A\u002FB framing | `..\u002Fyoutube-packaging\u002FSKILL.md` |\n| The thumbnail image itself | `..\u002Fyoutube-thumbnails\u002FSKILL.md` |\n| Render\u002Fproduce the actual video file in code | `..\u002Fremotion-video\u002FSKILL.md` |\n| Post one asset across many networks at once | `..\u002Fsocial-publisher\u002FSKILL.md` |\n| Wrap an arbitrary REST provider with OAuth + retries | `..\u002Fapi-connector-builder\u002FSKILL.md` |\n| Chain upload → Notion row → Slack across tools | `..\u002Fautomation-flows\u002FSKILL.md` |\n| Service-account auth to Gmail\u002FDrive\u002FSheets | `..\u002Fgoogle-workspace\u002FSKILL.md` |\n| Generic wiki structure and conventions | `..\u002Fknowledge-ops\u002FSKILL.md` |\n\n## 1. One-time setup (do this before any code)\n\nA checklist, because each missing step produces a distinct, confusing error later:\n\n1. Create (or pick) a **GCP project**.\n2. **Enable both APIs** in that project: \"YouTube Data API v3\" *and* \"YouTube Analytics API\". Enabling one is the most common cause of a `403 ... has not been used in project` on the other.\n3. Configure the **OAuth consent screen** and **publish it to \"In production.\"** Why: an app left in \"Testing\" status issues refresh tokens that **expire in 7 days** — your cron silently dies the following week. This is the single most common YouTube-ingestion breakage.\n4. Create an **OAuth client**: *Desktop app* for a personal\u002Flocal script, *Web application* (with an exact redirect URI) for a hosted app.\n5. Request **least-privilege scopes** — not the full management scope.\n\nScope table — request only what the job needs:\n\n| Scope | Grants | Use for |\n| --- | --- | --- |\n| `https:\u002F\u002Fwww.googleapis.com\u002Fauth\u002Fyoutube.upload` | Upload videos | `videos.insert` |\n| `https:\u002F\u002Fwww.googleapis.com\u002Fauth\u002Fyoutube.force-ssl` | Manage\u002Fedit\u002Fdelete | `videos.update`, `thumbnails.set` |\n| `https:\u002F\u002Fwww.googleapis.com\u002Fauth\u002Fyt-analytics.readonly` | Read performance | Analytics reports |\n| `https:\u002F\u002Fwww.googleapis.com\u002Fauth\u002Fyt-analytics-monetary.readonly` | Read revenue metrics | only if you pull `estimatedRevenue` etc. |\n\nBad → Good on scopes:\n\n```text\nBad:  scopes = [\"https:\u002F\u002Fwww.googleapis.com\u002Fauth\u002Fyoutube\"]   # full account control\nGood: scopes = [\"https:\u002F\u002Fwww.googleapis.com\u002Fauth\u002Fyoutube.upload\",\n                \"https:\u002F\u002Fwww.googleapis.com\u002Fauth\u002Fyoutube.force-ssl\",\n                \"https:\u002F\u002Fwww.googleapis.com\u002Fauth\u002Fyt-analytics.readonly\"]\n```\n\nFull GCP + consent-screen walkthrough, Desktop-vs-Web choice, and `unauthorized_client` \u002F `access_denied` \u002F redirect-URI troubleshooting live in `references\u002Foauth-setup.md`.\n\n## 2. Get an authed client and keep the token alive\n\nBuild both service clients from **one** set of OAuth credentials.\n\n```python\n# python: google-api-python-client + google-auth-oauthlib\nfrom google_auth_oauthlib.flow import InstalledAppFlow\nfrom google.auth.transport.requests import Request\nfrom googleapiclient.discovery import build\nimport json, os\nfrom google.oauth2.credentials import Credentials\n\nSCOPES = [\"https:\u002F\u002Fwww.googleapis.com\u002Fauth\u002Fyoutube.upload\",\n          \"https:\u002F\u002Fwww.googleapis.com\u002Fauth\u002Fyoutube.force-ssl\",\n          \"https:\u002F\u002Fwww.googleapis.com\u002Fauth\u002Fyt-analytics.readonly\"]\nTOKEN = \"token.json\"   # gitignored — holds the refresh_token\n\ndef creds():\n    c = Credentials.from_authorized_user_file(TOKEN, SCOPES) if os.path.exists(TOKEN) else None\n    if not c or not c.valid:\n        if c and c.expired and c.refresh_token:\n            c.refresh(Request())               # silent renewal — needs \"In production\" app\n        else:\n            c = InstalledAppFlow.from_client_secrets_file(\n                \"client_secret.json\", SCOPES).run_local_server(port=0)\n        with open(TOKEN, \"w\") as f:\n            f.write(c.to_json())\n    return c\n\nc = creds()\ndata = build(\"youtube\", \"v3\", credentials=c)\nyta  = build(\"youtubeAnalytics\", \"v2\", credentials=c)\n```\n\n```javascript\n\u002F\u002F node: googleapis + google-auth-library\nimport { google } from \"googleapis\";\nimport fs from \"node:fs\";\n\nconst oauth2 = new google.auth.OAuth2(CLIENT_ID, CLIENT_SECRET, REDIRECT_URI);\noauth2.setCredentials(JSON.parse(fs.readFileSync(\"token.json\", \"utf8\"))); \u002F\u002F { refresh_token, ... }\noauth2.on(\"tokens\", (t) => {                 \u002F\u002F persist the refreshed token\n  if (t.refresh_token) fs.writeFileSync(\"token.json\", JSON.stringify(t));\n});\nconst data = google.youtube({ version: \"v3\", auth: oauth2 });\nconst yta  = google.youtubeAnalytics({ version: \"v2\", auth: oauth2 });\n```\n\nRule: persist the **refresh token**, never a bare `access_token`. Access tokens expire in ~1 hour; the credential object refreshes itself. A hardcoded `access_token=...` literal is a guaranteed 401 within the hour — and is exactly what `verify.sh` flags.\n\n## 3. Upload a video (resumable, always)\n\nDecision: any file over a few MB → use the **resumable** protocol. A plain multipart POST drops the whole upload on one network hiccup; resumable survives it.\n\nThe protocol is two steps:\n\n1. **Init the session** — POST to the upload endpoint with `uploadType=resumable` and the metadata body. The response `Location` header is your session URL.\n2. **PUT the bytes** to that session URL — one shot or in chunks. On a dropped connection, query with `Content-Range: bytes *\u002F*`; the server returns the byte offset already received, and you resume from there.\n\nThe client libraries do this for you via a media-upload helper:\n\n```python\nfrom googleapiclient.http import MediaFileUpload\n\nbody = {\n  \"snippet\": {\"title\": \"Ep. 14\", \"description\": \"...\", \"tags\": [\"x\", \"y\"], \"categoryId\": \"27\"},\n  \"status\":  {\"privacyStatus\": \"private\", \"publishAt\": \"2026-06-10T15:00:00Z\",\n              \"selfDeclaredMadeForKids\": False},\n}\nmedia = MediaFileUpload(\"ep14.mp4\", chunksize=8 * 1024 * 1024, resumable=True)\nreq = data.videos().insert(part=\"snippet,status\", body=body, media_body=media)\nresp = None\nwhile resp is None:\n    status, resp = req.next_chunk()          # resumes automatically on a transient drop\nvideo_id = resp[\"id\"]\ndata.thumbnails().set(videoId=video_id, media_body=MediaFileUpload(\"ep14.jpg\")).execute()\n```\n\nThrottle the upload **count**, not the unit spend: `videos.insert` has its own cap of ~100 uploads\u002Fday, so `uploadLimitExceeded` (429) hits while the 10k unit pool still looks untouched. Space automated uploads out and back off on 429 — figures and citation in §7.\n\n## 4. Edit metadata after publish\n\n`videos.update` does **read-modify-write** semantics on whole parts. The trap: any field you omit inside a part you send gets **cleared**.\n\n```python\n# Bad: wipes description and tags because they aren't in the body\ndata.videos().update(part=\"snippet\",\n    body={\"id\": vid, \"snippet\": {\"title\": \"New title\", \"categoryId\": \"27\"}}).execute()\n\n# Good: fetch the current snippet, change one field, send it back whole\ncur = data.videos().list(part=\"snippet\", id=vid).execute()[\"items\"][0][\"snippet\"]\ncur[\"title\"] = \"New title\"\ndata.videos().update(part=\"snippet\", body={\"id\": vid, \"snippet\": cur}).execute()\n```\n\n`categoryId` is required when you send a `snippet` part — another reason to read-modify-write. An update costs **~50 units**.\n\n## 5. Pull performance (Analytics API v2)\n\nEvery report is `GET \u002Fv2\u002Freports?ids=channel==MINE&startDate=&endDate=&metrics=...&dimensions=...&filters=...`. Four recipes cover the loop:\n\n```python\n# (a) Channel KPIs over a date range\nyta.reports().query(ids=\"channel==MINE\", startDate=\"2026-05-01\", endDate=\"2026-05-31\",\n  metrics=\"views,estimatedMinutesWatched,averageViewDuration,averageViewPercentage\"\n).execute()\n\n# (b) Per-video KPIs\nyta.reports().query(ids=\"channel==MINE\", startDate=\"2026-05-01\", endDate=\"2026-05-31\",\n  metrics=\"views,estimatedMinutesWatched,averageViewPercentage\",\n  filters=\"video==VIDEO_ID\").execute()\n\n# (c) Audience-retention curve for one video\nyta.reports().query(ids=\"channel==MINE\", startDate=\"2026-05-01\", endDate=\"2026-05-31\",\n  metrics=\"audienceWatchRatio,relativeRetentionPerformance\",\n  dimensions=\"elapsedVideoTimeRatio\", filters=\"video==VIDEO_ID\").execute()\n\n# (d) Traffic sources\nyta.reports().query(ids=\"channel==MINE\", startDate=\"2026-05-01\", endDate=\"2026-05-31\",\n  metrics=\"views,estimatedMinutesWatched\",\n  dimensions=\"insightTrafficSourceType\").execute()\n```\n\nNotes that save an afternoon:\n\n- `elapsedVideoTimeRatio` runs 0.0–1.0 (playback position); `audienceWatchRatio` is the absolute retention at that point. Plot one against the other to find the drop-off.\n- `insightTrafficSourceType` values include `YT_SEARCH`, `SUGGESTED`, `BROWSE`, `EXT_URL`, `NOTIFICATION`, `PLAYLIST`, `END_SCREEN`, `NO_LINK_EMBEDDED`.\n- **Impressions \u002F CTR** (`impressions`, `impressionClickThroughRate`) are **content-owner-report metrics**, not reliably available on a plain channel query. If the API returns nothing for them, fall back to the value Studio shows — do not block the pull.\n\nFull metric+dimension catalog and copy-paste bodies for geography, device, and subscribed-status reports are in `references\u002Fanalytics-queries.md`.\n\n## 6. Ingest into the wiki — the actual deliverable\n\nA pull that prints to stdout and vanishes is wasted. **Every pull appends a dated entry under `02-DOCS\u002Fwiki\u002Fyoutube\u002F`** so the channel's numbers become queryable history that the strategy\u002Fpackaging siblings can read.\n\n```text\n02-DOCS\u002Fwiki\u002Fyoutube\u002F\n  index.md                  # rolling pointer to latest snapshot + open questions\n  channel-2026-05-31.md     # dated channel snapshot (one per pull)\n  videos\u002F\u003CVIDEO_ID>.md      # per-video running log, newest entry on top\n```\n\nPer-pull entry template (OKF v0.1: non-empty `type` + the domain keys siblings parse):\n\n```markdown\n---\ntype: youtube-metrics\ntitle: Channel snapshot 2026-05-31\ndescription: Channel KPIs, traffic and retention for 2026-05-01..2026-05-31.\ntags: [youtube, channel-snapshot]\ntimestamp: 2026-05-31T00:00:00Z\ndate: 2026-05-31\nrange: 2026-05-01..2026-05-31\nchannel: MINE\nsource: youtube-analytics-api-v2\n---\n## KPIs\nviews: 41,233 | watch_min: 88,140 | avg_view_pct: 38.2% | avg_view_dur: 0:04:11\n\n## Traffic (top 3)\nBROWSE 44% · SUGGESTED 31% · YT_SEARCH 12%\n\n## Retention\nSharp drop 0.00→0.06 (intro), recovers, second dip ~0.55.\n\n## What changed since last pull\navg_view_pct +2.1pts; SUGGESTED share up 6pts after the Ep.13 packaging change.\n```\n\nRule: **append, never overwrite.** The feedback log *is* the value — overwriting yesterday's snapshot destroys the trend the siblings need. `02-DOCS\u002Fwiki\u002F` is an OKF v0.1 bundle: keep the domain keys (`date`, `range`, `channel`, `source`) the siblings parse, add `type`\u002F`timestamp` alongside them, use standard markdown links (never `[[wikilinks]]`), and leave the reserved `index.md` frontmatter-free. Exact file tree, naming, per-video log shape, and how siblings read the log: `references\u002Fwiki-schema.md`.\n\n## 7. Quota & failure math\n\n| Call | Cost \u002F allocation |\n| --- | --- |\n| `videos.insert` (upload) | own daily cap: **~100 uploads\u002Fday**, not 10k-pool units |\n| `search.list` | own daily cap: ~100 calls\u002Fday |\n| write: `videos.update`, `thumbnails.set` | ~50 units (from the 10k pool) |\n| `*.list` read | 1–5 units (from the 10k pool) |\n| Analytics `reports.query` | (separate Analytics quota) |\n\nPer the official docs (Last updated 2026-06-01 UTC, `https:\u002F\u002Fdevelopers.google.com\u002Fyoutube\u002Fv3\u002Fgetting-started`; per-method costs at `https:\u002F\u002Fdevelopers.google.com\u002Fyoutube\u002Fv3\u002Fdetermine_quota_cost`), a project's default allocation is *\"100 search.list calls, 100 videos.insert calls, and 10,000 units per day combined for all other endpoints.\"* All quotas reset at midnight Pacific. This is a change from the older single-pool model where `videos.insert` cost ~1,600 units — confirm the live figure on the quota-cost page before relying on it, since Google notes the allocation \"is subject to change.\"\n\nOn `403 quotaExceeded` \u002F `rateLimitExceeded` or `429`: **exponential backoff with jitter**, then stop for the day on a hard quota cap — retrying a daily-quota 403 in a tight loop just burns the next day too.\n\nError → cause map:\n\n| Symptom | Cause | Fix |\n| --- | --- | --- |\n| Refresh token dies after ~7 days | App still in \"Testing\" | Publish consent screen to \"In production\" |\n| `unauthorized_client` | Consent\u002Fclient misconfig or wrong client type | Re-check OAuth client + authorized scopes |\n| `403 insufficient permissions` | Missing scope | Add the right scope, re-consent |\n| `uploadLimitExceeded` (429) | Hit the ~100 `videos.insert`\u002Fday cap (separate from the 10k unit pool) | Throttle upload count, back off |\n| Empty `impressions`\u002FCTR | Not a content-owner channel query | Read it from Studio |\n| `403 ... API has not been used` | Other API not enabled | Enable both Data v3 and Analytics v2 |\n\n## Anti-patterns\n\n| Anti-pattern | Why it bites | Do instead |\n| --- | --- | --- |\n| Commit `client_secret.json` \u002F `token.json` with `refresh_token` | Leaks full channel control to anyone with repo read | Gitignore both; load from env\u002Fsecret store |\n| Request full `auth\u002Fyoutube` scope | Grants total account control; fails review | Least set: `youtube.upload` + `youtube.force-ssl` + `yt-analytics.readonly` |\n| Hardcode an `access_token` | Dead in ~1 hour | Persist the refresh token; use a refreshable credential |\n| `videos.update` with a partial part | Omitted fields get wiped | Read-modify-write the whole part |\n| Plain multipart upload for a big file | One drop kills the whole upload | Resumable protocol with chunked PUT |\n| Treat the 10k unit pool as the upload budget | Uploads use a separate ~100\u002Fday call cap, so `uploadLimitExceeded` 429 hits with the pool untouched | Throttle upload count against the ~100\u002Fday cap |\n| Overwrite yesterday's wiki snapshot | Destroys the trend the siblings read | Append a new dated entry every pull |\n| Leave the app in \"Testing\" | Token silently dies in 7 days | Publish to \"In production\" |\n","# YouTube API — Transport + Ingestion for a Real Channel\n\n*You own the wire: authenticate to a YouTube channel, upload and edit videos, pull the numbers, and write those numbers into the wiki as a durable feedback log. You do not decide what to make or how to title it — that is the strategy\u002Fpackaging family. Deliver clean transport and a queryable log; let the siblings interpret.*\n\nYouTube has **two separate APIs** and you will touch both:\n\n- **Data API v3** — `https:\u002F\u002Fwww.googleapis.com\u002Fyoutube\u002Fv3` — the *write* side: `videos.insert` (upload), `videos.update` (edit metadata), `thumbnails.set`. Default quota: a shared 10,000 units\u002Fday pool *plus* separate per-day caps of ~100 uploads and ~100 `search.list` calls (see §7).\n- **Analytics API v2** — `https:\u002F\u002Fyoutubeanalytics.googleapis.com\u002Fv2\u002Freports` — the *read* side: views, watch time, retention, traffic sources. Separate scopes, separate quota.\n\nAuth is **user OAuth 2.0, not a service account.** A human owns the channel; you act on their behalf with a refresh token. A service account cannot own a YouTube channel — if you reach for one, stop. (Service-account Google auth for Gmail\u002FDrive\u002FSheets is `google-workspace`, a different model.)\n\nRoute elsewhere when the job is not transport:\n\n| You actually want | Go to |\n| --- | --- |\n| What videos to make \u002F niche \u002F cadence \u002F growth plan | `..\u002Fyoutube-strategy\u002FSKILL.md` |\n| Video ideas, hooks, a topic backlog | `..\u002Fyoutube-ideation\u002FSKILL.md` |\n| Title + thumbnail packaging, CTR copy, A\u002FB framing | `..\u002Fyoutube-packaging\u002FSKILL.md` |\n| The thumbnail image itself | `..\u002Fyoutube-thumbnails\u002FSKILL.md` |\n| Render\u002Fproduce the actual video file in code | `..\u002Fremotion-video\u002FSKILL.md` |\n| Post one asset across many networks at once | `..\u002Fsocial-publisher\u002FSKILL.md` |\n| Wrap an arbitrary REST provider with OAuth + retries | `..\u002Fapi-connector-builder\u002FSKILL.md` |\n| Chain upload → Notion row → Slack across tools | `..\u002Fautomation-flows\u002FSKILL.md` |\n| Service-account auth to Gmail\u002FDrive\u002FSheets | `..\u002Fgoogle-workspace\u002FSKILL.md` |\n| Generic wiki structure and conventions | `..\u002Fknowledge-ops\u002FSKILL.md` |\n\n## 1. One-time setup (do this before any code)\n\nA checklist, because each missing step produces a distinct, confusing error later:\n\n1. Create (or pick) a **GCP project**.\n2. **Enable both APIs** in that project: \"YouTube Data API v3\" *and* \"YouTube Analytics API\". Enabling one is the most common cause of a `403 ... has not been used in project` on the other.\n3. Configure the **OAuth consent screen** and **publish it to \"In production.\"** Why: an app left in \"Testing\" status issues refresh tokens that **expire in 7 days** — your cron silently dies the following week. This is the single most common YouTube-ingestion breakage.\n4. Create an **OAuth client**: *Desktop app* for a personal\u002Flocal script, *Web application* (with an exact redirect URI) for a hosted app.\n5. Request **least-privilege scopes** — not the full management scope.\n\nScope table — request only what the job needs:\n\n| Scope | Grants | Use for |\n| --- | --- | --- |\n| `https:\u002F\u002Fwww.googleapis.com\u002Fauth\u002Fyoutube.upload` | Upload videos | `videos.insert` |\n| `https:\u002F\u002Fwww.googleapis.com\u002Fauth\u002Fyoutube.force-ssl` | Manage\u002Fedit\u002Fdelete | `videos.update`, `thumbnails.set` |\n| `https:\u002F\u002Fwww.googleapis.com\u002Fauth\u002Fyt-analytics.readonly` | Read performance | Analytics reports |\n| `https:\u002F\u002Fwww.googleapis.com\u002Fauth\u002Fyt-analytics-monetary.readonly` | Read revenue metrics | only if you pull `estimatedRevenue` etc. |\n\nBad → Good on scopes:\n\n```text\nBad:  scopes = [\"https:\u002F\u002Fwww.googleapis.com\u002Fauth\u002Fyoutube\"]   # full account control\nGood: scopes = [\"https:\u002F\u002Fwww.googleapis.com\u002Fauth\u002Fyoutube.upload\",\n                \"https:\u002F\u002Fwww.googleapis.com\u002Fauth\u002Fyoutube.force-ssl\",\n                \"https:\u002F\u002Fwww.googleapis.com\u002Fauth\u002Fyt-analytics.readonly\"]\n```\n\nFull GCP + consent-screen walkthrough, Desktop-vs-Web choice, and `unauthorized_client` \u002F `access_denied` \u002F redirect-URI troubleshooting live in `references\u002Foauth-setup.md`.\n\n## 2. Get an authed client and keep the token alive\n\nBuild both service clients from **one** set of OAuth credentials.\n\n```python\n# python: google-api-python-client + google-auth-oauthlib\nfrom google_auth_oauthlib.flow import InstalledAppFlow\nfrom google.auth.transport.requests import Request\nfrom googleapiclient.discovery import build\nimport json, os\nfrom google.oauth2.credentials import Credentials\n\nSCOPES = [\"https:\u002F\u002Fwww.googleapis.com\u002Fauth\u002Fyoutube.upload\",\n          \"https:\u002F\u002Fwww.googleapis.com\u002Fauth\u002Fyoutube.force-ssl\",\n          \"https:\u002F\u002Fwww.googleapis.com\u002Fauth\u002Fyt-analytics.readonly\"]\nTOKEN = \"token.json\"   # gitignored — holds the refresh_token\n\ndef creds():\n    c = Credentials.from_authorized_user_file(TOKEN, SCOPES) if os.path.exists(TOKEN) else None\n    if not c or not c.valid:\n        if c and c.expired and c.refresh_token:\n            c.refresh(Request())               # silent renewal — needs \"In production\" app\n        else:\n            c = InstalledAppFlow.from_client_secrets_file(\n                \"client_secret.json\", SCOPES).run_local_server(port=0)\n        with open(TOKEN, \"w\") as f:\n            f.write(c.to_json())\n    return c\n\nc = creds()\ndata = build(\"youtube\", \"v3\", credentials=c)\nyta  = build(\"youtubeAnalytics\", \"v2\", credentials=c)\n```\n\n```javascript\n\u002F\u002F node: googleapis + google-auth-library\nimport { google } from \"googleapis\";\nimport fs from \"node:fs\";\n\nconst oauth2 = new google.auth.OAuth2(CLIENT_ID, CLIENT_SECRET, REDIRECT_URI);\noauth2.setCredentials(JSON.parse(fs.readFileSync(\"token.json\", \"utf8\"))); \u002F\u002F { refresh_token, ... }\noauth2.on(\"tokens\", (t) => {                 \u002F\u002F persist the refreshed token\n  if (t.refresh_token) fs.writeFileSync(\"token.json\", JSON.stringify(t));\n});\nconst data = google.youtube({ version: \"v3\", auth: oauth2 });\nconst yta  = google.youtubeAnalytics({ version: \"v2\", auth: oauth2 });\n```\n\nRule: persist the **refresh token**, never a bare `access_token`. Access tokens expire in ~1 hour; the credential object refreshes itself. A hardcoded `access_token=...` literal is a guaranteed 401 within the hour — and is exactly what `verify.sh` flags.\n\n## 3. Upload a video (resumable, always)\n\nDecision: any file over a few MB → use the **resumable** protocol. A plain multipart POST drops the whole upload on one network hiccup; resumable survives it.\n\nThe protocol is two steps:\n\n1. **Init the session** — POST to the upload endpoint with `uploadType=resumable` and the metadata body. The response `Location` header is your session URL.\n2. **PUT the bytes** to that session URL — one shot or in chunks. On a dropped connection, query with `Content-Range: bytes *\u002F*`; the server returns the byte offset already received, and you resume from there.\n\nThe client libraries do this for you via a media-upload helper:\n\n```python\nfrom googleapiclient.http import MediaFileUpload\n\nbody = {\n  \"snippet\": {\"title\": \"Ep. 14\", \"description\": \"...\", \"tags\": [\"x\", \"y\"], \"categoryId\": \"27\"},\n  \"status\":  {\"privacyStatus\": \"private\", \"publishAt\": \"2026-06-10T15:00:00Z\",\n              \"selfDeclaredMadeForKids\": False},\n}\nmedia = MediaFileUpload(\"ep14.mp4\", chunksize=8 * 1024 * 1024, resumable=True)\nreq = data.videos().insert(part=\"snippet,status\", body=body, media_body=media)\nresp = None\nwhile resp is None:\n    status, resp = req.next_chunk()          # resumes automatically on a transient drop\nvideo_id = resp[\"id\"]\ndata.thumbnails().set(videoId=video_id, media_body=MediaFileUpload(\"ep14.jpg\")).execute()\n```\n\nThrottle the upload **count**, not the unit spend: `videos.insert` has its own cap of ~100 uploads\u002Fday, so `uploadLimitExceeded` (429) hits while the 10k unit pool still looks untouched. Space automated uploads out and back off on 429 — figures and citation in §7.\n\n## 4. Edit metadata after publish\n\n`videos.update` does **read-modify-write** semantics on whole parts. The trap: any field you omit inside a part you send gets **cleared**.\n\n```python\n# Bad: wipes description and tags because they aren't in the body\ndata.videos().update(part=\"snippet\",\n    body={\"id\": vid, \"snippet\": {\"title\": \"New title\", \"categoryId\": \"27\"}}).execute()\n\n# Good: fetch the current snippet, change one field, send it back whole\ncur = data.videos().list(part=\"snippet\", id=vid).execute()[\"items\"][0][\"snippet\"]\ncur[\"title\"] = \"New title\"\ndata.videos().update(part=\"snippet\", body={\"id\": vid, \"snippet\": cur}).execute()\n```\n\n`categoryId` is required when you send a `snippet` part — another reason to read-modify-write. An update costs **~50 units**.\n\n## 5. Pull performance (Analytics API v2)\n\nEvery report is `GET \u002Fv2\u002Freports?ids=channel==MINE&startDate=&endDate=&metrics=...&dimensions=...&filters=...`. Four recipes cover the loop:\n\n```python\n# (a) Channel KPIs over a date range\nyta.reports().query(ids=\"channel==MINE\", startDate=\"2026-05-01\", endDate=\"2026-05-31\",\n  metrics=\"views,estimatedMinutesWatched,averageViewDuration,averageViewPercentage\"\n).execute()\n\n# (b) Per-video KPIs\nyta.reports().query(ids=\"channel==MINE\", startDate=\"2026-05-01\", endDate=\"2026-05-31\",\n  metrics=\"views,estimatedMinutesWatched,averageViewPercentage\",\n  filters=\"video==VIDEO_ID\").execute()\n\n# (c) Audience-retention curve for one video\nyta.reports().query(ids=\"channel==MINE\", startDate=\"2026-05-01\", endDate=\"2026-05-31\",\n  metrics=\"audienceWatchRatio,relativeRetentionPerformance\",\n  dimensions=\"elapsedVideoTimeRatio\", filters=\"video==VIDEO_ID\").execute()\n\n# (d) Traffic sources\nyta.reports().query(ids=\"channel==MINE\", startDate=\"2026-05-01\", endDate=\"2026-05-31\",\n  metrics=\"views,estimatedMinutesWatched\",\n  dimensions=\"insightTrafficSourceType\").execute()\n```\n\nNotes that save an afternoon:\n\n- `elapsedVideoTimeRatio` runs 0.0–1.0 (playback position); `audienceWatchRatio` is the absolute retention at that point. Plot one against the other to find the drop-off.\n- `insightTrafficSourceType` values include `YT_SEARCH`, `SUGGESTED`, `BROWSE`, `EXT_URL`, `NOTIFICATION`, `PLAYLIST`, `END_SCREEN`, `NO_LINK_EMBEDDED`.\n- **Impressions \u002F CTR** (`impressions`, `impressionClickThroughRate`) are **content-owner-report metrics**, not reliably available on a plain channel query. If the API returns nothing for them, fall back to the value Studio shows — do not block the pull.\n\nFull metric+dimension catalog and copy-paste bodies for geography, device, and subscribed-status reports are in `references\u002Fanalytics-queries.md`.\n\n## 6. Ingest into the wiki — the actual deliverable\n\nA pull that prints to stdout and vanishes is wasted. **Every pull appends a dated entry under `02-DOCS\u002Fwiki\u002Fyoutube\u002F`** so the channel's numbers become queryable history that the strategy\u002Fpackaging siblings can read.\n\n```text\n02-DOCS\u002Fwiki\u002Fyoutube\u002F\n  index.md                  # rolling pointer to latest snapshot + open questions\n  channel-2026-05-31.md     # dated channel snapshot (one per pull)\n  videos\u002F\u003CVIDEO_ID>.md      # per-video running log, newest entry on top\n```\n\nPer-pull entry template (OKF v0.1: non-empty `type` + the domain keys siblings parse):\n\n```markdown\n---\ntype: youtube-metrics\ntitle: Channel snapshot 2026-05-31\ndescription: Channel KPIs, traffic and retention for 2026-05-01..2026-05-31.\ntags: [youtube, channel-snapshot]\ntimestamp: 2026-05-31T00:00:00Z\ndate: 2026-05-31\nrange: 2026-05-01..2026-05-31\nchannel: MINE\nsource: youtube-analytics-api-v2\n---\n## KPIs\nviews: 41,233 | watch_min: 88,140 | avg_view_pct: 38.2% | avg_view_dur: 0:04:11\n\n## Traffic (top 3)\nBROWSE 44% · SUGGESTED 31% · YT_SEARCH 12%\n\n## Retention\nSharp drop 0.00→0.06 (intro), recovers, second dip ~0.55.\n\n## What changed since last pull\navg_view_pct +2.1pts; SUGGESTED share up 6pts after the Ep.13 packaging change.\n```\n\nRule: **append, never overwrite.** The feedback log *is* the value — overwriting yesterday's snapshot destroys the trend the siblings need. `02-DOCS\u002Fwiki\u002F` is an OKF v0.1 bundle: keep the domain keys (`date`, `range`, `channel`, `source`) the siblings parse, add `type`\u002F`timestamp` alongside them, use standard markdown links (never `[[wikilinks]]`), and leave the reserved `index.md` frontmatter-free. Exact file tree, naming, per-video log shape, and how siblings read the log: `references\u002Fwiki-schema.md`.\n\n## 7. Quota & failure math\n\n| Call | Cost \u002F allocation |\n| --- | --- |\n| `videos.insert` (upload) | own daily cap: **~100 uploads\u002Fday**, not 10k-pool units |\n| `search.list` | own daily cap: ~100 calls\u002Fday |\n| write: `videos.update`, `thumbnails.set` | ~50 units (from the 10k pool) |\n| `*.list` read | 1–5 units (from the 10k pool) |\n| Analytics `reports.query` | (separate Analytics quota) |\n\nPer the official docs (Last updated 2026-06-01 UTC, `https:\u002F\u002Fdevelopers.google.com\u002Fyoutube\u002Fv3\u002Fgetting-started`; per-method costs at `https:\u002F\u002Fdevelopers.google.com\u002Fyoutube\u002Fv3\u002Fdetermine_quota_cost`), a project's default allocation is *\"100 search.list calls, 100 videos.insert calls, and 10,000 units per day combined for all other endpoints.\"* All quotas reset at midnight Pacific. This is a change from the older single-pool model where `videos.insert` cost ~1,600 units — confirm the live figure on the quota-cost page before relying on it, since Google notes the allocation \"is subject to change.\"\n\nOn `403 quotaExceeded` \u002F `rateLimitExceeded` or `429`: **exponential backoff with jitter**, then stop for the day on a hard quota cap — retrying a daily-quota 403 in a tight loop just burns the next day too.\n\nError → cause map:\n\n| Symptom | Cause | Fix |\n| --- | --- | --- |\n| Refresh token dies after ~7 days | App still in \"Testing\" | Publish consent screen to \"In production\" |\n| `unauthorized_client` | Consent\u002Fclient misconfig or wrong client type | Re-check OAuth client + authorized scopes |\n| `403 insufficient permissions` | Missing scope | Add the right scope, re-consent |\n| `uploadLimitExceeded` (429) | Hit the ~100 `videos.insert`\u002Fday cap (separate from the 10k unit pool) | Throttle upload count, back off |\n| Empty `impressions`\u002FCTR | Not a content-owner channel query | Read it from Studio |\n| `403 ... API has not been used` | Other API not enabled | Enable both Data v3 and Analytics v2 |\n\n## Anti-patterns\n\n| Anti-pattern | Why it bites | Do instead |\n| --- | --- | --- |\n| Commit `client_secret.json` \u002F `token.json` with `refresh_token` | Leaks full channel control to anyone with repo read | Gitignore both; load from env\u002Fsecret store |\n| Request full `auth\u002Fyoutube` scope | Grants total account control; fails review | Least set: `youtube.upload` + `youtube.force-ssl` + `yt-analytics.readonly` |\n| Hardcode an `access_token` | Dead in ~1 hour | Persist the refresh token; use a refreshable credential |\n| `videos.update` with a partial part | Omitted fields get wiped | Read-modify-write the whole part |\n| Plain multipart upload for a big file | One drop kills the whole upload | Resumable protocol with chunked PUT |\n| Treat the 10k unit pool as the upload budget | Uploads use a separate ~100\u002Fday call cap, so `uploadLimitExceeded` 429 hits with the pool untouched | Throttle upload count against the ~100\u002Fday cap |\n| Overwrite yesterday's wiki snapshot | Destroys the trend the siblings read | Append a new dated entry every pull |\n| Leave the app in \"Testing\" | Token silently dies in 7 days | Publish to \"In production\" |\n",{"name":5,"tags":24,"origin":33,"recommends":34,"description":7},[25,26,27,28,29,30,31,32],"youtube","youtube-data-api","youtube-analytics-api","oauth2","resumable-upload","video-metadata","audience-retention","channel-feedback-log","risco",[35,36,37,38],"social-publisher","api-connector-builder","automation-flows","knowledge-ops","main","d69096e239f2a89aabc2cd078c47664a9d3b1e11","04-安全渗透\u002Fyoutube-api",3,"https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts","https:\u002F\u002Fgithub.com\u002Flza6","个人vx：Tf00798\r\n个人✈：@TFGY999","2026-10-08 14:29:22",{"source":8,"skillName":5,"commands":48,"prompt":58,"zipAvailable":59},[49,52,55],{"tool":50,"command":51},"npx","npx skills add lza6\u002FArmor-piercing-system-prompts --skill youtube-api",{"tool":53,"command":54},"bunx","bunx skills add lza6\u002FArmor-piercing-system-prompts --skill youtube-api",{"tool":56,"command":57},"pnpm","pnpm dlx skills add lza6\u002FArmor-piercing-system-prompts --skill youtube-api","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F04-安全渗透\u002Fyoutube-api\u002FSKILL.md",true,[61,67,71,75,79],{"path":62,"resourceType":63,"resourceTypeDesc":64,"sizeBytes":65,"sourceHtmlUrl":66},"evals\u002Fcases.yaml","REFERENCE","参考文档",3739,"https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F04-安全渗透\u002Fyoutube-api\u002Fevals\u002Fcases.yaml",{"path":68,"resourceType":63,"resourceTypeDesc":64,"sizeBytes":69,"sourceHtmlUrl":70},"evals\u002FREADME.md",894,"https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F04-安全渗透\u002Fyoutube-api\u002Fevals\u002FREADME.md",{"path":72,"resourceType":63,"resourceTypeDesc":64,"sizeBytes":73,"sourceHtmlUrl":74},"references\u002Fanalytics-queries.md",4115,"https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F04-安全渗透\u002Fyoutube-api\u002Freferences\u002Fanalytics-queries.md",{"path":76,"resourceType":63,"resourceTypeDesc":64,"sizeBytes":77,"sourceHtmlUrl":78},"references\u002Foauth-setup.md",3811,"https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F04-安全渗透\u002Fyoutube-api\u002Freferences\u002Foauth-setup.md",{"path":80,"resourceType":63,"resourceTypeDesc":64,"sizeBytes":81,"sourceHtmlUrl":82},"references\u002Fwiki-schema.md",4989,"https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F04-安全渗透\u002Fyoutube-api\u002Freferences\u002Fwiki-schema.md",[84,92,97,104,111,118],{"skillNo":85,"name":86,"nameZh":6,"description":87,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":88,"categories":89,"keywords":90,"publishedAt":91},"01M7FFG485KY83TD6HSC4YPCMC","obsidian-clipper-template-creator","Guide for creating templates for the Obsidian Web Clipper. Use when you want to create a new clipping template, understand available variables, or format clipped content.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobsidian-clipper-template-creator\u002FSKILL.md",[],[],"2026-11-16 10:05:34",{"skillNo":93,"name":86,"nameZh":6,"description":87,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":94,"categories":95,"keywords":96,"publishedAt":91},"01M7FFG0T6AZ0STEJPSB3CX84K","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobsidian-clipper-template-creator-antigravity-awesome-skills-main\u002FSKILL.md",[],[],{"skillNo":98,"name":99,"nameZh":6,"description":100,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":101,"categories":102,"keywords":103,"publishedAt":91},"01M7FFFY0QEM14SKWPDYGMXM2P","python-api","Programmatic Object-Detection-Metrics API guidance for BoundingBox, BoundingBoxes, Evaluator, enums, coordinate conversion, AP\u002FmAP semantics, and source-style import diagnostics.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobject-detection-metrics\u002Fsub-skills\u002Fpython-api\u002FSKILL.md",[],[],{"skillNo":105,"name":106,"nameZh":6,"description":107,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":108,"categories":109,"keywords":110,"publishedAt":91},"01M7FFFVZQZ2GJ0C0TGP7JHD20","file-evaluation","Folder-based PASCAL VOC AP\u002FmAP evaluation from ground-truth and detection text files.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobject-detection-metrics\u002Fsub-skills\u002Ffile-evaluation\u002FSKILL.md",[],[],{"skillNo":112,"name":113,"nameZh":6,"description":114,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":115,"categories":116,"keywords":117,"publishedAt":91},"01M7FFFSFNYSE77SJ6PE1CK2DA","object-detection-metrics","Guides legacy Object-Detection-Metrics PASCAL VOC AP\u002FmAP evaluation from detection text folders and direct Python API classes.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobject-detection-metrics\u002FSKILL.md",[],[],{"skillNo":119,"name":120,"nameZh":6,"description":121,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":122,"categories":123,"keywords":124,"publishedAt":91},"01M7FFFP0GCK1RVXBCPQ8APBMT","nx-workspace-patterns","Configure and optimize Nx monorepo workspaces. Use when setting up Nx, configuring project boundaries, optimizing build caching, or implementing affected commands.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fnx-workspace-patterns\u002FSKILL.md",[],[]]