mirror of
https://github.com/Alvin-Zilverstand/Twitter-X-Media-Batch-Downloader.git
synced 2026-11-24 15:23:11 +01:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f8b27ecb5a | ||
|
|
70e79af700 | ||
|
|
4fb60840a0 | ||
|
|
5613c152f8 | ||
|
|
ad5d7727eb | ||
|
|
ed1f0fce06 | ||
|
|
ee92174773 | ||
|
|
f08ce57feb | ||
|
|
4f21321e42 | ||
|
|
c8b7a5365a | ||
|
|
1049b544c5 | ||
|
|
e7db97a936 | ||
|
|
af1280b798 | ||
|
|
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 datetime import datetime
|
||||||
from gallery_dl.extractor import twitter
|
from gallery_dl.extractor import twitter
|
||||||
|
|
||||||
def get_metadata(username, auth_token):
|
def get_metadata(username, auth_token, timeline_type="timeline", batch_size=0, page=0, output_file=None):
|
||||||
url = f"https://x.com/{username}/timeline"
|
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:
|
if not match:
|
||||||
raise ValueError(f"Invalid URL: {url}")
|
raise ValueError(f"Invalid URL for {timeline_type}: {url}")
|
||||||
|
|
||||||
extractor = twitter.TwitterTimelineExtractor(match)
|
|
||||||
|
|
||||||
extractor.config = lambda key, default=None: {
|
extractor = extractor_class(match)
|
||||||
|
|
||||||
|
config_dict = {
|
||||||
"cookies": {
|
"cookies": {
|
||||||
"auth_token": auth_token
|
"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()
|
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': {},
|
'account_info': {},
|
||||||
'total_urls': 0,
|
'total_urls': 0,
|
||||||
'timeline': []
|
'timeline': []
|
||||||
}
|
}
|
||||||
|
|
||||||
for item in extractor:
|
if page > 0 and os.path.exists(output_file):
|
||||||
if isinstance(item, tuple) and len(item) >= 3:
|
try:
|
||||||
media_url = item[1]
|
with open(output_file, 'r', encoding='utf-8') as f:
|
||||||
tweet_data = item[2]
|
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 isinstance(item, tuple) and len(item) >= 3:
|
||||||
if 'user' in tweet_data:
|
media_url = item[1]
|
||||||
|
tweet_data = item[2]
|
||||||
|
|
||||||
|
if not structured_output['account_info'] and 'user' in tweet_data:
|
||||||
user = tweet_data['user']
|
user = tweet_data['user']
|
||||||
user_date = user.get('date', '')
|
user_date = user.get('date', '')
|
||||||
if isinstance(user_date, datetime):
|
if isinstance(user_date, datetime):
|
||||||
user_date = user_date.strftime("%Y-%m-%d %H:%M:%S")
|
user_date = user_date.strftime("%Y-%m-%d %H:%M:%S")
|
||||||
|
|
||||||
output['account_info'] = {
|
structured_output['account_info'] = {
|
||||||
'name': user.get('name', ''),
|
'name': user.get('name', ''),
|
||||||
'nick': user.get('nick', ''),
|
'nick': user.get('nick', ''),
|
||||||
'date': user_date,
|
'date': user_date,
|
||||||
@@ -48,32 +101,109 @@ def get_metadata(username, auth_token):
|
|||||||
'profile_image': user.get('profile_image', ''),
|
'profile_image': user.get('profile_image', ''),
|
||||||
'statuses_count': user.get('statuses_count', 0)
|
'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 = {
|
if 'pbs.twimg.com' in media_url or 'video.twimg.com' in media_url:
|
||||||
'url': media_url,
|
tweet_date = tweet_data.get('date', datetime.now())
|
||||||
'date': tweet_date,
|
if isinstance(tweet_date, datetime):
|
||||||
'tweet_id': tweet_data.get('tweet_id', 0),
|
tweet_date = tweet_date.strftime("%Y-%m-%d %H:%M:%S")
|
||||||
}
|
|
||||||
|
timeline_entry = {
|
||||||
if 'type' in tweet_data:
|
'url': media_url,
|
||||||
timeline_entry['type'] = tweet_data['type']
|
'date': tweet_date,
|
||||||
|
'tweet_id': tweet_data.get('tweet_id', 0),
|
||||||
output['timeline'].append(timeline_entry)
|
}
|
||||||
output['total_urls'] += 1
|
|
||||||
|
if 'type' in tweet_data:
|
||||||
current_dir = os.path.dirname(os.path.abspath(__file__))
|
timeline_entry['type'] = tweet_data['type']
|
||||||
output_file = os.path.join(current_dir, f"{username}.json")
|
|
||||||
|
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:
|
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 = ""
|
# Usage
|
||||||
auth_token = ""
|
if __name__ == "__main__":
|
||||||
get_metadata(username, auth_token)
|
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
|
import os
|
||||||
from gallery_dl.extractor import twitter
|
from gallery_dl.extractor import twitter
|
||||||
|
|
||||||
def get_metadata(username, auth_token):
|
def get_metadata(username, auth_token, timeline_type="timeline", batch_size=0, page=0, output_file=None):
|
||||||
url = f"https://x.com/{username}/timeline"
|
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:
|
if not match:
|
||||||
raise ValueError(f"Invalid URL: {url}")
|
raise ValueError(f"Invalid URL for {timeline_type}: {url}")
|
||||||
|
|
||||||
extractor = twitter.TwitterTimelineExtractor(match)
|
|
||||||
|
|
||||||
extractor.config = lambda key, default=None: {
|
extractor = extractor_class(match)
|
||||||
|
|
||||||
|
config_dict = {
|
||||||
"cookies": {
|
"cookies": {
|
||||||
"auth_token": auth_token
|
"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()
|
extractor.initialize()
|
||||||
|
|
||||||
all_items = []
|
if output_file is None:
|
||||||
for item in extractor:
|
current_dir = os.path.dirname(os.path.abspath(__file__))
|
||||||
all_items.append(item)
|
output_file = os.path.join(current_dir, f"{username}_{timeline_type}.json")
|
||||||
|
|
||||||
current_dir = os.path.dirname(os.path.abspath(__file__))
|
all_items = []
|
||||||
output_file = os.path.join(current_dir, f"{username}.json")
|
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:
|
with open(output_file, 'w', encoding='utf-8') as f:
|
||||||
json.dump(all_items, f, indent=2, default=str)
|
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 = ""
|
def continue_metadata_fetch(username, auth_token, timeline_type="media", batch_size=100, max_pages=None):
|
||||||
auth_token = ""
|
current_dir = os.path.dirname(os.path.abspath(__file__))
|
||||||
get_metadata(username, auth_token)
|
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,35 +3,32 @@
|
|||||||

|

|
||||||
|
|
||||||
<div align="center">
|
<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>
|
</div>
|
||||||
|
|
||||||
## 📥 Download
|
## 📥 Download
|
||||||
|
|
||||||
- Download the latest version of [TwitterXMediaBatchDownloader](https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases/download/v1.9/TwitterXMediaBatchDownloader.exe)
|
- Download the latest version of [TwitterXMediaBatchDownloader](https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases/download/v2.6/TwitterXMediaBatchDownloader.exe)
|
||||||
- If you're familiar with **userscripts**, please install it [here](https://greasyfork.org/en/scripts/523157-twitter-x-media-batch-downloader)
|
- If you're familiar with **userscripts**, please install it [here](https://greasyfork.org/en/scripts/523157)
|
||||||
|
|
||||||
## ✨ Features
|
## ✨ Features
|
||||||
|
|
||||||
- Powered by `gallery-dl`, similar to `yt-dlp`
|
- 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)
|
- **Choose media type**: All (Image + GIF + Video) or specific (Image/GIF/Video)
|
||||||
- Downloads in original quality
|
- Downloads in original quality
|
||||||
|
|
||||||
## 🖼️ Screenshots
|
## 🖼️ Screenshots
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||

|

|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
> [!Important]
|
> [!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
|
## 🔑 How to Obtain Auth Token
|
||||||
|
|
||||||
@@ -39,7 +36,7 @@
|
|||||||
> - I suggest not using the **main account** to obtain the token.
|
> - I suggest not using the **main account** to obtain the token.
|
||||||
> - You can use https://temp-mail.io to register a Twitter account.
|
> - 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.**
|
> - 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, try enabling Batch mode.
|
||||||
|
|
||||||
1. Go to [Twitter's website](https://www.x.com/)
|
1. Go to [Twitter's website](https://www.x.com/)
|
||||||
2. Log into your account
|
2. Log into your account
|
||||||
|
|||||||
+168
-112
@@ -4,6 +4,7 @@ import asyncio
|
|||||||
import aiohttp
|
import aiohttp
|
||||||
import requests
|
import requests
|
||||||
import subprocess
|
import subprocess
|
||||||
|
import imageio_ffmpeg
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from packaging import version
|
from packaging import version
|
||||||
@@ -38,13 +39,12 @@ class MetadataFetcher(QThread):
|
|||||||
finished = pyqtSignal(dict)
|
finished = pyqtSignal(dict)
|
||||||
error = pyqtSignal(str)
|
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__()
|
super().__init__()
|
||||||
self.username = username
|
self.username = username
|
||||||
self.auth_token = None
|
self.auth_token = None
|
||||||
self.timeline_type = timeline_type
|
self.timeline_type = timeline_type
|
||||||
self.media_type = media_type
|
self.media_type = media_type
|
||||||
self.use_api = use_api
|
|
||||||
self.batch_mode = batch_mode
|
self.batch_mode = batch_mode
|
||||||
self.batch_size = batch_size
|
self.batch_size = batch_size
|
||||||
self.page = page
|
self.page = page
|
||||||
@@ -64,35 +64,10 @@ class MetadataFetcher(QThread):
|
|||||||
username = username.strip()
|
username = username.strip()
|
||||||
return username
|
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):
|
def run(self):
|
||||||
try:
|
try:
|
||||||
normalized = self.normalize_url(self.username)
|
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:
|
try:
|
||||||
batch_size = self.batch_size if self.batch_mode else 0
|
batch_size = self.batch_size if self.batch_mode else 0
|
||||||
data = get_metadata(
|
data = get_metadata(
|
||||||
@@ -109,10 +84,7 @@ class MetadataFetcher(QThread):
|
|||||||
if not error_message or error_message == "None":
|
if not error_message or error_message == "None":
|
||||||
error_message = "Local gallery-dl error: None"
|
error_message = "Local gallery-dl error: None"
|
||||||
|
|
||||||
if self.use_api:
|
raise ValueError(f"Local gallery-dl error: {error_message}")
|
||||||
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}")
|
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
self.error.emit(str(e))
|
self.error.emit(str(e))
|
||||||
@@ -123,7 +95,7 @@ class MediaDownloader(QThread):
|
|||||||
error = pyqtSignal(str)
|
error = pyqtSignal(str)
|
||||||
status_update = pyqtSignal(str)
|
status_update = pyqtSignal(str)
|
||||||
|
|
||||||
def __init__(self, media_list, output_dir, filename_format, username, media_type='all', batch_size=10):
|
def __init__(self, media_list, output_dir, filename_format, username, media_type='all', batch_size=10, convert_gif=False):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
self.media_list = media_list
|
self.media_list = media_list
|
||||||
self.output_dir = output_dir
|
self.output_dir = output_dir
|
||||||
@@ -131,8 +103,10 @@ class MediaDownloader(QThread):
|
|||||||
self.filename_format = filename_format
|
self.filename_format = filename_format
|
||||||
self.media_type = media_type
|
self.media_type = media_type
|
||||||
self.batch_size = batch_size
|
self.batch_size = batch_size
|
||||||
|
self.convert_gif = convert_gif
|
||||||
self._is_cancelled = False
|
self._is_cancelled = False
|
||||||
self._download_lock = asyncio.Lock()
|
self._download_lock = asyncio.Lock()
|
||||||
|
self.filepath_map = []
|
||||||
|
|
||||||
def cancel(self):
|
def cancel(self):
|
||||||
self._is_cancelled = True
|
self._is_cancelled = True
|
||||||
@@ -141,7 +115,6 @@ class MediaDownloader(QThread):
|
|||||||
try:
|
try:
|
||||||
if os.path.exists(filepath):
|
if os.path.exists(filepath):
|
||||||
return True, True
|
return True, True
|
||||||
|
|
||||||
if self._is_cancelled:
|
if self._is_cancelled:
|
||||||
return False, False
|
return False, False
|
||||||
|
|
||||||
@@ -183,7 +156,28 @@ class MediaDownloader(QThread):
|
|||||||
formatted_date = date.strftime("%Y%m%d_%H%M%S")
|
formatted_date = date.strftime("%Y%m%d_%H%M%S")
|
||||||
tweet_id = str(item.get('tweet_id', ''))
|
tweet_id = str(item.get('tweet_id', ''))
|
||||||
|
|
||||||
extension = 'mp4' if 'video.twimg.com' in url else 'jpg'
|
item_type = item.get('type', '')
|
||||||
|
if item_type == 'animated_gif':
|
||||||
|
media_type_folder = 'gif'
|
||||||
|
extension = 'mp4'
|
||||||
|
elif item_type == 'video' or 'video.twimg.com' in url:
|
||||||
|
media_type_folder = 'video'
|
||||||
|
extension = 'mp4'
|
||||||
|
else:
|
||||||
|
media_type_folder = 'image'
|
||||||
|
extension = 'jpg'
|
||||||
|
|
||||||
|
if self.media_type == "all":
|
||||||
|
media_output_dir = os.path.join(self.output_dir, media_type_folder)
|
||||||
|
else:
|
||||||
|
if self.media_type == "image":
|
||||||
|
media_output_dir = os.path.join(self.output_dir, "image")
|
||||||
|
elif self.media_type == "video":
|
||||||
|
media_output_dir = os.path.join(self.output_dir, "video")
|
||||||
|
elif self.media_type == "gif":
|
||||||
|
media_output_dir = os.path.join(self.output_dir, "gif")
|
||||||
|
else:
|
||||||
|
media_output_dir = self.output_dir
|
||||||
|
|
||||||
if self.filename_format == "username_date":
|
if self.filename_format == "username_date":
|
||||||
base_filename = f"{self.username}_{formatted_date}_{tweet_id}"
|
base_filename = f"{self.username}_{formatted_date}_{tweet_id}"
|
||||||
@@ -197,8 +191,8 @@ class MediaDownloader(QThread):
|
|||||||
counter += 1
|
counter += 1
|
||||||
|
|
||||||
used_filenames.add(filename)
|
used_filenames.add(filename)
|
||||||
filepath = os.path.join(self.output_dir, filename)
|
filepath = os.path.join(media_output_dir, filename)
|
||||||
|
self.filepath_map.append((item, filepath))
|
||||||
task = asyncio.create_task(self.download_file(session, url, filepath))
|
task = asyncio.create_task(self.download_file(session, url, filepath))
|
||||||
tasks.append(task)
|
tasks.append(task)
|
||||||
|
|
||||||
@@ -244,6 +238,30 @@ class MediaDownloader(QThread):
|
|||||||
try:
|
try:
|
||||||
completed, skipped, failed = asyncio.run(self.download_all())
|
completed, skipped, failed = asyncio.run(self.download_all())
|
||||||
|
|
||||||
|
if getattr(self, 'convert_gif', False):
|
||||||
|
try:
|
||||||
|
ffmpeg_exe = imageio_ffmpeg.get_ffmpeg_exe()
|
||||||
|
gif_items = [(item, fp) for item, fp in self.filepath_map if item.get('type') == 'animated_gif']
|
||||||
|
total_gifs = len(gif_items)
|
||||||
|
if total_gifs > 0:
|
||||||
|
creationflags = subprocess.CREATE_NO_WINDOW if sys.platform == 'win32' else 0
|
||||||
|
self.progress.emit(0)
|
||||||
|
self.status_update.emit("Starting GIF conversion...")
|
||||||
|
for idx, (item, fp) in enumerate(gif_items, start=1):
|
||||||
|
gif_fp = fp.rsplit('.', 1)[0] + '.gif'
|
||||||
|
result = subprocess.run([ffmpeg_exe, '-i', fp, gif_fp], capture_output=True, creationflags=creationflags)
|
||||||
|
if result.returncode == 0 and os.path.exists(gif_fp):
|
||||||
|
try:
|
||||||
|
os.remove(fp)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
conv_progress = int((idx / total_gifs) * 100)
|
||||||
|
self.progress.emit(conv_progress)
|
||||||
|
self.status_update.emit(f"Converting GIF {idx}/{total_gifs}...")
|
||||||
|
self.status_update.emit("GIF conversion completed")
|
||||||
|
except Exception as conv_e:
|
||||||
|
self.status_update.emit(f"GIF conversion error: {conv_e}")
|
||||||
|
|
||||||
if self._is_cancelled:
|
if self._is_cancelled:
|
||||||
self.status_update.emit("Download cancelled")
|
self.status_update.emit("Download cancelled")
|
||||||
return
|
return
|
||||||
@@ -302,7 +320,7 @@ class UpdateDialog(QDialog):
|
|||||||
class TwitterMediaDownloaderGUI(QMainWindow):
|
class TwitterMediaDownloaderGUI(QMainWindow):
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
self.current_version = "1.9"
|
self.current_version = "2.7"
|
||||||
self.setWindowTitle("Twitter/X Media Batch Downloader")
|
self.setWindowTitle("Twitter/X Media Batch Downloader")
|
||||||
|
|
||||||
self.settings = QSettings('TwitterMediaDownloader', 'Settings')
|
self.settings = QSettings('TwitterMediaDownloader', 'Settings')
|
||||||
@@ -324,6 +342,10 @@ class TwitterMediaDownloaderGUI(QMainWindow):
|
|||||||
|
|
||||||
self.media_info = None
|
self.media_info = None
|
||||||
self.init_ui()
|
self.init_ui()
|
||||||
|
if not self.settings.contains('download_batch_size'):
|
||||||
|
index = self.download_batch_combo.findText("25")
|
||||||
|
if index >= 0:
|
||||||
|
self.download_batch_combo.setCurrentIndex(index)
|
||||||
self.load_settings()
|
self.load_settings()
|
||||||
self.setup_auto_save()
|
self.setup_auto_save()
|
||||||
self.clean_username = None
|
self.clean_username = None
|
||||||
@@ -370,8 +392,7 @@ class TwitterMediaDownloaderGUI(QMainWindow):
|
|||||||
self.tab_widget.addTab(self.main_tab, "Main")
|
self.tab_widget.addTab(self.main_tab, "Main")
|
||||||
self.tab_widget.addTab(self.settings_tab, "Settings")
|
self.tab_widget.addTab(self.settings_tab, "Settings")
|
||||||
|
|
||||||
self.main_layout.addWidget(self.tab_widget)
|
self.main_layout.addWidget(self.tab_widget)
|
||||||
|
|
||||||
self.input_widget = QWidget()
|
self.input_widget = QWidget()
|
||||||
input_layout = QVBoxLayout(self.input_widget)
|
input_layout = QVBoxLayout(self.input_widget)
|
||||||
input_layout.setSpacing(10)
|
input_layout.setSpacing(10)
|
||||||
@@ -430,18 +451,14 @@ class TwitterMediaDownloaderGUI(QMainWindow):
|
|||||||
first_row_layout = QHBoxLayout()
|
first_row_layout = QHBoxLayout()
|
||||||
first_row_layout.setSpacing(5)
|
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 = QCheckBox("Batch")
|
||||||
self.batch_checkbox.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
|
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)
|
self.batch_checkbox.stateChanged.connect(self.handle_batch_checkbox)
|
||||||
first_row_layout.addWidget(self.batch_checkbox)
|
first_row_layout.addWidget(self.batch_checkbox)
|
||||||
|
|
||||||
size_label = QLabel("Size:")
|
self.size_label = QLabel("Size:")
|
||||||
first_row_layout.addWidget(size_label)
|
first_row_layout.addWidget(self.size_label)
|
||||||
|
|
||||||
self.batch_size_combo = QComboBox()
|
self.batch_size_combo = QComboBox()
|
||||||
self.batch_size_combo.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
|
self.batch_size_combo.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
|
||||||
@@ -451,6 +468,13 @@ class TwitterMediaDownloaderGUI(QMainWindow):
|
|||||||
self.batch_size_combo.setCurrentIndex(1)
|
self.batch_size_combo.setCurrentIndex(1)
|
||||||
first_row_layout.addWidget(self.batch_size_combo)
|
first_row_layout.addWidget(self.batch_size_combo)
|
||||||
|
|
||||||
|
self.convert_gif_checkbox = QCheckBox("Convert GIF")
|
||||||
|
self.convert_gif_checkbox.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
|
||||||
|
first_row_layout.addWidget(self.convert_gif_checkbox)
|
||||||
|
|
||||||
|
self.size_label.hide()
|
||||||
|
self.batch_size_combo.hide()
|
||||||
|
|
||||||
first_row_layout.addSpacing(5)
|
first_row_layout.addSpacing(5)
|
||||||
|
|
||||||
timeline_label = QLabel("Timeline Type:")
|
timeline_label = QLabel("Timeline Type:")
|
||||||
@@ -470,12 +494,12 @@ class TwitterMediaDownloaderGUI(QMainWindow):
|
|||||||
|
|
||||||
first_row_layout.addSpacing(5)
|
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 = QComboBox()
|
||||||
self.media_type_combo.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
|
self.media_type_combo.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
|
||||||
self.media_type_combo.setFixedWidth(85)
|
self.media_type_combo.setFixedWidth(85)
|
||||||
media_types = [
|
media_types = [
|
||||||
('all', 'All Media'),
|
('all', 'All'),
|
||||||
('image', 'Image'),
|
('image', 'Image'),
|
||||||
('video', 'Video'),
|
('video', 'Video'),
|
||||||
('gif', 'GIF')
|
('gif', 'GIF')
|
||||||
@@ -492,24 +516,22 @@ class TwitterMediaDownloaderGUI(QMainWindow):
|
|||||||
self.settings_tab_layout.addWidget(download_settings_label)
|
self.settings_tab_layout.addWidget(download_settings_label)
|
||||||
|
|
||||||
batch_download_item_layout = QHBoxLayout()
|
batch_download_item_layout = QHBoxLayout()
|
||||||
batch_download_label = QLabel("Batch Download Items:")
|
batch_download_label = QLabel("Batch Size:")
|
||||||
self.download_batch_combo = QComboBox()
|
self.download_batch_combo = QComboBox()
|
||||||
self.download_batch_combo.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
|
self.download_batch_combo.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
|
||||||
self.download_batch_combo.setFixedWidth(80)
|
self.download_batch_combo.setFixedWidth(80)
|
||||||
for size in range(5, 101, 5):
|
for size in range(5, 101, 5):
|
||||||
self.download_batch_combo.addItem(str(size))
|
self.download_batch_combo.addItem(str(size))
|
||||||
index = self.download_batch_combo.findText("25")
|
|
||||||
if index >= 0:
|
|
||||||
self.download_batch_combo.setCurrentIndex(index)
|
|
||||||
batch_download_item_layout.addWidget(batch_download_label)
|
batch_download_item_layout.addWidget(batch_download_label)
|
||||||
batch_download_item_layout.addWidget(self.download_batch_combo)
|
batch_download_item_layout.addWidget(self.download_batch_combo)
|
||||||
|
batch_download_item_layout.addWidget(self.convert_gif_checkbox)
|
||||||
batch_download_item_layout.addStretch()
|
batch_download_item_layout.addStretch()
|
||||||
self.settings_tab_layout.addLayout(batch_download_item_layout)
|
self.settings_tab_layout.addLayout(batch_download_item_layout)
|
||||||
|
|
||||||
filename_layout = QHBoxLayout()
|
filename_layout = QHBoxLayout()
|
||||||
filename_label = QLabel("Filename Format:")
|
filename_label = QLabel("Filename Format:")
|
||||||
self.format_username = QRadioButton("Username - Post Date")
|
self.format_username = QRadioButton("Username - Date")
|
||||||
self.format_date = QRadioButton("Post Date - Username")
|
self.format_date = QRadioButton("Date - Username")
|
||||||
self.format_username.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
|
self.format_username.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
|
||||||
self.format_date.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
|
self.format_date.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
|
||||||
filename_layout.addWidget(filename_label)
|
filename_layout.addWidget(filename_label)
|
||||||
@@ -624,8 +646,18 @@ class TwitterMediaDownloaderGUI(QMainWindow):
|
|||||||
|
|
||||||
bottom_layout = QHBoxLayout()
|
bottom_layout = QHBoxLayout()
|
||||||
|
|
||||||
|
status_container = QWidget()
|
||||||
|
status_layout = QHBoxLayout(status_container)
|
||||||
|
status_layout.setContentsMargins(0, 0, 0, 0)
|
||||||
|
status_layout.setSpacing(5)
|
||||||
|
|
||||||
|
self.version_label = QLabel("v2.7 (gallery-dl v1.30.0)")
|
||||||
|
status_layout.addWidget(self.version_label)
|
||||||
|
|
||||||
self.status_label = QLabel("")
|
self.status_label = QLabel("")
|
||||||
bottom_layout.addWidget(self.status_label, stretch=1)
|
status_layout.addWidget(self.status_label, stretch=1)
|
||||||
|
|
||||||
|
bottom_layout.addWidget(status_container, stretch=1)
|
||||||
|
|
||||||
self.update_button = QPushButton()
|
self.update_button = QPushButton()
|
||||||
icon_path = os.path.join(os.path.dirname(__file__), "update.svg")
|
icon_path = os.path.join(os.path.dirname(__file__), "update.svg")
|
||||||
@@ -663,38 +695,36 @@ class TwitterMediaDownloaderGUI(QMainWindow):
|
|||||||
self.auto_batch_button.clicked.disconnect(self.stop_auto_batch)
|
self.auto_batch_button.clicked.disconnect(self.stop_auto_batch)
|
||||||
self.auto_batch_button.clicked.connect(self.start_auto_batch)
|
self.auto_batch_button.clicked.connect(self.start_auto_batch)
|
||||||
self.next_batch_button.setEnabled(True)
|
self.next_batch_button.setEnabled(True)
|
||||||
self.status_label.setText(f"Auto batch stopped. Total: {len(self.media_info['timeline']):,} media items")
|
self.set_status_text(f"Auto batch stopped. Total: {len(self.media_info['timeline']):,} media items")
|
||||||
|
|
||||||
def fetch_next_batch_auto(self):
|
def fetch_next_batch_auto(self):
|
||||||
if not self.auto_batch_running:
|
if not self.auto_batch_running:
|
||||||
return
|
return
|
||||||
|
|
||||||
if not self.media_info:
|
if not self.media_info:
|
||||||
self.status_label.setText("No profile information available")
|
self.set_status_text("No profile information available")
|
||||||
self.stop_auto_batch()
|
self.stop_auto_batch()
|
||||||
return
|
return
|
||||||
|
|
||||||
username = self.url_input.text().strip()
|
username = self.url_input.text().strip()
|
||||||
auth_token = self.auth_input.text().strip()
|
auth_token = self.auth_input.text().strip()
|
||||||
|
|
||||||
if not username or not auth_token:
|
if not username or not auth_token:
|
||||||
self.status_label.setText("Username or auth token missing")
|
self.set_status_text("Username or auth token missing")
|
||||||
self.stop_auto_batch()
|
self.stop_auto_batch()
|
||||||
return
|
return
|
||||||
|
|
||||||
self.current_page += 1
|
self.current_page += 1
|
||||||
self.status_label.setText(f"Auto fetching batch {self.current_page + 1}...")
|
self.set_status_text(f"Auto fetching batch {self.current_page + 1}...")
|
||||||
|
|
||||||
timeline_type = self.timeline_type_combo.currentData()
|
timeline_type = self.timeline_type_combo.currentData()
|
||||||
media_type = self.media_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())
|
batch_size = int(self.batch_size_combo.currentText())
|
||||||
|
|
||||||
self.fetcher = MetadataFetcher(
|
self.fetcher = MetadataFetcher(
|
||||||
username,
|
username,
|
||||||
timeline_type,
|
timeline_type,
|
||||||
media_type,
|
media_type,
|
||||||
use_api,
|
|
||||||
True,
|
True,
|
||||||
batch_size,
|
batch_size,
|
||||||
self.current_page
|
self.current_page
|
||||||
@@ -711,7 +741,7 @@ class TwitterMediaDownloaderGUI(QMainWindow):
|
|||||||
|
|
||||||
timeline = info.get('timeline', [])
|
timeline = info.get('timeline', [])
|
||||||
if not timeline:
|
if not timeline:
|
||||||
self.status_label.setText("No more media items found")
|
self.set_status_text("No more media items found")
|
||||||
self.stop_auto_batch()
|
self.stop_auto_batch()
|
||||||
self.next_batch_button.hide()
|
self.next_batch_button.hide()
|
||||||
return
|
return
|
||||||
@@ -724,28 +754,34 @@ class TwitterMediaDownloaderGUI(QMainWindow):
|
|||||||
media_count = len(self.media_info['timeline'])
|
media_count = len(self.media_info['timeline'])
|
||||||
new_items = len(timeline)
|
new_items = len(timeline)
|
||||||
|
|
||||||
self.status_label.setText(f"Auto batch: Added {new_items:,} items. Total: {media_count:,} media items")
|
self.set_status_text(f"Auto batch: Added {new_items:,} items. Total: {media_count:,} media items")
|
||||||
|
|
||||||
has_more = info.get('metadata', {}).get('has_more', False)
|
has_more = info.get('metadata', {}).get('has_more', False)
|
||||||
if not has_more:
|
if not has_more:
|
||||||
self.stop_auto_batch()
|
self.stop_auto_batch()
|
||||||
self.next_batch_button.hide()
|
self.next_batch_button.hide()
|
||||||
self.status_label.setText(f"Auto batch complete! All {media_count:,} media items fetched. No more items available.")
|
self.set_status_text(f"Auto batch complete! All {media_count:,} media items fetched. No more items available.")
|
||||||
return
|
return
|
||||||
|
|
||||||
QTimer.singleShot(500, self.fetch_next_batch_auto)
|
QTimer.singleShot(500, self.fetch_next_batch_auto)
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
self.status_label.setText(f"Error processing auto batch: {str(e)}")
|
self.set_status_text(f"Error processing auto batch: {str(e)}")
|
||||||
self.stop_auto_batch()
|
self.stop_auto_batch()
|
||||||
|
|
||||||
def handle_auto_batch_error(self, error):
|
def handle_auto_batch_error(self, error):
|
||||||
self.status_label.setText(f"Auto batch error: {error}")
|
self.set_status_text(f"Auto batch error: {error}")
|
||||||
self.stop_auto_batch()
|
self.stop_auto_batch()
|
||||||
|
|
||||||
def handle_batch_checkbox(self, state):
|
def handle_batch_checkbox(self, state):
|
||||||
|
if self.batch_checkbox.isChecked():
|
||||||
|
self.size_label.show()
|
||||||
|
self.batch_size_combo.show()
|
||||||
|
else:
|
||||||
|
self.size_label.hide()
|
||||||
|
self.batch_size_combo.hide()
|
||||||
|
|
||||||
if hasattr(self, 'media_info') and self.media_info:
|
if hasattr(self, 'media_info') and self.media_info:
|
||||||
if state == Qt.CheckState.Checked and self.media_info.get('metadata', {}).get('has_more', False):
|
if self.batch_checkbox.isChecked() and self.media_info.get('metadata', {}).get('has_more', False):
|
||||||
self.next_batch_button.show()
|
self.next_batch_button.show()
|
||||||
self.auto_batch_button.show()
|
self.auto_batch_button.show()
|
||||||
else:
|
else:
|
||||||
@@ -763,10 +799,10 @@ class TwitterMediaDownloaderGUI(QMainWindow):
|
|||||||
self.format_username.toggled.connect(self.auto_save_settings)
|
self.format_username.toggled.connect(self.auto_save_settings)
|
||||||
self.media_type_combo.currentTextChanged.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.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.batch_checkbox.stateChanged.connect(self.auto_save_settings)
|
||||||
self.download_batch_combo.currentTextChanged.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)
|
self.batch_size_combo.currentTextChanged.connect(self.auto_save_settings)
|
||||||
|
self.convert_gif_checkbox.stateChanged.connect(self.auto_save_settings)
|
||||||
|
|
||||||
def auto_save_settings(self):
|
def auto_save_settings(self):
|
||||||
try:
|
try:
|
||||||
@@ -777,13 +813,13 @@ class TwitterMediaDownloaderGUI(QMainWindow):
|
|||||||
'username_date' if self.format_username.isChecked() else 'date_username')
|
'username_date' if self.format_username.isChecked() else 'date_username')
|
||||||
self.settings.setValue('media_type', self.media_type_combo.currentData())
|
self.settings.setValue('media_type', self.media_type_combo.currentData())
|
||||||
self.settings.setValue('timeline_type', self.timeline_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()
|
batch_mode = self.batch_checkbox.isChecked()
|
||||||
self.settings.setValue('batch_mode', batch_mode)
|
self.settings.setValue('batch_mode', batch_mode)
|
||||||
|
|
||||||
self.settings.setValue('download_batch_size', self.download_batch_combo.currentText())
|
self.settings.setValue('download_batch_size', self.download_batch_combo.currentText())
|
||||||
self.settings.setValue('fetch_batch_size', self.batch_size_combo.currentText())
|
self.settings.setValue('fetch_batch_size', self.batch_size_combo.currentText())
|
||||||
|
self.settings.setValue('convert_gif', self.convert_gif_checkbox.isChecked())
|
||||||
self.settings.sync()
|
self.settings.sync()
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
pass
|
pass
|
||||||
@@ -810,30 +846,35 @@ class TwitterMediaDownloaderGUI(QMainWindow):
|
|||||||
self.timeline_type_combo.setCurrentIndex(i)
|
self.timeline_type_combo.setCurrentIndex(i)
|
||||||
break
|
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)
|
batch_mode = self.settings.value('batch_mode', False, type=bool)
|
||||||
|
|
||||||
self.batch_checkbox.blockSignals(True)
|
self.batch_checkbox.blockSignals(True)
|
||||||
self.batch_checkbox.setChecked(batch_mode)
|
self.batch_checkbox.setChecked(batch_mode)
|
||||||
self.batch_checkbox.blockSignals(False)
|
self.batch_checkbox.blockSignals(False)
|
||||||
|
|
||||||
|
if batch_mode:
|
||||||
|
self.size_label.show()
|
||||||
|
self.batch_size_combo.show()
|
||||||
|
else:
|
||||||
|
self.size_label.hide()
|
||||||
|
self.batch_size_combo.hide()
|
||||||
|
|
||||||
fetch_batch_size = str(self.settings.value('fetch_batch_size', '100'))
|
fetch_batch_size = str(self.settings.value('fetch_batch_size', '100'))
|
||||||
index = self.batch_size_combo.findText(fetch_batch_size)
|
index = self.batch_size_combo.findText(fetch_batch_size)
|
||||||
if index >= 0:
|
if index >= 0:
|
||||||
self.batch_size_combo.setCurrentIndex(index)
|
self.batch_size_combo.setCurrentIndex(index)
|
||||||
|
|
||||||
download_batch_size = str(self.settings.value('download_batch_size', '25'))
|
download_batch_size = str(self.settings.value('download_batch_size', '25'))
|
||||||
index = self.download_batch_combo.findText(download_batch_size)
|
index = self.download_batch_combo.findText(download_batch_size)
|
||||||
if index >= 0:
|
if index >= 0:
|
||||||
self.download_batch_combo.setCurrentIndex(index)
|
self.download_batch_combo.setCurrentIndex(index)
|
||||||
else:
|
else:
|
||||||
index = self.download_batch_combo.findText("25")
|
self.download_batch_combo.setCurrentIndex(0)
|
||||||
if index >= 0:
|
|
||||||
self.download_batch_combo.setCurrentIndex(index)
|
convert_gif = self.settings.value('convert_gif', False, type=bool)
|
||||||
else:
|
self.convert_gif_checkbox.blockSignals(True)
|
||||||
self.download_batch_combo.setCurrentIndex(0)
|
self.convert_gif_checkbox.setChecked(convert_gif)
|
||||||
|
self.convert_gif_checkbox.blockSignals(False)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
@@ -853,24 +894,30 @@ class TwitterMediaDownloaderGUI(QMainWindow):
|
|||||||
else:
|
else:
|
||||||
subprocess.run(['xdg-open', output_dir])
|
subprocess.run(['xdg-open', output_dir])
|
||||||
|
|
||||||
|
def set_status_text(self, text):
|
||||||
|
self.status_label.setText(text)
|
||||||
|
if text:
|
||||||
|
self.version_label.hide()
|
||||||
|
else:
|
||||||
|
self.version_label.show()
|
||||||
|
|
||||||
def fetch_metadata(self):
|
def fetch_metadata(self):
|
||||||
self.current_page = 0
|
self.current_page = 0
|
||||||
username = self.url_input.text().strip()
|
username = self.url_input.text().strip()
|
||||||
if not username:
|
if not username:
|
||||||
self.status_label.setText("Please enter a username or URL")
|
self.set_status_text("Please enter a username or URL")
|
||||||
return
|
return
|
||||||
|
|
||||||
auth_token = self.auth_input.text().strip()
|
auth_token = self.auth_input.text().strip()
|
||||||
if not auth_token:
|
if not auth_token:
|
||||||
self.status_label.setText("Please enter your auth token")
|
self.set_status_text("Please enter your auth token")
|
||||||
return
|
return
|
||||||
|
|
||||||
self.fetch_button.setEnabled(False)
|
self.fetch_button.setEnabled(False)
|
||||||
self.status_label.setText("Fetching profile information...")
|
self.set_status_text("Fetching profile information...")
|
||||||
|
|
||||||
timeline_type = self.timeline_type_combo.currentData()
|
timeline_type = self.timeline_type_combo.currentData()
|
||||||
media_type = self.media_type_combo.currentData()
|
media_type = self.media_type_combo.currentData()
|
||||||
use_api = self.use_api_checkbox.isChecked()
|
|
||||||
batch_mode = self.batch_checkbox.isChecked()
|
batch_mode = self.batch_checkbox.isChecked()
|
||||||
batch_size = int(self.batch_size_combo.currentText()) if batch_mode else 100
|
batch_size = int(self.batch_size_combo.currentText()) if batch_mode else 100
|
||||||
|
|
||||||
@@ -878,7 +925,6 @@ class TwitterMediaDownloaderGUI(QMainWindow):
|
|||||||
username,
|
username,
|
||||||
timeline_type,
|
timeline_type,
|
||||||
media_type,
|
media_type,
|
||||||
use_api,
|
|
||||||
batch_mode,
|
batch_mode,
|
||||||
batch_size,
|
batch_size,
|
||||||
self.current_page
|
self.current_page
|
||||||
@@ -890,30 +936,28 @@ class TwitterMediaDownloaderGUI(QMainWindow):
|
|||||||
|
|
||||||
def fetch_next_batch(self):
|
def fetch_next_batch(self):
|
||||||
if not self.media_info:
|
if not self.media_info:
|
||||||
self.status_label.setText("No profile information available")
|
self.set_status_text("No profile information available")
|
||||||
return
|
return
|
||||||
|
|
||||||
username = self.url_input.text().strip()
|
username = self.url_input.text().strip()
|
||||||
auth_token = self.auth_input.text().strip()
|
auth_token = self.auth_input.text().strip()
|
||||||
|
|
||||||
if not username or not auth_token:
|
if not username or not auth_token:
|
||||||
self.status_label.setText("Username or auth token missing")
|
self.set_status_text("Username or auth token missing")
|
||||||
return
|
return
|
||||||
|
|
||||||
self.current_page += 1
|
self.current_page += 1
|
||||||
self.next_batch_button.setEnabled(False)
|
self.next_batch_button.setEnabled(False)
|
||||||
self.status_label.setText(f"Fetching batch {self.current_page + 1}...")
|
self.set_status_text(f"Fetching batch {self.current_page + 1}...")
|
||||||
|
|
||||||
timeline_type = self.timeline_type_combo.currentData()
|
timeline_type = self.timeline_type_combo.currentData()
|
||||||
media_type = self.media_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())
|
batch_size = int(self.batch_size_combo.currentText())
|
||||||
|
|
||||||
self.fetcher = MetadataFetcher(
|
self.fetcher = MetadataFetcher(
|
||||||
username,
|
username,
|
||||||
timeline_type,
|
timeline_type,
|
||||||
media_type,
|
media_type,
|
||||||
use_api,
|
|
||||||
True,
|
True,
|
||||||
batch_size,
|
batch_size,
|
||||||
self.current_page
|
self.current_page
|
||||||
@@ -930,7 +974,7 @@ class TwitterMediaDownloaderGUI(QMainWindow):
|
|||||||
|
|
||||||
timeline = info.get('timeline', [])
|
timeline = info.get('timeline', [])
|
||||||
if not timeline:
|
if not timeline:
|
||||||
self.status_label.setText("No more media items found")
|
self.set_status_text("No more media items found")
|
||||||
self.next_batch_button.setEnabled(True)
|
self.next_batch_button.setEnabled(True)
|
||||||
return
|
return
|
||||||
|
|
||||||
@@ -942,17 +986,17 @@ class TwitterMediaDownloaderGUI(QMainWindow):
|
|||||||
media_count = len(self.media_info['timeline'])
|
media_count = len(self.media_info['timeline'])
|
||||||
new_items = len(timeline)
|
new_items = len(timeline)
|
||||||
|
|
||||||
self.status_label.setText(f"Added {new_items:,} items. Total: {media_count:,} media items")
|
self.set_status_text(f"Added {new_items:,} items. Total: {media_count:,} media items")
|
||||||
self.next_batch_button.setEnabled(True)
|
self.next_batch_button.setEnabled(True)
|
||||||
|
|
||||||
has_more = info.get('metadata', {}).get('has_more', False)
|
has_more = info.get('metadata', {}).get('has_more', False)
|
||||||
if not has_more:
|
if not has_more:
|
||||||
self.next_batch_button.hide()
|
self.next_batch_button.hide()
|
||||||
self.auto_batch_button.hide()
|
self.auto_batch_button.hide()
|
||||||
self.status_label.setText(f"All {media_count:,} media items fetched. No more items available.")
|
self.set_status_text(f"All {media_count:,} media items fetched. No more items available.")
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
self.status_label.setText(f"Error processing batch: {str(e)}")
|
self.set_status_text(f"Error processing batch: {str(e)}")
|
||||||
self.next_batch_button.setEnabled(True)
|
self.next_batch_button.setEnabled(True)
|
||||||
|
|
||||||
def handle_profile_info(self, info):
|
def handle_profile_info(self, info):
|
||||||
@@ -960,9 +1004,18 @@ class TwitterMediaDownloaderGUI(QMainWindow):
|
|||||||
if not info or not isinstance(info, dict):
|
if not info or not isinstance(info, dict):
|
||||||
raise ValueError("Invalid info data received")
|
raise ValueError("Invalid info data received")
|
||||||
|
|
||||||
|
if 'error' in info:
|
||||||
|
error_type = info['error']
|
||||||
|
if error_type == "withheld":
|
||||||
|
self.set_status_text("Please use the Userscript version for withheld accounts.")
|
||||||
|
else:
|
||||||
|
self.set_status_text("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', {})
|
account_info = info.get('account_info', {})
|
||||||
if not account_info:
|
if not account_info:
|
||||||
self.status_label.setText("Failed to fetch profile information")
|
self.set_status_text("Failed to fetch profile information")
|
||||||
self.fetch_button.setEnabled(True)
|
self.fetch_button.setEnabled(True)
|
||||||
return
|
return
|
||||||
|
|
||||||
@@ -1003,9 +1056,9 @@ class TwitterMediaDownloaderGUI(QMainWindow):
|
|||||||
elif media_type == "gif":
|
elif media_type == "gif":
|
||||||
media_type_str = "GIF"
|
media_type_str = "GIF"
|
||||||
|
|
||||||
self.status_label.setText(f"Successfully fetched {media_count:,} {media_type_str} items")
|
self.set_status_text(f"Successfully fetched {media_count:,} {media_type_str} items")
|
||||||
except Exception as ui_error:
|
except Exception as ui_error:
|
||||||
self.status_label.setText(f"Error updating UI: {str(ui_error)}")
|
self.set_status_text(f"Error updating UI: {str(ui_error)}")
|
||||||
return
|
return
|
||||||
|
|
||||||
if is_withheld:
|
if is_withheld:
|
||||||
@@ -1071,11 +1124,11 @@ class TwitterMediaDownloaderGUI(QMainWindow):
|
|||||||
self.user_output_dir = os.path.join(output_base, self.clean_username)
|
self.user_output_dir = os.path.join(output_base, self.clean_username)
|
||||||
os.makedirs(self.user_output_dir, exist_ok=True)
|
os.makedirs(self.user_output_dir, exist_ok=True)
|
||||||
except Exception as dir_error:
|
except Exception as dir_error:
|
||||||
self.status_label.setText(f"Error creating output directory: {str(dir_error)}")
|
self.set_status_text(f"Error creating output directory: {str(dir_error)}")
|
||||||
return
|
return
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
self.status_label.setText(f"Error processing profile info: {str(e)}")
|
self.set_status_text(f"Error processing profile info: {str(e)}")
|
||||||
self.fetch_button.setEnabled(True)
|
self.fetch_button.setEnabled(True)
|
||||||
|
|
||||||
def update_profile_image(self, image_data):
|
def update_profile_image(self, image_data):
|
||||||
@@ -1106,19 +1159,20 @@ class TwitterMediaDownloaderGUI(QMainWindow):
|
|||||||
self.next_batch_button.setEnabled(True)
|
self.next_batch_button.setEnabled(True)
|
||||||
|
|
||||||
error_str = str(error)
|
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.set_status_text("Please use the Userscript version for withheld accounts.")
|
||||||
else:
|
else:
|
||||||
self.status_label.setText(f"Error fetching profile info: {error}")
|
self.set_status_text("Please check the 'Auth Token'.")
|
||||||
|
|
||||||
def start_download(self):
|
def start_download(self):
|
||||||
if not self.media_info:
|
if not self.media_info:
|
||||||
self.status_label.setText("Please fetch profile information first")
|
self.set_status_text("Please fetch profile information first")
|
||||||
return
|
return
|
||||||
|
|
||||||
auth_token = self.auth_input.text().strip()
|
auth_token = self.auth_input.text().strip()
|
||||||
if not auth_token:
|
if not auth_token:
|
||||||
self.status_label.setText("Please enter your auth token")
|
self.set_status_text("Please enter your auth token")
|
||||||
return
|
return
|
||||||
|
|
||||||
self.download_button.hide()
|
self.download_button.hide()
|
||||||
@@ -1127,11 +1181,12 @@ class TwitterMediaDownloaderGUI(QMainWindow):
|
|||||||
self.cancel_button.show()
|
self.cancel_button.show()
|
||||||
self.progress_bar.show()
|
self.progress_bar.show()
|
||||||
self.progress_bar.setValue(0)
|
self.progress_bar.setValue(0)
|
||||||
self.status_label.setText("Starting download...")
|
self.set_status_text("Starting download...")
|
||||||
|
|
||||||
filename_format = "username_date" if self.format_username.isChecked() else "date_username"
|
filename_format = "username_date" if self.format_username.isChecked() else "date_username"
|
||||||
batch_size = int(self.download_batch_combo.currentText())
|
batch_size = int(self.download_batch_combo.currentText())
|
||||||
media_type = self.media_type_combo.currentData()
|
media_type = self.media_type_combo.currentData()
|
||||||
|
convert_gif = self.convert_gif_checkbox.isChecked()
|
||||||
|
|
||||||
self.worker = MediaDownloader(
|
self.worker = MediaDownloader(
|
||||||
self.media_info['timeline'],
|
self.media_info['timeline'],
|
||||||
@@ -1139,12 +1194,13 @@ class TwitterMediaDownloaderGUI(QMainWindow):
|
|||||||
filename_format,
|
filename_format,
|
||||||
self.clean_username,
|
self.clean_username,
|
||||||
media_type,
|
media_type,
|
||||||
batch_size
|
batch_size,
|
||||||
|
convert_gif
|
||||||
)
|
)
|
||||||
self.worker.progress.connect(self.update_progress)
|
self.worker.progress.connect(self.update_progress)
|
||||||
self.worker.finished.connect(self.download_finished)
|
self.worker.finished.connect(self.download_finished)
|
||||||
self.worker.error.connect(self.download_error)
|
self.worker.error.connect(self.download_error)
|
||||||
self.worker.status_update.connect(self.status_label.setText)
|
self.worker.status_update.connect(self.set_status_text)
|
||||||
self.worker.start()
|
self.worker.start()
|
||||||
|
|
||||||
def update_progress(self, value):
|
def update_progress(self, value):
|
||||||
@@ -1152,7 +1208,7 @@ class TwitterMediaDownloaderGUI(QMainWindow):
|
|||||||
|
|
||||||
def download_finished(self, message):
|
def download_finished(self, message):
|
||||||
self.progress_bar.hide()
|
self.progress_bar.hide()
|
||||||
self.status_label.setText(message)
|
self.set_status_text(message)
|
||||||
self.open_button.show()
|
self.open_button.show()
|
||||||
|
|
||||||
if self.batch_checkbox.isChecked() and self.media_info and self.media_info.get('metadata', {}).get('has_more', False):
|
if self.batch_checkbox.isChecked() and self.media_info and self.media_info.get('metadata', {}).get('has_more', False):
|
||||||
@@ -1168,7 +1224,7 @@ class TwitterMediaDownloaderGUI(QMainWindow):
|
|||||||
|
|
||||||
def download_error(self, error_message):
|
def download_error(self, error_message):
|
||||||
self.progress_bar.hide()
|
self.progress_bar.hide()
|
||||||
self.status_label.setText(f"Download error: {error_message}")
|
self.set_status_text(f"Download error: {error_message}")
|
||||||
self.download_button.setText("Retry")
|
self.download_button.setText("Retry")
|
||||||
self.download_button.show()
|
self.download_button.show()
|
||||||
self.cancel_button.show()
|
self.cancel_button.show()
|
||||||
@@ -1180,7 +1236,7 @@ class TwitterMediaDownloaderGUI(QMainWindow):
|
|||||||
def cancel_clicked(self):
|
def cancel_clicked(self):
|
||||||
if hasattr(self, 'worker') and self.worker.isRunning():
|
if hasattr(self, 'worker') and self.worker.isRunning():
|
||||||
self.worker.cancel()
|
self.worker.cancel()
|
||||||
self.status_label.setText("Cancelling download...")
|
self.set_status_text("Cancelling download...")
|
||||||
return
|
return
|
||||||
|
|
||||||
self.profile_widget.hide()
|
self.profile_widget.hide()
|
||||||
@@ -1192,7 +1248,7 @@ class TwitterMediaDownloaderGUI(QMainWindow):
|
|||||||
self.cancel_button.hide()
|
self.cancel_button.hide()
|
||||||
self.progress_bar.hide()
|
self.progress_bar.hide()
|
||||||
self.progress_bar.setValue(0)
|
self.progress_bar.setValue(0)
|
||||||
self.status_label.clear()
|
self.set_status_text("")
|
||||||
self.media_info = None
|
self.media_info = None
|
||||||
self.current_page = 0
|
self.current_page = 0
|
||||||
self.update_button.show()
|
self.update_button.show()
|
||||||
|
|||||||
+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.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:
|
try:
|
||||||
while items_fetched < items_to_fetch:
|
extractor.initialize()
|
||||||
item = next(iterator)
|
|
||||||
items_fetched += 1
|
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:
|
if hasattr(extractor, '_cursor') and extractor._cursor:
|
||||||
media_url = item[1]
|
pass
|
||||||
tweet_data = item[2]
|
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:
|
if isinstance(item, tuple) and len(item) >= 3:
|
||||||
user = tweet_data['user']
|
media_url = item[1]
|
||||||
user_date = user.get('date', '')
|
tweet_data = item[2]
|
||||||
if isinstance(user_date, datetime):
|
|
||||||
user_date = user_date.strftime("%Y-%m-%d %H:%M:%S")
|
|
||||||
|
|
||||||
structured_output['account_info'] = {
|
if not structured_output['account_info'] and 'user' in tweet_data:
|
||||||
'name': user.get('name', ''),
|
user = tweet_data['user']
|
||||||
'nick': user.get('nick', ''),
|
user_date = user.get('date', '')
|
||||||
'date': user_date,
|
if isinstance(user_date, datetime):
|
||||||
'followers_count': user.get('followers_count', 0),
|
user_date = user_date.strftime("%Y-%m-%d %H:%M:%S")
|
||||||
'friends_count': user.get('friends_count', 0),
|
|
||||||
'profile_image': user.get('profile_image', ''),
|
structured_output['account_info'] = {
|
||||||
'statuses_count': user.get('statuses_count', 0)
|
'name': user.get('name', ''),
|
||||||
}
|
'nick': user.get('nick', ''),
|
||||||
|
'date': user_date,
|
||||||
if 'pbs.twimg.com' in media_url or 'video.twimg.com' in media_url:
|
'followers_count': user.get('followers_count', 0),
|
||||||
tweet_date = tweet_data.get('date', datetime.now())
|
'friends_count': user.get('friends_count', 0),
|
||||||
if isinstance(tweet_date, datetime):
|
'profile_image': user.get('profile_image', ''),
|
||||||
tweet_date = tweet_date.strftime("%Y-%m-%d %H:%M:%S")
|
'statuses_count': user.get('statuses_count', 0)
|
||||||
|
}
|
||||||
|
|
||||||
timeline_entry = {
|
if 'pbs.twimg.com' in media_url or 'video.twimg.com' in media_url:
|
||||||
'url': media_url,
|
tweet_date = tweet_data.get('date', datetime.now())
|
||||||
'date': tweet_date,
|
if isinstance(tweet_date, datetime):
|
||||||
'tweet_id': tweet_data.get('tweet_id', 0),
|
tweet_date = tweet_date.strftime("%Y-%m-%d %H:%M:%S")
|
||||||
}
|
|
||||||
|
timeline_entry = {
|
||||||
if 'type' in tweet_data:
|
'url': media_url,
|
||||||
timeline_entry['type'] = tweet_data['type']
|
'date': tweet_date,
|
||||||
|
'tweet_id': tweet_data.get('tweet_id', 0),
|
||||||
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
|
if 'type' in tweet_data:
|
||||||
(media_type == 'gif' and 'video.twimg.com' in media_url and tweet_data.get('type') == 'animated_gif')
|
timeline_entry['type'] = tweet_data['type']
|
||||||
):
|
|
||||||
new_timeline_entries.append(timeline_entry)
|
if media_type == 'all' or (
|
||||||
structured_output['total_urls'] += 1
|
(media_type == 'image' and 'pbs.twimg.com' in media_url and tweet_data.get('type') == 'photo') or
|
||||||
except StopIteration:
|
(media_type == 'video' and 'video.twimg.com' in media_url and tweet_data.get('type') == 'video') or
|
||||||
pass
|
(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)
|
except Exception as e:
|
||||||
|
error_msg = str(e).lower()
|
||||||
cursor_info = None
|
if "withheld" in error_msg or e.__class__.__name__ == "ValueError" and str(e) == "withheld":
|
||||||
if hasattr(extractor, '_cursor') and extractor._cursor:
|
return {"error": "withheld"}
|
||||||
cursor_info = extractor._cursor
|
else:
|
||||||
|
error_str = str(e)
|
||||||
structured_output['metadata'] = {
|
if error_str == "None":
|
||||||
"new_entries": len(new_timeline_entries),
|
return {"error": "null"}
|
||||||
"page": page,
|
else:
|
||||||
"batch_size": batch_size,
|
return {"error": error_str}
|
||||||
"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
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
username = ""
|
username = ""
|
||||||
@@ -148,7 +176,11 @@ def main():
|
|||||||
)
|
)
|
||||||
print(json.dumps(data, ensure_ascii=False, indent=2))
|
print(json.dumps(data, ensure_ascii=False, indent=2))
|
||||||
except Exception as e:
|
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__':
|
if __name__ == '__main__':
|
||||||
main()
|
main()
|
||||||
+1
-1
@@ -1,3 +1,3 @@
|
|||||||
{
|
{
|
||||||
"version": "1.8"
|
"version": "2.6"
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user