mirror of
https://github.com/Alvin-Zilverstand/Twitter-X-Media-Batch-Downloader.git
synced 2026-11-30 18:17:59 +01:00
v4.6
This commit is contained in:
1 parent
33be717065
commit
e05a9379fc
20 files changed
+1449
-611
No files matched your search
+20
-2
@@ -2,8 +2,26 @@
|
||||
|
||||
package backend
|
||||
|
||||
import "os/exec"
|
||||
import (
|
||||
"errors"
|
||||
"os/exec"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
func hideWindow(cmd *exec.Cmd) {
|
||||
|
||||
cmd.SysProcAttr = &syscall.SysProcAttr{
|
||||
Setpgid: true,
|
||||
}
|
||||
}
|
||||
|
||||
func terminateCommandProcess(cmd *exec.Cmd) error {
|
||||
if cmd == nil || cmd.Process == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
if err := syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL); err != nil && !errors.Is(err, syscall.ESRCH) {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -4,6 +4,7 @@ package backend
|
||||
|
||||
import (
|
||||
"os/exec"
|
||||
"strconv"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
@@ -13,3 +14,17 @@ func hideWindow(cmd *exec.Cmd) {
|
||||
CreationFlags: 0x08000000,
|
||||
}
|
||||
}
|
||||
|
||||
func terminateCommandProcess(cmd *exec.Cmd) error {
|
||||
if cmd == nil || cmd.Process == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
taskkill := exec.Command("taskkill", "/T", "/F", "/PID", strconv.Itoa(cmd.Process.Pid))
|
||||
hideWindow(taskkill)
|
||||
if err := taskkill.Run(); err == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
return cmd.Process.Kill()
|
||||
}
|
||||
+69
-51
@@ -6,6 +6,8 @@ import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
_ "modernc.org/sqlite"
|
||||
@@ -41,6 +43,15 @@ type AccountListItem struct {
|
||||
}
|
||||
|
||||
var db *sql.DB
|
||||
var dbInitOnce sync.Once
|
||||
var dbInitErr error
|
||||
|
||||
func ensureDB() error {
|
||||
dbInitOnce.Do(func() {
|
||||
dbInitErr = initDBInternal()
|
||||
})
|
||||
return dbInitErr
|
||||
}
|
||||
|
||||
type accountMetricsPayload struct {
|
||||
AccountInfo struct {
|
||||
@@ -60,6 +71,10 @@ func GetDBPath() string {
|
||||
}
|
||||
|
||||
func InitDB() error {
|
||||
return ensureDB()
|
||||
}
|
||||
|
||||
func initDBInternal() error {
|
||||
dbPath := GetDBPath()
|
||||
|
||||
dir := filepath.Dir(dbPath)
|
||||
@@ -100,16 +115,12 @@ func InitDB() error {
|
||||
return err
|
||||
}
|
||||
|
||||
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")
|
||||
db.Exec("ALTER TABLE accounts ADD COLUMN followers_count INTEGER DEFAULT 0")
|
||||
db.Exec("ALTER TABLE accounts ADD COLUMN statuses_count INTEGER DEFAULT 0")
|
||||
|
||||
db.Exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_username_media_type ON accounts(username, media_type)")
|
||||
|
||||
if err := runMigrations(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := backfillAccountMetrics(); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -117,6 +128,37 @@ func InitDB() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func runMigrations() error {
|
||||
var version int
|
||||
if err := db.QueryRow("PRAGMA user_version").Scan(&version); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
migrations := []string{
|
||||
"ALTER TABLE accounts ADD COLUMN group_name TEXT DEFAULT ''",
|
||||
"ALTER TABLE accounts ADD COLUMN group_color TEXT DEFAULT ''",
|
||||
"ALTER TABLE accounts ADD COLUMN media_type TEXT DEFAULT 'all'",
|
||||
"ALTER TABLE accounts ADD COLUMN cursor TEXT DEFAULT ''",
|
||||
"ALTER TABLE accounts ADD COLUMN completed INTEGER DEFAULT 1",
|
||||
"ALTER TABLE accounts ADD COLUMN followers_count INTEGER DEFAULT 0",
|
||||
"ALTER TABLE accounts ADD COLUMN statuses_count INTEGER DEFAULT 0",
|
||||
}
|
||||
|
||||
for i := version; i < len(migrations); i++ {
|
||||
if _, err := db.Exec(migrations[i]); err != nil {
|
||||
if !strings.Contains(err.Error(), "duplicate column name") {
|
||||
return fmt.Errorf("migration %d failed: %w", i, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if _, err := db.Exec(fmt.Sprintf("PRAGMA user_version = %d", len(migrations))); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func CloseDB() {
|
||||
if db != nil {
|
||||
db.Close()
|
||||
@@ -128,10 +170,8 @@ func SaveAccount(username, name, profileImage string, totalMedia int, responseJS
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
if err := ensureDB(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if mediaType == "" {
|
||||
@@ -164,10 +204,8 @@ func SaveAccountWithStatus(username, name, profileImage string, totalMedia int,
|
||||
}
|
||||
|
||||
func GetAllAccounts() ([]AccountListItem, error) {
|
||||
if db == nil {
|
||||
if err := InitDB(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := ensureDB(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rows, err := db.Query(`
|
||||
@@ -264,10 +302,8 @@ func backfillAccountMetrics() error {
|
||||
}
|
||||
|
||||
func UpdateAccountGroup(id int64, groupName, groupColor string) error {
|
||||
if db == nil {
|
||||
if err := InitDB(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := ensureDB(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err := db.Exec("UPDATE accounts SET group_name = ?, group_color = ? WHERE id = ?", groupName, groupColor, id)
|
||||
@@ -275,10 +311,8 @@ func UpdateAccountGroup(id int64, groupName, groupColor string) error {
|
||||
}
|
||||
|
||||
func GetAllGroups() ([]map[string]string, error) {
|
||||
if db == nil {
|
||||
if err := InitDB(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := ensureDB(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rows, err := db.Query(`
|
||||
@@ -305,10 +339,8 @@ func GetAllGroups() ([]map[string]string, error) {
|
||||
}
|
||||
|
||||
func ClearAllAccounts() error {
|
||||
if db == nil {
|
||||
if err := InitDB(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := ensureDB(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err := db.Exec("DELETE FROM accounts")
|
||||
@@ -316,10 +348,8 @@ func ClearAllAccounts() error {
|
||||
}
|
||||
|
||||
func GetAccountByID(id int64) (*AccountDB, error) {
|
||||
if db == nil {
|
||||
if err := InitDB(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := ensureDB(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var acc AccountDB
|
||||
@@ -345,10 +375,8 @@ func GetAccountByID(id int64) (*AccountDB, error) {
|
||||
}
|
||||
|
||||
func GetAccountByUsernameAndMediaType(username, mediaType string) (*AccountDB, error) {
|
||||
if db == nil {
|
||||
if err := InitDB(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := ensureDB(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if mediaType == "" {
|
||||
@@ -380,10 +408,8 @@ func GetAccountByUsernameAndMediaType(username, mediaType string) (*AccountDB, e
|
||||
}
|
||||
|
||||
func DeleteAccount(id int64) error {
|
||||
if db == nil {
|
||||
if err := InitDB(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := ensureDB(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err := db.Exec("DELETE FROM accounts WHERE id = ?", id)
|
||||
@@ -523,13 +549,7 @@ func ExportAccountsToTXT(ids []int64, outputDir string) (string, error) {
|
||||
return "", fmt.Errorf("no valid usernames found")
|
||||
}
|
||||
|
||||
txtContent := ""
|
||||
for i, username := range usernames {
|
||||
if i > 0 {
|
||||
txtContent += "\n"
|
||||
}
|
||||
txtContent += username
|
||||
}
|
||||
txtContent := strings.Join(usernames, "\n")
|
||||
|
||||
filePath := filepath.Join(exportDir, "twitterxmediabatchdownloader_multiple.txt")
|
||||
|
||||
@@ -541,10 +561,8 @@ func ExportAccountsToTXT(ids []int64, outputDir string) (string, error) {
|
||||
}
|
||||
|
||||
func ImportAccountFromFile(filePath string) (string, error) {
|
||||
if db == nil {
|
||||
if err := InitDB(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := ensureDB(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
data, err := os.ReadFile(filePath)
|
||||
|
||||
+264
-48
@@ -2,6 +2,7 @@ package backend
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
@@ -15,9 +16,45 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
MaxConcurrentDownloads = 10
|
||||
DefaultConcurrentDownloads = 10
|
||||
MaxConcurrentDownloads = 50
|
||||
DefaultRetryAttempts = 2
|
||||
MaxRetryAttempts = 5
|
||||
)
|
||||
|
||||
func NormalizeConcurrentDownloads(requested int) int {
|
||||
if requested <= 0 {
|
||||
return DefaultConcurrentDownloads
|
||||
}
|
||||
if requested > MaxConcurrentDownloads {
|
||||
return MaxConcurrentDownloads
|
||||
}
|
||||
return requested
|
||||
}
|
||||
|
||||
func NormalizeRetryAttempts(requested int) int {
|
||||
if requested < 0 {
|
||||
return 0
|
||||
}
|
||||
if requested > MaxRetryAttempts {
|
||||
return MaxRetryAttempts
|
||||
}
|
||||
return requested
|
||||
}
|
||||
|
||||
type DownloadOptions struct {
|
||||
ConcurrentDownloads int
|
||||
SkipExistingFiles bool
|
||||
DeleteIncompleteFiles bool
|
||||
RetryAttempts int
|
||||
}
|
||||
|
||||
func NormalizeDownloadOptions(options DownloadOptions) DownloadOptions {
|
||||
options.ConcurrentDownloads = NormalizeConcurrentDownloads(options.ConcurrentDownloads)
|
||||
options.RetryAttempts = NormalizeRetryAttempts(options.RetryAttempts)
|
||||
return options
|
||||
}
|
||||
|
||||
type MediaItem struct {
|
||||
URL string `json:"url"`
|
||||
Date string `json:"date"`
|
||||
@@ -28,7 +65,8 @@ type MediaItem struct {
|
||||
OriginalFilename string `json:"original_filename,omitempty"`
|
||||
}
|
||||
|
||||
func DownloadMediaFiles(urls []string, outputDir string, customProxy string) (downloaded int, failed int, err error) {
|
||||
func DownloadMediaFiles(urls []string, outputDir string, options DownloadOptions, customProxy string) (downloaded int, failed int, err error) {
|
||||
options = NormalizeDownloadOptions(options)
|
||||
|
||||
if err := os.MkdirAll(outputDir, 0755); err != nil {
|
||||
return 0, len(urls), fmt.Errorf("failed to create output directory: %v", err)
|
||||
@@ -46,12 +84,14 @@ func DownloadMediaFiles(urls []string, outputDir string, customProxy string) (do
|
||||
filename := extractFilename(mediaURL)
|
||||
outputPath := filepath.Join(outputDir, filename)
|
||||
|
||||
if _, err := os.Stat(outputPath); err == nil {
|
||||
downloaded++
|
||||
continue
|
||||
if options.SkipExistingFiles {
|
||||
if _, err := os.Stat(outputPath); err == nil {
|
||||
downloaded++
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
if err := downloadFile(client, mediaURL, outputPath); err != nil {
|
||||
if err := downloadFileWithRetry(context.Background(), client, mediaURL, outputPath, options); err != nil {
|
||||
failed++
|
||||
continue
|
||||
}
|
||||
@@ -61,6 +101,140 @@ func DownloadMediaFiles(urls []string, outputDir string, customProxy string) (do
|
||||
return downloaded, failed, nil
|
||||
}
|
||||
|
||||
func fileExists(path string) (bool, error) {
|
||||
_, err := os.Stat(path)
|
||||
if err == nil {
|
||||
return true, nil
|
||||
}
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return false, nil
|
||||
}
|
||||
return false, err
|
||||
}
|
||||
|
||||
func cleanupIncompleteDownload(outputPath string) {
|
||||
_ = os.Remove(outputPath)
|
||||
}
|
||||
|
||||
func replaceFile(tempPath, outputPath string, allowOverwrite bool) error {
|
||||
if !allowOverwrite {
|
||||
return os.Rename(tempPath, outputPath)
|
||||
}
|
||||
|
||||
exists, err := fileExists(outputPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !exists {
|
||||
return os.Rename(tempPath, outputPath)
|
||||
}
|
||||
|
||||
backupPath := fmt.Sprintf("%s.bak.%d", outputPath, time.Now().UnixNano())
|
||||
if err := os.Rename(outputPath, backupPath); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := os.Rename(tempPath, outputPath); err != nil {
|
||||
restoreErr := os.Rename(backupPath, outputPath)
|
||||
if restoreErr != nil {
|
||||
return fmt.Errorf("failed to replace existing file: %v (restore failed: %v)", err, restoreErr)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
_ = os.Remove(backupPath)
|
||||
return nil
|
||||
}
|
||||
|
||||
func writeFileAtomically(outputPath string, data []byte, allowOverwrite bool, keepPartialOnFailure bool) error {
|
||||
out, err := os.CreateTemp(filepath.Dir(outputPath), filepath.Base(outputPath)+".*.part")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tempPath := out.Name()
|
||||
cleanupTemp := !keepPartialOnFailure
|
||||
defer func() {
|
||||
if out != nil {
|
||||
_ = out.Close()
|
||||
}
|
||||
if cleanupTemp {
|
||||
_ = os.Remove(tempPath)
|
||||
}
|
||||
}()
|
||||
|
||||
if _, err := out.Write(data); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := out.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
out = nil
|
||||
|
||||
if err := replaceFile(tempPath, outputPath, allowOverwrite); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
cleanupTemp = false
|
||||
return nil
|
||||
}
|
||||
|
||||
func waitForRetry(ctx context.Context, attempt int) error {
|
||||
timer := time.NewTimer(time.Duration(attempt) * 500 * time.Millisecond)
|
||||
defer timer.Stop()
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-timer.C:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func downloadFileWithRetry(ctx context.Context, client *http.Client, mediaURL, outputPath string, options DownloadOptions) error {
|
||||
options = NormalizeDownloadOptions(options)
|
||||
|
||||
var lastErr error
|
||||
totalAttempts := options.RetryAttempts + 1
|
||||
for attempt := 1; attempt <= totalAttempts; attempt++ {
|
||||
keepPartialOnFailure := !options.DeleteIncompleteFiles && attempt == totalAttempts
|
||||
lastErr = downloadFileWithContext(ctx, client, mediaURL, outputPath, !options.SkipExistingFiles, keepPartialOnFailure)
|
||||
if lastErr == nil {
|
||||
return nil
|
||||
}
|
||||
if ctx.Err() != nil || errors.Is(lastErr, context.Canceled) {
|
||||
if options.DeleteIncompleteFiles {
|
||||
cleanupIncompleteDownload(outputPath)
|
||||
}
|
||||
return lastErr
|
||||
}
|
||||
if options.DeleteIncompleteFiles {
|
||||
cleanupIncompleteDownload(outputPath)
|
||||
}
|
||||
if attempt < totalAttempts {
|
||||
if err := waitForRetry(ctx, attempt); err != nil {
|
||||
if options.DeleteIncompleteFiles {
|
||||
cleanupIncompleteDownload(outputPath)
|
||||
}
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return lastErr
|
||||
}
|
||||
|
||||
func writeTextFileWithOptions(outputPath string, content string, options DownloadOptions) error {
|
||||
keepPartialOnFailure := !options.DeleteIncompleteFiles
|
||||
if err := writeFileAtomically(outputPath, []byte(content), !options.SkipExistingFiles, keepPartialOnFailure); err != nil {
|
||||
if options.DeleteIncompleteFiles {
|
||||
cleanupIncompleteDownload(outputPath)
|
||||
}
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type ProgressCallback func(current, total int)
|
||||
|
||||
type ItemStatusCallback func(tweetID int64, index int, status string) // status: "success", "failed", "skipped"
|
||||
@@ -71,10 +245,11 @@ type downloadTask struct {
|
||||
index int
|
||||
}
|
||||
|
||||
func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir string, username string, progress ProgressCallback, itemStatus ItemStatusCallback, ctx context.Context, customProxy string) (downloaded int, skipped int, failed int, err error) {
|
||||
func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir string, username string, progress ProgressCallback, itemStatus ItemStatusCallback, ctx context.Context, options DownloadOptions, customProxy string) (downloaded int, skipped int, failed int, err error) {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
options = NormalizeDownloadOptions(options)
|
||||
|
||||
total := len(items)
|
||||
if total == 0 {
|
||||
@@ -144,7 +319,7 @@ func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir str
|
||||
taskChan := make(chan downloadTask, len(tasks))
|
||||
var wg sync.WaitGroup
|
||||
|
||||
numWorkers := MaxConcurrentDownloads
|
||||
numWorkers := options.ConcurrentDownloads
|
||||
if numWorkers > len(tasks) {
|
||||
numWorkers = len(tasks)
|
||||
}
|
||||
@@ -167,14 +342,6 @@ func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir str
|
||||
client := sharedClient
|
||||
|
||||
for task := range taskChan {
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
default:
|
||||
}
|
||||
|
||||
var status string
|
||||
markCompleted := func() {
|
||||
completed := atomic.AddInt64(&completedCount, 1)
|
||||
if progress != nil {
|
||||
@@ -182,25 +349,54 @@ func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir str
|
||||
}
|
||||
}
|
||||
|
||||
if _, err := os.Stat(task.outputPath); err == nil {
|
||||
status = "skipped"
|
||||
|
||||
if ctx.Err() != nil {
|
||||
if itemStatus != nil {
|
||||
itemStatus(task.item.TweetID, task.index, status)
|
||||
itemStatus(task.item.TweetID, task.index, "cancelled")
|
||||
}
|
||||
atomic.AddInt64(&skippedCount, 1)
|
||||
markCompleted()
|
||||
continue
|
||||
} else if task.item.Type == "text" {
|
||||
}
|
||||
|
||||
if err := os.WriteFile(task.outputPath, []byte(task.item.Content), 0644); err != nil {
|
||||
var status string
|
||||
|
||||
if options.SkipExistingFiles {
|
||||
exists, err := fileExists(task.outputPath)
|
||||
if err == nil && exists {
|
||||
status = "skipped"
|
||||
|
||||
if itemStatus != nil {
|
||||
itemStatus(task.item.TweetID, task.index, status)
|
||||
}
|
||||
atomic.AddInt64(&skippedCount, 1)
|
||||
markCompleted()
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
if task.item.Type == "text" {
|
||||
if ctx.Err() != nil {
|
||||
if itemStatus != nil {
|
||||
itemStatus(task.item.TweetID, task.index, "cancelled")
|
||||
}
|
||||
markCompleted()
|
||||
continue
|
||||
}
|
||||
|
||||
if err := writeTextFileWithOptions(task.outputPath, task.item.Content, options); 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 {
|
||||
} else if err := downloadFileWithRetry(ctx, client, task.item.URL, task.outputPath, options); err != nil {
|
||||
if ctx.Err() != nil || errors.Is(err, context.Canceled) {
|
||||
if itemStatus != nil {
|
||||
itemStatus(task.item.TweetID, task.index, "cancelled")
|
||||
}
|
||||
markCompleted()
|
||||
continue
|
||||
}
|
||||
atomic.AddInt64(&failedCount, 1)
|
||||
status = "failed"
|
||||
} else {
|
||||
@@ -209,8 +405,10 @@ func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir str
|
||||
|
||||
originalFilename := ExtractOriginalFilename(task.item.URL)
|
||||
|
||||
if err := EmbedMetadata(task.outputPath, task.item.Content, tweetURL, originalFilename); err != nil {
|
||||
if ctx.Err() == nil {
|
||||
if err := EmbedMetadata(ctx, task.outputPath, task.item.Content, tweetURL, originalFilename); err != nil && !errors.Is(err, context.Canceled) {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
atomic.AddInt64(&downloadedCount, 1)
|
||||
@@ -231,7 +429,7 @@ func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir str
|
||||
case <-ctx.Done():
|
||||
close(taskChan)
|
||||
wg.Wait()
|
||||
return int(downloadedCount), int(skippedCount), int(failedCount) + (total - int(completedCount)), ctx.Err()
|
||||
return int(downloadedCount), int(skippedCount), int(failedCount), ctx.Err()
|
||||
case taskChan <- task:
|
||||
}
|
||||
}
|
||||
@@ -239,10 +437,14 @@ func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir str
|
||||
|
||||
wg.Wait()
|
||||
|
||||
if err := ctx.Err(); err != nil {
|
||||
return int(downloadedCount), int(skippedCount), int(failedCount), err
|
||||
}
|
||||
|
||||
return int(downloadedCount), int(skippedCount), int(failedCount), nil
|
||||
}
|
||||
|
||||
func downloadFileWithContext(ctx context.Context, client *http.Client, url, outputPath string) error {
|
||||
func downloadFileWithContext(ctx context.Context, client *http.Client, url, outputPath string, allowOverwrite bool, keepPartialOnFailure bool) error {
|
||||
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -258,14 +460,41 @@ func downloadFileWithContext(ctx context.Context, client *http.Client, url, outp
|
||||
return fmt.Errorf("bad status: %s", resp.Status)
|
||||
}
|
||||
|
||||
out, err := os.Create(outputPath)
|
||||
out, err := os.CreateTemp(filepath.Dir(outputPath), filepath.Base(outputPath)+".*.part")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer out.Close()
|
||||
tempPath := out.Name()
|
||||
cleanupTemp := !keepPartialOnFailure
|
||||
defer func() {
|
||||
if out != nil {
|
||||
_ = out.Close()
|
||||
}
|
||||
if cleanupTemp {
|
||||
_ = os.Remove(tempPath)
|
||||
}
|
||||
}()
|
||||
|
||||
_, err = io.Copy(out, resp.Body)
|
||||
return err
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := out.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
out = nil
|
||||
|
||||
if ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
|
||||
if err := replaceFile(tempPath, outputPath, allowOverwrite); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
cleanupTemp = false
|
||||
return nil
|
||||
}
|
||||
|
||||
func formatTimestamp(dateStr string) string {
|
||||
@@ -354,22 +583,9 @@ func extractFilename(mediaURL string) string {
|
||||
}
|
||||
|
||||
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
|
||||
return downloadFileWithRetry(context.Background(), client, url, outputPath, DownloadOptions{
|
||||
SkipExistingFiles: false,
|
||||
DeleteIncompleteFiles: true,
|
||||
RetryAttempts: 0,
|
||||
})
|
||||
}
|
||||
@@ -469,6 +469,10 @@ func extractExifToolFromZip(zipPath, destPath string) error {
|
||||
}
|
||||
|
||||
libDir := filepath.Join(filepath.Dir(destPath), "exiftool_files")
|
||||
libDirAbs, err := filepath.Abs(libDir)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to resolve libDir: %v", err)
|
||||
}
|
||||
for _, f := range r.File {
|
||||
if strings.Contains(f.Name, "exiftool_files") && !strings.HasSuffix(f.Name, "/") {
|
||||
parts := strings.Split(f.Name, "exiftool_files/")
|
||||
@@ -482,6 +486,14 @@ func extractExifToolFromZip(zipPath, destPath string) error {
|
||||
|
||||
targetPath := filepath.Join(libDir, relPath)
|
||||
|
||||
targetAbs, err := filepath.Abs(targetPath)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if !strings.HasPrefix(targetAbs+string(os.PathSeparator), libDirAbs+string(os.PathSeparator)) && targetAbs != libDirAbs {
|
||||
continue
|
||||
}
|
||||
|
||||
if err := os.MkdirAll(filepath.Dir(targetPath), 0755); err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
+9
-2
@@ -11,12 +11,19 @@ import (
|
||||
)
|
||||
|
||||
func OpenFolderInExplorer(path string) error {
|
||||
info, err := os.Stat(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !info.IsDir() {
|
||||
return os.ErrInvalid
|
||||
}
|
||||
|
||||
var cmd *exec.Cmd
|
||||
|
||||
switch runtime.GOOS {
|
||||
case "windows":
|
||||
|
||||
cmd = exec.Command("cmd", "/c", "start", "", path)
|
||||
cmd = exec.Command("explorer", path)
|
||||
case "darwin":
|
||||
cmd = exec.Command("open", path)
|
||||
case "linux":
|
||||
|
||||
+34
-14
@@ -1,6 +1,7 @@
|
||||
package backend
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"os"
|
||||
@@ -11,6 +12,11 @@ import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
var (
|
||||
filenameSafeRegex = regexp.MustCompile(`^[A-Za-z0-9_]+$`)
|
||||
filenameLetterRegex = regexp.MustCompile(`[A-Za-z]`)
|
||||
)
|
||||
|
||||
func ExtractOriginalFilename(mediaURL string) string {
|
||||
parsedURL, err := url.Parse(mediaURL)
|
||||
if err != nil {
|
||||
@@ -29,7 +35,7 @@ func ExtractOriginalFilename(mediaURL string) string {
|
||||
filename = filename[:idx]
|
||||
}
|
||||
|
||||
if matched, _ := regexp.MatchString(`^[A-Za-z0-9_]+$`, filename); matched && len(filename) > 0 {
|
||||
if filenameSafeRegex.MatchString(filename) && len(filename) > 0 {
|
||||
return filename
|
||||
}
|
||||
}
|
||||
@@ -44,7 +50,7 @@ func ExtractOriginalFilename(mediaURL string) string {
|
||||
filename = filename[:idx]
|
||||
}
|
||||
|
||||
if matched, _ := regexp.MatchString(`^[A-Za-z0-9_]+$`, filename); matched && len(filename) > 0 {
|
||||
if filenameSafeRegex.MatchString(filename) && len(filename) > 0 {
|
||||
return filename
|
||||
}
|
||||
}
|
||||
@@ -58,9 +64,8 @@ func ExtractOriginalFilename(mediaURL string) string {
|
||||
filename = filename[:idx]
|
||||
}
|
||||
|
||||
if matched, _ := regexp.MatchString(`^[A-Za-z0-9_]+$`, filename); matched {
|
||||
hasLetter, _ := regexp.MatchString(`[A-Za-z]`, filename)
|
||||
if hasLetter && len(filename) >= 8 {
|
||||
if filenameSafeRegex.MatchString(filename) {
|
||||
if filenameLetterRegex.MatchString(filename) && len(filename) >= 8 {
|
||||
return filename
|
||||
}
|
||||
}
|
||||
@@ -70,21 +75,24 @@ func ExtractOriginalFilename(mediaURL string) string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func EmbedMetadata(filePath string, tweetContent string, tweetURL string, originalFilename string) error {
|
||||
func EmbedMetadata(ctx context.Context, filePath string, tweetContent string, tweetURL string, originalFilename string) error {
|
||||
ext := strings.ToLower(filepath.Ext(filePath))
|
||||
|
||||
switch ext {
|
||||
case ".jpg", ".jpeg":
|
||||
return embedImageMetadata(filePath, tweetContent, tweetURL, originalFilename)
|
||||
return embedImageMetadata(ctx, filePath, tweetContent, tweetURL, originalFilename)
|
||||
case ".mp4":
|
||||
return embedVideoMetadata(filePath, tweetContent, tweetURL, originalFilename)
|
||||
return embedVideoMetadata(ctx, filePath, tweetContent, tweetURL, originalFilename)
|
||||
default:
|
||||
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func embedImageMetadata(filePath string, tweetContent string, tweetURL string, originalFilename string) error {
|
||||
func embedImageMetadata(ctx context.Context, filePath string, tweetContent string, tweetURL string, originalFilename string) error {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
|
||||
exiftoolPath := findExifTool()
|
||||
if exiftoolPath == "" {
|
||||
@@ -100,10 +108,13 @@ func embedImageMetadata(filePath string, tweetContent string, tweetURL string, o
|
||||
filePath,
|
||||
}
|
||||
|
||||
cmd := exec.Command(exiftoolPath, args...)
|
||||
cmd := exec.CommandContext(ctx, exiftoolPath, args...)
|
||||
hideWindow(cmd)
|
||||
output, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
if ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
|
||||
return fmt.Errorf("exiftool error (non-fatal): %v, output: %s", err, string(output))
|
||||
}
|
||||
@@ -112,7 +123,10 @@ func embedImageMetadata(filePath string, tweetContent string, tweetURL string, o
|
||||
return nil
|
||||
}
|
||||
|
||||
func embedVideoMetadata(filePath string, tweetContent string, tweetURL string, originalFilename string) error {
|
||||
func embedVideoMetadata(ctx context.Context, filePath string, tweetContent string, tweetURL string, originalFilename string) error {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
|
||||
exiftoolPath := findExifTool()
|
||||
if exiftoolPath == "" {
|
||||
@@ -120,10 +134,13 @@ func embedVideoMetadata(filePath string, tweetContent string, tweetURL string, o
|
||||
return nil
|
||||
}
|
||||
|
||||
return embedVideoMetadataWithExifTool(exiftoolPath, filePath, tweetContent, tweetURL, originalFilename)
|
||||
return embedVideoMetadataWithExifTool(ctx, exiftoolPath, filePath, tweetContent, tweetURL, originalFilename)
|
||||
}
|
||||
|
||||
func embedVideoMetadataWithExifTool(exiftoolPath string, filePath string, tweetContent string, tweetURL string, originalFilename string) error {
|
||||
func embedVideoMetadataWithExifTool(ctx context.Context, exiftoolPath string, filePath string, tweetContent string, tweetURL string, originalFilename string) error {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
|
||||
metadataComment := buildMetadataComment(tweetContent, tweetURL, originalFilename)
|
||||
|
||||
@@ -133,10 +150,13 @@ func embedVideoMetadataWithExifTool(exiftoolPath string, filePath string, tweetC
|
||||
filePath,
|
||||
}
|
||||
|
||||
cmd := exec.Command(exiftoolPath, args...)
|
||||
cmd := exec.CommandContext(ctx, exiftoolPath, args...)
|
||||
hideWindow(cmd)
|
||||
output, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
if ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
|
||||
return fmt.Errorf("exiftool error (non-fatal): %v, output: %s", err, string(output))
|
||||
}
|
||||
|
||||
+7
-1
@@ -82,7 +82,7 @@ func KillAllExtractorProcesses() {
|
||||
|
||||
for _, cmd := range commands {
|
||||
if cmd != nil && cmd.Process != nil {
|
||||
_ = cmd.Process.Kill()
|
||||
_ = terminateCommandProcess(cmd)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -548,6 +548,9 @@ func ExtractTimeline(req TimelineRequest) (*TwitterResponse, error) {
|
||||
|
||||
if err != nil {
|
||||
outputStr := string(output)
|
||||
if strings.TrimSpace(outputStr) == "" {
|
||||
return nil, fmt.Errorf("xtractor process terminated before returning data")
|
||||
}
|
||||
errorMsg := parseExtractorError(outputStr, req.Username)
|
||||
return nil, fmt.Errorf("%s", errorMsg)
|
||||
}
|
||||
@@ -731,6 +734,9 @@ func ExtractDateRange(req DateRangeRequest) (*TwitterResponse, error) {
|
||||
|
||||
if err != nil {
|
||||
outputStr := string(output)
|
||||
if strings.TrimSpace(outputStr) == "" {
|
||||
return nil, fmt.Errorf("xtractor process terminated before returning data")
|
||||
}
|
||||
errorMsg := parseExtractorError(outputStr, req.Username)
|
||||
return nil, fmt.Errorf("%s", errorMsg)
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user