Compare commits

..
7 Commits
Author SHA1 Message Date
afkarxyz 981bc8d9ec v3.0 2025-07-04 13:37:03 +07:00
afkarxyz c894bfd4d2 . 2025-07-04 13:36:31 +07:00
afkarxyz 61e50b8121 Update README.md 2025-07-04 13:29:21 +07:00
afkarxyz ba69dd7cf4 v2.9 2025-07-04 07:10:01 +07:00
afkarxyz bcc332d0d7 v2.9 2025-07-04 07:01:58 +07:00
afkarxyz 82184aef33 Update README.md 2025-07-04 06:57:57 +07:00
afkarxyz 357ad0f020 v2.8 2025-07-03 20:38:35 +07:00
6 changed files with 237 additions and 416 deletions

No files matched your search

-209
View File
@@ -1,209 +0,0 @@
import json
import re
import os
from datetime import datetime
from gallery_dl.extractor import twitter
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}"
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 for {timeline_type}: {url}")
extractor = extractor_class(match)
config_dict = {
"cookies": {
"auth_token": auth_token
}
}
if batch_size > 0:
config_dict["count"] = batch_size
extractor.config = lambda key, default=None: config_dict.get(key, default)
extractor.initialize()
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': []
}
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 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")
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']
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(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
}
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
# 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}")
-161
View File
@@ -1,161 +0,0 @@
import json
import re
import os
from gallery_dl.extractor import twitter
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}"
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 for {timeline_type}: {url}")
extractor = extractor_class(match)
config_dict = {
"cookies": {
"auth_token": auth_token
}
}
if batch_size > 0:
config_dict["count"] = batch_size
extractor.config = lambda key, default=None: config_dict.get(key, default)
extractor.initialize()
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")
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
}
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}")
-11
View File
@@ -1,11 +0,0 @@
<?xml version="1.0" ?>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1"
id="Layer_1" width="512px" height="512px" viewBox="0 0 24 24" style="enable-background:new 0 0 24 24;"
xml:space="preserve">
<g fill="#1da0f1">
<polygon
points="12.153992,10.729553 8.088684,5.041199 5.92041,5.041199 10.956299,12.087097 11.59021,12.97345 15.900635,19.009583 18.068909,19.009583 12.785217,11.615906 " />
<path
d="M21.15979,1H2.84021C1.823853,1,1,1.823853,1,2.84021v18.31958C1,22.176147,1.823853,23,2.84021,23h18.31958 C22.176147,23,23,22.176147,23,21.15979V2.84021C23,1.823853,22.176147,1,21.15979,1z M15.235352,20l-4.362549-6.213013 L5.411438,20H4l6.246887-7.104675L4,4h4.764648l4.130127,5.881958L18.06958,4h1.411377l-5.95697,6.775635L20,20H15.235352z" />
</g>
</svg>

Before

Width:  |  Height:  |  Size: 876 B

