ytstudio-cli 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
ytstudio/__init__.py ADDED
File without changes
ytstudio/api.py ADDED
@@ -0,0 +1,174 @@
1
+ import typer
2
+ from google.auth.exceptions import RefreshError
3
+ from google.auth.transport.requests import Request
4
+ from google.oauth2.credentials import Credentials
5
+ from google_auth_oauthlib.flow import InstalledAppFlow
6
+ from googleapiclient.discovery import build
7
+ from googleapiclient.errors import HttpError
8
+
9
+ from ytstudio.config import (
10
+ CLIENT_SECRETS_FILE,
11
+ clear_credentials,
12
+ load_credentials,
13
+ save_credentials,
14
+ )
15
+ from ytstudio.ui import console, success_message
16
+
17
+
18
+ def handle_api_error(error: HttpError) -> None:
19
+ if error.resp.status == 403:
20
+ error_details = error.error_details[0] if error.error_details else {}
21
+ reason = error_details.get("reason", "")
22
+
23
+ if reason == "quotaExceeded":
24
+ console.print(
25
+ "[red]Daily YouTube API quota exceeded.[/red] "
26
+ "Quota resets at midnight Pacific Time (PT).\n"
27
+ "See: https://developers.google.com/youtube/v3/guides/quota_and_compliance_audits"
28
+ )
29
+ raise SystemExit(1) from None
30
+
31
+ if reason == "forbidden":
32
+ console.print("[red]Access denied. You may not have permission for this action.[/red]")
33
+ raise SystemExit(1) from None
34
+
35
+ # Re-raise for other errors
36
+ raise error
37
+
38
+
39
+ def api(request):
40
+ """Execute an API request with automatic error handling.
41
+
42
+ Usage:
43
+ response = api(service.videos().list(part="snippet", id=video_id))
44
+ """
45
+ try:
46
+ return request.execute()
47
+ except HttpError as e:
48
+ handle_api_error(e)
49
+ except RefreshError:
50
+ console.print(
51
+ "[red]Session expired or revoked.[/red] Run [bold]ytstudio login[/bold] to re-authenticate."
52
+ )
53
+ raise SystemExit(1) from None
54
+
55
+
56
+ # YouTube API scopes
57
+ SCOPES = [
58
+ "https://www.googleapis.com/auth/youtube.readonly",
59
+ "https://www.googleapis.com/auth/youtube.force-ssl",
60
+ "https://www.googleapis.com/auth/yt-analytics.readonly",
61
+ ]
62
+
63
+
64
+ def authenticate() -> None:
65
+ if not CLIENT_SECRETS_FILE.exists():
66
+ console.print("[red]No client secrets found. Run 'ytstudio init' first.[/red]")
67
+ raise SystemExit(1) from None
68
+
69
+ console.print("[bold]Authenticating with YouTube...[/bold]\n")
70
+
71
+ flow = InstalledAppFlow.from_client_secrets_file(
72
+ str(CLIENT_SECRETS_FILE),
73
+ scopes=SCOPES,
74
+ )
75
+
76
+ # Run local server for OAuth callback
77
+ credentials = flow.run_local_server(
78
+ port=9876,
79
+ prompt="consent",
80
+ open_browser=True,
81
+ )
82
+
83
+ # Save credentials
84
+ creds_data = {
85
+ "token": credentials.token,
86
+ "refresh_token": credentials.refresh_token,
87
+ "token_uri": credentials.token_uri,
88
+ "client_id": credentials.client_id,
89
+ "client_secret": credentials.client_secret,
90
+ "scopes": credentials.scopes,
91
+ }
92
+ save_credentials(creds_data)
93
+
94
+ # Get channel info
95
+ service = build("youtube", "v3", credentials=credentials)
96
+ response = service.channels().list(part="snippet", mine=True).execute()
97
+
98
+ console.print()
99
+ if response.get("items"):
100
+ channel = response["items"][0]["snippet"]
101
+ success_message(f"Logged in as: {channel['title']}")
102
+ else:
103
+ success_message("Authentication successful")
104
+
105
+
106
+ def get_credentials() -> Credentials | None:
107
+ creds_data = load_credentials()
108
+ if not creds_data:
109
+ return None
110
+
111
+ credentials = Credentials(
112
+ token=creds_data.get("token"),
113
+ refresh_token=creds_data.get("refresh_token"),
114
+ token_uri=creds_data.get("token_uri"),
115
+ client_id=creds_data.get("client_id"),
116
+ client_secret=creds_data.get("client_secret"),
117
+ scopes=creds_data.get("scopes"),
118
+ )
119
+
120
+ if credentials.expired and credentials.refresh_token:
121
+ try:
122
+ credentials.refresh(Request())
123
+ except RefreshError:
124
+ console.print(
125
+ "[red]Session expired or revoked.[/red] Run [bold]ytstudio login[/bold] to re-authenticate."
126
+ )
127
+ raise SystemExit(1) from None
128
+ # Save refreshed credentials
129
+ creds_data["token"] = credentials.token
130
+ save_credentials(creds_data)
131
+
132
+ return credentials
133
+
134
+
135
+ def get_authenticated_service(api_name: str = "youtube", version: str = "v3"):
136
+ credentials = get_credentials()
137
+ if not credentials:
138
+ console.print("[red]Not authenticated. Run 'ytstudio login' first.[/red]")
139
+ raise typer.Exit(1)
140
+ return build(api_name, version, credentials=credentials)
141
+
142
+
143
+ def get_status() -> None:
144
+ creds_data = load_credentials()
145
+
146
+ if not creds_data:
147
+ console.print("[yellow]Not authenticated. Run 'ytstudio login' to authenticate.[/yellow]")
148
+ return
149
+
150
+ credentials = get_credentials()
151
+ if not credentials or not credentials.valid:
152
+ console.print(
153
+ "[yellow]Credentials expired. Run 'ytstudio login' to re-authenticate.[/yellow]"
154
+ )
155
+ return
156
+
157
+ # Get channel info
158
+ service = build("youtube", "v3", credentials=credentials)
159
+ response = api(service.channels().list(part="snippet,statistics", mine=True))
160
+
161
+ if response.get("items"):
162
+ channel = response["items"][0]
163
+ snippet = channel["snippet"]
164
+ stats = channel["statistics"]
165
+
166
+ success_message("Authenticated")
167
+ console.print(f" Channel: [bold]{snippet['title']}[/bold]")
168
+ console.print(f" Subscribers: {stats.get('subscriberCount', 'N/A')}")
169
+ console.print(f" Videos: {stats.get('videoCount', 'N/A')}")
170
+
171
+
172
+ def logout() -> None:
173
+ clear_credentials()
174
+ success_message("Logged out successfully")
File without changes