Update v2.0

This commit is contained in:
afkarxyz committed 2025-03-25 18:44:06 +07:00
1 parent 967d91d370
commit 46e09532fc
2 files changed
+133 -90

No files matched your search

+17 -6
View File
@@ -302,7 +302,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.0"
self.setWindowTitle("Twitter/X Media Batch Downloader") self.setWindowTitle("Twitter/X Media Batch Downloader")
self.settings = QSettings('TwitterMediaDownloader', 'Settings') self.settings = QSettings('TwitterMediaDownloader', 'Settings')
@@ -437,6 +437,7 @@ class TwitterMediaDownloaderGUI(QMainWindow):
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)
@@ -470,12 +471,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')
@@ -960,6 +961,15 @@ 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.status_label.setText("Please enable the 'Use API' option.")
else:
self.status_label.setText("Please check the 'Auth Token' value. Your account may be 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.status_label.setText("Failed to fetch profile information")
@@ -1106,10 +1116,11 @@ 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.status_label.setText("Please enable the 'Use API' option.")
else: else:
self.status_label.setText(f"Error fetching profile info: {error}") self.status_label.setText("Please check the 'Auth Token'.")
def start_download(self): def start_download(self):
if not self.media_info: if not self.media_info:
+116 -84
View File
@@ -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
if isinstance(item, tuple) and len(item) >= 3: api = twitter.TwitterAPI(extractor)
media_url = item[1] try:
tweet_data = item[2] if username.startswith("id:"):
user = api.user_by_rest_id(username[3:])
else:
user = api.user_by_screen_name(username)
if not structured_output['account_info'] and 'user' in tweet_data: if "legacy" in user and user["legacy"].get("withheld_scope"):
user = tweet_data['user'] raise ValueError("withheld")
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'] = { except Exception as e:
'name': user.get('name', ''), error_msg = str(e).lower()
'nick': user.get('nick', ''), if "withheld" in error_msg or (hasattr(e, "response") and "withheld" in str(e.response.text).lower()):
'date': user_date, raise ValueError("withheld")
'followers_count': user.get('followers_count', 0), raise
'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: structured_output = {
tweet_date = tweet_data.get('date', datetime.now()) 'account_info': {},
if isinstance(tweet_date, datetime): 'total_urls': 0,
tweet_date = tweet_date.strftime("%Y-%m-%d %H:%M:%S") 'timeline': []
}
timeline_entry = { iterator = iter(extractor)
'url': media_url,
'date': tweet_date,
'tweet_id': tweet_data.get('tweet_id', 0),
}
if 'type' in tweet_data: if batch_size > 0 and page > 0:
timeline_entry['type'] = tweet_data['type'] items_to_skip = page * batch_size
if media_type == 'all' or ( if hasattr(extractor, '_cursor') and extractor._cursor:
(media_type == 'image' and 'pbs.twimg.com' in media_url and tweet_data.get('type') == 'photo') or pass
(media_type == 'video' and 'video.twimg.com' in media_url and tweet_data.get('type') == 'video') or else:
(media_type == 'gif' and 'video.twimg.com' in media_url and tweet_data.get('type') == 'animated_gif') skipped = 0
): try:
new_timeline_entries.append(timeline_entry) for _ in range(items_to_skip):
structured_output['total_urls'] += 1 next(iterator)
except StopIteration: skipped += 1
pass except StopIteration:
pass
structured_output['timeline'].extend(new_timeline_entries) new_timeline_entries = []
cursor_info = None items_to_fetch = batch_size if batch_size > 0 else float('inf')
if hasattr(extractor, '_cursor') and extractor._cursor: items_fetched = 0
cursor_info = extractor._cursor
structured_output['metadata'] = { try:
"new_entries": len(new_timeline_entries), while items_fetched < items_to_fetch:
"page": page, item = next(iterator)
"batch_size": batch_size, items_fetched += 1
"has_more": batch_size > 0 and items_fetched == batch_size,
"cursor": cursor_info
}
if not structured_output['account_info']: if isinstance(item, tuple) and len(item) >= 3:
raise ValueError("Failed to fetch account information. Please check the username and auth token.") media_url = item[1]
tweet_data = item[2]
return structured_output 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)
}
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
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(): 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()