diff --git a/twitter_cli/cli.py b/twitter_cli/cli.py index d2dc523..4ee59f1 100644 --- a/twitter_cli/cli.py +++ b/twitter_cli/cli.py @@ -1120,19 +1120,31 @@ def following(screen_name, max_count, as_json, as_yaml): # ── Write commands ────────────────────────────────────────────────────── _MAX_IMAGES = 4 # Twitter allows up to 4 images per tweet +_MAX_VIDEOS = 1 # X allows 1 video per tweet (or up to 4 images, not both) -def _upload_images(client, image_paths, rich_output=True): - # type: (TwitterClient, tuple, bool) -> list - """Upload images and return list of media_id strings.""" - if not image_paths: - return [] +def _upload_images(client, image_paths, video_paths=None, rich_output=True): + # type: (TwitterClient, tuple, Optional[tuple], bool) -> list + """Upload images and/or a video and return list of media_id strings.""" + image_paths = tuple(image_paths or ()) + video_paths = tuple(video_paths or ()) if len(image_paths) > _MAX_IMAGES: raise click.UsageError("Too many images: max %d, got %d" % (_MAX_IMAGES, len(image_paths))) + if len(video_paths) > _MAX_VIDEOS: + raise click.UsageError( + "Too many videos: max %d, got %d (X allows 1 video per tweet)" % (_MAX_VIDEOS, len(video_paths)) + ) + if image_paths and video_paths: + raise click.UsageError("Attach images OR a video, not both (X allows one media type per tweet)") media_ids = [] + total = len(image_paths) + len(video_paths) for i, path in enumerate(image_paths, 1): if rich_output: - console.print("📤 Uploading image %d/%d: %s" % (i, len(image_paths), path)) + console.print("📤 Uploading image %d/%d: %s" % (i, total, path)) + media_ids.append(client.upload_media(path)) + for i, path in enumerate(video_paths, 1): + if rich_output: + console.print("🎥 Uploading video %d/%d: %s" % (i, total, path)) media_ids.append(client.upload_media(path)) return media_ids @@ -1163,23 +1175,25 @@ def operation(client: TwitterClient) -> WritePayload: @click.argument("text") @click.option("--reply-to", "-r", default=None, help="Reply to this tweet ID.") @click.option("--image", "-i", "images", multiple=True, type=click.Path(exists=True), help="Attach image (up to 4). Repeatable.") +@click.option("--video", "-V", "videos", multiple=True, type=click.Path(exists=True), help="Attach video (max 1; free accounts: mp4 ≤ 2:20). Repeatable but capped.") @structured_output_options -def post(text, reply_to, images, as_json, as_yaml): - # type: (str, Optional[str], tuple, bool, bool) -> None +def post(text, reply_to, images, videos, as_json, as_yaml): + # type: (str, Optional[str], tuple, tuple, bool, bool) -> None """Post a new tweet. TEXT is the tweet content. - Attach images with --image / -i (up to 4): + Attach images with --image / -i (up to 4), or one video with --video / -V: \b twitter post "Hello!" --image photo.jpg twitter post "Gallery" -i a.png -i b.png -i c.jpg + twitter post "Clip:" --video clip.mp4 """ normalized_reply_to = _normalize_tweet_id(reply_to) if reply_to else None action = "Replying to %s" % normalized_reply_to if normalized_reply_to else "Posting tweet" rich_output = not _structured_mode(as_json=as_json, as_yaml=as_yaml) def operation(client: TwitterClient) -> WritePayload: - media_ids = _upload_images(client, images, rich_output=rich_output) + media_ids = _upload_images(client, images, video_paths=videos, rich_output=rich_output) tweet_id = client.create_tweet(text, reply_to_id=normalized_reply_to, media_ids=media_ids or None) return {"success": True, "action": "post", "id": tweet_id, "url": "https://x.com/i/status/%s" % tweet_id} @@ -1199,14 +1213,15 @@ def operation(client: TwitterClient) -> WritePayload: @click.argument("tweet_id") @click.argument("text") @click.option("--image", "-i", "images", multiple=True, type=click.Path(exists=True), help="Attach image (up to 4). Repeatable.") +@click.option("--video", "-V", "videos", multiple=True, type=click.Path(exists=True), help="Attach video (max 1; free accounts: mp4 ≤ 2:20). Repeatable but capped.") @structured_output_options -def reply_tweet(tweet_id, text, images, as_json, as_yaml): - # type: (str, str, tuple, bool, bool) -> None +def reply_tweet(tweet_id, text, images, videos, as_json, as_yaml): + # type: (str, str, tuple, tuple, bool, bool) -> None """Reply to a tweet. TWEET_ID is the tweet to reply to, TEXT is the reply content.""" tweet_id = _normalize_tweet_id(tweet_id) rich_output = not _structured_mode(as_json=as_json, as_yaml=as_yaml) def operation(client: TwitterClient) -> WritePayload: - media_ids = _upload_images(client, images, rich_output=rich_output) + media_ids = _upload_images(client, images, video_paths=videos, rich_output=rich_output) new_id = client.create_tweet(text, reply_to_id=tweet_id, media_ids=media_ids or None) return { "success": True, @@ -1232,14 +1247,15 @@ def operation(client: TwitterClient) -> WritePayload: @click.argument("tweet_id") @click.argument("text") @click.option("--image", "-i", "images", multiple=True, type=click.Path(exists=True), help="Attach image (up to 4). Repeatable.") +@click.option("--video", "-V", "videos", multiple=True, type=click.Path(exists=True), help="Attach video (max 1; free accounts: mp4 ≤ 2:20). Repeatable but capped.") @structured_output_options -def quote_tweet(tweet_id, text, images, as_json, as_yaml): - # type: (str, str, tuple, bool, bool) -> None +def quote_tweet(tweet_id, text, images, videos, as_json, as_yaml): + # type: (str, str, tuple, tuple, bool, bool) -> None """Quote-tweet a tweet. TWEET_ID is the tweet to quote, TEXT is the commentary.""" tweet_id = _normalize_tweet_id(tweet_id) rich_output = not _structured_mode(as_json=as_json, as_yaml=as_yaml) def operation(client: TwitterClient) -> WritePayload: - media_ids = _upload_images(client, images, rich_output=rich_output) + media_ids = _upload_images(client, images, video_paths=videos, rich_output=rich_output) new_id = client.quote_tweet(tweet_id, text, media_ids=media_ids or None) return { "success": True, diff --git a/twitter_cli/client.py b/twitter_cli/client.py index 0436c8e..1cbf256 100644 --- a/twitter_cli/client.py +++ b/twitter_cli/client.py @@ -473,6 +473,9 @@ def fetch_following(self, user_id, count=20): # Supported image MIME types and max file size (5 MB) _SUPPORTED_IMAGE_TYPES = {"image/jpeg", "image/png", "image/gif", "image/webp"} _MAX_IMAGE_SIZE = 5 * 1024 * 1024 # 5 MB + _MAX_VIDEO_SIZE = 512 * 1024 * 1024 # 512 MB (X hard cap for tweet_video) + _VIDEO_CHUNK_SIZE = 4 * 1024 * 1024 # 4 MB per APPEND segment + _VIDEO_PROCESS_TIMEOUT = 300 # seconds to wait for async video processing def _write_delay(self): # type: () -> None @@ -483,26 +486,40 @@ def _write_delay(self): def upload_media(self, file_path): # type: (str) -> str - """Upload an image file to Twitter. Returns the media_id string. + """Upload an image or video file to Twitter. Returns the media_id string. Uses Twitter's chunked upload API (INIT → APPEND → FINALIZE). - Supports JPEG, PNG, GIF, and WebP images up to 5 MB. + Images: JPEG, PNG, GIF, WebP up to 5 MB (single APPEND segment). + Videos (mp4/mov/webm): up to 512 MB, uploaded in 4 MB APPEND chunks, + then STATUS-polled until async processing succeeds. Note: X itself + rejects videos longer than 2:20 on non-Premium accounts — that + duration error surfaces at CreateTweet, not here. """ if not os.path.isfile(file_path): raise MediaUploadError("File not found: %s" % file_path) file_size = os.path.getsize(file_path) - if file_size > self._MAX_IMAGE_SIZE: - raise MediaUploadError( - "File too large: %.1f MB (max %.0f MB)" - % (file_size / (1024 * 1024), self._MAX_IMAGE_SIZE / (1024 * 1024)) - ) - media_type = mimetypes.guess_type(file_path)[0] or "" - if media_type not in self._SUPPORTED_IMAGE_TYPES: - raise MediaUploadError( - "Unsupported image format: %s (supported: jpeg, png, gif, webp)" % media_type - ) + is_video = media_type.startswith("video/") + + if is_video: + if file_size > self._MAX_VIDEO_SIZE: + raise MediaUploadError( + "File too large: %.1f MB (max %.0f MB)" + % (file_size / (1024 * 1024), self._MAX_VIDEO_SIZE / (1024 * 1024)) + ) + media_category = "tweet_video" + else: + if file_size > self._MAX_IMAGE_SIZE: + raise MediaUploadError( + "File too large: %.1f MB (max %.0f MB)" + % (file_size / (1024 * 1024), self._MAX_IMAGE_SIZE / (1024 * 1024)) + ) + if media_type not in self._SUPPORTED_IMAGE_TYPES: + raise MediaUploadError( + "Unsupported image format: %s (supported: jpeg, png, gif, webp)" % media_type + ) + media_category = "tweet_image" upload_url = "https://upload.twitter.com/i/media/upload.json" session = _get_cffi_session() @@ -514,6 +531,7 @@ def upload_media(self, file_path): "command": "INIT", "total_bytes": str(file_size), "media_type": media_type, + "media_category": media_category, } resp = session.post(upload_url, headers=headers, data=init_data, timeout=30) if resp.status_code >= 400: @@ -525,25 +543,39 @@ def upload_media(self, file_path): media_id = init_result.get("media_id_string", "") if not media_id: raise MediaUploadError("INIT did not return media_id") - logger.info("Media INIT: media_id=%s", media_id) + logger.info("Media INIT: media_id=%s category=%s", media_id, media_category) # ── APPEND ─────────────────────────────────────────────────── + segment_index = 0 with open(file_path, "rb") as f: - media_data = base64.b64encode(f.read()).decode("ascii") - - headers = self._build_headers(url=upload_url, method="POST") - # Remove JSON content-type — curl_cffi handles multipart encoding - headers.pop("Content-Type", None) - append_data = { - "command": "APPEND", - "media_id": media_id, - "segment_index": "0", - "media_data": media_data, - } - resp = session.post(upload_url, headers=headers, data=append_data, timeout=60) - if resp.status_code >= 400: - raise MediaUploadError("APPEND failed (HTTP %d): %s" % (resp.status_code, resp.text[:300])) - logger.info("Media APPEND: segment 0 uploaded") + while True: + media_bytes = f.read(self._VIDEO_CHUNK_SIZE if is_video else None) + if not media_bytes: + if segment_index == 0 and not is_video: + media_bytes = b"" + else: + break + media_data = base64.b64encode(media_bytes).decode("ascii") + headers = self._build_headers(url=upload_url, method="POST") + # Remove JSON content-type — curl_cffi handles multipart encoding + headers.pop("Content-Type", None) + append_data = { + "command": "APPEND", + "media_id": media_id, + "segment_index": str(segment_index), + "media_data": media_data, + } + resp = session.post(upload_url, headers=headers, data=append_data, + timeout=300 if is_video else 60) + if resp.status_code >= 400: + raise MediaUploadError( + "APPEND segment %d failed (HTTP %d): %s" + % (segment_index, resp.status_code, resp.text[:300]) + ) + logger.info("Media APPEND: segment %d uploaded", segment_index) + segment_index += 1 + if not is_video: + break # ── FINALIZE ───────────────────────────────────────────────── headers = self._build_headers(url=upload_url, method="POST") @@ -557,6 +589,31 @@ def upload_media(self, file_path): raise MediaUploadError("FINALIZE failed (HTTP %d): %s" % (resp.status_code, resp.text[:300])) logger.info("Media FINALIZE: media_id=%s ready", media_id) + # ── STATUS (videos only) ───────────────────────────────────── + if is_video: + info = json.loads(resp.text).get("processing_info") + deadline = time.time() + self._VIDEO_PROCESS_TIMEOUT + while info and info.get("state") not in (None, "succeeded"): + state = info.get("state") + if state == "failed": + raise MediaUploadError( + "Video processing failed: %s" % json.dumps(info.get("error", info)) + ) + wait = int(info.get("check_after_secs", 3)) + time.sleep(wait) + if time.time() > deadline: + raise MediaUploadError( + "Video processing timed out after %ds" % self._VIDEO_PROCESS_TIMEOUT + ) + headers = self._build_headers(url=upload_url, method="GET") + resp = session.get(upload_url, headers=headers, params={ + "command": "STATUS", "media_id": media_id, + }, timeout=30) + if resp.status_code >= 400: + raise MediaUploadError("STATUS failed (HTTP %d): %s" % (resp.status_code, resp.text[:300])) + info = json.loads(resp.text).get("processing_info") + logger.info("Media STATUS: video processing complete") + return media_id def create_tweet(self, text, reply_to_id=None, media_ids=None):