Compare commits

...
20 Commits
Author SHA1 Message Date
afkarxyz dfb536f663 Update README.md 2025-01-22 17:35:38 +07:00
afkarxyz 2b5e7985d5 Create getRAW.py 2025-01-22 17:34:52 +07:00
afkarxyz 81bacad4d8 Update and rename GetMetadata.py to getMetadata.py 2025-01-22 17:34:28 +07:00
afkarxyz aa89fda847 Update v1.2 2025-01-22 17:33:24 +07:00
afkarxyz e98cd51cf4 Update README.md 2025-01-22 05:30:38 +07:00
afkarxyz 6bb5348485 Update README.md 2025-01-21 12:03:57 +07:00
afkarxyz 784bb494fc Update README.md 2025-01-21 10:22:43 +07:00
afkarxyz 5096e18cb8 Update README.md 2025-01-21 00:08:41 +07:00
afkarxyz 2237de2b2c Update README.md 2025-01-21 00:05:14 +07:00
afkarxyz 4656ebc56c Update README.md 2025-01-20 23:49:42 +07:00
afkarxyz f5357370b1 Update v1.1 2025-01-20 23:34:27 +07:00
afkarxyz e216769e57 Update README.md 2025-01-20 23:34:01 +07:00
afkarxyz 72fb45fc8a Update GetMetadata.py 2025-01-20 21:26:04 +07:00
afkarxyz f6a2986dbf Update README.md 2025-01-20 20:59:02 +07:00
afkarxyz 20b15191ac Update README.md 2025-01-20 17:10:54 +07:00
afkarxyz c616d688ff Update README.md 2025-01-20 04:47:14 +07:00
afkarxyz 3f35f81fbe Update README.md 2025-01-20 04:46:19 +07:00
afkarxyz 9109eeca76 Update README.md 2025-01-19 21:20:50 +07:00
afkarxyz d70b0c3522 Update README.md 2025-01-19 20:27:41 +07:00
afkarxyz e324d7b724 Update README.md 2025-01-19 18:47:03 +07:00
5 changed files with 325 additions and 212 deletions

No files matched your search

