Compare commits

..
111 Commits
Author SHA1 Message Date
afkarxyz dacf6f5a01 v3.5 2025-09-11 22:24:40 +07:00
afkarxyz fe095afb38 v3.4 2025-08-08 16:35:38 +07:00
afkarxyz e769ea8d20 v3.4 2025-08-08 15:51:32 +07:00
afkarxyz befe838e79 v3.4 2025-08-08 15:20:30 +07:00
afkarxyz b534bc278e Update README.md 2025-08-08 15:17:31 +07:00
afkarxyz 2e882635eb v3.3 2025-07-31 12:08:25 +07:00
afkarxyz 5d5b778c8e v3.3 2025-07-30 05:26:56 +07:00
afkarxyz 7cf134f681 v3.3 2025-07-30 05:24:47 +07:00
afkarxyz 7d90eb7cb2 v3.3 2025-07-26 21:27:45 +07:00
afkarxyz 3d1fd7d1fb v3.3 2025-07-26 21:11:53 +07:00
afkarxyz c0885b1812 v3.2 2025-07-26 12:34:42 +07:00
afkarxyz 1ca5c613ae Update latest.json 2025-07-26 12:34:32 +07:00
afkarxyz 596ba9bb3c v3.2 2025-07-26 12:33:59 +07:00
afkarxyz a1cbb04402 v3.2 2025-07-26 12:33:58 +07:00
afkarxyz ddf6439893 v3.2 2025-07-26 12:27:48 +07:00
afkarxyz fed2bf7b0c Create latest.json 2025-07-26 12:24:54 +07:00
afkarxyz 241884de89 v3.2 2025-07-26 12:20:20 +07:00
afkarxyz 77b443ace0 v3.2 2025-07-26 11:55:30 +07:00
afkarxyz cd48b6f9bc Update README.md 2025-07-26 11:44:31 +07:00
afkarxyz 6f45b48047 v3.1 2025-07-19 05:45:26 +07:00
afkarxyz 7083c56c8b v3.1 2025-07-19 05:40:26 +07:00
afkarxyz 60cb3cbabd v3.1 2025-07-19 01:06:36 +07:00
afkarxyz b38bff238a . 2025-07-19 01:06:15 +07:00
afkarxyz d4d216ed6b v3.1 2025-07-19 01:04:35 +07:00
afkarxyz 129c007f6f v3.1 2025-07-18 23:42:12 +07:00
afkarxyz d78ad32c09 v3.1 2025-07-18 23:26:33 +07:00
afkarxyz 3975e5dd0e v3.0 2025-07-17 09:54:09 +07:00
afkarxyz 37f1d910cb v3.0 2025-07-14 09:49:50 +07:00
afkarxyz 74ed38cc31 v3.0 2025-07-14 09:24:38 +07:00
afkarxyz 2e326c39a0 v3.0 2025-07-14 09:22:56 +07:00
afkarxyz 39c37d4776 v3.0 2025-07-13 22:04:17 +07:00
afkarxyz 5709d76ceb . 2025-07-13 22:04:00 +07:00
afkarxyz 75b3549653 Update README.md 2025-07-13 21:55:44 +07:00
afkarxyz ebe739e612 Add files via upload 2025-07-13 21:20:26 +07:00
afkarxyz d423f20bad Update README.md 2025-07-13 21:14:28 +07:00
afkarxyz fba8a8ac45 Update README.md 2025-07-13 00:15:58 +07:00
afkarxyz a36c7613d2 Update README.md 2025-07-13 00:07:41 +07:00
afkarxyz c7615ed2f6 Merge pull request #16 from Alvin-Zilverstand/main
feat: Add Linux executable and compilation instructions
2025-07-12 22:12:19 +07:00
afkarxyz 0c17f1b419 Update README.md 2025-07-12 22:09:34 +07:00
Alvin dd38880366 feat: Add Linux executable and compilation instructions 2025-07-11 21:12:40 +02:00
afkarxyz 306d2c3c95 v3.0 2025-07-05 06:16:21 +07:00
afkarxyz 1caa59bbcf v3.0 2025-07-04 13:47:23 +07:00
afkarxyz 4d0021092c v3.0 2025-07-04 13:44:57 +07:00
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
afkarxyz 43f4d84593 v2.8 2025-07-03 20:30:46 +07:00
afkarxyz 4cecb6b14e Update README.md 2025-07-03 20:17:50 +07:00
afkarxyz eb712d5d8d Update README.md 2025-07-03 19:59:24 +07:00
afkarxyz 46c178fec0 Update README.md 2025-06-29 14:59:54 +07:00
afkarxyz 8ce5f1f833 v2.7 2025-06-24 18:39:50 +07:00
afkarxyz 0a80a3d331 v2.7 2025-06-24 18:39:30 +07:00
afkarxyz f8b27ecb5a v2.7 2025-06-24 18:30:38 +07:00
afkarxyz 70e79af700 v2.6 2025-06-03 05:17:49 +07:00
afkarxyz 4fb60840a0 v2.6 2025-05-31 20:23:57 +07:00
afkarxyz 5613c152f8 v2.6 2025-05-31 20:19:24 +07:00
afkarxyz ad5d7727eb Update README.md 2025-05-31 20:16:53 +07:00
afkarxyz ed1f0fce06 v2.5 2025-05-08 08:03:31 +07:00
afkarxyz ee92174773 v2.4.5 2025-05-08 07:54:31 +07:00
afkarxyz f08ce57feb Update README.md 2025-05-06 15:37:20 +07:00
afkarxyz 4f21321e42 Update README.md 2025-05-04 06:24:24 +07:00
afkarxyz c8b7a5365a v2.4 2025-05-04 06:22:28 +07:00
afkarxyz 1049b544c5 v2.4 2025-05-04 06:19:03 +07:00
afkarxyz e7db97a936 Small fix 2025-04-23 18:32:29 +07:00
afkarxyz af1280b798 Update v2.3 2025-04-23 18:27:12 +07:00
afkarxyz 4f6004a501 Update v2.3 2025-04-23 18:23:34 +07:00
afkarxyz e7141cd8d1 Update v2.2 2025-04-22 22:01:51 +07:00
afkarxyz 4d6f4d904a Update v2.2 2025-04-22 21:57:59 +07:00
afkarxyz 4081e6aacf Update README.md 2025-04-22 21:45:29 +07:00
afkarxyz 2b405a16a7 Update v2.1 2025-04-22 05:35:30 +07:00
afkarxyz 5e658c05d4 Update v2.1 2025-04-22 05:22:34 +07:00
afkarxyz b26dd0b2af Update TwitterXMediaBatchDownloader.py 2025-03-25 19:44:54 +07:00
afkarxyz 28422dcf1d Update v2.0 2025-03-25 18:47:21 +07:00
afkarxyz 46e09532fc Update v2.0 2025-03-25 18:44:06 +07:00
afkarxyz 967d91d370 Update README.md 2025-03-25 18:42:57 +07:00
afkarxyz 2ff0242e32 Update README.md 2025-03-24 04:41:38 +07:00
afkarxyz 1e1d612807 Update README.md 2025-03-23 23:59:41 +07:00
afkarxyz 9821dd8c65 Update README.md 2025-03-23 23:59:07 +07:00
afkarxyz 46bb7d38f7 Update README.md 2025-03-23 23:58:34 +07:00
afkarxyz 112f5992c4 Batch Request 2025-03-23 23:48:06 +07:00
afkarxyz 178b3c490f Update v1.9 2025-03-23 23:35:15 +07:00
afkarxyz bb1c0dccae Merge branch 'main' of https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader 2025-03-23 23:31:55 +07:00
afkarxyz 0cf5316745 Update v1.9 2025-03-23 23:31:44 +07:00
afkarxyz c3493944e8 Update README.md 2025-03-23 23:30:54 +07:00
afkarxyz c656459171 Update README.md 2025-03-23 21:11:17 +07:00
afkarxyz 0e14f92244 Update README.md 2025-03-23 18:40:24 +07:00
afkarxyz fad4434753 Update README.md 2025-03-23 18:34:41 +07:00
afkarxyz 77a9c83f4d Update v1.8 2025-03-23 18:30:14 +07:00
afkarxyz 7fa277931c Update v1.8 2025-03-23 18:26:37 +07:00
afkarxyz be080481bf Update README.md 2025-03-23 18:24:45 +07:00
afkarxyz 8a720e3e2b Update README.md 2025-03-04 09:16:57 +07:00
afkarxyz 48a672e0bd Update README.md 2025-03-04 09:10:50 +07:00
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
12 changed files with 7414 additions and 1069 deletions

