Compare commits

...
8 Commits
Author SHA1 Message Date
afkarxyz 2ada5da9bf v4.9 2026-07-16 18:27:23 +07:00
afkarxyz 3fb8bda2ff Update README 2026-07-15 12:26:49 +07:00
asdfghjkkly b4dfb75f5b Fix group editing and skip existing downloads (#105) 2026-07-12 10:59:29 +07:00
afkarxyz 7e584aff2c Update README 2026-07-12 10:58:42 +07:00
afkarxyz 76acb6f5e1 v4.8 2026-07-05 19:09:54 +07:00
afkarxyz 6bd03678f8 Merge pull request #103 from asdfghjkkly/fix-windows-folder-and-reposts
Fix repost folder routing and Windows folder opening
2026-07-05 17:00:37 +07:00
asdfghjkkly e400df6ea7 Fix repost folder routing and Windows folder opening 2026-07-05 05:41:36 -04:00
afkarxyz 52ffa5ba17 Update README 2026-06-22 14:31:56 +07:00
22 changed files with 651 additions and 452 deletions

No files matched your search

+25 -10
View File
@@ -1,20 +1,35 @@
# Twitter/X Media Batch Downloader <div align="left">
<h1>Twitter/X Media Batch Downloader</h1>
A GUI tool to download original-quality images and videos from Twitter/X accounts. <p>
Downloads original-quality images and videos from Twitter/X accounts.
![Windows](https://img.shields.io/badge/Windows-10%2B-0078D6?style=for-the-badge&logo=data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI1MTIiIGhlaWdodD0iNTEyIiB2aWV3Qm94PSIwIDAgMjAgMjAiPjxwYXRoIGZpbGw9IiNmZmZmZmYiIGZpbGwtcnVsZT0iZXZlbm9kZCIgZD0iTTIwIDEwLjg3M1YyMEw4LjQ3OSAxOC41MzdsLjAwMS03LjY2NEgyMFptLTEzLjEyIDBsLS4wMDEgNy40NjFMMCAxNy40NjF2LTYuNTg4aDYuODhaTTIwIDkuMjczSDguNDhsLS4wMDEtNy44MUwyMCAwdjkuMjczWk02Ljg3OSAxLjY2NmwuMDAxIDcuNjA3SDBWMi41MzlsNi44NzktLjg3M1oiLz48L3N2Zz4=) </p>
![macOS](https://img.shields.io/badge/macOS-10.13%2B-000000?style=for-the-badge&logo=apple&logoColor=white) <p>
![Linux](https://img.shields.io/badge/Linux-Any-FCC624?style=for-the-badge&logo=linux&logoColor=white) <a href="https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/stargazers"><img
src="https://img.shields.io/github/stars/afkarxyz/Twitter-X-Media-Batch-Downloader?color=ffcb47&labelColor=black&logo=github&label=Stars" /></a><a
href="https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases"><img
src="https://img.shields.io/github/downloads/afkarxyz/Twitter-X-Media-Batch-Downloader/total?color=22c55e&labelColor=black&logo=github&label=Downloads" /></a><a
href="https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases/latest"><img
src="https://img.shields.io/github/v/release/afkarxyz/Twitter-X-Media-Batch-Downloader?color=8b5cf6&labelColor=black&logo=github&label=Latest%20Release" /></a><a
href="https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases/latest"><img
src="https://img.shields.io/badge/Windows-10%2B-369eff?labelColor=black&logo=data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI1MTIiIGhlaWdodD0iNTEyIiB2aWV3Qm94PSIwIDAgMjAgMjAiPjxwYXRoIGZpbGw9IiNmZmZmZmYiIGZpbGwtcnVsZT0iZXZlbm9kZCIgZD0iTTIwIDEwLjg3M1YyMEw4LjQ3OSAxOC41MzdsLjAwMS03LjY2NEgyMFptLTEzLjEyIDBsLS4wMDEgNy40NjFMMCAxNy40NjF2LTYuNTg4aDYuODhaTTIwIDkuMjczSDguNDhsLS4wMDEtNy44MUwyMCAwdjkuMjczWk02Ljg3OSAxLjY2NmwuMDAxIDcuNjA3SDBWMi41MzlsNi44NzktLjg3M1oiLz48L3N2Zz4=" /></a><a
href="https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases/latest"><img
src="https://img.shields.io/badge/macOS-10.13%2B-FFFFFF?labelColor=black&logo=apple&logoColor=white" /></a><a
href="https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases/latest"><img
src="https://img.shields.io/badge/Linux-Any-FCC624?labelColor=black&logo=linux&logoColor=white" /></a>
<br />
<br />
<a href="https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases/latest" target="_blank"><img
src="https://github.com/user-attachments/assets/cef7b7e6-5a64-497a-91fe-b6fb549f3b09" alt="Twitter/X Media Batch Downloader" /></a>
</p>
</div>
### [Download](https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases) ### [Download](https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases)
![Image](https://github.com/user-attachments/assets/324243e4-b64b-4ea2-9f3d-8b08575a138e)
- If you're familiar with userscripts, install it [**here**](https://greasyfork.org/en/scripts/523157) - If you're familiar with userscripts, install it [**here**](https://greasyfork.org/en/scripts/523157)
- To install the Chrome extension version, click [**here**](https://chromewebstore.google.com/detail/cboceolmgkoobpfjiojkigmihijfgmdo) - To install the Chrome extension version, click [**here**](https://chromewebstore.google.com/detail/cboceolmgkoobpfjiojkigmihijfgmdo)
- Also available on the web at [**MediaBatchDL.com**](https://mediabatchdl.com) - Also available on the web at [**TwitterDL.app**](https://twitterdl.app)
## How to Obtain Auth Token ## How to Obtain Auth Token
+9 -1
View File
@@ -243,6 +243,7 @@ type MediaItemRequest struct {
Content string `json:"content,omitempty"` Content string `json:"content,omitempty"`
OriginalFilename string `json:"original_filename,omitempty"` OriginalFilename string `json:"original_filename,omitempty"`
AuthorUsername string `json:"author_username,omitempty"` AuthorUsername string `json:"author_username,omitempty"`
AccountName string `json:"account_name,omitempty"`
} }
type DownloadMediaWithMetadataRequest struct { type DownloadMediaWithMetadataRequest struct {
@@ -256,6 +257,9 @@ type DownloadMediaWithMetadataRequest struct {
Proxy string `json:"proxy,omitempty"` Proxy string `json:"proxy,omitempty"`
FilenameTemplate string `json:"filename_template,omitempty"` FilenameTemplate string `json:"filename_template,omitempty"`
FolderTemplate string `json:"folder_template,omitempty"` FolderTemplate string `json:"folder_template,omitempty"`
AutoConvertGIFs bool `json:"auto_convert_gifs,omitempty"`
GIFQuality string `json:"gif_quality,omitempty"`
GIFResolution string `json:"gif_resolution,omitempty"`
} }
type DownloadMediaResponse struct { type DownloadMediaResponse struct {
@@ -350,7 +354,7 @@ func (a *App) DownloadMediaWithMetadata(req DownloadMediaWithMetadataRequest) (D
} }
username := req.Username username := req.Username
if item.AuthorUsername != "" { if (req.Username == "bookmarks" || req.Username == "likes") && item.AuthorUsername != "" {
username = item.AuthorUsername username = item.AuthorUsername
} }
@@ -360,6 +364,7 @@ func (a *App) DownloadMediaWithMetadata(req DownloadMediaWithMetadataRequest) (D
TweetID: int64(item.TweetID), TweetID: int64(item.TweetID),
Type: item.Type, Type: item.Type,
Username: username, Username: username,
AccountName: item.AccountName,
Content: item.Content, Content: item.Content,
OriginalFilename: originalFilename, OriginalFilename: originalFilename,
} }
@@ -402,6 +407,9 @@ func (a *App) DownloadMediaWithMetadata(req DownloadMediaWithMetadataRequest) (D
RetryAttempts: req.RetryAttempts, RetryAttempts: req.RetryAttempts,
FilenameTemplate: req.FilenameTemplate, FilenameTemplate: req.FilenameTemplate,
FolderTemplate: req.FolderTemplate, FolderTemplate: req.FolderTemplate,
AutoConvertGIFs: req.AutoConvertGIFs,
GIFQuality: req.GIFQuality,
GIFResolution: req.GIFResolution,
} }
downloaded, skipped, failed, err := backend.DownloadMediaWithMetadataProgressAndStatus( downloaded, skipped, failed, err := backend.DownloadMediaWithMetadataProgressAndStatus(
+143 -18
View File
@@ -49,6 +49,9 @@ type DownloadOptions struct {
RetryAttempts int RetryAttempts int
FilenameTemplate string FilenameTemplate string
FolderTemplate string FolderTemplate string
AutoConvertGIFs bool
GIFQuality string
GIFResolution string
} }
func NormalizeDownloadOptions(options DownloadOptions) DownloadOptions { func NormalizeDownloadOptions(options DownloadOptions) DownloadOptions {
@@ -63,6 +66,7 @@ type MediaItem struct {
TweetID int64 `json:"tweet_id"` TweetID int64 `json:"tweet_id"`
Type string `json:"type"` Type string `json:"type"`
Username string `json:"username"` Username string `json:"username"`
AccountName string `json:"account_name,omitempty"`
Content string `json:"content,omitempty"` Content string `json:"content,omitempty"`
OriginalFilename string `json:"original_filename,omitempty"` OriginalFilename string `json:"original_filename,omitempty"`
} }
@@ -247,6 +251,13 @@ type downloadTask struct {
index int index int
} }
type pendingDownloadTask struct {
task downloadTask
typeDir string
baseName string
ext string
}
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) { 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 { if ctx == nil {
ctx = context.Background() ctx = context.Background()
@@ -259,7 +270,8 @@ func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir str
} }
tweetMediaCount := make(map[string]map[int64]int) tweetMediaCount := make(map[string]map[int64]int)
tasks := make([]downloadTask, 0, total) pendingTasks := make([]pendingDownloadTask, 0, total)
filenameCounts := make(map[string]int)
downloadDate := time.Now().Format("20060102") downloadDate := time.Now().Format("20060102")
for i, item := range items { for i, item := range items {
@@ -268,6 +280,10 @@ func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir str
if itemUsername == "" { if itemUsername == "" {
itemUsername = username itemUsername = username
} }
itemAccountName := item.AccountName
if itemAccountName == "" {
itemAccountName = itemUsername
}
if tweetMediaCount[itemUsername] == nil { if tweetMediaCount[itemUsername] == nil {
tweetMediaCount[itemUsername] = make(map[int64]int) tweetMediaCount[itemUsername] = make(map[int64]int)
@@ -287,7 +303,7 @@ func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir str
subfolder = "other" subfolder = "other"
} }
baseDir := filepath.Join(outputDir, renderFolder(options.FolderTemplate, itemUsername, downloadDate)) baseDir := filepath.Join(outputDir, renderFolder(options.FolderTemplate, itemUsername, itemAccountName, downloadDate))
if err := os.MkdirAll(baseDir, 0755); err != nil { if err := os.MkdirAll(baseDir, 0755); err != nil {
continue continue
} }
@@ -309,20 +325,53 @@ func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir str
mediaID = ExtractOriginalFilename(item.URL) mediaID = ExtractOriginalFilename(item.URL)
} }
filename := renderFilename(options.FilenameTemplate, itemUsername, timestamp, item.TweetID, item.Type, mediaIndex, mediaID) + ext baseName := renderFilename(options.FilenameTemplate, itemUsername, itemAccountName, timestamp, item.TweetID, item.Type, mediaIndex, mediaID)
outputPath := filepath.Join(typeDir, filename) filenameCounts[filenameCollisionKey(typeDir, baseName, ext)]++
tasks = append(tasks, downloadTask{ pendingTasks = append(pendingTasks, pendingDownloadTask{
item: item, task: downloadTask{
outputPath: outputPath, item: item,
index: i, index: i,
},
typeDir: typeDir,
baseName: baseName,
ext: ext,
}) })
} }
filenameIndexes := make(map[string]int, len(filenameCounts))
tasks := make([]downloadTask, 0, len(pendingTasks))
for _, pending := range pendingTasks {
key := filenameCollisionKey(pending.typeDir, pending.baseName, pending.ext)
filenameIndexes[key]++
filename := formatDownloadFilename(
pending.baseName,
pending.ext,
filenameCounts[key],
filenameIndexes[key],
)
if options.SkipExistingFiles {
canonicalPath := filepath.Join(pending.typeDir, formatDownloadFilename(pending.baseName, pending.ext, 1, 1))
if exists, err := fileExists(canonicalPath); err == nil && exists {
pending.task.outputPath = canonicalPath
tasks = append(tasks, pending.task)
continue
}
}
pending.task.outputPath = filepath.Join(pending.typeDir, filename)
tasks = append(tasks, pending.task)
}
var downloadedCount int64 var downloadedCount int64
var skippedCount int64 var skippedCount int64
var failedCount int64 var failedCount int64
var completedCount int64 var completedCount int64
var conversionWG sync.WaitGroup
taskChan := make(chan downloadTask, len(tasks)) taskChan := make(chan downloadTask, len(tasks))
var wg sync.WaitGroup var wg sync.WaitGroup
@@ -421,6 +470,15 @@ func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir str
atomic.AddInt64(&downloadedCount, 1) atomic.AddInt64(&downloadedCount, 1)
status = "success" status = "success"
if shouldAutoConvertGIF(task.item.Type, options) && ctx.Err() == nil {
conversionWG.Add(1)
go func(inputPath string) {
defer conversionWG.Done()
outputPath := strings.TrimSuffix(inputPath, filepath.Ext(inputPath)) + ".gif"
_ = ConvertMP4ToGIFWithContext(ctx, inputPath, outputPath, normalizeGIFQuality(options.GIFQuality), normalizeGIFResolution(options.GIFResolution))
}(task.outputPath)
}
} }
if itemStatus != nil { if itemStatus != nil {
@@ -444,6 +502,7 @@ func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir str
close(taskChan) close(taskChan)
wg.Wait() wg.Wait()
conversionWG.Wait()
if err := ctx.Err(); err != nil { if err := ctx.Err(); err != nil {
return int(downloadedCount), int(skippedCount), int(failedCount), err return int(downloadedCount), int(skippedCount), int(failedCount), err
@@ -452,6 +511,34 @@ func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir str
return int(downloadedCount), int(skippedCount), int(failedCount), nil return int(downloadedCount), int(skippedCount), int(failedCount), nil
} }
func shouldAutoConvertGIF(mediaType string, options DownloadOptions) bool {
if !options.AutoConvertGIFs || !IsFFmpegInstalled() {
return false
}
switch mediaType {
case "gif", "animated_gif":
return true
default:
return false
}
}
func normalizeGIFQuality(quality string) string {
if quality == "better" {
return quality
}
return "fast"
}
func normalizeGIFResolution(resolution string) string {
switch resolution {
case "original", "high", "medium", "low":
return resolution
default:
return "original"
}
}
func downloadFileWithContext(ctx context.Context, client *http.Client, url, outputPath string, allowOverwrite bool, keepPartialOnFailure bool) 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) req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
if err != nil { if err != nil {
@@ -527,12 +614,15 @@ func formatTimestamp(dateStr string) string {
return "00000000_000000" return "00000000_000000"
} }
func renderFilename(template, username, timestamp string, tweetID int64, mediaType string, index int, mediaID string) string { func renderFilename(template, username, accountName, timestamp string, tweetID int64, mediaType string, index int, mediaID string) string {
if strings.TrimSpace(template) == "" { if strings.TrimSpace(template) == "" {
template = "{username}_{date}_{tweet_id}_{index}" template = "{handle}_{date}_{tweet_id}"
} }
replacer := strings.NewReplacer( replacer := strings.NewReplacer(
"{handle}", sanitizeFilenamePart(username),
"{name}", sanitizeFilenamePart(accountName),
"{username}", sanitizeFilenamePart(username), "{username}", sanitizeFilenamePart(username),
"{account_name}", sanitizeFilenamePart(accountName),
"{date}", timestamp, "{date}", timestamp,
"{tweet_id}", fmt.Sprintf("%d", tweetID), "{tweet_id}", fmt.Sprintf("%d", tweetID),
"{index}", fmt.Sprintf("%02d", index), "{index}", fmt.Sprintf("%02d", index),
@@ -540,25 +630,37 @@ func renderFilename(template, username, timestamp string, tweetID int64, mediaTy
"{type}", sanitizeFilenamePart(mediaType), "{type}", sanitizeFilenamePart(mediaType),
) )
name := strings.TrimSpace(replacer.Replace(template)) name := strings.TrimSpace(replacer.Replace(template))
name = sanitizeFilenamePart(name)
if name == "" { if name == "" {
name = fmt.Sprintf("%s_%s_%d_%02d", username, timestamp, tweetID, index) name = sanitizeFilenamePart(fmt.Sprintf("%s_%s_%d", username, timestamp, tweetID))
}
if mediaID != "" && !strings.Contains(template, "{media_id}") {
name = name + "_" + sanitizeFilenamePart(mediaID)
} }
return name return name
} }
func renderFolder(template, username, date string) string { func filenameCollisionKey(dir, baseName, ext string) string {
return dir + "\x00" + baseName + ext
}
func formatDownloadFilename(baseName, ext string, duplicateCount, duplicateIndex int) string {
if duplicateCount > 1 {
return fmt.Sprintf("%s_%02d%s", baseName, duplicateIndex, ext)
}
return baseName + ext
}
func renderFolder(template, username, accountName, date string) string {
if strings.TrimSpace(template) == "" { if strings.TrimSpace(template) == "" {
template = "{username}" template = "{handle}"
} }
replacer := strings.NewReplacer( replacer := strings.NewReplacer(
"{handle}", sanitizeFilenamePart(username),
"{name}", sanitizeFilenamePart(accountName),
"{username}", sanitizeFilenamePart(username), "{username}", sanitizeFilenamePart(username),
"{account_name}", sanitizeFilenamePart(accountName),
"{date}", date, "{date}", date,
) )
name := strings.TrimSpace(replacer.Replace(template)) name := strings.TrimSpace(replacer.Replace(template))
name = sanitizeFilenamePart(name)
if name == "" { if name == "" {
name = sanitizeFilenamePart(username) name = sanitizeFilenamePart(username)
} }
@@ -566,13 +668,36 @@ func renderFolder(template, username, date string) string {
} }
func sanitizeFilenamePart(s string) string { func sanitizeFilenamePart(s string) string {
return strings.TrimSpace(strings.Map(func(r rune) rune { cleaned := strings.TrimSpace(strings.Map(func(r rune) rune {
switch r { switch r {
case '\\', '/', ':', '*', '?', '"', '<', '>', '|': case '\\', '/', ':', '*', '?', '"', '<', '>', '|':
return -1 return -1
} }
if r >= 0 && r < 32 {
return -1
}
return r return r
}, s)) }, s))
cleaned = strings.TrimRight(cleaned, ". ")
if isWindowsReservedName(cleaned) {
return cleaned + "_"
}
return cleaned
}
func isWindowsReservedName(name string) bool {
base := name
if dotIndex := strings.IndexByte(base, '.'); dotIndex >= 0 {
base = base[:dotIndex]
}
base = strings.ToUpper(strings.TrimSpace(base))
switch base {
case "CON", "PRN", "AUX", "NUL":
return true
}
return len(base) == 4 &&
((strings.HasPrefix(base, "COM") && base[3] >= '1' && base[3] <= '9') ||
(strings.HasPrefix(base, "LPT") && base[3] >= '1' && base[3] <= '9'))
} }
func getExtension(mediaURL string, mediaType string) string { func getExtension(mediaURL string, mediaType string) string {
+12 -1
View File
@@ -2,6 +2,7 @@ package backend
import ( import (
"archive/zip" "archive/zip"
"context"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io" "io"
@@ -531,11 +532,18 @@ func normalizeFFmpegVersion(version string) string {
} }
func ConvertMP4ToGIF(inputPath, outputPath, quality, resolution string) error { func ConvertMP4ToGIF(inputPath, outputPath, quality, resolution string) error {
return ConvertMP4ToGIFWithContext(context.Background(), inputPath, outputPath, quality, resolution)
}
func ConvertMP4ToGIFWithContext(ctx context.Context, inputPath, outputPath, quality, resolution string) error {
ffmpegPath := GetFFmpegPath() ffmpegPath := GetFFmpegPath()
if !IsFFmpegInstalled() { if !IsFFmpegInstalled() {
return fmt.Errorf("ffmpeg not installed") return fmt.Errorf("ffmpeg not installed")
} }
if ctx == nil {
ctx = context.Background()
}
var args []string var args []string
@@ -598,10 +606,13 @@ func ConvertMP4ToGIF(inputPath, outputPath, quality, resolution string) error {
} }
} }
cmd := exec.Command(ffmpegPath, args...) cmd := exec.CommandContext(ctx, ffmpegPath, args...)
hideWindow(cmd) hideWindow(cmd)
output, err := cmd.CombinedOutput() output, err := cmd.CombinedOutput()
if err != nil { if err != nil {
if ctx.Err() != nil {
return ctx.Err()
}
return fmt.Errorf("ffmpeg error: %v, output: %s", err, string(output)) return fmt.Errorf("ffmpeg error: %v, output: %s", err, string(output))
} }
+2 -1
View File
@@ -11,6 +11,7 @@ import (
) )
func OpenFolderInExplorer(path string) error { func OpenFolderInExplorer(path string) error {
os.WriteFile(filepath.Join(os.TempDir(), "openfolder.txt"), []byte(path), 0644)
info, err := os.Stat(path) info, err := os.Stat(path)
if err != nil { if err != nil {
return err return err
@@ -23,7 +24,7 @@ func OpenFolderInExplorer(path string) error {
switch runtime.GOOS { switch runtime.GOOS {
case "windows": case "windows":
cmd = exec.Command("explorer", path) cmd = exec.Command("cmd", "/C", "start", "", path)
case "darwin": case "darwin":
cmd = exec.Command("open", path) cmd = exec.Command("open", path)
case "linux": case "linux":
+5 -3
View File
@@ -272,6 +272,7 @@ type TimelineEntry struct {
Verified bool `json:"verified,omitempty"` Verified bool `json:"verified,omitempty"`
OriginalFilename string `json:"original_filename,omitempty"` OriginalFilename string `json:"original_filename,omitempty"`
AuthorUsername string `json:"author_username,omitempty"` AuthorUsername string `json:"author_username,omitempty"`
AuthorName string `json:"author_name,omitempty"`
} }
type AccountInfo struct { type AccountInfo struct {
@@ -575,6 +576,7 @@ func textEntry(t richTweet) TimelineEntry {
Source: t.Source, Source: t.Source,
Verified: isVerified(t.Author), Verified: isVerified(t.Author),
AuthorUsername: t.Author.Username, AuthorUsername: t.Author.Username,
AuthorName: t.Author.Name,
} }
} }
@@ -608,6 +610,7 @@ func mediaEntry(t richTweet, m richMedia, videoQuality, imageSize string) Timeli
Source: t.Source, Source: t.Source,
Verified: isVerified(t.Author), Verified: isVerified(t.Author),
AuthorUsername: t.Author.Username, AuthorUsername: t.Author.Username,
AuthorName: t.Author.Name,
} }
} }
@@ -695,11 +698,10 @@ func ExtractTimeline(req TimelineRequest) (*TwitterResponse, error) {
} }
includeText := req.IncludeText includeText := req.IncludeText
wantsRetweets := req.Retweets
timelineType := req.TimelineType timelineType := req.TimelineType
if timelineType == "" { if timelineType == "" {
if includeText || wantsRetweets { if includeText {
timelineType = "tweets" timelineType = "tweets"
} else { } else {
timelineType = "media" timelineType = "media"
@@ -722,7 +724,7 @@ func ExtractTimeline(req TimelineRequest) (*TwitterResponse, error) {
args = append(args, "--limit", fmt.Sprintf("%d", req.BatchSize)) args = append(args, "--limit", fmt.Sprintf("%d", req.BatchSize))
} }
if timelineType == "tweets" || timelineType == "timeline" { if timelineType == "tweets" || timelineType == "timeline" || timelineType == "media" {
if req.Retweets { if req.Retweets {
args = append(args, "--retweets", "include") args = append(args, "--retweets", "include")
} else { } else {
+1 -1
View File
@@ -1 +1 @@
66d76291490cdae022ca7ad778594a1f b9015b5860764ef52b634f74fd0f1180
+4 -1
View File
@@ -9,6 +9,7 @@ import { openExternal } from "@/lib/utils";
import { compareVersionNumbers } from "@/lib/version"; import { compareVersionNumbers } from "@/lib/version";
import { toastWithSound as toast } from "@/lib/toast-with-sound"; import { toastWithSound as toast } from "@/lib/toast-with-sound";
import { logger } from "@/lib/logger"; import { logger } from "@/lib/logger";
import { initDownloadProgressEvents } from "@/lib/download-state";
import { saveFetchState, getFetchState, clearFetchState, getResumableInfo, mergeTimelines, saveCursor, getCursor, clearCursor, type FetchState, } from "@/lib/fetch-state"; import { saveFetchState, getFetchState, clearFetchState, getResumableInfo, mergeTimelines, saveCursor, getCursor, clearCursor, type FetchState, } from "@/lib/fetch-state";
import { TitleBar } from "@/components/TitleBar"; import { TitleBar } from "@/components/TitleBar";
import { Sidebar, type PageType } from "@/components/Sidebar"; import { Sidebar, type PageType } from "@/components/Sidebar";
@@ -165,10 +166,12 @@ function App() {
} }
}; };
mediaQuery.addEventListener("change", handleChange); mediaQuery.addEventListener("change", handleChange);
const cleanupDownloadProgress = initDownloadProgressEvents();
checkForUpdates(); checkForUpdates();
loadHistory(); loadHistory();
return () => { return () => {
mediaQuery.removeEventListener("change", handleChange); mediaQuery.removeEventListener("change", handleChange);
cleanupDownloadProgress();
}; };
}, []); }, []);
useEffect(() => { useEffect(() => {
@@ -438,7 +441,7 @@ function App() {
} }
else { else {
const batchSize = BATCH_SIZE; const batchSize = BATCH_SIZE;
let timelineType = (settings.includeText || retweets) ? "tweets" : "media"; let timelineType = settings.includeText ? "tweets" : "media";
if (isBookmarks) { if (isBookmarks) {
timelineType = "bookmarks"; timelineType = "bookmarks";
} }
Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

+33 -17
View File
@@ -316,17 +316,24 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
toast.error("Failed to load account data"); toast.error("Failed to load account data");
} }
}; };
const handleOpenFolder = async (username: string) => { const handleOpenFolder = async (account: AccountListItem) => {
const settings = getSettings(); const settings = getSettings();
let folderName = username; const basePath = settings.downloadPath || "";
if (username === "bookmarks") { if (!basePath) {
folderName = "My Bookmarks"; toast.error("Download folder is not set");
return;
} }
else if (username === "likes") { let username = account.username || account.name || "";
folderName = "My Likes";
}
const folderPath = await GetFolderPath(settings.downloadPath, folderName);
try { try {
const responseJSON = await GetAccountFromDB(account.id);
const data = JSON.parse(responseJSON);
username = data.account_info?.name || username;
}
catch {
}
const folderName = getFolderNameForAccount(username);
try {
const folderPath = await GetFolderPath(basePath, folderName);
await OpenFolder(folderPath); await OpenFolder(folderPath);
} }
catch (error) { catch (error) {
@@ -1053,13 +1060,13 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
{formatNumberWithComma(account.total_media)} media {formatNumberWithComma(account.total_media)} media
</div> </div>
</div> </div>
<div className="flex gap-1"> <div className="flex gap-1" onClick={(e) => e.stopPropagation()}>
{downloadingAccountId === account.id ? (<Button variant="outline" size="icon" className="h-8 w-8" onClick={handleStopDownload}> {downloadingAccountId === account.id ? (<Button variant="outline" size="icon" className="h-8 w-8" onClick={handleStopDownload}>
<StopCircle className="h-4 w-4 text-destructive"/> <StopCircle className="h-4 w-4 text-destructive"/>
</Button>) : (<Button variant="default" size="icon" className="h-8 w-8" onClick={() => handleDownload(account.id, account.username)} disabled={isDownloading}> </Button>) : (<Button variant="default" size="icon" className="h-8 w-8" onClick={() => handleDownload(account.id, account.username)} disabled={isDownloading}>
<Download className="h-4 w-4"/> <Download className="h-4 w-4"/>
</Button>)} </Button>)}
<Button variant="outline" size="icon" className="h-8 w-8" onClick={() => handleOpenFolder(account.username)} disabled={!folderExistence.get(account.id)}> <Button variant="outline" size="icon" className="h-8 w-8" onClick={() => handleOpenFolder(account)} disabled={!folderExistence.get(account.id)}>
<FolderOpen className="h-4 w-4"/> <FolderOpen className="h-4 w-4"/>
</Button> </Button>
<DropdownMenu> <DropdownMenu>
@@ -1069,7 +1076,10 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
</Button> </Button>
</DropdownMenuTrigger> </DropdownMenuTrigger>
<DropdownMenuContent align="end"> <DropdownMenuContent align="end">
{!isPrivateAccount(account.username) && (<DropdownMenuItem onClick={() => handleEditGroup(account)}> {!isPrivateAccount(account.username) && (<DropdownMenuItem onSelect={(event) => {
event.preventDefault();
handleEditGroup(account);
}}>
<Pencil className="h-4 w-4 mr-2"/> <Pencil className="h-4 w-4 mr-2"/>
Edit Group Edit Group
</DropdownMenuItem>)} </DropdownMenuItem>)}
@@ -1147,13 +1157,13 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
{formatNumberWithComma(account.total_media)} media {formatNumberWithComma(account.total_media)} media
</div> </div>
</div> </div>
<div className="flex gap-1"> <div className="flex gap-1" onClick={(e) => e.stopPropagation()}>
{downloadingAccountId === account.id ? (<Button variant="outline" size="icon" className="h-7 w-7" onClick={handleStopDownload}> {downloadingAccountId === account.id ? (<Button variant="outline" size="icon" className="h-7 w-7" onClick={handleStopDownload}>
<StopCircle className="h-3 w-3 text-destructive"/> <StopCircle className="h-3 w-3 text-destructive"/>
</Button>) : (<Button variant="default" size="icon" className="h-7 w-7" onClick={() => handleDownload(account.id, account.username)} disabled={isDownloading}> </Button>) : (<Button variant="default" size="icon" className="h-7 w-7" onClick={() => handleDownload(account.id, account.username)} disabled={isDownloading}>
<Download className="h-3 w-3"/> <Download className="h-3 w-3"/>
</Button>)} </Button>)}
<Button variant="outline" size="icon" className="h-7 w-7" onClick={() => handleOpenFolder(account.username)} disabled={!folderExistence.get(account.id)}> <Button variant="outline" size="icon" className="h-7 w-7" onClick={() => handleOpenFolder(account)} disabled={!folderExistence.get(account.id)}>
<FolderOpen className="h-3 w-3"/> <FolderOpen className="h-3 w-3"/>
</Button> </Button>
<DropdownMenu> <DropdownMenu>
@@ -1163,7 +1173,10 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
</Button> </Button>
</DropdownMenuTrigger> </DropdownMenuTrigger>
<DropdownMenuContent align="end"> <DropdownMenuContent align="end">
{!isPrivateAccount(account.username) && (<DropdownMenuItem onClick={() => handleEditGroup(account)}> {!isPrivateAccount(account.username) && (<DropdownMenuItem onSelect={(event) => {
event.preventDefault();
handleEditGroup(account);
}}>
<Pencil className="h-4 w-4 mr-2"/> <Pencil className="h-4 w-4 mr-2"/>
Edit Group Edit Group
</DropdownMenuItem>)} </DropdownMenuItem>)}
@@ -1258,7 +1271,7 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
{account.last_fetched} {getRelativeTime(account.last_fetched)} {account.last_fetched} {getRelativeTime(account.last_fetched)}
</div> </div>
</div> </div>
<div className="flex items-center gap-2"> <div className="flex items-center gap-2" onClick={(e) => e.stopPropagation()}>
{downloadingAccountId === account.id ? (<Tooltip> {downloadingAccountId === account.id ? (<Tooltip>
<TooltipTrigger asChild> <TooltipTrigger asChild>
<Button variant="outline" size="icon" onClick={handleStopDownload}> <Button variant="outline" size="icon" onClick={handleStopDownload}>
@@ -1276,7 +1289,7 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
</Tooltip>)} </Tooltip>)}
<Tooltip> <Tooltip>
<TooltipTrigger asChild> <TooltipTrigger asChild>
<Button variant="outline" size="icon" onClick={() => handleOpenFolder(account.username)} disabled={!folderExistence.get(account.id)}> <Button variant="outline" size="icon" onClick={() => handleOpenFolder(account)} disabled={!folderExistence.get(account.id)}>
<FolderOpen className="h-4 w-4"/> <FolderOpen className="h-4 w-4"/>
</Button> </Button>
</TooltipTrigger> </TooltipTrigger>
@@ -1294,7 +1307,10 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
<TooltipContent>More Options</TooltipContent> <TooltipContent>More Options</TooltipContent>
</Tooltip> </Tooltip>
<DropdownMenuContent align="end"> <DropdownMenuContent align="end">
{!isPrivateAccount(account.username) && (<DropdownMenuItem onClick={() => handleEditGroup(account)}> {!isPrivateAccount(account.username) && (<DropdownMenuItem onSelect={(event) => {
event.preventDefault();
handleEditGroup(account);
}}>
<Pencil className="h-4 w-4 mr-2"/> <Pencil className="h-4 w-4 mr-2"/>
Edit Group Edit Group
</DropdownMenuItem>)} </DropdownMenuItem>)}
@@ -4,30 +4,40 @@ import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from "@/components/ui/dialog"; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from "@/components/ui/dialog";
import { Spinner } from "@/components/ui/spinner"; import { Spinner } from "@/components/ui/spinner";
import { toastWithSound as toast } from "@/lib/toast-with-sound"; import { toastWithSound as toast } from "@/lib/toast-with-sound";
import { compareVersionNumbers } from "@/lib/version";
import { Quit } from "../../wailsjs/runtime/runtime"; import { Quit } from "../../wailsjs/runtime/runtime";
import { DownloadExtractor, IsExtractorInstalled } from "../../wailsjs/go/main/App"; import { DownloadExtractor, GetExtractorVersionStatus } from "../../wailsjs/go/main/App";
interface DependencySetupDialogProps { interface DependencySetupDialogProps {
onInstalled?: () => void; onInstalled?: () => void;
} }
interface GithubReleaseResponse { interface ExtractorVersionStatus {
tag_name?: string; installed: boolean;
installed_version?: string;
latest_version?: string;
} }
const extractorReleaseAPIURL = "https://api.github.com/repos/afkarxyz/xtractor-binaries/releases/latest";
export function DependencySetupDialog({ onInstalled }: DependencySetupDialogProps) { export function DependencySetupDialog({ onInstalled }: DependencySetupDialogProps) {
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
const [checking, setChecking] = useState(true); const [checking, setChecking] = useState(true);
const [downloading, setDownloading] = useState(false); const [downloading, setDownloading] = useState(false);
const [errorMessage, setErrorMessage] = useState<string | null>(null); const [errorMessage, setErrorMessage] = useState<string | null>(null);
const [updateRequired, setUpdateRequired] = useState(false);
const [installedVersion, setInstalledVersion] = useState<string | null>(null);
const [releaseVersion, setReleaseVersion] = useState<string | null>(null); const [releaseVersion, setReleaseVersion] = useState<string | null>(null);
const [releaseStatusMessage, setReleaseStatusMessage] = useState("Checking latest GitHub release..."); const [releaseStatusMessage, setReleaseStatusMessage] = useState("Checking latest GitHub release...");
useEffect(() => { useEffect(() => {
let cancelled = false; let cancelled = false;
const abortController = new AbortController();
const checkDependency = async () => { const checkDependency = async () => {
try { try {
const installed = await IsExtractorInstalled(); const status = await GetExtractorVersionStatus() as ExtractorVersionStatus;
const nextInstalledVersion = status.installed_version?.trim() || null;
const nextLatestVersion = status.latest_version?.trim() || null;
const nextUpdateRequired = !!(status.installed && nextLatestVersion && (!nextInstalledVersion || compareVersionNumbers(nextLatestVersion, nextInstalledVersion) > 0));
if (!cancelled) { if (!cancelled) {
setOpen(!installed); setUpdateRequired(nextUpdateRequired);
setInstalledVersion(nextInstalledVersion);
setReleaseVersion(nextLatestVersion);
setReleaseStatusMessage(nextLatestVersion ? `Latest GitHub release: ${nextLatestVersion}` : "Latest GitHub release unavailable.");
setOpen(!status.installed || nextUpdateRequired);
setErrorMessage(null); setErrorMessage(null);
} }
} }
@@ -43,39 +53,9 @@ export function DependencySetupDialog({ onInstalled }: DependencySetupDialogProp
} }
} }
}; };
const loadReleaseInfo = async () => {
try {
const response = await fetch(extractorReleaseAPIURL, {
headers: {
Accept: "application/vnd.github+json",
},
signal: abortController.signal,
});
if (!response.ok) {
throw new Error(`GitHub release status ${response.status}`);
}
const release = (await response.json()) as GithubReleaseResponse;
const version = release.tag_name?.trim();
if (!version) {
throw new Error("Missing GitHub release tag");
}
if (!cancelled) {
setReleaseVersion(version);
setReleaseStatusMessage(`Latest GitHub release: ${version}`);
}
}
catch {
if (!cancelled && !abortController.signal.aborted) {
setReleaseVersion(null);
setReleaseStatusMessage("Latest GitHub release unavailable.");
}
}
};
void checkDependency(); void checkDependency();
void loadReleaseInfo();
return () => { return () => {
cancelled = true; cancelled = true;
abortController.abort();
}; };
}, []); }, []);
const handleDownload = async () => { const handleDownload = async () => {
@@ -84,7 +64,7 @@ export function DependencySetupDialog({ onInstalled }: DependencySetupDialogProp
try { try {
await DownloadExtractor(); await DownloadExtractor();
setOpen(false); setOpen(false);
toast.success("Xtractor installed"); toast.success(updateRequired ? "Xtractor updated" : "Xtractor installed");
onInstalled?.(); onInstalled?.();
} }
catch (error) { catch (error) {
@@ -114,11 +94,16 @@ export function DependencySetupDialog({ onInstalled }: DependencySetupDialogProp
<div className="mb-2 flex h-12 w-12 items-center justify-center rounded-2xl border bg-muted/50"> <div className="mb-2 flex h-12 w-12 items-center justify-center rounded-2xl border bg-muted/50">
<Package className="h-6 w-6"/> <Package className="h-6 w-6"/>
</div> </div>
<DialogTitle>Download Xtractor</DialogTitle> <DialogTitle>{updateRequired ? "Update Xtractor" : "Download Xtractor"}</DialogTitle>
<DialogDescription>Xtractor is required before you can use this app.</DialogDescription> <DialogDescription>
{updateRequired ? "A newer Xtractor binary is available or the installed version could not be verified." : "Xtractor is required before you can use this app."}
</DialogDescription>
</DialogHeader> </DialogHeader>
<div className="space-y-3"> <div className="space-y-3">
{updateRequired && releaseVersion && (<p className="text-sm text-amber-600 dark:text-amber-400">
Installed: {installedVersion || "unknown"} - Latest: {releaseVersion}
</p>)}
<p className="text-sm text-muted-foreground">{releaseVersion ? `Latest GitHub release: ${releaseVersion}` : releaseStatusMessage}</p> <p className="text-sm text-muted-foreground">{releaseVersion ? `Latest GitHub release: ${releaseVersion}` : releaseStatusMessage}</p>
{errorMessage && (<div className="flex items-start gap-2 rounded-lg border border-destructive/40 bg-destructive/10 p-3 text-sm text-destructive"> {errorMessage && (<div className="flex items-start gap-2 rounded-lg border border-destructive/40 bg-destructive/10 p-3 text-sm text-destructive">
@@ -134,10 +119,10 @@ export function DependencySetupDialog({ onInstalled }: DependencySetupDialogProp
<Button onClick={handleDownload} disabled={downloading}> <Button onClick={handleDownload} disabled={downloading}>
{downloading ? (<> {downloading ? (<>
<Spinner /> <Spinner />
Downloading Xtractor... {updateRequired ? "Updating Xtractor..." : "Downloading Xtractor..."}
</>) : (<> </>) : (<>
<Download className="h-4 w-4"/> <Download className="h-4 w-4"/>
Download Xtractor {updateRequired ? "Update Xtractor" : "Download Xtractor"}
</>)} </>)}
</Button> </Button>
</DialogFooter> </DialogFooter>
+101 -312
View File
@@ -11,21 +11,11 @@ import type { TimelineEntry, AccountInfo } from "@/types/api";
import { logger } from "@/lib/logger"; import { logger } from "@/lib/logger";
import { toastWithSound as toast } from "@/lib/toast-with-sound"; import { toastWithSound as toast } from "@/lib/toast-with-sound";
import { getSettings, renderFolderTemplate } from "@/lib/settings"; import { getSettings, renderFolderTemplate } from "@/lib/settings";
import { getCachedDependencyStatus, getCachedMediaFolderStatus, setCachedDependencyStatus, setCachedMediaFolderStatus } from "@/lib/runtime-cache"; import { beginDownload, finishDownload, setDownloadItemStatus, useDownloadState } from "@/lib/download-state";
import { getCachedMediaFolderStatus, setCachedMediaFolderStatus } from "@/lib/runtime-cache";
import { openExternal } from "@/lib/utils"; import { openExternal } from "@/lib/utils";
import { DownloadMediaWithMetadata, DownloadProfileImage, OpenFolder, IsFFmpegInstalled, ConvertGIFs, StopDownload, CheckFolderExists, CheckGifsFolderHasMP4 } from "../../wailsjs/go/main/App"; import { DownloadMediaWithMetadata, DownloadProfileImage, OpenFolder, StopDownload, CheckFolderExists } from "../../wailsjs/go/main/App";
import { EventsOn } from "../../wailsjs/runtime/runtime";
import { main } from "../../wailsjs/go/models"; import { main } from "../../wailsjs/go/models";
interface DownloadProgress {
current: number;
total: number;
percent: number;
}
interface DownloadItemStatus {
tweet_id: number;
index: number;
status: "success" | "failed" | "skipped";
}
interface MediaListProps { interface MediaListProps {
accountInfo: AccountInfo; accountInfo: AccountInfo;
timeline: TimelineEntry[]; timeline: TimelineEntry[];
@@ -188,6 +178,7 @@ function getAccountFolderName(accountInfo: AccountInfo): string {
const now = new Date(); const now = new Date();
const rendered = renderFolderTemplate(template, { const rendered = renderFolderTemplate(template, {
username: accountInfo.name, username: accountInfo.name,
accountName: accountInfo.nick,
date: `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}`, date: `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}`,
}); });
return rendered || accountInfo.name; return rendered || accountInfo.name;
@@ -206,6 +197,12 @@ function pickVariantUrl(variants: {
export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType = "all", newMediaCount = null, }: MediaListProps) { export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType = "all", newMediaCount = null, }: MediaListProps) {
const settings = getSettings(); const settings = getSettings();
const folderName = getAccountFolderName(accountInfo); const folderName = getAccountFolderName(accountInfo);
const downloadState = useDownloadState();
const anyDownloadActive = downloadState.active;
const isDownloading = downloadState.active && downloadState.scope === "media";
const downloadProgress = isDownloading ? downloadState.progress : null;
const downloadingItem = isDownloading ? downloadState.currentItemKey : null;
const itemStatusByKey = downloadState.itemStatusByKey;
const cachedMediaFolderStatus = settings.downloadPath const cachedMediaFolderStatus = settings.downloadPath
? getCachedMediaFolderStatus(settings.downloadPath, folderName) ? getCachedMediaFolderStatus(settings.downloadPath, folderName)
: null; : null;
@@ -219,19 +216,10 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
useEffect(() => { useEffect(() => {
localStorage.setItem("resultViewMode", viewMode); localStorage.setItem("resultViewMode", viewMode);
}, [viewMode]); }, [viewMode]);
const [isDownloading, setIsDownloading] = useState(false);
const [downloadProgress, setDownloadProgress] = useState<DownloadProgress | null>(null);
const [hasDownloaded, setHasDownloaded] = useState(false); const [hasDownloaded, setHasDownloaded] = useState(false);
const [isConverting, setIsConverting] = useState(false);
const [ffmpegInstalled, setFfmpegInstalled] = useState(() => getCachedDependencyStatus("ffmpeg").installed ?? false);
const [showScrollTop, setShowScrollTop] = useState(false); const [showScrollTop, setShowScrollTop] = useState(false);
const [folderExists, setFolderExists] = useState(cachedMediaFolderStatus?.folderExists ?? false); const [folderExists, setFolderExists] = useState(cachedMediaFolderStatus?.folderExists ?? false);
const [gifsFolderHasMP4, setGifsFolderHasMP4] = useState(cachedMediaFolderStatus?.gifsFolderHasMP4 ?? false);
const [previewIndex, setPreviewIndex] = useState<number | null>(null); const [previewIndex, setPreviewIndex] = useState<number | null>(null);
const [downloadedItems, setDownloadedItems] = useState<Set<string>>(new Set());
const [failedItems, setFailedItems] = useState<Set<string>>(new Set());
const [skippedItems, setSkippedItems] = useState<Set<string>>(new Set());
const [downloadingItem, setDownloadingItem] = useState<string | null>(null);
const [visibleCount, setVisibleCount] = useState<number>(MEDIA_LIST_PAGE_SIZE); const [visibleCount, setVisibleCount] = useState<number>(MEDIA_LIST_PAGE_SIZE);
const loadMoreRef = useRef<HTMLDivElement>(null); const loadMoreRef = useRef<HTMLDivElement>(null);
useEffect(() => { useEffect(() => {
@@ -282,24 +270,19 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
setVisibleCount(MEDIA_LIST_PAGE_SIZE); setVisibleCount(MEDIA_LIST_PAGE_SIZE);
}, [filteredTimeline.length]); }, [filteredTimeline.length]);
useEffect(() => { useEffect(() => {
const checkFoldersAndFFmpeg = async () => { const checkFolders = async () => {
const settings = getSettings(); const settings = getSettings();
const basePath = settings.downloadPath; const basePath = settings.downloadPath;
const installed = await IsFFmpegInstalled();
setCachedDependencyStatus("ffmpeg", { installed });
setFfmpegInstalled(installed);
if (!basePath || !accountInfo.name) if (!basePath || !accountInfo.name)
return; return;
const exists = await CheckFolderExists(basePath, folderName); const exists = await CheckFolderExists(basePath, folderName);
const hasMP4 = exists ? await CheckGifsFolderHasMP4(basePath, folderName) : false;
setCachedMediaFolderStatus(basePath, folderName, { setCachedMediaFolderStatus(basePath, folderName, {
folderExists: exists, folderExists: exists,
gifsFolderHasMP4: hasMP4, gifsFolderHasMP4: false,
}); });
setFolderExists(exists); setFolderExists(exists);
setGifsFolderHasMP4(hasMP4);
}; };
checkFoldersAndFFmpeg(); checkFolders();
}, [accountInfo.name, accountInfo.nick, folderName, hasDownloaded]); }, [accountInfo.name, accountInfo.nick, folderName, hasDownloaded]);
useEffect(() => { useEffect(() => {
const sentinel = loadMoreRef.current; const sentinel = loadMoreRef.current;
@@ -340,58 +323,6 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
document.body.style.overflow = previousOverflow; document.body.style.overflow = previousOverflow;
}; };
}, [previewIndex]); }, [previewIndex]);
useEffect(() => {
const unsubscribe = EventsOn("download-progress", (progress: DownloadProgress) => {
setDownloadProgress(progress);
});
return () => {
unsubscribe();
};
}, []);
const currentDownloadingItemKeyRef = useRef<string | null>(null);
const bulkDownloadKeyMapRef = useRef<Map<number, string>>(new Map());
useEffect(() => {
const unsubscribe = EventsOn("download-item-status", (status: DownloadItemStatus) => {
const currentKey = currentDownloadingItemKeyRef.current;
const keyMap = bulkDownloadKeyMapRef.current;
let itemKey: string;
if (currentKey) {
itemKey = currentKey;
}
else if (keyMap.size > 0) {
itemKey = keyMap.get(status.index) ?? `${String(status.tweet_id)}-${status.index}`;
}
else {
itemKey = `${String(status.tweet_id)}-${status.index}`;
}
if (status.status === "success") {
setDownloadedItems((prev) => new Set(prev).add(itemKey));
if (currentKey) {
toast.success("Downloaded");
}
}
else if (status.status === "failed") {
setFailedItems((prev) => new Set(prev).add(itemKey));
if (currentKey) {
toast.error("Download failed");
}
}
else if (status.status === "skipped") {
setDownloadedItems((prev) => {
const newSet = new Set(prev);
newSet.delete(itemKey);
return newSet;
});
setSkippedItems((prev) => new Set(prev).add(itemKey));
if (currentKey) {
toast.info("Already exists");
}
}
});
return () => {
unsubscribe();
};
}, []);
const goToPrevious = () => { const goToPrevious = () => {
if (previewIndex !== null && previewIndex > 0) { if (previewIndex !== null && previewIndex > 0) {
setPreviewIndex(previewIndex - 1); setPreviewIndex(previewIndex - 1);
@@ -459,6 +390,73 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
} }
return settings.downloadPath; return settings.downloadPath;
}; };
const createMediaItemRequest = (item: TimelineEntry) => new main.MediaItemRequest({
url: item.url,
date: item.date,
tweet_id: item.tweet_id,
type: item.type,
content: item.content || "",
original_filename: item.original_filename || "",
author_username: item.author_username || "",
account_name: item.author_name || accountInfo.nick || accountInfo.name,
});
const getItemStatusFlags = (itemKey: string) => {
const status = itemStatusByKey[itemKey];
return {
isItemDownloaded: status === "success",
isItemFailed: status === "failed",
isItemSkipped: status === "skipped",
isItemDownloading: downloadingItem === itemKey,
};
};
const handleDownloadItem = async (item: TimelineEntry, itemKey: string) => {
beginDownload({ current: 0, total: 1, percent: 0 }, { scope: "media", currentItemKey: itemKey, itemKeyByIndex: { 0: itemKey } });
try {
const settings = getSettings();
const request = new main.DownloadMediaWithMetadataRequest({
items: [createMediaItemRequest(item)],
output_dir: getOutputDir(),
username: accountInfo.name,
concurrent_downloads: settings.concurrentDownloads || 10,
skip_existing: settings.skipExistingFiles,
delete_incomplete_files: settings.deleteIncompleteFiles,
retry_attempts: settings.retryAttempts,
proxy: settings.proxy || "",
filename_template: settings.filenameTemplate || "",
folder_template: settings.folderTemplate || "",
auto_convert_gifs: settings.autoConvertGifs,
gif_quality: settings.gifQuality || "fast",
gif_resolution: settings.gifResolution || "original",
});
const response = await DownloadMediaWithMetadata(request);
if (response.cancelled) {
toast.info(response.message || "Download stopped");
}
else if (response.success) {
if (response.skipped > 0) {
setDownloadItemStatus(itemKey, "skipped");
toast.info("Already exists");
}
else if (response.downloaded > 0) {
setDownloadItemStatus(itemKey, "success");
toast.success("Downloaded");
}
setHasDownloaded(true);
}
else {
setDownloadItemStatus(itemKey, "failed");
toast.error(response.message || "Download failed");
}
}
catch (error) {
setDownloadItemStatus(itemKey, "failed");
const errorMsg = error instanceof Error ? error.message : String(error);
toast.error(`Download failed: ${errorMsg}`);
}
finally {
finishDownload();
}
};
const handleDownload = async () => { const handleDownload = async () => {
const itemsWithIndices = selectedItems.size > 0 const itemsWithIndices = selectedItems.size > 0
? filteredTimeline ? filteredTimeline
@@ -469,26 +467,16 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
toast.error("No media to download"); toast.error("No media to download");
return; return;
} }
const keyMap = new Map<number, string>(); const keyMap: Record<number, string> = {};
itemsWithIndices.forEach((entry, backendIndex) => { itemsWithIndices.forEach((entry, backendIndex) => {
keyMap.set(backendIndex, getItemKey(entry.item)); keyMap[backendIndex] = getItemKey(entry.item);
}); });
bulkDownloadKeyMapRef.current = keyMap; beginDownload({ current: 0, total: itemsWithIndices.length, percent: 0 }, { scope: "media", itemKeyByIndex: keyMap });
setIsDownloading(true);
setDownloadProgress({ current: 0, total: itemsWithIndices.length, percent: 0 });
logger.info(`Starting download of ${itemsWithIndices.length} files...`); logger.info(`Starting download of ${itemsWithIndices.length} files...`);
try { try {
const settings = getSettings(); const settings = getSettings();
const request = new main.DownloadMediaWithMetadataRequest({ const request = new main.DownloadMediaWithMetadataRequest({
items: itemsWithIndices.map(({ item }) => new main.MediaItemRequest({ items: itemsWithIndices.map(({ item }) => createMediaItemRequest(item)),
url: item.url,
date: item.date,
tweet_id: item.tweet_id,
type: item.type,
content: item.content || "",
original_filename: item.original_filename || "",
author_username: item.author_username || "",
})),
output_dir: getOutputDir(), output_dir: getOutputDir(),
username: accountInfo.name, username: accountInfo.name,
concurrent_downloads: settings.concurrentDownloads || 10, concurrent_downloads: settings.concurrentDownloads || 10,
@@ -498,6 +486,9 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
proxy: settings.proxy || "", proxy: settings.proxy || "",
filename_template: settings.filenameTemplate || "", filename_template: settings.filenameTemplate || "",
folder_template: settings.folderTemplate || "", folder_template: settings.folderTemplate || "",
auto_convert_gifs: settings.autoConvertGifs,
gif_quality: settings.gifQuality || "fast",
gif_resolution: settings.gifResolution || "original",
}); });
const response = await DownloadMediaWithMetadata(request); const response = await DownloadMediaWithMetadata(request);
if (response.cancelled) { if (response.cancelled) {
@@ -528,17 +519,12 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
toast.success(message); toast.success(message);
} }
setHasDownloaded(true); setHasDownloaded(true);
const installed = await IsFFmpegInstalled();
setCachedDependencyStatus("ffmpeg", { installed });
setFfmpegInstalled(installed);
if (settings.downloadPath) { if (settings.downloadPath) {
const hasMP4 = await CheckGifsFolderHasMP4(settings.downloadPath, folderName);
setCachedMediaFolderStatus(settings.downloadPath, folderName, { setCachedMediaFolderStatus(settings.downloadPath, folderName, {
folderExists: true, folderExists: true,
gifsFolderHasMP4: hasMP4, gifsFolderHasMP4: false,
}); });
setFolderExists(true); setFolderExists(true);
setGifsFolderHasMP4(hasMP4);
} }
} }
else { else {
@@ -552,15 +538,14 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
toast.error("Download failed"); toast.error("Download failed");
} }
finally { finally {
setIsDownloading(false); finishDownload();
setDownloadProgress(null);
bulkDownloadKeyMapRef.current = new Map();
} }
}; };
const handleStopDownload = async () => { const handleStopDownload = async () => {
try { try {
const stopped = await StopDownload(); const stopped = await StopDownload();
if (stopped) { if (stopped) {
finishDownload();
logger.info("Download stopped by user"); logger.info("Download stopped by user");
toast.info("Stopped"); toast.info("Stopped");
} }
@@ -607,8 +592,8 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
} }
else { else {
folderPath = settings.downloadPath folderPath = settings.downloadPath
? `${settings.downloadPath}/${accountInfo.name}` ? `${settings.downloadPath}/${folderName}`
: accountInfo.name; : folderName;
} }
try { try {
await OpenFolder(folderPath); await OpenFolder(folderPath);
@@ -625,52 +610,6 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
const handleOpenTweet = (tweetId: string) => { const handleOpenTweet = (tweetId: string) => {
openExternal(`https://x.com/${accountInfo.name}/status/${tweetId}`); openExternal(`https://x.com/${accountInfo.name}/status/${tweetId}`);
}; };
const handleConvertGifs = async () => {
const settings = getSettings();
const isBookmarks = accountInfo.nick === "My Bookmarks";
const isLikes = accountInfo.nick === "My Likes";
let folderPath: string;
if (isBookmarks || isLikes) {
const separator = settings.downloadPath.includes("/") ? "/" : "\\";
const folderName = isBookmarks ? "My Bookmarks" : "My Likes";
folderPath = `${settings.downloadPath}${separator}${folderName}`;
}
else {
folderPath = `${settings.downloadPath}/${accountInfo.name}`;
}
setIsConverting(true);
logger.info("Converting GIFs...");
try {
const response = await ConvertGIFs({
folder_path: folderPath,
quality: settings.gifQuality || "fast",
resolution: settings.gifResolution || "high",
delete_original: false,
});
if (response.success) {
logger.success(`Converted ${response.converted} GIFs`);
toast.success(`${response.converted} GIFs converted`);
const hasMP4 = await CheckGifsFolderHasMP4(settings.downloadPath, folderName);
setCachedMediaFolderStatus(settings.downloadPath, folderName, {
folderExists: true,
gifsFolderHasMP4: hasMP4,
});
setGifsFolderHasMP4(hasMP4);
}
else {
logger.error(response.message);
toast.error("Convert failed");
}
}
catch (error) {
const errorMsg = error instanceof Error ? error.message : String(error);
logger.error(`Convert failed: ${errorMsg}`);
toast.error("Convert failed");
}
finally {
setIsConverting(false);
}
};
return (<div className="space-y-4"> return (<div className="space-y-4">
{accountInfo.name === "bookmarks" || accountInfo.name === "likes" ? (<div className="flex items-center gap-4 p-4 bg-muted/50 rounded-lg"> {accountInfo.name === "bookmarks" || accountInfo.name === "likes" ? (<div className="flex items-center gap-4 p-4 bg-muted/50 rounded-lg">
@@ -819,21 +758,12 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
<FolderOpen className="h-4 w-4"/> <FolderOpen className="h-4 w-4"/>
Open Folder Open Folder
</Button> </Button>
<Button variant="outline" onClick={handleConvertGifs} disabled={isConverting || !gifsFolderHasMP4 || !ffmpegInstalled}>
{isConverting ? (<>
<Spinner />
Converting...
</>) : (<>
<Film className="h-4 w-4"/>
Convert GIFs
</>)}
</Button>
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
{isDownloading && (<Button variant="destructive" onClick={handleStopDownload}> {isDownloading && (<Button variant="destructive" onClick={handleStopDownload}>
<StopCircle className="h-4 w-4"/> <StopCircle className="h-4 w-4"/>
Stop Stop
</Button>)} </Button>)}
<Button onClick={handleDownload} disabled={isDownloading}> <Button onClick={handleDownload} disabled={anyDownloadActive}>
{isDownloading ? (<> {isDownloading ? (<>
<Spinner /> <Spinner />
Downloading... Downloading...
@@ -870,10 +800,7 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
{filteredTimeline.slice(0, visibleCount).map((item, index) => { {filteredTimeline.slice(0, visibleCount).map((item, index) => {
const itemKey = getItemKey(item); const itemKey = getItemKey(item);
const isSelected = selectedItems.has(itemKey); const isSelected = selectedItems.has(itemKey);
const isItemDownloaded = downloadedItems.has(itemKey); const { isItemDownloaded, isItemFailed, isItemSkipped, isItemDownloading } = getItemStatusFlags(itemKey);
const isItemFailed = failedItems.has(itemKey);
const isItemSkipped = skippedItems.has(itemKey);
const isItemDownloading = downloadingItem === itemKey;
return (<div key={itemKey} onClick={() => openPreview(index)} className={`flex items-center gap-4 p-3 rounded-lg border-2 transition-all cursor-pointer ${isSelected ? "border-primary bg-primary/5" : "border-transparent hover:bg-muted/50"}`}> return (<div key={itemKey} onClick={() => openPreview(index)} className={`flex items-center gap-4 p-3 rounded-lg border-2 transition-all cursor-pointer ${isSelected ? "border-primary bg-primary/5" : "border-transparent hover:bg-muted/50"}`}>
<Checkbox checked={isSelected} onCheckedChange={() => toggleItem(itemKey)} onClick={(e) => e.stopPropagation()}/> <Checkbox checked={isSelected} onCheckedChange={() => toggleItem(itemKey)} onClick={(e) => e.stopPropagation()}/>
<div className="relative shrink-0"> <div className="relative shrink-0">
@@ -912,53 +839,7 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
<div className="flex items-center gap-2 shrink-0"> <div className="flex items-center gap-2 shrink-0">
<Tooltip> <Tooltip>
<TooltipTrigger asChild> <TooltipTrigger asChild>
<Button size="icon" variant="default" onClick={async () => { <Button size="icon" variant="default" onClick={() => void handleDownloadItem(item, itemKey)} disabled={anyDownloadActive}>
setDownloadingItem(itemKey);
currentDownloadingItemKeyRef.current = itemKey;
try {
const settings = getSettings();
const request = new main.DownloadMediaWithMetadataRequest({
items: [new main.MediaItemRequest({
url: item.url,
date: item.date,
tweet_id: item.tweet_id,
type: item.type,
content: item.content || "",
original_filename: item.original_filename || "",
author_username: item.author_username || "",
})],
output_dir: getOutputDir(),
username: accountInfo.name,
concurrent_downloads: settings.concurrentDownloads || 10,
skip_existing: settings.skipExistingFiles,
delete_incomplete_files: settings.deleteIncompleteFiles,
retry_attempts: settings.retryAttempts,
proxy: settings.proxy || "",
filename_template: settings.filenameTemplate || "",
folder_template: settings.folderTemplate || "",
});
const response = await DownloadMediaWithMetadata(request);
if (response.cancelled) {
toast.info(response.message || "Download stopped");
}
else if (response.success) {
setHasDownloaded(true);
}
else {
setFailedItems((prev) => new Set(prev).add(itemKey));
toast.error(response.message || "Download failed");
}
}
catch (error) {
setFailedItems((prev) => new Set(prev).add(itemKey));
const errorMsg = error instanceof Error ? error.message : String(error);
toast.error(`Download failed: ${errorMsg}`);
}
finally {
setDownloadingItem(null);
setTimeout(() => { currentDownloadingItemKeyRef.current = null; }, 1000);
}
}} disabled={downloadingItem !== null}>
{isItemDownloading ? (<Spinner />) : isItemSkipped ? (<FileCheck className="h-4 w-4"/>) : isItemDownloaded ? (<CheckCircle className="h-4 w-4"/>) : isItemFailed ? (<XCircle className="h-4 w-4"/>) : (<Download className="h-4 w-4"/>)} {isItemDownloading ? (<Spinner />) : isItemSkipped ? (<FileCheck className="h-4 w-4"/>) : isItemDownloaded ? (<CheckCircle className="h-4 w-4"/>) : isItemFailed ? (<XCircle className="h-4 w-4"/>) : (<Download className="h-4 w-4"/>)}
</Button> </Button>
</TooltipTrigger> </TooltipTrigger>
@@ -976,10 +857,7 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
{filteredTimeline.slice(0, visibleCount).map((item, index) => { {filteredTimeline.slice(0, visibleCount).map((item, index) => {
const itemKey = getItemKey(item); const itemKey = getItemKey(item);
const isSelected = selectedItems.has(itemKey); const isSelected = selectedItems.has(itemKey);
const isItemDownloaded = downloadedItems.has(itemKey); const { isItemDownloaded, isItemFailed, isItemSkipped, isItemDownloading } = getItemStatusFlags(itemKey);
const isItemFailed = failedItems.has(itemKey);
const isItemSkipped = skippedItems.has(itemKey);
const isItemDownloading = downloadingItem === itemKey;
return (<div key={itemKey} className={`relative group rounded-lg overflow-hidden border-2 transition-all ${isSelected ? "border-primary" : "border-transparent hover:border-muted-foreground/30"}`}> return (<div key={itemKey} className={`relative group rounded-lg overflow-hidden border-2 transition-all ${isSelected ? "border-primary" : "border-transparent hover:border-muted-foreground/30"}`}>
<div className="aspect-square bg-muted relative cursor-pointer" onClick={() => openPreview(index)}> <div className="aspect-square bg-muted relative cursor-pointer" onClick={() => openPreview(index)}>
@@ -996,51 +874,8 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
<TooltipTrigger asChild> <TooltipTrigger asChild>
<Button size="icon" variant="default" className="h-8 w-8" onClick={async (e) => { <Button size="icon" variant="default" className="h-8 w-8" onClick={async (e) => {
e.stopPropagation(); e.stopPropagation();
setDownloadingItem(itemKey); await handleDownloadItem(item, itemKey);
currentDownloadingItemKeyRef.current = itemKey; }} disabled={anyDownloadActive}>
try {
const settings = getSettings();
const request = new main.DownloadMediaWithMetadataRequest({
items: [new main.MediaItemRequest({
url: item.url,
date: item.date,
tweet_id: item.tweet_id,
type: item.type,
content: item.content || "",
author_username: item.author_username || "",
})],
output_dir: getOutputDir(),
username: accountInfo.name,
concurrent_downloads: settings.concurrentDownloads || 10,
skip_existing: settings.skipExistingFiles,
delete_incomplete_files: settings.deleteIncompleteFiles,
retry_attempts: settings.retryAttempts,
proxy: settings.proxy || "",
filename_template: settings.filenameTemplate || "",
folder_template: settings.folderTemplate || "",
});
const response = await DownloadMediaWithMetadata(request);
if (response.cancelled) {
toast.info(response.message || "Download stopped");
}
else if (response.success) {
setHasDownloaded(true);
}
else {
setFailedItems((prev) => new Set(prev).add(itemKey));
toast.error(response.message || "Download failed");
}
}
catch (error) {
setFailedItems((prev) => new Set(prev).add(itemKey));
const errorMsg = error instanceof Error ? error.message : String(error);
toast.error(`Download failed: ${errorMsg}`);
}
finally {
setDownloadingItem(null);
setTimeout(() => { currentDownloadingItemKeyRef.current = null; }, 1000);
}
}} disabled={downloadingItem !== null}>
{isItemDownloading ? (<Spinner />) : isItemSkipped ? (<FileCheck className="h-4 w-4"/>) : isItemDownloaded ? (<CheckCircle className="h-4 w-4"/>) : isItemFailed ? (<XCircle className="h-4 w-4"/>) : (<Download className="h-4 w-4"/>)} {isItemDownloading ? (<Spinner />) : isItemSkipped ? (<FileCheck className="h-4 w-4"/>) : isItemDownloaded ? (<CheckCircle className="h-4 w-4"/>) : isItemFailed ? (<XCircle className="h-4 w-4"/>) : (<Download className="h-4 w-4"/>)}
</Button> </Button>
</TooltipTrigger> </TooltipTrigger>
@@ -1169,56 +1004,10 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
{(() => { {(() => {
const item = filteredTimeline[previewIndex]; const item = filteredTimeline[previewIndex];
const itemKey = getItemKey(item); const itemKey = getItemKey(item);
const isItemDownloaded = downloadedItems.has(itemKey); const { isItemDownloaded, isItemFailed, isItemSkipped, isItemDownloading } = getItemStatusFlags(itemKey);
const isItemFailed = failedItems.has(itemKey);
const isItemSkipped = skippedItems.has(itemKey);
const isItemDownloading = downloadingItem === itemKey;
return (<Button variant="default" size="sm" className="h-9" onClick={async () => { return (<Button variant="default" size="sm" className="h-9" onClick={async () => {
setDownloadingItem(itemKey); await handleDownloadItem(item, itemKey);
currentDownloadingItemKeyRef.current = itemKey; }} disabled={anyDownloadActive}>
try {
const settings = getSettings();
const request = new main.DownloadMediaWithMetadataRequest({
items: [new main.MediaItemRequest({
url: item.url,
date: item.date,
tweet_id: item.tweet_id,
type: item.type,
content: item.content || "",
original_filename: item.original_filename || "",
author_username: item.author_username || "",
})],
output_dir: getOutputDir(),
username: accountInfo.name,
concurrent_downloads: settings.concurrentDownloads || 10,
skip_existing: settings.skipExistingFiles,
delete_incomplete_files: settings.deleteIncompleteFiles,
retry_attempts: settings.retryAttempts,
proxy: settings.proxy || "",
filename_template: settings.filenameTemplate || "",
folder_template: settings.folderTemplate || "",
});
const response = await DownloadMediaWithMetadata(request);
if (response.cancelled) {
toast.info(response.message || "Download stopped");
}
else if (response.success) {
setHasDownloaded(true);
}
else {
setFailedItems((prev) => new Set(prev).add(itemKey));
toast.error("Download failed");
}
}
catch {
setFailedItems((prev) => new Set(prev).add(itemKey));
toast.error("Download failed");
}
finally {
setDownloadingItem(null);
setTimeout(() => { currentDownloadingItemKeyRef.current = null; }, 1000);
}
}} disabled={downloadingItem !== null}>
{isItemDownloading ? (<Spinner className="mr-1"/>) : isItemSkipped ? (<FileCheck className="h-4 w-4 mr-1"/>) : isItemDownloaded ? (<CheckCircle className="h-4 w-4 mr-1"/>) : isItemFailed ? (<XCircle className="h-4 w-4 mr-1"/>) : (<Download className="h-4 w-4 mr-1"/>)} {isItemDownloading ? (<Spinner className="mr-1"/>) : isItemSkipped ? (<FileCheck className="h-4 w-4 mr-1"/>) : isItemDownloaded ? (<CheckCircle className="h-4 w-4 mr-1"/>) : isItemFailed ? (<XCircle className="h-4 w-4 mr-1"/>) : (<Download className="h-4 w-4 mr-1"/>)}
{isItemDownloading ? "Downloading..." : isItemSkipped ? "Already exists" : isItemDownloaded ? "Downloaded" : isItemFailed ? "Failed" : "Download"} {isItemDownloading ? "Downloading..." : isItemSkipped ? "Already exists" : isItemDownloaded ? "Downloaded" : isItemFailed ? "Failed" : "Download"}
</Button>); </Button>);
+16 -1
View File
@@ -11,7 +11,7 @@ import { toastWithSound as toast } from "@/lib/toast-with-sound";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { getSettings, updateSettings, VIDEO_QUALITIES, IMAGE_SIZES, AVATAR_SIZES, BANNER_SIZES, type VideoQuality, type ImageSize, type AvatarSize, type BannerSize } from "@/lib/settings"; import { getSettings, updateSettings, VIDEO_QUALITIES, IMAGE_SIZES, AVATAR_SIZES, BANNER_SIZES, type VideoQuality, type ImageSize, type AvatarSize, type BannerSize } from "@/lib/settings";
import { GetStoredAuthToken, SetStoredAuthToken } from "../../wailsjs/go/main/App"; import { GetStoredAuthToken, SetStoredAuthToken } from "../../wailsjs/go/main/App";
import { AlertCircle, Bookmark, CheckCircle, CloudDownload, Clock, Database, Eye, EyeOff, Globe, Heart, Hourglass, Info, Lock, RotateCcw, SlidersHorizontal, StopCircle, Trash2, User, Users, XCircle } from "lucide-react"; import { AlertCircle, Bookmark, CheckCircle, Clipboard, CloudDownload, Clock, Database, Eye, EyeOff, Globe, Heart, Hourglass, Info, Lock, RotateCcw, SlidersHorizontal, StopCircle, Trash2, User, Users, XCircle } from "lucide-react";
import { Spinner } from "@/components/ui/spinner"; import { Spinner } from "@/components/ui/spinner";
function formatNumberWithComma(num: number): string { function formatNumberWithComma(num: number): string {
return num.toLocaleString(); return num.toLocaleString();
@@ -207,6 +207,17 @@ export function SearchBar({ username, loading, onUsernameChange, onFetch, onStop
onFetch(false, undefined, undefined, undefined, retweets, mode, privateType, authToken, false); onFetch(false, undefined, undefined, undefined, retweets, mode, privateType, authToken, false);
}); });
}; };
const handleClipboardPaste = async () => {
try {
const clipboardText = (await navigator.clipboard.readText()).trim();
if (clipboardText) {
onUsernameChange(clipboardText);
}
}
catch (error) {
console.error("Failed to read clipboard:", error);
}
};
const handleResume = () => { const handleResume = () => {
if (onResume) { if (onResume) {
requireAuthToken((authToken) => { requireAuthToken((authToken) => {
@@ -371,6 +382,10 @@ export function SearchBar({ username, loading, onUsernameChange, onFetch, onStop
</button>)} </button>)}
</div> </div>
<Button variant="outline" size="icon" className="shrink-0" aria-label="Paste from clipboard" onClick={() => void handleClipboardPaste()}>
<Clipboard className="h-4 w-4"/>
</Button>
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
{loading && (<Button variant="destructive" onClick={onStopFetch}> {loading && (<Button variant="destructive" onClick={onStopFetch}>
<StopCircle className="h-4 w-4"/> <StopCircle className="h-4 w-4"/>
+7 -3
View File
@@ -591,14 +591,18 @@ export function SettingsPage({ onUnsavedChangesChange, onResetRequest }: Setting
</Tooltip> </Tooltip>
</Label> </Label>
<div className="flex items-center justify-between gap-4"> <div className="flex items-center justify-between gap-4">
<Label htmlFor="gif-quality" className={!ffmpegInstalled ? "text-muted-foreground" : undefined}>GIF Quality</Label> <Label htmlFor="auto-convert-gifs" className={!ffmpegInstalled ? "text-muted-foreground" : undefined}>Auto Convert GIFs</Label>
<Switch id="auto-convert-gifs" checked={tempSettings.autoConvertGifs} onCheckedChange={(checked) => setTempSettings((prev) => ({ ...prev, autoConvertGifs: checked }))} disabled={!ffmpegInstalled}/>
</div>
<div className="flex items-center justify-between gap-4">
<Label htmlFor="gif-quality" className={!ffmpegInstalled || !tempSettings.autoConvertGifs ? "text-muted-foreground" : undefined}>GIF Quality</Label>
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<Select value={tempSettings.gifQuality} onValueChange={(value: GifQuality) => { <Select value={tempSettings.gifQuality} onValueChange={(value: GifQuality) => {
setTempSettings((prev) => ({ setTempSettings((prev) => ({
...prev, ...prev,
gifQuality: value, gifQuality: value,
})); }));
}} disabled={!ffmpegInstalled}> }} disabled={!ffmpegInstalled || !tempSettings.autoConvertGifs}>
<SelectTrigger id="gif-quality" className="w-fit"> <SelectTrigger id="gif-quality" className="w-fit">
<SelectValue placeholder="Select quality"/> <SelectValue placeholder="Select quality"/>
</SelectTrigger> </SelectTrigger>
@@ -607,7 +611,7 @@ export function SettingsPage({ onUnsavedChangesChange, onResetRequest }: Setting
<SelectItem value="better">Better</SelectItem> <SelectItem value="better">Better</SelectItem>
</SelectContent> </SelectContent>
</Select> </Select>
<Select value={tempSettings.gifResolution} onValueChange={(value: GifResolution) => setTempSettings((prev) => ({ ...prev, gifResolution: value }))} disabled={!ffmpegInstalled}> <Select value={tempSettings.gifResolution} onValueChange={(value: GifResolution) => setTempSettings((prev) => ({ ...prev, gifResolution: value }))} disabled={!ffmpegInstalled || !tempSettings.autoConvertGifs}>
<SelectTrigger id="gif-resolution" className="w-fit"> <SelectTrigger id="gif-resolution" className="w-fit">
<SelectValue placeholder="Resolution"/> <SelectValue placeholder="Resolution"/>
</SelectTrigger> </SelectTrigger>
+85 -20
View File
@@ -1,16 +1,57 @@
import { useState } from "react"; import { useState } from "react";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { CircleCheck, Copy } from "lucide-react"; import { CircleCheck, Copy } from "lucide-react";
import { openExternal } from "@/lib/utils"; import { openExternal } from "@/lib/utils";
import KofiLogo from "@/assets/ko-fi.gif"; import KofiLogo from "@/assets/ko-fi.gif";
import KofiSvg from "@/assets/kofi_symbol.svg"; import KofiSvg from "@/assets/kofi_symbol.svg";
import UsdtBarcode from "@/assets/usdt.jpg"; import UsdtTronQr from "@/assets/usdt.jpg";
const USDT_ADDRESS = "THnzAAwZgp2Sq5CAXLP2njQDhTvgZG9EWs"; import UsdtEvmQr from "@/assets/usdt_evm.jpg";
import UsdcEvmQr from "@/assets/usdc.jpg";
type CryptoCoin = "usdt" | "usdc";
type CryptoNetwork = "ethereum" | "bsc" | "polygon" | "base" | "tron";
const EVM_ADDRESS = "0xB563a7F39770C151e2FacE26926081a00c5EF349";
const TRON_ADDRESS = "THnzAAwZgp2Sq5CAXLP2njQDhTvgZG9EWs";
const EVM_NETWORKS: Array<{
value: CryptoNetwork;
label: string;
shortLabel: string;
}> = [
{ value: "bsc", label: "BNB Smart Chain (BEP20)", shortLabel: "BEP20" },
{ value: "polygon", label: "Polygon", shortLabel: "Polygon" },
{ value: "ethereum", label: "Ethereum (ERC20)", shortLabel: "ERC20" },
{ value: "base", label: "Base", shortLabel: "Base" },
];
const USDT_NETWORKS: Array<{
value: CryptoNetwork;
label: string;
shortLabel: string;
}> = [
{ value: "ethereum", label: "Ethereum (ERC20)", shortLabel: "ERC20" },
{ value: "bsc", label: "BNB Smart Chain (BEP20)", shortLabel: "BEP20" },
{ value: "tron", label: "Tron (TRC20)", shortLabel: "TRC20" },
{ value: "polygon", label: "Polygon", shortLabel: "Polygon" },
];
export function SupportPage() { export function SupportPage() {
const [copiedUsdt, setCopiedUsdt] = useState(false); const [selectedCoin, setSelectedCoin] = useState<CryptoCoin>("usdt");
const [selectedNetwork, setSelectedNetwork] = useState<CryptoNetwork>("tron");
const [copiedAddress, setCopiedAddress] = useState(false);
const networkOptions = selectedCoin === "usdt" ? USDT_NETWORKS : EVM_NETWORKS;
const activeNetwork = networkOptions.find((network) => network.value === selectedNetwork) || EVM_NETWORKS[0];
const isTron = selectedNetwork === "tron";
const cryptoAddress = isTron ? TRON_ADDRESS : EVM_ADDRESS;
const cryptoQr = isTron ? UsdtTronQr : selectedCoin === "usdt" ? UsdtEvmQr : UsdcEvmQr;
const handleCoinChange = (coin: CryptoCoin) => {
setSelectedCoin(coin);
setCopiedAddress(false);
const nextNetworks = coin === "usdt" ? USDT_NETWORKS : EVM_NETWORKS;
if (!nextNetworks.some((network) => network.value === selectedNetwork)) {
setSelectedNetwork("ethereum");
}
};
return (<div className="flex min-h-[70vh] items-center justify-center p-4"> return (<div className="flex min-h-[70vh] items-center justify-center p-4">
<div className="flex w-full max-w-3xl flex-col items-stretch rounded-xl border bg-card shadow-sm md:flex-row"> <div className="flex w-full max-w-3xl flex-col items-stretch rounded-xl border bg-card shadow-sm md:flex-row">
<div className="flex flex-1 flex-col items-center justify-between space-y-6 border-b p-6 md:border-r md:border-b-0"> <div className="flex min-w-0 flex-1 basis-0 flex-col items-center justify-between space-y-6 border-b p-6 md:border-r md:border-b-0">
<div className="flex flex-col items-center space-y-4"> <div className="flex flex-col items-center space-y-4">
<div className="relative flex h-32 w-full items-center justify-center"> <div className="relative flex h-32 w-full items-center justify-center">
<img src={KofiLogo} className="pointer-events-none absolute w-72" alt="Ko-fi"/> <img src={KofiLogo} className="pointer-events-none absolute w-72" alt="Ko-fi"/>
@@ -20,35 +61,59 @@ export function SupportPage() {
Enjoying the project? You can support ongoing development by buying me a coffee. Enjoying the project? You can support ongoing development by buying me a coffee.
</p> </p>
</div> </div>
<Button className="h-10 w-full gap-2 bg-[#72a4f2] text-sm font-semibold text-white hover:bg-[#5f8cd6]" onClick={() => openExternal("https://ko-fi.com/afkarxyz")}> <Button className="h-9 w-4/5 gap-2 bg-[#72a4f2] text-sm font-semibold text-white hover:bg-[#5f8cd6]" onClick={() => openExternal("https://ko-fi.com/afkarxyz")}>
<img src={KofiSvg} className="h-5 w-5 shrink-0" alt="" aria-hidden="true"/> <img src={KofiSvg} className="h-6 w-6 shrink-0" alt="" aria-hidden="true"/>
Support me on Ko-fi Support me on Ko-fi
</Button> </Button>
</div> </div>
<div className="flex flex-1 flex-col items-center justify-between space-y-6 p-6"> <div className="flex min-w-0 flex-1 basis-0 flex-col items-center justify-between space-y-4 p-6">
<div className="flex w-full flex-col items-center space-y-4"> <div className="flex w-full flex-col items-center space-y-3">
<div className="flex h-32 items-center justify-center"> <div className="flex h-32 items-center justify-center">
<div className="rounded-xl border bg-white p-2 shadow-sm"> <div className="rounded-xl border bg-white p-2 shadow-sm">
<img src={UsdtBarcode} className="h-24 w-24 object-contain" alt="USDT Barcode"/> <img src={cryptoQr} className="h-24 w-24 object-contain" alt={`${selectedCoin.toUpperCase()} ${activeNetwork.label} QR code`}/>
</div> </div>
</div> </div>
<h4 className="font-semibold text-foreground">USDT (TRC20)</h4> <h4 className="font-semibold text-foreground">Support via Crypto</h4>
<p className="px-4 text-center text-sm text-muted-foreground"> <p className="px-4 text-center text-sm text-muted-foreground">
Crypto donations are also accepted. Scan the QR code or copy the address. Crypto donations are also accepted. Scan the QR code or copy the address.
</p> </p>
</div> </div>
<div className="flex h-10 w-full items-center justify-between gap-2 rounded-lg border bg-muted/50 py-1.5 pr-1.5 pl-3"> <div className="w-full space-y-2">
<code className="truncate text-xs font-mono text-muted-foreground" title={USDT_ADDRESS}> <div className="grid grid-cols-2 gap-2">
{USDT_ADDRESS} <Select value={selectedCoin} onValueChange={(value: CryptoCoin) => handleCoinChange(value)}>
</code> <SelectTrigger size="sm" className="w-full" aria-label="Coin">
<Button variant="ghost" size="icon" className="h-7 w-7 shrink-0 hover:bg-background" onClick={() => { <SelectValue />
navigator.clipboard.writeText(USDT_ADDRESS); </SelectTrigger>
setCopiedUsdt(true); <SelectContent>
setTimeout(() => setCopiedUsdt(false), 500); <SelectItem value="usdt">USDT</SelectItem>
<SelectItem value="usdc">USDC</SelectItem>
</SelectContent>
</Select>
<Select value={selectedNetwork} onValueChange={(value: CryptoNetwork) => {
setSelectedNetwork(value);
setCopiedAddress(false);
}}> }}>
{copiedUsdt ? <CircleCheck className="h-3.5 w-3.5 text-green-500"/> : <Copy className="h-3.5 w-3.5"/>} <SelectTrigger size="sm" className="w-full" aria-label="Network">
</Button> <SelectValue>{activeNetwork.shortLabel}</SelectValue>
</SelectTrigger>
<SelectContent>
{networkOptions.map((network) => (<SelectItem key={network.value} value={network.value}>{network.label}</SelectItem>))}
</SelectContent>
</Select>
</div>
<div className="flex h-10 w-full items-center justify-between gap-2 rounded-lg border bg-muted/50 py-1.5 pr-1.5 pl-3">
<code className="min-w-0 flex-1 truncate text-xs font-mono text-muted-foreground" title={cryptoAddress}>
{cryptoAddress}
</code>
<Button variant="ghost" size="icon" className="h-7 w-7 shrink-0 hover:bg-background" aria-label="Copy wallet address" onClick={() => {
navigator.clipboard.writeText(cryptoAddress);
setCopiedAddress(true);
setTimeout(() => setCopiedAddress(false), 500);
}}>
{copiedAddress ? <CircleCheck className="h-3.5 w-3.5 text-green-500"/> : <Copy className="h-3.5 w-3.5"/>}
</Button>
</div>
</div> </div>
</div> </div>
</div> </div>
+1 -1
View File
@@ -5,7 +5,7 @@ import { openExternal } from "@/lib/utils";
const INFO_LINKS = [ const INFO_LINKS = [
{ label: "Chrome Extension", icon: Puzzle, url: "https://chromewebstore.google.com/detail/cboceolmgkoobpfjiojkigmihijfgmdo" }, { label: "Chrome Extension", icon: Puzzle, url: "https://chromewebstore.google.com/detail/cboceolmgkoobpfjiojkigmihijfgmdo" },
{ label: "Userscript", icon: FileCode2, url: "https://greasyfork.org/en/scripts/523157" }, { label: "Userscript", icon: FileCode2, url: "https://greasyfork.org/en/scripts/523157" },
{ label: "Website", icon: Globe, url: "https://mediabatchdl.com" }, { label: "Website", icon: Globe, url: "https://twitterdl.app" },
]; ];
export function TitleBar() { export function TitleBar() {
const handleMinimize = () => { const handleMinimize = () => {
+112
View File
@@ -0,0 +1,112 @@
import { useSyncExternalStore } from "react";
import { EventsOn } from "../../wailsjs/runtime/runtime";
export interface DownloadProgress {
current: number;
total: number;
percent: number;
}
export interface DownloadItemStatus {
tweet_id: number;
index: number;
status: "success" | "failed" | "skipped" | "cancelled";
}
export type DownloadScope = "media" | "database" | "database-bulk";
export type DownloadItemResult = "success" | "failed" | "skipped";
export interface DownloadState {
active: boolean;
scope: DownloadScope | null;
accountId: number | null;
progress: DownloadProgress | null;
currentItemKey: string | null;
itemKeyByIndex: Record<number, string>;
itemStatusByKey: Record<string, DownloadItemResult>;
}
const listeners = new Set<() => void>();
let state: DownloadState = {
active: false,
scope: null,
accountId: null,
progress: null,
currentItemKey: null,
itemKeyByIndex: {},
itemStatusByKey: {},
};
let unsubscribeEvents: (() => void) | null = null;
function emit() {
for (const listener of listeners) {
listener();
}
}
function setState(next: Partial<DownloadState>) {
state = { ...state, ...next };
emit();
}
export function initDownloadProgressEvents() {
if (unsubscribeEvents) {
return unsubscribeEvents;
}
const unsubscribeProgress = EventsOn("download-progress", (progress: DownloadProgress) => {
if (!state.scope) {
return;
}
setState({ progress });
});
const unsubscribeItemStatus = EventsOn("download-item-status", (status: DownloadItemStatus) => {
if (status.status === "cancelled") {
return;
}
const itemKey = state.currentItemKey || state.itemKeyByIndex[status.index] || `${String(status.tweet_id)}-${status.index}`;
setState({
itemStatusByKey: {
...state.itemStatusByKey,
[itemKey]: status.status,
},
});
});
unsubscribeEvents = () => {
unsubscribeProgress();
unsubscribeItemStatus();
unsubscribeEvents = null;
};
return unsubscribeEvents;
}
export function beginDownload(progress: DownloadProgress, meta: Pick<DownloadState, "scope"> & Partial<Pick<DownloadState, "accountId" | "currentItemKey" | "itemKeyByIndex">>) {
setState({
active: true,
scope: meta.scope,
accountId: meta.accountId ?? null,
progress,
currentItemKey: meta.currentItemKey ?? null,
itemKeyByIndex: meta.itemKeyByIndex ?? {},
});
}
export function finishDownload() {
setState({
active: false,
scope: null,
accountId: null,
progress: null,
currentItemKey: null,
itemKeyByIndex: {},
});
}
export function setDownloadItemStatus(itemKey: string, status: DownloadItemResult) {
setState({
itemStatusByKey: {
...state.itemStatusByKey,
[itemKey]: status,
},
});
}
export function subscribeDownloadState(listener: () => void) {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
}
export function getDownloadState() {
return state;
}
export function useDownloadState() {
return useSyncExternalStore(subscribeDownloadState, getDownloadState, getDownloadState);
}
+58 -19
View File
@@ -58,67 +58,86 @@ export const BANNER_SIZES: {
{ value: "600x200", label: "600×200" }, { value: "600x200", label: "600×200" },
{ value: "300x100", label: "300×100" }, { value: "300x100", label: "300×100" },
]; ];
export const DEFAULT_FILENAME_TEMPLATE = "{username}_{date}_{tweet_id}_{index}"; export const DEFAULT_FILENAME_TEMPLATE = "{handle}_{date}_{tweet_id}";
export interface TemplateToken { export interface TemplateToken {
key: string; key: string;
description: string; description: string;
example: string; example: string;
} }
export const FILENAME_TEMPLATE_VARIABLES: TemplateToken[] = [ export const FILENAME_TEMPLATE_VARIABLES: TemplateToken[] = [
{ key: "{username}", description: "Author handle", example: "NASA" }, { key: "{handle}", description: "Author handle", example: "elonmusk" },
{ key: "{name}", description: "Author display name", example: "Elon Musk" },
{ key: "{date}", description: "Tweet date & time", example: "20250620_104556" }, { key: "{date}", description: "Tweet date & time", example: "20250620_104556" },
{ key: "{tweet_id}", description: "Tweet ID", example: "1989033613824815258" }, { key: "{tweet_id}", description: "Tweet ID", example: "1989033613824815258" },
{ key: "{index}", description: "Media position in tweet", example: "01" },
{ key: "{media_id}", description: "Unique media ID (prevents overwrites)", example: "Gx1aB2cXkAA7Yz9" }, { key: "{media_id}", description: "Unique media ID (prevents overwrites)", example: "Gx1aB2cXkAA7Yz9" },
{ key: "{type}", description: "Media type", example: "photo" }, { key: "{type}", description: "Media type", example: "photo" },
]; ];
export interface FilenameTemplateData { export interface FilenameTemplateData {
username?: string; username?: string;
accountName?: string;
date?: string; date?: string;
tweetId?: string; tweetId?: string;
index?: number; index?: number;
mediaID?: string;
type?: string; type?: string;
} }
export const SAMPLE_FILENAME_DATA: FilenameTemplateData = { export const SAMPLE_FILENAME_DATA: FilenameTemplateData = {
username: "NASA", username: "elonmusk",
accountName: "Elon Musk",
date: "20250620_104556", date: "20250620_104556",
tweetId: "1989033613824815258", tweetId: "1989033613824815258",
index: 1, index: 1,
mediaID: "Gx1aB2cXkAA7Yz9",
type: "photo", type: "photo",
}; };
function sanitizeTemplatePart(input: string): string {
const cleaned = input
.replace(/[\u0000-\u001f\\/:*?"<>|]/g, "")
.trim()
.replace(/[. ]+$/g, "");
return /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i.test(cleaned) ? `${cleaned}_` : cleaned;
}
export function renderFilenameTemplate(template: string, data: FilenameTemplateData): string { export function renderFilenameTemplate(template: string, data: FilenameTemplateData): string {
if (!template) if (!template)
return ""; return "";
const safe = (s: string) => s.replace(/[\\/:*?"<>|]/g, "").trim(); return sanitizeTemplatePart(template
return template .replace(/\{handle\}/g, sanitizeTemplatePart(data.username ?? ""))
.replace(/\{username\}/g, safe(data.username ?? "")) .replace(/\{name\}/g, sanitizeTemplatePart(data.accountName ?? ""))
.replace(/\{date\}/g, safe(data.date ?? "")) .replace(/\{username\}/g, sanitizeTemplatePart(data.username ?? ""))
.replace(/\{tweet_id\}/g, safe(data.tweetId ?? "")) .replace(/\{account_name\}/g, sanitizeTemplatePart(data.accountName ?? ""))
.replace(/\{date\}/g, sanitizeTemplatePart(data.date ?? ""))
.replace(/\{tweet_id\}/g, sanitizeTemplatePart(data.tweetId ?? ""))
.replace(/\{index\}/g, String(data.index ?? 1).padStart(2, "0")) .replace(/\{index\}/g, String(data.index ?? 1).padStart(2, "0"))
.replace(/\{type\}/g, safe(data.type ?? "")) .replace(/\{media_id\}/g, sanitizeTemplatePart(data.mediaID ?? ""))
.trim(); .replace(/\{type\}/g, sanitizeTemplatePart(data.type ?? ""))
.trim());
} }
export const DEFAULT_FOLDER_TEMPLATE = "{username}"; export const DEFAULT_FOLDER_TEMPLATE = "{handle}";
export const FOLDER_TEMPLATE_VARIABLES: TemplateToken[] = [ export const FOLDER_TEMPLATE_VARIABLES: TemplateToken[] = [
{ key: "{username}", description: "Author handle", example: "NASA" }, { key: "{handle}", description: "Author handle", example: "elonmusk" },
{ key: "{name}", description: "Author display name", example: "Elon Musk" },
{ key: "{date}", description: "Download date", example: "20250620" }, { key: "{date}", description: "Download date", example: "20250620" },
]; ];
export interface FolderTemplateData { export interface FolderTemplateData {
username?: string; username?: string;
accountName?: string;
date?: string; date?: string;
} }
export const SAMPLE_FOLDER_DATA: FolderTemplateData = { export const SAMPLE_FOLDER_DATA: FolderTemplateData = {
username: "NASA", username: "elonmusk",
accountName: "Elon Musk",
date: "20250620", date: "20250620",
}; };
export function renderFolderTemplate(template: string, data: FolderTemplateData): string { export function renderFolderTemplate(template: string, data: FolderTemplateData): string {
if (!template) if (!template)
return ""; return "";
const safe = (s: string) => s.replace(/[\\/:*?"<>|]/g, "").trim(); return sanitizeTemplatePart(template
return template .replace(/\{handle\}/g, sanitizeTemplatePart(data.username ?? ""))
.replace(/\{username\}/g, safe(data.username ?? "")) .replace(/\{name\}/g, sanitizeTemplatePart(data.accountName ?? ""))
.replace(/\{date\}/g, safe(data.date ?? "")) .replace(/\{username\}/g, sanitizeTemplatePart(data.username ?? ""))
.trim(); .replace(/\{account_name\}/g, sanitizeTemplatePart(data.accountName ?? ""))
.replace(/\{date\}/g, sanitizeTemplatePart(data.date ?? ""))
.trim());
} }
const DEFAULT_CONCURRENT_DOWNLOADS = 10; const DEFAULT_CONCURRENT_DOWNLOADS = 10;
const MIN_CONCURRENT_DOWNLOADS = 1; const MIN_CONCURRENT_DOWNLOADS = 1;
@@ -137,6 +156,7 @@ export interface Settings {
fontFamily: FontFamily; fontFamily: FontFamily;
customFonts: CustomFontOption[]; customFonts: CustomFontOption[];
sfxEnabled: boolean; sfxEnabled: boolean;
autoConvertGifs: boolean;
gifQuality: GifQuality; gifQuality: GifQuality;
gifResolution: GifResolution; gifResolution: GifResolution;
proxy: string; proxy: string;
@@ -164,6 +184,7 @@ export const DEFAULT_SETTINGS: Settings = {
fontFamily: "google-sans", fontFamily: "google-sans",
customFonts: [], customFonts: [],
sfxEnabled: true, sfxEnabled: true,
autoConvertGifs: false,
gifQuality: "fast", gifQuality: "fast",
gifResolution: "original", gifResolution: "original",
proxy: "", proxy: "",
@@ -428,6 +449,21 @@ function normalizeRetryAttempts(value: unknown): number {
} }
return rounded; return rounded;
} }
function normalizeTemplateTokens(value: unknown, fallback: string): string {
if (typeof value !== "string") {
return fallback;
}
return value
.replace(/\{username\}/g, "{handle}")
.replace(/\{account_name\}/g, "{name}");
}
function normalizeFilenameTemplate(value: unknown): string {
const template = normalizeTemplateTokens(value, DEFAULT_FILENAME_TEMPLATE);
return template === "{handle}_{date}_{tweet_id}_{index}" ? DEFAULT_FILENAME_TEMPLATE : template;
}
function normalizeFolderTemplate(value: unknown): string {
return normalizeTemplateTokens(value, DEFAULT_FOLDER_TEMPLATE);
}
export function getFontOptions(customFonts: CustomFontOption[] = []): FontOption[] { export function getFontOptions(customFonts: CustomFontOption[] = []): FontOption[] {
return [...FONT_OPTIONS, ...normalizeCustomFonts(customFonts)]; return [...FONT_OPTIONS, ...normalizeCustomFonts(customFonts)];
} }
@@ -480,6 +516,9 @@ function toNormalizedSettings(settings: Partial<Settings>): Settings {
skipExistingFiles: normalizeBoolean(settings.skipExistingFiles, DEFAULT_SETTINGS.skipExistingFiles), skipExistingFiles: normalizeBoolean(settings.skipExistingFiles, DEFAULT_SETTINGS.skipExistingFiles),
deleteIncompleteFiles: normalizeBoolean(settings.deleteIncompleteFiles, DEFAULT_SETTINGS.deleteIncompleteFiles), deleteIncompleteFiles: normalizeBoolean(settings.deleteIncompleteFiles, DEFAULT_SETTINGS.deleteIncompleteFiles),
retryAttempts: normalizeRetryAttempts(settings.retryAttempts), retryAttempts: normalizeRetryAttempts(settings.retryAttempts),
autoConvertGifs: normalizeBoolean(settings.autoConvertGifs, DEFAULT_SETTINGS.autoConvertGifs),
filenameTemplate: normalizeFilenameTemplate(settings.filenameTemplate),
folderTemplate: normalizeFolderTemplate(settings.folderTemplate),
customFonts, customFonts,
fontFamily: normalizeFontFamily(settings.fontFamily, customFonts), fontFamily: normalizeFontFamily(settings.fontFamily, customFonts),
}; };
+1
View File
@@ -44,6 +44,7 @@ export interface TimelineEntry {
verified?: boolean; verified?: boolean;
original_filename?: string; original_filename?: string;
author_username?: string; author_username?: string;
author_name?: string;
} }
export interface ExtractMetadata { export interface ExtractMetadata {
new_entries: number; new_entries: number;
+8
View File
@@ -187,6 +187,7 @@ export namespace main {
content?: string; content?: string;
original_filename?: string; original_filename?: string;
author_username?: string; author_username?: string;
account_name?: string;
static createFrom(source: any = {}) { static createFrom(source: any = {}) {
return new MediaItemRequest(source); return new MediaItemRequest(source);
@@ -201,6 +202,7 @@ export namespace main {
this.content = source["content"]; this.content = source["content"];
this.original_filename = source["original_filename"]; this.original_filename = source["original_filename"];
this.author_username = source["author_username"]; this.author_username = source["author_username"];
this.account_name = source["account_name"];
} }
} }
export class DownloadMediaWithMetadataRequest { export class DownloadMediaWithMetadataRequest {
@@ -214,6 +216,9 @@ export namespace main {
proxy?: string; proxy?: string;
filename_template?: string; filename_template?: string;
folder_template?: string; folder_template?: string;
auto_convert_gifs?: boolean;
gif_quality?: string;
gif_resolution?: string;
static createFrom(source: any = {}) { static createFrom(source: any = {}) {
return new DownloadMediaWithMetadataRequest(source); return new DownloadMediaWithMetadataRequest(source);
@@ -231,6 +236,9 @@ export namespace main {
this.proxy = source["proxy"]; this.proxy = source["proxy"];
this.filename_template = source["filename_template"]; this.filename_template = source["filename_template"];
this.folder_template = source["folder_template"]; this.folder_template = source["folder_template"];
this.auto_convert_gifs = source["auto_convert_gifs"];
this.gif_quality = source["gif_quality"];
this.gif_resolution = source["gif_resolution"];
} }
convertValues(a: any, classs: any, asMap: boolean = false): any { convertValues(a: any, classs: any, asMap: boolean = false): any {
+1 -1
View File
@@ -11,7 +11,7 @@
}, },
"info": { "info": {
"productName": "Twitter/X Media Batch Downloader", "productName": "Twitter/X Media Batch Downloader",
"productVersion": "4.7" "productVersion": "4.9"
}, },
"wailsjsdir": "./frontend", "wailsjsdir": "./frontend",
"assetdir": "./frontend/dist", "assetdir": "./frontend/dist",