mirror of
https://github.com/Alvin-Zilverstand/Twitter-X-Media-Batch-Downloader.git
synced 2026-11-24 07:13:11 +01:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4f6004a501 | ||
|
|
e7141cd8d1 | ||
|
|
4d6f4d904a | ||
|
|
4081e6aacf | ||
|
|
2b405a16a7 | ||
|
|
5e658c05d4 | ||
|
|
b26dd0b2af | ||
|
|
28422dcf1d | ||
|
|
46e09532fc | ||
|
|
967d91d370 | ||
|
|
2ff0242e32 | ||
|
|
1e1d612807 | ||
|
|
9821dd8c65 | ||
|
|
46bb7d38f7 | ||
|
|
112f5992c4 | ||
|
|
178b3c490f |
No files matched your search
+171
-41
@@ -4,42 +4,95 @@ import os
|
||||
from datetime import datetime
|
||||
from gallery_dl.extractor import twitter
|
||||
|
||||
def get_metadata(username, auth_token):
|
||||
url = f"https://x.com/{username}/timeline"
|
||||
def get_metadata(username, auth_token, timeline_type="timeline", batch_size=0, page=0, output_file=None):
|
||||
url = f"https://x.com/{username}/{timeline_type}"
|
||||
|
||||
match = re.match(twitter.TwitterTimelineExtractor.pattern, url)
|
||||
if timeline_type == "media":
|
||||
extractor_class = twitter.TwitterMediaExtractor
|
||||
elif timeline_type == "tweets":
|
||||
extractor_class = twitter.TwitterTweetsExtractor
|
||||
elif timeline_type == "with_replies":
|
||||
extractor_class = twitter.TwitterRepliesExtractor
|
||||
else:
|
||||
extractor_class = twitter.TwitterTimelineExtractor
|
||||
|
||||
match = re.match(extractor_class.pattern, url)
|
||||
if not match:
|
||||
raise ValueError(f"Invalid URL: {url}")
|
||||
|
||||
extractor = twitter.TwitterTimelineExtractor(match)
|
||||
raise ValueError(f"Invalid URL for {timeline_type}: {url}")
|
||||
|
||||
extractor.config = lambda key, default=None: {
|
||||
extractor = extractor_class(match)
|
||||
|
||||
config_dict = {
|
||||
"cookies": {
|
||||
"auth_token": auth_token
|
||||
}
|
||||
}.get(key, default)
|
||||
}
|
||||
|
||||
if batch_size > 0:
|
||||
config_dict["count"] = batch_size
|
||||
|
||||
extractor.config = lambda key, default=None: config_dict.get(key, default)
|
||||
|
||||
extractor.initialize()
|
||||
|
||||
output = {
|
||||
if output_file is None:
|
||||
current_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
output_file = os.path.join(current_dir, f"{username}_{timeline_type}.json")
|
||||
|
||||
structured_output = {
|
||||
'account_info': {},
|
||||
'total_urls': 0,
|
||||
'timeline': []
|
||||
}
|
||||
|
||||
for item in extractor:
|
||||
if isinstance(item, tuple) and len(item) >= 3:
|
||||
media_url = item[1]
|
||||
tweet_data = item[2]
|
||||
if page > 0 and os.path.exists(output_file):
|
||||
try:
|
||||
with open(output_file, 'r', encoding='utf-8') as f:
|
||||
structured_output = json.load(f)
|
||||
print(f"Loaded existing data with {structured_output['total_urls']} items from {output_file}")
|
||||
except json.JSONDecodeError:
|
||||
print(f"Warning: Could not load existing data from {output_file}, starting fresh")
|
||||
|
||||
iterator = iter(extractor)
|
||||
|
||||
if batch_size > 0 and page > 0:
|
||||
items_to_skip = page * batch_size
|
||||
print(f"Skipping {items_to_skip} items for page {page}...")
|
||||
|
||||
if hasattr(extractor, '_cursor') and extractor._cursor:
|
||||
print(f"Using cursor: {extractor._cursor}")
|
||||
else:
|
||||
skipped = 0
|
||||
try:
|
||||
for _ in range(items_to_skip):
|
||||
next(iterator)
|
||||
skipped += 1
|
||||
except StopIteration:
|
||||
print(f"Warning: Could only skip {skipped} items")
|
||||
|
||||
batch_items = []
|
||||
new_timeline_entries = []
|
||||
|
||||
items_to_fetch = batch_size if batch_size > 0 else float('inf')
|
||||
items_fetched = 0
|
||||
|
||||
try:
|
||||
while items_fetched < items_to_fetch:
|
||||
item = next(iterator)
|
||||
batch_items.append(item)
|
||||
items_fetched += 1
|
||||
|
||||
if not output['account_info']:
|
||||
if 'user' in tweet_data:
|
||||
if isinstance(item, tuple) and len(item) >= 3:
|
||||
media_url = item[1]
|
||||
tweet_data = item[2]
|
||||
|
||||
if not structured_output['account_info'] and 'user' in tweet_data:
|
||||
user = tweet_data['user']
|
||||
user_date = user.get('date', '')
|
||||
if isinstance(user_date, datetime):
|
||||
user_date = user_date.strftime("%Y-%m-%d %H:%M:%S")
|
||||
|
||||
output['account_info'] = {
|
||||
|
||||
structured_output['account_info'] = {
|
||||
'name': user.get('name', ''),
|
||||
'nick': user.get('nick', ''),
|
||||
'date': user_date,
|
||||
@@ -48,32 +101,109 @@ def get_metadata(username, auth_token):
|
||||
'profile_image': user.get('profile_image', ''),
|
||||
'statuses_count': user.get('statuses_count', 0)
|
||||
}
|
||||
|
||||
if 'pbs.twimg.com' in media_url or 'video.twimg.com' in media_url:
|
||||
tweet_date = tweet_data.get('date', datetime.now())
|
||||
if isinstance(tweet_date, datetime):
|
||||
tweet_date = tweet_date.strftime("%Y-%m-%d %H:%M:%S")
|
||||
|
||||
timeline_entry = {
|
||||
'url': media_url,
|
||||
'date': tweet_date,
|
||||
'tweet_id': tweet_data.get('tweet_id', 0),
|
||||
}
|
||||
|
||||
if 'type' in tweet_data:
|
||||
timeline_entry['type'] = tweet_data['type']
|
||||
|
||||
output['timeline'].append(timeline_entry)
|
||||
output['total_urls'] += 1
|
||||
|
||||
current_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
output_file = os.path.join(current_dir, f"{username}.json")
|
||||
if 'pbs.twimg.com' in media_url or 'video.twimg.com' in media_url:
|
||||
tweet_date = tweet_data.get('date', datetime.now())
|
||||
if isinstance(tweet_date, datetime):
|
||||
tweet_date = tweet_date.strftime("%Y-%m-%d %H:%M:%S")
|
||||
|
||||
timeline_entry = {
|
||||
'url': media_url,
|
||||
'date': tweet_date,
|
||||
'tweet_id': tweet_data.get('tweet_id', 0),
|
||||
}
|
||||
|
||||
if 'type' in tweet_data:
|
||||
timeline_entry['type'] = tweet_data['type']
|
||||
|
||||
new_timeline_entries.append(timeline_entry)
|
||||
structured_output['total_urls'] += 1
|
||||
except StopIteration:
|
||||
pass
|
||||
|
||||
structured_output['timeline'].extend(new_timeline_entries)
|
||||
|
||||
with open(output_file, 'w', encoding='utf-8') as f:
|
||||
json.dump(output, f, ensure_ascii=False, indent=2)
|
||||
json.dump(structured_output, f, ensure_ascii=False, indent=2)
|
||||
|
||||
if batch_size > 0:
|
||||
print(f"Page {page}: Added {len(new_timeline_entries)} media URLs. Total URLs: {structured_output['total_urls']}")
|
||||
else:
|
||||
print(f"Added {len(new_timeline_entries)} media URLs. Total URLs: {structured_output['total_urls']}")
|
||||
|
||||
cursor_info = None
|
||||
if hasattr(extractor, '_cursor') and extractor._cursor:
|
||||
cursor_info = extractor._cursor
|
||||
print(f"Current cursor: {cursor_info}")
|
||||
|
||||
return {
|
||||
"items": batch_items,
|
||||
"structured_output": structured_output,
|
||||
"new_entries": len(new_timeline_entries),
|
||||
"total_urls": structured_output['total_urls'],
|
||||
"page": page,
|
||||
"batch_size": batch_size,
|
||||
"has_more": batch_size > 0 and items_fetched == batch_size,
|
||||
"cursor": cursor_info
|
||||
}
|
||||
|
||||
return output
|
||||
def continue_metadata_fetch(username, auth_token, timeline_type="media", batch_size=100, max_pages=None):
|
||||
current_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
output_file = os.path.join(current_dir, f"{username}_{timeline_type}.json")
|
||||
|
||||
page = 0
|
||||
total_urls = 0
|
||||
has_more = True
|
||||
|
||||
if os.path.exists(output_file):
|
||||
try:
|
||||
with open(output_file, 'r', encoding='utf-8') as f:
|
||||
existing_data = json.load(f)
|
||||
total_urls = existing_data.get('total_urls', 0)
|
||||
page = total_urls // batch_size if batch_size > 0 else 0
|
||||
print(f"Continuing from page {page} with {total_urls} existing URLs")
|
||||
except json.JSONDecodeError:
|
||||
print(f"Warning: Could not load existing data from {output_file}, starting fresh")
|
||||
|
||||
while has_more and (max_pages is None or page < max_pages):
|
||||
result = get_metadata(
|
||||
username=username,
|
||||
auth_token=auth_token,
|
||||
timeline_type=timeline_type,
|
||||
batch_size=batch_size,
|
||||
page=page,
|
||||
output_file=output_file
|
||||
)
|
||||
|
||||
has_more = result["has_more"]
|
||||
total_urls = result["total_urls"]
|
||||
|
||||
if not has_more:
|
||||
print(f"No more items to fetch. Total URLs: {total_urls}")
|
||||
break
|
||||
|
||||
page += 1
|
||||
|
||||
return total_urls
|
||||
|
||||
username = ""
|
||||
auth_token = ""
|
||||
get_metadata(username, auth_token)
|
||||
# Usage
|
||||
if __name__ == "__main__":
|
||||
username = "takomayuyi"
|
||||
auth_token = ""
|
||||
|
||||
# Example 1: Non-batch mode - fetch all items at once
|
||||
# This will fetch all items without pagination
|
||||
# result = get_metadata(username, auth_token, "media")
|
||||
# print(f"Non-batch mode: Added {result['new_entries']} media URLs")
|
||||
|
||||
# Example 2: Batch mode - fetch items in pages
|
||||
# This will fetch only the specified page with the given batch size
|
||||
result = get_metadata(username, auth_token, "media", batch_size=100, page=0)
|
||||
print(f"Batch mode: Added {result['new_entries']} media URLs (page 0)")
|
||||
|
||||
# To fetch the next page:
|
||||
# result = get_metadata(username, auth_token, "media", batch_size=100, page=1)
|
||||
|
||||
# To automatically fetch all pages in batch mode:
|
||||
# total = continue_metadata_fetch(username, auth_token, "media", batch_size=100)
|
||||
# print(f"Total media URLs fetched across all pages: {total}")
|
||||
+142
-16
@@ -3,33 +3,159 @@ import re
|
||||
import os
|
||||
from gallery_dl.extractor import twitter
|
||||
|
||||
def get_metadata(username, auth_token):
|
||||
url = f"https://x.com/{username}/timeline"
|
||||
def get_metadata(username, auth_token, timeline_type="timeline", batch_size=0, page=0, output_file=None):
|
||||
url = f"https://x.com/{username}/{timeline_type}"
|
||||
|
||||
match = re.match(twitter.TwitterTimelineExtractor.pattern, url)
|
||||
if timeline_type == "media":
|
||||
extractor_class = twitter.TwitterMediaExtractor
|
||||
elif timeline_type == "tweets":
|
||||
extractor_class = twitter.TwitterTweetsExtractor
|
||||
elif timeline_type == "with_replies":
|
||||
extractor_class = twitter.TwitterRepliesExtractor
|
||||
else:
|
||||
extractor_class = twitter.TwitterTimelineExtractor
|
||||
|
||||
match = re.match(extractor_class.pattern, url)
|
||||
if not match:
|
||||
raise ValueError(f"Invalid URL: {url}")
|
||||
|
||||
extractor = twitter.TwitterTimelineExtractor(match)
|
||||
raise ValueError(f"Invalid URL for {timeline_type}: {url}")
|
||||
|
||||
extractor.config = lambda key, default=None: {
|
||||
extractor = extractor_class(match)
|
||||
|
||||
config_dict = {
|
||||
"cookies": {
|
||||
"auth_token": auth_token
|
||||
}
|
||||
}.get(key, default)
|
||||
}
|
||||
|
||||
if batch_size > 0:
|
||||
config_dict["count"] = batch_size
|
||||
|
||||
extractor.config = lambda key, default=None: config_dict.get(key, default)
|
||||
|
||||
extractor.initialize()
|
||||
|
||||
all_items = []
|
||||
for item in extractor:
|
||||
all_items.append(item)
|
||||
if output_file is None:
|
||||
current_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
output_file = os.path.join(current_dir, f"{username}_{timeline_type}.json")
|
||||
|
||||
current_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
output_file = os.path.join(current_dir, f"{username}.json")
|
||||
all_items = []
|
||||
if page > 0 and os.path.exists(output_file):
|
||||
try:
|
||||
with open(output_file, 'r', encoding='utf-8') as f:
|
||||
all_items = json.load(f)
|
||||
print(f"Loaded {len(all_items)} existing items from {output_file}")
|
||||
except json.JSONDecodeError:
|
||||
print(f"Warning: Could not load existing data from {output_file}, starting fresh")
|
||||
|
||||
iterator = iter(extractor)
|
||||
|
||||
if batch_size > 0 and page > 0:
|
||||
items_to_skip = page * batch_size
|
||||
print(f"Skipping {items_to_skip} items for page {page}...")
|
||||
|
||||
if hasattr(extractor, '_cursor') and extractor._cursor:
|
||||
print(f"Using cursor: {extractor._cursor}")
|
||||
else:
|
||||
skipped = 0
|
||||
try:
|
||||
for _ in range(items_to_skip):
|
||||
next(iterator)
|
||||
skipped += 1
|
||||
except StopIteration:
|
||||
print(f"Warning: Could only skip {skipped} items")
|
||||
|
||||
batch_items = []
|
||||
if batch_size > 0:
|
||||
try:
|
||||
for _ in range(batch_size):
|
||||
item = next(iterator)
|
||||
batch_items.append(item)
|
||||
except StopIteration:
|
||||
pass
|
||||
else:
|
||||
batch_items = list(iterator)
|
||||
|
||||
all_items.extend(batch_items)
|
||||
|
||||
with open(output_file, 'w', encoding='utf-8') as f:
|
||||
json.dump(all_items, f, indent=2, default=str)
|
||||
|
||||
if batch_size > 0:
|
||||
print(f"Page {page}: Retrieved {len(batch_items)} items. Total items: {len(all_items)}")
|
||||
else:
|
||||
print(f"Retrieved {len(batch_items)} items total")
|
||||
|
||||
cursor_info = None
|
||||
if hasattr(extractor, '_cursor') and extractor._cursor:
|
||||
cursor_info = extractor._cursor
|
||||
print(f"Current cursor: {cursor_info}")
|
||||
|
||||
return {
|
||||
"items": batch_items,
|
||||
"total_items": len(all_items),
|
||||
"page": page,
|
||||
"batch_size": batch_size,
|
||||
"has_more": batch_size > 0 and len(batch_items) == batch_size,
|
||||
"cursor": cursor_info
|
||||
}
|
||||
|
||||
username = ""
|
||||
auth_token = ""
|
||||
get_metadata(username, auth_token)
|
||||
def continue_metadata_fetch(username, auth_token, timeline_type="media", batch_size=100, max_pages=None):
|
||||
current_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
output_file = os.path.join(current_dir, f"{username}_{timeline_type}.json")
|
||||
|
||||
page = 0
|
||||
total_items = 0
|
||||
has_more = True
|
||||
|
||||
if os.path.exists(output_file):
|
||||
try:
|
||||
with open(output_file, 'r', encoding='utf-8') as f:
|
||||
existing_data = json.load(f)
|
||||
total_items = len(existing_data)
|
||||
page = total_items // batch_size
|
||||
print(f"Continuing from page {page} with {total_items} existing items")
|
||||
except json.JSONDecodeError:
|
||||
print(f"Warning: Could not load existing data from {output_file}, starting fresh")
|
||||
|
||||
while has_more and (max_pages is None or page < max_pages):
|
||||
result = get_metadata(
|
||||
username=username,
|
||||
auth_token=auth_token,
|
||||
timeline_type=timeline_type,
|
||||
batch_size=batch_size,
|
||||
page=page,
|
||||
output_file=output_file
|
||||
)
|
||||
|
||||
has_more = result["has_more"]
|
||||
total_items = result["total_items"]
|
||||
|
||||
if not has_more:
|
||||
print(f"No more items to fetch. Total items: {total_items}")
|
||||
break
|
||||
|
||||
page += 1
|
||||
|
||||
return total_items
|
||||
|
||||
# Usage
|
||||
if __name__ == "__main__":
|
||||
username = "takomayuyi"
|
||||
auth_token = ""
|
||||
|
||||
# Example 1: Non-batch mode - fetch all items at once
|
||||
# This will fetch all items without pagination
|
||||
# result = get_metadata(username, auth_token, "media")
|
||||
# print(f"Non-batch mode: Retrieved {len(result['items'])} items")
|
||||
|
||||
# Example 2: Batch mode - fetch items in pages
|
||||
# This will fetch only the specified page with the given batch size
|
||||
result = get_metadata(username, auth_token, "media", batch_size=100, page=0)
|
||||
print(f"Batch mode: Retrieved {len(result['items'])} items (page 0)")
|
||||
|
||||
# To fetch the next page:
|
||||
# result = get_metadata(username, auth_token, "media", batch_size=100, page=1)
|
||||
|
||||
# To automatically fetch all pages in batch mode:
|
||||
# total = continue_metadata_fetch(username, auth_token, "media", batch_size=100)
|
||||
# print(f"Total items fetched across all pages: {total}")
|
||||
@@ -3,18 +3,17 @@
|
||||

|
||||
|
||||
<div align="center">
|
||||
<b>Twitter/X Media Batch Downloader</b> is a GUI tool that allows users to download all media, including images and videos, in their original quality from Twitter/X accounts, even withheld account, using <code>gallery-dl</code>
|
||||
<b>Twitter/X Media Batch Downloader</b> is a GUI tool that allows users to download all media, including images and videos, in their original quality from Twitter/X accounts using <code>gallery-dl</code>
|
||||
</div>
|
||||
|
||||
## 📥 Download
|
||||
|
||||
- Download the latest version of [TwitterXMediaBatchDownloader](https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases/download/v1.9/TwitterXMediaBatchDownloader.exe)
|
||||
- If you're familiar with **userscripts**, please install it [here](https://greasyfork.org/en/scripts/523157-twitter-x-media-batch-downloader)
|
||||
- Download the latest version of [TwitterXMediaBatchDownloader](https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases/download/v2.2/TwitterXMediaBatchDownloader.exe)
|
||||
- If you're familiar with **userscripts**, please install it [here](https://greasyfork.org/en/scripts/523157)
|
||||
|
||||
## ✨ Features
|
||||
|
||||
- Powered by `gallery-dl`, similar to `yt-dlp`
|
||||
- Supports downloading from **Withheld Accounts**
|
||||
- **Choose media type**: All (Image + GIF + Video) or specific (Image/GIF/Video)
|
||||
- Downloads in original quality
|
||||
|
||||
@@ -24,14 +23,10 @@
|
||||
|
||||

|
||||
|
||||

|
||||

|
||||
|
||||
> [!Important]
|
||||
> It is highly recommended to use the local `gallery-dl` **(by unchecking "Use API").** Use the API only for withheld accounts, as it has a 60-second timeout limit.
|
||||
|
||||

|
||||
|
||||

|
||||
> Use **Batch** if the items to be downloaded are in the thousands.
|
||||
|
||||
## 🔑 How to Obtain Auth Token
|
||||
|
||||
@@ -39,7 +34,7 @@
|
||||
> - I suggest not using the **main account** to obtain the token.
|
||||
> - You can use https://temp-mail.io to register a Twitter account.
|
||||
> - Using an auth token or cookies has the potential to get the **account suspended.**
|
||||
> - If too many media files are fetched, it will trigger a **rate limit**, and the media retrieval will fail.
|
||||
> - If too many media files are fetched, it may trigger a **rate limit**, and the media retrieval will fail.
|
||||
|
||||
1. Go to [Twitter's website](https://www.x.com/)
|
||||
2. Log into your account
|
||||
|
||||
@@ -38,13 +38,12 @@ class MetadataFetcher(QThread):
|
||||
finished = pyqtSignal(dict)
|
||||
error = pyqtSignal(str)
|
||||
|
||||
def __init__(self, username, timeline_type='media', media_type='all', use_api=False, batch_mode=False, batch_size=100, page=0):
|
||||
def __init__(self, username, timeline_type='media', media_type='all', batch_mode=False, batch_size=100, page=0):
|
||||
super().__init__()
|
||||
self.username = username
|
||||
self.auth_token = None
|
||||
self.timeline_type = timeline_type
|
||||
self.media_type = media_type
|
||||
self.use_api = use_api
|
||||
self.batch_mode = batch_mode
|
||||
self.batch_size = batch_size
|
||||
self.page = page
|
||||
@@ -64,35 +63,10 @@ class MetadataFetcher(QThread):
|
||||
username = username.strip()
|
||||
return username
|
||||
|
||||
async def fetch_from_api(self, username, auth_token):
|
||||
try:
|
||||
async with aiohttp.ClientSession() as session:
|
||||
if self.batch_mode:
|
||||
url = f"https://gallerydl.vercel.app/metadata/{self.timeline_type}/{self.batch_size}/{self.page}/{self.media_type}/{username}/{auth_token}"
|
||||
else:
|
||||
url = f"https://gallerydl.vercel.app/metadata/{self.timeline_type}/{self.media_type}/{username}/{auth_token}"
|
||||
|
||||
async with session.get(url) as response:
|
||||
if response.status == 200:
|
||||
data = await response.json()
|
||||
return data
|
||||
else:
|
||||
raise ValueError(f"API request failed with status {response.status}")
|
||||
except Exception as e:
|
||||
raise ValueError(f"API request failed: {str(e)}")
|
||||
|
||||
def run(self):
|
||||
try:
|
||||
normalized = self.normalize_url(self.username)
|
||||
|
||||
if self.use_api:
|
||||
try:
|
||||
data = asyncio.run(self.fetch_from_api(normalized, self.auth_token))
|
||||
self.finished.emit(data)
|
||||
return
|
||||
except Exception as api_error:
|
||||
pass
|
||||
|
||||
try:
|
||||
batch_size = self.batch_size if self.batch_mode else 0
|
||||
data = get_metadata(
|
||||
@@ -109,10 +83,7 @@ class MetadataFetcher(QThread):
|
||||
if not error_message or error_message == "None":
|
||||
error_message = "Local gallery-dl error: None"
|
||||
|
||||
if self.use_api:
|
||||
raise ValueError(f"Both API and local methods failed.\nAPI error: {str(api_error)}\nLocal error: {error_message}")
|
||||
else:
|
||||
raise ValueError(f"Local gallery-dl error: {error_message}")
|
||||
raise ValueError(f"Local gallery-dl error: {error_message}")
|
||||
|
||||
except Exception as e:
|
||||
self.error.emit(str(e))
|
||||
@@ -302,7 +273,7 @@ class UpdateDialog(QDialog):
|
||||
class TwitterMediaDownloaderGUI(QMainWindow):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.current_version = "1.9"
|
||||
self.current_version = "2.3"
|
||||
self.setWindowTitle("Twitter/X Media Batch Downloader")
|
||||
|
||||
self.settings = QSettings('TwitterMediaDownloader', 'Settings')
|
||||
@@ -430,13 +401,9 @@ class TwitterMediaDownloaderGUI(QMainWindow):
|
||||
first_row_layout = QHBoxLayout()
|
||||
first_row_layout.setSpacing(5)
|
||||
|
||||
self.use_api_checkbox = QCheckBox("Use API")
|
||||
self.use_api_checkbox.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
|
||||
self.use_api_checkbox.setToolTip("Use API instead of local gallery-dl")
|
||||
first_row_layout.addWidget(self.use_api_checkbox)
|
||||
|
||||
self.batch_checkbox = QCheckBox("Batch")
|
||||
self.batch_checkbox.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
|
||||
self.batch_checkbox.setToolTip("Enable for accounts with thousands of media")
|
||||
self.batch_checkbox.stateChanged.connect(self.handle_batch_checkbox)
|
||||
first_row_layout.addWidget(self.batch_checkbox)
|
||||
|
||||
@@ -470,12 +437,12 @@ class TwitterMediaDownloaderGUI(QMainWindow):
|
||||
|
||||
first_row_layout.addSpacing(5)
|
||||
|
||||
media_type_label = QLabel("Item Type:")
|
||||
media_type_label = QLabel("Media Type:")
|
||||
self.media_type_combo = QComboBox()
|
||||
self.media_type_combo.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
|
||||
self.media_type_combo.setFixedWidth(85)
|
||||
media_types = [
|
||||
('all', 'All Media'),
|
||||
('all', 'All'),
|
||||
('image', 'Image'),
|
||||
('video', 'Video'),
|
||||
('gif', 'GIF')
|
||||
@@ -687,14 +654,12 @@ class TwitterMediaDownloaderGUI(QMainWindow):
|
||||
|
||||
timeline_type = self.timeline_type_combo.currentData()
|
||||
media_type = self.media_type_combo.currentData()
|
||||
use_api = self.use_api_checkbox.isChecked()
|
||||
batch_size = int(self.batch_size_combo.currentText())
|
||||
|
||||
self.fetcher = MetadataFetcher(
|
||||
username,
|
||||
timeline_type,
|
||||
media_type,
|
||||
use_api,
|
||||
True,
|
||||
batch_size,
|
||||
self.current_page
|
||||
@@ -763,7 +728,6 @@ class TwitterMediaDownloaderGUI(QMainWindow):
|
||||
self.format_username.toggled.connect(self.auto_save_settings)
|
||||
self.media_type_combo.currentTextChanged.connect(self.auto_save_settings)
|
||||
self.timeline_type_combo.currentTextChanged.connect(self.auto_save_settings)
|
||||
self.use_api_checkbox.stateChanged.connect(self.auto_save_settings)
|
||||
self.batch_checkbox.stateChanged.connect(self.auto_save_settings)
|
||||
self.download_batch_combo.currentTextChanged.connect(self.auto_save_settings)
|
||||
self.batch_size_combo.currentTextChanged.connect(self.auto_save_settings)
|
||||
@@ -777,7 +741,6 @@ class TwitterMediaDownloaderGUI(QMainWindow):
|
||||
'username_date' if self.format_username.isChecked() else 'date_username')
|
||||
self.settings.setValue('media_type', self.media_type_combo.currentData())
|
||||
self.settings.setValue('timeline_type', self.timeline_type_combo.currentData())
|
||||
self.settings.setValue('use_api', self.use_api_checkbox.isChecked())
|
||||
|
||||
batch_mode = self.batch_checkbox.isChecked()
|
||||
self.settings.setValue('batch_mode', batch_mode)
|
||||
@@ -810,9 +773,6 @@ class TwitterMediaDownloaderGUI(QMainWindow):
|
||||
self.timeline_type_combo.setCurrentIndex(i)
|
||||
break
|
||||
|
||||
use_api = self.settings.value('use_api', False, type=bool)
|
||||
self.use_api_checkbox.setChecked(use_api)
|
||||
|
||||
batch_mode = self.settings.value('batch_mode', False, type=bool)
|
||||
|
||||
self.batch_checkbox.blockSignals(True)
|
||||
@@ -870,7 +830,6 @@ class TwitterMediaDownloaderGUI(QMainWindow):
|
||||
|
||||
timeline_type = self.timeline_type_combo.currentData()
|
||||
media_type = self.media_type_combo.currentData()
|
||||
use_api = self.use_api_checkbox.isChecked()
|
||||
batch_mode = self.batch_checkbox.isChecked()
|
||||
batch_size = int(self.batch_size_combo.currentText()) if batch_mode else 100
|
||||
|
||||
@@ -878,7 +837,6 @@ class TwitterMediaDownloaderGUI(QMainWindow):
|
||||
username,
|
||||
timeline_type,
|
||||
media_type,
|
||||
use_api,
|
||||
batch_mode,
|
||||
batch_size,
|
||||
self.current_page
|
||||
@@ -906,14 +864,12 @@ class TwitterMediaDownloaderGUI(QMainWindow):
|
||||
|
||||
timeline_type = self.timeline_type_combo.currentData()
|
||||
media_type = self.media_type_combo.currentData()
|
||||
use_api = self.use_api_checkbox.isChecked()
|
||||
batch_size = int(self.batch_size_combo.currentText())
|
||||
|
||||
self.fetcher = MetadataFetcher(
|
||||
username,
|
||||
timeline_type,
|
||||
media_type,
|
||||
use_api,
|
||||
True,
|
||||
batch_size,
|
||||
self.current_page
|
||||
@@ -960,6 +916,15 @@ class TwitterMediaDownloaderGUI(QMainWindow):
|
||||
if not info or not isinstance(info, dict):
|
||||
raise ValueError("Invalid info data received")
|
||||
|
||||
if 'error' in info:
|
||||
error_type = info['error']
|
||||
if error_type == "withheld":
|
||||
self.status_label.setText("Please use the Userscript version for withheld accounts.")
|
||||
else:
|
||||
self.status_label.setText("Please check the 'Auth Token' value. Your account may be logged out, locked, or suspended.")
|
||||
self.fetch_button.setEnabled(True)
|
||||
return
|
||||
|
||||
account_info = info.get('account_info', {})
|
||||
if not account_info:
|
||||
self.status_label.setText("Failed to fetch profile information")
|
||||
@@ -1106,10 +1071,11 @@ class TwitterMediaDownloaderGUI(QMainWindow):
|
||||
self.next_batch_button.setEnabled(True)
|
||||
|
||||
error_str = str(error)
|
||||
if "Local gallery-dl error: None" in error_str and not self.use_api_checkbox.isChecked():
|
||||
self.status_label.setText("Please check the 'Use API' option to fetch metadata using the API method.")
|
||||
|
||||
if '"error": "withheld"' in error_str or "withheld" in error_str:
|
||||
self.status_label.setText("please use userscripe version")
|
||||
else:
|
||||
self.status_label.setText(f"Error fetching profile info: {error}")
|
||||
self.status_label.setText("Please check the 'Auth Token'.")
|
||||
|
||||
def start_download(self):
|
||||
if not self.media_info:
|
||||
|
||||
+123
-91
@@ -32,102 +32,130 @@ def get_metadata(username, auth_token, timeline_type="timeline", batch_size=0, p
|
||||
|
||||
extractor.config = lambda key, default=None: config_dict.get(key, default)
|
||||
|
||||
extractor.initialize()
|
||||
|
||||
structured_output = {
|
||||
'account_info': {},
|
||||
'total_urls': 0,
|
||||
'timeline': []
|
||||
}
|
||||
|
||||
iterator = iter(extractor)
|
||||
|
||||
if batch_size > 0 and page > 0:
|
||||
items_to_skip = page * batch_size
|
||||
|
||||
if hasattr(extractor, '_cursor') and extractor._cursor:
|
||||
pass
|
||||
else:
|
||||
skipped = 0
|
||||
try:
|
||||
for _ in range(items_to_skip):
|
||||
next(iterator)
|
||||
skipped += 1
|
||||
except StopIteration:
|
||||
pass
|
||||
|
||||
new_timeline_entries = []
|
||||
|
||||
items_to_fetch = batch_size if batch_size > 0 else float('inf')
|
||||
items_fetched = 0
|
||||
|
||||
try:
|
||||
while items_fetched < items_to_fetch:
|
||||
item = next(iterator)
|
||||
items_fetched += 1
|
||||
extractor.initialize()
|
||||
|
||||
api = twitter.TwitterAPI(extractor)
|
||||
try:
|
||||
if username.startswith("id:"):
|
||||
user = api.user_by_rest_id(username[3:])
|
||||
else:
|
||||
user = api.user_by_screen_name(username)
|
||||
|
||||
if "legacy" in user and user["legacy"].get("withheld_scope"):
|
||||
raise ValueError("withheld")
|
||||
|
||||
except Exception as e:
|
||||
error_msg = str(e).lower()
|
||||
if "withheld" in error_msg or (hasattr(e, "response") and "withheld" in str(e.response.text).lower()):
|
||||
raise ValueError("withheld")
|
||||
raise
|
||||
|
||||
structured_output = {
|
||||
'account_info': {},
|
||||
'total_urls': 0,
|
||||
'timeline': []
|
||||
}
|
||||
|
||||
iterator = iter(extractor)
|
||||
|
||||
if batch_size > 0 and page > 0:
|
||||
items_to_skip = page * batch_size
|
||||
|
||||
if isinstance(item, tuple) and len(item) >= 3:
|
||||
media_url = item[1]
|
||||
tweet_data = item[2]
|
||||
if hasattr(extractor, '_cursor') and extractor._cursor:
|
||||
pass
|
||||
else:
|
||||
skipped = 0
|
||||
try:
|
||||
for _ in range(items_to_skip):
|
||||
next(iterator)
|
||||
skipped += 1
|
||||
except StopIteration:
|
||||
pass
|
||||
|
||||
new_timeline_entries = []
|
||||
|
||||
items_to_fetch = batch_size if batch_size > 0 else float('inf')
|
||||
items_fetched = 0
|
||||
|
||||
try:
|
||||
while items_fetched < items_to_fetch:
|
||||
item = next(iterator)
|
||||
items_fetched += 1
|
||||
|
||||
if not structured_output['account_info'] and 'user' in tweet_data:
|
||||
user = tweet_data['user']
|
||||
user_date = user.get('date', '')
|
||||
if isinstance(user_date, datetime):
|
||||
user_date = user_date.strftime("%Y-%m-%d %H:%M:%S")
|
||||
if isinstance(item, tuple) and len(item) >= 3:
|
||||
media_url = item[1]
|
||||
tweet_data = item[2]
|
||||
|
||||
structured_output['account_info'] = {
|
||||
'name': user.get('name', ''),
|
||||
'nick': user.get('nick', ''),
|
||||
'date': user_date,
|
||||
'followers_count': user.get('followers_count', 0),
|
||||
'friends_count': user.get('friends_count', 0),
|
||||
'profile_image': user.get('profile_image', ''),
|
||||
'statuses_count': user.get('statuses_count', 0)
|
||||
}
|
||||
|
||||
if 'pbs.twimg.com' in media_url or 'video.twimg.com' in media_url:
|
||||
tweet_date = tweet_data.get('date', datetime.now())
|
||||
if isinstance(tweet_date, datetime):
|
||||
tweet_date = tweet_date.strftime("%Y-%m-%d %H:%M:%S")
|
||||
if not structured_output['account_info'] and 'user' in tweet_data:
|
||||
user = tweet_data['user']
|
||||
user_date = user.get('date', '')
|
||||
if isinstance(user_date, datetime):
|
||||
user_date = user_date.strftime("%Y-%m-%d %H:%M:%S")
|
||||
|
||||
structured_output['account_info'] = {
|
||||
'name': user.get('name', ''),
|
||||
'nick': user.get('nick', ''),
|
||||
'date': user_date,
|
||||
'followers_count': user.get('followers_count', 0),
|
||||
'friends_count': user.get('friends_count', 0),
|
||||
'profile_image': user.get('profile_image', ''),
|
||||
'statuses_count': user.get('statuses_count', 0)
|
||||
}
|
||||
|
||||
timeline_entry = {
|
||||
'url': media_url,
|
||||
'date': tweet_date,
|
||||
'tweet_id': tweet_data.get('tweet_id', 0),
|
||||
}
|
||||
|
||||
if 'type' in tweet_data:
|
||||
timeline_entry['type'] = tweet_data['type']
|
||||
|
||||
if media_type == 'all' or (
|
||||
(media_type == 'image' and 'pbs.twimg.com' in media_url and tweet_data.get('type') == 'photo') or
|
||||
(media_type == 'video' and 'video.twimg.com' in media_url and tweet_data.get('type') == 'video') or
|
||||
(media_type == 'gif' and 'video.twimg.com' in media_url and tweet_data.get('type') == 'animated_gif')
|
||||
):
|
||||
new_timeline_entries.append(timeline_entry)
|
||||
structured_output['total_urls'] += 1
|
||||
except StopIteration:
|
||||
pass
|
||||
if 'pbs.twimg.com' in media_url or 'video.twimg.com' in media_url:
|
||||
tweet_date = tweet_data.get('date', datetime.now())
|
||||
if isinstance(tweet_date, datetime):
|
||||
tweet_date = tweet_date.strftime("%Y-%m-%d %H:%M:%S")
|
||||
|
||||
timeline_entry = {
|
||||
'url': media_url,
|
||||
'date': tweet_date,
|
||||
'tweet_id': tweet_data.get('tweet_id', 0),
|
||||
}
|
||||
|
||||
if 'type' in tweet_data:
|
||||
timeline_entry['type'] = tweet_data['type']
|
||||
|
||||
if media_type == 'all' or (
|
||||
(media_type == 'image' and 'pbs.twimg.com' in media_url and tweet_data.get('type') == 'photo') or
|
||||
(media_type == 'video' and 'video.twimg.com' in media_url and tweet_data.get('type') == 'video') or
|
||||
(media_type == 'gif' and 'video.twimg.com' in media_url and tweet_data.get('type') == 'animated_gif')
|
||||
):
|
||||
new_timeline_entries.append(timeline_entry)
|
||||
structured_output['total_urls'] += 1
|
||||
except StopIteration:
|
||||
pass
|
||||
|
||||
structured_output['timeline'].extend(new_timeline_entries)
|
||||
|
||||
cursor_info = None
|
||||
if hasattr(extractor, '_cursor') and extractor._cursor:
|
||||
cursor_info = extractor._cursor
|
||||
|
||||
structured_output['metadata'] = {
|
||||
"new_entries": len(new_timeline_entries),
|
||||
"page": page,
|
||||
"batch_size": batch_size,
|
||||
"has_more": batch_size > 0 and items_fetched == batch_size,
|
||||
"cursor": cursor_info
|
||||
}
|
||||
|
||||
if not structured_output['account_info']:
|
||||
raise ValueError("Failed to fetch account information. Please check the username and auth token.")
|
||||
|
||||
return structured_output
|
||||
|
||||
structured_output['timeline'].extend(new_timeline_entries)
|
||||
|
||||
cursor_info = None
|
||||
if hasattr(extractor, '_cursor') and extractor._cursor:
|
||||
cursor_info = extractor._cursor
|
||||
|
||||
structured_output['metadata'] = {
|
||||
"new_entries": len(new_timeline_entries),
|
||||
"page": page,
|
||||
"batch_size": batch_size,
|
||||
"has_more": batch_size > 0 and items_fetched == batch_size,
|
||||
"cursor": cursor_info
|
||||
}
|
||||
|
||||
if not structured_output['account_info']:
|
||||
raise ValueError("Failed to fetch account information. Please check the username and auth token.")
|
||||
|
||||
return structured_output
|
||||
except Exception as e:
|
||||
error_msg = str(e).lower()
|
||||
if "withheld" in error_msg or e.__class__.__name__ == "ValueError" and str(e) == "withheld":
|
||||
return {"error": "withheld"}
|
||||
else:
|
||||
error_str = str(e)
|
||||
if error_str == "None":
|
||||
return {"error": "null"}
|
||||
else:
|
||||
return {"error": error_str}
|
||||
|
||||
def main():
|
||||
username = ""
|
||||
@@ -148,7 +176,11 @@ def main():
|
||||
)
|
||||
print(json.dumps(data, ensure_ascii=False, indent=2))
|
||||
except Exception as e:
|
||||
print(json.dumps({"error": str(e)}, ensure_ascii=False))
|
||||
error_str = str(e)
|
||||
if error_str == "None":
|
||||
print(json.dumps({"error": "null"}, ensure_ascii=False))
|
||||
else:
|
||||
print(json.dumps({"error": error_str}, ensure_ascii=False))
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
+1
-1
@@ -1,3 +1,3 @@
|
||||
{
|
||||
"version": "1.8"
|
||||
"version": "2.2"
|
||||
}
|
||||
Reference in new issue
Block a user