No files matched your search

-78
View File
@@ -1,78 +0,0 @@
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
@@ -1,34 +0,0 @@
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)
Binary file not shown.
+11 -11
View File
@@ -1,11 +1,11 @@
<?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>
<?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

After

Width:  |  Height:  |  Size: 865 B

+121 -25
View File
@@ -3,52 +3,148 @@
![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>
<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.3/TwitterXMediaBatchDownloader.exe)
- If you're familiar with **userscripts**, please install it [here](https://greasyfork.org/en/scripts/523157-twitter-x-media-batch-downloader)
- [**Windows**](https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases/download/v3.4/TwitterXMediaBatchDownloader_Windows.exe)
- [**Linux**](https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases/download/v3.4/TwitterXMediaBatchDownloader_Linux)
- [**Mac**](https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases/download/v3.4/TwitterXMediaBatchDownloader_Mac.app.zip)
- If you're familiar with **userscripts**, please install it [**here**](https://greasyfork.org/en/scripts/523157)
## Features
### The downloaded application won't run❓
- Uses the powerful `gallery-dl` library, similar to `yt-dlp`
- The ability to download media from **Withheld Accounts**
- Simple and compact GUI
- 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
🐧 **Solution (Ubuntu/Linux)**: Open your terminal and run:
```bash
chmod +x TwitterXMediaBatchDownloader_Linux
```
https://github.com/user-attachments/assets/cc7400ec-76dd-4519-848d-71a834b7ec95
🍎 **Solution (macOS)**: Open your terminal and run:
```bash
xattr -rd com.apple.quarantine ~/Downloads/TwitterXMediaBatchDownloader_Mac.app
```
https://github.com/user-attachments/assets/4b13c0b9-cf3a-48ce-ac35-a19007189ac8
## ✨ Features
- Powered by `gallery-dl`, similar to `yt-dlp`
- **Bulk download**: Download multiple accounts at once
- Media-type selection: All (Images + GIFs + Videos) or specific (Images / GIFs / Videos)
- **MP4 → GIF conversion:** Convert downloaded MP4 videos into GIF format
- Downloads at original quality
## Screenshots
## 🖼️ Screenshots
![image](https://github.com/user-attachments/assets/c8af187c-fd4c-4b3d-abb8-475a4d4a6b14)
![image](https://github.com/user-attachments/assets/bae739f3-c6be-415f-8e9b-18cceae659f6)
![image](https://github.com/user-attachments/assets/8e9ecb0b-59ec-43a8-9648-78838b121582)
![image](https://github.com/user-attachments/assets/cfb57b60-661d-4d82-a1f3-1e859a33e8c4)
![image](https://github.com/user-attachments/assets/779c7f75-08fb-4ba8-977a-8a29bae4a7e3)
## 🐧 Build Yourself (Ubuntu/Linux)
> Downloading from **Withheld Accounts**
### 1. Install Required Packages
![image](https://github.com/user-attachments/assets/8ed5d0de-e83e-4dca-bf17-f9ed78bfd2ae)
```bash
sudo apt install git python3-pip python3-venv
```
![image](https://github.com/user-attachments/assets/bb76e9f1-6fa9-416d-92f1-e9d10ff85d86)
### 2. Clone the Repository
![image](https://github.com/user-attachments/assets/48bf3cc6-81d7-45dd-9d8c-40ef5b0317e9)
```bash
git clone https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader.git
cd Twitter-X-Media-Batch-Downloader
```
## How to Obtain Auth Token
### 3. Create and Activate a Virtual Environment
```bash
python3 -m venv .venv
source .venv/bin/activate
```
### 4. Install Python Dependencies
```bash
pip install -r requirements.txt
pip install pyinstaller
```
### 5. Build the Application
```bash
pyinstaller --onefile --windowed TwitterXMediaBatchDownloader_Linux.py
```
The compiled binary will be located in the `dist/` folder.
## 🍎 Build Yourself (macOS)
### 1. Install Homebrew (if not already installed)
```bash
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
```
### 2. Install Git and Python
```bash
brew install git python
```
### 3. Go to Downloads and Clone the Repository
```bash
cd ~/Downloads
git clone https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader.git
cd Twitter-X-Media-Batch-Downloader
```
### 4. Create and Activate a Virtual Environment
```bash
python3 -m venv .venv
source .venv/bin/activate
```
### 5. Install Python Dependencies
```bash
pip install -r requirements.txt
pip install pyinstaller
```
### 6. Build the Application
```bash
pyinstaller --onefile --windowed --icon=Archived/icon.icns TwitterXMediaBatchDownloader_Mac.py
```
The `.app` bundle will be generated inside the `dist/` folder.
## 🔑 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 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/)
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/)
4. Navigate to the **Application** tab, then select **Storage → Cookies**
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
![image](https://github.com/user-attachments/assets/50f819da-7490-4f3c-b130-c5a3ee482e2d)
> 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/8e81dd8f-f8be-4254-9cf6-cacfa97743e9)
-921
View File
@@ -1,921 +0,0 @@
import sys
import os
import asyncio
import aiohttp
import re
import subprocess
from datetime import datetime
from pathlib import Path
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
from gallery_dl.extractor import twitter
class ImageDownloader(QThread):
finished = pyqtSignal(bytes)
def __init__(self, url):
super().__init__()
self.url = url
async def download_image(self):
async with aiohttp.ClientSession() as session:
async with session.get(self.url) as response:
if response.status == 200:
return await response.read()
return None
def run(self):
image_data = asyncio.run(self.download_image())
if image_data:
self.finished.emit(image_data)
class MetadataFetcher(QThread):
finished = pyqtSignal(dict)
error = pyqtSignal(str)
def __init__(self, username, media_type='media', use_api=True):
super().__init__()
self.username = username
self.auth_token = None
self.media_type = media_type
self.use_api = use_api
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
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)}")
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:
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:
raise ValueError(f"Both API and local methods failed.\nAPI error: {str(api_error)}\nLocal error: {str(local_error)}")
except Exception as e:
self.error.emit(str(e))
class MediaDownloader(QThread):
progress = pyqtSignal(int)
finished = pyqtSignal(str)
error = pyqtSignal(str)
status_update = pyqtSignal(str)
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.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, False
return False, False
except Exception as e:
print(f"Error downloading {url}: {str(e)}")
return False, False
async def download_all(self):
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
used_filenames = set()
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)
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, 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 TwitterMediaDownloaderGUI(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Twitter/X Media Batch Downloader")
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(210)
self.default_pictures_dir = str(Path.home() / "Pictures")
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
def init_ui(self):
central_widget = QWidget()
self.setCentralWidget(central_widget)
self.main_layout = QVBoxLayout(central_widget)
self.main_layout.setContentsMargins(10, 10, 10, 10)
self.input_widget = QWidget()
input_layout = QVBoxLayout(self.input_widget)
input_layout.setSpacing(10)
url_layout = QHBoxLayout()
url_label = QLabel("Username/URL:")
url_label.setFixedWidth(100)
self.url_input = QLineEdit()
self.url_input.setPlaceholderText("e.g. Takomayuyi or https://x.com/Takomayuyi")
self.url_input.setClearButtonEnabled(True)
self.fetch_button = QPushButton("Fetch")
self.fetch_button.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
self.fetch_button.setFixedWidth(100)
self.fetch_button.clicked.connect(self.fetch_metadata)
url_layout.addWidget(url_label)
url_layout.addWidget(self.url_input)
url_layout.addWidget(self.fetch_button)
input_layout.addLayout(url_layout)
dir_layout = QHBoxLayout()
dir_label = QLabel("Output Directory:")
dir_label.setFixedWidth(100)
self.dir_input = QLineEdit(self.default_pictures_dir)
self.dir_button = QPushButton("Browse")
self.dir_button.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
self.dir_button.setFixedWidth(100)
self.dir_button.clicked.connect(self.select_directory)
dir_layout.addWidget(dir_label)
dir_layout.addWidget(self.dir_input)
dir_layout.addWidget(self.dir_button)
input_layout.addLayout(dir_layout)
auth_layout = QHBoxLayout()
auth_label = QLabel("Auth Token:")
auth_label.setFixedWidth(100)
self.auth_input = QLineEdit()
self.auth_input.setPlaceholderText("Enter your Twitter/X auth_token")
self.auth_input.setClearButtonEnabled(True)
auth_layout.addWidget(auth_label)
auth_layout.addWidget(self.auth_input)
input_layout.addLayout(auth_layout)
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("Use API")
self.use_api_checkbox.setToolTip("Use external API instead of gallery-dl")
self.use_api_checkbox.setChecked(True)
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(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)
batch_layout.addSpacing(10)
filename_layout = QHBoxLayout()
filename_layout.setSpacing(5)
format_label = QLabel("Filename:")
format_label.setFixedWidth(50)
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)
self.profile_widget = QWidget()
self.profile_widget.hide()
profile_layout = QHBoxLayout(self.profile_widget)
profile_layout.setContentsMargins(0, 0, 0, 0)
profile_layout.setSpacing(10)
profile_container = QWidget()
profile_image_layout = QVBoxLayout(profile_container)
profile_image_layout.setContentsMargins(0, 0, 0, 0)
profile_image_layout.setAlignment(Qt.AlignmentFlag.AlignTop)
self.profile_image_label = QLabel()
self.profile_image_label.setFixedSize(100, 100)
self.profile_image_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
profile_image_layout.addWidget(self.profile_image_label)
profile_layout.addWidget(profile_container)
profile_details_container = QWidget()
profile_details_layout = QVBoxLayout(profile_details_container)
profile_details_layout.setContentsMargins(0, 0, 0, 0)
profile_details_layout.setSpacing(2)
profile_details_layout.setAlignment(Qt.AlignmentFlag.AlignTop)
self.name_label = QLabel()
self.name_label.setStyleSheet("font-size: 14px;")
self.name_label.setWordWrap(True)
self.name_label.setMinimumWidth(400)
self.join_date_label = QLabel()
self.join_date_label.setStyleSheet("font-size: 12px;")
self.join_date_label.setWordWrap(True)
self.join_date_label.setMinimumWidth(400)
self.followers_label = QLabel()
self.followers_label.setStyleSheet("font-size: 12px;")
self.followers_label.setWordWrap(True)
self.followers_label.setMinimumWidth(400)
self.following_label = QLabel()
self.following_label.setStyleSheet("font-size: 12px;")
self.following_label.setWordWrap(True)
self.following_label.setMinimumWidth(400)
self.posts_label = QLabel()
self.posts_label.setStyleSheet("font-size: 12px;")
self.posts_label.setWordWrap(True)
self.posts_label.setMinimumWidth(400)
profile_details_layout.addWidget(self.name_label)
profile_details_layout.addWidget(self.join_date_label)
profile_details_layout.addWidget(self.followers_label)
profile_details_layout.addWidget(self.following_label)
profile_details_layout.addWidget(self.posts_label)
profile_layout.addWidget(profile_details_container, stretch=1)
profile_layout.addStretch()
self.main_layout.addWidget(self.profile_widget)
self.download_button = QPushButton("Download")
self.download_button.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
self.download_button.setFixedWidth(100)
self.download_button.clicked.connect(self.start_download)
self.download_button.hide()
self.cancel_button = QPushButton("Cancel")
self.cancel_button.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
self.cancel_button.setFixedWidth(100)
self.cancel_button.clicked.connect(self.cancel_clicked)
self.cancel_button.hide()
self.open_button = QPushButton("Open")
self.open_button.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
self.open_button.setFixedWidth(100)
self.open_button.clicked.connect(self.open_output_directory)
self.open_button.hide()
button_layout = QHBoxLayout()
button_layout.addStretch()
button_layout.addWidget(self.open_button)
button_layout.addWidget(self.download_button)
button_layout.addWidget(self.cancel_button)
button_layout.addStretch()
self.main_layout.addLayout(button_layout)
self.progress_bar = QProgressBar()
self.progress_bar.hide()
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)
self.update_button = QPushButton()
icon_path = os.path.join(os.path.dirname(__file__), "update.svg")
if os.path.exists(icon_path):
self.update_button.setIcon(QIcon(icon_path))
self.update_button.setFixedSize(16, 16)
self.update_button.setStyleSheet("""
QPushButton {
border: none;
background: transparent;
}
QPushButton:hover {
background: transparent;
}
""")
self.update_button.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
self.update_button.setToolTip("Check for Updates")
self.update_button.clicked.connect(self.open_update_page)
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
webbrowser.open('https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases')
def setup_auto_save(self):
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.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.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('batch_size', self.batch_size_combo.currentText())
self.settings.sync()
def load_settings(self):
self.url_input.setText(self.settings.value('url_input', '', str))
self.auth_input.setText(self.settings.value('auth_token', '', str))
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.setChecked(format_setting == 'username_date')
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
use_api = self.settings.value('use_api', True, type=bool)
self.use_api_checkbox.setChecked(use_api)
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)
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):
output_dir = self.dir_input.text().strip() or self.default_pictures_dir
if os.path.exists(output_dir):
if sys.platform == 'win32':
os.startfile(output_dir)
elif sys.platform == 'darwin':
subprocess.run(['open', output_dir])
else:
subprocess.run(['xdg-open', output_dir])
def fetch_metadata(self):
username = self.url_input.text().strip()
if not username:
self.status_label.setText("Please enter a username or URL")
return
auth_token = self.auth_input.text().strip()
if not auth_token:
self.status_label.setText("Please enter your auth token")
return
self.fetch_button.setEnabled(False)
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)
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):
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)
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')
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:,}")
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
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()
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):
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}")
def start_download(self):
if not self.media_info:
self.status_label.setText("Please fetch profile information first")
return
auth_token = self.auth_input.text().strip()
if not auth_token:
self.status_label.setText("Please enter your auth token")
return
self.download_button.hide()
self.cancel_button.hide()
self.progress_bar.show()
self.progress_bar.setValue(0)
self.status_label.setText("Starting download...")
filename_format = "username_date" if self.format_username.isChecked() else "date_username"
batch_size = int(self.batch_size_combo.currentText())
media_type = self.media_type_combo.currentData()
self.worker = MediaDownloader(
self.media_info['timeline'],
self.user_output_dir,
filename_format,
self.clean_username,
media_type,
batch_size
)
self.worker.progress.connect(self.update_progress)
self.worker.finished.connect(self.download_finished)
self.worker.error.connect(self.download_error)
self.worker.status_update.connect(self.status_label.setText)
self.worker.start()
def update_progress(self, value):
self.progress_bar.setValue(value)
def download_finished(self, message):
self.progress_bar.hide()
self.status_label.setText(message)
self.open_button.show()
self.download_button.setText("Clear")
self.download_button.clicked.disconnect()
self.download_button.clicked.connect(self.clear_form)
self.download_button.show()
self.cancel_button.hide()
def clear_form(self):
self.url_input.clear()
self.profile_widget.hide()
self.input_widget.show()
self.download_button.hide()
self.cancel_button.hide()
self.open_button.hide()
self.progress_bar.hide()
self.progress_bar.setValue(0)
self.status_label.clear()
self.media_info = None
self.update_button.show()
self.fetch_button.setEnabled(True)
self.download_button.setText("Download")
self.download_button.clicked.disconnect()
self.download_button.clicked.connect(self.start_download)
def download_error(self, error_message):
self.progress_bar.hide()
self.status_label.setText(f"Download error: {error_message}")
self.download_button.setText("Retry")
self.download_button.show()
self.cancel_button.show()
def cancel_clicked(self):
self.profile_widget.hide()
self.input_widget.show()
self.download_button.hide()
self.cancel_button.hide()
self.open_button.hide()
self.progress_bar.hide()
self.progress_bar.setValue(0)
self.status_label.clear()
self.media_info = None
self.update_button.show()
self.fetch_button.setEnabled(True)
def main():
if getattr(sys, 'frozen', False):
os.chdir(os.path.dirname(sys.executable))
app = QApplication(sys.argv)
window = TwitterMediaDownloaderGUI()
window.show()
sys.exit(app.exec())
if __name__ == "__main__":
main()
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+186
View File
@@ -0,0 +1,186 @@
import re
import json
from datetime import datetime
from gallery_dl.extractor import twitter
def get_metadata(username, auth_token, timeline_type="timeline", batch_size=0, page=0, media_type="all"):
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)
try:
extractor.initialize()
api = twitter.TwitterAPI(extractor)
try:
if username.startswith("id:"):
user = api.user_by_rest_id(username[3:])
else:
user = api.user_by_screen_name(username)
if "legacy" in user and user["legacy"].get("withheld_scope"):
raise ValueError("withheld")
except Exception as e:
error_msg = str(e).lower()
if "withheld" in error_msg or (hasattr(e, "response") and "withheld" in str(e.response.text).lower()):
raise ValueError("withheld")
raise
structured_output = {
'account_info': {},
'total_urls': 0,
'timeline': []
}
iterator = iter(extractor)
if batch_size > 0 and page > 0:
items_to_skip = page * batch_size
if hasattr(extractor, '_cursor') and extractor._cursor:
pass
else:
skipped = 0
try:
for _ in range(items_to_skip):
next(iterator)
skipped += 1
except StopIteration:
pass
new_timeline_entries = []
items_to_fetch = batch_size if batch_size > 0 else float('inf')
items_fetched = 0
try:
while items_fetched < items_to_fetch:
item = next(iterator)
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']
if media_type == 'all' or (
(media_type == 'image' and 'pbs.twimg.com' in media_url and tweet_data.get('type') == 'photo') or
(media_type == 'video' and 'video.twimg.com' in media_url and tweet_data.get('type') == 'video') or
(media_type == 'gif' and 'video.twimg.com' in media_url and tweet_data.get('type') == 'animated_gif')
):
new_timeline_entries.append(timeline_entry)
structured_output['total_urls'] += 1
except StopIteration:
pass
structured_output['timeline'].extend(new_timeline_entries)
cursor_info = None
if hasattr(extractor, '_cursor') and extractor._cursor:
cursor_info = extractor._cursor
structured_output['metadata'] = {
"new_entries": len(new_timeline_entries),
"page": page,
"batch_size": batch_size,
"has_more": batch_size > 0 and items_fetched == batch_size,
"cursor": cursor_info
}
if not structured_output['account_info']:
raise ValueError("Failed to fetch account information. Please check the username and auth token.")
return structured_output
except Exception as e:
error_msg = str(e).lower()
if "withheld" in error_msg or e.__class__.__name__ == "ValueError" and str(e) == "withheld":
return {"error": "To download withheld accounts, use this userscript version: https://www.patreon.com/exyezed"}
else:
error_str = str(e)
if error_str == "None":
return {"error": "Failed to authenticate. Please verify your auth token is valid and not expired."}
else:
return {"error": error_str}
def main():
username = ""
auth_token = ""
timeline_type = "media"
batch_size = 100
page = 0
media_type = "all"
try:
data = get_metadata(
username=username,
auth_token=auth_token,
timeline_type=timeline_type,
batch_size=batch_size,
page=page,
media_type=media_type
)
print(json.dumps(data, ensure_ascii=False, indent=2))
except Exception as e:
error_str = str(e)
if error_str == "None":
print(json.dumps({"error": "Failed to authenticate. Please verify your auth token is valid and not expired."}, ensure_ascii=False))
else:
print(json.dumps({"error": error_str}, ensure_ascii=False))
if __name__ == '__main__':
main()
+6
View File
@@ -0,0 +1,6 @@
PyQt6
requests
aiohttp
imageio-ffmpeg
packaging
gallery-dl
+3
View File
@@ -0,0 +1,3 @@
{
"version": "3.4"
}