feat: 이번주 코디 영상 스크립트·템플릿·모델 사진과 명령 파일 추가, 클립 동작은 후보에서 무작위로 고름 (손가락 모양 동작 제외), .sh·.py·.mjs 는 LF 로 받음
This commit is contained in:
1 parent
1ec87a82c1
commit
56f71cdfbe
54 files changed
+1576
No files matched your search
Executable
+140
@@ -0,0 +1,140 @@
|
||||
"""YouTube Shorts 업로드. 표준 라이브러리만 쓴다 (OAuth 데스크톱 앱 + resumable upload).
|
||||
|
||||
usage:
|
||||
python3 youtube.py auth # 채널 계정으로 한 번 로그인해 refresh token을 저장
|
||||
python3 youtube.py upload video.mp4 meta.json # meta: {title, description, tags[], privacy}
|
||||
비밀 파일은 저장소 밖 ~/.config/nalssigak/ 에 둔다 (client_secret.json, youtube_token.json).
|
||||
감사를 통과해 공개로 올릴 수 있게 되면 ~/.config/nalssigak/youtube_public 파일을 만든다(스킬이 privacy 를 public 으로 쓴다).
|
||||
"""
|
||||
import base64
|
||||
import hashlib
|
||||
import http.server
|
||||
import json
|
||||
import os
|
||||
import secrets
|
||||
import socket
|
||||
import sys
|
||||
import threading
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
import webbrowser
|
||||
from pathlib import Path
|
||||
|
||||
CONFIG = Path(os.environ.get("NALSSIGAK_CONFIG", Path.home() / ".config" / "nalssigak"))
|
||||
CLIENT = CONFIG / "client_secret.json"
|
||||
TOKEN = CONFIG / "youtube_token.json"
|
||||
SCOPE = "https://www.googleapis.com/auth/youtube.upload"
|
||||
TOKEN_URL = "https://oauth2.googleapis.com/token"
|
||||
|
||||
|
||||
def client():
|
||||
data = json.loads(CLIENT.read_text(encoding="utf-8"))
|
||||
return data.get("installed") or data["web"]
|
||||
|
||||
|
||||
def post_form(url, fields):
|
||||
body = urllib.parse.urlencode(fields).encode()
|
||||
request = urllib.request.Request(url, data=body, headers={"Content-Type": "application/x-www-form-urlencoded"})
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=30) as response:
|
||||
return json.loads(response.read())
|
||||
except urllib.error.HTTPError as error:
|
||||
sys.exit(f"토큰 요청 실패 {error.code}: {error.read()[:300].decode(errors='replace')}")
|
||||
|
||||
|
||||
def auth():
|
||||
c = client()
|
||||
verifier = secrets.token_urlsafe(64)
|
||||
challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).rstrip(b"=").decode()
|
||||
state = secrets.token_urlsafe(16)
|
||||
with socket.socket() as sock:
|
||||
sock.bind(("127.0.0.1", 0))
|
||||
port = sock.getsockname()[1]
|
||||
redirect = f"http://127.0.0.1:{port}"
|
||||
result = {}
|
||||
|
||||
class Handler(http.server.BaseHTTPRequestHandler):
|
||||
def do_GET(self):
|
||||
query = urllib.parse.parse_qs(urllib.parse.urlparse(self.path).query)
|
||||
if query.get("state", [""])[0] == state:
|
||||
result.update({k: v[0] for k, v in query.items()})
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/html; charset=utf-8")
|
||||
self.end_headers()
|
||||
self.wfile.write("로그인 완료. 이 창은 닫아도 돼요.".encode())
|
||||
|
||||
def log_message(self, *_):
|
||||
pass
|
||||
|
||||
server = http.server.HTTPServer(("127.0.0.1", port), Handler)
|
||||
url = c["auth_uri"] + "?" + urllib.parse.urlencode({
|
||||
"client_id": c["client_id"], "redirect_uri": redirect, "response_type": "code", "scope": SCOPE,
|
||||
"access_type": "offline", "prompt": "consent", "state": state,
|
||||
"code_challenge": challenge, "code_challenge_method": "S256"})
|
||||
print("브라우저에서 채널 계정으로 로그인하세요:\n" + url, flush=True)
|
||||
webbrowser.open(url)
|
||||
thread = threading.Thread(target=server.handle_request)
|
||||
thread.start()
|
||||
thread.join(timeout=600)
|
||||
server.server_close()
|
||||
if "code" not in result:
|
||||
sys.exit(f"로그인이 끝나지 않았어요: {result.get('error', '시간 초과')}")
|
||||
token = post_form(c["token_uri"], {"client_id": c["client_id"], "client_secret": c["client_secret"], "code": result["code"],
|
||||
"code_verifier": verifier, "grant_type": "authorization_code", "redirect_uri": redirect})
|
||||
if "refresh_token" not in token:
|
||||
sys.exit("refresh token을 받지 못했어요. 다시 auth를 실행하세요.")
|
||||
CONFIG.mkdir(parents=True, exist_ok=True)
|
||||
TOKEN.write_text(json.dumps({"refresh_token": token["refresh_token"], "scope": token.get("scope")}), encoding="utf-8")
|
||||
TOKEN.chmod(0o600)
|
||||
print("저장했어요:", TOKEN)
|
||||
|
||||
|
||||
def access_token():
|
||||
if not TOKEN.is_file():
|
||||
sys.exit("먼저 python3 youtube.py auth 로 로그인하세요.")
|
||||
c = client()
|
||||
refresh = json.loads(TOKEN.read_text(encoding="utf-8"))["refresh_token"]
|
||||
return post_form(TOKEN_URL, {"client_id": c["client_id"], "client_secret": c["client_secret"],
|
||||
"refresh_token": refresh, "grant_type": "refresh_token"})["access_token"]
|
||||
|
||||
|
||||
def upload(video_path, meta_path):
|
||||
meta = json.loads(Path(meta_path).read_text(encoding="utf-8"))
|
||||
video = Path(video_path).read_bytes()
|
||||
body = {
|
||||
"snippet": {"title": meta["title"], "description": meta["description"], "tags": meta.get("tags", []),
|
||||
"categoryId": meta.get("category", "26"), "defaultLanguage": "ko", "defaultAudioLanguage": "ko"},
|
||||
"status": {"privacyStatus": meta.get("privacy", "private"), "selfDeclaredMadeForKids": False,
|
||||
"containsSyntheticMedia": True},
|
||||
}
|
||||
token = access_token()
|
||||
start = urllib.request.Request(
|
||||
"https://www.googleapis.com/upload/youtube/v3/videos?uploadType=resumable&part=snippet,status",
|
||||
data=json.dumps(body).encode(), method="POST",
|
||||
headers={"Authorization": f"Bearer {token}", "Content-Type": "application/json; charset=UTF-8",
|
||||
"X-Upload-Content-Type": "video/mp4", "X-Upload-Content-Length": str(len(video))})
|
||||
try:
|
||||
with urllib.request.urlopen(start, timeout=60) as response:
|
||||
location = response.headers["Location"]
|
||||
put = urllib.request.Request(location, data=video, method="PUT",
|
||||
headers={"Authorization": f"Bearer {token}", "Content-Type": "video/mp4"})
|
||||
with urllib.request.urlopen(put, timeout=600) as response:
|
||||
result = json.loads(response.read())
|
||||
except urllib.error.HTTPError as error:
|
||||
sys.exit(f"업로드 실패 {error.code}: {error.read()[:600].decode(errors='replace')}")
|
||||
asked, got = body["status"]["privacyStatus"], result["status"]["privacyStatus"]
|
||||
print(json.dumps({"id": result["id"], "privacy": got, "url": f"https://youtube.com/shorts/{result['id']}",
|
||||
"studio": f"https://studio.youtube.com/video/{result['id']}/edit"}, ensure_ascii=False))
|
||||
if asked != got:
|
||||
# 감사 전 API 프로젝트는 공개 요청도 비공개로 바뀐다
|
||||
print(f"경고: {asked} 로 요청했지만 {got} 로 올라갔어요. API 감사가 필요해요.", file=sys.stderr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
if len(sys.argv) >= 2 and sys.argv[1] == "auth":
|
||||
auth()
|
||||
elif len(sys.argv) == 4 and sys.argv[1] == "upload":
|
||||
upload(sys.argv[2], sys.argv[3])
|
||||
else:
|
||||
sys.exit(__doc__)
|
||||
Reference in new issue
Block a user