Compare commits

..
43 Commits
Author SHA1 Message Date
afkarxyz 91210f1c82 Update v1.7 2025-03-04 08:54:07 +07:00
afkarxyz cb2a244e37 Update README.md 2025-02-19 09:52:41 +07:00
afkarxyz 096425a0e1 Update version.json 2025-02-19 09:52:31 +07:00
afkarxyz c01a995b3d Update v1.6 2025-02-19 09:52:22 +07:00
afkarxyz b28b4ef14c Update README.md 2025-02-18 12:16:32 +07:00
afkarxyz 1e14fa6934 Update README.md 2025-02-18 10:41:57 +07:00
afkarxyz eac8a0f168 Update v1.5 2025-02-18 10:41:29 +07:00
afkarxyz f3904c276c Create version.json 2025-02-18 10:35:16 +07:00
afkarxyz fe9724fa2f Update README.md 2025-01-30 05:17:14 +07:00
afkarxyz 85e8f3135a Update README.md 2025-01-29 10:00:12 +07:00
afkarxyz 1e2725f900 Update README.md 2025-01-28 23:09:37 +07:00
afkarxyz 8e114a45e0 Update README.md 2025-01-28 23:08:55 +07:00
afkarxyz 92267dbf5e Update v1.4 2025-01-28 16:47:50 +07:00
afkarxyz 37da356f4c Update README.md 2025-01-28 16:47:25 +07:00
afkarxyz eb268f5f9f Update v1.3 2025-01-28 12:45:19 +07:00
afkarxyz e8ac4b8734 Update TwitterXMediaBatchDownloader.py 2025-01-28 12:39:36 +07:00
afkarxyz 99afe59a11 Update README.md 2025-01-28 12:28:27 +07:00
afkarxyz 8e8c0667df Update README.md 2025-01-27 06:27:52 +07:00
afkarxyz 03479326b3 Update README.md 2025-01-27 03:56:41 +07:00
afkarxyz b39f40e9f9 Update README.md 2025-01-24 04:44:54 +07:00
afkarxyz 5ed127f226 Update README.md 2025-01-23 09:36:27 +07:00
afkarxyz 3487edf691 Update README.md 2025-01-23 09:26:32 +07:00
afkarxyz 5b336df1d4 Update README.md 2025-01-23 09:02:23 +07:00
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
6 changed files with 717 additions and 316 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)
+79
View File
@@ -0,0 +1,79 @@
import json
import re
import os
from datetime import datetime
from gallery_dl.extractor import twitter
def get_metadata(username, auth_token):
url = f"https://x.com/{username}/timeline"
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": 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 = ""
auth_token = ""
get_metadata(username, auth_token)
+35
View File
@@ -0,0 +1,35 @@
import json
import re
import os
from gallery_dl.extractor import twitter
def get_metadata(username, auth_token):
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": 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 = ""
auth_token = ""
get_metadata(username, auth_token)
+42 -9
View File
@@ -1,25 +1,58 @@
[![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, even withheld accounts, using <code>gallery-dl</code>
</div>
## Download
- Download the latest version of [TwitterXMediaBatchDownloader](https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases/download/v1.7/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`
- The ability to download media from **Withheld Accounts** _(maybe requires checking the **Use gallery-dl API** option)_
- Option to choose the media type to download: **All Media** (Image + GIF + Video) or just **Image/GIF/Video**
- Download images and videos in original quality
## Screenshots
![image](https://github.com/user-attachments/assets/6401f71b-328f-4f57-950c-3300c2bd2939)
![image](https://github.com/user-attachments/assets/085cdcee-5272-41bb-8612-06737c0ebe32)
![image](https://github.com/user-attachments/assets/a9ff0e34-892e-4538-9ea3-63fa0c222be4)
![image](https://github.com/user-attachments/assets/3e71f14b-c4f0-4e86-87d5-9217d88cb0c2)
![image](https://github.com/user-attachments/assets/f5c0933b-6a3e-463f-9170-c11f85610853)
![image](https://github.com/user-attachments/assets/c4e086c2-d4d5-4eee-8bab-dba8e5fdd90d)
## How to obtain Auth Token
> Downloading from **Withheld Accounts**
1. Go to [X's website](https://www.x.com/)
![image](https://github.com/user-attachments/assets/f5e301cf-9700-4986-a87d-8424be40db5c)
![image](https://github.com/user-attachments/assets/92f814b1-069f-4605-b31f-8a5ff8dc0f17)
![image](https://github.com/user-attachments/assets/c6e7dc0d-659d-456e-b30c-6cca66fe9359)
## How to Obtain Auth Token
> [!Warning]
> - I suggest not using the **main account** to obtain the token.
> - You can use https://temp-mail.io to register a Twitter account.
> - Using an auth token or cookies has the potential to get the **account suspended.**
> - If too many media files are fetched, it will trigger a **rate limit**, and the media retrieval will fail.
1. Go to [Twitter's website](https://www.x.com/)
2. Log into your account
3. Open the Developer Tools by pressing `F12`
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 [X.com Auth Token Grabber](https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases/download/v1.0/X.com.Auth.Token.Grabber.zip)
6. Do not log out of your account, as a new `auth_token` will be generated by Twitter
7. Close your browser
> X.com Auth Token Grabber
![image](https://github.com/user-attachments/assets/4bf5f787-d34f-4259-837c-07a6432c4360)
> Developer Tools
![image](https://github.com/user-attachments/assets/50f819da-7490-4f3c-b130-c5a3ee482e2d)
+558 -232
View File
@@ -1,16 +1,20 @@
import sys
import os
import json
import asyncio
import aiohttp
import requests
import re
import subprocess
from datetime import datetime
from pathlib import Path
from packaging import version
from PyQt6.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout,
QHBoxLayout, QLabel, QLineEdit, QPushButton,
QProgressBar, QFileDialog, QRadioButton, QComboBox)
from PyQt6.QtCore import QThread, pyqtSignal, Qt, QSettings
from PyQt6.QtGui import QIcon, QPixmap, QCursor
QProgressBar, QFileDialog, QRadioButton, QComboBox,
QGroupBox, QCheckBox, QDialog, QDialogButtonBox)
from PyQt6.QtCore import QThread, pyqtSignal, Qt, QSettings, QTimer, QUrl
from PyQt6.QtGui import QIcon, QPixmap, QCursor, QPainter, QPainterPath, QDesktopServices
from gallery_dl.extractor import twitter
class ImageDownloader(QThread):
finished = pyqtSignal(bytes)
@@ -35,117 +39,161 @@ class MetadataFetcher(QThread):
finished = pyqtSignal(dict)
error = pyqtSignal(str)
def __init__(self, username):
def __init__(self, username, media_type='media', use_local=False):
super().__init__()
self.username = username
self.auth_token = None
self.media_type = media_type
self.use_local = use_local
def run(self):
try:
username = self.username.strip()
if "x.com/" in username or "twitter.com/" in username:
username = username.split("/")[-1]
if username.endswith("/timeline"):
username = username[:-9]
url = f"https://x.com/{username}/timeline"
if getattr(sys, 'frozen', False):
base_path = sys._MEIPASS
else:
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:
json.dump(config, f)
except Exception as e:
raise Exception(f"Failed to write cookies file: {str(e)}")
def normalize_url(self, url_or_username):
url_or_username = url_or_username.strip()
username = url_or_username
if "x.com/" in url_or_username or "twitter.com/" in url_or_username:
parts = url_or_username.split('/')
for i, part in enumerate(parts):
if part in ['x.com', 'twitter.com'] and i + 1 < len(parts):
username = parts[i + 1]
username = username.split('/')[0]
break
username = username.strip()
return username
startupinfo = None
if sys.platform == 'win32':
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
async def fetch_from_api(self, username, auth_token):
try:
async with aiohttp.ClientSession() as session:
url = f"https://twitterxapis.vercel.app/metadata/{username}/{auth_token}"
async with session.get(url) as response:
if response.status == 200:
data = await response.json()
if self.media_type != 'media':
filtered_timeline = []
for item in data['timeline']:
if (self.media_type == 'image' and item['type'] == 'photo') or \
(self.media_type == 'gif' and item['type'] == 'animated_gif') or \
(self.media_type == 'video' and item['type'] == 'video'):
filtered_timeline.append(item)
data['timeline'] = filtered_timeline
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)}")
async def fetch_local(self, normalized):
try:
match = re.match(twitter.TwitterTimelineExtractor.pattern, f"https://x.com/{normalized}/timeline")
if not match:
raise ValueError(f"Invalid username: {normalized}")
extractor = twitter.TwitterTimelineExtractor(match)
extractor.config = lambda key, default=None: {
"cookies": {
"auth_token": self.auth_token
}
}.get(key, default)
try:
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
extractor.initialize()
data = json.loads(process.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
})
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)
}
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', '')
})
self.finished.emit(output)
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)
return output
except Exception as e:
raise ValueError(f"Local gallery-dl error: {str(e)}")
def run(self):
try:
normalized = self.normalize_url(self.username)
if not self.use_local:
try:
data = asyncio.run(self.fetch_from_api(normalized, self.auth_token))
self.finished.emit(data)
return
except Exception as api_error:
print(f"API fetch failed, falling back to local: {str(api_error)}")
pass
try:
data = asyncio.run(self.fetch_local(normalized))
self.finished.emit(data)
except Exception as local_error:
if not self.use_local:
raise ValueError(f"Both API and local methods failed.\nAPI error: {str(api_error)}\nLocal error: {str(local_error)}")
else:
raise ValueError(f"Local gallery-dl failed: {str(local_error)}")
except Exception as e:
self.error.emit(str(e))
@@ -155,93 +203,229 @@ class MediaDownloader(QThread):
error = 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__()
self.media_list = media_list
self.output_dir = output_dir
self.filename_format = filename_format
self.username = username
self.filename_format = filename_format
self.media_type = media_type
self.batch_size = batch_size
self._is_cancelled = False
self._download_lock = asyncio.Lock()
def cancel(self):
self._is_cancelled = True
async def download_file(self, session, url, filepath):
try:
if os.path.exists(filepath):
return True, True
if self._is_cancelled:
return False, False
os.makedirs(os.path.dirname(filepath), exist_ok=True)
async with session.get(url) as response:
if response.status == 200:
with open(filepath, 'wb') as f:
f.write(await response.read())
return True
return False
except Exception:
return False
return True, False
return False, False
except Exception as e:
print(f"Error downloading {url}: {str(e)}")
return False, False
async def download_all(self):
async with aiohttp.ClientSession() as session:
os.makedirs(self.output_dir, exist_ok=True)
timeout = aiohttp.ClientTimeout(total=30)
connector = aiohttp.TCPConnector(limit=self.batch_size)
async with aiohttp.ClientSession(timeout=timeout, connector=connector) as session:
total = len(self.media_list)
completed = 0
skipped = 0
failed = 0
tasks = []
for item in self.media_list:
url = item['url']
date = datetime.strptime(item['date'], "%Y-%m-%d %H:%M:%S")
formatted_date = date.strftime("%Y-%m-%d")
if self.filename_format == "username_date":
filename = f"{self.username}_{formatted_date}"
else:
filename = f"{formatted_date}_{self.username}"
filename = f"{filename}_{len(tasks):03d}.{'mp4' if 'video' in url else 'jpg'}"
filepath = os.path.join(self.output_dir, filename)
task = asyncio.create_task(self.download_file(session, url, filepath))
tasks.append(task)
if len(tasks) >= self.batch_size:
results = await asyncio.gather(*tasks)
completed += sum(1 for r in results if r)
progress = int((completed / total) * 100)
self.progress.emit(progress)
self.status_update.emit(f"Downloaded {completed} of {total} files...")
tasks = []
used_filenames = set()
if tasks:
results = await asyncio.gather(*tasks)
completed += sum(1 for r in results if r)
for i in range(0, total, self.batch_size):
if self._is_cancelled:
break
batch = self.media_list[i:i + self.batch_size]
tasks = []
for item in batch:
url = item['url']
date = datetime.strptime(item['date'], "%Y-%m-%d %H:%M:%S")
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":
base_filename = f"{self.username}_{formatted_date}_{tweet_id}"
else:
base_filename = f"{formatted_date}_{self.username}_{tweet_id}"
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)
task = asyncio.create_task(self.download_file(session, url, filepath))
tasks.append(task)
results = await asyncio.gather(*tasks, return_exceptions=True)
for result in results:
if isinstance(result, tuple):
success, was_skipped = result
if success:
completed += 1
if was_skipped:
skipped += 1
else:
failed += 1
else:
failed += 1
progress = int((completed / total) * 100)
self.progress.emit(progress)
return completed
completed_str = f"{completed:,}" if completed >= 1000 else str(completed)
total_str = f"{total:,}" if total >= 1000 else str(total)
skipped_str = f" ({skipped:,} skipped)" if skipped > 0 else ""
failed_str = f" ({failed:,} failed)" if failed > 0 else ""
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}{skipped_str}{failed_str}..."
)
await asyncio.sleep(0.1)
return completed, skipped, failed
def run(self):
try:
completed = asyncio.run(self.download_all())
self.finished.emit(f"Downloaded {completed} files successfully!")
completed, skipped, failed = asyncio.run(self.download_all())
if self._is_cancelled:
self.status_update.emit("Download cancelled")
return
completed_str = f"{completed:,}" if completed >= 1000 else str(completed)
skipped_str = f" ({skipped:,} skipped)" if skipped > 0 else ""
failed_str = f" ({failed:,} failed)" if failed > 0 else ""
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}{skipped_str}{failed_str} successfully!"
)
except Exception as e:
self.error.emit(str(e))
class UpdateDialog(QDialog):
def __init__(self, current_version, new_version, parent=None):
super().__init__(parent)
self.setWindowTitle("Update Available")
self.setFixedWidth(400)
self.setModal(True)
layout = QVBoxLayout()
message = QLabel(f"A new version of Twitter/X Media Batch Downloader is available!\n\n"
f"Current version: v{current_version}\n"
f"New version: v{new_version}")
message.setWordWrap(True)
layout.addWidget(message)
self.disable_check = QCheckBox("Turn off update checking")
self.disable_check.setCursor(Qt.CursorShape.PointingHandCursor)
layout.addWidget(self.disable_check)
button_box = QDialogButtonBox()
self.update_button = QPushButton("Update")
self.update_button.setCursor(Qt.CursorShape.PointingHandCursor)
self.cancel_button = QPushButton("Cancel")
self.cancel_button.setCursor(Qt.CursorShape.PointingHandCursor)
button_box.addButton(self.update_button, QDialogButtonBox.ButtonRole.AcceptRole)
button_box.addButton(self.cancel_button, QDialogButtonBox.ButtonRole.RejectRole)
layout.addWidget(button_box)
self.setLayout(layout)
self.update_button.clicked.connect(self.accept)
self.cancel_button.clicked.connect(self.reject)
class TwitterMediaDownloaderGUI(QMainWindow):
def __init__(self):
super().__init__()
self.current_version = "1.6"
self.setWindowTitle("Twitter/X Media Batch Downloader")
self.settings = QSettings('TwitterMediaDownloader', 'Settings')
self.check_for_updates = self.settings.value('check_for_updates', True, type=bool)
icon_path = os.path.join(os.path.dirname(__file__), "icon.svg")
if os.path.exists(icon_path):
self.setWindowIcon(QIcon(icon_path))
self.setFixedWidth(600)
self.setFixedHeight(180)
self.setFixedHeight(210)
self.default_pictures_dir = str(Path.home() / "Pictures")
if not os.path.exists(self.default_pictures_dir):
os.makedirs(self.default_pictures_dir)
os.makedirs(self.default_pictures_dir, exist_ok=True)
self.media_info = None
self.settings = QSettings('TwitterMediaDownloader', 'Settings')
self.init_ui()
self.load_settings()
self.setup_auto_save()
self.clean_username = None
if self.check_for_updates:
QTimer.singleShot(0, self.check_updates)
def check_updates(self):
try:
response = requests.get("https://raw.githubusercontent.com/afkarxyz/Twitter-X-Media-Batch-Downloader/refs/heads/main/version.json")
if response.status_code == 200:
data = response.json()
new_version = data.get("version")
if new_version and version.parse(new_version) > version.parse(self.current_version):
dialog = UpdateDialog(self.current_version, new_version, self)
result = dialog.exec()
if dialog.disable_check.isChecked():
self.settings.setValue('check_for_updates', False)
self.check_for_updates = False
if result == QDialog.DialogCode.Accepted:
QDesktopServices.openUrl(QUrl("https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases"))
except Exception as e:
print(f"Error checking for updates: {e}")
def init_ui(self):
central_widget = QWidget()
@@ -299,34 +483,82 @@ class TwitterMediaDownloaderGUI(QMainWindow):
auth_layout.addWidget(self.auth_input)
input_layout.addLayout(auth_layout)
combined_layout = QHBoxLayout()
batch_label = QLabel("Batch Size:")
batch_label.setFixedWidth(100)
settings_group = QGroupBox("Settings")
settings_layout = QVBoxLayout()
settings_layout.setSpacing(5)
settings_layout.setContentsMargins(5, 5, 5, 5)
centered_settings_layout = QHBoxLayout()
centered_settings_layout.addStretch()
media_layout = QHBoxLayout()
media_layout.setSpacing(5)
media_label = QLabel("Media Type:")
media_label.setFixedWidth(65)
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(70)
media_layout.addWidget(media_label)
media_layout.addWidget(self.media_type_combo)
media_layout.addSpacing(10)
self.use_api_checkbox = QCheckBox("Local")
self.use_api_checkbox.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
self.use_api_checkbox.setToolTip("Use local gallery-dl instead of API")
self.use_api_checkbox.stateChanged.connect(self.auto_save_settings)
media_layout.addWidget(self.use_api_checkbox)
media_layout.addSpacing(10)
batch_layout = QHBoxLayout()
batch_layout.setSpacing(5)
batch_label = QLabel("Batch:")
batch_label.setFixedWidth(35)
self.batch_size_combo = QComboBox()
self.batch_size_combo.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
self.batch_size_combo.setFixedWidth(70)
self.batch_size_combo.setFixedWidth(60)
for size in range(10, 101, 10):
self.batch_size_combo.addItem(str(size))
batch_layout.addWidget(batch_label)
batch_layout.addWidget(self.batch_size_combo)
batch_layout.addSpacing(10)
filename_layout = QHBoxLayout()
filename_layout.setSpacing(5)
format_label = QLabel("Filename:")
format_label.setFixedWidth(50)
self.format_username_date = QRadioButton("Username - Date")
self.format_date_username = QRadioButton("Date - Username")
self.format_username_date.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
self.format_date_username.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
combined_layout.addWidget(batch_label)
combined_layout.addWidget(self.batch_size_combo)
combined_layout.addSpacing(10)
combined_layout.addWidget(format_label)
combined_layout.addWidget(self.format_username_date)
combined_layout.addWidget(self.format_date_username)
combined_layout.addStretch()
input_layout.addLayout(combined_layout)
self.format_username = QRadioButton("Username")
self.format_date = QRadioButton("Date")
self.format_username.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
self.format_date.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
filename_layout.addWidget(format_label)
filename_layout.addWidget(self.format_username)
filename_layout.addWidget(self.format_date)
combined_layout = QHBoxLayout()
combined_layout.addLayout(media_layout)
combined_layout.addLayout(batch_layout)
combined_layout.addLayout(filename_layout)
centered_settings_layout.addLayout(combined_layout)
centered_settings_layout.addStretch()
settings_layout.addLayout(centered_settings_layout)
settings_group.setLayout(settings_layout)
input_layout.addWidget(settings_group)
self.main_layout.addWidget(self.input_widget)
@@ -453,15 +685,19 @@ class TwitterMediaDownloaderGUI(QMainWindow):
self.url_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.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.use_api_checkbox.stateChanged.connect(self.auto_save_settings)
self.batch_size_combo.currentTextChanged.connect(self.auto_save_settings)
def auto_save_settings(self):
self.settings.setValue('url_input', self.url_input.text())
self.settings.setValue('auth_token', self.auth_input.text())
self.settings.setValue('output_dir', self.dir_input.text())
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('use_local', self.use_api_checkbox.isChecked())
self.settings.setValue('batch_size', self.batch_size_combo.currentText())
self.settings.sync()
@@ -471,10 +707,19 @@ class TwitterMediaDownloaderGUI(QMainWindow):
self.dir_input.setText(self.settings.value('output_dir', self.default_pictures_dir, str))
format_setting = self.settings.value('filename_format', 'username_date')
self.format_username_date.setChecked(format_setting == 'username_date')
self.format_date_username.setChecked(format_setting == 'date_username')
self.format_username.setChecked(format_setting == 'username_date')
self.format_date.setChecked(format_setting == 'date_username')
batch_size = self.settings.value('batch_size', '10')
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
use_local = self.settings.value('use_local', False, type=bool)
self.use_api_checkbox.setChecked(use_local)
batch_size = self.settings.value('batch_size', '20')
index = self.batch_size_combo.findText(batch_size)
if index >= 0:
self.batch_size_combo.setCurrentIndex(index)
@@ -482,6 +727,7 @@ class TwitterMediaDownloaderGUI(QMainWindow):
def select_directory(self):
directory = QFileDialog.getExistingDirectory(self, "Select Output Directory")
if directory:
os.makedirs(directory, exist_ok=True)
self.dir_input.setText(directory)
def open_output_directory(self):
@@ -508,72 +754,154 @@ class TwitterMediaDownloaderGUI(QMainWindow):
self.fetch_button.setEnabled(False)
self.status_label.setText("Fetching profile information...")
self.fetcher = MetadataFetcher(username)
media_type = self.media_type_combo.currentData()
use_local = self.use_api_checkbox.isChecked()
self.fetcher = MetadataFetcher(username, media_type, use_local)
self.fetcher.auth_token = auth_token
self.fetcher.finished.connect(self.handle_profile_info)
self.fetcher.error.connect(self.handle_fetch_error)
self.fetcher.start()
def handle_profile_info(self, info):
if not info.get('account_info'):
self.status_label.setText("Failed to fetch profile information")
try:
if not info or not isinstance(info, dict):
raise ValueError("Invalid info data received")
account_info = info.get('account_info', {})
if not account_info:
self.status_label.setText("Failed to fetch profile information")
self.fetch_button.setEnabled(True)
return
self.media_info = info
self.fetch_button.setEnabled(True)
return
self.media_info = info
self.fetch_button.setEnabled(True)
account_info = info['account_info']
name = account_info['name']
nick = account_info['nick']
join_date = datetime.strptime(account_info['date'], "%Y-%m-%d %H:%M:%S")
followers = account_info['followers_count']
following = account_info['friends_count']
posts = account_info['statuses_count']
join_date_str = join_date.strftime("%A, %d %B %Y - %H:%M")
self.name_label.setText(f"<b>{name}</b> ({nick})")
self.join_date_label.setText(f"<b>Join Date:</b> {join_date_str}")
self.followers_label.setText(f"<b>Followers:</b> {followers:,}")
self.following_label.setText(f"<b>Following:</b> {following:,}")
self.posts_label.setText(f"<b>Posts:</b> {posts:,}")
is_withheld = not account_info.get('nick') and not account_info.get('profile_image')
name = account_info.get('name', 'Unknown')
nick = "Withheld Account" if is_withheld else account_info.get('nick', 'Unknown')
date_str = account_info.get('date', '')
followers = account_info.get('followers_count', 0)
following = account_info.get('friends_count', 0)
posts = account_info.get('statuses_count', 0)
try:
join_date = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")
join_date_str = join_date.strftime("%A, %d %B %Y - %H:%M")
except (ValueError, TypeError):
join_date_str = "Unknown Date"
try:
self.name_label.setText(f"<b>{name}</b> ({nick})")
self.join_date_label.setText(f"<b>Join Date:</b> {join_date_str}")
self.followers_label.setText(f"<b>Followers:</b> {followers:,}")
self.following_label.setText(f"<b>Following:</b> {following:,}")
self.posts_label.setText(f"<b>Posts:</b> {posts:,}")
media_count = len(info['timeline'])
self.status_label.setText(f"Successfully fetched {media_count:,} media items")
profile_image_url = account_info['profile_image']
self.image_downloader = ImageDownloader(profile_image_url)
self.image_downloader.finished.connect(self.update_profile_image)
self.image_downloader.start()
self.input_widget.hide()
self.profile_widget.show()
self.download_button.show()
self.cancel_button.show()
self.update_button.hide()
timeline = info.get('timeline', [])
media_count = len(timeline) if isinstance(timeline, list) else 0
self.status_label.setText(f"Successfully fetched {media_count:,} media items")
except Exception as ui_error:
self.status_label.setText(f"Error updating UI: {str(ui_error)}")
return
username = self.url_input.text().strip()
if "x.com/" in username or "twitter.com/" in username:
username = username.split("/")[-1]
if username.endswith("/timeline"):
username = username[:-9]
output_base = self.dir_input.text().strip() or self.default_pictures_dir
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)
if is_withheld:
try:
withheld_icon_path = os.path.join(os.path.dirname(__file__), "withheld.svg")
if os.path.exists(withheld_icon_path):
icon = QIcon(withheld_icon_path)
pixmap = icon.pixmap(90, 90)
painter = QPainter(pixmap)
painter.setCompositionMode(QPainter.CompositionMode.CompositionMode_SourceIn)
painter.fillRect(pixmap.rect(), self.palette().text().color())
painter.end()
scaled_pixmap = pixmap.scaled(
90, 90,
Qt.AspectRatioMode.KeepAspectRatio,
Qt.TransformationMode.SmoothTransformation
)
self.profile_image_label.setPixmap(scaled_pixmap)
else:
print("Withheld icon not found:", withheld_icon_path)
except Exception as icon_error:
print(f"Error loading withheld icon: {str(icon_error)}")
else:
profile_image_url = account_info.get('profile_image', '')
if profile_image_url:
try:
self.image_downloader = ImageDownloader(profile_image_url)
self.image_downloader.finished.connect(self.update_profile_image)
self.image_downloader.start()
except Exception as img_error:
print(f"Error starting image download: {str(img_error)}")
try:
username = self.url_input.text().strip()
if "x.com/" in username or "twitter.com/" in username:
parts = username.split('/')
for i, part in enumerate(parts):
if part in ['x.com', 'twitter.com'] and i + 1 < len(parts):
username = parts[i + 1]
username = username.split('/')[0]
break
self.clean_username = username.strip()
except Exception as username_error:
self.clean_username = "unknown_user"
print(f"Error cleaning username: {str(username_error)}")
self.input_widget.hide()
self.profile_widget.show()
self.download_button.show()
self.cancel_button.show()
self.update_button.hide()
self.setFixedHeight(180)
try:
output_base = self.dir_input.text().strip() or self.default_pictures_dir
self.user_output_dir = os.path.join(output_base, self.clean_username)
os.makedirs(self.user_output_dir, exist_ok=True)
except Exception as dir_error:
self.status_label.setText(f"Error creating output directory: {str(dir_error)}")
return
except Exception as e:
self.status_label.setText(f"Error processing profile info: {str(e)}")
self.fetch_button.setEnabled(True)
print(f"Full error in handle_profile_info: {str(e)}")
def update_profile_image(self, image_data):
pixmap = QPixmap()
pixmap.loadFromData(image_data)
scaled_pixmap = pixmap.scaled(100, 100, Qt.AspectRatioMode.KeepAspectRatio,
Qt.TransformationMode.SmoothTransformation)
self.profile_image_label.setPixmap(scaled_pixmap)
original_pixmap = QPixmap()
original_pixmap.loadFromData(image_data)
scaled_pixmap = original_pixmap.scaled(100, 100,
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):
self.fetch_button.setEnabled(True)
self.status_label.setText(f"Error fetching profile info: {error}")
error_str = str(error)
if "Local gallery-dl error: None" in error_str and self.use_api_checkbox.isChecked():
self.status_label.setText("Please uncheck the 'Local' option to fetch metadata using the API method.")
else:
self.status_label.setText(f"Error fetching profile info: {error}")
def start_download(self):
if not self.media_info:
@@ -591,20 +919,16 @@ class TwitterMediaDownloaderGUI(QMainWindow):
self.progress_bar.setValue(0)
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())
username = self.url_input.text().strip()
if "x.com/" in username or "twitter.com/" in username:
username = username.split("/")[-1]
if username.endswith("/timeline"):
username = username[:-9]
media_type = self.media_type_combo.currentData()
self.worker = MediaDownloader(
self.media_info['timeline'],
self.user_output_dir,
filename_format,
username,
self.clean_username,
media_type,
batch_size
)
self.worker.progress.connect(self.update_progress)
@@ -642,6 +966,7 @@ class TwitterMediaDownloaderGUI(QMainWindow):
self.download_button.setText("Download")
self.download_button.clicked.disconnect()
self.download_button.clicked.connect(self.start_download)
self.setFixedHeight(210)
def download_error(self, error_message):
self.progress_bar.hide()
@@ -662,6 +987,7 @@ class TwitterMediaDownloaderGUI(QMainWindow):
self.media_info = None
self.update_button.show()
self.fetch_button.setEnabled(True)
self.setFixedHeight(210)
def main():
if getattr(sys, 'frozen', False):
+3
View File
@@ -0,0 +1,3 @@
{
"version": "1.7"
}