Compare commits

..
15 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
5 changed files with 220 additions and 130 deletions

No files matched your search

+4 -3
View File
@@ -4,7 +4,7 @@ import os
from datetime import datetime
from gallery_dl.extractor import twitter
def get_metadata(username):
def get_metadata(username, auth_token):
url = f"https://x.com/{username}/timeline"
match = re.match(twitter.TwitterTimelineExtractor.pattern, url)
@@ -15,7 +15,7 @@ def get_metadata(username):
extractor.config = lambda key, default=None: {
"cookies": {
"auth_token": ""
"auth_token": auth_token
}
}.get(key, default)
@@ -75,4 +75,5 @@ def get_metadata(username):
return output
username = ""
get_metadata(username)
auth_token = ""
get_metadata(username, auth_token)
+4 -3
View File
@@ -3,7 +3,7 @@ import re
import os
from gallery_dl.extractor import twitter
def get_metadata(username):
def get_metadata(username, auth_token):
url = f"https://x.com/{username}/timeline"
match = re.match(twitter.TwitterTimelineExtractor.pattern, url)
@@ -14,7 +14,7 @@ def get_metadata(username):
extractor.config = lambda key, default=None: {
"cookies": {
"auth_token": ""
"auth_token": auth_token
}
}.get(key, default)
@@ -31,4 +31,5 @@ def get_metadata(username):
json.dump(all_items, f, indent=2, default=str)
username = ""
get_metadata(username)
auth_token = ""
get_metadata(username, auth_token)
+18 -14
View File
@@ -8,34 +8,31 @@
## Download
- Download the latest version of [TwitterXMediaBatchDownloader](https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases/download/v1.3/TwitterXMediaBatchDownloader.exe)
- 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**
- Simple and compact GUI
- 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
- Option to choose the media type to download: **media** (image + GIF + video) or just **image/GIF/video**
- **Batch** download settings, ranging from 10 to 100 files per download
- Filename format customization
## Screenshots
![image](https://github.com/user-attachments/assets/c8af187c-fd4c-4b3d-abb8-475a4d4a6b14)
![image](https://github.com/user-attachments/assets/085cdcee-5272-41bb-8612-06737c0ebe32)
![image](https://github.com/user-attachments/assets/8e9ecb0b-59ec-43a8-9648-78838b121582)
![image](https://github.com/user-attachments/assets/3e71f14b-c4f0-4e86-87d5-9217d88cb0c2)
![image](https://github.com/user-attachments/assets/779c7f75-08fb-4ba8-977a-8a29bae4a7e3)
![image](https://github.com/user-attachments/assets/c4e086c2-d4d5-4eee-8bab-dba8e5fdd90d)
> Downloading from **Withheld Accounts**
![image](https://github.com/user-attachments/assets/8ed5d0de-e83e-4dca-bf17-f9ed78bfd2ae)
![image](https://github.com/user-attachments/assets/f5e301cf-9700-4986-a87d-8424be40db5c)
![image](https://github.com/user-attachments/assets/bb76e9f1-6fa9-416d-92f1-e9d10ff85d86)
![image](https://github.com/user-attachments/assets/92f814b1-069f-4605-b31f-8a5ff8dc0f17)
![image](https://github.com/user-attachments/assets/48bf3cc6-81d7-45dd-9d8c-40ef5b0317e9)
![image](https://github.com/user-attachments/assets/c6e7dc0d-659d-456e-b30c-6cca66fe9359)
## How to Obtain Auth Token
@@ -43,12 +40,19 @@
> - 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 or use the browser extension [Cookie-Editor](https://cookie-editor.com/)
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
> 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)
+191 -110
View File
@@ -2,16 +2,18 @@ import sys
import os
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,
QGroupBox, QCheckBox)
from PyQt6.QtCore import QThread, pyqtSignal, Qt, QSettings
from PyQt6.QtGui import QIcon, QPixmap, QCursor, QPainter, QPainterPath
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):
@@ -37,12 +39,12 @@ class MetadataFetcher(QThread):
finished = pyqtSignal(dict)
error = pyqtSignal(str)
def __init__(self, username, media_type='media', use_api=True):
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_api = use_api
self.use_local = use_local
def normalize_url(self, url_or_username):
url_or_username = url_or_username.strip()
@@ -82,101 +84,115 @@ class MetadataFetcher(QThread):
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)
extractor.initialize()
output = {
'account_info': {},
'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)
}
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)
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)
try:
data = asyncio.run(self.fetch_from_api(normalized, self.auth_token))
self.finished.emit(data)
return
except Exception as api_error:
if not self.use_local:
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)
extractor.initialize()
output = {
'account_info': {},
'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)
}
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)
except Exception as local_error:
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))
@@ -327,11 +343,50 @@ class MediaDownloader(QThread):
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))
@@ -343,12 +398,34 @@ class TwitterMediaDownloaderGUI(QMainWindow):
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()
@@ -431,9 +508,9 @@ class TwitterMediaDownloaderGUI(QMainWindow):
media_layout.addWidget(self.media_type_combo)
media_layout.addSpacing(10)
self.use_api_checkbox = QCheckBox("Use API")
self.use_api_checkbox.setToolTip("Use external API instead of gallery-dl")
self.use_api_checkbox.setChecked(True)
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)
@@ -450,7 +527,6 @@ class TwitterMediaDownloaderGUI(QMainWindow):
self.batch_size_combo.setFixedWidth(60)
for size in range(10, 101, 10):
self.batch_size_combo.addItem(str(size))
self.batch_size_combo.setCurrentText("20")
batch_layout.addWidget(batch_label)
batch_layout.addWidget(self.batch_size_combo)
@@ -575,8 +651,6 @@ class TwitterMediaDownloaderGUI(QMainWindow):
self.main_layout.addWidget(self.progress_bar)
bottom_layout = QHBoxLayout()
bottom_layout.setContentsMargins(0, 0, 0, 0)
bottom_layout.setSpacing(5)
self.status_label = QLabel("")
bottom_layout.addWidget(self.status_label, stretch=1)
@@ -602,7 +676,6 @@ class TwitterMediaDownloaderGUI(QMainWindow):
bottom_layout.addWidget(self.update_button)
self.main_layout.addLayout(bottom_layout)
self.main_layout.setAlignment(bottom_layout, Qt.AlignmentFlag.AlignBottom)
def open_update_page(self):
import webbrowser
@@ -624,7 +697,7 @@ class TwitterMediaDownloaderGUI(QMainWindow):
self.settings.setValue('filename_format',
'username_date' if self.format_username.isChecked() else 'date_username')
self.settings.setValue('media_type', self.media_type_combo.currentData())
self.settings.setValue('use_api', self.use_api_checkbox.isChecked())
self.settings.setValue('use_local', self.use_api_checkbox.isChecked())
self.settings.setValue('batch_size', self.batch_size_combo.currentText())
self.settings.sync()
@@ -643,8 +716,8 @@ class TwitterMediaDownloaderGUI(QMainWindow):
self.media_type_combo.setCurrentIndex(i)
break
use_api = self.settings.value('use_api', True, type=bool)
self.use_api_checkbox.setChecked(use_api)
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)
@@ -682,8 +755,8 @@ class TwitterMediaDownloaderGUI(QMainWindow):
self.status_label.setText("Fetching profile information...")
media_type = self.media_type_combo.currentData()
use_api = self.use_api_checkbox.isChecked()
self.fetcher = MetadataFetcher(username, media_type, use_api)
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)
@@ -706,7 +779,7 @@ class TwitterMediaDownloaderGUI(QMainWindow):
is_withheld = not account_info.get('nick') and not account_info.get('profile_image')
name = account_info.get('name', 'Unknown')
nick = "Withheld" if is_withheld else account_info.get('nick', '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)
@@ -783,6 +856,7 @@ class TwitterMediaDownloaderGUI(QMainWindow):
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
@@ -822,7 +896,12 @@ class TwitterMediaDownloaderGUI(QMainWindow):
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:
@@ -887,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()
@@ -907,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"
}