+7 -8
View File
@@ -8,7 +8,7 @@
## 📥 Download ## 📥 Download
- Download the latest version of [TwitterXMediaBatchDownloader](https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases/download/v2.7/TwitterXMediaBatchDownloader.exe) - Download the latest version of [TwitterXMediaBatchDownloader](https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases/download/v2.9/TwitterXMediaBatchDownloader.exe)
- If you're familiar with **userscripts**, please install it [here](https://greasyfork.org/en/scripts/523157) - If you're familiar with **userscripts**, please install it [here](https://greasyfork.org/en/scripts/523157)
## ✨ Features ## ✨ Features
@@ -21,16 +21,13 @@
## 🖼️ Screenshots ## 🖼️ Screenshots
![image](https://github.com/user-attachments/assets/c08d913d-6e1c-4401-9336-7d9642a6a609) ![image](https://github.com/user-attachments/assets/7295213a-d9ba-4d75-8359-d43907b74aef)
![image](https://github.com/user-attachments/assets/79fb6281-03c1-4629-9db2-c1f8990ca8b8) ![image](https://github.com/user-attachments/assets/67bb51ef-0051-4470-b89b-66f653093543)
![image](https://github.com/user-attachments/assets/b20b3431-f64c-4c18-8946-99ce52018caa) ![image](https://github.com/user-attachments/assets/27138746-cd60-41bf-abc1-c4340d72edb5)
> [!Important] ## 🔑 How to Obtain Auth Token
> Please enable **Batch** if the media to be downloaded is thousands.
## 🔑 How to Obtain Auth Token 👉 [Video](https://www.patreon.com/posts/how-to-obtain-127206894)
> [!Warning] > [!Warning]
> - I suggest not using the **main account** to obtain the token. > - I suggest not using the **main account** to obtain the token.
@@ -38,6 +35,8 @@
> - 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 may trigger a **rate limit**, and the media retrieval will fail, try enabling Batch mode. > - If too many media files are fetched, it may trigger a **rate limit**, and the media retrieval will fail, try enabling Batch mode.
### [Video Tutorial](https://www.patreon.com/posts/how-to-obtain-127206894)
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
3. Open the Developer Tools by pressing `F12` 3. Open the Developer Tools by pressing `F12`
+229 -26
View File
@@ -14,10 +14,11 @@ from dataclasses import dataclass
from PyQt6.QtWidgets import ( from PyQt6.QtWidgets import (
QApplication, QWidget, QVBoxLayout, QHBoxLayout, QPushButton, QLineEdit, QApplication, QWidget, QVBoxLayout, QHBoxLayout, QPushButton, QLineEdit,
QLabel, QFileDialog, QListWidget, QTextEdit, QTabWidget, QAbstractItemView, QSpacerItem, QSizePolicy, QProgressBar, QCheckBox, QDialog, QLabel, QFileDialog, QListWidget, QTextEdit, QTabWidget, QAbstractItemView, QSpacerItem, QSizePolicy, QProgressBar, QCheckBox, QDialog,
QDialogButtonBox, QComboBox QDialogButtonBox, QComboBox, QListWidgetItem
) )
from PyQt6.QtCore import Qt, QThread, pyqtSignal, QUrl, QTimer, QTime, QSettings from PyQt6.QtCore import Qt, QThread, pyqtSignal, QUrl, QTimer, QTime, QSettings, QSize
from PyQt6.QtGui import QIcon, QTextCursor, QDesktopServices from PyQt6.QtNetwork import QNetworkAccessManager, QNetworkRequest
from PyQt6.QtGui import QIcon, QTextCursor, QDesktopServices, QPixmap, QPainter, QPainterPath
from getMetadata import get_metadata from getMetadata import get_metadata
@dataclass @dataclass
@@ -28,6 +29,7 @@ class Account:
following: int following: int
posts: int posts: int
media_type: str media_type: str
profile_image: str = None
media_list: list = None media_list: list = None
class MetadataFetchWorker(QThread): class MetadataFetchWorker(QThread):
@@ -80,7 +82,7 @@ class DownloadWorker(QThread):
download_progress = pyqtSignal(str, int) download_progress = pyqtSignal(str, int)
def __init__(self, accounts, outpath, auth_token, filename_format='username_date', def __init__(self, accounts, outpath, auth_token, filename_format='username_date',
download_batch_size=25, convert_gif=False): download_batch_size=25, convert_gif=False, gif_resolution='original'):
super().__init__() super().__init__()
self.accounts = accounts self.accounts = accounts
self.outpath = outpath self.outpath = outpath
@@ -88,6 +90,7 @@ class DownloadWorker(QThread):
self.filename_format = filename_format self.filename_format = filename_format
self.download_batch_size = download_batch_size self.download_batch_size = download_batch_size
self.convert_gif = convert_gif self.convert_gif = convert_gif
self.gif_resolution = gif_resolution
self.is_paused = False self.is_paused = False
self.is_stopped = False self.is_stopped = False
self.filepath_map = [] self.filepath_map = []
@@ -233,15 +236,23 @@ class DownloadWorker(QThread):
if self.is_stopped: if self.is_stopped:
break break
gif_fp = fp.rsplit('.', 1)[0] + '.gif' gif_fp = fp.rsplit('.', 1)[0] + '.gif'
result = subprocess.run([ffmpeg_exe, '-i', fp, gif_fp], capture_output=True, creationflags=creationflags) if self.gif_resolution == 'high':
ffmpeg_args = [ffmpeg_exe, '-i', fp, '-vf', 'scale=800:-1:flags=lanczos', '-r', '15', gif_fp]
elif self.gif_resolution == 'medium':
ffmpeg_args = [ffmpeg_exe, '-i', fp, '-vf', 'scale=600:-1:flags=lanczos', '-r', '10', gif_fp]
elif self.gif_resolution == 'low':
ffmpeg_args = [ffmpeg_exe, '-i', fp, '-vf', 'scale=400:-1:flags=lanczos', '-r', '8', gif_fp]
else:
ffmpeg_args = [ffmpeg_exe, '-i', fp, gif_fp]
result = subprocess.run(ffmpeg_args, capture_output=True, creationflags=creationflags)
if result.returncode == 0 and os.path.exists(gif_fp): if result.returncode == 0 and os.path.exists(gif_fp):
try: try:
os.remove(fp) os.remove(fp)
except Exception: except Exception:
pass pass
conv_progress = int((idx / total_gifs) * 100) conv_progress = int((idx / total_gifs) * 100)
self.conversion_progress.emit(f"Converting GIF {idx}/{total_gifs}", conv_progress) self.conversion_progress.emit(f"Converting GIF {idx}/{total_gifs} ({self.gif_resolution})", conv_progress)
self.progress.emit("GIF conversion completed", 100) self.progress.emit("GIF conversion completed", 100)
except Exception as conv_e: except Exception as conv_e:
self.progress.emit(f"GIF conversion error: {conv_e}", 0) self.progress.emit(f"GIF conversion error: {conv_e}", 0)
@@ -304,7 +315,7 @@ class UpdateDialog(QDialog):
class TwitterMediaDownloaderGUI(QWidget): class TwitterMediaDownloaderGUI(QWidget):
def __init__(self): def __init__(self):
super().__init__() super().__init__()
self.current_version = "2.8" self.current_version = "3.0"
self.accounts = [] self.accounts = []
self.temp_dir = os.path.join(tempfile.gettempdir(), "twitterxmediabatchdownloader") self.temp_dir = os.path.join(tempfile.gettempdir(), "twitterxmediabatchdownloader")
os.makedirs(self.temp_dir, exist_ok=True) os.makedirs(self.temp_dir, exist_ok=True)
@@ -321,11 +332,16 @@ class TwitterMediaDownloaderGUI(QWidget):
self.timeline_type = self.settings.value('timeline_type', 'media') self.timeline_type = self.settings.value('timeline_type', 'media')
self.media_type = self.settings.value('media_type', 'all') self.media_type = self.settings.value('media_type', 'all')
self.convert_gif = self.settings.value('convert_gif', False, type=bool) self.convert_gif = self.settings.value('convert_gif', False, type=bool)
self.gif_resolution = self.settings.value('gif_resolution', 'original')
self.check_for_updates = self.settings.value('check_for_updates', True, type=bool) self.check_for_updates = self.settings.value('check_for_updates', True, type=bool)
self.current_page = 0 self.current_page = 0
self.media_info = None self.media_info = None
self.profile_image_cache = {}
self.pending_downloads = {}
self.network_manager = QNetworkAccessManager()
self.elapsed_time = QTime(0, 0, 0) self.elapsed_time = QTime(0, 0, 0)
self.timer = QTimer(self) self.timer = QTimer(self)
self.timer.timeout.connect(self.update_timer) self.timer.timeout.connect(self.update_timer)
@@ -422,6 +438,36 @@ class TwitterMediaDownloaderGUI(QWidget):
self.account_list = QListWidget() self.account_list = QListWidget()
self.account_list.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection) self.account_list.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection)
self.account_list.itemSelectionChanged.connect(self.update_button_states) self.account_list.itemSelectionChanged.connect(self.update_button_states)
self.account_list.setIconSize(QSize(36, 36))
self.account_list.setStyleSheet("""
QListWidget {
background-color: palette(base);
border: 1px solid palette(mid);
border-radius: 4px;
padding: 0px;
outline: none;
}
QListWidget::item {
padding: 8px 12px;
margin: 2px 0px;
border: none;
border-radius: 4px;
outline: none;
}
QListWidget::item:selected {
background-color: palette(highlight);
border: none;
outline: none;
}
QListWidget::item:focus {
border: none;
outline: none;
}
QListWidget::item:hover {
background-color: palette(midlight);
}
""")
dashboard_layout.addWidget(self.account_list) dashboard_layout.addWidget(self.account_list)
self.setup_account_buttons() self.setup_account_buttons()
@@ -575,12 +621,6 @@ class TwitterMediaDownloaderGUI(QWidget):
self.batch_size_combo.currentTextChanged.connect(self.save_batch_size) self.batch_size_combo.currentTextChanged.connect(self.save_batch_size)
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(Qt.CursorShape.PointingHandCursor)
self.convert_gif_checkbox.setChecked(self.convert_gif)
self.convert_gif_checkbox.toggled.connect(self.save_settings)
first_row_layout.addWidget(self.convert_gif_checkbox)
self.size_label.hide() self.size_label.hide()
self.batch_size_combo.hide() self.batch_size_combo.hide()
@@ -639,9 +679,35 @@ class TwitterMediaDownloaderGUI(QWidget):
self.download_batch_combo.setCurrentText(str(self.download_batch_size)) self.download_batch_combo.setCurrentText(str(self.download_batch_size))
self.download_batch_combo.currentTextChanged.connect(self.save_settings) self.download_batch_combo.currentTextChanged.connect(self.save_settings)
self.convert_gif_checkbox = QCheckBox("Convert GIF")
self.convert_gif_checkbox.setCursor(Qt.CursorShape.PointingHandCursor)
self.convert_gif_checkbox.setChecked(self.convert_gif)
self.convert_gif_checkbox.toggled.connect(self.handle_gif_checkbox)
batch_layout.addWidget(batch_label) batch_layout.addWidget(batch_label)
batch_layout.addWidget(self.download_batch_combo) batch_layout.addWidget(self.download_batch_combo)
batch_layout.addWidget(self.convert_gif_checkbox) batch_layout.addWidget(self.convert_gif_checkbox)
self.gif_resolution_label = QLabel("GIF Quality:")
self.gif_resolution_combo = QComboBox()
self.gif_resolution_combo.setCursor(Qt.CursorShape.PointingHandCursor)
self.gif_resolution_combo.setFixedWidth(85)
gif_resolutions = [
('original', 'Original'),
('high', 'High'),
('medium', 'Medium'),
('low', 'Low')
]
for value, display in gif_resolutions:
self.gif_resolution_combo.addItem(display, value)
self.gif_resolution_combo.currentTextChanged.connect(self.save_settings)
batch_layout.addWidget(self.gif_resolution_label)
batch_layout.addWidget(self.gif_resolution_combo)
if not self.convert_gif:
self.gif_resolution_label.hide()
self.gif_resolution_combo.hide()
batch_layout.addStretch() batch_layout.addStretch()
download_layout.addLayout(batch_layout) download_layout.addLayout(batch_layout)
@@ -699,10 +765,9 @@ class TwitterMediaDownloaderGUI(QWidget):
spacer = QSpacerItem(20, 6, QSizePolicy.Policy.Minimum, QSizePolicy.Policy.Fixed) spacer = QSpacerItem(20, 6, QSizePolicy.Policy.Minimum, QSizePolicy.Policy.Fixed)
about_layout.addItem(spacer) about_layout.addItem(spacer)
footer_label = QLabel("v2.8 | gallery-dl v1.30.0 | July 2025") footer_label = QLabel("v3.0 | gallery-dl v1.30.0 | July 2025")
footer_label.setStyleSheet("font-size: 12px; margin-top: 10px;") footer_label.setStyleSheet("font-size: 12px; margin-top: 10px;")
about_layout.addWidget(footer_label, alignment=Qt.AlignmentFlag.AlignCenter) about_layout.addWidget(footer_label, alignment=Qt.AlignmentFlag.AlignCenter)
about_tab.setLayout(about_layout) about_tab.setLayout(about_layout)
self.tab_widget.addTab(about_tab, "About") self.tab_widget.addTab(about_tab, "About")
@@ -724,6 +789,11 @@ class TwitterMediaDownloaderGUI(QWidget):
if hasattr(self, 'convert_gif_checkbox'): if hasattr(self, 'convert_gif_checkbox'):
self.settings.setValue('convert_gif', self.convert_gif_checkbox.isChecked()) self.settings.setValue('convert_gif', self.convert_gif_checkbox.isChecked())
self.convert_gif = self.convert_gif_checkbox.isChecked() self.convert_gif = self.convert_gif_checkbox.isChecked()
if hasattr(self, 'gif_resolution_combo'):
self.settings.setValue('gif_resolution', self.gif_resolution_combo.currentData())
self.gif_resolution = self.gif_resolution_combo.currentData()
self.settings.sync() self.settings.sync()
def load_settings(self): def load_settings(self):
@@ -759,18 +829,32 @@ class TwitterMediaDownloaderGUI(QWidget):
self.download_batch_combo.setCurrentIndex(index) self.download_batch_combo.setCurrentIndex(index)
else: else:
self.download_batch_combo.setCurrentIndex(0) self.download_batch_combo.setCurrentIndex(0)
media_type = self.settings.value('media_type', 'all') media_type = self.settings.value('media_type', 'all')
for i in range(self.media_type_combo.count()): for i in range(self.media_type_combo.count()):
if self.media_type_combo.itemData(i) == media_type: if self.media_type_combo.itemData(i) == media_type:
self.media_type_combo.setCurrentIndex(i) self.media_type_combo.setCurrentIndex(i)
break break
convert_gif = self.settings.value('convert_gif', False, type=bool) convert_gif = self.settings.value('convert_gif', False, type=bool)
if hasattr(self, 'convert_gif_checkbox'): if hasattr(self, 'convert_gif_checkbox'):
self.convert_gif_checkbox.blockSignals(True) self.convert_gif_checkbox.blockSignals(True)
self.convert_gif_checkbox.setChecked(convert_gif) self.convert_gif_checkbox.setChecked(convert_gif)
self.convert_gif_checkbox.blockSignals(False) self.convert_gif_checkbox.blockSignals(False)
if convert_gif:
self.gif_resolution_label.show()
self.gif_resolution_combo.show()
else:
self.gif_resolution_label.hide()
self.gif_resolution_combo.hide()
gif_resolution = self.settings.value('gif_resolution', 'original')
if hasattr(self, 'gif_resolution_combo'):
for i in range(self.gif_resolution_combo.count()):
if self.gif_resolution_combo.itemData(i) == gif_resolution:
self.gif_resolution_combo.setCurrentIndex(i)
break
last_username_url = self.settings.value('twitter_url', '') last_username_url = self.settings.value('twitter_url', '')
if last_username_url and hasattr(self, 'twitter_url'): if last_username_url and hasattr(self, 'twitter_url'):
self.twitter_url.setText(last_username_url) self.twitter_url.setText(last_username_url)
@@ -793,9 +877,19 @@ class TwitterMediaDownloaderGUI(QWidget):
self.size_label.hide() self.size_label.hide()
self.batch_size_combo.hide() self.batch_size_combo.hide()
self.fetch_btn.setText('Fetch') self.fetch_btn.setText('Fetch')
self.update_button_states() self.update_button_states()
def handle_gif_checkbox(self, checked):
self.convert_gif = checked
self.save_settings()
if checked:
self.gif_resolution_label.show()
self.gif_resolution_combo.show()
else:
self.gif_resolution_label.hide()
self.gif_resolution_combo.hide()
def browse_output(self): def browse_output(self):
directory = QFileDialog.getExistingDirectory(self, "Select Output Directory") directory = QFileDialog.getExistingDirectory(self, "Select Output Directory")
if directory: if directory:
@@ -827,10 +921,6 @@ class TwitterMediaDownloaderGUI(QWidget):
except: except:
pass pass
def is_batch_account(self, username, media_type):
cache_path = self.get_cache_file_path(username, media_type)
return os.path.exists(cache_path) and self.batch_mode
def load_all_cached_accounts(self): def load_all_cached_accounts(self):
try: try:
if not os.path.exists(self.temp_dir): if not os.path.exists(self.temp_dir):
@@ -878,6 +968,7 @@ class TwitterMediaDownloaderGUI(QWidget):
following = account_info.get('friends_count', 0) following = account_info.get('friends_count', 0)
posts = account_info.get('statuses_count', 0) posts = account_info.get('statuses_count', 0)
nick = account_info.get('nick', account_info.get('name', '')) nick = account_info.get('nick', account_info.get('name', ''))
profile_image_url = account_info.get('profile_image', '')
account = Account( account = Account(
username=username, username=username,
@@ -886,8 +977,9 @@ class TwitterMediaDownloaderGUI(QWidget):
following=following, following=following,
posts=posts, posts=posts,
media_type=media_type, media_type=media_type,
profile_image=profile_image_url,
media_list=timeline media_list=timeline
) )
self.accounts.append(account) self.accounts.append(account)
loaded_count += 1 loaded_count += 1
@@ -1009,6 +1101,7 @@ class TwitterMediaDownloaderGUI(QWidget):
following = account_info.get('friends_count', 0) following = account_info.get('friends_count', 0)
posts = account_info.get('statuses_count', 0) posts = account_info.get('statuses_count', 0)
nick = account_info.get('nick', account_info.get('name', '')) nick = account_info.get('nick', account_info.get('name', ''))
profile_image_url = account_info.get('profile_image', '')
account = Account( account = Account(
username=username, username=username,
@@ -1017,6 +1110,7 @@ class TwitterMediaDownloaderGUI(QWidget):
following=following, following=following,
posts=posts, posts=posts,
media_type=media_type, media_type=media_type,
profile_image=profile_image_url,
media_list=timeline media_list=timeline
) )
@@ -1059,6 +1153,7 @@ class TwitterMediaDownloaderGUI(QWidget):
except Exception as e: except Exception as e:
self.log_output.append(f'Error: {str(e)}') self.log_output.append(f'Error: {str(e)}')
self.update_account_list() self.update_account_list()
def on_metadata_error(self, error_message): def on_metadata_error(self, error_message):
self.log_output.append(f'Error: {error_message}') self.log_output.append(f'Error: {error_message}')
@@ -1069,11 +1164,111 @@ class TwitterMediaDownloaderGUI(QWidget):
for i, account in enumerate(self.accounts, 1): for i, account in enumerate(self.accounts, 1):
media_count = len(account.media_list) if account.media_list else 0 media_count = len(account.media_list) if account.media_list else 0
media_type_display = "GIF" if account.media_type.lower() == "gif" else account.media_type.title() media_type_display = "GIF" if account.media_type.lower() == "gif" else account.media_type.title()
display_text = f"{i}. {account.username} ({account.nick}) - Followers: {account.followers:,} - Following: {account.following:,} - Posts: {account.posts:,} • {media_type_display} - {media_count:,} Items"
self.account_list.addItem(display_text) line1 = f"{i}. {account.username} ({account.nick})"
line2 = f"Followers: {account.followers:,} • Following: {account.following:,} • Posts: {account.posts:,} • {media_type_display}: {media_count:,}"
display_text = f"{line1}\n{line2}"
item = QListWidgetItem()
item.setText(display_text)
item.setSizeHint(QSize(0, 52))
if account.profile_image:
if account.profile_image in self.profile_image_cache:
item.setIcon(QIcon(self.profile_image_cache[account.profile_image]))
else:
self.download_profile_image(account.profile_image)
placeholder = self.create_placeholder_icon(52)
if placeholder:
item.setIcon(QIcon(placeholder))
else:
placeholder = self.create_placeholder_icon(52)
if placeholder:
item.setIcon(QIcon(placeholder))
self.account_list.addItem(item)
self.update_button_states() self.update_button_states()
def create_placeholder_icon(self, size=36):
pixmap = QPixmap(size, size)
pixmap.fill(Qt.GlobalColor.transparent)
painter = QPainter(pixmap)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
painter.setBrush(Qt.GlobalColor.gray)
painter.setPen(Qt.PenStyle.NoPen)
painter.drawRoundedRect(0, 0, size, size, 8, 8)
painter.setPen(Qt.GlobalColor.white)
font_size = int(size * 0.4)
painter.setFont(painter.font())
painter.drawText(pixmap.rect(), Qt.AlignmentFlag.AlignCenter, "👤")
painter.end()
return pixmap
def create_square_pixmap(self, original_pixmap, size=36):
if original_pixmap.isNull():
return self.create_placeholder_icon(size)
square_pixmap = QPixmap(size, size)
square_pixmap.fill(Qt.GlobalColor.transparent)
painter = QPainter(square_pixmap)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
path = QPainterPath()
path.addRoundedRect(0, 0, size, size, 8, 8)
painter.setClipPath(path)
scaled_pixmap = original_pixmap.scaled(
size, size,
Qt.AspectRatioMode.KeepAspectRatioByExpanding,
Qt.TransformationMode.SmoothTransformation
)
x = (size - scaled_pixmap.width()) // 2
y = (size - scaled_pixmap.height()) // 2
painter.drawPixmap(x, y, scaled_pixmap)
painter.end()
return square_pixmap
def download_profile_image(self, url):
if not url or url in self.profile_image_cache or url in self.pending_downloads:
return
try:
request = QNetworkRequest(QUrl(url))
request.setHeader(QNetworkRequest.KnownHeaders.UserAgentHeader,
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36")
reply = self.network_manager.get(request)
self.pending_downloads[url] = reply
reply.finished.connect(lambda: self.on_profile_image_downloaded(reply, url))
except Exception as e:
print(f"Error downloading profile image: {e}")
def on_profile_image_downloaded(self, reply, image_url):
try:
if reply.error() == reply.NetworkError.NoError:
data = reply.readAll()
pixmap = QPixmap()
if pixmap.loadFromData(data):
square_pixmap = self.create_square_pixmap(pixmap, 52)
self.profile_image_cache[image_url] = square_pixmap
self.update_account_list()
if image_url in self.pending_downloads:
del self.pending_downloads[image_url]
except Exception as e:
print(f"Error processing profile image: {e}")
finally:
reply.deleteLater()
def update_button_states(self): def update_button_states(self):
has_accounts = len(self.accounts) > 0 has_accounts = len(self.accounts) > 0
@@ -1135,7 +1330,8 @@ class TwitterMediaDownloaderGUI(QWidget):
self.auth_token_input.text().strip(), self.auth_token_input.text().strip(),
self.filename_format, self.filename_format,
self.download_batch_size, self.download_batch_size,
self.convert_gif self.convert_gif,
self.gif_resolution
) )
self.worker.finished.connect(self.on_download_finished) self.worker.finished.connect(self.on_download_finished)
self.worker.progress.connect(self.update_progress) self.worker.progress.connect(self.update_progress)
@@ -1181,6 +1377,7 @@ class TwitterMediaDownloaderGUI(QWidget):
if percentage > 0: if percentage > 0:
self.progress_bar.setValue(percentage) self.progress_bar.setValue(percentage)
def update_conversion_progress(self, message, percentage): def update_conversion_progress(self, message, percentage):
cursor = self.log_output.textCursor() cursor = self.log_output.textCursor()
cursor.movePosition(QTextCursor.MoveOperation.End) cursor.movePosition(QTextCursor.MoveOperation.End)
@@ -1300,6 +1497,12 @@ class TwitterMediaDownloaderGUI(QWidget):
self.timer.stop() self.timer.stop()
self.time_label.hide() self.time_label.hide()
def show_account_buttons(self):
self.download_selected_btn.show()
self.download_all_btn.show()
self.remove_btn.show()
self.clear_btn.show()
def main(): def main():
if getattr(sys, 'frozen', False): if getattr(sys, 'frozen', False):
os.chdir(os.path.dirname(sys.executable)) os.chdir(os.path.dirname(sys.executable))
+1 -1
View File
@@ -1,3 +1,3 @@
{ {
"version": "2.7" "version": "2.9"
} }