Add duplicate detection and failed-download tracking
Skip already-downloaded TikTok IDs across runs Log failed URLs to ./failed.txt for later retry
This commit is contained in:
1 parent
d7da49c922
commit
7c71ed6df8
6 files changed
+313
-82
No files matched your search
@@ -3,4 +3,11 @@ youtube-dl*
|
|||||||
yt-dlp*
|
yt-dlp*
|
||||||
authorized_users.txt
|
authorized_users.txt
|
||||||
.env
|
.env
|
||||||
|
__pycache__/*
|
||||||
|
metadata.json
|
||||||
|
|
||||||
*.log
|
*.log
|
||||||
|
in.txt
|
||||||
|
in/*
|
||||||
|
downloaded_ids.txt
|
||||||
|
failed.txt
|
||||||
Vendored
+3
@@ -0,0 +1,3 @@
|
|||||||
|
{
|
||||||
|
"python.analysis.autoImportCompletions": true
|
||||||
|
}
|
||||||
@@ -1,3 +1,51 @@
|
|||||||
pip install python-telegram-bot yt-dlp
|
# TikDown
|
||||||
pip install python-dotenv
|
|
||||||
|
|
||||||
|
TikTok video & photo downloader — CLI tool and Telegram bot powered by yt-dlp.
|
||||||
|
|
||||||
|
## Setup
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pip install python-telegram-bot yt-dlp python-dotenv
|
||||||
|
```
|
||||||
|
|
||||||
|
Place `yt-dlp.exe` (or `yt-dlp`) in the project root, or set `YT_DLP_PATH` in `downloader.py`.
|
||||||
|
|
||||||
|
### Telegram bot (optional)
|
||||||
|
|
||||||
|
Create a `.env` file:
|
||||||
|
|
||||||
|
```
|
||||||
|
TELEGRAM_API_TOKEN=your_bot_token
|
||||||
|
BOT_AUTH_PASSWORD=your_password
|
||||||
|
```
|
||||||
|
|
||||||
|
Create `authorized_users.txt` with one Telegram user ID per line. Users authenticate with `/authenticate <password>`.
|
||||||
|
|
||||||
|
## CLI Usage
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Download a single video/photo
|
||||||
|
python downloader.py https://www.tiktok.com/@user/video/123456789
|
||||||
|
|
||||||
|
# Batch download from a file (one URL per line)
|
||||||
|
python downloader.py in/my-urls.txt
|
||||||
|
|
||||||
|
# Retry previously failed downloads
|
||||||
|
python downloader.py failed.txt
|
||||||
|
```
|
||||||
|
|
||||||
|
## Downloads
|
||||||
|
|
||||||
|
Videos and photos are saved to `./downloads/`. Filenames include the upload date when metadata is available:
|
||||||
|
|
||||||
|
```
|
||||||
|
./downloads/2024-12-25_123456789_username_userid.mp4
|
||||||
|
```
|
||||||
|
|
||||||
|
## Duplicate detection
|
||||||
|
|
||||||
|
Downloaded TikTok IDs are tracked in `./downloaded_ids.txt`. Before any download, the ID is checked — already-downloaded URLs are skipped automatically.
|
||||||
|
|
||||||
|
## Failed downloads
|
||||||
|
|
||||||
|
URLs that fail to download (network errors, removed videos, etc.) are appended to `./failed.txt`.
|
||||||
Binary file not shown.
@@ -1,28 +1,34 @@
|
|||||||
import os
|
|
||||||
import logging
|
|
||||||
import time
|
|
||||||
import asyncio
|
import asyncio
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import time
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
|
||||||
from urllib.parse import urlparse
|
from urllib.parse import urlparse
|
||||||
from telegram import BotCommand
|
|
||||||
from telegram import Update
|
from dotenv import load_dotenv
|
||||||
|
from telegram import BotCommand, Update
|
||||||
from telegram.ext import (
|
from telegram.ext import (
|
||||||
ApplicationBuilder,
|
ApplicationBuilder,
|
||||||
CommandHandler,
|
CommandHandler,
|
||||||
MessageHandler,
|
|
||||||
ContextTypes,
|
ContextTypes,
|
||||||
filters
|
MessageHandler,
|
||||||
|
filters,
|
||||||
|
)
|
||||||
|
|
||||||
|
from downloader import (
|
||||||
|
download_video,
|
||||||
|
extract_tiktok_id,
|
||||||
|
load_downloaded_ids,
|
||||||
|
log_failed_url,
|
||||||
|
save_downloaded_id,
|
||||||
)
|
)
|
||||||
from dotenv import load_dotenv
|
|
||||||
from downloader import download_video
|
|
||||||
|
|
||||||
load_dotenv()
|
load_dotenv()
|
||||||
|
|
||||||
# Configuration
|
# Configuration
|
||||||
API_TOKEN = os.getenv('TELEGRAM_API_TOKEN')
|
API_TOKEN = os.getenv("TELEGRAM_API_TOKEN")
|
||||||
AUTH_PASSWORD = os.getenv('BOT_AUTH_PASSWORD')
|
AUTH_PASSWORD = os.getenv("BOT_AUTH_PASSWORD")
|
||||||
AUTHORIZED_USERS_FILE = 'authorized_users.txt'
|
AUTHORIZED_USERS_FILE = "authorized_users.txt"
|
||||||
DELETE_AFTER_SEND = False
|
DELETE_AFTER_SEND = False
|
||||||
|
|
||||||
# Rate limiting configuration
|
# Rate limiting configuration
|
||||||
@@ -31,33 +37,38 @@ MAX_REQUESTS_PER_WINDOW = 5 # Maximum requests allowed per user in the time win
|
|||||||
|
|
||||||
# Setup logging
|
# Setup logging
|
||||||
logging.basicConfig(
|
logging.basicConfig(
|
||||||
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
|
||||||
level=logging.INFO
|
|
||||||
)
|
)
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
# Load authorized users
|
# Load authorized users
|
||||||
def load_authorized_users():
|
def load_authorized_users():
|
||||||
if not os.path.exists(AUTHORIZED_USERS_FILE):
|
if not os.path.exists(AUTHORIZED_USERS_FILE):
|
||||||
return set()
|
return set()
|
||||||
with open(AUTHORIZED_USERS_FILE, 'r') as f:
|
with open(AUTHORIZED_USERS_FILE, "r") as f:
|
||||||
return set(line.strip() for line in f if line.strip())
|
return set(line.strip() for line in f if line.strip())
|
||||||
|
|
||||||
|
|
||||||
AUTHORIZED_USERS = load_authorized_users()
|
AUTHORIZED_USERS = load_authorized_users()
|
||||||
|
|
||||||
|
|
||||||
# Save authorized users
|
# Save authorized users
|
||||||
def save_authorized_users():
|
def save_authorized_users():
|
||||||
with open(AUTHORIZED_USERS_FILE, 'w') as f:
|
with open(AUTHORIZED_USERS_FILE, "w") as f:
|
||||||
for user_id in AUTHORIZED_USERS:
|
for user_id in AUTHORIZED_USERS:
|
||||||
f.write(f"{user_id}\n")
|
f.write(f"{user_id}\n")
|
||||||
|
|
||||||
|
|
||||||
# Helper to check if user is authorized
|
# Helper to check if user is authorized
|
||||||
def is_user_authorized(user_id: int) -> bool:
|
def is_user_authorized(user_id: int) -> bool:
|
||||||
return str(user_id) in AUTHORIZED_USERS
|
return str(user_id) in AUTHORIZED_USERS
|
||||||
|
|
||||||
|
|
||||||
# Rate limiting tracker
|
# Rate limiting tracker
|
||||||
user_request_tracker = {}
|
user_request_tracker = {}
|
||||||
|
|
||||||
|
|
||||||
# Check if user is rate-limited
|
# Check if user is rate-limited
|
||||||
def is_rate_limited(user_id: int) -> bool:
|
def is_rate_limited(user_id: int) -> bool:
|
||||||
current_time = time.time()
|
current_time = time.time()
|
||||||
@@ -66,7 +77,9 @@ def is_rate_limited(user_id: int) -> bool:
|
|||||||
|
|
||||||
# Remove old requests outside the time window
|
# Remove old requests outside the time window
|
||||||
user_request_tracker[user_id] = [
|
user_request_tracker[user_id] = [
|
||||||
t for t in user_request_tracker[user_id] if current_time - t <= RATE_LIMIT_WINDOW
|
t
|
||||||
|
for t in user_request_tracker[user_id]
|
||||||
|
if current_time - t <= RATE_LIMIT_WINDOW
|
||||||
]
|
]
|
||||||
|
|
||||||
# Check if the user has exceeded the limit
|
# Check if the user has exceeded the limit
|
||||||
@@ -77,16 +90,19 @@ def is_rate_limited(user_id: int) -> bool:
|
|||||||
user_request_tracker[user_id].append(current_time)
|
user_request_tracker[user_id].append(current_time)
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
# Log user requests
|
# Log user requests
|
||||||
def log_user_request(user_id: int, username: str, message: str):
|
def log_user_request(user_id: int, username: str, message: str):
|
||||||
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||||
with open('requests.log', 'a') as log_file:
|
with open("requests.log", "a") as log_file:
|
||||||
log_file.write(f"[{timestamp}] {username} ({user_id}): {message}\n")
|
log_file.write(f"[{timestamp}] {username} ({user_id}): {message}\n")
|
||||||
|
|
||||||
|
|
||||||
# Command: /start
|
# Command: /start
|
||||||
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||||||
await update.message.reply_text("Welcome! Use /help to see available commands.")
|
await update.message.reply_text("Welcome! Use /help to see available commands.")
|
||||||
|
|
||||||
|
|
||||||
# Command: /help
|
# Command: /help
|
||||||
async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||||||
help_text = """
|
help_text = """
|
||||||
@@ -98,6 +114,7 @@ Send one or more TikTok video URLs (separated by new lines) to download the vide
|
|||||||
"""
|
"""
|
||||||
await update.message.reply_text(help_text)
|
await update.message.reply_text(help_text)
|
||||||
|
|
||||||
|
|
||||||
# Command: /authenticate <password>
|
# Command: /authenticate <password>
|
||||||
async def authenticate(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
async def authenticate(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||||||
user_id = update.message.from_user.id
|
user_id = update.message.from_user.id
|
||||||
@@ -111,16 +128,21 @@ async def authenticate(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
|||||||
if password == AUTH_PASSWORD:
|
if password == AUTH_PASSWORD:
|
||||||
AUTHORIZED_USERS.add(str(user_id))
|
AUTHORIZED_USERS.add(str(user_id))
|
||||||
save_authorized_users()
|
save_authorized_users()
|
||||||
await update.message.reply_text("Authentication successful! You can now use the bot.")
|
await update.message.reply_text(
|
||||||
|
"Authentication successful! You can now use the bot."
|
||||||
|
)
|
||||||
else:
|
else:
|
||||||
await update.message.reply_text("Authentication failed. Incorrect password.")
|
await update.message.reply_text("Authentication failed. Incorrect password.")
|
||||||
|
|
||||||
|
|
||||||
# Handle TikTok URLs
|
# Handle TikTok URLs
|
||||||
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||||||
user_id = update.message.from_user.id
|
user_id = update.message.from_user.id
|
||||||
username = update.message.from_user.username or "UnknownUser"
|
username = update.message.from_user.username or "UnknownUser"
|
||||||
if not is_user_authorized(user_id):
|
if not is_user_authorized(user_id):
|
||||||
await update.message.reply_text("You are not authorized. Use /authenticate <password> to authorize.")
|
await update.message.reply_text(
|
||||||
|
"You are not authorized. Use /authenticate <password> to authorize."
|
||||||
|
)
|
||||||
return
|
return
|
||||||
|
|
||||||
# Log the user's message
|
# Log the user's message
|
||||||
@@ -128,7 +150,9 @@ async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
|||||||
|
|
||||||
# Check rate limiting
|
# Check rate limiting
|
||||||
if is_rate_limited(user_id):
|
if is_rate_limited(user_id):
|
||||||
await update.message.reply_text("You are sending too many requests. Please try again later.")
|
await update.message.reply_text(
|
||||||
|
"You are sending too many requests. Please try again later."
|
||||||
|
)
|
||||||
return
|
return
|
||||||
|
|
||||||
message = update.message
|
message = update.message
|
||||||
@@ -136,14 +160,22 @@ async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
|||||||
return
|
return
|
||||||
|
|
||||||
# Split the message into multiple lines and process each URL
|
# Split the message into multiple lines and process each URL
|
||||||
urls = message.text.strip().split('\n')
|
urls = message.text.strip().split("\n")
|
||||||
valid_urls = [url.strip() for url in urls if is_valid_tiktok_url(url.strip())]
|
valid_urls = [url.strip() for url in urls if is_valid_tiktok_url(url.strip())]
|
||||||
|
|
||||||
if not valid_urls:
|
if not valid_urls:
|
||||||
await message.reply_text("Please send valid TikTok video URLs.")
|
await message.reply_text("Please send valid TikTok video URLs.")
|
||||||
return
|
return
|
||||||
|
|
||||||
|
downloaded_ids = load_downloaded_ids()
|
||||||
|
|
||||||
for url in valid_urls:
|
for url in valid_urls:
|
||||||
|
# Skip if already downloaded
|
||||||
|
video_id = extract_tiktok_id(url)
|
||||||
|
if video_id and video_id in downloaded_ids:
|
||||||
|
logger.info(f"Skipping (already downloaded): {url}")
|
||||||
|
continue
|
||||||
|
|
||||||
video_path = None
|
video_path = None
|
||||||
try:
|
try:
|
||||||
# Run the synchronous download_video function in a separate thread
|
# Run the synchronous download_video function in a separate thread
|
||||||
@@ -151,40 +183,53 @@ async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
|||||||
if not video_path:
|
if not video_path:
|
||||||
raise Exception("Download failed")
|
raise Exception("Download failed")
|
||||||
|
|
||||||
|
# Mark as downloaded
|
||||||
|
if video_id:
|
||||||
|
save_downloaded_id(video_id)
|
||||||
|
|
||||||
# Open the file properly with a context manager
|
# Open the file properly with a context manager
|
||||||
with open(video_path, 'rb') as video_file:
|
with open(video_path, "rb") as video_file:
|
||||||
try:
|
try:
|
||||||
await message.reply_video(video=video_file)
|
await message.reply_video(video=video_file)
|
||||||
except Exception as send_error:
|
except Exception as send_error:
|
||||||
# Check file size
|
# Check file size
|
||||||
file_size = os.path.getsize(video_path) / (1024 * 1024) # Size in MB
|
file_size = os.path.getsize(video_path) / (
|
||||||
|
1024 * 1024
|
||||||
|
) # Size in MB
|
||||||
if file_size > 50:
|
if file_size > 50:
|
||||||
await message.reply_text(f"Video is too large ({file_size:.1f}MB). Telegram has a 50MB limit.")
|
await message.reply_text(
|
||||||
|
f"Video is too large ({file_size:.1f}MB). Telegram has a 50MB limit."
|
||||||
|
)
|
||||||
else:
|
else:
|
||||||
await message.reply_text(f"Failed to send video: {str(send_error)}")
|
await message.reply_text(
|
||||||
|
f"Failed to send video: {str(send_error)}"
|
||||||
|
)
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Error processing {url}: {str(e)}")
|
logger.error(f"Error processing {url}: {str(e)}")
|
||||||
|
log_failed_url(url)
|
||||||
await message.reply_text(f"Failed to process video: {str(e)}")
|
await message.reply_text(f"Failed to process video: {str(e)}")
|
||||||
|
|
||||||
finally:
|
finally:
|
||||||
if video_path and os.path.exists(video_path):
|
if video_path and os.path.exists(video_path):
|
||||||
try:
|
try:
|
||||||
if DELETE_AFTER_SEND:
|
if DELETE_AFTER_SEND == True:
|
||||||
os.remove(video_path)
|
os.remove(video_path)
|
||||||
except Exception as del_error:
|
except Exception as del_error:
|
||||||
logger.error(f"Error removing file {video_path}: {str(del_error)}")
|
logger.error(f"Error removing file {video_path}: {str(del_error)}")
|
||||||
|
|
||||||
|
|
||||||
# Validate TikTok URL
|
# Validate TikTok URL
|
||||||
def is_valid_tiktok_url(url: str) -> bool:
|
def is_valid_tiktok_url(url: str) -> bool:
|
||||||
parsed = urlparse(url)
|
parsed = urlparse(url)
|
||||||
return (
|
return (
|
||||||
parsed.scheme in ['http', 'https'] and
|
parsed.scheme in ["http", "https"]
|
||||||
'tiktok.com' in parsed.netloc and
|
and "tiktok.com" in parsed.netloc
|
||||||
'/video/' in parsed.path
|
and ("/video/" in parsed.path or "/photo/" in parsed.path)
|
||||||
)
|
)
|
||||||
|
|
||||||
if __name__ == '__main__':
|
|
||||||
|
if __name__ == "__main__":
|
||||||
if not API_TOKEN:
|
if not API_TOKEN:
|
||||||
raise ValueError("TELEGRAM_API_TOKEN environment variable not set")
|
raise ValueError("TELEGRAM_API_TOKEN environment variable not set")
|
||||||
|
|
||||||
|
|||||||
+174
-46
@@ -1,26 +1,60 @@
|
|||||||
import os
|
|
||||||
import subprocess
|
|
||||||
import json
|
import json
|
||||||
import re
|
|
||||||
import logging
|
import logging
|
||||||
import time
|
import os
|
||||||
|
import re
|
||||||
|
import subprocess
|
||||||
import sys
|
import sys
|
||||||
|
import time
|
||||||
from typing import List
|
from typing import List
|
||||||
from urllib.parse import urlparse
|
from urllib.parse import urlparse
|
||||||
|
|
||||||
# Setup logging
|
# Setup logging
|
||||||
logging.basicConfig(
|
logging.basicConfig(
|
||||||
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
|
||||||
level=logging.INFO
|
|
||||||
)
|
)
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
DOWNLOAD_DIR = './'
|
DOWNLOAD_DIR = "./downloads"
|
||||||
YT_DLP_PATH = './yt-dlp'
|
YT_DLP_PATH = "./yt-dlp"
|
||||||
|
DOWNLOADED_IDS_FILE = "./downloaded_ids.txt"
|
||||||
|
FAILED_FILE = "./failed.txt"
|
||||||
|
|
||||||
# Rate limiting configuration
|
# Rate limiting configuration
|
||||||
DOWNLOAD_DELAY = 1 # Delay in seconds between downloads
|
DOWNLOAD_DELAY = 1 # Delay in seconds between downloads
|
||||||
|
|
||||||
|
|
||||||
|
def extract_tiktok_id(url: str) -> str | None:
|
||||||
|
"""
|
||||||
|
Extracts the TikTok video/photo ID from a URL.
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
https://www.tiktok.com/@user/video/7500623452873723158 -> 7500623452873723158
|
||||||
|
https://www.tiktok.com/@user/photo/7500623452873723158 -> 7500623452873723158
|
||||||
|
"""
|
||||||
|
match = re.search(r"/(?:video|photo)/(\d+)", url)
|
||||||
|
return match.group(1) if match else None
|
||||||
|
|
||||||
|
|
||||||
|
def load_downloaded_ids() -> set:
|
||||||
|
"""Loads the set of already-downloaded TikTok IDs from disk."""
|
||||||
|
if not os.path.exists(DOWNLOADED_IDS_FILE):
|
||||||
|
return set()
|
||||||
|
with open(DOWNLOADED_IDS_FILE, "r") as f:
|
||||||
|
return set(line.strip() for line in f if line.strip())
|
||||||
|
|
||||||
|
|
||||||
|
def save_downloaded_id(video_id: str) -> None:
|
||||||
|
"""Appends a TikTok ID to the downloaded-ids tracking file."""
|
||||||
|
with open(DOWNLOADED_IDS_FILE, "a") as f:
|
||||||
|
f.write(video_id + "\n")
|
||||||
|
|
||||||
|
|
||||||
|
def log_failed_url(url: str) -> None:
|
||||||
|
"""Appends a failed URL to ./failed.txt."""
|
||||||
|
with open(FAILED_FILE, "a") as f:
|
||||||
|
f.write(url + "\n")
|
||||||
|
|
||||||
|
|
||||||
def download_video(url: str) -> str:
|
def download_video(url: str) -> str:
|
||||||
"""
|
"""
|
||||||
Downloads a TikTok video using yt-dlp.
|
Downloads a TikTok video using yt-dlp.
|
||||||
@@ -34,17 +68,12 @@ def download_video(url: str) -> str:
|
|||||||
os.makedirs(DOWNLOAD_DIR, exist_ok=True)
|
os.makedirs(DOWNLOAD_DIR, exist_ok=True)
|
||||||
|
|
||||||
# First, get metadata to extract the publish date
|
# First, get metadata to extract the publish date
|
||||||
metadata_cmd = [
|
metadata_cmd = [YT_DLP_PATH, "--no-check-certificate", "--dump-json", url]
|
||||||
YT_DLP_PATH,
|
|
||||||
'--no-check-certificate',
|
|
||||||
'--dump-json',
|
|
||||||
url
|
|
||||||
]
|
|
||||||
|
|
||||||
metadata_result = subprocess.run(metadata_cmd, capture_output=True, text=True)
|
metadata_result = subprocess.run(metadata_cmd, capture_output=True, text=True)
|
||||||
|
|
||||||
# Default template without date
|
# Default template without date
|
||||||
output_template = os.path.join(DOWNLOAD_DIR, '%(id)s.%(ext)s')
|
output_template = os.path.join(DOWNLOAD_DIR, "%(id)s.%(ext)s")
|
||||||
|
|
||||||
# Try to extract date from metadata
|
# Try to extract date from metadata
|
||||||
try:
|
try:
|
||||||
@@ -52,16 +81,21 @@ def download_video(url: str) -> str:
|
|||||||
metadata = json.loads(metadata_result.stdout)
|
metadata = json.loads(metadata_result.stdout)
|
||||||
|
|
||||||
# Extract the upload date if available
|
# Extract the upload date if available
|
||||||
if 'upload_date' in metadata:
|
if "upload_date" in metadata:
|
||||||
# Format is typically YYYYMMDD
|
# Format is typically YYYYMMDD
|
||||||
upload_date = metadata['upload_date']
|
upload_date = metadata["upload_date"]
|
||||||
uploader = metadata['uploader']
|
uploader = metadata["uploader"]
|
||||||
uploader_id = metadata['uploader_id']
|
uploader_id = metadata["uploader_id"]
|
||||||
# You can reformat it if you want (e.g., YYYY-MM-DD)
|
# You can reformat it if you want (e.g., YYYY-MM-DD)
|
||||||
formatted_date = f"{upload_date[:4]}-{upload_date[4:6]}-{upload_date[6:8]}"
|
formatted_date = (
|
||||||
|
f"{upload_date[:4]}-{upload_date[4:6]}-{upload_date[6:8]}"
|
||||||
|
)
|
||||||
|
|
||||||
# Update the output template to include the date
|
# Update the output template to include the date
|
||||||
output_template = os.path.join(DOWNLOAD_DIR, f"{formatted_date}_%(id)s_{uploader}_{uploader_id}.%(ext)s")
|
output_template = os.path.join(
|
||||||
|
DOWNLOAD_DIR,
|
||||||
|
f"{formatted_date}_%(id)s_{uploader}_{uploader_id}.%(ext)s",
|
||||||
|
)
|
||||||
# logger.info(f"Using date format: {formatted_date}")
|
# logger.info(f"Using date format: {formatted_date}")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Error parsing metadata: {str(e)}")
|
logger.error(f"Error parsing metadata: {str(e)}")
|
||||||
@@ -70,11 +104,13 @@ def download_video(url: str) -> str:
|
|||||||
# Download the video with the determined output template
|
# Download the video with the determined output template
|
||||||
cmd = [
|
cmd = [
|
||||||
YT_DLP_PATH,
|
YT_DLP_PATH,
|
||||||
'--no-check-certificate',
|
"--no-check-certificate",
|
||||||
'--format', 'best',
|
"--format",
|
||||||
'--verbose',
|
"bestvideo+bestaudio/best",
|
||||||
'-o', output_template,
|
"--verbose",
|
||||||
url
|
"-o",
|
||||||
|
output_template,
|
||||||
|
url,
|
||||||
]
|
]
|
||||||
|
|
||||||
result = subprocess.run(cmd, capture_output=True, text=True)
|
result = subprocess.run(cmd, capture_output=True, text=True)
|
||||||
@@ -88,9 +124,9 @@ def download_video(url: str) -> str:
|
|||||||
|
|
||||||
# Try to find the destination file
|
# Try to find the destination file
|
||||||
filename = None
|
filename = None
|
||||||
for line in full_output.split('\n'):
|
for line in full_output.split("\n"):
|
||||||
if '[download]' in line and 'Destination:' in line:
|
if "[download]" in line and "Destination:" in line:
|
||||||
parts = line.split('Destination:')
|
parts = line.split("Destination:")
|
||||||
if len(parts) > 1:
|
if len(parts) > 1:
|
||||||
filename = parts[1].strip()
|
filename = parts[1].strip()
|
||||||
break
|
break
|
||||||
@@ -98,9 +134,11 @@ def download_video(url: str) -> str:
|
|||||||
# If we couldn't find it with the above method, try alternative approaches
|
# If we couldn't find it with the above method, try alternative approaches
|
||||||
if not filename:
|
if not filename:
|
||||||
# Look for the "[download] ... has already been downloaded" message
|
# Look for the "[download] ... has already been downloaded" message
|
||||||
for line in full_output.split('\n'):
|
for line in full_output.split("\n"):
|
||||||
if '[download]' in line and 'has already been downloaded' in line:
|
if "[download]" in line and "has already been downloaded" in line:
|
||||||
match = re.search(r'\[download\] (.*?) has already been downloaded', line)
|
match = re.search(
|
||||||
|
r"\[download\] (.*?) has already been downloaded", line
|
||||||
|
)
|
||||||
if match:
|
if match:
|
||||||
filename = match.group(1)
|
filename = match.group(1)
|
||||||
break
|
break
|
||||||
@@ -124,6 +162,71 @@ def download_video(url: str) -> str:
|
|||||||
|
|
||||||
return filename
|
return filename
|
||||||
|
|
||||||
|
|
||||||
|
def download_photo(url: str) -> List[str]:
|
||||||
|
"""
|
||||||
|
Downloads a TikTok photo slideshow and returns list of file paths.
|
||||||
|
|
||||||
|
Files are saved as: xxx1.jpg, xxx2.jpg, etc.
|
||||||
|
"""
|
||||||
|
os.makedirs(DOWNLOAD_DIR, exist_ok=True)
|
||||||
|
|
||||||
|
# Get metadata to extract ID or date
|
||||||
|
metadata_cmd = [YT_DLP_PATH, "--no-check-certificate", "--dump-json", url]
|
||||||
|
metadata_result = subprocess.run(metadata_cmd, capture_output=True, text=True)
|
||||||
|
|
||||||
|
base_name = "xxx"
|
||||||
|
try:
|
||||||
|
if metadata_result.returncode == 0:
|
||||||
|
metadata = json.loads(metadata_result.stdout)
|
||||||
|
upload_date = metadata.get("upload_date", "")
|
||||||
|
if upload_date:
|
||||||
|
formatted_date = (
|
||||||
|
f"{upload_date[:4]}-{upload_date[4:6]}-{upload_date[6:8]}"
|
||||||
|
)
|
||||||
|
base_name = f"{formatted_date}_xxx"
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"Could not parse metadata for photo naming: {e}")
|
||||||
|
|
||||||
|
# Output template for photos
|
||||||
|
output_template = os.path.join(
|
||||||
|
DOWNLOAD_DIR, f"{base_name}%(playlist_index)s.%(ext)s"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Download command with best image quality
|
||||||
|
cmd = [
|
||||||
|
YT_DLP_PATH,
|
||||||
|
"--no-check-certificate",
|
||||||
|
"--format",
|
||||||
|
"bestvideo+bestaudio/best",
|
||||||
|
"-o",
|
||||||
|
output_template,
|
||||||
|
url,
|
||||||
|
]
|
||||||
|
|
||||||
|
result = subprocess.run(cmd, capture_output=True, text=True)
|
||||||
|
|
||||||
|
if result.returncode != 0:
|
||||||
|
logger.error(f"yt-dlp error downloading photo: {result.stderr}")
|
||||||
|
raise Exception("Failed to download TikTok photo slideshow")
|
||||||
|
|
||||||
|
full_output = result.stdout + result.stderr
|
||||||
|
downloaded_files = []
|
||||||
|
|
||||||
|
# Parse downloaded files from output
|
||||||
|
for line in full_output.split("\n"):
|
||||||
|
if "[download]" in line and "Destination:" in line:
|
||||||
|
parts = line.split("Destination:")
|
||||||
|
if len(parts) > 1:
|
||||||
|
file_path = parts[1].strip()
|
||||||
|
downloaded_files.append(file_path)
|
||||||
|
|
||||||
|
if not downloaded_files:
|
||||||
|
logger.warning("No photo files were found in the output.")
|
||||||
|
|
||||||
|
return downloaded_files
|
||||||
|
|
||||||
|
|
||||||
def is_valid_tiktok_url(url: str) -> bool:
|
def is_valid_tiktok_url(url: str) -> bool:
|
||||||
"""
|
"""
|
||||||
Validates a TikTok URL.
|
Validates a TikTok URL.
|
||||||
@@ -136,11 +239,24 @@ def is_valid_tiktok_url(url: str) -> bool:
|
|||||||
"""
|
"""
|
||||||
parsed = urlparse(url)
|
parsed = urlparse(url)
|
||||||
return (
|
return (
|
||||||
parsed.scheme in ['http', 'https'] and
|
parsed.scheme in ["http", "https"]
|
||||||
'tiktok.com' in parsed.netloc and
|
and "tiktok.com" in parsed.netloc
|
||||||
'/video/' in parsed.path
|
and ("/video/" in parsed.path or "/photo/" in parsed.path)
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def is_tiktok_photo_url(url: str) -> bool:
|
||||||
|
"""
|
||||||
|
Checks if a TikTok URL points to a photo/slideshow post.
|
||||||
|
"""
|
||||||
|
parsed = urlparse(url)
|
||||||
|
return (
|
||||||
|
parsed.scheme in ["http", "https"]
|
||||||
|
and "tiktok.com" in parsed.netloc
|
||||||
|
and "/photo/" in parsed.path
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def process_urls(urls: List[str]):
|
def process_urls(urls: List[str]):
|
||||||
"""
|
"""
|
||||||
Processes a list of TikTok URLs for downloading.
|
Processes a list of TikTok URLs for downloading.
|
||||||
@@ -154,27 +270,41 @@ def process_urls(urls: List[str]):
|
|||||||
print("No valid TikTok URLs found.")
|
print("No valid TikTok URLs found.")
|
||||||
return
|
return
|
||||||
|
|
||||||
|
downloaded_ids = load_downloaded_ids()
|
||||||
|
|
||||||
for i, url in enumerate(valid_urls, start=1):
|
for i, url in enumerate(valid_urls, start=1):
|
||||||
logger.info(f"Processing URL {i}/{len(valid_urls)}: {url}")
|
logger.info(f"Processing URL {i}/{len(valid_urls)}: {url}")
|
||||||
# print(f"Processing URL {i}/{len(valid_urls)}: {url}")
|
# print(f"Processing URL {i}/{len(valid_urls)}: {url}")
|
||||||
try:
|
try:
|
||||||
video_path = download_video(url)
|
# Extract ID and check if already downloaded
|
||||||
if video_path:
|
video_id = extract_tiktok_id(url)
|
||||||
logger.info(f"Downloaded successfully: {video_path}")
|
if video_id and video_id in downloaded_ids:
|
||||||
# print(f"Downloaded successfully: {video_path}")
|
logger.info(f"Skipping (already downloaded): {url}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
if is_tiktok_photo_url(url):
|
||||||
|
photo_paths = download_photo(url)
|
||||||
|
for path in photo_paths:
|
||||||
|
logger.info(f"Downloaded photo: {path}")
|
||||||
else:
|
else:
|
||||||
logger.error(f"Failed to download: {url}")
|
video_path = download_video(url)
|
||||||
# print(f"Failed to download: {url}")
|
logger.info(f"Downloaded video: {video_path}")
|
||||||
|
|
||||||
|
# Mark as downloaded
|
||||||
|
if video_id:
|
||||||
|
save_downloaded_id(video_id)
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Error processing {url}: {str(e)}")
|
logger.error(f"Error processing {url}: {str(e)}")
|
||||||
# print(f"Error processing {url}: {str(e)}")
|
log_failed_url(url)
|
||||||
|
|
||||||
# Apply rate limiting
|
# Apply rate limiting
|
||||||
if i < len(valid_urls):
|
if i < len(valid_urls):
|
||||||
logger.info(f"Waiting {DOWNLOAD_DELAY} seconds before next download...")
|
logger.info(f"Waiting {DOWNLOAD_DELAY} seconds before next download...")
|
||||||
time.sleep(DOWNLOAD_DELAY)
|
time.sleep(DOWNLOAD_DELAY)
|
||||||
|
|
||||||
if __name__ == '__main__':
|
|
||||||
|
if __name__ == "__main__":
|
||||||
if len(sys.argv) < 2:
|
if len(sys.argv) < 2:
|
||||||
print("Usage: python downloader.py <url_or_input_file>")
|
print("Usage: python downloader.py <url_or_input_file>")
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
@@ -184,7 +314,7 @@ if __name__ == '__main__':
|
|||||||
# Check if the input is a file
|
# Check if the input is a file
|
||||||
if os.path.isfile(input_arg):
|
if os.path.isfile(input_arg):
|
||||||
try:
|
try:
|
||||||
with open(input_arg, 'r') as f:
|
with open(input_arg, "r") as f:
|
||||||
urls = f.readlines()
|
urls = f.readlines()
|
||||||
logger.info(f"Processing URLs from file: {input_arg}")
|
logger.info(f"Processing URLs from file: {input_arg}")
|
||||||
process_urls(urls)
|
process_urls(urls)
|
||||||
@@ -195,5 +325,3 @@ if __name__ == '__main__':
|
|||||||
# Assume it's a single URL
|
# Assume it's a single URL
|
||||||
urls = [input_arg]
|
urls = [input_arg]
|
||||||
process_urls(urls)
|
process_urls(urls)
|
||||||
|
|
||||||
|
|
||||||
Reference in new issue
Block a user