-75
View File
@@ -1,75 +0,0 @@
import json
import subprocess
import sys
import os
from datetime import datetime
def get_metadata(username):
if sys.platform == 'win32':
sys.stdout.reconfigure(encoding='utf-8')
url = f"https://x.com/{username}/timeline"
current_dir = os.path.dirname(os.path.abspath(__file__))
cookies_path = os.path.join(current_dir, 'cookies.json')
output_path = os.path.join(current_dir, f'{username}.json')
gallery_dl_path = os.path.join(current_dir, 'gallery-dl.exe')
config = {
"extractor": {
"twitter": {
"cookies": {
"auth_token": ""
}
}
}
}
with open(cookies_path, 'w') as f:
json.dump(config, f)
result = subprocess.run([gallery_dl_path, '-j', '--config', cookies_path, url],
capture_output=True,
text=True,
encoding='utf-8',
check=True)
os.remove(cookies_path)
data = json.loads(result.stdout)
output = {
'account_info': {},
'timeline': []
}
for item in data:
if isinstance(item, list) and len(item) > 2 and isinstance(item[2], dict):
if not output['account_info'] and 'user' in item[2]:
user = item[2]['user']
output['account_info'] = {
'date': user.get('date', ''),
'followers_count': user.get('followers_count', ''),
'friends_count': user.get('friends_count', ''),
'name': user.get('name', ''),
'nick': user.get('nick', ''),
'profile_image': user.get('profile_image', ''),
'statuses_count': user.get('statuses_count', '')
}
if isinstance(item[1], str):
url = item[1]
if ('pbs.twimg.com' in url and 'format=jpg&name=orig' in url) or 'video.twimg.com' in url:
tweet_date = item[2].get('date')
if not tweet_date:
tweet_date = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
output['timeline'].append({
'url': url,
'date': tweet_date
})
with open(output_path, 'w', encoding='utf-8') as f:
json.dump(output, f, ensure_ascii=False, indent=2)
username = ""
get_metadata(username)
+78
View File
@@ -0,0 +1,78 @@
import json
import re
import os
from datetime import datetime
from gallery_dl.extractor import twitter
def get_metadata(username):
url = f"https://x.com/{username}/timeline"
match = re.match(twitter.TwitterTimelineExtractor.pattern, url)
if not match:
raise ValueError(f"Invalid URL: {url}")
extractor = twitter.TwitterTimelineExtractor(match)
extractor.config = lambda key, default=None: {
"cookies": {
"auth_token": ""
}
}.get(key, default)
extractor.initialize()
output = {
'account_info': {},
'total_urls': 0,
'timeline': []
}
for item in extractor:
if isinstance(item, tuple) and len(item) >= 3:
media_url = item[1]
tweet_data = item[2]
if not output['account_info']:
if 'user' in tweet_data:
user = tweet_data['user']
user_date = user.get('date', '')
if isinstance(user_date, datetime):
user_date = user_date.strftime("%Y-%m-%d %H:%M:%S")
output['account_info'] = {
'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']
output['timeline'].append(timeline_entry)
output['total_urls'] += 1
current_dir = os.path.dirname(os.path.abspath(__file__))
output_file = os.path.join(current_dir, f"{username}.json")
with open(output_file, 'w', encoding='utf-8') as f:
json.dump(output, f, ensure_ascii=False, indent=2)
return output
username = ""
get_metadata(username)
+34
View File
@@ -0,0 +1,34 @@
import json
import re
import os
from gallery_dl.extractor import twitter
def get_metadata(username):
url = f"https://x.com/{username}/timeline"
match = re.match(twitter.TwitterTimelineExtractor.pattern, url)
if not match:
raise ValueError(f"Invalid URL: {url}")
extractor = twitter.TwitterTimelineExtractor(match)
extractor.config = lambda key, default=None: {
"cookies": {
"auth_token": ""
}
}.get(key, default)
extractor.initialize()
all_items = []
for item in extractor:
all_items.append(item)
current_dir = os.path.dirname(os.path.abspath(__file__))
output_file = os.path.join(current_dir, f"{username}.json")
with open(output_file, 'w', encoding='utf-8') as f:
json.dump(all_items, f, indent=2, default=str)
username = ""
get_metadata(username)
+23 -8
View File
@@ -1,25 +1,40 @@
[![GitHub All Releases](https://img.shields.io/github/downloads/afkarxyz/Twitter-X-Media-Batch-Downloader/total?style=for-the-badge)](https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases) [![GitHub All Releases](https://img.shields.io/github/downloads/afkarxyz/Twitter-X-Media-Batch-Downloader/total?style=for-the-badge)](https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases)
**Twitter/X Media Batch Downloader** is a GUI tool for downloading all media, including images and videos, from Twitter/X accounts, using `gallery-dl` and requiring `cookies.` ![TwitterXMediaBatchDownloader](https://github.com/user-attachments/assets/354d7470-c01c-4aa6-9da1-ea6c42d27330)
<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 using <code>gallery-dl</code>
</div>
## Download ## Download
- Download the latest version of [TwitterXMediaBatchDownloader](https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases/download/v1.2/TwitterXMediaBatchDownloader.exe)
- If you're familiar with **userscripts**, please install it [here](https://greasyfork.org/en/scripts/523157-twitter-x-media-batch-downloader)
## Features
- Uses the powerful `gallery-dl` library, similar to `yt-dlp`
- Simple and compact GUI
- Download images and videos in original quality
- Option to choose the media type to download: **media** (image + video) or just **image/video**
- **Batch** download settings, ranging from 10 to 100 files per download
- Filename format customization
## Screenshots ## Screenshots
![image](https://github.com/user-attachments/assets/6401f71b-328f-4f57-950c-3300c2bd2939) ![image](https://github.com/user-attachments/assets/ccdd8a8d-890f-4d3c-a3b1-56dad3eb82a9)
![image](https://github.com/user-attachments/assets/a9ff0e34-892e-4538-9ea3-63fa0c222be4) ![image](https://github.com/user-attachments/assets/01a80593-59fe-4c2b-a325-7e401fa3048f)
![image](https://github.com/user-attachments/assets/f5c0933b-6a3e-463f-9170-c11f85610853) ![image](https://github.com/user-attachments/assets/1779659e-3512-4e74-be0a-088419267fe0)
## How to obtain Auth Token ## How to Obtain Auth Token
1. Go to [X'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`
4. Navigate to the **Application** tab, then select **Storage** > **Cookies** 4. Navigate to the **Application** tab, then select **Storage** > **Cookies**
5. Find and copy the `auth_token` value 5. Find and copy the `auth_token` value or use the browser extension [Cookie-Editor](https://cookie-editor.com/)
6. Do not log out of your account, as a new `auth_token` will be generated by Twitter 6. Do not log out of your account, as a new `auth_token` will be generated by Twitter
7. Close your browser
![image](https://github.com/user-attachments/assets/50f819da-7490-4f3c-b130-c5a3ee482e2d) ![image](https://github.com/user-attachments/assets/50f819da-7490-4f3c-b130-c5a3ee482e2d)
+190 -129
View File
@@ -1,8 +1,8 @@
import sys import sys
import os import os
import json
import asyncio import asyncio
import aiohttp import aiohttp
import re
import subprocess import subprocess
from datetime import datetime from datetime import datetime
from pathlib import Path from pathlib import Path
@@ -10,7 +10,8 @@ from PyQt6.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout,
QHBoxLayout, QLabel, QLineEdit, QPushButton, QHBoxLayout, QLabel, QLineEdit, QPushButton,
QProgressBar, QFileDialog, QRadioButton, QComboBox) QProgressBar, QFileDialog, QRadioButton, QComboBox)
from PyQt6.QtCore import QThread, pyqtSignal, Qt, QSettings from PyQt6.QtCore import QThread, pyqtSignal, Qt, QSettings
from PyQt6.QtGui import QIcon, QPixmap, QCursor from PyQt6.QtGui import QIcon, QPixmap, QCursor, QPainter, QPainterPath
from gallery_dl.extractor import twitter
class ImageDownloader(QThread): class ImageDownloader(QThread):
finished = pyqtSignal(bytes) finished = pyqtSignal(bytes)
@@ -35,9 +36,11 @@ class MetadataFetcher(QThread):
finished = pyqtSignal(dict) finished = pyqtSignal(dict)
error = pyqtSignal(str) error = pyqtSignal(str)
def __init__(self, username): def __init__(self, username, media_type='media'):
super().__init__() super().__init__()
self.username = username self.username = username
self.auth_token = None
self.media_type = media_type
def run(self): def run(self):
try: try:
@@ -49,100 +52,86 @@ class MetadataFetcher(QThread):
url = f"https://x.com/{username}/timeline" url = f"https://x.com/{username}/timeline"
if getattr(sys, 'frozen', False): match = re.match(twitter.TwitterTimelineExtractor.pattern, url)
base_path = sys._MEIPASS if not match:
else: raise ValueError(f"Invalid URL: {url}")
base_path = os.path.dirname(os.path.abspath(__file__))
cookies_path = os.path.join(base_path, 'cookies.json')
gallery_dl_path = os.path.join(base_path, 'gallery-dl.exe')
if not os.path.exists(gallery_dl_path):
gallery_dl_path = os.path.join(os.getcwd(), 'gallery-dl.exe')
if not os.path.exists(gallery_dl_path):
gallery_dl_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'gallery-dl.exe')
if not os.path.exists(gallery_dl_path):
raise FileNotFoundError(
"gallery-dl.exe not found. Please ensure it's in the same directory as the executable."
)
config = {
"extractor": {
"twitter": {
"cookies": {
"auth_token": self.auth_token
}
}
}
}
try:
cookies_dir = os.path.dirname(cookies_path)
if not os.path.exists(cookies_dir):
os.makedirs(cookies_dir)
with open(cookies_path, 'w', encoding='utf-8') as f: extractor = twitter.TwitterTimelineExtractor(match)
json.dump(config, f) extractor.config = lambda key, default=None: {
except Exception as e: "cookies": {
raise Exception(f"Failed to write cookies file: {str(e)}") "auth_token": self.auth_token
}
startupinfo = None }.get(key, default)
if sys.platform == 'win32':
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
try: extractor.initialize()
process = subprocess.run(
[gallery_dl_path, '-j', '--config', cookies_path, url],
capture_output=True,
text=True,
encoding='utf-8',
check=True,
startupinfo=startupinfo
)
except subprocess.CalledProcessError as e:
raise Exception(f"gallery-dl.exe failed: {e.stderr}")
except Exception as e:
raise Exception(f"Failed to execute gallery-dl.exe: {str(e)}")
finally:
try:
if os.path.exists(cookies_path):
os.remove(cookies_path)
except Exception:
pass
data = json.loads(process.stdout)
output = { output = {
'account_info': {}, 'account_info': {},
'timeline': [] 'timeline': []
} }
for item in data: for item in extractor:
if isinstance(item, list) and len(item) > 2 and isinstance(item[2], dict): if isinstance(item, tuple) and len(item) >= 3:
if not output['account_info'] and 'user' in item[2]: media_url = item[1]
user = item[2]['user'] tweet_data = item[2]
output['account_info'] = {
'date': user.get('date', ''), if not output['account_info']:
'followers_count': user.get('followers_count', ''), if 'user' in tweet_data:
'friends_count': user.get('friends_count', ''), user = tweet_data['user']
'name': user.get('name', ''), user_date = user.get('date', '')
'nick': user.get('nick', ''), if isinstance(user_date, datetime):
'profile_image': user.get('profile_image', ''), user_date = user_date.strftime("%Y-%m-%d %H:%M:%S")
'statuses_count': user.get('statuses_count', '')
} output['account_info'] = {
if isinstance(item[1], str): 'name': user.get('name', ''),
url = item[1] 'nick': user.get('nick', ''),
if ('pbs.twimg.com' in url and 'format=jpg&name=orig' in url) or 'video.twimg.com' in url: 'date': user_date,
tweet_date = item[2].get('date') 'followers_count': user.get('followers_count', 0),
if not tweet_date: 'friends_count': user.get('friends_count', 0),
tweet_date = datetime.now().strftime("%Y-%m-%d %H:%M:%S") 'profile_image': user.get('profile_image', ''),
'statuses_count': user.get('statuses_count', 0)
output['timeline'].append({ }
'url': url,
'date': tweet_date should_include = False
}) media_type = tweet_data.get('type', '')
if self.media_type == 'media':
should_include = ('pbs.twimg.com' in media_url or
'video.twimg.com' in media_url)
elif self.media_type == 'image':
should_include = ('pbs.twimg.com' in media_url and
media_type == 'photo')
elif self.media_type == 'gif':
should_include = media_type == 'animated_gif'
elif self.media_type == 'video':
should_include = (media_type == 'video' and
'video.twimg.com' in media_url)
if should_include:
tweet_date = tweet_data.get('date', datetime.now())
if isinstance(tweet_date, datetime):
tweet_date = tweet_date.strftime("%Y-%m-%d %H:%M:%S")
output['timeline'].append({
'url': media_url,
'date': tweet_date,
'type': media_type,
'tweet_id': tweet_data.get('tweet_id', '')
})
if not output['account_info']:
raise ValueError("Failed to fetch account information. Please check the username and auth token.")
if not output['timeline']:
if self.media_type == 'media':
message = "No media found in timeline"
elif self.media_type == 'image':
message = "No images found in timeline"
elif self.media_type == 'gif':
message = "No GIFs found in timeline"
else:
message = "No videos found in timeline"
raise ValueError(message)
self.finished.emit(output) self.finished.emit(output)
@@ -155,16 +144,19 @@ 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, batch_size=10): def __init__(self, media_list, output_dir, filename_format, username, media_type='media', batch_size=10):
super().__init__() super().__init__()
self.media_list = media_list self.media_list = media_list
self.output_dir = output_dir self.output_dir = output_dir
self.filename_format = filename_format self.filename_format = filename_format
self.username = username self.username = username
self.media_type = media_type
self.batch_size = batch_size self.batch_size = batch_size
async def download_file(self, session, url, filepath): async def download_file(self, session, url, filepath):
try: try:
os.makedirs(os.path.dirname(filepath), exist_ok=True)
async with session.get(url) as response: async with session.get(url) as response:
if response.status == 200: if response.status == 200:
with open(filepath, 'wb') as f: with open(filepath, 'wb') as f:
@@ -175,23 +167,35 @@ class MediaDownloader(QThread):
return False return False
async def download_all(self): async def download_all(self):
os.makedirs(self.output_dir, exist_ok=True)
async with aiohttp.ClientSession() as session: async with aiohttp.ClientSession() as session:
total = len(self.media_list) total = len(self.media_list)
completed = 0 completed = 0
used_filenames = set()
tasks = [] tasks = []
for item in self.media_list: for item in self.media_list:
url = item['url'] url = item['url']
date = datetime.strptime(item['date'], "%Y-%m-%d %H:%M:%S") date = datetime.strptime(item['date'], "%Y-%m-%d %H:%M:%S")
formatted_date = date.strftime("%Y-%m-%d") formatted_date = date.strftime("%Y%m%d_%H%M%S")
tweet_id = str(item.get('tweet_id', ''))
extension = 'mp4' if 'video.twimg.com' in url else 'jpg'
if self.filename_format == "username_date": if self.filename_format == "username_date":
filename = f"{self.username}_{formatted_date}" base_filename = f"{self.username}_{formatted_date}_{tweet_id}"
else: else:
filename = f"{formatted_date}_{self.username}" base_filename = f"{formatted_date}_{self.username}_{tweet_id}"
filename = f"{filename}_{len(tasks):03d}.{'mp4' if 'video' in url else 'jpg'}" filename = f"{base_filename}.{extension}"
counter = 1
while filename in used_filenames:
filename = f"{base_filename}_{counter:02d}.{extension}"
counter += 1
used_filenames.add(filename)
filepath = os.path.join(self.output_dir, filename) filepath = os.path.join(self.output_dir, filename)
task = asyncio.create_task(self.download_file(session, url, filepath)) task = asyncio.create_task(self.download_file(session, url, filepath))
@@ -202,7 +206,16 @@ class MediaDownloader(QThread):
completed += sum(1 for r in results if r) completed += sum(1 for r in results if r)
progress = int((completed / total) * 100) progress = int((completed / total) * 100)
self.progress.emit(progress) self.progress.emit(progress)
self.status_update.emit(f"Downloaded {completed} of {total} files...") completed_str = f"{completed:,}" if completed >= 1000 else str(completed)
total_str = f"{total:,}" if total >= 1000 else str(total)
media_type_str = "files"
if self.media_type == "image":
media_type_str = "images"
elif self.media_type == "video":
media_type_str = "videos"
self.status_update.emit(f"Downloaded {completed_str} of {total_str} {media_type_str}...")
tasks = [] tasks = []
if tasks: if tasks:
@@ -216,7 +229,15 @@ class MediaDownloader(QThread):
def run(self): def run(self):
try: try:
completed = asyncio.run(self.download_all()) completed = asyncio.run(self.download_all())
self.finished.emit(f"Downloaded {completed} files successfully!") completed_str = f"{completed:,}" if completed >= 1000 else str(completed)
media_type_str = "files"
if self.media_type == "image":
media_type_str = "images"
elif self.media_type == "video":
media_type_str = "videos"
self.finished.emit(f"Downloaded {completed_str} {media_type_str} successfully!")
except Exception as e: except Exception as e:
self.error.emit(str(e)) self.error.emit(str(e))
@@ -233,8 +254,7 @@ class TwitterMediaDownloaderGUI(QMainWindow):
self.setFixedHeight(180) self.setFixedHeight(180)
self.default_pictures_dir = str(Path.home() / "Pictures") self.default_pictures_dir = str(Path.home() / "Pictures")
if not os.path.exists(self.default_pictures_dir): os.makedirs(self.default_pictures_dir, exist_ok=True)
os.makedirs(self.default_pictures_dir)
self.media_info = None self.media_info = None
self.settings = QSettings('TwitterMediaDownloader', 'Settings') self.settings = QSettings('TwitterMediaDownloader', 'Settings')
@@ -299,34 +319,47 @@ class TwitterMediaDownloaderGUI(QMainWindow):
auth_layout.addWidget(self.auth_input) auth_layout.addWidget(self.auth_input)
input_layout.addLayout(auth_layout) input_layout.addLayout(auth_layout)
combined_layout = QHBoxLayout() options_layout = QHBoxLayout()
batch_label = QLabel("Batch Size:") media_label = QLabel("Media Type:")
batch_label.setFixedWidth(100) media_label.setFixedWidth(100)
self.media_type_combo = QComboBox()
self.media_type_combo.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
media_types = [('media', 'Media'), ('image', 'Image'), ('gif', 'GIF'), ('video', 'Video')]
for value, display in media_types:
self.media_type_combo.addItem(display, value)
self.media_type_combo.setFixedWidth(100)
batch_label = QLabel("Batch:")
batch_label.setFixedWidth(40)
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))
self.batch_size_combo.setFixedWidth(70) self.batch_size_combo.setFixedWidth(50)
for size in range(10, 101, 10): for size in range(10, 101, 10):
self.batch_size_combo.addItem(str(size)) self.batch_size_combo.addItem(str(size))
format_label = QLabel("Filename:") format_label = QLabel("Filename:")
format_label.setFixedWidth(50) format_label.setFixedWidth(60)
self.format_username_date = QRadioButton("Username - Date") self.format_username = QRadioButton("Username")
self.format_date_username = QRadioButton("Date - Username") self.format_date = QRadioButton("Date")
self.format_username_date.setCursor(QCursor(Qt.CursorShape.PointingHandCursor)) self.format_username.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
self.format_date_username.setCursor(QCursor(Qt.CursorShape.PointingHandCursor)) self.format_date.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
combined_layout.addWidget(batch_label) options_layout.addWidget(media_label)
combined_layout.addWidget(self.batch_size_combo) options_layout.addWidget(self.media_type_combo)
combined_layout.addSpacing(10) options_layout.addSpacing(10)
combined_layout.addWidget(format_label) options_layout.addWidget(batch_label)
combined_layout.addWidget(self.format_username_date) options_layout.addWidget(self.batch_size_combo)
combined_layout.addWidget(self.format_date_username) options_layout.addSpacing(10)
combined_layout.addStretch() options_layout.addWidget(format_label)
options_layout.addWidget(self.format_username)
options_layout.addWidget(self.format_date)
options_layout.addStretch()
input_layout.addLayout(combined_layout) input_layout.addLayout(options_layout)
self.main_layout.addWidget(self.input_widget) self.main_layout.addWidget(self.input_widget)
@@ -383,6 +416,7 @@ class TwitterMediaDownloaderGUI(QMainWindow):
profile_details_layout.addWidget(self.followers_label) profile_details_layout.addWidget(self.followers_label)
profile_details_layout.addWidget(self.following_label) profile_details_layout.addWidget(self.following_label)
profile_details_layout.addWidget(self.posts_label) profile_details_layout.addWidget(self.posts_label)
profile_details_layout.addWidget(self.posts_label)
profile_layout.addWidget(profile_details_container, stretch=1) profile_layout.addWidget(profile_details_container, stretch=1)
profile_layout.addStretch() profile_layout.addStretch()
@@ -453,7 +487,8 @@ class TwitterMediaDownloaderGUI(QMainWindow):
self.url_input.textChanged.connect(self.auto_save_settings) self.url_input.textChanged.connect(self.auto_save_settings)
self.auth_input.textChanged.connect(self.auto_save_settings) self.auth_input.textChanged.connect(self.auto_save_settings)
self.dir_input.textChanged.connect(self.auto_save_settings) self.dir_input.textChanged.connect(self.auto_save_settings)
self.format_username_date.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.batch_size_combo.currentTextChanged.connect(self.auto_save_settings) self.batch_size_combo.currentTextChanged.connect(self.auto_save_settings)
def auto_save_settings(self): def auto_save_settings(self):
@@ -461,7 +496,8 @@ class TwitterMediaDownloaderGUI(QMainWindow):
self.settings.setValue('auth_token', self.auth_input.text()) self.settings.setValue('auth_token', self.auth_input.text())
self.settings.setValue('output_dir', self.dir_input.text()) self.settings.setValue('output_dir', self.dir_input.text())
self.settings.setValue('filename_format', self.settings.setValue('filename_format',
'username_date' if self.format_username_date.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('batch_size', self.batch_size_combo.currentText()) self.settings.setValue('batch_size', self.batch_size_combo.currentText())
self.settings.sync() self.settings.sync()
@@ -471,8 +507,14 @@ class TwitterMediaDownloaderGUI(QMainWindow):
self.dir_input.setText(self.settings.value('output_dir', self.default_pictures_dir, str)) self.dir_input.setText(self.settings.value('output_dir', self.default_pictures_dir, str))
format_setting = self.settings.value('filename_format', 'username_date') format_setting = self.settings.value('filename_format', 'username_date')
self.format_username_date.setChecked(format_setting == 'username_date') self.format_username.setChecked(format_setting == 'username_date')
self.format_date_username.setChecked(format_setting == 'date_username') self.format_date.setChecked(format_setting == 'date_username')
media_type = self.settings.value('media_type', 'media')
for i in range(self.media_type_combo.count()):
if self.media_type_combo.itemData(i) == media_type:
self.media_type_combo.setCurrentIndex(i)
break
batch_size = self.settings.value('batch_size', '10') batch_size = self.settings.value('batch_size', '10')
index = self.batch_size_combo.findText(batch_size) index = self.batch_size_combo.findText(batch_size)
@@ -482,6 +524,7 @@ class TwitterMediaDownloaderGUI(QMainWindow):
def select_directory(self): def select_directory(self):
directory = QFileDialog.getExistingDirectory(self, "Select Output Directory") directory = QFileDialog.getExistingDirectory(self, "Select Output Directory")
if directory: if directory:
os.makedirs(directory, exist_ok=True)
self.dir_input.setText(directory) self.dir_input.setText(directory)
def open_output_directory(self): def open_output_directory(self):
@@ -508,7 +551,8 @@ class TwitterMediaDownloaderGUI(QMainWindow):
self.fetch_button.setEnabled(False) self.fetch_button.setEnabled(False)
self.status_label.setText("Fetching profile information...") self.status_label.setText("Fetching profile information...")
self.fetcher = MetadataFetcher(username) media_type = self.media_type_combo.currentData()
self.fetcher = MetadataFetcher(username, media_type)
self.fetcher.auth_token = auth_token self.fetcher.auth_token = auth_token
self.fetcher.finished.connect(self.handle_profile_info) self.fetcher.finished.connect(self.handle_profile_info)
self.fetcher.error.connect(self.handle_fetch_error) self.fetcher.error.connect(self.handle_fetch_error)
@@ -561,15 +605,30 @@ class TwitterMediaDownloaderGUI(QMainWindow):
output_base = self.dir_input.text().strip() or self.default_pictures_dir output_base = self.dir_input.text().strip() or self.default_pictures_dir
self.user_output_dir = os.path.join(output_base, username) self.user_output_dir = os.path.join(output_base, username)
if not os.path.exists(self.user_output_dir): os.makedirs(self.user_output_dir, exist_ok=True)
os.makedirs(self.user_output_dir)
def update_profile_image(self, image_data): def update_profile_image(self, image_data):
pixmap = QPixmap() original_pixmap = QPixmap()
pixmap.loadFromData(image_data) original_pixmap.loadFromData(image_data)
scaled_pixmap = pixmap.scaled(100, 100, Qt.AspectRatioMode.KeepAspectRatio,
Qt.TransformationMode.SmoothTransformation) scaled_pixmap = original_pixmap.scaled(100, 100,
self.profile_image_label.setPixmap(scaled_pixmap) Qt.AspectRatioMode.KeepAspectRatio,
Qt.TransformationMode.SmoothTransformation)
rounded_pixmap = QPixmap(scaled_pixmap.size())
rounded_pixmap.fill(Qt.GlobalColor.transparent)
painter = QPainter(rounded_pixmap)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
path = QPainterPath()
path.addRoundedRect(0, 0, scaled_pixmap.width(), scaled_pixmap.height(), 10, 10)
painter.setClipPath(path)
painter.drawPixmap(0, 0, scaled_pixmap)
painter.end()
self.profile_image_label.setPixmap(rounded_pixmap)
def handle_fetch_error(self, error): def handle_fetch_error(self, error):
self.fetch_button.setEnabled(True) self.fetch_button.setEnabled(True)
@@ -591,8 +650,9 @@ class TwitterMediaDownloaderGUI(QMainWindow):
self.progress_bar.setValue(0) self.progress_bar.setValue(0)
self.status_label.setText("Starting download...") self.status_label.setText("Starting download...")
filename_format = "username_date" if self.format_username_date.isChecked() else "date_username" filename_format = "username_date" if self.format_username.isChecked() else "date_username"
batch_size = int(self.batch_size_combo.currentText()) batch_size = int(self.batch_size_combo.currentText())
media_type = self.media_type_combo.currentData()
username = self.url_input.text().strip() username = self.url_input.text().strip()
if "x.com/" in username or "twitter.com/" in username: if "x.com/" in username or "twitter.com/" in username:
@@ -605,6 +665,7 @@ class TwitterMediaDownloaderGUI(QMainWindow):
self.user_output_dir, self.user_output_dir,
filename_format, filename_format,
username, username,
media_type,
batch_size batch_size
) )
self.worker.progress.connect(self.update_progress) self.worker.progress.connect(self.update_progress)