This commit is contained in:
afkarxyz committed 2025-12-05 05:00:51 +07:00
1 parent 8e5f18c6cc
commit 280133649d
92 files changed
+15747 -4673

No files matched your search

+10
View File
@@ -0,0 +1,10 @@
//go:build !windows
package backend
import "os/exec"
// hideWindow is a no-op on non-Windows platforms
func hideWindow(cmd *exec.Cmd) {
// No action needed on Unix-like systems
}
+16
View File
@@ -0,0 +1,16 @@
//go:build windows
package backend
import (
"os/exec"
"syscall"
)
// hideWindow sets the command to run without showing a console window on Windows
func hideWindow(cmd *exec.Cmd) {
cmd.SysProcAttr = &syscall.SysProcAttr{
HideWindow: true,
CreationFlags: 0x08000000, // CREATE_NO_WINDOW
}
}
+18
View File
@@ -0,0 +1,18 @@
package backend
import (
"os"
"path/filepath"
)
func GetDefaultDownloadPath() string {
// Get user's home directory
homeDir, err := os.UserHomeDir()
if err != nil {
// Fallback to Public Pictures if can't get home dir
return "C:\\Users\\Public\\Pictures"
}
// Return path to user's Pictures folder
return filepath.Join(homeDir, "Pictures")
}
+499
View File
@@ -0,0 +1,499 @@
package backend
import (
"database/sql"
"encoding/json"
"fmt"
"os"
"path/filepath"
"time"
_ "github.com/mattn/go-sqlite3"
)
// AccountDB represents a saved account in the database
type AccountDB struct {
ID int64 `json:"id"`
Username string `json:"username"`
Name string `json:"name"`
ProfileImage string `json:"profile_image"`
TotalMedia int `json:"total_media"`
LastFetched time.Time `json:"last_fetched"`
ResponseJSON string `json:"response_json"`
MediaType string `json:"media_type"`
Cursor string `json:"cursor"`
Completed bool `json:"completed"`
}
// AccountListItem represents a simplified account for listing
type AccountListItem struct {
ID int64 `json:"id"`
Username string `json:"username"`
Name string `json:"name"`
ProfileImage string `json:"profile_image"`
TotalMedia int `json:"total_media"`
LastFetched string `json:"last_fetched"`
GroupName string `json:"group_name"`
GroupColor string `json:"group_color"`
MediaType string `json:"media_type"`
Cursor string `json:"cursor"`
Completed bool `json:"completed"`
}
var db *sql.DB
// GetDBPath returns the database file path
func GetDBPath() string {
homeDir, err := os.UserHomeDir()
if err != nil {
homeDir = "."
}
return filepath.Join(homeDir, ".twitterxmediabatchdownloader", "accounts.db")
}
// InitDB initializes the database connection
func InitDB() error {
dbPath := GetDBPath()
// Create directory if not exists
dir := filepath.Dir(dbPath)
if err := os.MkdirAll(dir, 0755); err != nil {
return err
}
var err error
db, err = sql.Open("sqlite3", dbPath)
if err != nil {
return err
}
// Create tables
_, err = db.Exec(`
CREATE TABLE IF NOT EXISTS accounts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL,
name TEXT,
profile_image TEXT,
total_media INTEGER DEFAULT 0,
last_fetched DATETIME,
response_json TEXT,
group_name TEXT DEFAULT '',
group_color TEXT DEFAULT '',
media_type TEXT DEFAULT 'all',
cursor TEXT DEFAULT '',
completed INTEGER DEFAULT 1,
UNIQUE(username, media_type)
)
`)
if err != nil {
return err
}
// Add group columns if they don't exist (migration for existing databases)
db.Exec("ALTER TABLE accounts ADD COLUMN group_name TEXT DEFAULT ''")
db.Exec("ALTER TABLE accounts ADD COLUMN group_color TEXT DEFAULT ''")
db.Exec("ALTER TABLE accounts ADD COLUMN media_type TEXT DEFAULT 'all'")
db.Exec("ALTER TABLE accounts ADD COLUMN cursor TEXT DEFAULT ''")
db.Exec("ALTER TABLE accounts ADD COLUMN completed INTEGER DEFAULT 1")
// Migration: Update unique constraint for existing databases
// This allows same username with different media types
db.Exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_username_media_type ON accounts(username, media_type)")
return nil
}
// CloseDB closes the database connection
func CloseDB() {
if db != nil {
db.Close()
}
}
// SaveAccount saves or updates an account in the database
func SaveAccount(username, name, profileImage string, totalMedia int, responseJSON string, mediaType string) error {
return SaveAccountWithStatus(username, name, profileImage, totalMedia, responseJSON, mediaType, "", true)
}
// SaveAccountWithStatus saves or updates an account with cursor and completion status
func SaveAccountWithStatus(username, name, profileImage string, totalMedia int, responseJSON string, mediaType string, cursor string, completed bool) error {
if db == nil {
if err := InitDB(); err != nil {
return err
}
}
// Default to "all" if not specified
if mediaType == "" {
mediaType = "all"
}
completedInt := 0
if completed {
completedInt = 1
}
_, err := db.Exec(`
INSERT INTO accounts (username, name, profile_image, total_media, last_fetched, response_json, media_type, cursor, completed)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(username, media_type) DO UPDATE SET
name = excluded.name,
profile_image = excluded.profile_image,
total_media = excluded.total_media,
last_fetched = excluded.last_fetched,
response_json = excluded.response_json,
cursor = excluded.cursor,
completed = excluded.completed
`, username, name, profileImage, totalMedia, time.Now(), responseJSON, mediaType, cursor, completedInt)
return err
}
// GetAllAccounts returns all saved accounts
func GetAllAccounts() ([]AccountListItem, error) {
if db == nil {
if err := InitDB(); err != nil {
return nil, err
}
}
rows, err := db.Query(`
SELECT id, username, name, profile_image, total_media, last_fetched,
COALESCE(group_name, '') as group_name, COALESCE(group_color, '') as group_color,
COALESCE(media_type, 'all') as media_type,
COALESCE(cursor, '') as cursor, COALESCE(completed, 1) as completed
FROM accounts
ORDER BY group_name ASC, last_fetched DESC
`)
if err != nil {
return nil, err
}
defer rows.Close()
var accounts []AccountListItem
for rows.Next() {
var acc AccountListItem
var lastFetched time.Time
var completedInt int
if err := rows.Scan(&acc.ID, &acc.Username, &acc.Name, &acc.ProfileImage, &acc.TotalMedia, &lastFetched, &acc.GroupName, &acc.GroupColor, &acc.MediaType, &acc.Cursor, &completedInt); err != nil {
continue
}
acc.LastFetched = lastFetched.Format("2006-01-02 15:04")
acc.Completed = completedInt == 1
accounts = append(accounts, acc)
}
return accounts, nil
}
// UpdateAccountGroup updates the group for an account
func UpdateAccountGroup(id int64, groupName, groupColor string) error {
if db == nil {
if err := InitDB(); err != nil {
return err
}
}
_, err := db.Exec("UPDATE accounts SET group_name = ?, group_color = ? WHERE id = ?", groupName, groupColor, id)
return err
}
// GetAllGroups returns all unique groups
func GetAllGroups() ([]map[string]string, error) {
if db == nil {
if err := InitDB(); err != nil {
return nil, err
}
}
rows, err := db.Query(`
SELECT DISTINCT group_name, group_color
FROM accounts
WHERE group_name != ''
ORDER BY group_name
`)
if err != nil {
return nil, err
}
defer rows.Close()
var groups []map[string]string
for rows.Next() {
var name, color string
if err := rows.Scan(&name, &color); err != nil {
continue
}
groups = append(groups, map[string]string{"name": name, "color": color})
}
return groups, nil
}
// ClearAllAccounts deletes all accounts from the database
func ClearAllAccounts() error {
if db == nil {
if err := InitDB(); err != nil {
return err
}
}
_, err := db.Exec("DELETE FROM accounts")
return err
}
// GetAccountByUsername returns a specific account by username
func GetAccountByUsername(username string) (*AccountDB, error) {
if db == nil {
if err := InitDB(); err != nil {
return nil, err
}
}
var acc AccountDB
var lastFetched time.Time
var completedInt int
err := db.QueryRow(`
SELECT id, username, name, profile_image, total_media, last_fetched, response_json,
COALESCE(cursor, '') as cursor, COALESCE(completed, 1) as completed
FROM accounts WHERE username = ?
`, username).Scan(&acc.ID, &acc.Username, &acc.Name, &acc.ProfileImage, &acc.TotalMedia, &lastFetched, &acc.ResponseJSON, &acc.Cursor, &completedInt)
if err != nil {
return nil, err
}
acc.LastFetched = lastFetched
acc.Completed = completedInt == 1
// Convert legacy format if needed
if converted, err := ConvertLegacyToNewFormat(acc.ResponseJSON); err == nil {
acc.ResponseJSON = converted
}
return &acc, nil
}
// GetAccountByID returns a specific account by ID
func GetAccountByID(id int64) (*AccountDB, error) {
if db == nil {
if err := InitDB(); err != nil {
return nil, err
}
}
var acc AccountDB
var lastFetched time.Time
var completedInt int
err := db.QueryRow(`
SELECT id, username, name, profile_image, total_media, last_fetched, response_json,
COALESCE(cursor, '') as cursor, COALESCE(completed, 1) as completed
FROM accounts WHERE id = ?
`, id).Scan(&acc.ID, &acc.Username, &acc.Name, &acc.ProfileImage, &acc.TotalMedia, &lastFetched, &acc.ResponseJSON, &acc.Cursor, &completedInt)
if err != nil {
return nil, err
}
acc.LastFetched = lastFetched
acc.Completed = completedInt == 1
// Convert legacy format if needed
if converted, err := ConvertLegacyToNewFormat(acc.ResponseJSON); err == nil {
acc.ResponseJSON = converted
}
return &acc, nil
}
// DeleteAccount deletes an account from the database
func DeleteAccount(id int64) error {
if db == nil {
if err := InitDB(); err != nil {
return err
}
}
_, err := db.Exec("DELETE FROM accounts WHERE id = ?", id)
return err
}
// ParseResponseJSON parses the stored JSON response
func ParseResponseJSON(jsonStr string) (map[string]interface{}, error) {
var result map[string]interface{}
err := json.Unmarshal([]byte(jsonStr), &result)
return result, err
}
// LegacyMediaEntry represents media entry in old format
type LegacyMediaEntry struct {
TweetID string `json:"tweet_id"`
URL string `json:"url"`
Date string `json:"date"`
Type string `json:"type"`
}
// LegacyAccountFormat represents the old saved account format
type LegacyAccountFormat struct {
Username string `json:"username"`
Nick string `json:"nick"`
Followers int `json:"followers"`
Following int `json:"following"`
Posts int `json:"posts"`
MediaType string `json:"media_type"`
ProfileImage string `json:"profile_image"`
FetchMode string `json:"fetch_mode"`
FetchTimestamp string `json:"fetch_timestamp"`
GroupID interface{} `json:"group_id"`
MediaList []LegacyMediaEntry `json:"media_list"`
}
// ConvertLegacyToNewFormat converts old format to new TwitterResponse format
func ConvertLegacyToNewFormat(jsonStr string) (string, error) {
// First check if it's already in new format (has account_info key)
var check map[string]interface{}
if err := json.Unmarshal([]byte(jsonStr), &check); err != nil {
return jsonStr, err
}
// If already has account_info, it's new format - return as is
if _, hasAccountInfo := check["account_info"]; hasAccountInfo {
return jsonStr, nil
}
// Check if it's legacy format (has username and media_list)
if _, hasUsername := check["username"]; !hasUsername {
return jsonStr, nil
}
if _, hasMediaList := check["media_list"]; !hasMediaList {
return jsonStr, nil
}
// Parse as legacy format
var legacy LegacyAccountFormat
if err := json.Unmarshal([]byte(jsonStr), &legacy); err != nil {
return jsonStr, err
}
// Convert timeline entries
timeline := make([]map[string]interface{}, len(legacy.MediaList))
for i, media := range legacy.MediaList {
timeline[i] = map[string]interface{}{
"url": media.URL,
"date": media.Date,
"tweet_id": media.TweetID,
"type": media.Type,
"is_retweet": false,
}
}
// Build new format
newFormat := map[string]interface{}{
"account_info": map[string]interface{}{
"name": legacy.Username,
"nick": legacy.Nick,
"date": "",
"followers_count": legacy.Followers,
"friends_count": legacy.Following,
"profile_image": legacy.ProfileImage,
"statuses_count": legacy.Posts,
},
"total_urls": len(legacy.MediaList),
"timeline": timeline,
"metadata": map[string]interface{}{
"new_entries": len(legacy.MediaList),
"page": 0,
"batch_size": 0,
"has_more": false,
},
}
// Convert back to JSON
newJSON, err := json.Marshal(newFormat)
if err != nil {
return jsonStr, err
}
return string(newJSON), nil
}
// ExportAccountToFile exports account JSON to a file
func ExportAccountToFile(id int64, outputDir string) (string, error) {
acc, err := GetAccountByID(id)
if err != nil {
return "", err
}
// Create export directory if not exists
exportDir := filepath.Join(outputDir, "twitterxmediabatchdownloader_backups")
if err := os.MkdirAll(exportDir, 0755); err != nil {
return "", err
}
// Use username (nick) for filename
filename := acc.Username
if filename == "" {
filename = acc.Name
}
filePath := filepath.Join(exportDir, filename+".json")
if err := os.WriteFile(filePath, []byte(acc.ResponseJSON), 0644); err != nil {
return "", err
}
return filePath, nil
}
// ImportAccountFromFile imports account from JSON file (supports both old and new format)
func ImportAccountFromFile(filePath string) (string, error) {
if db == nil {
if err := InitDB(); err != nil {
return "", err
}
}
// Read file
data, err := os.ReadFile(filePath)
if err != nil {
return "", err
}
jsonStr := string(data)
// Convert legacy format if needed
convertedJSON, err := ConvertLegacyToNewFormat(jsonStr)
if err != nil {
return "", err
}
// Parse the converted JSON to extract account info
var parsed map[string]interface{}
if err := json.Unmarshal([]byte(convertedJSON), &parsed); err != nil {
return "", err
}
// Extract account info
accountInfo, ok := parsed["account_info"].(map[string]interface{})
if !ok {
return "", fmt.Errorf("invalid JSON format: missing account_info")
}
username, _ := accountInfo["name"].(string)
name, _ := accountInfo["nick"].(string)
profileImage, _ := accountInfo["profile_image"].(string)
totalURLs := 0
if total, ok := parsed["total_urls"].(float64); ok {
totalURLs = int(total)
}
if username == "" {
return "", fmt.Errorf("invalid JSON format: missing username")
}
// Save to database with default media type "all" for imported files
err = SaveAccount(username, name, profileImage, totalURLs, convertedJSON, "all")
if err != nil {
return "", err
}
return username, nil
}
+380
View File
@@ -0,0 +1,380 @@
package backend
import (
"context"
"fmt"
"io"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"time"
)
const (
// MaxConcurrentDownloads is the number of parallel downloads
MaxConcurrentDownloads = 10
)
// MediaItem represents a media item with metadata for download
type MediaItem struct {
URL string `json:"url"`
Date string `json:"date"`
TweetID int64 `json:"tweet_id"`
Type string `json:"type"`
Username string `json:"username"`
Content string `json:"content,omitempty"` // Tweet text content (for text-only tweets)
}
// DownloadMediaFiles downloads media files from URLs to the output directory (legacy)
func DownloadMediaFiles(urls []string, outputDir string) (downloaded int, failed int, err error) {
// Create output directory if it doesn't exist
if err := os.MkdirAll(outputDir, 0755); err != nil {
return 0, len(urls), fmt.Errorf("failed to create output directory: %v", err)
}
client := &http.Client{
Timeout: 60 * time.Second,
}
for _, mediaURL := range urls {
filename := extractFilename(mediaURL)
outputPath := filepath.Join(outputDir, filename)
// Skip if file already exists
if _, err := os.Stat(outputPath); err == nil {
downloaded++
continue
}
if err := downloadFile(client, mediaURL, outputPath); err != nil {
failed++
continue
}
downloaded++
}
return downloaded, failed, nil
}
// ProgressCallback is a function type for progress updates
type ProgressCallback func(current, total int)
// ItemStatusCallback is a function type for per-item status updates
type ItemStatusCallback func(tweetID int64, index int, status string) // status: "success", "failed", "skipped"
// downloadTask represents a single download task
type downloadTask struct {
item MediaItem
outputPath string
index int
}
// DownloadMediaWithMetadata downloads media files with proper naming and categorization
func DownloadMediaWithMetadata(items []MediaItem, outputDir string, username string) (downloaded int, failed int, err error) {
return DownloadMediaWithMetadataProgressAndStatus(items, outputDir, username, nil, nil, nil)
}
// DownloadMediaWithMetadataProgress downloads media files with progress callback and cancellation support
func DownloadMediaWithMetadataProgress(items []MediaItem, outputDir string, username string, progress ProgressCallback, ctx context.Context) (downloaded int, failed int, err error) {
return DownloadMediaWithMetadataProgressAndStatus(items, outputDir, username, progress, nil, ctx)
}
// DownloadMediaWithMetadataProgressAndStatus downloads media files with progress and per-item status callbacks
func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir string, username string, progress ProgressCallback, itemStatus ItemStatusCallback, ctx context.Context) (downloaded int, failed int, err error) {
if ctx == nil {
ctx = context.Background()
}
// Create base output directory
baseDir := filepath.Join(outputDir, username)
if err := os.MkdirAll(baseDir, 0755); err != nil {
return 0, len(items), fmt.Errorf("failed to create output directory: %v", err)
}
total := len(items)
if total == 0 {
return 0, 0, nil
}
// Prepare all tasks first (sequential to handle tweet media count)
tweetMediaCount := make(map[int64]int)
tasks := make([]downloadTask, 0, total)
for i, item := range items {
// Determine subfolder based on type
var subfolder string
switch item.Type {
case "photo":
subfolder = "images"
case "video":
subfolder = "videos"
case "gif", "animated_gif":
subfolder = "gifs"
case "text":
subfolder = "texts"
default:
subfolder = "other"
}
// Create type subfolder
typeDir := filepath.Join(baseDir, subfolder)
if err := os.MkdirAll(typeDir, 0755); err != nil {
continue
}
// Format timestamp from date
timestamp := formatTimestamp(item.Date)
// Get file extension
ext := getExtension(item.URL, item.Type)
// Increment counter for this tweet_id
tweetMediaCount[item.TweetID]++
mediaIndex := tweetMediaCount[item.TweetID]
// Create filename: {username}_{timestamp}_{tweet_id}_{index}.{ext}
filename := fmt.Sprintf("%s_%s_%d_%02d%s", username, timestamp, item.TweetID, mediaIndex, ext)
outputPath := filepath.Join(typeDir, filename)
tasks = append(tasks, downloadTask{
item: item,
outputPath: outputPath,
index: i,
})
}
// Counters for parallel downloads
var downloadedCount int64
var failedCount int64
var completedCount int64
// Create worker pool
taskChan := make(chan downloadTask, len(tasks))
var wg sync.WaitGroup
// Start workers
numWorkers := MaxConcurrentDownloads
if numWorkers > len(tasks) {
numWorkers = len(tasks)
}
for i := 0; i < numWorkers; i++ {
wg.Add(1)
go func() {
defer wg.Done()
client := &http.Client{
Timeout: 60 * time.Second,
}
for task := range taskChan {
// Check for cancellation
select {
case <-ctx.Done():
return
default:
}
var status string
// Skip if file already exists
if _, err := os.Stat(task.outputPath); err == nil {
atomic.AddInt64(&downloadedCount, 1)
status = "skipped"
} else if task.item.Type == "text" {
// For text tweets, write content to file
if err := os.WriteFile(task.outputPath, []byte(task.item.Content), 0644); err != nil {
atomic.AddInt64(&failedCount, 1)
status = "failed"
} else {
atomic.AddInt64(&downloadedCount, 1)
status = "success"
}
} else if err := downloadFileWithContext(ctx, client, task.item.URL, task.outputPath); err != nil {
atomic.AddInt64(&failedCount, 1)
status = "failed"
} else {
atomic.AddInt64(&downloadedCount, 1)
status = "success"
}
// Emit per-item status
if itemStatus != nil {
itemStatus(task.item.TweetID, task.index, status)
}
// Update progress
completed := atomic.AddInt64(&completedCount, 1)
if progress != nil {
progress(int(completed), total)
}
}
}()
}
// Send tasks to workers
for _, task := range tasks {
select {
case <-ctx.Done():
close(taskChan)
wg.Wait()
return int(downloadedCount), int(failedCount) + (total - int(completedCount)), ctx.Err()
case taskChan <- task:
}
}
close(taskChan)
// Wait for all workers to finish
wg.Wait()
return int(downloadedCount), int(failedCount), nil
}
// downloadFileWithContext downloads a single file with context support for cancellation
func downloadFileWithContext(ctx context.Context, client *http.Client, url, outputPath string) error {
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
if err != nil {
return err
}
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("bad status: %s", resp.Status)
}
out, err := os.Create(outputPath)
if err != nil {
return err
}
defer out.Close()
_, err = io.Copy(out, resp.Body)
return err
}
// formatTimestamp converts date string to timestamp format
func formatTimestamp(dateStr string) string {
// Try parsing various date formats
formats := []string{
"2006-01-02T15:04:05", // ISO 8601 without timezone (from extractor)
"2006-01-02T15:04:05+00:00", // ISO 8601 with timezone
"2006-01-02T15:04:05-07:00", // ISO 8601 with timezone offset
time.RFC3339, // Standard RFC3339
"2006-01-02T15:04:05.000Z",
"2006-01-02T15:04:05Z",
"2006-01-02 15:04:05",
"Mon Jan 02 15:04:05 -0700 2006",
}
for _, format := range formats {
if t, err := time.Parse(format, dateStr); err == nil {
return t.Format("20060102_150405")
}
}
// Fallback: use empty string to indicate parsing failed
return "00000000_000000"
}
// getExtension determines file extension from URL and type
func getExtension(mediaURL string, mediaType string) string {
parsedURL, err := url.Parse(mediaURL)
if err != nil {
return ".jpg"
}
// Check format query param for Twitter images
if format := parsedURL.Query().Get("format"); format != "" {
return "." + format
}
// Get extension from path
path := parsedURL.Path
ext := filepath.Ext(path)
if ext != "" {
return ext
}
// Default based on type
switch mediaType {
case "video":
return ".mp4"
case "gif", "animated_gif":
return ".mp4" // Twitter GIFs are actually MP4
case "text":
return ".txt"
default:
return ".jpg"
}
}
// extractFilename extracts filename from URL (legacy)
func extractFilename(mediaURL string) string {
parsedURL, err := url.Parse(mediaURL)
if err != nil {
return fmt.Sprintf("media_%d", time.Now().UnixNano())
}
// Get the path part
path := parsedURL.Path
// Extract base filename
base := filepath.Base(path)
// Handle Twitter image URLs: /media/XXX -> XXX.jpg
if strings.Contains(mediaURL, "pbs.twimg.com/media/") {
// Get format from query params
format := parsedURL.Query().Get("format")
if format == "" {
format = "jpg"
}
// Remove any existing extension
if idx := strings.LastIndex(base, "."); idx > 0 {
base = base[:idx]
}
return base + "." + format
}
// Handle Twitter video URLs
if strings.Contains(mediaURL, "video.twimg.com") {
return base
}
// Default: use base name or generate one
if base == "" || base == "." {
return fmt.Sprintf("media_%d", time.Now().UnixNano())
}
return base
}
// downloadFile downloads a single file from URL
func downloadFile(client *http.Client, url, outputPath string) error {
resp, err := client.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("bad status: %s", resp.Status)
}
out, err := os.Create(outputPath)
if err != nil {
return err
}
defer out.Close()
_, err = io.Copy(out, resp.Body)
return err
}
+8
View File
@@ -0,0 +1,8 @@
//go:build linux || darwin
package backend
import _ "embed"
//go:embed bin/extractor
var extractorBin []byte
+8
View File
@@ -0,0 +1,8 @@
//go:build windows
package backend
import _ "embed"
//go:embed bin/extractor.exe
var extractorBin []byte
+316
View File
@@ -0,0 +1,316 @@
package backend
import (
"archive/tar"
"archive/zip"
"fmt"
"io"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"github.com/ulikunitz/xz"
)
// FFmpeg download URLs
const (
ffmpegWindowsURL = "https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/ffmpeg-master-latest-win64-gpl.zip"
ffmpegLinuxURL = "https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/ffmpeg-master-latest-linux64-gpl.tar.xz"
ffmpegMacOSURL = "https://evermeet.cx/ffmpeg/getrelease/ffmpeg/zip"
)
// GetFFmpegPath returns the path to ffmpeg binary
func GetFFmpegPath() string {
homeDir, _ := os.UserHomeDir()
baseDir := filepath.Join(homeDir, ".twitterxmediabatchdownloader")
switch runtime.GOOS {
case "windows":
return filepath.Join(baseDir, "ffmpeg.exe")
default:
return filepath.Join(baseDir, "ffmpeg")
}
}
// IsFFmpegInstalled checks if ffmpeg is available
func IsFFmpegInstalled() bool {
ffmpegPath := GetFFmpegPath()
if _, err := os.Stat(ffmpegPath); err == nil {
return true
}
return false
}
// DownloadFFmpeg downloads ffmpeg binary for current platform
func DownloadFFmpeg(progressCallback func(downloaded, total int64)) error {
var downloadURL string
switch runtime.GOOS {
case "windows":
downloadURL = ffmpegWindowsURL
case "linux":
downloadURL = ffmpegLinuxURL
case "darwin":
downloadURL = ffmpegMacOSURL
default:
return fmt.Errorf("unsupported platform: %s", runtime.GOOS)
}
// Create temp file for download
tempFile, err := os.CreateTemp("", "ffmpeg-*")
if err != nil {
return fmt.Errorf("failed to create temp file: %v", err)
}
tempPath := tempFile.Name()
defer os.Remove(tempPath)
defer tempFile.Close()
// Download file
resp, err := http.Get(downloadURL)
if err != nil {
return fmt.Errorf("failed to download ffmpeg: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("failed to download ffmpeg: status %d", resp.StatusCode)
}
// Copy with progress
total := resp.ContentLength
var downloaded int64
buf := make([]byte, 32*1024)
for {
n, err := resp.Body.Read(buf)
if n > 0 {
_, writeErr := tempFile.Write(buf[:n])
if writeErr != nil {
return fmt.Errorf("failed to write temp file: %v", writeErr)
}
downloaded += int64(n)
if progressCallback != nil {
progressCallback(downloaded, total)
}
}
if err == io.EOF {
break
}
if err != nil {
return fmt.Errorf("failed to download: %v", err)
}
}
tempFile.Close()
// Extract ffmpeg binary
ffmpegPath := GetFFmpegPath()
baseDir := filepath.Dir(ffmpegPath)
if err := os.MkdirAll(baseDir, 0755); err != nil {
return fmt.Errorf("failed to create directory: %v", err)
}
switch runtime.GOOS {
case "windows", "darwin":
return extractFromZip(tempPath, ffmpegPath)
case "linux":
return extractFromTarXz(tempPath, ffmpegPath)
}
return nil
}
// extractFromZip extracts ffmpeg from zip archive
func extractFromZip(zipPath, destPath string) error {
r, err := zip.OpenReader(zipPath)
if err != nil {
return fmt.Errorf("failed to open zip: %v", err)
}
defer r.Close()
for _, f := range r.File {
// Look for ffmpeg binary
name := filepath.Base(f.Name)
if name == "ffmpeg" || name == "ffmpeg.exe" {
rc, err := f.Open()
if err != nil {
return fmt.Errorf("failed to open file in zip: %v", err)
}
defer rc.Close()
out, err := os.Create(destPath)
if err != nil {
return fmt.Errorf("failed to create output file: %v", err)
}
defer out.Close()
if _, err := io.Copy(out, rc); err != nil {
return fmt.Errorf("failed to extract file: %v", err)
}
// Make executable on Unix
if runtime.GOOS != "windows" {
os.Chmod(destPath, 0755)
}
return nil
}
}
return fmt.Errorf("ffmpeg binary not found in archive")
}
// extractFromTarXz extracts ffmpeg from tar.xz archive
func extractFromTarXz(tarXzPath, destPath string) error {
file, err := os.Open(tarXzPath)
if err != nil {
return fmt.Errorf("failed to open tar.xz: %v", err)
}
defer file.Close()
xzReader, err := xz.NewReader(file)
if err != nil {
return fmt.Errorf("failed to create xz reader: %v", err)
}
tarReader := tar.NewReader(xzReader)
for {
header, err := tarReader.Next()
if err == io.EOF {
break
}
if err != nil {
return fmt.Errorf("failed to read tar: %v", err)
}
// Look for ffmpeg binary
name := filepath.Base(header.Name)
if name == "ffmpeg" && header.Typeflag == tar.TypeReg {
out, err := os.Create(destPath)
if err != nil {
return fmt.Errorf("failed to create output file: %v", err)
}
defer out.Close()
if _, err := io.Copy(out, tarReader); err != nil {
return fmt.Errorf("failed to extract file: %v", err)
}
os.Chmod(destPath, 0755)
return nil
}
}
return fmt.Errorf("ffmpeg binary not found in archive")
}
// ConvertMP4ToGIF converts an MP4 file to GIF using ffmpeg
// quality: "fast" for simple conversion, "better" for optimized palette
// resolution: "original", "high" (800px), "medium" (600px), "low" (400px)
func ConvertMP4ToGIF(inputPath, outputPath, quality, resolution string) error {
ffmpegPath := GetFFmpegPath()
if !IsFFmpegInstalled() {
return fmt.Errorf("ffmpeg not installed")
}
var args []string
if quality == "fast" {
// Fast mode: simple conversion
args = []string{
"-i", inputPath,
"-loop", "0",
"-y",
outputPath,
}
} else {
// Better mode: optimized palette with dithering
var filter string
switch resolution {
case "high":
filter = "scale=800:-1:flags=lanczos,palettegen=stats_mode=full[palette];[0:v]scale=800:-1:flags=lanczos[scaled];[scaled][palette]paletteuse=dither=sierra2_4a"
case "medium":
filter = "scale=600:-1:flags=lanczos,palettegen=stats_mode=full[palette];[0:v]scale=600:-1:flags=lanczos[scaled];[scaled][palette]paletteuse=dither=sierra2_4a"
case "low":
filter = "scale=400:-1:flags=lanczos,palettegen=stats_mode=full[palette];[0:v]scale=400:-1:flags=lanczos[scaled];[scaled][palette]paletteuse=dither=sierra2_4a"
default: // original
filter = "palettegen=stats_mode=full[palette];[0:v][palette]paletteuse=dither=sierra2_4a"
}
// Set FPS based on resolution
fps := "15"
if resolution == "medium" {
fps = "10"
} else if resolution == "low" {
fps = "8"
}
args = []string{
"-i", inputPath,
"-lavfi", filter,
"-r", fps,
"-y",
outputPath,
}
}
cmd := exec.Command(ffmpegPath, args...)
hideWindow(cmd) // Hide console window on Windows
output, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("ffmpeg error: %v, output: %s", err, string(output))
}
return nil
}
// ConvertGIFsInFolder converts all MP4 files in gifs folder to actual GIF format
func ConvertGIFsInFolder(folderPath, quality, resolution string, deleteOriginal bool) (converted int, failed int, err error) {
if !IsFFmpegInstalled() {
return 0, 0, fmt.Errorf("ffmpeg not installed")
}
// Clean the path to handle cross-platform path separators
cleanPath := filepath.Clean(folderPath)
gifsFolder := filepath.Join(cleanPath, "gifs")
if _, err := os.Stat(gifsFolder); os.IsNotExist(err) {
return 0, 0, fmt.Errorf("gifs folder not found: %s", gifsFolder)
}
files, err := os.ReadDir(gifsFolder)
if err != nil {
return 0, 0, fmt.Errorf("failed to read gifs folder: %v", err)
}
for _, file := range files {
if file.IsDir() {
continue
}
name := file.Name()
if !strings.HasSuffix(strings.ToLower(name), ".mp4") {
continue
}
inputPath := filepath.Join(gifsFolder, name)
outputPath := filepath.Join(gifsFolder, strings.TrimSuffix(name, filepath.Ext(name))+".gif")
if err := ConvertMP4ToGIF(inputPath, outputPath, quality, resolution); err != nil {
failed++
continue
}
if deleteOriginal {
os.Remove(inputPath)
}
converted++
}
return converted, failed, nil
}
+52
View File
@@ -0,0 +1,52 @@
package backend
import (
"context"
"os/exec"
"runtime"
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
)
func OpenFolderInExplorer(path string) error {
var cmd *exec.Cmd
switch runtime.GOOS {
case "windows":
// Use cmd /c start to open explorer - more reliable
cmd = exec.Command("cmd", "/c", "start", "", path)
case "darwin": // macOS
cmd = exec.Command("open", path)
case "linux":
cmd = exec.Command("xdg-open", path)
default:
cmd = exec.Command("xdg-open", path)
}
hideWindow(cmd) // Hide console window on Windows
return cmd.Run()
}
func SelectFolderDialog(ctx context.Context, defaultPath string) (string, error) {
// If defaultPath is empty, use default download path
if defaultPath == "" {
defaultPath = GetDefaultDownloadPath()
}
options := wailsRuntime.OpenDialogOptions{
Title: "Select Download Folder",
DefaultDirectory: defaultPath,
}
selectedPath, err := wailsRuntime.OpenDirectoryDialog(ctx, options)
if err != nil {
return "", err
}
// If user cancelled, selectedPath will be empty
if selectedPath == "" {
return "", nil
}
return selectedPath, nil
}
+898
View File
@@ -0,0 +1,898 @@
package backend
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"net/url"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
)
// getExecutableName returns the appropriate executable name for the current OS
func getExecutableName() string {
if runtime.GOOS == "windows" {
return "extractor.exe"
}
return "extractor"
}
// KillAllExtractorProcesses kills all running extractor processes
// This is useful for cleanup when starting fresh or when user stops fetch
func KillAllExtractorProcesses() {
exeName := getExecutableName()
var cmd *exec.Cmd
if runtime.GOOS == "windows" {
// Use taskkill on Windows
cmd = exec.Command("taskkill", "/F", "/IM", exeName)
} else {
// Use pkill on Unix
cmd = exec.Command("pkill", "-f", exeName)
}
hideWindow(cmd)
cmd.CombinedOutput() // Ignore errors - it's okay if no processes found
}
// parseExtractorError parses the extractor output and returns a user-friendly error message
// while preserving the original error from gallery-dl
func parseExtractorError(output string, username string) string {
outputLower := strings.ToLower(output)
// Extract the actual error line from gallery-dl output
lines := strings.Split(output, "\n")
var errorLine string
for _, line := range lines {
lineLower := strings.ToLower(line)
if strings.Contains(lineLower, "error:") || strings.Contains(lineLower, "exception") {
errorLine = strings.TrimSpace(line)
break
}
}
if errorLine == "" {
errorLine = strings.TrimSpace(output)
}
// Truncate if too long
if len(errorLine) > 300 {
errorLine = errorLine[:300] + "..."
}
// Add context hint based on error type, but keep original message
var hint string
if strings.Contains(outputLower, "unable to retrieve tweets from this timeline") {
hint = " [Hint: End of timeline reached or rate limited - data already fetched has been saved]"
} else if strings.Contains(outputLower, "rate limit") || strings.Contains(output, "429") {
hint = " [Hint: Wait 5-15 minutes before retrying]"
} else if strings.Contains(output, "401") || strings.Contains(outputLower, "unauthorized") {
hint = " [Hint: Auth token may be invalid or expired]"
} else if strings.Contains(output, "404") {
hint = fmt.Sprintf(" [Hint: @%s may not exist or is suspended]", username)
} else if strings.Contains(outputLower, "protected") || strings.Contains(output, "403") {
hint = " [Hint: Protected account - need to follow and use auth token]"
}
return errorLine + hint
}
// TweetIDString is a custom type that unmarshals int64 but marshals as string
type TweetIDString int64
// MarshalJSON converts TweetIDString to JSON string to preserve precision in JavaScript
func (t TweetIDString) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%d"`, t)), nil
}
// UnmarshalJSON accepts both number and string from JSON
func (t *TweetIDString) UnmarshalJSON(data []byte) error {
// Try to unmarshal as number first (from extractor)
var num int64
if err := json.Unmarshal(data, &num); err == nil {
*t = TweetIDString(num)
return nil
}
// Try as string (for future compatibility)
var str string
if err := json.Unmarshal(data, &str); err == nil {
parsed, err := fmt.Sscanf(str, "%d", &num)
if err != nil || parsed != 1 {
return fmt.Errorf("invalid tweet_id string: %s", str)
}
*t = TweetIDString(num)
return nil
}
return fmt.Errorf("tweet_id must be number or string")
}
// Author represents tweet author information from extractor
type Author struct {
ID int64 `json:"id"`
Name string `json:"name"`
Nick string `json:"nick"`
}
// UserInfo represents full user information from extractor
type UserInfo struct {
ID int64 `json:"id"`
Name string `json:"name"`
Nick string `json:"nick"`
Location string `json:"location"`
Date string `json:"date"`
Verified bool `json:"verified"`
Protected bool `json:"protected"`
ProfileBanner string `json:"profile_banner"`
ProfileImage string `json:"profile_image"`
FavouritesCount int `json:"favourites_count"`
FollowersCount int `json:"followers_count"`
FriendsCount int `json:"friends_count"`
ListedCount int `json:"listed_count"`
MediaCount int `json:"media_count"`
StatusesCount int `json:"statuses_count"`
Description string `json:"description"`
URL string `json:"url"`
}
// CLIMediaItem represents a single media entry from extractor CLI
type CLIMediaItem struct {
URL string `json:"url"`
TweetID TweetIDString `json:"tweet_id"`
RetweetID TweetIDString `json:"retweet_id"`
QuoteID TweetIDString `json:"quote_id"`
ReplyID TweetIDString `json:"reply_id"`
ConversationID TweetIDString `json:"conversation_id"`
Date string `json:"date"`
Extension string `json:"extension"`
Width int `json:"width"`
Height int `json:"height"`
Type string `json:"type"`
Bitrate int `json:"bitrate"`
Duration float64 `json:"duration"`
Author UserInfo `json:"author"`
User UserInfo `json:"user"`
Content string `json:"content"`
FavoriteCount int `json:"favorite_count"`
RetweetCount int `json:"retweet_count"`
ReplyCount int `json:"reply_count"`
QuoteCount int `json:"quote_count"`
BookmarkCount int `json:"bookmark_count"`
ViewCount int `json:"view_count"`
Source string `json:"source"`
Sensitive bool `json:"sensitive"`
}
// TweetMetadata represents tweet metadata from extractor
type TweetMetadata struct {
TweetID TweetIDString `json:"tweet_id"`
RetweetID TweetIDString `json:"retweet_id,omitempty"`
QuoteID TweetIDString `json:"quote_id,omitempty"`
ReplyID TweetIDString `json:"reply_id,omitempty"`
ConversationID TweetIDString `json:"conversation_id,omitempty"`
Date string `json:"date"`
Author Author `json:"author"`
Content string `json:"content"`
Lang string `json:"lang,omitempty"`
Hashtags []string `json:"hashtags,omitempty"`
FavoriteCount int `json:"favorite_count"`
RetweetCount int `json:"retweet_count"`
QuoteCount int `json:"quote_count,omitempty"`
ReplyCount int `json:"reply_count,omitempty"`
BookmarkCount int `json:"bookmark_count,omitempty"`
ViewCount int `json:"view_count,omitempty"`
Sensitive bool `json:"sensitive,omitempty"`
}
// CLIResponse represents the raw response from extractor CLI
type CLIResponse struct {
Media []CLIMediaItem `json:"media"`
Metadata []TweetMetadata `json:"metadata"`
Cursor string `json:"cursor,omitempty"` // Cursor for resume
Total int `json:"total,omitempty"` // Total items fetched
Completed bool `json:"completed,omitempty"` // True if all fetched
}
// TimelineEntry represents a single media entry for frontend (converted from MediaItem)
type TimelineEntry struct {
URL string `json:"url"`
Date string `json:"date"`
TweetID TweetIDString `json:"tweet_id"`
Type string `json:"type"`
IsRetweet bool `json:"is_retweet"`
Extension string `json:"extension"`
Width int `json:"width"`
Height int `json:"height"`
Content string `json:"content,omitempty"`
ViewCount int `json:"view_count,omitempty"`
BookmarkCount int `json:"bookmark_count,omitempty"`
FavoriteCount int `json:"favorite_count,omitempty"`
RetweetCount int `json:"retweet_count,omitempty"`
ReplyCount int `json:"reply_count,omitempty"`
Source string `json:"source,omitempty"`
Verified bool `json:"verified,omitempty"`
}
// AccountInfo represents Twitter account information (derived from metadata)
type AccountInfo struct {
Name string `json:"name"`
Nick string `json:"nick"`
Date string `json:"date"`
FollowersCount int `json:"followers_count"`
FriendsCount int `json:"friends_count"`
ProfileImage string `json:"profile_image"`
StatusesCount int `json:"statuses_count"`
}
// ExtractMetadata represents extraction metadata
type ExtractMetadata struct {
NewEntries int `json:"new_entries"`
Page int `json:"page"`
BatchSize int `json:"batch_size"`
HasMore bool `json:"has_more"`
Cursor string `json:"cursor,omitempty"` // Cursor for resume capability
Completed bool `json:"completed,omitempty"` // True if all media fetched
}
// TwitterResponse represents the full response for frontend
type TwitterResponse struct {
AccountInfo AccountInfo `json:"account_info"`
TotalURLs int `json:"total_urls"`
Timeline []TimelineEntry `json:"timeline"`
Metadata ExtractMetadata `json:"metadata"`
Cursor string `json:"cursor,omitempty"` // Cursor for next fetch
Completed bool `json:"completed,omitempty"` // True if fetch completed
}
// TimelineRequest represents request parameters for timeline extraction
type TimelineRequest struct {
Username string `json:"username"`
AuthToken string `json:"auth_token"`
TimelineType string `json:"timeline_type"` // media, timeline, tweets, with_replies, likes, bookmarks
BatchSize int `json:"batch_size"` // 0 = all
Page int `json:"page"`
MediaType string `json:"media_type"` // all, image, video, gif
Retweets bool `json:"retweets"`
Cursor string `json:"cursor,omitempty"` // Resume from this cursor position
}
// DateRangeRequest represents request parameters for date range extraction
type DateRangeRequest struct {
Username string `json:"username"`
AuthToken string `json:"auth_token"`
StartDate string `json:"start_date"` // YYYY-MM-DD
EndDate string `json:"end_date"` // YYYY-MM-DD
MediaFilter string `json:"media_filter"`
Retweets bool `json:"retweets"`
}
// buildTwitterURL constructs the Twitter URL based on username and timeline type
func buildTwitterURL(username, timelineType string) string {
// Special case: bookmarks don't need username
if timelineType == "bookmarks" {
return "https://x.com/i/bookmarks"
}
// Clean username - extract handle from URL if needed
username = cleanUsername(username)
// Build URL based on timeline type
baseURL := "https://x.com/" + username
switch timelineType {
case "media":
return baseURL + "/media"
case "timeline":
return baseURL + "/timeline" // Best for cursor support
case "tweets":
return baseURL + "/tweets"
case "with_replies":
return baseURL + "/with_replies"
case "likes":
return baseURL + "/likes"
default:
return baseURL + "/timeline" // Default to timeline for reliable cursor
}
}
// cleanUsername extracts the handle from different input formats
// Handles: @username, username, https://x.com/username, https://x.com/username/media, etc.
func cleanUsername(username string) string {
username = strings.TrimSpace(username)
username = strings.TrimPrefix(username, "@")
if strings.Contains(username, "x.com/") || strings.Contains(username, "twitter.com/") {
parsed := username
if !strings.HasPrefix(parsed, "http://") && !strings.HasPrefix(parsed, "https://") {
parsed = "https://" + strings.TrimPrefix(parsed, "//")
}
if u, err := url.Parse(parsed); err == nil {
segments := strings.Split(strings.Trim(u.Path, "/"), "/")
// Skip special paths like /i/bookmarks, /search, /home, /explore
if len(segments) > 0 && segments[0] != "" {
firstSegment := strings.ToLower(segments[0])
// These are not usernames
if firstSegment == "i" || firstSegment == "search" || firstSegment == "home" || firstSegment == "explore" || firstSegment == "settings" || firstSegment == "messages" || firstSegment == "notifications" {
return username // Return as-is, let caller handle
}
return segments[0]
}
}
}
return username
}
// ensureURLScheme normalises URLs so the CLI accepts them
func ensureURLScheme(raw string) string {
raw = strings.TrimSpace(raw)
if raw == "" {
return raw
}
if strings.HasPrefix(raw, "http://") || strings.HasPrefix(raw, "https://") {
return raw
}
if strings.HasPrefix(raw, "//") {
return "https:" + raw
}
return "https://" + strings.TrimPrefix(raw, "//")
}
// buildSearchURL assembles an X.com search URL for date range queries
func buildSearchURL(username, startDate, endDate, mediaFilter string, includeRetweets bool) string {
trimmed := strings.TrimSpace(username)
lower := strings.ToLower(trimmed)
if strings.Contains(lower, "search?q=") {
return ensureURLScheme(trimmed)
}
handle := cleanUsername(trimmed)
var parts []string
if handle != "" {
parts = append(parts, fmt.Sprintf("from:%s", handle))
}
if startDate != "" {
parts = append(parts, fmt.Sprintf("since:%s", startDate))
}
if endDate != "" {
parts = append(parts, fmt.Sprintf("until:%s", endDate))
}
switch strings.ToLower(strings.TrimSpace(mediaFilter)) {
case "image", "images", "photo", "photos":
parts = append(parts, "filter:images")
case "video", "videos", "gif", "gifs":
parts = append(parts, "filter:videos")
case "text":
parts = append(parts, "-filter:media")
default:
parts = append(parts, "filter:media")
}
if !includeRetweets {
parts = append(parts, "-filter:retweets")
}
query := url.QueryEscape(strings.Join(parts, " "))
return fmt.Sprintf("https://x.com/search?q=%s&src=typed_query&f=live", query)
}
// convertMetadataToTimelineEntry converts metadata-only tweets to timeline entries
func convertMetadataToTimelineEntry(meta TweetMetadata) TimelineEntry {
return TimelineEntry{
URL: "",
Date: meta.Date,
TweetID: meta.TweetID,
Type: "text",
IsRetweet: meta.RetweetID != 0,
Extension: "txt",
Width: 0,
Height: 0,
Content: meta.Content,
ViewCount: meta.ViewCount,
BookmarkCount: meta.BookmarkCount,
FavoriteCount: meta.FavoriteCount,
RetweetCount: meta.RetweetCount,
ReplyCount: meta.ReplyCount,
}
}
// convertToTimelineEntry converts CLIMediaItem to TimelineEntry
func convertToTimelineEntry(media CLIMediaItem) TimelineEntry {
entry := TimelineEntry{
URL: media.URL,
TweetID: media.TweetID,
Date: media.Date,
Extension: media.Extension,
Width: media.Width,
Height: media.Height,
IsRetweet: media.RetweetID != 0,
Content: media.Content,
ViewCount: media.ViewCount,
BookmarkCount: media.BookmarkCount,
FavoriteCount: media.FavoriteCount,
RetweetCount: media.RetweetCount,
ReplyCount: media.ReplyCount,
Source: media.Source,
Verified: media.Author.Verified,
}
// Determine type - media item already has type from CLI
if media.Type != "" {
entry.Type = media.Type
} else {
switch strings.ToLower(media.Extension) {
case "mp4", "webm":
entry.Type = "video"
case "gif":
entry.Type = "gif"
default:
entry.Type = "photo"
}
}
return entry
}
// getExtractorPath returns the path to extractor binary
// Binary is stored in ~/.twitterxmediabatchdownloader/ (same as ffmpeg and database)
func getExtractorPath() string {
homeDir, _ := os.UserHomeDir()
baseDir := filepath.Join(homeDir, ".twitterxmediabatchdownloader")
return filepath.Join(baseDir, getExecutableName())
}
// getHashFilePath returns the path to the hash file for version checking
func getHashFilePath() string {
homeDir, _ := os.UserHomeDir()
baseDir := filepath.Join(homeDir, ".twitterxmediabatchdownloader")
return filepath.Join(baseDir, "extractor.sha256")
}
// calculateHash calculates SHA256 hash of data
func calculateHash(data []byte) string {
hash := sha256.Sum256(data)
return hex.EncodeToString(hash[:])
}
// ensureExtractor ensures the extractor binary exists
// Extracts from embedded binary if not present or if hash differs (update)
func ensureExtractor() (string, error) {
exePath := getExtractorPath()
hashPath := getHashFilePath()
baseDir := filepath.Dir(exePath)
// Create directory if not exists
if err := os.MkdirAll(baseDir, 0755); err != nil {
return "", fmt.Errorf("failed to create directory: %v", err)
}
// Calculate hash of embedded binary
embeddedHash := calculateHash(extractorBin)
// Check if binary and hash file exist
if _, err := os.Stat(exePath); err == nil {
// Binary exists - check hash
if storedHash, err := os.ReadFile(hashPath); err == nil {
if string(storedHash) == embeddedHash {
return exePath, nil // Already extracted and up to date
}
}
// Hash differs or missing - need to update
os.Remove(exePath)
}
// Extract binary
if err := os.WriteFile(exePath, extractorBin, 0755); err != nil {
return "", fmt.Errorf("failed to write extractor: %v", err)
}
// Save hash for future comparison
if err := os.WriteFile(hashPath, []byte(embeddedHash), 0644); err != nil {
// Non-fatal - binary still works, just won't skip next time
fmt.Printf("Warning: failed to save hash file: %v\n", err)
}
return exePath, nil
}
// ExtractTimeline extracts media from user timeline using the new CLI
func ExtractTimeline(req TimelineRequest) (*TwitterResponse, error) {
// Get or extract extractor binary (persistent, not temp)
exePath, err := ensureExtractor()
if err != nil {
return nil, err
}
// Determine the right endpoint based on what user wants:
// - Media (all/image/video/gif): Use /media endpoint - fastest and most reliable
// - Text tweets: Use /tweets endpoint with --text-tweets
// - With retweets: Use /tweets endpoint (retweets not available on /media)
isTextOnly := req.MediaType == "text"
wantsRetweets := req.Retweets
timelineType := req.TimelineType
if timelineType == "" {
if isTextOnly {
// Text-only tweets need /tweets endpoint
timelineType = "tweets"
} else if wantsRetweets {
// Retweets need /tweets endpoint (not available on /media)
timelineType = "tweets"
} else {
// Default: /media endpoint - fastest for media-only fetch
timelineType = "media"
}
}
url := buildTwitterURL(req.Username, timelineType)
// Build command arguments for new CLI format
// Format: extractor.exe URL --auth-token TOKEN --json [options]
args := []string{url}
// Add auth token
if req.AuthToken != "" {
args = append(args, "--auth-token", req.AuthToken)
} else {
args = append(args, "--guest")
}
// Always request JSON output with metadata
args = append(args, "--json", "--metadata")
// Add limit if specified
if req.BatchSize > 0 {
args = append(args, "--limit", fmt.Sprintf("%d", req.BatchSize))
}
// Handle retweets - only relevant when using /tweets endpoint
if timelineType == "tweets" || timelineType == "timeline" {
if req.Retweets {
args = append(args, "--retweets", "include")
} else {
args = append(args, "--retweets", "skip")
}
}
// Only add --text-tweets when explicitly requesting text content
if isTextOnly {
args = append(args, "--text-tweets")
}
// Handle media type filter using --type parameter
if req.MediaType != "" && req.MediaType != "all" && !isTextOnly {
switch req.MediaType {
case "image":
args = append(args, "--type", "photo")
case "video":
args = append(args, "--type", "video")
case "gif":
args = append(args, "--type", "animated_gif")
}
}
// Add cursor for resume capability
if req.Cursor != "" {
args = append(args, "--cursor", req.Cursor)
}
// Execute command with UTF-8 encoding
cmd := exec.Command(exePath, args...)
cmd.Env = append(os.Environ(),
"PYTHONIOENCODING=utf-8",
"PYTHONUTF8=1",
)
hideWindow(cmd) // Hide console window on Windows
output, err := cmd.CombinedOutput()
// Ensure process is killed after completion
if cmd.Process != nil {
cmd.Process.Kill()
}
if err != nil {
outputStr := string(output)
errorMsg := parseExtractorError(outputStr, req.Username)
return nil, fmt.Errorf("%s", errorMsg)
}
// Find JSON in output (skip any info messages)
jsonStr := extractJSON(string(output))
if jsonStr == "" {
outputStr := string(output)
if strings.TrimSpace(outputStr) == "" {
return nil, fmt.Errorf("empty_response: Extractor returned no data. The timeline may be empty or inaccessible")
}
return nil, fmt.Errorf("parse_error: Could not parse extractor output. Raw output: %s", outputStr)
}
// Parse CLI response
var cliResponse CLIResponse
if err := json.Unmarshal([]byte(jsonStr), &cliResponse); err != nil {
return nil, fmt.Errorf("json_error: Failed to parse JSON response: %v", err)
}
// Convert to frontend format
var timeline []TimelineEntry
accountInfo := AccountInfo{
Name: req.Username,
Nick: req.Username,
}
// Build a set of tweet IDs that have media
mediaTweetIDs := make(map[int64]bool)
for _, media := range cliResponse.Media {
mediaTweetIDs[int64(media.TweetID)] = true
}
if isTextOnly {
// Text-only mode: get tweets from metadata that don't have media
timeline = make([]TimelineEntry, 0)
for _, meta := range cliResponse.Metadata {
if !mediaTweetIDs[int64(meta.TweetID)] {
timeline = append(timeline, convertMetadataToTimelineEntry(meta))
}
}
// Get account info from first media item if available, otherwise from metadata
if len(cliResponse.Media) > 0 {
user := cliResponse.Media[0].User
accountInfo.Name = user.Name
accountInfo.Nick = user.Nick
accountInfo.Date = user.Date
accountInfo.FollowersCount = user.FollowersCount
accountInfo.FriendsCount = user.FriendsCount
accountInfo.ProfileImage = user.ProfileImage
accountInfo.StatusesCount = user.StatusesCount
} else if len(cliResponse.Metadata) > 0 {
firstMeta := cliResponse.Metadata[0]
accountInfo.Name = firstMeta.Author.Name
accountInfo.Nick = firstMeta.Author.Nick
}
} else if len(cliResponse.Media) > 0 {
// Normal media items only (text tweets handled separately with "text" media type)
timeline = make([]TimelineEntry, 0, len(cliResponse.Media))
// Add media items
for _, media := range cliResponse.Media {
timeline = append(timeline, convertToTimelineEntry(media))
}
// Get account info from first media item
user := cliResponse.Media[0].User
accountInfo.Name = user.Name
accountInfo.Nick = user.Nick
accountInfo.Date = user.Date
accountInfo.FollowersCount = user.FollowersCount
accountInfo.FriendsCount = user.FriendsCount
accountInfo.ProfileImage = user.ProfileImage
accountInfo.StatusesCount = user.StatusesCount
} else if len(cliResponse.Metadata) > 0 {
// Fallback: Text-only tweets (no media) - convert metadata to timeline entries
timeline = make([]TimelineEntry, 0, len(cliResponse.Metadata))
for _, meta := range cliResponse.Metadata {
entry := TimelineEntry{
URL: "", // No media URL for text tweets
TweetID: meta.TweetID,
Date: meta.Date,
Type: "text",
IsRetweet: meta.RetweetID != 0,
Extension: "txt",
Width: 0,
Height: 0,
Content: meta.Content,
ViewCount: meta.ViewCount,
BookmarkCount: meta.BookmarkCount,
FavoriteCount: meta.FavoriteCount,
RetweetCount: meta.RetweetCount,
ReplyCount: meta.ReplyCount,
}
timeline = append(timeline, entry)
}
// Get account info from first metadata
firstMeta := cliResponse.Metadata[0]
accountInfo.Name = firstMeta.Author.Name
accountInfo.Nick = firstMeta.Author.Nick
}
// Determine if there's more data to fetch
hasMore := cliResponse.Cursor != "" && !cliResponse.Completed
response := &TwitterResponse{
AccountInfo: accountInfo,
TotalURLs: len(timeline),
Timeline: timeline,
Metadata: ExtractMetadata{
NewEntries: len(timeline),
Page: req.Page,
BatchSize: req.BatchSize,
HasMore: hasMore,
Cursor: cliResponse.Cursor,
Completed: cliResponse.Completed,
},
Cursor: cliResponse.Cursor,
Completed: cliResponse.Completed,
}
return response, nil
}
// ExtractDateRange extracts media based on date range using the new CLI
func ExtractDateRange(req DateRangeRequest) (*TwitterResponse, error) {
// Get or extract extractor binary (persistent, not temp)
exePath, err := ensureExtractor()
if err != nil {
return nil, err
}
mediaFilter := strings.ToLower(strings.TrimSpace(req.MediaFilter))
url := buildSearchURL(req.Username, req.StartDate, req.EndDate, mediaFilter, req.Retweets)
// Build command arguments
args := []string{url}
// Add auth token
if req.AuthToken != "" {
args = append(args, "--auth-token", req.AuthToken)
} else {
args = append(args, "--guest")
}
// Always request JSON output with metadata
args = append(args, "--json", "--metadata")
if req.Retweets {
args = append(args, "--retweets", "include")
} else {
args = append(args, "--retweets", "skip")
}
isTextOnly := mediaFilter == "text"
if isTextOnly {
args = append(args, "--text-tweets")
}
// Execute command with UTF-8 encoding
cmd := exec.Command(exePath, args...)
cmd.Env = append(os.Environ(),
"PYTHONIOENCODING=utf-8",
"PYTHONUTF8=1",
)
hideWindow(cmd)
output, err := cmd.CombinedOutput()
// Ensure process is killed after completion
if cmd.Process != nil {
cmd.Process.Kill()
}
if err != nil {
outputStr := string(output)
errorMsg := parseExtractorError(outputStr, req.Username)
return nil, fmt.Errorf("%s", errorMsg)
}
// Find JSON in output (skip any info messages)
jsonStr := extractJSON(string(output))
if jsonStr == "" {
outputStr := string(output)
if strings.TrimSpace(outputStr) == "" {
return nil, fmt.Errorf("empty_response: Extractor returned no data. The timeline may be empty or inaccessible")
}
return nil, fmt.Errorf("parse_error: Could not parse extractor output. Raw output: %s", outputStr)
}
// Parse CLI response
var cliResponse CLIResponse
if err := json.Unmarshal([]byte(jsonStr), &cliResponse); err != nil {
return nil, fmt.Errorf("json_error: Failed to parse JSON response: %v", err)
}
// Convert to frontend format
mediaTweetIDs := make(map[int64]bool)
for _, media := range cliResponse.Media {
mediaTweetIDs[int64(media.TweetID)] = true
}
timeline := make([]TimelineEntry, 0, len(cliResponse.Media)+len(cliResponse.Metadata))
for _, media := range cliResponse.Media {
timeline = append(timeline, convertToTimelineEntry(media))
}
if isTextOnly {
for _, meta := range cliResponse.Metadata {
if !mediaTweetIDs[int64(meta.TweetID)] {
timeline = append(timeline, convertMetadataToTimelineEntry(meta))
}
}
}
// Build account info from first media item (has full user info)
accountInfo := AccountInfo{
Name: req.Username,
Nick: req.Username,
}
if len(cliResponse.Media) > 0 {
user := cliResponse.Media[0].User
accountInfo.Name = user.Name
accountInfo.Nick = user.Nick
accountInfo.Date = user.Date
accountInfo.FollowersCount = user.FollowersCount
accountInfo.FriendsCount = user.FriendsCount
accountInfo.ProfileImage = user.ProfileImage
accountInfo.StatusesCount = user.StatusesCount
} else if len(cliResponse.Metadata) > 0 {
firstMeta := cliResponse.Metadata[0]
accountInfo.Name = firstMeta.Author.Name
accountInfo.Nick = firstMeta.Author.Nick
}
// Determine if there's more data to fetch
hasMore := cliResponse.Cursor != "" && !cliResponse.Completed
response := &TwitterResponse{
AccountInfo: accountInfo,
TotalURLs: len(timeline),
Timeline: timeline,
Metadata: ExtractMetadata{
NewEntries: len(timeline),
Page: 0,
BatchSize: 0,
HasMore: hasMore,
Cursor: cliResponse.Cursor,
Completed: cliResponse.Completed,
},
Cursor: cliResponse.Cursor,
Completed: cliResponse.Completed,
}
return response, nil
}
// extractJSON finds and extracts JSON object from output string
func extractJSON(output string) string {
// Find the start of JSON object
start := strings.Index(output, "{")
if start == -1 {
return ""
}
// Find the matching closing brace
depth := 0
for i := start; i < len(output); i++ {
if output[i] == '{' {
depth++
} else if output[i] == '}' {
depth--
if depth == 0 {
return output[start : i+1]
}
}
}
return ""
}
// GetThumbnailURL converts a Twitter media URL to thumbnail size
func GetThumbnailURL(url string) string {
// For images: https://pbs.twimg.com/media/XXX?format=jpg&name=thumb
if strings.Contains(url, "pbs.twimg.com/media/") {
// Check if it already has format parameter
if strings.Contains(url, "?format=") {
// Replace name parameter with thumb
if strings.Contains(url, "&name=") {
parts := strings.Split(url, "&name=")
return parts[0] + "&name=thumb"
}
return url + "&name=thumb"
}
// Add format and name parameters
if strings.Contains(url, "?") {
return url + "&name=thumb"
}
return url + "?format=jpg&name=thumb"
}
return url
}