This commit is contained in:
429Enjoyer committed 2026-06-22 14:08:53 +07:00
1 parent e05a9379fc
commit c42808431c
31 files changed
+3187 -2798

No files matched your search

+39 -11
View File
@@ -151,8 +151,28 @@ jobs:
retention-days: 7
build-linux:
name: Build Linux
runs-on: ubuntu-24.04
name: Build Linux (${{ matrix.display_name }})
runs-on: ${{ matrix.runner }}
strategy:
fail-fast: false
matrix:
include:
- display_name: amd64
runner: ubuntu-24.04
wails_platform: linux/amd64
artifact_name: linux-portable
output_name: TwitterXMediaBatchDownloader.AppImage
appimage_arch: x86_64
appimagetool_arch: x86_64
pkgconfig_dir: /usr/lib/x86_64-linux-gnu/pkgconfig
- display_name: arm64
runner: ubuntu-24.04-arm
wails_platform: linux/arm64
artifact_name: linux-portable-arm
output_name: TwitterXMediaBatchDownloader-ARM.AppImage
appimage_arch: aarch64
appimagetool_arch: aarch64
pkgconfig_dir: /usr/lib/aarch64-linux-gnu/pkgconfig
steps:
- name: Checkout code
uses: actions/checkout@v4
@@ -189,7 +209,7 @@ jobs:
run: |
sudo apt-get update
sudo apt-get install -y libgtk-3-dev libwebkit2gtk-4.1-dev libfuse2 imagemagick upx-ucl
sudo ln -sf /usr/lib/x86_64-linux-gnu/pkgconfig/webkit2gtk-4.1.pc /usr/lib/x86_64-linux-gnu/pkgconfig/webkit2gtk-4.0.pc
sudo ln -sf "${{ matrix.pkgconfig_dir }}/webkit2gtk-4.1.pc" "${{ matrix.pkgconfig_dir }}/webkit2gtk-4.0.pc"
- name: Install Wails CLI
run: go install github.com/wailsapp/wails/v2/cmd/wails@latest
@@ -201,7 +221,7 @@ jobs:
pnpm run generate-icon
- name: Build application
run: wails build -platform linux/amd64
run: wails build -platform ${{ matrix.wails_platform }}
- name: Compress with UPX
run: upx --best --lzma "build/bin/${{ env.APP_NAME }}"
@@ -211,13 +231,13 @@ jobs:
uses: actions/cache@v4
with:
path: appimagetool
key: appimagetool-x86_64-v2
key: appimagetool-${{ matrix.appimagetool_arch }}-v2
- name: Download appimagetool
if: steps.cache-appimagetool.outputs.cache-hit != 'true'
run: |
wget --timeout=30 --tries=5 --retry-connrefused --waitretry=5 -O appimagetool "https://github.com/AppImage/appimagetool/releases/download/continuous/appimagetool-x86_64.AppImage" || \
wget --timeout=30 --tries=5 --retry-connrefused --waitretry=5 -O appimagetool "https://github.com/AppImage/appimagetool/releases/download/1.9.1/appimagetool-x86_64.AppImage"
wget --timeout=30 --tries=5 --retry-connrefused --waitretry=5 -O appimagetool "https://github.com/AppImage/appimagetool/releases/download/continuous/appimagetool-${{ matrix.appimagetool_arch }}.AppImage" || \
wget --timeout=30 --tries=5 --retry-connrefused --waitretry=5 -O appimagetool "https://github.com/AppImage/appimagetool/releases/download/1.9.1/appimagetool-${{ matrix.appimagetool_arch }}.AppImage"
- name: Make appimagetool executable
run: chmod +x appimagetool
@@ -266,13 +286,13 @@ jobs:
chmod +x AppDir/AppRun
mkdir -p dist
ARCH=x86_64 ./appimagetool --no-appstream AppDir "dist/${{ env.APP_NAME }}.AppImage"
ARCH=${{ matrix.appimage_arch }} ./appimagetool --no-appstream AppDir "dist/${{ matrix.output_name }}"
- name: Upload artifacts
uses: actions/upload-artifact@v4
with:
name: linux-portable
path: dist/${{ env.APP_NAME }}.AppImage
name: ${{ matrix.artifact_name }}
path: dist/${{ matrix.output_name }}
retention-days: 7
create-release:
@@ -307,7 +327,8 @@ jobs:
- `TwitterXMediaBatchDownloader.exe` - Windows
- `TwitterXMediaBatchDownloader.dmg` - macOS
- `TwitterXMediaBatchDownloader.AppImage` - Linux
- `TwitterXMediaBatchDownloader.AppImage` - Linux AMD64
- `TwitterXMediaBatchDownloader-ARM.AppImage` - Linux ARM64
<details>
<summary><b>Linux Requirements</b></summary>
@@ -335,10 +356,17 @@ jobs:
./TwitterXMediaBatchDownloader.AppImage
```
For ARM64:
```bash
chmod +x TwitterXMediaBatchDownloader-ARM.AppImage
./TwitterXMediaBatchDownloader-ARM.AppImage
```
</details>
files: |
artifacts/windows-portable/${{ env.APP_NAME }}.exe
artifacts/macos-portable/${{ env.APP_NAME }}.dmg
artifacts/linux-portable/${{ env.APP_NAME }}.AppImage
artifacts/linux-portable-arm/${{ env.APP_NAME }}-ARM.AppImage
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+2
View File
@@ -14,6 +14,8 @@ A GUI tool to download original-quality images and videos from Twitter/X account
- 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)
## How to Obtain Auth Token
> [!Warning]
+55 -16
View File
@@ -44,14 +44,20 @@ func (a *App) CleanupExtractorProcesses() {
}
type TimelineRequest struct {
Username string `json:"username"`
AuthToken string `json:"auth_token"`
TimelineType string `json:"timeline_type"`
BatchSize int `json:"batch_size"`
Page int `json:"page"`
MediaType string `json:"media_type"`
Retweets bool `json:"retweets"`
Cursor string `json:"cursor,omitempty"`
Username string `json:"username"`
AuthToken string `json:"auth_token"`
TimelineType string `json:"timeline_type"`
BatchSize int `json:"batch_size"`
Page int `json:"page"`
MediaType string `json:"media_type"`
Retweets bool `json:"retweets"`
Cursor string `json:"cursor,omitempty"`
IncludePhotos bool `json:"include_photos"`
IncludeVideos bool `json:"include_videos"`
IncludeGifs bool `json:"include_gifs"`
IncludeText bool `json:"include_text"`
VideoQuality string `json:"video_quality,omitempty"`
ImageSize string `json:"image_size,omitempty"`
}
type DateRangeRequest struct {
@@ -73,14 +79,20 @@ func (a *App) ExtractTimeline(req TimelineRequest) (string, error) {
}
backendReq := backend.TimelineRequest{
Username: req.Username,
AuthToken: req.AuthToken,
TimelineType: req.TimelineType,
BatchSize: req.BatchSize,
Page: req.Page,
MediaType: req.MediaType,
Retweets: req.Retweets,
Cursor: req.Cursor,
Username: req.Username,
AuthToken: req.AuthToken,
TimelineType: req.TimelineType,
BatchSize: req.BatchSize,
Page: req.Page,
MediaType: req.MediaType,
Retweets: req.Retweets,
Cursor: req.Cursor,
IncludePhotos: req.IncludePhotos,
IncludeVideos: req.IncludeVideos,
IncludeGifs: req.IncludeGifs,
IncludeText: req.IncludeText,
VideoQuality: req.VideoQuality,
ImageSize: req.ImageSize,
}
response, err := backend.ExtractTimeline(backendReq)
@@ -147,6 +159,29 @@ func (a *App) OpenFolder(path string) error {
return nil
}
type DownloadProfileImageRequest struct {
URL string `json:"url"`
OutputDir string `json:"output_dir"`
Username string `json:"username"`
Kind string `json:"kind"`
Proxy string `json:"proxy,omitempty"`
}
func (a *App) DownloadProfileImage(req DownloadProfileImageRequest) (string, error) {
if req.URL == "" {
return "", fmt.Errorf("image url is required")
}
outputDir := req.OutputDir
if outputDir == "" {
outputDir = backend.GetDefaultDownloadPath()
}
path, err := backend.DownloadProfileImage(req.URL, outputDir, req.Username, req.Kind, req.Proxy)
if err != nil {
return "", err
}
return path, nil
}
func (a *App) SelectFolder(defaultPath string) (string, error) {
return backend.SelectFolderDialog(a.ctx, defaultPath)
}
@@ -219,6 +254,8 @@ type DownloadMediaWithMetadataRequest struct {
DeleteIncompleteFiles bool `json:"delete_incomplete_files"`
RetryAttempts int `json:"retry_attempts,omitempty"`
Proxy string `json:"proxy,omitempty"`
FilenameTemplate string `json:"filename_template,omitempty"`
FolderTemplate string `json:"folder_template,omitempty"`
}
type DownloadMediaResponse struct {
@@ -363,6 +400,8 @@ func (a *App) DownloadMediaWithMetadata(req DownloadMediaWithMetadataRequest) (D
SkipExistingFiles: req.SkipExisting,
DeleteIncompleteFiles: req.DeleteIncompleteFiles,
RetryAttempts: req.RetryAttempts,
FilenameTemplate: req.FilenameTemplate,
FolderTemplate: req.FolderTemplate,
}
downloaded, skipped, failed, err := backend.DownloadMediaWithMetadataProgressAndStatus(
+43 -17
View File
@@ -43,14 +43,23 @@ type AccountListItem struct {
}
var db *sql.DB
var dbInitOnce sync.Once
var dbInitErr error
var dbInitMu sync.Mutex
var dbInitialized bool
func ensureDB() error {
dbInitOnce.Do(func() {
dbInitErr = initDBInternal()
})
return dbInitErr
dbInitMu.Lock()
defer dbInitMu.Unlock()
if dbInitialized && db != nil {
return nil
}
if err := initDBInternal(); err != nil {
return err
}
dbInitialized = true
return nil
}
type accountMetricsPayload struct {
@@ -273,7 +282,31 @@ func backfillAccountMetrics() error {
if err != nil {
return err
}
defer rows.Close()
type metricUpdate struct {
id int64
followersCount int
statusesCount int
}
var updates []metricUpdate
for rows.Next() {
var id int64
var responseJSON string
if err := rows.Scan(&id, &responseJSON); err != nil {
continue
}
followersCount, statusesCount := extractAccountMetrics(responseJSON)
updates = append(updates, metricUpdate{id, followersCount, statusesCount})
}
if err := rows.Err(); err != nil {
rows.Close()
return err
}
rows.Close()
if len(updates) == 0 {
return nil
}
stmt, err := db.Prepare(`
UPDATE accounts
@@ -285,20 +318,13 @@ func backfillAccountMetrics() error {
}
defer stmt.Close()
for rows.Next() {
var id int64
var responseJSON string
if err := rows.Scan(&id, &responseJSON); err != nil {
continue
}
followersCount, statusesCount := extractAccountMetrics(responseJSON)
if _, err := stmt.Exec(followersCount, statusesCount, id); err != nil {
for _, u := range updates {
if _, err := stmt.Exec(u.followersCount, u.statusesCount, u.id); err != nil {
return err
}
}
return rows.Err()
return nil
}
func UpdateAccountGroup(id int64, groupName, groupColor string) error {
+86 -2
View File
@@ -47,6 +47,8 @@ type DownloadOptions struct {
SkipExistingFiles bool
DeleteIncompleteFiles bool
RetryAttempts int
FilenameTemplate string
FolderTemplate string
}
func NormalizeDownloadOptions(options DownloadOptions) DownloadOptions {
@@ -258,6 +260,7 @@ func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir str
tweetMediaCount := make(map[string]map[int64]int)
tasks := make([]downloadTask, 0, total)
downloadDate := time.Now().Format("20060102")
for i, item := range items {
@@ -284,7 +287,7 @@ func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir str
subfolder = "other"
}
baseDir := filepath.Join(outputDir, itemUsername)
baseDir := filepath.Join(outputDir, renderFolder(options.FolderTemplate, itemUsername, downloadDate))
if err := os.MkdirAll(baseDir, 0755); err != nil {
continue
}
@@ -301,7 +304,12 @@ func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir str
tweetMediaCount[itemUsername][item.TweetID]++
mediaIndex := tweetMediaCount[itemUsername][item.TweetID]
filename := fmt.Sprintf("%s_%s_%d_%02d%s", itemUsername, timestamp, item.TweetID, mediaIndex, ext)
mediaID := item.OriginalFilename
if mediaID == "" {
mediaID = ExtractOriginalFilename(item.URL)
}
filename := renderFilename(options.FilenameTemplate, itemUsername, timestamp, item.TweetID, item.Type, mediaIndex, mediaID) + ext
outputPath := filepath.Join(typeDir, filename)
tasks = append(tasks, downloadTask{
@@ -519,6 +527,54 @@ func formatTimestamp(dateStr string) string {
return "00000000_000000"
}
func renderFilename(template, username, timestamp string, tweetID int64, mediaType string, index int, mediaID string) string {
if strings.TrimSpace(template) == "" {
template = "{username}_{date}_{tweet_id}_{index}"
}
replacer := strings.NewReplacer(
"{username}", sanitizeFilenamePart(username),
"{date}", timestamp,
"{tweet_id}", fmt.Sprintf("%d", tweetID),
"{index}", fmt.Sprintf("%02d", index),
"{media_id}", sanitizeFilenamePart(mediaID),
"{type}", sanitizeFilenamePart(mediaType),
)
name := strings.TrimSpace(replacer.Replace(template))
if name == "" {
name = fmt.Sprintf("%s_%s_%d_%02d", username, timestamp, tweetID, index)
}
if mediaID != "" && !strings.Contains(template, "{media_id}") {
name = name + "_" + sanitizeFilenamePart(mediaID)
}
return name
}
func renderFolder(template, username, date string) string {
if strings.TrimSpace(template) == "" {
template = "{username}"
}
replacer := strings.NewReplacer(
"{username}", sanitizeFilenamePart(username),
"{date}", date,
)
name := strings.TrimSpace(replacer.Replace(template))
if name == "" {
name = sanitizeFilenamePart(username)
}
return name
}
func sanitizeFilenamePart(s string) string {
return strings.TrimSpace(strings.Map(func(r rune) rune {
switch r {
case '\\', '/', ':', '*', '?', '"', '<', '>', '|':
return -1
}
return r
}, s))
}
func getExtension(mediaURL string, mediaType string) string {
parsedURL, err := url.Parse(mediaURL)
if err != nil {
@@ -589,3 +645,31 @@ func downloadFile(client *http.Client, url, outputPath string) error {
RetryAttempts: 0,
})
}
func DownloadProfileImage(imageURL, outputDir, username, kind, customProxy string) (string, error) {
if strings.TrimSpace(imageURL) == "" {
return "", fmt.Errorf("no %s url available", kind)
}
baseDir := outputDir
if username != "" {
baseDir = filepath.Join(outputDir, username)
}
if err := os.MkdirAll(baseDir, 0755); err != nil {
return "", fmt.Errorf("failed to create output directory: %v", err)
}
ext := getExtension(imageURL, "photo")
filename := fmt.Sprintf("%s_%s%s", sanitizeFilenamePart(username), kind, ext)
outputPath := filepath.Join(baseDir, filename)
client, err := CreateHTTPClient(customProxy, 60*time.Second)
if err != nil {
client = &http.Client{Timeout: 60 * time.Second}
}
if err := downloadFile(client, imageURL, outputPath); err != nil {
return "", fmt.Errorf("failed to download %s: %v", kind, err)
}
return outputPath, nil
}
+4 -2
View File
@@ -144,8 +144,11 @@ func getExtractorAssetName() (string, error) {
return "windows-amd64.zip", nil
}
case "linux":
if runtime.GOARCH == "amd64" {
switch runtime.GOARCH {
case "amd64":
return "linux-amd64.zip", nil
case "arm64":
return "linux-arm64.zip", nil
}
case "darwin":
switch resolveMacOSExtractorArch(runtime.GOARCH, detectMacOSHardwareArch()) {
@@ -172,7 +175,6 @@ func detectMacOSHardwareArch() string {
return ""
}
// On Apple Silicon, this stays "1" even if the app itself runs under Rosetta.
cmd := exec.Command("sysctl", "-in", "hw.optional.arm64")
hideWindow(cmd)
output, err := cmd.Output()
+3 -3
View File
@@ -17,9 +17,9 @@ import (
)
const (
ffmpegReleaseAPIURL = "https://api.github.com/repos/afkarxyz/ffmpeg-binaries/releases/latest"
ffmpegLatestReleaseURL = "https://github.com/afkarxyz/ffmpeg-binaries/releases/latest"
ffmpegLatestDownloadBaseURL = "https://github.com/afkarxyz/ffmpeg-binaries/releases/latest/download"
ffmpegReleaseAPIURL = "https://api.github.com/repos/spotbye/Dependencies/releases/tags/FFmpeg-8.1"
ffmpegLatestReleaseURL = "https://github.com/spotbye/Dependencies/releases/tag/FFmpeg-8.1"
ffmpegLatestDownloadBaseURL = "https://github.com/spotbye/Dependencies/releases/download/FFmpeg-8.1"
)
var ffmpegVersionPattern = regexp.MustCompile(`^[0-9]+(?:\.[0-9]+)+`)
+1 -1
View File
@@ -13,7 +13,7 @@ import (
)
var (
filenameSafeRegex = regexp.MustCompile(`^[A-Za-z0-9_]+$`)
filenameSafeRegex = regexp.MustCompile(`^[A-Za-z0-9_]+$`)
filenameLetterRegex = regexp.MustCompile(`[A-Za-z]`)
)
+408 -317
View File
@@ -9,6 +9,7 @@ import (
"os/exec"
"path/filepath"
"runtime"
"sort"
"strings"
"sync"
)
@@ -110,11 +111,11 @@ func parseExtractorError(output string, username string) string {
var hint string
if strings.Contains(outputLower, "unable to retrieve tweets from this timeline") {
hint = " [Hint: End of timeline reached or rate limited - data already fetched has been saved]"
} else if strings.Contains(outputLower, "rate limit") || strings.Contains(output, "429") {
} else if strings.Contains(outputLower, "rate limit") || strings.Contains(outputLower, "rate_limited") || strings.Contains(output, "429") {
hint = " [Hint: Wait 5-15 minutes before retrying]"
} else if strings.Contains(output, "401") || strings.Contains(outputLower, "unauthorized") {
} else if strings.Contains(output, "401") || strings.Contains(outputLower, "unauthorized") || strings.Contains(outputLower, "auth_invalid") {
hint = " [Hint: Auth token may be invalid or expired]"
} else if strings.Contains(output, "404") {
} else if strings.Contains(output, "404") || strings.Contains(outputLower, "user_not_found") {
hint = fmt.Sprintf(" [Hint: @%s may not exist or is suspended]", username)
} else if strings.Contains(outputLower, "protected") || strings.Contains(output, "403") {
hint = " [Hint: Protected account - need to follow and use auth token]"
@@ -149,85 +150,103 @@ func (t *TweetIDString) UnmarshalJSON(data []byte) error {
return fmt.Errorf("tweet_id must be number or string")
}
type Author struct {
ID int64 `json:"id"`
type richThumb struct {
Name string `json:"name"`
Nick string `json:"nick"`
URL string `json:"url"`
}
type UserInfo struct {
ID int64 `json:"id"`
Name string `json:"name"`
Nick string `json:"nick"`
Location string `json:"location"`
Date string `json:"date"`
Verified bool `json:"verified"`
Protected bool `json:"protected"`
ProfileBanner string `json:"profile_banner"`
ProfileImage string `json:"profile_image"`
FavouritesCount int `json:"favourites_count"`
FollowersCount int `json:"followers_count"`
FriendsCount int `json:"friends_count"`
ListedCount int `json:"listed_count"`
MediaCount int `json:"media_count"`
StatusesCount int `json:"statuses_count"`
Description string `json:"description"`
URL string `json:"url"`
type richSize struct {
W int `json:"w"`
H int `json:"h"`
Resize string `json:"resize"`
URL string `json:"url"`
}
type CLIMediaItem struct {
URL string `json:"url"`
TweetID TweetIDString `json:"tweet_id"`
RetweetID TweetIDString `json:"retweet_id"`
QuoteID TweetIDString `json:"quote_id"`
ReplyID TweetIDString `json:"reply_id"`
ConversationID TweetIDString `json:"conversation_id"`
Date string `json:"date"`
Extension string `json:"extension"`
Width int `json:"width"`
Height int `json:"height"`
Type string `json:"type"`
Bitrate int `json:"bitrate"`
Duration float64 `json:"duration"`
Author UserInfo `json:"author"`
User UserInfo `json:"user"`
Content string `json:"content"`
FavoriteCount int `json:"favorite_count"`
RetweetCount int `json:"retweet_count"`
ReplyCount int `json:"reply_count"`
QuoteCount int `json:"quote_count"`
BookmarkCount int `json:"bookmark_count"`
ViewCount int `json:"view_count"`
Source string `json:"source"`
Sensitive bool `json:"sensitive"`
type richVariant struct {
ContentType string `json:"content_type"`
URL string `json:"url"`
Bitrate int `json:"bitrate"`
Resolution string `json:"resolution"`
}
type TweetMetadata struct {
TweetID TweetIDString `json:"tweet_id"`
RetweetID TweetIDString `json:"retweet_id,omitempty"`
QuoteID TweetIDString `json:"quote_id,omitempty"`
ReplyID TweetIDString `json:"reply_id,omitempty"`
ConversationID TweetIDString `json:"conversation_id,omitempty"`
Date string `json:"date"`
Author Author `json:"author"`
Content string `json:"content"`
Lang string `json:"lang,omitempty"`
Hashtags []string `json:"hashtags,omitempty"`
FavoriteCount int `json:"favorite_count"`
RetweetCount int `json:"retweet_count"`
QuoteCount int `json:"quote_count,omitempty"`
ReplyCount int `json:"reply_count,omitempty"`
BookmarkCount int `json:"bookmark_count,omitempty"`
ViewCount int `json:"view_count,omitempty"`
Sensitive bool `json:"sensitive,omitempty"`
type richMedia struct {
Type string `json:"type"`
MediaID string `json:"media_id"`
MediaKey string `json:"media_key"`
Thumbnail string `json:"thumbnail"`
ExpandedURL string `json:"expanded_url"`
Width int `json:"width"`
Height int `json:"height"`
AspectRatio []int `json:"aspect_ratio"`
DurationMS int `json:"duration_ms"`
AltText string `json:"alt_text"`
Sizes map[string]richSize `json:"sizes"`
Thumbs []richThumb `json:"thumbs"`
Variants []richVariant `json:"variants"`
}
type CLIResponse struct {
Media []CLIMediaItem `json:"media"`
Metadata []TweetMetadata `json:"metadata"`
Cursor string `json:"cursor,omitempty"`
Total int `json:"total,omitempty"`
Completed bool `json:"completed,omitempty"`
type richMiniUser struct {
UserID string `json:"user_id"`
Username string `json:"username"`
Name string `json:"name"`
Avatar string `json:"avatar"`
Verified bool `json:"verified"`
BlueVerified bool `json:"blue_verified"`
}
type richStats struct {
Likes int `json:"likes"`
Retweets int `json:"retweets"`
Replies int `json:"replies"`
Quotes int `json:"quotes"`
Bookmarks int `json:"bookmarks"`
Views int `json:"views"`
}
type richTweet struct {
TweetID string `json:"tweet_id"`
URL string `json:"url"`
Text string `json:"text"`
Lang string `json:"lang"`
CreatedAt string `json:"created_at"`
Source string `json:"source"`
Sensitive bool `json:"sensitive"`
IsRepost bool `json:"is_repost"`
IsReply bool `json:"is_reply"`
IsQuote bool `json:"is_quote"`
RepostedBy *richMiniUser `json:"reposted_by"`
Author richMiniUser `json:"author"`
Stats richStats `json:"stats"`
Media []richMedia `json:"media"`
Hashtags []string `json:"hashtags"`
}
type richAccount struct {
ID string `json:"id"`
Username string `json:"username"`
Name string `json:"name"`
Bio string `json:"bio"`
Avatar string `json:"avatar"`
AvatarVariants []richThumb `json:"avatar_variants"`
Banner string `json:"banner"`
BannerVariants []richThumb `json:"banner_variants"`
Location string `json:"location"`
URL string `json:"url"`
CreatedAt string `json:"created_at"`
Followers int `json:"followers"`
Following int `json:"following"`
Tweets int `json:"tweets"`
MediaCount int `json:"media_count"`
Protected bool `json:"protected"`
Verified bool `json:"verified"`
BlueVerified bool `json:"blue_verified"`
}
type richResponse struct {
Account richAccount `json:"account"`
Tweets []richTweet `json:"tweets"`
NextCursor string `json:"next_cursor"`
HasMore bool `json:"has_more"`
}
type TimelineEntry struct {
@@ -239,12 +258,16 @@ type TimelineEntry struct {
Extension string `json:"extension"`
Width int `json:"width"`
Height int `json:"height"`
Thumbnail string `json:"thumbnail,omitempty"`
DurationMS int `json:"duration_ms,omitempty"`
AltText string `json:"alt_text,omitempty"`
Content string `json:"content,omitempty"`
ViewCount int `json:"view_count,omitempty"`
BookmarkCount int `json:"bookmark_count,omitempty"`
FavoriteCount int `json:"favorite_count,omitempty"`
RetweetCount int `json:"retweet_count,omitempty"`
ReplyCount int `json:"reply_count,omitempty"`
QuoteCount int `json:"quote_count,omitempty"`
Source string `json:"source,omitempty"`
Verified bool `json:"verified,omitempty"`
OriginalFilename string `json:"original_filename,omitempty"`
@@ -252,13 +275,23 @@ type TimelineEntry struct {
}
type AccountInfo struct {
Name string `json:"name"`
Nick string `json:"nick"`
Date string `json:"date"`
FollowersCount int `json:"followers_count"`
FriendsCount int `json:"friends_count"`
ProfileImage string `json:"profile_image"`
StatusesCount int `json:"statuses_count"`
Name string `json:"name"`
Nick string `json:"nick"`
Date string `json:"date"`
FollowersCount int `json:"followers_count"`
FriendsCount int `json:"friends_count"`
ProfileImage string `json:"profile_image"`
StatusesCount int `json:"statuses_count"`
Bio string `json:"bio,omitempty"`
Banner string `json:"banner,omitempty"`
Location string `json:"location,omitempty"`
URL string `json:"url,omitempty"`
MediaCount int `json:"media_count,omitempty"`
Verified bool `json:"verified,omitempty"`
BlueVerified bool `json:"blue_verified,omitempty"`
Protected bool `json:"protected,omitempty"`
AvatarVariants []richThumb `json:"avatar_variants,omitempty"`
BannerVariants []richThumb `json:"banner_variants,omitempty"`
}
type ExtractMetadata struct {
@@ -280,14 +313,20 @@ type TwitterResponse struct {
}
type TimelineRequest struct {
Username string `json:"username"`
AuthToken string `json:"auth_token"`
TimelineType string `json:"timeline_type"`
BatchSize int `json:"batch_size"`
Page int `json:"page"`
MediaType string `json:"media_type"`
Retweets bool `json:"retweets"`
Cursor string `json:"cursor,omitempty"`
Username string `json:"username"`
AuthToken string `json:"auth_token"`
TimelineType string `json:"timeline_type"`
BatchSize int `json:"batch_size"`
Page int `json:"page"`
MediaType string `json:"media_type"`
Retweets bool `json:"retweets"`
Cursor string `json:"cursor,omitempty"`
IncludePhotos bool `json:"include_photos"`
IncludeVideos bool `json:"include_videos"`
IncludeGifs bool `json:"include_gifs"`
IncludeText bool `json:"include_text"`
VideoQuality string `json:"video_quality,omitempty"`
ImageSize string `json:"image_size,omitempty"`
}
type DateRangeRequest struct {
@@ -402,74 +441,250 @@ func buildSearchURL(username, startDate, endDate, mediaFilter string, includeRet
return fmt.Sprintf("https://x.com/search?q=%s&src=typed_query&f=live", query)
}
func convertMetadataToTimelineEntry(meta TweetMetadata) TimelineEntry {
return TimelineEntry{
URL: "",
Date: meta.Date,
TweetID: meta.TweetID,
Type: "text",
IsRetweet: meta.RetweetID != 0,
Extension: "txt",
Width: 0,
Height: 0,
Content: meta.Content,
ViewCount: meta.ViewCount,
BookmarkCount: meta.BookmarkCount,
FavoriteCount: meta.FavoriteCount,
RetweetCount: meta.RetweetCount,
ReplyCount: meta.ReplyCount,
AuthorUsername: meta.Author.Name,
}
func parseTweetID(s string) TweetIDString {
var n int64
_, _ = fmt.Sscanf(strings.TrimSpace(s), "%d", &n)
return TweetIDString(n)
}
func convertToTimelineEntry(media CLIMediaItem) TimelineEntry {
authorUsername := ""
if media.Author.Name != "" {
authorUsername = media.Author.Name
} else if media.User.Name != "" {
authorUsername = media.User.Name
func bestPhotoURL(m richMedia, size string) string {
if size == "" {
size = "orig"
}
entry := TimelineEntry{
URL: media.URL,
TweetID: media.TweetID,
Date: media.Date,
Extension: media.Extension,
Width: media.Width,
Height: media.Height,
IsRetweet: media.RetweetID != 0,
Content: media.Content,
ViewCount: media.ViewCount,
BookmarkCount: media.BookmarkCount,
FavoriteCount: media.FavoriteCount,
RetweetCount: media.RetweetCount,
ReplyCount: media.ReplyCount,
Source: media.Source,
Verified: media.Author.Verified,
AuthorUsername: authorUsername,
if size == "orig" {
for _, t := range m.Thumbs {
if t.Name == "orig" {
return t.URL
}
}
} else if s, ok := m.Sizes[size]; ok && s.URL != "" {
return s.URL
}
if s, ok := m.Sizes["large"]; ok && s.URL != "" {
return s.URL
}
if s, ok := m.Sizes["medium"]; ok && s.URL != "" {
return s.URL
}
if s, ok := m.Sizes["small"]; ok && s.URL != "" {
return s.URL
}
return m.Thumbnail
}
if media.Type != "" {
entry.Type = media.Type
} else {
switch strings.ToLower(media.Extension) {
case "mp4", "webm":
entry.Type = "video"
case "gif":
entry.Type = "gif"
default:
entry.Type = "photo"
func bestVideoURL(m richMedia, quality string) string {
mp4s := make([]richVariant, 0, len(m.Variants))
for _, v := range m.Variants {
if v.ContentType == "video/mp4" && v.URL != "" {
mp4s = append(mp4s, v)
}
}
if len(mp4s) == 0 {
if len(m.Variants) > 0 {
return m.Variants[len(m.Variants)-1].URL
}
return m.Thumbnail
}
sort.Slice(mp4s, func(i, j int) bool { return mp4s[i].Bitrate < mp4s[j].Bitrate })
return entry
switch quality {
case "lowest":
return mp4s[0].URL
case "", "highest":
return mp4s[len(mp4s)-1].URL
}
target := 0
_, _ = fmt.Sscanf(quality, "%d", &target)
if target == 0 {
return mp4s[len(mp4s)-1].URL
}
best := mp4s[0]
bestDelta := 1 << 30
for _, v := range mp4s {
h := resolutionHeight(v.Resolution)
delta := h - target
if delta < 0 {
delta = -delta
}
if delta < bestDelta {
bestDelta = delta
best = v
}
}
return best.URL
}
func getExtractorPath() string {
homeDir, _ := os.UserHomeDir()
baseDir := filepath.Join(homeDir, ".twitterxmediabatchdownloader")
return filepath.Join(baseDir, getExecutableName())
func resolutionHeight(resolution string) int {
if i := strings.Index(resolution, "x"); i >= 0 {
h := 0
_, _ = fmt.Sscanf(resolution[i+1:], "%d", &h)
return h
}
return 0
}
func previewURL(m richMedia) string {
for _, t := range m.Thumbs {
if t.Name == "360x360" {
return t.URL
}
}
if s, ok := m.Sizes["small"]; ok && s.URL != "" {
return s.URL
}
return m.Thumbnail
}
func extensionFor(downloadURL, mediaType string) string {
switch mediaType {
case "video", "gif", "animated_gif":
return "mp4"
}
if i := strings.Index(downloadURL, "format="); i >= 0 {
rest := downloadURL[i+len("format="):]
if amp := strings.IndexByte(rest, '&'); amp >= 0 {
rest = rest[:amp]
}
if rest != "" {
return rest
}
}
return "jpg"
}
func isVerified(u richMiniUser) bool {
return u.Verified || u.BlueVerified
}
func textEntry(t richTweet) TimelineEntry {
return TimelineEntry{
URL: "",
Date: t.CreatedAt,
TweetID: parseTweetID(t.TweetID),
Type: "text",
IsRetweet: t.IsRepost,
Extension: "txt",
Content: t.Text,
ViewCount: t.Stats.Views,
BookmarkCount: t.Stats.Bookmarks,
FavoriteCount: t.Stats.Likes,
RetweetCount: t.Stats.Retweets,
ReplyCount: t.Stats.Replies,
QuoteCount: t.Stats.Quotes,
Source: t.Source,
Verified: isVerified(t.Author),
AuthorUsername: t.Author.Username,
}
}
func mediaEntry(t richTweet, m richMedia, videoQuality, imageSize string) TimelineEntry {
var downloadURL string
switch m.Type {
case "video", "animated_gif", "gif":
downloadURL = bestVideoURL(m, videoQuality)
default:
downloadURL = bestPhotoURL(m, imageSize)
}
return TimelineEntry{
URL: downloadURL,
Date: t.CreatedAt,
TweetID: parseTweetID(t.TweetID),
Type: m.Type,
IsRetweet: t.IsRepost,
Extension: extensionFor(downloadURL, m.Type),
Width: m.Width,
Height: m.Height,
Thumbnail: previewURL(m),
DurationMS: m.DurationMS,
AltText: m.AltText,
Content: t.Text,
ViewCount: t.Stats.Views,
BookmarkCount: t.Stats.Bookmarks,
FavoriteCount: t.Stats.Likes,
RetweetCount: t.Stats.Retweets,
ReplyCount: t.Stats.Replies,
QuoteCount: t.Stats.Quotes,
Source: t.Source,
Verified: isVerified(t.Author),
AuthorUsername: t.Author.Username,
}
}
type FlattenOptions struct {
IncludePhotos bool
IncludeVideos bool
IncludeGifs bool
IncludeText bool
VideoQuality string
ImageSize string
}
func flattenTweets(tweets []richTweet, opts FlattenOptions) []TimelineEntry {
out := make([]TimelineEntry, 0, len(tweets))
for _, t := range tweets {
if len(t.Media) == 0 {
if opts.IncludeText && strings.TrimSpace(t.Text) != "" {
out = append(out, textEntry(t))
}
continue
}
for _, m := range t.Media {
switch m.Type {
case "photo":
if !opts.IncludePhotos {
continue
}
case "video":
if !opts.IncludeVideos {
continue
}
case "animated_gif", "gif":
if !opts.IncludeGifs {
continue
}
}
out = append(out, mediaEntry(t, m, opts.VideoQuality, opts.ImageSize))
}
}
return out
}
func buildAccountInfo(acc richAccount, fallbackUsername string) AccountInfo {
info := AccountInfo{
Name: fallbackUsername,
Nick: fallbackUsername,
}
if acc.Username != "" {
info.Name = acc.Username
}
if acc.Name != "" {
info.Nick = acc.Name
}
info.Date = acc.CreatedAt
info.FollowersCount = acc.Followers
info.FriendsCount = acc.Following
info.ProfileImage = acc.Avatar
info.StatusesCount = acc.Tweets
info.Bio = acc.Bio
info.Banner = acc.Banner
info.Location = acc.Location
info.URL = acc.URL
info.MediaCount = acc.MediaCount
info.Verified = acc.Verified
info.BlueVerified = acc.BlueVerified
info.Protected = acc.Protected
info.AvatarVariants = acc.AvatarVariants
info.BannerVariants = acc.BannerVariants
return info
}
func parseRichResponse(jsonStr string) (*richResponse, error) {
var resp richResponse
if err := json.Unmarshal([]byte(jsonStr), &resp); err != nil {
return nil, fmt.Errorf("json_error: Failed to parse JSON response: %v", err)
}
return &resp, nil
}
func ExtractTimeline(req TimelineRequest) (*TwitterResponse, error) {
@@ -479,26 +694,21 @@ func ExtractTimeline(req TimelineRequest) (*TwitterResponse, error) {
return nil, err
}
isTextOnly := req.MediaType == "text"
includeText := req.IncludeText
wantsRetweets := req.Retweets
timelineType := req.TimelineType
if timelineType == "" {
if isTextOnly {
timelineType = "tweets"
} else if wantsRetweets {
if includeText || wantsRetweets {
timelineType = "tweets"
} else {
timelineType = "media"
}
}
url := buildTwitterURL(req.Username, timelineType)
targetURL := buildTwitterURL(req.Username, timelineType)
args := []string{url}
args := []string{targetURL}
if req.AuthToken != "" {
args = append(args, "--auth-token", req.AuthToken)
@@ -520,21 +730,10 @@ func ExtractTimeline(req TimelineRequest) (*TwitterResponse, error) {
}
}
if isTextOnly {
if includeText {
args = append(args, "--text-tweets")
}
if req.MediaType != "" && req.MediaType != "all" && !isTextOnly {
switch req.MediaType {
case "image":
args = append(args, "--type", "photo")
case "video":
args = append(args, "--type", "video")
case "gif":
args = append(args, "--type", "animated_gif")
}
}
if req.Cursor != "" {
args = append(args, "--cursor", req.Cursor)
}
@@ -564,21 +763,12 @@ func ExtractTimeline(req TimelineRequest) (*TwitterResponse, error) {
return nil, fmt.Errorf("parse_error: Could not parse xtractor output. Raw output: %s", outputStr)
}
var cliResponse CLIResponse
if err := json.Unmarshal([]byte(jsonStr), &cliResponse); err != nil {
return nil, fmt.Errorf("json_error: Failed to parse JSON response: %v", err)
resp, err := parseRichResponse(jsonStr)
if err != nil {
return nil, err
}
timeline := make([]TimelineEntry, 0)
accountInfo := AccountInfo{
Name: req.Username,
Nick: req.Username,
}
mediaTweetIDs := make(map[int64]bool)
for _, media := range cliResponse.Media {
mediaTweetIDs[int64(media.TweetID)] = true
}
accountInfo := buildAccountInfo(resp.Account, req.Username)
isBookmarks := req.TimelineType == "bookmarks"
isLikes := req.TimelineType == "likes"
@@ -590,90 +780,15 @@ func ExtractTimeline(req TimelineRequest) (*TwitterResponse, error) {
accountInfo.Nick = "My Likes"
}
if isTextOnly {
for _, meta := range cliResponse.Metadata {
if !mediaTweetIDs[int64(meta.TweetID)] {
timeline = append(timeline, convertMetadataToTimelineEntry(meta))
}
}
if !isBookmarks && !isLikes {
if len(cliResponse.Media) > 0 {
user := cliResponse.Media[0].User
accountInfo.Name = user.Name
accountInfo.Nick = user.Nick
accountInfo.Date = user.Date
accountInfo.FollowersCount = user.FollowersCount
accountInfo.FriendsCount = user.FriendsCount
accountInfo.ProfileImage = user.ProfileImage
accountInfo.StatusesCount = user.StatusesCount
} else if len(cliResponse.Metadata) > 0 {
firstMeta := cliResponse.Metadata[0]
accountInfo.Name = firstMeta.Author.Name
accountInfo.Nick = firstMeta.Author.Nick
}
} else {
if len(cliResponse.Media) > 0 {
user := cliResponse.Media[0].User
accountInfo.Date = user.Date
accountInfo.FollowersCount = user.FollowersCount
accountInfo.FriendsCount = user.FriendsCount
accountInfo.ProfileImage = user.ProfileImage
accountInfo.StatusesCount = user.StatusesCount
}
}
} else if len(cliResponse.Media) > 0 {
timeline = make([]TimelineEntry, 0, len(cliResponse.Media))
for _, media := range cliResponse.Media {
timeline = append(timeline, convertToTimelineEntry(media))
}
user := cliResponse.Media[0].User
if !isBookmarks && !isLikes {
accountInfo.Name = user.Name
accountInfo.Nick = user.Nick
}
accountInfo.Date = user.Date
accountInfo.FollowersCount = user.FollowersCount
accountInfo.FriendsCount = user.FriendsCount
accountInfo.ProfileImage = user.ProfileImage
accountInfo.StatusesCount = user.StatusesCount
} else if len(cliResponse.Metadata) > 0 {
timeline = make([]TimelineEntry, 0, len(cliResponse.Metadata))
for _, meta := range cliResponse.Metadata {
entry := TimelineEntry{
URL: "",
TweetID: meta.TweetID,
Date: meta.Date,
Type: "text",
IsRetweet: meta.RetweetID != 0,
Extension: "txt",
Width: 0,
Height: 0,
Content: meta.Content,
ViewCount: meta.ViewCount,
BookmarkCount: meta.BookmarkCount,
FavoriteCount: meta.FavoriteCount,
RetweetCount: meta.RetweetCount,
ReplyCount: meta.ReplyCount,
AuthorUsername: meta.Author.Name,
}
timeline = append(timeline, entry)
}
if !isBookmarks && !isLikes {
firstMeta := cliResponse.Metadata[0]
accountInfo.Name = firstMeta.Author.Name
accountInfo.Nick = firstMeta.Author.Nick
}
}
hasMore := cliResponse.Cursor != "" && !cliResponse.Completed
timeline := flattenTweets(resp.Tweets, FlattenOptions{
IncludePhotos: req.IncludePhotos,
IncludeVideos: req.IncludeVideos,
IncludeGifs: req.IncludeGifs,
IncludeText: req.IncludeText,
VideoQuality: req.VideoQuality,
ImageSize: req.ImageSize,
})
completed := !resp.HasMore
response := &TwitterResponse{
AccountInfo: accountInfo,
@@ -683,12 +798,12 @@ func ExtractTimeline(req TimelineRequest) (*TwitterResponse, error) {
NewEntries: len(timeline),
Page: req.Page,
BatchSize: req.BatchSize,
HasMore: hasMore,
Cursor: cliResponse.Cursor,
Completed: cliResponse.Completed,
HasMore: resp.HasMore,
Cursor: resp.NextCursor,
Completed: completed,
},
Cursor: cliResponse.Cursor,
Completed: cliResponse.Completed,
Cursor: resp.NextCursor,
Completed: completed,
}
return response, nil
@@ -702,9 +817,9 @@ func ExtractDateRange(req DateRangeRequest) (*TwitterResponse, error) {
}
mediaFilter := strings.ToLower(strings.TrimSpace(req.MediaFilter))
url := buildSearchURL(req.Username, req.StartDate, req.EndDate, mediaFilter, req.Retweets)
targetURL := buildSearchURL(req.Username, req.StartDate, req.EndDate, mediaFilter, req.Retweets)
args := []string{url}
args := []string{targetURL}
if req.AuthToken != "" {
args = append(args, "--auth-token", req.AuthToken)
@@ -750,49 +865,19 @@ func ExtractDateRange(req DateRangeRequest) (*TwitterResponse, error) {
return nil, fmt.Errorf("parse_error: Could not parse xtractor output. Raw output: %s", outputStr)
}
var cliResponse CLIResponse
if err := json.Unmarshal([]byte(jsonStr), &cliResponse); err != nil {
return nil, fmt.Errorf("json_error: Failed to parse JSON response: %v", err)
resp, err := parseRichResponse(jsonStr)
if err != nil {
return nil, err
}
mediaTweetIDs := make(map[int64]bool)
for _, media := range cliResponse.Media {
mediaTweetIDs[int64(media.TweetID)] = true
}
timeline := make([]TimelineEntry, 0, len(cliResponse.Media)+len(cliResponse.Metadata))
for _, media := range cliResponse.Media {
timeline = append(timeline, convertToTimelineEntry(media))
}
if isTextOnly {
for _, meta := range cliResponse.Metadata {
if !mediaTweetIDs[int64(meta.TweetID)] {
timeline = append(timeline, convertMetadataToTimelineEntry(meta))
}
}
}
accountInfo := AccountInfo{
Name: req.Username,
Nick: req.Username,
}
if len(cliResponse.Media) > 0 {
user := cliResponse.Media[0].User
accountInfo.Name = user.Name
accountInfo.Nick = user.Nick
accountInfo.Date = user.Date
accountInfo.FollowersCount = user.FollowersCount
accountInfo.FriendsCount = user.FriendsCount
accountInfo.ProfileImage = user.ProfileImage
accountInfo.StatusesCount = user.StatusesCount
} else if len(cliResponse.Metadata) > 0 {
firstMeta := cliResponse.Metadata[0]
accountInfo.Name = firstMeta.Author.Name
accountInfo.Nick = firstMeta.Author.Nick
}
hasMore := cliResponse.Cursor != "" && !cliResponse.Completed
timeline := flattenTweets(resp.Tweets, FlattenOptions{
IncludePhotos: true,
IncludeVideos: true,
IncludeGifs: true,
IncludeText: isTextOnly,
})
accountInfo := buildAccountInfo(resp.Account, req.Username)
completed := !resp.HasMore
response := &TwitterResponse{
AccountInfo: accountInfo,
@@ -802,17 +887,23 @@ func ExtractDateRange(req DateRangeRequest) (*TwitterResponse, error) {
NewEntries: len(timeline),
Page: 0,
BatchSize: 0,
HasMore: hasMore,
Cursor: cliResponse.Cursor,
Completed: cliResponse.Completed,
HasMore: resp.HasMore,
Cursor: resp.NextCursor,
Completed: completed,
},
Cursor: cliResponse.Cursor,
Completed: cliResponse.Completed,
Cursor: resp.NextCursor,
Completed: completed,
}
return response, nil
}
func getExtractorPath() string {
homeDir, _ := os.UserHomeDir()
baseDir := filepath.Join(homeDir, ".twitterxmediabatchdownloader")
return filepath.Join(baseDir, getExecutableName())
}
func extractJSON(output string) string {
start := strings.Index(output, "{")
+28 -28
View File
@@ -12,42 +12,42 @@
"postinstall": "node scripts/generate-icon.js"
},
"dependencies": {
"@radix-ui/react-checkbox": "^1.3.3",
"@radix-ui/react-context-menu": "^2.2.16",
"@radix-ui/react-dialog": "^1.1.15",
"@radix-ui/react-dropdown-menu": "^2.1.16",
"@radix-ui/react-label": "^2.1.8",
"@radix-ui/react-progress": "^1.1.8",
"@radix-ui/react-select": "^2.2.6",
"@radix-ui/react-slot": "^1.2.4",
"@radix-ui/react-switch": "^1.2.6",
"@radix-ui/react-tooltip": "^1.2.8",
"@tailwindcss/vite": "^4.1.18",
"@radix-ui/react-checkbox": "^1.3.5",
"@radix-ui/react-context-menu": "^2.3.1",
"@radix-ui/react-dialog": "^1.1.17",
"@radix-ui/react-dropdown-menu": "^2.1.18",
"@radix-ui/react-label": "^2.1.10",
"@radix-ui/react-progress": "^1.1.10",
"@radix-ui/react-select": "^2.3.1",
"@radix-ui/react-slot": "^1.3.0",
"@radix-ui/react-switch": "^1.3.1",
"@radix-ui/react-tooltip": "^1.2.10",
"@tailwindcss/vite": "^4.3.1",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"lucide-react": "^0.562.0",
"motion": "^12.23.26",
"motion": "^12.40.0",
"next-themes": "^0.4.6",
"react": "^19.2.3",
"react-dom": "^19.2.3",
"react": "^19.2.7",
"react-dom": "^19.2.7",
"sonner": "^2.0.7",
"tailwind-merge": "^3.4.0",
"tailwindcss": "^4.1.18"
"tailwind-merge": "^3.6.0",
"tailwindcss": "^4.3.1"
},
"devDependencies": {
"@eslint/js": "^9.39.2",
"@types/node": "^25.0.3",
"@types/react": "^19.2.7",
"@eslint/js": "^10.0.1",
"@types/node": "^26.0.0",
"@types/react": "^19.2.17",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^5.1.2",
"eslint": "^9.39.2",
"eslint-plugin-react-hooks": "^7.0.1",
"eslint-plugin-react-refresh": "^0.4.26",
"globals": "^16.5.0",
"sharp": "^0.34.5",
"@vitejs/plugin-react": "^6.0.2",
"eslint": "^10.5.0",
"eslint-plugin-react-hooks": "^7.1.1",
"eslint-plugin-react-refresh": "^0.5.3",
"globals": "^17.6.0",
"sharp": "^0.35.2",
"tw-animate-css": "^1.4.0",
"typescript": "~5.9.3",
"typescript-eslint": "^8.50.0",
"vite": "^7.3.0"
"typescript": "~6.0.3",
"typescript-eslint": "^8.61.1",
"vite": "^8.0.16"
}
}
+1 -1
View File
@@ -1 +1 @@
cb4545ab700ecc9d641ab1be76b622f1
66d76291490cdae022ca7ad778594a1f
+1678 -1858
View File
File diff suppressed because it is too large. Load diff
+80 -29
View File
@@ -26,22 +26,19 @@ import { ExtractTimeline, ExtractDateRange, SaveAccountToDBWithStatus, CleanupEx
const HISTORY_KEY = "twitter_media_fetch_history";
const MAX_HISTORY = 10;
const CURRENT_VERSION = __APP_VERSION__;
const BATCH_SIZE = 200;
const BATCH_SIZE = 100;
function formatNumberWithComma(num: number): string {
return num.toLocaleString();
}
function normalizeTimeline(timeline: TwitterResponse["timeline"] | null | undefined): TwitterResponse["timeline"] {
return Array.isArray(timeline) ? timeline : [];
}
function normalizeTwitterResponse(data: TwitterResponse): TwitterResponse {
return {
...data,
timeline: normalizeTimeline(data.timeline),
};
}
async function loadSavedAccountResponse(username: string, mediaType: string): Promise<TwitterResponse | null> {
try {
const savedResponseJSON = await GetSavedAccountFromDB(username, mediaType);
@@ -51,7 +48,6 @@ async function loadSavedAccountResponse(username: string, mediaType: string): Pr
return null;
}
}
function App() {
const [currentPage, setCurrentPage] = useState<PageType>("main");
const [username, setUsername] = useState("");
@@ -102,12 +98,20 @@ function App() {
}
return;
}
const canResume = !!savedState.cursor && !savedState.completed;
if (!canResume) {
clearFetchState(cleanUsername);
clearCursor(cleanUsername);
setResumeInfo(null);
}
const partialResponse = await loadSavedAccountResponse(cleanUsername, savedState.mediaType || mediaType);
setResumeInfo({ canResume: true, mediaCount: savedState.totalFetched });
if (canResume) {
setResumeInfo({ canResume: true, mediaCount: savedState.totalFetched });
}
if (partialResponse) {
setResult(partialResponse);
try {
await SaveAccountToDBWithStatus(partialResponse.account_info.name, partialResponse.account_info.nick, partialResponse.account_info.profile_image, partialResponse.total_urls, JSON.stringify(partialResponse), savedState.mediaType || mediaType, savedState.cursor || "", false);
await SaveAccountToDBWithStatus(partialResponse.account_info.name, partialResponse.account_info.nick, partialResponse.account_info.profile_image, partialResponse.total_urls, JSON.stringify(partialResponse), savedState.mediaType || mediaType, savedState.cursor || "", savedState.completed);
}
catch (dbErr) {
reportDatabaseSaveError("partial fetch data", dbErr);
@@ -193,7 +197,6 @@ function App() {
openExternal(url.toString());
}
catch {
// Ignore invalid URLs and allow the browser/webview to handle them.
}
};
document.addEventListener("click", handleDocumentClick);
@@ -434,10 +437,8 @@ function App() {
}
}
else {
const settings = getSettings();
const isSingleMode = settings.fetchMode === "single";
const batchSize = isSingleMode ? 0 : BATCH_SIZE;
let timelineType = "timeline";
const batchSize = BATCH_SIZE;
let timelineType = (settings.includeText || retweets) ? "tweets" : "media";
if (isBookmarks) {
timelineType = "bookmarks";
}
@@ -446,6 +447,7 @@ function App() {
}
let hasMore = true;
let page = 0;
const seenCursors = new Set<string>();
while (hasMore && !stopFetchRef.current) {
if (fetchStartTimeRef.current !== null) {
const settings = getSettings();
@@ -492,7 +494,7 @@ function App() {
}
}
const batchNum = page + 1;
logger.info(isSingleMode ? "Fetching all media..." : `Fetching batch ${batchNum}${cursor ? " (resuming)" : ""}...`);
logger.info(`Fetching batch ${batchNum}${cursor ? " (resuming)" : ""}...`);
const response = await ExtractTimeline({
username: isBookmarks ? "" : username.trim(),
auth_token: authToken.trim(),
@@ -502,6 +504,12 @@ function App() {
media_type: requestedMediaType,
retweets: retweets || false,
cursor: cursor,
include_photos: settings.includePhotos,
include_videos: settings.includeVideos,
include_gifs: settings.includeGifs,
include_text: settings.includeText,
video_quality: settings.videoQuality,
image_size: settings.imageSize,
});
const data = normalizeTwitterResponse(JSON.parse(response) as TwitterResponse);
if (!accountInfo && data.account_info) {
@@ -524,6 +532,14 @@ function App() {
}
cursor = data.cursor;
hasMore = !!data.cursor && !data.completed;
if (hasMore && cursor) {
if (seenCursors.has(cursor) || (data.timeline.length > 0 && newCount === 0)) {
hasMore = false;
}
else {
seenCursors.add(cursor);
}
}
page++;
if (cursor) {
saveCursor(cleanUsername, cursor);
@@ -579,7 +595,7 @@ function App() {
}
}
}
if (stopFetchRef.current) {
if (stopFetchRef.current && hasMore && cursor) {
const elapsedSecs = fetchStartTimeRef.current ? Math.floor((Date.now() - fetchStartTimeRef.current) / 1000) : 0;
logger.info(`Stopped at ${allTimeline.length} items - can resume later (${elapsedSecs}s)`);
toast.info(`Stopped at ${formatNumberWithComma(allTimeline.length)} items`);
@@ -808,7 +824,7 @@ function App() {
return;
}
const settings = getSettings();
const selectedMediaType = settings.mediaType || "all";
const selectedMediaType = "all";
setFetchedMediaType(selectedMediaType);
const timeoutSeconds = settings.fetchTimeout || 60;
setMultipleAccounts((prev) => prev.map((acc) => ({
@@ -882,15 +898,14 @@ function App() {
}));
continue;
}
const fetchSettings = getSettings();
const isSingleModeMultiple = fetchSettings.fetchMode === "single";
const batchSizeMultiple = isSingleModeMultiple ? 0 : BATCH_SIZE;
const batchSizeMultiple = BATCH_SIZE;
const cleanUsername = account.username.trim();
let allTimeline: TwitterResponse["timeline"] = [];
let accountInfo: TwitterResponse["account_info"] | null = null;
let cursor: string | undefined;
let hasMore = true;
let page = 0;
const seenCursors = new Set<string>();
let previousMediaCount = account.mediaCount || 0;
while (hasMore && !stopAllRef.current) {
if (accountStopFlagsRef.current.get(accountId)) {
@@ -930,20 +945,35 @@ function App() {
const response = await ExtractTimeline({
username: cleanUsername,
auth_token: authToken.trim(),
timeline_type: "timeline",
timeline_type: (settings.includeText || settings.includeRetweets) ? "tweets" : "media",
batch_size: batchSizeMultiple,
page: page,
media_type: selectedMediaType,
retweets: false,
retweets: settings.includeRetweets,
cursor: cursor,
include_photos: settings.includePhotos,
include_videos: settings.includeVideos,
include_gifs: settings.includeGifs,
include_text: settings.includeText,
video_quality: settings.videoQuality,
image_size: settings.imageSize,
});
const data = normalizeTwitterResponse(JSON.parse(response) as TwitterResponse);
if (!accountInfo && data.account_info) {
accountInfo = data.account_info;
}
const previousMergeCount = allTimeline.length;
allTimeline = mergeTimelines(allTimeline, data.timeline);
cursor = data.cursor;
hasMore = !!data.cursor && !data.completed;
if (hasMore && cursor) {
if (seenCursors.has(cursor) || (data.timeline.length > 0 && allTimeline.length === previousMergeCount)) {
hasMore = false;
}
else {
seenCursors.add(cursor);
}
}
page++;
if (cursor) {
saveCursor(cleanUsername, cursor);
@@ -997,7 +1027,7 @@ function App() {
},
cursor: cursor,
completed: !hasMore,
}), selectedMediaType, cursor || "", !hasMore);
}), selectedMediaType, cursor || "", !hasMore);
}
catch (err) {
reportDatabaseSaveError("multi-account progress", err);
@@ -1144,10 +1174,9 @@ function App() {
return;
}
const retrySettings = getSettings();
const selectedMediaType = retrySettings.mediaType || fetchedMediaType || "all";
const selectedMediaType = fetchedMediaType || "all";
setFetchedMediaType(selectedMediaType);
const isSingleModeRetry = retrySettings.fetchMode === "single";
const batchSizeRetry = isSingleModeRetry ? 0 : BATCH_SIZE;
const batchSizeRetry = BATCH_SIZE;
const cleanUsername = account.username.trim();
let existingState: FetchState | null = null;
let cursor: string | undefined = account.cursor;
@@ -1157,7 +1186,12 @@ function App() {
existingState = getFetchState(cleanUsername);
if (existingState && existingState.cursor && !existingState.completed) {
cursor = existingState.cursor;
const savedResponse = await loadSavedAccountResponse(cleanUsername, existingState.mediaType || selectedMediaType);
const resumeMediaType = existingState.mediaType || selectedMediaType;
const canonicalHandle = account.accountInfo?.name?.trim();
let savedResponse = await loadSavedAccountResponse(cleanUsername, resumeMediaType);
if (!savedResponse && canonicalHandle && canonicalHandle.toLowerCase() !== cleanUsername.toLowerCase()) {
savedResponse = await loadSavedAccountResponse(canonicalHandle, resumeMediaType);
}
if (savedResponse) {
allTimeline = savedResponse.timeline;
accountInfo = savedResponse.account_info;
@@ -1167,7 +1201,8 @@ function App() {
else {
clearFetchState(cleanUsername);
clearCursor(cleanUsername);
logger.info(`Saved retry state for @${cleanUsername} was missing. Starting from beginning...`);
logger.warning(`Saved data for @${cleanUsername} is missing (Saved Accounts entry was cleared). Re-fetching from the beginning...`);
toast.warning(`@${cleanUsername}: saved progress was lost, re-fetching from the start`);
cursor = undefined;
allTimeline = [];
accountInfo = null;
@@ -1261,6 +1296,7 @@ function App() {
try {
let hasMore = true;
let page = 0;
const seenCursors = new Set<string>();
while (hasMore && !stopAllRef.current) {
if (accountStopFlagsRef.current.get(accountId)) {
break;
@@ -1268,20 +1304,35 @@ function App() {
const response = await ExtractTimeline({
username: cleanUsername,
auth_token: authToken.trim(),
timeline_type: "timeline",
timeline_type: (retrySettings.includeText || retrySettings.includeRetweets) ? "tweets" : "media",
batch_size: batchSizeRetry,
page: page,
media_type: selectedMediaType,
retweets: false,
retweets: retrySettings.includeRetweets,
cursor: cursor,
include_photos: retrySettings.includePhotos,
include_videos: retrySettings.includeVideos,
include_gifs: retrySettings.includeGifs,
include_text: retrySettings.includeText,
video_quality: retrySettings.videoQuality,
image_size: retrySettings.imageSize,
});
const data = normalizeTwitterResponse(JSON.parse(response) as TwitterResponse);
if (!accountInfo && data.account_info) {
accountInfo = data.account_info;
}
const previousRetryCount = allTimeline.length;
allTimeline = mergeTimelines(allTimeline, data.timeline);
cursor = data.cursor;
hasMore = !!data.cursor && !data.completed;
if (hasMore && cursor) {
if (seenCursors.has(cursor) || (data.timeline.length > 0 && allTimeline.length === previousRetryCount)) {
hasMore = false;
}
else {
seenCursors.add(cursor);
}
}
page++;
if (cursor) {
saveCursor(cleanUsername, cursor);
@@ -1433,7 +1484,7 @@ function App() {
return (<>
<Header version={CURRENT_VERSION} hasUpdate={hasUpdate} releaseDate={releaseDate}/>
<SearchBar username={username} loading={loading} onUsernameChange={setUsername} onFetch={handleFetch} onStopFetch={handleStopFetch} onResume={handleResume} onClearResume={handleClearResume} resumeInfo={resumeInfo} history={fetchHistory} onHistorySelect={handleHistorySelect} onHistoryRemove={removeFromHistory} hasResult={!!result} elapsedTime={elapsedTime} remainingTime={remainingTime} fetchType={fetchType} onFetchTypeChange={handleFetchTypeChange} multipleAccounts={multipleAccounts} onImportAccounts={handleImportAccounts} onFetchAll={handleFetchAll} onStopAll={handleStopAll} onStopAccount={handleStopAccount} onRetryAccount={handleRetryAccount} onClearMultipleAccounts={handleClearMultipleAccounts} onRemoveMultipleAccount={handleRemoveMultipleAccount} isFetchingAll={isFetchingAll} mode={searchMode} privateType={searchPrivateType} onModeChange={(mode, privateType) => {
<SearchBar username={username} loading={loading} onUsernameChange={setUsername} onFetch={handleFetch} onStopFetch={handleStopFetch} onResume={handleResume} onClearResume={handleClearResume} resumeInfo={resumeInfo} history={fetchHistory} onHistorySelect={handleHistorySelect} onHistoryRemove={removeFromHistory} hasResult={!!result} elapsedTime={elapsedTime} remainingTime={remainingTime} fetchType={fetchType} onFetchTypeChange={handleFetchTypeChange} multipleAccounts={multipleAccounts} onImportAccounts={handleImportAccounts} onFetchAll={handleFetchAll} onStopAll={handleStopAll} onStopAccount={handleStopAccount} onRetryAccount={handleRetryAccount} onClearMultipleAccounts={handleClearMultipleAccounts} onRemoveMultipleAccount={handleRemoveMultipleAccount} onOpenSavedAccounts={() => setCurrentPage("database")} isFetchingAll={isFetchingAll} mode={searchMode} privateType={searchPrivateType} onModeChange={(mode, privateType) => {
setSearchMode(mode);
if (privateType) {
setSearchPrivateType(privateType);
+137 -120
View File
@@ -66,11 +66,9 @@ interface DatabaseViewProps {
}
const INITIAL_LOAD_COUNT = 12;
const LOAD_MORE_COUNT = 12;
function getContentScrollElement(): HTMLElement | null {
return document.getElementById("app-content-scroll");
}
export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewProps) {
const [accounts, setAccounts] = useState<AccountListItem[]>([]);
const [loading, setLoading] = useState(true);
@@ -84,7 +82,13 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
const [searchQuery, setSearchQuery] = useState<string>("");
const deferredSearchQuery = useDeferredValue(searchQuery);
const [sortOrder, setSortOrder] = useState<"newest" | "oldest" | "username-asc" | "username-desc" | "followers-high" | "followers-low" | "posts-high" | "posts-low" | "media-high" | "media-low">("newest");
const [gridView, setGridView] = useState<"large" | "small" | "list">("list");
const [gridView, setGridView] = useState<"large" | "small" | "list">(() => {
const stored = localStorage.getItem("savedAccountsViewMode");
return stored === "large" || stored === "small" || stored === "list" ? stored : "list";
});
useEffect(() => {
localStorage.setItem("savedAccountsViewMode", gridView);
}, [gridView]);
const [editingAccount, setEditingAccount] = useState<AccountListItem | null>(null);
const [editGroupName, setEditGroupName] = useState("");
const [editGroupColor, setEditGroupColor] = useState("");
@@ -230,11 +234,9 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
setFolderExistence(new Map());
return;
}
if (visibleAccounts.length === 0) {
return;
}
let active = true;
const loadVisibleFolderExistence = async () => {
try {
@@ -243,7 +245,6 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
if (!active) {
return;
}
setFolderExistence((prev) => {
const next = new Map(prev);
for (const account of visibleAccounts) {
@@ -256,7 +257,6 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
console.error("Failed to check visible folders:", error);
}
};
void loadVisibleFolderExistence();
return () => {
active = false;
@@ -382,6 +382,8 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
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) {
@@ -505,6 +507,8 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
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) {
@@ -628,105 +632,106 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
};
input.onchange = async (e) => {
try {
const files = (e.target as HTMLInputElement).files;
if (!files || files.length === 0)
return;
let imported = 0;
for (const file of Array.from(files)) {
try {
const text = await file.text();
const data = JSON.parse(text);
let detectedMediaType = "all";
if (data.media_type) {
detectedMediaType = data.media_type;
}
else if (data.media_list && Array.isArray(data.media_list)) {
const types = new Set(data.media_list.map((item: {
media_type?: string;
type?: string;
}) => item.media_type || item.type).filter(Boolean));
if (types.size === 1) {
const singleType = Array.from(types)[0] as string;
if (singleType === "photo")
detectedMediaType = "image";
else if (singleType === "video")
detectedMediaType = "video";
else if (singleType === "animated_gif")
detectedMediaType = "gif";
else
detectedMediaType = singleType;
const files = (e.target as HTMLInputElement).files;
if (!files || files.length === 0)
return;
let imported = 0;
for (const file of Array.from(files)) {
try {
const text = await file.text();
const data = JSON.parse(text);
let detectedMediaType = "all";
if (data.media_type) {
detectedMediaType = data.media_type;
}
}
else if (data.timeline && Array.isArray(data.timeline)) {
const types = new Set(data.timeline.map((item: {
type?: string;
}) => item.type).filter(Boolean));
if (types.size === 1) {
const singleType = Array.from(types)[0] as string;
if (singleType === "photo")
detectedMediaType = "image";
else if (singleType === "video")
detectedMediaType = "video";
else if (singleType === "animated_gif")
detectedMediaType = "gif";
else if (singleType === "text")
detectedMediaType = "text";
else
detectedMediaType = singleType;
}
}
if (data.account_info && data.timeline) {
await SaveAccountToDB(data.account_info.name, data.account_info.nick, data.account_info.profile_image, data.total_urls || data.timeline.length, text, detectedMediaType);
imported++;
}
else if (data.username && data.media_list) {
const convertedData = {
account_info: {
name: data.username,
nick: data.nick || data.username,
date: "",
followers_count: data.followers || 0,
friends_count: data.following || 0,
profile_image: data.profile_image || "",
statuses_count: data.posts || 0,
},
total_urls: data.media_list.length,
timeline: data.media_list.map((item: {
url: string;
date: string;
tweet_id: string;
type: string;
else if (data.media_list && Array.isArray(data.media_list)) {
const types = new Set(data.media_list.map((item: {
media_type?: string;
}) => ({
url: item.url,
date: item.date,
tweet_id: item.tweet_id,
type: item.media_type || item.type,
is_retweet: false,
})),
metadata: {
new_entries: data.media_list.length,
page: 0,
batch_size: 0,
has_more: false,
},
};
await SaveAccountToDB(convertedData.account_info.name, convertedData.account_info.nick, convertedData.account_info.profile_image, convertedData.total_urls, JSON.stringify(convertedData), detectedMediaType);
imported++;
type?: string;
}) => item.media_type || item.type).filter(Boolean));
if (types.size === 1) {
const singleType = Array.from(types)[0] as string;
if (singleType === "photo")
detectedMediaType = "image";
else if (singleType === "video")
detectedMediaType = "video";
else if (singleType === "animated_gif")
detectedMediaType = "gif";
else
detectedMediaType = singleType;
}
}
else if (data.timeline && Array.isArray(data.timeline)) {
const types = new Set(data.timeline.map((item: {
type?: string;
}) => item.type).filter(Boolean));
if (types.size === 1) {
const singleType = Array.from(types)[0] as string;
if (singleType === "photo")
detectedMediaType = "image";
else if (singleType === "video")
detectedMediaType = "video";
else if (singleType === "animated_gif")
detectedMediaType = "gif";
else if (singleType === "text")
detectedMediaType = "text";
else
detectedMediaType = singleType;
}
}
if (data.account_info && data.timeline) {
await SaveAccountToDB(data.account_info.name, data.account_info.nick, data.account_info.profile_image, data.total_urls || data.timeline.length, text, detectedMediaType);
imported++;
}
else if (data.username && data.media_list) {
const convertedData = {
account_info: {
name: data.username,
nick: data.nick || data.username,
date: "",
followers_count: data.followers || 0,
friends_count: data.following || 0,
profile_image: data.profile_image || "",
statuses_count: data.posts || 0,
},
total_urls: data.media_list.length,
timeline: data.media_list.map((item: {
url: string;
date: string;
tweet_id: string;
type: string;
media_type?: string;
}) => ({
url: item.url,
date: item.date,
tweet_id: item.tweet_id,
type: item.media_type || item.type,
is_retweet: false,
})),
metadata: {
new_entries: data.media_list.length,
page: 0,
batch_size: 0,
has_more: false,
},
};
await SaveAccountToDB(convertedData.account_info.name, convertedData.account_info.nick, convertedData.account_info.profile_image, convertedData.total_urls, JSON.stringify(convertedData), detectedMediaType);
imported++;
}
}
catch (err) {
console.error(`Failed to import ${file.name}:`, err);
}
}
catch (err) {
console.error(`Failed to import ${file.name}:`, err);
if (imported > 0) {
toast.success(`Imported ${imported} account(s)`);
loadAccounts();
}
else {
toast.error("No valid files imported");
}
}
if (imported > 0) {
toast.success(`Imported ${imported} account(s)`);
loadAccounts();
}
else {
toast.error("No valid files imported");
}
} finally {
finally {
cleanup();
}
};
@@ -1014,9 +1019,9 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
{gridView === "large" && (<div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
{filteredAccounts
.slice(0, visibleCount)
.map((account) => (<div key={account.id} className={`relative rounded-lg border transition-colors p-4 ${selectedIds.has(account.id) ? "border-primary bg-primary/5" : "bg-card hover:bg-muted/50"}`}>
<Checkbox checked={selectedIds.has(account.id)} onCheckedChange={() => toggleSelect(account.id)} className="absolute top-2 left-2 z-10"/>
.map((account, index) => (<div key={account.id} onClick={() => handleView(account.id, account.username)} className={`relative rounded-lg border transition-colors p-4 cursor-pointer ${selectedIds.has(account.id) ? "border-primary bg-primary/5" : "bg-card hover:bg-muted/50"}`}>
<Checkbox checked={selectedIds.has(account.id)} onCheckedChange={() => toggleSelect(account.id)} onClick={(e) => e.stopPropagation()} className="absolute top-2 left-2 z-10"/>
<div className="absolute top-2 right-2 z-10 flex gap-1">
<Badge variant="secondary" className={cn("text-xs flex items-center gap-1", account.media_type === "text" && "bg-orange-500/20 text-orange-600 dark:text-orange-400", account.media_type === "image" && "bg-blue-500/20 text-blue-600 dark:text-blue-400", account.media_type === "video" && "bg-purple-500/20 text-purple-600 dark:text-purple-400", account.media_type === "gif" && "bg-green-500/20 text-green-600 dark:text-green-400", (!account.media_type || account.media_type === "all") && "bg-indigo-500/20 text-indigo-600 dark:text-indigo-400")}>
@@ -1031,9 +1036,14 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
</Badge>)}
</div>
<div className="flex flex-col items-center text-center gap-3 pt-4">
{isPrivateAccount(account.username) ? (<div className="w-20 h-20 rounded-full bg-primary/10 flex items-center justify-center cursor-pointer hover:bg-primary/20 transition-colors" onClick={() => handleView(account.id, account.username)}>
{account.username === "bookmarks" ? (<Bookmark className="h-10 w-10 text-primary"/>) : (<Heart className="h-10 w-10 text-primary"/>)}
</div>) : (<img src={account.profile_image} alt={account.name} className="w-20 h-20 rounded-full cursor-pointer hover:opacity-80 transition-opacity" onClick={() => handleView(account.id, account.username)}/>)}
<div className="relative">
<span className="absolute -top-1.5 -left-1.5 z-10 flex h-5 min-w-5 items-center justify-center rounded-full bg-primary px-1 text-xs font-medium text-primary-foreground">
{index + 1}
</span>
{isPrivateAccount(account.username) ? (<div className="w-20 h-20 rounded-full bg-primary/10 flex items-center justify-center">
{account.username === "bookmarks" ? (<Bookmark className="h-10 w-10 text-primary"/>) : (<Heart className="h-10 w-10 text-primary"/>)}
</div>) : (<img src={account.profile_image} alt={account.name} className="w-20 h-20 rounded-full"/>)}
</div>
<div className="w-full min-w-0">
<div className="font-medium truncate">{account.name}</div>
{!isPrivateAccount(account.username) && (<button type="button" onClick={() => openExternal(`https://x.com/${account.username}`)} className="text-sm text-muted-foreground hover:text-primary hover:underline">
@@ -1103,9 +1113,9 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
{gridView === "small" && (<div className="grid grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-3">
{filteredAccounts
.slice(0, visibleCount)
.map((account) => (<div key={account.id} className={`relative rounded-lg border transition-colors p-3 ${selectedIds.has(account.id) ? "border-primary bg-primary/5" : "bg-card hover:bg-muted/50"}`}>
<Checkbox checked={selectedIds.has(account.id)} onCheckedChange={() => toggleSelect(account.id)} className="absolute top-1.5 left-1.5 z-10"/>
.map((account, index) => (<div key={account.id} onClick={() => handleView(account.id, account.username)} className={`relative rounded-lg border transition-colors p-3 cursor-pointer ${selectedIds.has(account.id) ? "border-primary bg-primary/5" : "bg-card hover:bg-muted/50"}`}>
<Checkbox checked={selectedIds.has(account.id)} onCheckedChange={() => toggleSelect(account.id)} onClick={(e) => e.stopPropagation()} className="absolute top-1.5 left-1.5 z-10"/>
<div className="absolute top-1.5 right-1.5 z-10 flex gap-1">
<Badge variant="secondary" className={cn("text-xs p-1", account.media_type === "text" && "bg-orange-500/20 text-orange-600 dark:text-orange-400", account.media_type === "image" && "bg-blue-500/20 text-blue-600 dark:text-blue-400", account.media_type === "video" && "bg-purple-500/20 text-purple-600 dark:text-purple-400", account.media_type === "gif" && "bg-green-500/20 text-green-600 dark:text-green-400", (!account.media_type || account.media_type === "all") && "bg-indigo-500/20 text-indigo-600 dark:text-indigo-400")}>
@@ -1120,9 +1130,14 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
</Badge>)}
</div>
<div className="flex flex-col items-center text-center gap-2 pt-4">
{isPrivateAccount(account.username) ? (<div className="w-14 h-14 rounded-full bg-primary/10 flex items-center justify-center cursor-pointer hover:bg-primary/20 transition-colors" onClick={() => handleView(account.id, account.username)}>
{account.username === "bookmarks" ? (<Bookmark className="h-7 w-7 text-primary"/>) : (<Heart className="h-7 w-7 text-primary"/>)}
</div>) : (<img src={account.profile_image} alt={account.name} className="w-14 h-14 rounded-full cursor-pointer hover:opacity-80 transition-opacity" onClick={() => handleView(account.id, account.username)}/>)}
<div className="relative">
<span className="absolute -top-1.5 -left-1.5 z-10 flex h-5 min-w-5 items-center justify-center rounded-full bg-primary px-1 text-xs font-medium text-primary-foreground">
{index + 1}
</span>
{isPrivateAccount(account.username) ? (<div className="w-14 h-14 rounded-full bg-primary/10 flex items-center justify-center">
{account.username === "bookmarks" ? (<Bookmark className="h-7 w-7 text-primary"/>) : (<Heart className="h-7 w-7 text-primary"/>)}
</div>) : (<img src={account.profile_image} alt={account.name} className="w-14 h-14 rounded-full"/>)}
</div>
<div className="w-full min-w-0">
<div className="text-xs font-medium truncate">{account.name}</div>
{!isPrivateAccount(account.username) && (<button type="button" onClick={() => openExternal(`https://x.com/${account.username}`)} className="text-xs text-muted-foreground hover:text-primary hover:underline truncate block w-full">
@@ -1192,14 +1207,16 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
{gridView === "list" && filteredAccounts
.slice(0, visibleCount)
.map((account, index) => (<div key={account.id} className={`rounded-lg border transition-colors ${selectedIds.has(account.id) ? "border-primary bg-primary/5" : "bg-card hover:bg-muted/50"}`}>
<div className="flex items-center gap-4 p-4">
<Checkbox checked={selectedIds.has(account.id)} onCheckedChange={() => toggleSelect(account.id)}/>
<span className="text-sm text-muted-foreground w-8 text-center shrink-0">
{index + 1}
</span>
{isPrivateAccount(account.username) ? (<div className="w-12 h-12 rounded-full bg-primary/10 flex items-center justify-center cursor-pointer hover:bg-primary/20 transition-colors" onClick={() => handleView(account.id, account.username)}>
{account.username === "bookmarks" ? (<Bookmark className="h-6 w-6 text-primary"/>) : (<Heart className="h-6 w-6 text-primary"/>)}
</div>) : (<img src={account.profile_image} alt={account.name} className="w-12 h-12 rounded-full cursor-pointer hover:opacity-80 transition-opacity" onClick={() => handleView(account.id, account.username)}/>)}
<div className="flex items-center gap-4 p-4 cursor-pointer" onClick={() => handleView(account.id, account.username)}>
<Checkbox checked={selectedIds.has(account.id)} onCheckedChange={() => toggleSelect(account.id)} onClick={(e) => e.stopPropagation()}/>
<div className="relative shrink-0">
<span className="absolute -top-1.5 -left-1.5 z-10 flex h-5 min-w-5 items-center justify-center rounded-full bg-primary px-1 text-xs font-medium text-primary-foreground">
{index + 1}
</span>
{isPrivateAccount(account.username) ? (<div className="w-12 h-12 rounded-full bg-primary/10 flex items-center justify-center">
{account.username === "bookmarks" ? (<Bookmark className="h-6 w-6 text-primary"/>) : (<Heart className="h-6 w-6 text-primary"/>)}
</div>) : (<img src={account.profile_image} alt={account.name} className="w-12 h-12 rounded-full"/>)}
</div>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<span className="truncate">{account.name}</span>
@@ -6,17 +6,13 @@ import { Spinner } from "@/components/ui/spinner";
import { toastWithSound as toast } from "@/lib/toast-with-sound";
import { Quit } from "../../wailsjs/runtime/runtime";
import { DownloadExtractor, IsExtractorInstalled } from "../../wailsjs/go/main/App";
interface DependencySetupDialogProps {
onInstalled?: () => void;
}
interface GithubReleaseResponse {
tag_name?: string;
}
const extractorReleaseAPIURL = "https://api.github.com/repos/afkarxyz/xtractor-binaries/releases/latest";
export function DependencySetupDialog({ onInstalled }: DependencySetupDialogProps) {
const [open, setOpen] = useState(false);
const [checking, setChecking] = useState(true);
@@ -24,11 +20,9 @@ export function DependencySetupDialog({ onInstalled }: DependencySetupDialogProp
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const [releaseVersion, setReleaseVersion] = useState<string | null>(null);
const [releaseStatusMessage, setReleaseStatusMessage] = useState("Checking latest GitHub release...");
useEffect(() => {
let cancelled = false;
const abortController = new AbortController();
const checkDependency = async () => {
try {
const installed = await IsExtractorInstalled();
@@ -49,7 +43,6 @@ export function DependencySetupDialog({ onInstalled }: DependencySetupDialogProp
}
}
};
const loadReleaseInfo = async () => {
try {
const response = await fetch(extractorReleaseAPIURL, {
@@ -58,18 +51,14 @@ export function DependencySetupDialog({ onInstalled }: DependencySetupDialogProp
},
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}`);
@@ -82,16 +71,13 @@ export function DependencySetupDialog({ onInstalled }: DependencySetupDialogProp
}
}
};
void checkDependency();
void loadReleaseInfo();
return () => {
cancelled = true;
abortController.abort();
};
}, []);
const handleDownload = async () => {
setDownloading(true);
setErrorMessage(null);
@@ -110,17 +96,14 @@ export function DependencySetupDialog({ onInstalled }: DependencySetupDialogProp
setDownloading(false);
}
};
const handleExit = () => {
if (!downloading) {
void Quit();
}
};
if (checking && !open) {
return null;
}
return (<Dialog open={open} onOpenChange={(nextOpen) => {
if (nextOpen) {
setOpen(true);
+66
View File
@@ -0,0 +1,66 @@
import { useRef } from "react";
import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
import { RefreshCw } from "lucide-react";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { type TemplateToken } from "@/lib/settings";
export function FormatEditor({ title, value, defaultValue, tokens, suffix, placeholder, render, onChange }: {
title: string;
value: string;
defaultValue: string;
tokens: TemplateToken[];
suffix?: string;
placeholder?: string;
render: (template: string) => string;
onChange: (next: string) => void;
}) {
const inputRef = useRef<HTMLInputElement | null>(null);
const insertToken = (token: string) => {
const input = inputRef.current;
let next: string;
let caret: number;
if (input && input.selectionStart !== null && input.selectionEnd !== null) {
const start = input.selectionStart;
const end = input.selectionEnd;
next = value.slice(0, start) + token + value.slice(end);
caret = start + token.length;
}
else {
next = value + token;
caret = next.length;
}
onChange(next);
requestAnimationFrame(() => {
if (input) {
input.focus();
input.setSelectionRange(caret, caret);
}
});
};
const preview = render(value) + (suffix ?? "");
return (<div className="space-y-3">
<Label className="text-sm font-semibold">{title}</Label>
<div className="relative">
<Input ref={inputRef} value={value} placeholder={placeholder} onChange={(e) => onChange(e.target.value)} className="font-mono text-sm pr-9"/>
<button type="button" onClick={() => onChange(defaultValue)} className="absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground transition-colors">
<RefreshCw className="h-4 w-4"/>
</button>
</div>
<div className="rounded-lg border bg-muted/40 px-3 py-2">
<div className="text-[10px] font-semibold uppercase tracking-wide text-muted-foreground">Preview</div>
<div className="font-mono text-sm break-all">{preview || <span className="text-muted-foreground italic">empty</span>}</div>
</div>
<div className="flex flex-wrap gap-2">
{tokens.map((token) => (<Tooltip key={token.key}>
<TooltipTrigger asChild>
<button type="button" onMouseDown={(e) => e.preventDefault()} onClick={() => insertToken(token.key)} className="rounded-md border bg-background px-2.5 py-1 text-xs font-mono text-muted-foreground transition-colors hover:text-foreground hover:border-primary/50">
{token.key}
</button>
</TooltipTrigger>
<TooltipContent side="top">
<span className="font-mono">{token.example || "—"}</span>
</TooltipContent>
</Tooltip>))}
</div>
</div>);
}
+152 -50
View File
@@ -5,15 +5,15 @@ import { Badge } from "@/components/ui/badge";
import { Progress } from "@/components/ui/progress";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select";
import { Tooltip, TooltipContent, TooltipTrigger, } from "@/components/ui/tooltip";
import { Image, Video, Film, FileText, ExternalLink, Repeat2, Download, FolderOpen, LayoutGrid, Grid3X3, List, StopCircle, Users, UserPlus, MessageSquare, Calendar, ArrowUp, ChevronLeft, ChevronRight, Eye, Heart, Bookmark, BadgeCheck, Maximize2, CheckCircle, XCircle, FileCheck, } from "lucide-react";
import { Image, Video, Film, FileText, ExternalLink, Repeat2, Download, FolderOpen, LayoutGrid, Grid3X3, List, StopCircle, MapPin, Link2, Lock, Calendar, ArrowUp, ChevronLeft, ChevronRight, Eye, Heart, Bookmark, BadgeCheck, Maximize2, CheckCircle, XCircle, FileCheck, } from "lucide-react";
import { Spinner } from "@/components/ui/spinner";
import type { TimelineEntry, AccountInfo } from "@/types/api";
import { logger } from "@/lib/logger";
import { toastWithSound as toast } from "@/lib/toast-with-sound";
import { getSettings } from "@/lib/settings";
import { getSettings, renderFolderTemplate } from "@/lib/settings";
import { getCachedDependencyStatus, getCachedMediaFolderStatus, setCachedDependencyStatus, setCachedMediaFolderStatus } from "@/lib/runtime-cache";
import { openExternal } from "@/lib/utils";
import { DownloadMediaWithMetadata, OpenFolder, IsFFmpegInstalled, ConvertGIFs, StopDownload, CheckFolderExists, CheckGifsFolderHasMP4 } from "../../wailsjs/go/main/App";
import { DownloadMediaWithMetadata, DownloadProfileImage, OpenFolder, IsFFmpegInstalled, ConvertGIFs, StopDownload, CheckFolderExists, CheckGifsFolderHasMP4 } from "../../wailsjs/go/main/App";
import { EventsOn } from "../../wailsjs/runtime/runtime";
import { main } from "../../wailsjs/go/models";
interface DownloadProgress {
@@ -34,11 +34,9 @@ interface MediaListProps {
newMediaCount?: number | null;
}
const MEDIA_LIST_PAGE_SIZE = 30;
function getContentScrollElement(): HTMLElement | null {
return document.getElementById("app-content-scroll");
}
function getThumbnailUrl(url: string): string {
if (url.includes("video.twimg.com/tweet_video/")) {
const match = url.match(/tweet_video\/([^/]+)\.mp4/);
@@ -78,6 +76,12 @@ function getPreviewUrl(url: string): string {
}
return url;
}
function getEntryThumbnail(item: TimelineEntry): string {
if (item.thumbnail) {
return item.thumbnail;
}
return getThumbnailUrl(item.url);
}
function getMediaIcon(type: string) {
switch (type) {
case "photo":
@@ -95,10 +99,14 @@ function getMediaIcon(type: string) {
}
function formatDate(dateStr: string): string {
try {
if (dateStr.includes("T")) {
const [datePart, timePart] = dateStr.split("T");
const timeClean = timePart.split("+")[0].split("Z")[0];
return `${datePart} • ${timeClean}`;
const d = new Date(dateStr);
if (!Number.isNaN(d.getTime())) {
const year = d.getFullYear();
const month = String(d.getMonth() + 1).padStart(2, "0");
const day = String(d.getDate()).padStart(2, "0");
const hours = String(d.getHours()).padStart(2, "0");
const minutes = String(d.getMinutes()).padStart(2, "0");
return `${year}-${month}-${day} ${hours}:${minutes}`;
}
return dateStr;
}
@@ -168,7 +176,6 @@ function formatJoinDate(dateStr: string): string {
return dateStr;
}
}
function getAccountFolderName(accountInfo: AccountInfo): string {
if (accountInfo.nick === "My Bookmarks" || accountInfo.name === "bookmarks") {
return "My Bookmarks";
@@ -176,9 +183,26 @@ function getAccountFolderName(accountInfo: AccountInfo): string {
if (accountInfo.nick === "My Likes" || accountInfo.name === "likes") {
return "My Likes";
}
return accountInfo.name;
const template = getSettings().folderTemplate;
const pad = (n: number) => String(n).padStart(2, "0");
const now = new Date();
const rendered = renderFolderTemplate(template, {
username: accountInfo.name,
date: `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}`,
});
return rendered || accountInfo.name;
}
function pickVariantUrl(variants: {
name: string;
url: string;
}[] | undefined, size: string, fallback: string): string {
if (variants && variants.length > 0) {
const match = variants.find((v) => v.name === size);
if (match?.url)
return match.url;
}
return fallback;
}
export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType = "all", newMediaCount = null, }: MediaListProps) {
const settings = getSettings();
const folderName = getAccountFolderName(accountInfo);
@@ -188,7 +212,13 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set());
const [sortBy, setSortBy] = useState<string>("date-desc");
const [filterType, setFilterType] = useState<string>("all");
const [viewMode, setViewMode] = useState<"large" | "small" | "list">("list");
const [viewMode, setViewMode] = useState<"large" | "small" | "list">(() => {
const stored = localStorage.getItem("resultViewMode");
return stored === "large" || stored === "small" || stored === "list" ? stored : "list";
});
useEffect(() => {
localStorage.setItem("resultViewMode", viewMode);
}, [viewMode]);
const [isDownloading, setIsDownloading] = useState(false);
const [downloadProgress, setDownloadProgress] = useState<DownloadProgress | null>(null);
const [hasDownloaded, setHasDownloaded] = useState(false);
@@ -466,6 +496,8 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
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) {
@@ -537,6 +569,30 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
console.error("Failed to stop download:", error);
}
};
const handleDownloadProfileImage = async (kind: "avatar" | "banner") => {
const settings = getSettings();
const url = kind === "avatar"
? pickVariantUrl(accountInfo.avatar_variants, settings.avatarSize, accountInfo.profile_image)
: pickVariantUrl(accountInfo.banner_variants, settings.bannerSize, accountInfo.banner || "");
if (!url) {
toast.error(`No ${kind} available`);
return;
}
try {
await DownloadProfileImage(new main.DownloadProfileImageRequest({
url,
output_dir: settings.downloadPath,
username: folderName,
kind,
proxy: settings.proxy || "",
}));
toast.success(`${kind === "avatar" ? "Avatar" : "Banner"} downloaded`);
}
catch (error) {
logger.error(`Failed to download ${kind}: ${error}`);
toast.error(`Failed to download ${kind}`);
}
};
const handleOpenFolder = async () => {
const settings = getSettings();
const isBookmarks = accountInfo.nick === "My Bookmarks";
@@ -633,40 +689,69 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
</div>
<div className="text-sm text-muted-foreground">items found</div>
</div>
</div>) : (<div className="flex items-center gap-4 p-4 bg-muted/50 rounded-lg">
<img src={accountInfo.profile_image} alt={accountInfo.nick} className="w-16 h-16 rounded-full"/>
<div className="flex-1">
<div className="flex items-center gap-2">
<h2 className="text-xl">{accountInfo.nick}</h2>
<span className="text-muted-foreground">@{accountInfo.name}</span>
</div>) : (<div className="rounded-lg overflow-hidden bg-muted/50 border">
{accountInfo.banner && (<div className="group/banner relative h-24 w-full bg-cover bg-center" style={{ backgroundImage: `url("${accountInfo.banner}")` }}>
<button type="button" aria-label="Download banner" onClick={() => void handleDownloadProfileImage("banner")} className="absolute top-2 right-2 flex h-9 w-9 items-center justify-center rounded-full bg-black/60 text-white opacity-0 transition-all hover:scale-105 hover:bg-primary hover:text-primary-foreground group-hover/banner:opacity-100">
<Download className="h-4 w-4"/>
</button>
</div>)}
<div className="p-4">
<div className="flex items-end justify-between gap-4">
<div className="flex items-end gap-3 min-w-0">
<div className={`group/avatar relative shrink-0 ${accountInfo.banner ? "-mt-14" : ""}`}>
<img src={accountInfo.profile_image} alt={accountInfo.nick} className={`w-20 h-20 rounded-full object-cover bg-muted ${accountInfo.banner ? "ring-4 ring-background" : ""}`}/>
<button type="button" aria-label="Download avatar" onClick={() => void handleDownloadProfileImage("avatar")} className="absolute inset-0 flex items-center justify-center rounded-full bg-black/50 text-white opacity-0 transition-opacity hover:bg-black/62 group-hover/avatar:opacity-100">
<Download className="h-5 w-5"/>
</button>
</div>
<div className="min-w-0">
<div className="flex items-center gap-1.5">
<h2 className="text-xl font-bold truncate">{accountInfo.nick}</h2>
{(accountInfo.verified || accountInfo.blue_verified) && (<BadgeCheck className="h-4 w-4 text-blue-500 shrink-0"/>)}
{accountInfo.protected && (<Lock className="h-3.5 w-3.5 text-muted-foreground shrink-0"/>)}
</div>
<div className="text-sm text-muted-foreground truncate">@{accountInfo.name}</div>
</div>
</div>
<div className="text-right shrink-0">
<div className="flex items-center justify-end gap-2">
{newMediaCount !== null && newMediaCount > 0 && (<div className="text-lg font-semibold text-green-600 dark:text-green-400 animate-in fade-in slide-in-from-left-2 duration-300">
{formatNumberWithComma(newMediaCount)}+
</div>)}
<div className="text-2xl font-bold text-primary">{formatNumberWithComma(totalUrls)}</div>
</div>
<div className="text-sm text-muted-foreground">items found</div>
</div>
</div>
<div className="flex items-center gap-4 text-sm text-muted-foreground mt-1">
<span className="flex items-center gap-1">
<Users className="h-3.5 w-3.5"/>
{formatNumber(accountInfo.followers_count)} followers
</span>
<span className="flex items-center gap-1">
<UserPlus className="h-3.5 w-3.5"/>
{formatNumber(accountInfo.friends_count)} following
</span>
<span className="flex items-center gap-1">
<MessageSquare className="h-3.5 w-3.5"/>
{formatNumber(accountInfo.statuses_count)} posts
</span>
{accountInfo.bio && (<p className="text-sm mt-3 whitespace-pre-wrap wrap-break-word">{accountInfo.bio}</p>)}
<div className="flex flex-wrap items-center gap-x-4 gap-y-1 text-sm text-muted-foreground mt-3">
{accountInfo.location && (<span className="flex items-center gap-1">
<MapPin className="h-3.5 w-3.5"/>
{accountInfo.location}
</span>)}
{accountInfo.url && (<button type="button" onClick={() => openExternal(accountInfo.url!)} className="flex items-center gap-1 hover:underline">
<Link2 className="h-3.5 w-3.5"/>
{accountInfo.url.replace(/^https?:\/\//, "").replace(/\/+$/, "")}
</button>)}
{accountInfo.date && (<span className="flex items-center gap-1">
<Calendar className="h-3.5 w-3.5"/>
Joined {formatJoinDate(accountInfo.date)}
</span>)}
</div>
</div>
<div className="text-right">
<div className="flex items-center justify-end gap-2">
{newMediaCount !== null && newMediaCount > 0 && (<div className="text-lg font-semibold text-green-600 dark:text-green-400 animate-in fade-in slide-in-from-left-2 duration-300">
{formatNumberWithComma(newMediaCount)}+
</div>)}
<div className="text-2xl font-bold text-primary">{formatNumberWithComma(totalUrls)}</div>
<div className="flex flex-wrap items-center gap-x-2 gap-y-1 text-sm mt-3">
<span><strong className="text-foreground">{formatNumber(accountInfo.statuses_count)}</strong> <span className="text-muted-foreground">posts</span></span>
<span className="text-muted-foreground">·</span>
<span><strong className="text-foreground">{formatNumber(accountInfo.friends_count)}</strong> <span className="text-muted-foreground">following</span></span>
<span className="text-muted-foreground">·</span>
<span><strong className="text-foreground">{formatNumber(accountInfo.followers_count)}</strong> <span className="text-muted-foreground">followers</span></span>
{accountInfo.media_count ? (<>
<span className="text-muted-foreground">·</span>
<span><strong className="text-foreground">{formatNumber(accountInfo.media_count)}</strong> <span className="text-muted-foreground">media</span></span>
</>) : null}
</div>
<div className="text-sm text-muted-foreground">items found</div>
</div>
</div>)}
@@ -707,6 +792,12 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
GIFs ({formatNumberWithComma(mediaCounts.gif)})
</span>
</SelectItem>)}
{mediaCounts.text > 0 && (<SelectItem value="text">
<span className="flex items-center gap-2">
<FileText className="h-4 w-4 text-orange-500"/>
Text ({formatNumberWithComma(mediaCounts.text)})
</span>
</SelectItem>)}
</SelectContent>
</Select>)}
@@ -783,15 +874,17 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
const isItemFailed = failedItems.has(itemKey);
const isItemSkipped = skippedItems.has(itemKey);
const isItemDownloading = downloadingItem === itemKey;
return (<div key={itemKey} className={`flex items-center gap-4 p-3 rounded-lg border-2 transition-all ${isSelected ? "border-primary bg-primary/5" : "border-transparent hover:bg-muted/50"}`}>
<Checkbox checked={isSelected} onCheckedChange={() => toggleItem(itemKey)}/>
<span className="text-sm text-muted-foreground w-8 text-center shrink-0">
{index + 1}
</span>
<div className="w-16 h-16 rounded overflow-hidden bg-muted shrink-0 cursor-pointer hover:opacity-80 transition-opacity" onClick={() => openPreview(index)}>
{item.type === "photo" || item.type === "animated_gif" || item.type === "gif" ? (<img src={getThumbnailUrl(item.url)} alt="" className="w-full h-full object-cover" loading="lazy"/>) : (<div className="w-full h-full flex items-center justify-center">
{getMediaIcon(item.type)}
</div>)}
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()}/>
<div className="relative shrink-0">
<span className="absolute -top-1.5 -left-1.5 z-10 flex h-5 min-w-5 items-center justify-center rounded-full bg-primary px-1 text-xs font-medium text-primary-foreground">
{index + 1}
</span>
<div className="w-16 h-16 rounded overflow-hidden bg-muted">
{item.type !== "text" && getEntryThumbnail(item) ? (<img src={getEntryThumbnail(item)} alt="" className="w-full h-full object-cover" loading="lazy"/>) : (<div className="w-full h-full flex items-center justify-center">
{getMediaIcon(item.type)}
</div>)}
</div>
</div>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
@@ -841,6 +934,8 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
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) {
@@ -888,7 +983,10 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
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)}>
{item.type === "photo" || item.type === "animated_gif" || item.type === "gif" ? (<img src={getThumbnailUrl(item.url)} alt="" className="w-full h-full object-cover" loading="lazy"/>) : (<div className="w-full h-full flex items-center justify-center bg-muted">
<span className="absolute top-1.5 left-1.5 z-20 flex h-5 min-w-5 items-center justify-center rounded-full bg-primary px-1 text-xs font-medium text-primary-foreground">
{index + 1}
</span>
{item.type !== "text" && getEntryThumbnail(item) ? (<img src={getEntryThumbnail(item)} alt="" className="w-full h-full object-cover" loading="lazy"/>) : (<div className="w-full h-full flex items-center justify-center bg-muted">
{getMediaIcon(item.type)}
</div>)}
@@ -918,6 +1016,8 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
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) {
@@ -1095,6 +1195,8 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
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) {
+86 -118
View File
@@ -4,30 +4,29 @@ import { Checkbox } from "@/components/ui/checkbox";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { InputWithContext } from "@/components/ui/input-with-context";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { FetchHistory } from "@/components/FetchHistory";
import type { HistoryItem } from "@/components/FetchHistory";
import { toastWithSound as toast } from "@/lib/toast-with-sound";
import { cn } from "@/lib/utils";
import { getSettings, updateSettings, type FetchMode as SettingsFetchMode, type MediaType as SettingsMediaType } 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 { AlertCircle, Bookmark, Calendar, CheckCircle, CloudDownload, Clock, Eye, EyeOff, Globe, Heart, Hourglass, Info, Lock, RotateCcw, SlidersHorizontal, StopCircle, Trash2, User, Users, XCircle } from "lucide-react";
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 { Spinner } from "@/components/ui/spinner";
function formatNumberWithComma(num: number): string {
return num.toLocaleString();
}
function pillClass(active: boolean): string {
return cn("rounded-md px-3 py-1.5 text-sm font-medium transition-colors cursor-pointer", active
? "bg-primary text-primary-foreground"
: "bg-muted text-muted-foreground hover:text-foreground");
}
export type FetchMode = "public" | "private";
export type PrivateType = "bookmarks" | "likes";
export type FetchType = "single" | "multiple";
const LEGACY_PUBLIC_AUTH_TOKEN_KEY = "twitter_public_auth_token";
const LEGACY_PRIVATE_AUTH_TOKEN_KEY = "twitter_private_auth_token";
let sessionAuthToken = "";
export interface MultipleAccount {
id: string;
username: string;
@@ -45,7 +44,6 @@ export interface MultipleAccount {
showDiff?: boolean;
cursor?: string;
}
interface SearchBarProps {
username: string;
loading: boolean;
@@ -74,19 +72,22 @@ interface SearchBarProps {
onRetryAccount?: (accountId: string, authToken: string) => void;
onClearMultipleAccounts?: () => void;
onRemoveMultipleAccount?: (accountId: string) => void;
onOpenSavedAccounts?: () => void;
isFetchingAll?: boolean;
mode?: FetchMode;
privateType?: PrivateType;
onModeChange?: (mode: FetchMode, privateType?: PrivateType) => void;
}
export function SearchBar({ username, loading, onUsernameChange, onFetch, onStopFetch, onResume, onClearResume, resumeInfo, history, onHistorySelect, onHistoryRemove, hasResult, elapsedTime = 0, remainingTime = null, fetchType = "single", onFetchTypeChange, multipleAccounts = [], onImportAccounts, onFetchAll, onStopAll, onStopAccount, onRetryAccount, onClearMultipleAccounts, onRemoveMultipleAccount, isFetchingAll = false, mode: externalMode, privateType: externalPrivateType, onModeChange, }: SearchBarProps) {
const [useDateRange, setUseDateRange] = useState(false);
const [startDate, setStartDate] = useState("");
const [endDate, setEndDate] = useState("");
const [mediaType, setMediaType] = useState<SettingsMediaType>(getSettings().mediaType);
export function SearchBar({ username, loading, onUsernameChange, onFetch, onStopFetch, onResume, onClearResume, resumeInfo, history, onHistorySelect, onHistoryRemove, hasResult, elapsedTime = 0, remainingTime = null, fetchType = "single", onFetchTypeChange, multipleAccounts = [], onImportAccounts, onFetchAll, onStopAll, onStopAccount, onRetryAccount, onClearMultipleAccounts, onRemoveMultipleAccount, onOpenSavedAccounts, isFetchingAll = false, mode: externalMode, privateType: externalPrivateType, onModeChange, }: SearchBarProps) {
const [includePhotos, setIncludePhotos] = useState(getSettings().includePhotos);
const [includeVideos, setIncludeVideos] = useState(getSettings().includeVideos);
const [includeGifs, setIncludeGifs] = useState(getSettings().includeGifs);
const [includeText, setIncludeText] = useState(getSettings().includeText);
const [retweets, setRetweets] = useState(getSettings().includeRetweets);
const [currentFetchMode, setCurrentFetchMode] = useState<SettingsFetchMode>(getSettings().fetchMode);
const [videoQuality, setVideoQuality] = useState<VideoQuality>(getSettings().videoQuality);
const [imageSize, setImageSize] = useState<ImageSize>(getSettings().imageSize);
const [avatarSize, setAvatarSize] = useState<AvatarSize>(getSettings().avatarSize);
const [bannerSize, setBannerSize] = useState<BannerSize>(getSettings().bannerSize);
const [sharedAuthToken, setSharedAuthToken] = useState(() => sessionAuthToken || localStorage.getItem(LEGACY_PUBLIC_AUTH_TOKEN_KEY) || localStorage.getItem(LEGACY_PRIVATE_AUTH_TOKEN_KEY) || "");
const [showAuthToken, setShowAuthToken] = useState(false);
const [showAuthRequiredDialog, setShowAuthRequiredDialog] = useState(false);
@@ -94,29 +95,31 @@ export function SearchBar({ username, loading, onUsernameChange, onFetch, onStop
useEffect(() => {
if (showSettingsDialog) {
const fresh = getSettings();
setMediaType(fresh.mediaType);
setIncludePhotos(fresh.includePhotos);
setIncludeVideos(fresh.includeVideos);
setIncludeGifs(fresh.includeGifs);
setIncludeText(fresh.includeText);
setRetweets(fresh.includeRetweets);
setCurrentFetchMode(fresh.fetchMode);
setVideoQuality(fresh.videoQuality);
setImageSize(fresh.imageSize);
setAvatarSize(fresh.avatarSize);
setBannerSize(fresh.bannerSize);
}
}, [showSettingsDialog]);
const [showImportDialog, setShowImportDialog] = useState(false);
const [importAccountsText, setImportAccountsText] = useState("");
const [authPromptToken, setAuthPromptToken] = useState("");
const mode = externalMode || "public";
const privateType = externalPrivateType || "bookmarks";
const isLikesMode = mode === "private" && privateType === "likes";
const isBookmarksMode = mode === "private" && privateType === "bookmarks";
const isAnyMultipleAccountFetching = multipleAccounts.some((account) => account.status === "fetching");
useEffect(() => {
let active = true;
const syncStoredTokens = async () => {
const legacyPublicToken = localStorage.getItem(LEGACY_PUBLIC_AUTH_TOKEN_KEY) || "";
const legacyPrivateToken = localStorage.getItem(LEGACY_PRIVATE_AUTH_TOKEN_KEY) || "";
const legacyUnifiedToken = legacyPublicToken || legacyPrivateToken;
try {
if (legacyUnifiedToken) {
await Promise.all([
@@ -132,7 +135,6 @@ export function SearchBar({ username, loading, onUsernameChange, onFetch, onStop
localStorage.removeItem(LEGACY_PUBLIC_AUTH_TOKEN_KEY);
localStorage.removeItem(LEGACY_PRIVATE_AUTH_TOKEN_KEY);
}
try {
const [storedPublicToken, storedPrivateToken] = await Promise.all([
GetStoredAuthToken("public"),
@@ -141,11 +143,9 @@ export function SearchBar({ username, loading, onUsernameChange, onFetch, onStop
if (!active) {
return;
}
const unifiedToken = storedPublicToken || storedPrivateToken || "";
sessionAuthToken = unifiedToken;
setSharedAuthToken(unifiedToken);
if (unifiedToken && (storedPublicToken !== unifiedToken || storedPrivateToken !== unifiedToken)) {
await Promise.all([
SetStoredAuthToken("public", unifiedToken),
@@ -157,14 +157,11 @@ export function SearchBar({ username, loading, onUsernameChange, onFetch, onStop
console.error("Failed to load auth token from secure storage:", error);
}
};
void syncStoredTokens();
return () => {
active = false;
};
}, []);
const tokenWriteTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const pendingAuthActionRef = useRef<((authToken: string) => void) | null>(null);
useEffect(() => {
@@ -174,7 +171,6 @@ export function SearchBar({ username, loading, onUsernameChange, onFetch, onStop
}
};
}, []);
const handleSharedTokenChange = (value: string) => {
sessionAuthToken = value;
setSharedAuthToken(value);
@@ -190,14 +186,12 @@ export function SearchBar({ username, loading, onUsernameChange, onFetch, onStop
});
}, 400);
};
const closeAuthRequiredDialog = (open: boolean) => {
setShowAuthRequiredDialog(open);
if (!open) {
pendingAuthActionRef.current = null;
}
};
const requireAuthToken = (onAuthorized: (authToken: string) => void) => {
const token = sharedAuthToken.trim();
if (token) {
@@ -208,33 +202,28 @@ export function SearchBar({ username, loading, onUsernameChange, onFetch, onStop
setAuthPromptToken(sharedAuthToken);
setShowAuthRequiredDialog(true);
};
const handleFetch = () => {
requireAuthToken((authToken) => {
onFetch(useDateRange, startDate, endDate, mediaType, retweets, mode, privateType, authToken, false);
onFetch(false, undefined, undefined, undefined, retweets, mode, privateType, authToken, false);
});
};
const handleResume = () => {
if (onResume) {
requireAuthToken((authToken) => {
onResume(authToken, mediaType, retweets);
onResume(authToken, undefined, retweets);
});
}
};
const handleFetchAll = () => {
requireAuthToken((authToken) => {
onFetchAll?.(authToken);
});
};
const handleRetry = (accountId: string) => {
requireAuthToken((authToken) => {
onRetryAccount?.(accountId, authToken);
});
};
const handleAuthPromptSubmit = () => {
const token = authPromptToken.trim();
if (!token) {
@@ -247,39 +236,32 @@ export function SearchBar({ username, loading, onUsernameChange, onFetch, onStop
setShowAuthRequiredDialog(false);
pendingAction?.(token);
};
const handleOpenFetchSettings = () => {
pendingAuthActionRef.current = null;
setShowAuthRequiredDialog(false);
setShowSettingsDialog(true);
};
const openImportDialog = () => {
setImportAccountsText(multipleAccounts.map((account) => account.username).join("\n"));
setShowImportDialog(true);
};
const handleImportSubmit = () => {
const accounts = importAccountsText
.split(/[\n,;]+/)
.map((entry) => entry.trim())
.filter((entry) => entry.length > 0);
if (accounts.length === 0) {
toast.error("Please enter at least one account");
return;
}
onImportAccounts?.(accounts);
setShowImportDialog(false);
};
const formatTime = (seconds: number): string => {
const mins = Math.floor(seconds / 60);
const secs = seconds % 60;
return `${mins}:${String(secs).padStart(2, "0")}`;
};
const activeCountdown = remainingTime !== null && remainingTime >= 0
? formatTime(remainingTime)
: elapsedTime > 0
@@ -289,7 +271,6 @@ export function SearchBar({ username, loading, onUsernameChange, onFetch, onStop
const authTokenHelpText = mode === "private"
? "Use auth token from the account whose bookmarks or likes you want to fetch."
: "Recommended to use a dummy account, not your main account. Excessive usage may cause suspension.";
return (<div className="space-y-3">
<div className="flex justify-center gap-2">
@@ -508,11 +489,17 @@ export function SearchBar({ username, loading, onUsernameChange, onFetch, onStop
</span>
</div>
<div className="ml-auto flex items-center gap-2">
<span className="text-muted-foreground">Total:</span>
<span className="font-medium">
{formatNumberWithComma(multipleAccounts.filter((acc) => acc.status === "completed" || acc.status === "incomplete" || acc.status === "failed").length)}/{formatNumberWithComma(multipleAccounts.length)}
</span>
<div className="ml-auto flex items-center gap-3">
<div className="flex items-center gap-2">
<span className="text-muted-foreground">Total:</span>
<span className="font-medium">
{formatNumberWithComma(multipleAccounts.filter((acc) => acc.status === "completed" || acc.status === "incomplete" || acc.status === "failed").length)}/{formatNumberWithComma(multipleAccounts.length)}
</span>
</div>
{!isFetchingAll && onOpenSavedAccounts && multipleAccounts.some((acc) => acc.status === "completed" || acc.status === "incomplete") && (<Button variant="secondary" size="sm" onClick={onOpenSavedAccounts} className="flex items-center gap-2">
<Database className="h-3.5 w-3.5"/>
Open Saved Accounts to Download
</Button>)}
</div>
</div>
</div>)}
@@ -557,8 +544,8 @@ export function SearchBar({ username, loading, onUsernameChange, onFetch, onStop
<Clock className="h-3.5 w-3.5 shrink-0 text-muted-foreground"/>
<span className="font-mono">
{account.remainingTime !== null && account.remainingTime >= 0
? formatTime(account.remainingTime)
: formatTime(account.elapsedTime)}
? formatTime(account.remainingTime)
: formatTime(account.elapsedTime)}
</span>
</div>
<Button variant="destructive" onClick={() => onStopAccount?.(account.id)} className="flex items-center gap-2">
@@ -640,10 +627,10 @@ export function SearchBar({ username, loading, onUsernameChange, onFetch, onStop
<Label htmlFor="required-auth-token">Auth Token</Label>
<div className="relative">
<InputWithContext id="required-auth-token" type={showAuthToken ? "text" : "password"} placeholder="Enter your auth_token cookie value" value={authPromptToken} onChange={(e) => setAuthPromptToken(e.target.value)} onKeyDown={(e) => {
if (e.key === "Enter") {
handleAuthPromptSubmit();
}
}} className="pr-10"/>
if (e.key === "Enter") {
handleAuthPromptSubmit();
}
}} className="pr-10"/>
<button type="button" aria-label={showAuthToken ? "Hide auth token" : "Show auth token"} className="absolute top-1/2 right-2 -translate-y-1/2 text-muted-foreground transition-colors hover:text-foreground" onClick={() => setShowAuthToken((prev) => !prev)}>
{showAuthToken ? <EyeOff className="h-4 w-4"/> : <Eye className="h-4 w-4"/>}
</button>
@@ -690,12 +677,12 @@ export function SearchBar({ username, loading, onUsernameChange, onFetch, onStop
</Dialog>
<Dialog open={showSettingsDialog} onOpenChange={setShowSettingsDialog}>
<DialogContent className="sm:max-w-xl">
<DialogContent className="sm:max-w-xl max-h-[85vh] flex flex-col overflow-hidden">
<DialogHeader>
<DialogTitle>Fetch Settings</DialogTitle>
</DialogHeader>
<div className="space-y-5">
<div className="space-y-4 overflow-y-auto flex-1 min-h-0 -mx-2 px-2">
<div className="space-y-2">
<div className="flex items-center gap-2">
<Label htmlFor="shared-auth-token" className="text-sm">Auth Token</Label>
@@ -709,74 +696,55 @@ export function SearchBar({ username, loading, onUsernameChange, onFetch, onStop
</Tooltip>
</div>
<div className="relative">
<InputWithContext id="shared-auth-token" type={showAuthToken ? "text" : "password"} placeholder="Enter your auth_token cookie value" value={sharedAuthToken} onChange={(e) => void handleSharedTokenChange(e.target.value)} className="pr-10"/>
<button type="button" aria-label={showAuthToken ? "Hide auth token" : "Show auth token"} className="absolute top-1/2 right-2 -translate-y-1/2 text-muted-foreground transition-colors hover:text-foreground" onClick={() => setShowAuthToken((prev) => !prev)}>
{showAuthToken ? <EyeOff className="h-4 w-4"/> : <Eye className="h-4 w-4"/>}
</button>
</div>
<InputWithContext id="shared-auth-token" type="text" placeholder="Enter your auth_token cookie value" value={sharedAuthToken} onChange={(e) => void handleSharedTokenChange(e.target.value)}/>
</div>
<div className="space-y-3">
<div className="flex items-center justify-between gap-4">
<Label htmlFor="fetch-mode" className="text-sm">Fetch Mode</Label>
<Select value={currentFetchMode} onValueChange={(value: SettingsFetchMode) => {
updateSettings({ fetchMode: value });
setCurrentFetchMode(value);
}}>
<SelectTrigger id="fetch-mode" className="w-28">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="batch">Batch</SelectItem>
<SelectItem value="single">Single</SelectItem>
</SelectContent>
</Select>
{fetchType === "single" && (<div className="flex items-center justify-between gap-4">
<Label htmlFor="retweets" className="cursor-pointer text-sm">Include Reposts</Label>
<Checkbox id="retweets" checked={retweets} onCheckedChange={(checked) => {
const value = checked as boolean;
updateSettings({ includeRetweets: value });
setRetweets(value);
}}/>
</div>)}
<div className="space-y-2">
<Label className="text-sm">Include Media</Label>
<div className="grid grid-cols-4 gap-2">
<button type="button" className={pillClass(includePhotos)} onClick={() => { updateSettings({ includePhotos: !includePhotos }); setIncludePhotos((v) => !v); }}>Photos</button>
<button type="button" className={pillClass(includeVideos)} onClick={() => { updateSettings({ includeVideos: !includeVideos }); setIncludeVideos((v) => !v); }}>Videos</button>
<button type="button" className={pillClass(includeGifs)} onClick={() => { updateSettings({ includeGifs: !includeGifs }); setIncludeGifs((v) => !v); }}>GIFs</button>
<button type="button" className={pillClass(includeText)} onClick={() => { updateSettings({ includeText: !includeText }); setIncludeText((v) => !v); }}>Text</button>
</div>
</div>
<div className="flex items-center justify-between gap-4">
<Label htmlFor="media-type" className="text-sm">Media Type</Label>
<Select value={mediaType} onValueChange={(value: SettingsMediaType) => {
updateSettings({ mediaType: value });
setMediaType(value);
}}>
<SelectTrigger id="media-type" className="w-40">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">All Media</SelectItem>
<SelectItem value="image">Images</SelectItem>
<SelectItem value="video">Videos</SelectItem>
<SelectItem value="gif">GIFs</SelectItem>
<SelectItem value="text">Text (No Media)</SelectItem>
</SelectContent>
</Select>
<div className="space-y-2">
<Label className="text-sm">Video Quality</Label>
<div className="grid grid-cols-5 gap-2">
{VIDEO_QUALITIES.map((q) => (<button key={q.value} type="button" className={pillClass(videoQuality === q.value)} onClick={() => { updateSettings({ videoQuality: q.value }); setVideoQuality(q.value); }}>{q.label}</button>))}
</div>
</div>
{fetchType === "single" && (<div className="flex items-center justify-between gap-4">
<Label htmlFor="retweets" className="cursor-pointer text-sm">Include Retweets</Label>
<Checkbox id="retweets" checked={retweets} onCheckedChange={(checked) => {
const value = checked as boolean;
updateSettings({ includeRetweets: value });
setRetweets(value);
}}/>
</div>)}
<div className="space-y-2">
<Label className="text-sm">Image Size</Label>
<div className="grid grid-cols-4 gap-2">
{IMAGE_SIZES.map((s) => (<button key={s.value} type="button" className={pillClass(imageSize === s.value)} onClick={() => { updateSettings({ imageSize: s.value }); setImageSize(s.value); }}>{s.label}</button>))}
</div>
</div>
{fetchType === "single" && mode === "public" && (<div className="space-y-3">
<div className="flex items-center justify-between gap-4">
<Label htmlFor="date-range" className="flex cursor-pointer items-center gap-2 text-sm">
<Calendar className="h-4 w-4"/>
Date Range
</Label>
<Checkbox id="date-range" checked={useDateRange} onCheckedChange={(checked) => setUseDateRange(checked as boolean)}/>
</div>
<div className="space-y-2">
<Label className="text-sm">Avatar Size</Label>
<div className="grid grid-cols-5 gap-2">
{AVATAR_SIZES.map((s) => (<button key={s.value} type="button" className={pillClass(avatarSize === s.value)} onClick={() => { updateSettings({ avatarSize: s.value }); setAvatarSize(s.value); }}>{s.label}</button>))}
</div>
</div>
{useDateRange && (<div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
<InputWithContext id="start-date" type="date" value={startDate} onChange={(e) => setStartDate(e.target.value)}/>
<InputWithContext id="end-date" type="date" value={endDate} onChange={(e) => setEndDate(e.target.value)}/>
</div>)}
</div>)}
<div className="space-y-2">
<Label className="text-sm">Banner Size</Label>
<div className="grid grid-cols-4 gap-2">
{BANNER_SIZES.map((s) => (<button key={s.value} type="button" className={pillClass(bannerSize === s.value)} onClick={() => { updateSettings({ bannerSize: s.value }); setBannerSize(s.value); }}>{s.label}</button>))}
</div>
</div>
</div>
+96 -103
View File
@@ -6,31 +6,28 @@ import { InputWithContext } from "@/components/ui/input-with-context";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { Check, Download, ExternalLink, FolderOpen, Info, MonitorCog, PackageSearch, Plus, RotateCcw, Save, Trash2 } from "lucide-react";
import { Check, Download, ExternalLink, FolderOpen, Info, MonitorCog, PackageSearch, Plus, RotateCcw, Save, Trash2, FileSignature } from "lucide-react";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from "@/components/ui/dialog";
import { Spinner } from "@/components/ui/spinner";
import { Switch } from "@/components/ui/switch";
import { getSettings, getSettingsWithDefaults, saveSettings, resetToDefaultSettings, applyThemeMode, applyFont, getFontOptions, parseGoogleFontUrl, loadGoogleFontUrl, loadCustomFonts, saveCustomFonts, type Settings as SettingsType, type FontFamily, type GifQuality, type GifResolution, type CustomFontFamily } from "@/lib/settings";
import { getSettings, getSettingsWithDefaults, saveSettings, resetToDefaultSettings, applyThemeMode, applyFont, getFontOptions, parseGoogleFontUrl, loadGoogleFontUrl, loadCustomFonts, saveCustomFonts, DEFAULT_FILENAME_TEMPLATE, FILENAME_TEMPLATE_VARIABLES, renderFilenameTemplate, SAMPLE_FILENAME_DATA, DEFAULT_FOLDER_TEMPLATE, FOLDER_TEMPLATE_VARIABLES, renderFolderTemplate, SAMPLE_FOLDER_DATA, type Settings as SettingsType, type FontFamily, type GifQuality, type GifResolution, type CustomFontFamily } from "@/lib/settings";
import { FormatEditor } from "@/components/FormatEditor";
import { getCachedDependencyStatus, setCachedDependencyStatus } from "@/lib/runtime-cache";
import { themes, applyTheme } from "@/lib/themes";
import { compareVersionNumbers } from "@/lib/version";
import { SelectFolder, IsExtractorInstalled, DownloadExtractor, IsFFmpegInstalled, DownloadFFmpeg, IsExifToolInstalled, DownloadExifTool } from "../../wailsjs/go/main/App";
import { toastWithSound as toast } from "@/lib/toast-with-sound";
interface DependencyVersionStatus {
installed: boolean;
installed_version?: string;
latest_version?: string;
}
type DependencyVersionMethod = "GetExtractorVersionStatus" | "GetFFmpegVersionStatus" | "GetExifToolVersionStatus";
type SettingsTab = "general" | "downloads" | "dependencies";
type SettingsTab = "general" | "downloads" | "naming" | "dependencies";
interface SettingsPageProps {
onUnsavedChangesChange?: (hasUnsavedChanges: boolean) => void;
onResetRequest?: (resetFn: () => void) => void;
}
function getDependencyVersionStatus(methodName: DependencyVersionMethod) {
const app = (window as Window & {
go?: {
@@ -42,14 +39,12 @@ function getDependencyVersionStatus(methodName: DependencyVersionMethod) {
const method = app?.[methodName];
return method ? method() : Promise.resolve(null);
}
function hasNewDependencyVersion(installedVersion: string | null, latestVersion: string | null) {
if (!installedVersion || !latestVersion) {
return false;
}
return compareVersionNumbers(latestVersion, installedVersion) > 0;
}
function buildDependencyVersionText(name: string, installed: boolean, installedVersion: string | null, latestVersion: string | null, updateAvailable: boolean) {
if (installed) {
if (!installedVersion) {
@@ -61,7 +56,6 @@ function buildDependencyVersionText(name: string, installed: boolean, installedV
}
return latestVersion ? `Latest ${name}: ${latestVersion}` : null;
}
export function SettingsPage({ onUnsavedChangesChange, onResetRequest }: SettingsPageProps) {
const cachedExtractorStatus = getCachedDependencyStatus("extractor");
const cachedFfmpegStatus = getCachedDependencyStatus("ffmpeg");
@@ -85,14 +79,12 @@ export function SettingsPage({ onUnsavedChangesChange, onResetRequest }: Setting
const [exiftoolLatestVersion, setExiftoolLatestVersion] = useState<string | null>(cachedExiftoolStatus.latestVersion);
const [downloadingExifTool, setDownloadingExifTool] = useState(false);
const [showResetConfirm, setShowResetConfirm] = useState(false);
const extractorUpdateAvailable = hasNewDependencyVersion(extractorInstalledVersion, extractorLatestVersion);
const ffmpegUpdateAvailable = hasNewDependencyVersion(ffmpegInstalledVersion, ffmpegLatestVersion);
const exiftoolUpdateAvailable = hasNewDependencyVersion(exiftoolInstalledVersion, exiftoolLatestVersion);
const parsedAddFont = parseGoogleFontUrl(addFontUrl);
const fontOptions = getFontOptions(tempSettings.customFonts);
const hasUnsavedChanges = JSON.stringify(savedSettings) !== JSON.stringify(tempSettings);
const resetToSaved = useCallback(() => {
const freshSavedSettings = getSettings();
flushSync(() => {
@@ -100,17 +92,14 @@ export function SettingsPage({ onUnsavedChangesChange, onResetRequest }: Setting
setIsDark(document.documentElement.classList.contains("dark"));
});
}, []);
useEffect(() => {
if (onResetRequest) {
onResetRequest(resetToSaved);
}
}, [onResetRequest, resetToSaved]);
useEffect(() => {
onUnsavedChangesChange?.(hasUnsavedChanges);
}, [hasUnsavedChanges, onUnsavedChangesChange]);
const extractorVersionText = extractorInstalled
? extractorInstalledVersion
? extractorUpdateAvailable && extractorLatestVersion
@@ -120,10 +109,8 @@ export function SettingsPage({ onUnsavedChangesChange, onResetRequest }: Setting
: extractorLatestVersion
? `Latest: ${extractorLatestVersion}`
: null;
const ffmpegVersionText = buildDependencyVersionText("FFmpeg", ffmpegInstalled, ffmpegInstalledVersion, ffmpegLatestVersion, ffmpegUpdateAvailable);
const exiftoolVersionText = buildDependencyVersionText("ExifTool", exiftoolInstalled, exiftoolInstalledVersion, exiftoolLatestVersion, exiftoolUpdateAvailable);
const loadDependencyStatus = async () => {
try {
const [extractorVersionStatus, ffmpegVersionStatus, exiftoolVersionStatus, extractor, ffmpeg, exiftool] = await Promise.all([
@@ -143,7 +130,6 @@ export function SettingsPage({ onUnsavedChangesChange, onResetRequest }: Setting
const nextExiftoolInstalled = exiftoolVersionStatus?.installed ?? exiftool;
const nextExiftoolInstalledVersion = exiftoolVersionStatus?.installed_version?.trim() || null;
const nextExiftoolLatestVersion = exiftoolVersionStatus?.latest_version?.trim() || null;
setCachedDependencyStatus("extractor", {
installed: nextExtractorInstalled,
installedVersion: nextExtractorInstalledVersion,
@@ -159,7 +145,6 @@ export function SettingsPage({ onUnsavedChangesChange, onResetRequest }: Setting
installedVersion: nextExiftoolInstalledVersion,
latestVersion: nextExiftoolLatestVersion,
});
setExtractorInstalled(nextExtractorInstalled);
setExtractorInstalledVersion(nextExtractorInstalledVersion);
setExtractorLatestVersion(nextExtractorLatestVersion);
@@ -174,7 +159,6 @@ export function SettingsPage({ onUnsavedChangesChange, onResetRequest }: Setting
console.error("Failed to check dependency status:", error);
}
};
useEffect(() => {
applyThemeMode(savedSettings.themeMode);
applyTheme(savedSettings.theme);
@@ -188,7 +172,6 @@ export function SettingsPage({ onUnsavedChangesChange, onResetRequest }: Setting
mediaQuery.addEventListener("change", handleChange);
return () => mediaQuery.removeEventListener("change", handleChange);
}, [savedSettings.themeMode, savedSettings.theme]);
useEffect(() => {
applyThemeMode(tempSettings.themeMode);
applyTheme(tempSettings.theme);
@@ -197,13 +180,11 @@ export function SettingsPage({ onUnsavedChangesChange, onResetRequest }: Setting
setIsDark(document.documentElement.classList.contains("dark"));
}, 0);
}, [tempSettings.themeMode, tempSettings.theme, tempSettings.fontFamily, tempSettings.customFonts]);
useEffect(() => {
if (showAddFontDialog && parsedAddFont) {
loadGoogleFontUrl(parsedAddFont.url, "twitter-media-add-font-preview");
}
}, [showAddFontDialog, parsedAddFont]);
useEffect(() => {
const loadDefaults = async () => {
if (!savedSettings.downloadPath) {
@@ -215,7 +196,6 @@ export function SettingsPage({ onUnsavedChangesChange, onResetRequest }: Setting
void loadDefaults();
void loadDependencyStatus();
}, []);
useEffect(() => {
const syncCustomFonts = async () => {
const customFonts = await loadCustomFonts();
@@ -224,14 +204,12 @@ export function SettingsPage({ onUnsavedChangesChange, onResetRequest }: Setting
};
void syncCustomFonts();
}, []);
const handleSave = () => {
saveSettings(tempSettings);
setSavedSettings(tempSettings);
toast.success("Settings saved");
onUnsavedChangesChange?.(false);
};
const handleReset = async () => {
const defaultSettings = await resetToDefaultSettings();
setTempSettings(defaultSettings);
@@ -242,7 +220,6 @@ export function SettingsPage({ onUnsavedChangesChange, onResetRequest }: Setting
setShowResetConfirm(false);
toast.success("Settings reset to default");
};
const handleBrowseFolder = async () => {
try {
const selectedPath = await SelectFolder(tempSettings.downloadPath || "");
@@ -255,12 +232,10 @@ export function SettingsPage({ onUnsavedChangesChange, onResetRequest }: Setting
toast.error(`Error selecting folder: ${error}`);
}
};
const closeAddFontDialog = () => {
setShowAddFontDialog(false);
setAddFontUrl("");
};
const handleAddFont = async () => {
if (!parsedAddFont) {
toast.error("Enter a valid Google Fonts URL");
@@ -281,7 +256,6 @@ export function SettingsPage({ onUnsavedChangesChange, onResetRequest }: Setting
closeAddFontDialog();
toast.success(`${parsedAddFont.label} added`);
};
const handleDeleteCustomFont = async (fontValue: CustomFontFamily) => {
const customFonts = (tempSettings.customFonts || []).filter((font) => font.value !== fontValue);
const savedCustomFonts = await saveCustomFonts(customFonts);
@@ -303,7 +277,6 @@ export function SettingsPage({ onUnsavedChangesChange, onResetRequest }: Setting
}
toast.success("Font deleted");
};
const handleDownloadExtractor = async () => {
setDownloadingExtractor(true);
try {
@@ -324,7 +297,6 @@ export function SettingsPage({ onUnsavedChangesChange, onResetRequest }: Setting
setDownloadingExtractor(false);
}
};
const handleDownloadFFmpeg = async () => {
setDownloadingFFmpeg(true);
try {
@@ -345,7 +317,6 @@ export function SettingsPage({ onUnsavedChangesChange, onResetRequest }: Setting
setDownloadingFFmpeg(false);
}
};
const handleDownloadExifTool = async () => {
setDownloadingExifTool(true);
try {
@@ -366,7 +337,6 @@ export function SettingsPage({ onUnsavedChangesChange, onResetRequest }: Setting
setDownloadingExifTool(false);
}
};
return (<div className="space-y-4">
<div className="flex items-center justify-between">
<h1 className="text-2xl font-bold">Settings</h1>
@@ -391,6 +361,10 @@ export function SettingsPage({ onUnsavedChangesChange, onResetRequest }: Setting
<Download className="h-4 w-4"/>
Downloads
</Button>
<Button variant={activeTab === "naming" ? "default" : "ghost"} size="sm" onClick={() => setActiveTab("naming")} className="rounded-b-none gap-2">
<FileSignature className="h-4 w-4"/>
Naming
</Button>
<Button variant={activeTab === "dependencies" ? "default" : "ghost"} size="sm" onClick={() => setActiveTab("dependencies")} className="rounded-b-none gap-2">
<PackageSearch className="h-4 w-4"/>
Dependencies
@@ -490,28 +464,54 @@ export function SettingsPage({ onUnsavedChangesChange, onResetRequest }: Setting
</div>
<div className="space-y-4">
<div className="space-y-2">
<Label htmlFor="concurrent-downloads" className="flex items-center gap-2">
Concurrent Downloads
<Tooltip>
<TooltipTrigger asChild>
<Info className="h-3.5 w-3.5 cursor-help text-muted-foreground"/>
</TooltipTrigger>
<TooltipContent side="top">
<p>How many media files can download at the same time.</p>
</TooltipContent>
<div className="flex flex-wrap gap-6">
<div className="space-y-2">
<Label htmlFor="concurrent-downloads" className="flex items-center gap-2">
Concurrent Downloads
<Tooltip>
<TooltipTrigger asChild>
<Info className="h-3.5 w-3.5 cursor-help text-muted-foreground"/>
</TooltipTrigger>
<TooltipContent side="top">
<p>How many media files can download at the same time.</p>
</TooltipContent>
</Tooltip>
</Label>
<Select value={String(tempSettings.concurrentDownloads || 10)} onValueChange={(value) => setTempSettings((prev) => ({ ...prev, concurrentDownloads: parseInt(value, 10) }))}>
<SelectTrigger id="concurrent-downloads" className="w-28">
<SelectValue placeholder="10"/>
</SelectTrigger>
<SelectContent>
{[1, 2, 3, 5, 8, 10, 15, 20, 25, 30, 40, 50].map((value) => (<SelectItem key={value} value={String(value)}>
{value}
</SelectItem>))}
</SelectContent>
</Select>
<Select value={String(tempSettings.concurrentDownloads || 10)} onValueChange={(value) => setTempSettings((prev) => ({ ...prev, concurrentDownloads: parseInt(value, 10) }))}>
<SelectTrigger id="concurrent-downloads" className="w-fit">
<SelectValue placeholder="10"/>
</SelectTrigger>
<SelectContent>
{[1, 2, 3, 5, 8, 10, 15, 20, 25, 30, 40, 50].map((value) => (<SelectItem key={value} value={String(value)}>
{value}
</SelectItem>))}
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label htmlFor="retry-attempts" className="flex items-center gap-2">
Retry Attempts
<Tooltip>
<TooltipTrigger asChild>
<Info className="h-3.5 w-3.5 cursor-help text-muted-foreground"/>
</TooltipTrigger>
<TooltipContent side="top">
<p>How many times to retry a failed download before giving up.</p>
</TooltipContent>
</Tooltip>
</Label>
<Select value={String(tempSettings.retryAttempts)} onValueChange={(value) => setTempSettings((prev) => ({ ...prev, retryAttempts: parseInt(value, 10) }))}>
<SelectTrigger id="retry-attempts" className="w-fit">
<SelectValue placeholder="1"/>
</SelectTrigger>
<SelectContent>
{[1, 2, 3, 4, 5].map((value) => (<SelectItem key={value} value={String(value)}>
{value}
</SelectItem>))}
</SelectContent>
</Select>
</div>
</div>
<div className="flex items-center justify-between gap-4">
@@ -523,20 +523,6 @@ export function SettingsPage({ onUnsavedChangesChange, onResetRequest }: Setting
<Label htmlFor="delete-incomplete-files" className="cursor-pointer">Delete Incomplete Files</Label>
<Switch id="delete-incomplete-files" checked={tempSettings.deleteIncompleteFiles} onCheckedChange={(checked) => setTempSettings((prev) => ({ ...prev, deleteIncompleteFiles: checked }))}/>
</div>
<div className="flex items-center justify-between gap-4">
<Label htmlFor="retry-attempts">Retry Attempts</Label>
<Select value={String(tempSettings.retryAttempts)} onValueChange={(value) => setTempSettings((prev) => ({ ...prev, retryAttempts: parseInt(value, 10) }))}>
<SelectTrigger id="retry-attempts" className="w-24">
<SelectValue placeholder="1"/>
</SelectTrigger>
<SelectContent>
{[1, 2, 3, 4, 5].map((value) => (<SelectItem key={value} value={String(value)}>
{value}
</SelectItem>))}
</SelectContent>
</Select>
</div>
</div>
</div>
@@ -606,49 +592,56 @@ export function SettingsPage({ onUnsavedChangesChange, onResetRequest }: Setting
</Label>
<div className="flex items-center justify-between gap-4">
<Label htmlFor="gif-quality" className={!ffmpegInstalled ? "text-muted-foreground" : undefined}>GIF Quality</Label>
<Select value={tempSettings.gifQuality} onValueChange={(value: GifQuality) => {
setTempSettings((prev) => ({
...prev,
gifQuality: value,
}));
}} disabled={!ffmpegInstalled}>
<SelectTrigger id="gif-quality" className="w-fit">
<SelectValue placeholder="Select quality"/>
</SelectTrigger>
<SelectContent>
<SelectItem value="fast">Fast</SelectItem>
<SelectItem value="better">Better</SelectItem>
</SelectContent>
</Select>
</div>
<div className="flex items-center justify-between gap-4">
<Label htmlFor="gif-resolution" className={!ffmpegInstalled ? "text-muted-foreground" : undefined}>Resolution</Label>
<Select value={tempSettings.gifResolution} onValueChange={(value: GifResolution) => setTempSettings((prev) => ({ ...prev, gifResolution: value }))} disabled={!ffmpegInstalled}>
<SelectTrigger id="gif-resolution" className="w-fit">
<SelectValue placeholder="Resolution"/>
</SelectTrigger>
<SelectContent>
<SelectItem value="original">Original</SelectItem>
<SelectItem value="high">High (800px)</SelectItem>
<SelectItem value="medium">Medium (600px)</SelectItem>
<SelectItem value="low">Low (400px)</SelectItem>
</SelectContent>
</Select>
<div className="flex items-center gap-2">
<Select value={tempSettings.gifQuality} onValueChange={(value: GifQuality) => {
setTempSettings((prev) => ({
...prev,
gifQuality: value,
}));
}} disabled={!ffmpegInstalled}>
<SelectTrigger id="gif-quality" className="w-fit">
<SelectValue placeholder="Select quality"/>
</SelectTrigger>
<SelectContent>
<SelectItem value="fast">Fast</SelectItem>
<SelectItem value="better">Better</SelectItem>
</SelectContent>
</Select>
<Select value={tempSettings.gifResolution} onValueChange={(value: GifResolution) => setTempSettings((prev) => ({ ...prev, gifResolution: value }))} disabled={!ffmpegInstalled}>
<SelectTrigger id="gif-resolution" className="w-fit">
<SelectValue placeholder="Resolution"/>
</SelectTrigger>
<SelectContent>
<SelectItem value="original">Original</SelectItem>
<SelectItem value="high">High (800px)</SelectItem>
<SelectItem value="medium">Medium (600px)</SelectItem>
<SelectItem value="low">Low (400px)</SelectItem>
</SelectContent>
</Select>
</div>
</div>
</div>
</div>
</div>
</div>)}
{activeTab === "naming" && (<div className="grid grid-cols-1 gap-6 md:grid-cols-2 md:gap-8 items-start">
<div className="md:pr-8 md:border-r border-border">
<FormatEditor title="Folder" value={tempSettings.folderTemplate} defaultValue={DEFAULT_FOLDER_TEMPLATE} tokens={FOLDER_TEMPLATE_VARIABLES} placeholder={DEFAULT_FOLDER_TEMPLATE} render={(t) => renderFolderTemplate(t, SAMPLE_FOLDER_DATA)} onChange={(next) => setTempSettings((prev) => ({ ...prev, folderTemplate: next }))}/>
</div>
<div>
<FormatEditor title="Filename" value={tempSettings.filenameTemplate} defaultValue={DEFAULT_FILENAME_TEMPLATE} tokens={FILENAME_TEMPLATE_VARIABLES} placeholder={DEFAULT_FILENAME_TEMPLATE} suffix=".jpg" render={(t) => renderFilenameTemplate(t, SAMPLE_FILENAME_DATA)} onChange={(next) => setTempSettings((prev) => ({ ...prev, filenameTemplate: next }))}/>
</div>
</div>)}
{activeTab === "dependencies" && (<div className="grid grid-cols-1 gap-4 md:grid-cols-2">
<div className="space-y-4">
<div className="space-y-2">
<Label className="flex flex-wrap items-center gap-2">
<span>Core Xtractor</span>
{extractorVersionText && (<span className={extractorUpdateAvailable
? "text-xs font-normal text-amber-600 dark:text-amber-400"
: "text-xs font-normal text-muted-foreground"}>
? "text-xs font-normal text-amber-600 dark:text-amber-400"
: "text-xs font-normal text-muted-foreground"}>
{extractorVersionText}
</span>)}
<Tooltip>
@@ -681,8 +674,8 @@ export function SettingsPage({ onUnsavedChangesChange, onResetRequest }: Setting
<Label className="flex flex-wrap items-center gap-2">
<span>GIF Conversion</span>
{ffmpegVersionText && (<span className={ffmpegUpdateAvailable
? "text-xs font-normal text-amber-600 dark:text-amber-400"
: "text-xs font-normal text-muted-foreground"}>
? "text-xs font-normal text-amber-600 dark:text-amber-400"
: "text-xs font-normal text-muted-foreground"}>
{ffmpegVersionText}
</span>)}
<Tooltip>
@@ -715,8 +708,8 @@ export function SettingsPage({ onUnsavedChangesChange, onResetRequest }: Setting
<Label className="flex flex-wrap items-center gap-2">
<span>Metadata Embedding</span>
{exiftoolVersionText && (<span className={exiftoolUpdateAvailable
? "text-xs font-normal text-amber-600 dark:text-amber-400"
: "text-xs font-normal text-muted-foreground"}>
? "text-xs font-normal text-amber-600 dark:text-amber-400"
: "text-xs font-normal text-muted-foreground"}>
{exiftoolVersionText}
</span>)}
<Tooltip>
-3
View File
@@ -5,12 +5,9 @@ import { openExternal } from "@/lib/utils";
import KofiLogo from "@/assets/ko-fi.gif";
import KofiSvg from "@/assets/kofi_symbol.svg";
import UsdtBarcode from "@/assets/usdt.jpg";
const USDT_ADDRESS = "THnzAAwZgp2Sq5CAXLP2njQDhTvgZG9EWs";
export function SupportPage() {
const [copiedUsdt, setCopiedUsdt] = useState(false);
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 flex-1 flex-col items-center justify-between space-y-6 border-b p-6 md:border-r md:border-b-0">
+28 -8
View File
@@ -1,5 +1,12 @@
import { X, Minus, Maximize } from "lucide-react";
import { X, Minus, Maximize, Info, Puzzle, FileCode2, Globe } from "lucide-react";
import { WindowMinimise, WindowToggleMaximise, Quit } from "../../wailsjs/runtime/runtime";
import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem } from "@/components/ui/dropdown-menu";
import { openExternal } from "@/lib/utils";
const INFO_LINKS = [
{ label: "Chrome Extension", icon: Puzzle, url: "https://chromewebstore.google.com/detail/cboceolmgkoobpfjiojkigmihijfgmdo" },
{ label: "Userscript", icon: FileCode2, url: "https://greasyfork.org/en/scripts/523157" },
{ label: "Website", icon: Globe, url: "https://mediabatchdl.com" },
];
export function TitleBar() {
const handleMinimize = () => {
WindowMinimise();
@@ -11,18 +18,31 @@ export function TitleBar() {
Quit();
};
return (<>
<div className="fixed top-0 left-14 right-0 h-10 z-40 bg-background/80 backdrop-blur-sm" style={{ "--wails-draggable": "drag" } as React.CSSProperties} onDoubleClick={handleMaximize}/>
<div className="fixed top-1.5 right-2 z-50 flex h-7 gap-0.5">
<button onClick={handleMinimize} className="w-8 h-7 flex items-center justify-center hover:bg-muted transition-colors rounded" style={{ "--wails-draggable": "no-drag" } as React.CSSProperties} aria-label="Minimize">
<div className="fixed top-1.5 right-2 z-50 flex h-7 gap-0.5" style={{ "--wails-draggable": "no-drag" } as React.CSSProperties}>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button className="w-8 h-7 flex items-center justify-center hover:bg-muted transition-colors rounded" aria-label="Info">
<Info className="w-3.5 h-3.5"/>
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
{INFO_LINKS.map(({ label, icon: Icon, url }) => (<DropdownMenuItem key={label} onClick={() => openExternal(url)} className="gap-2 cursor-pointer">
<Icon className="w-4 h-4 text-muted-foreground"/>
{label}
</DropdownMenuItem>))}
</DropdownMenuContent>
</DropdownMenu>
<button onClick={handleMinimize} className="w-8 h-7 flex items-center justify-center hover:bg-muted transition-colors rounded" aria-label="Minimize">
<Minus className="w-3.5 h-3.5"/>
</button>
<button onClick={handleMaximize} className="w-8 h-7 flex items-center justify-center hover:bg-muted transition-colors rounded" style={{ "--wails-draggable": "no-drag" } as React.CSSProperties} aria-label="Maximize">
<button onClick={handleMaximize} className="w-8 h-7 flex items-center justify-center hover:bg-muted transition-colors rounded" aria-label="Maximize">
<Maximize className="w-3.5 h-3.5"/>
</button>
<button onClick={handleClose} className="w-8 h-7 flex items-center justify-center hover:bg-destructive hover:text-white transition-colors rounded" style={{ "--wails-draggable": "no-drag" } as React.CSSProperties} aria-label="Close">
<button onClick={handleClose} className="w-8 h-7 flex items-center justify-center hover:bg-destructive hover:text-white transition-colors rounded" aria-label="Close">
<X className="w-3.5 h-3.5"/>
</button>
</div>
+4 -19
View File
@@ -1,19 +1,14 @@
"use client";
import type { Transition, Variants } from "motion/react";
import { AnimatePresence, motion } from "motion/react";
import { useEffect, useState, type HTMLAttributes } from "react";
import { cn } from "@/lib/utils";
type ReportIconMode = "bug" | "bulb";
interface BugReportIconProps extends HTMLAttributes<HTMLDivElement> {
size?: number;
loop?: boolean;
}
const LOOP_INTERVAL_MS = 2200;
const GROUP_VARIANTS: Variants = {
hidden: {
opacity: 0,
@@ -33,7 +28,6 @@ const GROUP_VARIANTS: Variants = {
},
},
};
const DRAW_VARIANTS: Variants = {
hidden: {
pathLength: 0,
@@ -48,7 +42,6 @@ const DRAW_VARIANTS: Variants = {
opacity: 0,
},
};
function createDrawTransition(delay = 0, duration = 0.36): Transition {
return {
duration,
@@ -57,7 +50,6 @@ function createDrawTransition(delay = 0, duration = 0.36): Transition {
opacity: { delay },
};
}
function BugPaths() {
return (<>
<motion.path d="m8 2 1.88 1.88" transition={createDrawTransition(0)} variants={DRAW_VARIANTS}/>
@@ -73,7 +65,6 @@ function BugPaths() {
<motion.path d="M3 21a4 4 0 0 1 3.81-4" transition={createDrawTransition(0.56)} variants={DRAW_VARIANTS}/>
</>);
}
function BulbPaths() {
return (<>
<motion.path d="M15 14c.2-1 .7-1.7 1.5-2.5 1-.9 1.5-2.2 1.5-3.5A6 6 0 0 0 6 8c0 1 .2 2.2 1.5 3.5.7.7 1.3 1.5 1.5 2.5" transition={createDrawTransition(0, 0.46)} variants={DRAW_VARIANTS}/>
@@ -81,13 +72,13 @@ function BulbPaths() {
<motion.path d="M10 22h4" transition={createDrawTransition(0.24)} variants={DRAW_VARIANTS}/>
</>);
}
function ReportIconGroup({ mode }: { mode: ReportIconMode; }) {
function ReportIconGroup({ mode }: {
mode: ReportIconMode;
}) {
return (<motion.g animate="visible" exit="exit" initial="hidden" variants={GROUP_VARIANTS}>
{mode === "bug" ? <BugPaths /> : <BulbPaths />}
</motion.g>);
}
function StaticBugIcon() {
return (<g>
<path d="m8 2 1.88 1.88"/>
@@ -103,29 +94,23 @@ function StaticBugIcon() {
<path d="M3 21a4 4 0 0 1 3.81-4"/>
</g>);
}
function BugReportIcon({ className, size = 28, loop = false, ...props }: BugReportIconProps) {
const [mode, setMode] = useState<ReportIconMode>("bug");
useEffect(() => {
if (!loop) {
return;
}
const intervalId = window.setInterval(() => {
setMode((currentMode) => currentMode === "bug" ? "bulb" : "bug");
}, LOOP_INTERVAL_MS);
return () => window.clearInterval(intervalId);
}, [loop]);
return (<div className={cn("flex items-center justify-center", className)} {...props}>
<svg fill="none" height={size} stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" viewBox="0 0 24 24" width={size} xmlns="http://www.w3.org/2000/svg">
{loop ? (<AnimatePresence>
<ReportIconGroup key={mode} mode={mode} />
<ReportIconGroup key={mode} mode={mode}/>
</AnimatePresence>) : (<StaticBugIcon />)}
</svg>
</div>);
}
export { BugReportIcon };
-3
View File
@@ -11,12 +11,10 @@ export interface FetchState {
retweets: boolean;
timelineType: string;
}
function normalizeFetchState(state: FetchState | null | undefined): FetchState | null {
if (!state) {
return null;
}
return {
...state,
cursor: state.cursor || "",
@@ -26,7 +24,6 @@ function normalizeFetchState(state: FetchState | null | undefined): FetchState |
timelineType: state.timelineType || "timeline",
};
}
export function saveFetchState(state: Partial<FetchState> & {
username: string;
}): void {
-9
View File
@@ -1,16 +1,13 @@
export type DependencyName = "extractor" | "ffmpeg" | "exiftool";
export interface CachedDependencyStatus {
installed: boolean | null;
installedVersion: string | null;
latestVersion: string | null;
}
export interface CachedMediaFolderStatus {
folderExists: boolean;
gifsFolderHasMP4: boolean;
}
const dependencyStatusCache: Record<DependencyName, CachedDependencyStatus> = {
extractor: {
installed: null,
@@ -28,28 +25,22 @@ const dependencyStatusCache: Record<DependencyName, CachedDependencyStatus> = {
latestVersion: null,
},
};
const mediaFolderStatusCache = new Map<string, CachedMediaFolderStatus>();
function getMediaFolderStatusKey(downloadPath: string, folderName: string): string {
return `${downloadPath}::${folderName}`;
}
export function getCachedDependencyStatus(name: DependencyName): CachedDependencyStatus {
return { ...dependencyStatusCache[name] };
}
export function setCachedDependencyStatus(name: DependencyName, status: Partial<CachedDependencyStatus>): void {
dependencyStatusCache[name] = {
...dependencyStatusCache[name],
...status,
};
}
export function getCachedMediaFolderStatus(downloadPath: string, folderName: string): CachedMediaFolderStatus | null {
return mediaFolderStatusCache.get(getMediaFolderStatusKey(downloadPath, folderName)) ?? null;
}
export function setCachedMediaFolderStatus(downloadPath: string, folderName: string, status: CachedMediaFolderStatus): void {
mediaFolderStatusCache.set(getMediaFolderStatusKey(downloadPath, folderName), status);
}
+128 -62
View File
@@ -1,52 +1,131 @@
import { GetDefaults } from "../../wailsjs/go/main/App";
export type BuiltInFontFamily =
| "google-sans"
| "inter"
| "poppins"
| "roboto"
| "dm-sans"
| "plus-jakarta-sans"
| "manrope"
| "space-grotesk"
| "noto-sans"
| "nunito-sans"
| "figtree"
| "raleway"
| "public-sans"
| "outfit"
| "jetbrains-mono"
| "geist-sans"
| "bricolage-grotesque";
export type BuiltInFontFamily = "google-sans" | "inter" | "poppins" | "roboto" | "dm-sans" | "plus-jakarta-sans" | "manrope" | "space-grotesk" | "noto-sans" | "nunito-sans" | "figtree" | "raleway" | "public-sans" | "outfit" | "jetbrains-mono" | "geist-sans" | "bricolage-grotesque";
export type CustomFontFamily = `custom-${string}`;
export type FontFamily = BuiltInFontFamily | CustomFontFamily;
export interface CustomFontOption {
value: CustomFontFamily;
label: string;
fontFamily: string;
url: string;
}
export interface FontOption {
value: FontFamily;
label: string;
fontFamily: string;
url?: string;
}
export type GifQuality = "fast" | "better";
export type GifResolution = "original" | "high" | "medium" | "low";
export type FetchMode = "single" | "batch";
export type MediaType = "all" | "image" | "video" | "gif" | "text";
export type VideoQuality = "highest" | "720" | "480" | "360" | "lowest";
export type ImageSize = "orig" | "large" | "medium" | "small";
export type AvatarSize = "orig" | "400x400" | "200x200" | "bigger" | "normal";
export type BannerSize = "orig" | "1500x500" | "600x200" | "300x100";
export const VIDEO_QUALITIES: {
value: VideoQuality;
label: string;
}[] = [
{ value: "highest", label: "Highest" },
{ value: "720", label: "720p" },
{ value: "480", label: "480p" },
{ value: "360", label: "360p" },
{ value: "lowest", label: "Lowest" },
];
export const IMAGE_SIZES: {
value: ImageSize;
label: string;
}[] = [
{ value: "orig", label: "Original" },
{ value: "large", label: "Large" },
{ value: "medium", label: "Medium" },
{ value: "small", label: "Small" },
];
export const AVATAR_SIZES: {
value: AvatarSize;
label: string;
}[] = [
{ value: "orig", label: "Original" },
{ value: "400x400", label: "400px" },
{ value: "200x200", label: "200px" },
{ value: "bigger", label: "Bigger" },
{ value: "normal", label: "Normal" },
];
export const BANNER_SIZES: {
value: BannerSize;
label: string;
}[] = [
{ value: "orig", label: "Original" },
{ value: "1500x500", label: "1500×500" },
{ value: "600x200", label: "600×200" },
{ value: "300x100", label: "300×100" },
];
export const DEFAULT_FILENAME_TEMPLATE = "{username}_{date}_{tweet_id}_{index}";
export interface TemplateToken {
key: string;
description: string;
example: string;
}
export const FILENAME_TEMPLATE_VARIABLES: TemplateToken[] = [
{ key: "{username}", description: "Author handle", example: "NASA" },
{ key: "{date}", description: "Tweet date & time", example: "20250620_104556" },
{ 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: "{type}", description: "Media type", example: "photo" },
];
export interface FilenameTemplateData {
username?: string;
date?: string;
tweetId?: string;
index?: number;
type?: string;
}
export const SAMPLE_FILENAME_DATA: FilenameTemplateData = {
username: "NASA",
date: "20250620_104556",
tweetId: "1989033613824815258",
index: 1,
type: "photo",
};
export function renderFilenameTemplate(template: string, data: FilenameTemplateData): string {
if (!template)
return "";
const safe = (s: string) => s.replace(/[\\/:*?"<>|]/g, "").trim();
return template
.replace(/\{username\}/g, safe(data.username ?? ""))
.replace(/\{date\}/g, safe(data.date ?? ""))
.replace(/\{tweet_id\}/g, safe(data.tweetId ?? ""))
.replace(/\{index\}/g, String(data.index ?? 1).padStart(2, "0"))
.replace(/\{type\}/g, safe(data.type ?? ""))
.trim();
}
export const DEFAULT_FOLDER_TEMPLATE = "{username}";
export const FOLDER_TEMPLATE_VARIABLES: TemplateToken[] = [
{ key: "{username}", description: "Author handle", example: "NASA" },
{ key: "{date}", description: "Download date", example: "20250620" },
];
export interface FolderTemplateData {
username?: string;
date?: string;
}
export const SAMPLE_FOLDER_DATA: FolderTemplateData = {
username: "NASA",
date: "20250620",
};
export function renderFolderTemplate(template: string, data: FolderTemplateData): string {
if (!template)
return "";
const safe = (s: string) => s.replace(/[\\/:*?"<>|]/g, "").trim();
return template
.replace(/\{username\}/g, safe(data.username ?? ""))
.replace(/\{date\}/g, safe(data.date ?? ""))
.trim();
}
const DEFAULT_CONCURRENT_DOWNLOADS = 10;
const MIN_CONCURRENT_DOWNLOADS = 1;
const MAX_CONCURRENT_DOWNLOADS = 50;
const DEFAULT_RETRY_ATTEMPTS = 1;
const MIN_RETRY_ATTEMPTS = 1;
const MAX_RETRY_ATTEMPTS = 5;
export interface Settings {
downloadPath: string;
concurrentDownloads: number;
@@ -62,11 +141,18 @@ export interface Settings {
gifResolution: GifResolution;
proxy: string;
fetchTimeout: number;
fetchMode: FetchMode;
mediaType: MediaType;
includePhotos: boolean;
includeVideos: boolean;
includeGifs: boolean;
includeText: boolean;
includeRetweets: boolean;
videoQuality: VideoQuality;
imageSize: ImageSize;
avatarSize: AvatarSize;
bannerSize: BannerSize;
filenameTemplate: string;
folderTemplate: string;
}
export const DEFAULT_SETTINGS: Settings = {
downloadPath: "",
concurrentDownloads: DEFAULT_CONCURRENT_DOWNLOADS,
@@ -82,11 +168,18 @@ export const DEFAULT_SETTINGS: Settings = {
gifResolution: "original",
proxy: "",
fetchTimeout: 60,
fetchMode: "batch",
mediaType: "all",
includePhotos: true,
includeVideos: true,
includeGifs: true,
includeText: false,
includeRetweets: false,
videoQuality: "highest",
imageSize: "orig",
avatarSize: "orig",
bannerSize: "orig",
filenameTemplate: DEFAULT_FILENAME_TEMPLATE,
folderTemplate: DEFAULT_FOLDER_TEMPLATE,
};
export const FONT_OPTIONS: FontOption[] = [
{
value: "bricolage-grotesque",
@@ -174,13 +267,11 @@ export const FONT_OPTIONS: FontOption[] = [
fontFamily: '"Space Grotesk", system-ui, sans-serif',
},
];
const BUILT_IN_FONT_VALUES = new Set(FONT_OPTIONS.map((font) => font.value));
const SETTINGS_KEY = "twitter-media-downloader-settings";
const GOOGLE_FONT_LINK_ID_PREFIX = "twitter-media-custom-font-";
const GOOGLE_FONTS_CSS_HOST = "fonts.googleapis.com";
const GOOGLE_FONTS_SPECIMEN_HOST = "fonts.google.com";
function extractGoogleFontInputUrl(input: string): string {
const trimmed = input.trim();
const hrefMatch = trimmed.match(/\bhref=["']([^"']+)["']/i);
@@ -193,7 +284,6 @@ function extractGoogleFontInputUrl(input: string): string {
}
return trimmed;
}
function coerceGoogleFontUrl(rawUrl: string): string {
const trimmed = rawUrl.trim();
if (/^https?:\/\//i.test(trimmed)) {
@@ -204,34 +294,28 @@ function coerceGoogleFontUrl(rawUrl: string): string {
}
return trimmed;
}
function normalizeFontLabel(label: string): string {
return label.replace(/\+/g, " ").replace(/\s+/g, " ").trim();
}
function slugifyFontLabel(label: string): string {
return label.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "font";
}
function toFontFamilyCss(label: string): string {
const escapedLabel = label.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
return `"${escapedLabel}", system-ui, sans-serif`;
}
function buildGoogleFontsCssUrl(label: string): string {
const url = new URL("https://fonts.googleapis.com/css2");
url.searchParams.set("family", label);
url.searchParams.set("display", "swap");
return url.toString();
}
function extractSpecimenFontLabel(parsed: URL): string {
const segments = parsed.pathname.split("/").filter(Boolean);
const specimenIndex = segments.findIndex((segment) => segment.toLowerCase() === "specimen");
const specimenName = specimenIndex >= 0 ? segments[specimenIndex + 1] : "";
return normalizeFontLabel(decodeURIComponent(specimenName || ""));
}
function normalizeGoogleFontCssUrl(rawUrl: string): string | null {
try {
const parsed = new URL(coerceGoogleFontUrl(extractGoogleFontInputUrl(rawUrl)));
@@ -257,7 +341,6 @@ function normalizeGoogleFontCssUrl(rawUrl: string): string | null {
return null;
}
}
export function parseGoogleFontUrl(rawUrl: string): CustomFontOption | null {
const normalizedUrl = normalizeGoogleFontCssUrl(rawUrl);
if (!normalizedUrl) {
@@ -276,7 +359,6 @@ export function parseGoogleFontUrl(rawUrl: string): CustomFontOption | null {
url: normalizedUrl,
};
}
function normalizeCustomFonts(customFonts: unknown): CustomFontOption[] {
if (!Array.isArray(customFonts)) {
return [];
@@ -288,7 +370,9 @@ function normalizeCustomFonts(customFonts: unknown): CustomFontOption[] {
if (!item || typeof item !== "object") {
continue;
}
const rawUrl = (item as { url?: unknown }).url;
const rawUrl = (item as {
url?: unknown;
}).url;
if (typeof rawUrl !== "string") {
continue;
}
@@ -302,7 +386,6 @@ function normalizeCustomFonts(customFonts: unknown): CustomFontOption[] {
}
return normalizedFonts;
}
function normalizeFontFamily(fontFamily: unknown, customFonts: CustomFontOption[]): FontFamily {
if (typeof fontFamily !== "string") {
return DEFAULT_SETTINGS.fontFamily;
@@ -313,7 +396,6 @@ function normalizeFontFamily(fontFamily: unknown, customFonts: CustomFontOption[
const customFont = customFonts.find((font) => font.value === fontFamily);
return customFont ? customFont.value : DEFAULT_SETTINGS.fontFamily;
}
function normalizeConcurrentDownloads(value: unknown): number {
if (typeof value !== "number" || !Number.isFinite(value)) {
return DEFAULT_CONCURRENT_DOWNLOADS;
@@ -327,14 +409,12 @@ function normalizeConcurrentDownloads(value: unknown): number {
}
return rounded;
}
function normalizeBoolean(value: unknown, fallback: boolean): boolean {
if (typeof value === "boolean") {
return value;
}
return fallback;
}
function normalizeRetryAttempts(value: unknown): number {
if (typeof value !== "number" || !Number.isFinite(value)) {
return DEFAULT_RETRY_ATTEMPTS;
@@ -348,11 +428,9 @@ function normalizeRetryAttempts(value: unknown): number {
}
return rounded;
}
export function getFontOptions(customFonts: CustomFontOption[] = []): FontOption[] {
return [...FONT_OPTIONS, ...normalizeCustomFonts(customFonts)];
}
export function loadGoogleFontUrl(url: string, id = `${GOOGLE_FONT_LINK_ID_PREFIX}preview`): void {
const normalizedUrl = normalizeGoogleFontCssUrl(url);
if (!normalizedUrl) {
@@ -369,13 +447,11 @@ export function loadGoogleFontUrl(url: string, id = `${GOOGLE_FONT_LINK_ID_PREFI
link.href = normalizedUrl;
}
}
function loadCustomFontStylesheets(customFonts: CustomFontOption[]): void {
for (const font of normalizeCustomFonts(customFonts)) {
loadGoogleFontUrl(font.url, `${GOOGLE_FONT_LINK_ID_PREFIX}${font.value}`);
}
}
export function applyFont(fontFamily: FontFamily, customFonts: CustomFontOption[] = []): void {
const fontOptions = getFontOptions(customFonts);
loadCustomFontStylesheets(customFonts);
@@ -385,7 +461,6 @@ export function applyFont(fontFamily: FontFamily, customFonts: CustomFontOption[
document.body.style.fontFamily = font.fontFamily;
}
}
async function fetchDefaultPath(): Promise<string> {
try {
const data = await GetDefaults();
@@ -396,7 +471,6 @@ async function fetchDefaultPath(): Promise<string> {
return "";
}
}
function toNormalizedSettings(settings: Partial<Settings>): Settings {
const customFonts = normalizeCustomFonts(settings.customFonts);
return {
@@ -410,7 +484,6 @@ function toNormalizedSettings(settings: Partial<Settings>): Settings {
fontFamily: normalizeFontFamily(settings.fontFamily, customFonts),
};
}
export function getSettings(): Settings {
try {
const stored = localStorage.getItem(SETTINGS_KEY);
@@ -423,7 +496,6 @@ export function getSettings(): Settings {
}
return DEFAULT_SETTINGS;
}
export async function getSettingsWithDefaults(): Promise<Settings> {
const settings = getSettings();
if (!settings.downloadPath) {
@@ -431,7 +503,6 @@ export async function getSettingsWithDefaults(): Promise<Settings> {
}
return toNormalizedSettings(settings);
}
export function saveSettings(settings: Settings): void {
try {
const normalizedSettings = toNormalizedSettings(settings);
@@ -441,14 +512,12 @@ export function saveSettings(settings: Settings): void {
console.error("Failed to save settings:", error);
}
}
export function updateSettings(partial: Partial<Settings>): Settings {
const current = getSettings();
const updated = toNormalizedSettings({ ...current, ...partial });
saveSettings(updated);
return updated;
}
export async function resetToDefaultSettings(): Promise<Settings> {
const defaultPath = await fetchDefaultPath();
const defaultSettings = toNormalizedSettings({
@@ -458,11 +527,9 @@ export async function resetToDefaultSettings(): Promise<Settings> {
saveSettings(defaultSettings);
return defaultSettings;
}
export async function loadCustomFonts(): Promise<CustomFontOption[]> {
return normalizeCustomFonts(getSettings().customFonts);
}
export async function saveCustomFonts(customFonts: CustomFontOption[]): Promise<CustomFontOption[]> {
const normalizedFonts = normalizeCustomFonts(customFonts);
const settings = getSettings();
@@ -473,7 +540,6 @@ export async function saveCustomFonts(customFonts: CustomFontOption[]): Promise<
});
return normalizedFonts;
}
export function applyThemeMode(mode: "auto" | "light" | "dark"): void {
if (mode === "auto") {
const prefersDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
+18
View File
@@ -1,3 +1,7 @@
export interface Thumb {
name: string;
url: string;
}
export interface AccountInfo {
name: string;
nick: string;
@@ -6,6 +10,16 @@ export interface AccountInfo {
friends_count: number;
profile_image: string;
statuses_count: number;
bio?: string;
banner?: string;
location?: string;
url?: string;
media_count?: number;
verified?: boolean;
blue_verified?: boolean;
protected?: boolean;
avatar_variants?: Thumb[];
banner_variants?: Thumb[];
}
export interface TimelineEntry {
url: string;
@@ -16,12 +30,16 @@ export interface TimelineEntry {
extension: string;
width: number;
height: number;
thumbnail?: string;
duration_ms?: number;
alt_text?: string;
content?: string;
view_count?: number;
bookmark_count?: number;
favorite_count?: number;
retweet_count?: number;
reply_count?: number;
quote_count?: number;
source?: string;
verified?: boolean;
original_filename?: string;
+1
View File
@@ -1,5 +1,6 @@
{
"compilerOptions": {
"ignoreDeprecations": "6.0",
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "ES2022",
"useDefineForClassFields": true,
+2
View File
@@ -31,6 +31,8 @@ export function DownloadMedia(arg1:main.DownloadMediaRequest):Promise<main.Downl
export function DownloadMediaWithMetadata(arg1:main.DownloadMediaWithMetadataRequest):Promise<main.DownloadMediaResponse>;
export function DownloadProfileImage(arg1:main.DownloadProfileImageRequest):Promise<string>;
export function ExportAccountJSON(arg1:number,arg2:string):Promise<string>;
export function ExportAccountsTXT(arg1:Array<number>,arg2:string):Promise<string>;
+4
View File
@@ -58,6 +58,10 @@ export function DownloadMediaWithMetadata(arg1) {
return window['go']['main']['App']['DownloadMediaWithMetadata'](arg1);
}
export function DownloadProfileImage(arg1) {
return window['go']['main']['App']['DownloadProfileImage'](arg1);
}
export function ExportAccountJSON(arg1, arg2) {
return window['go']['main']['App']['ExportAccountJSON'](arg1, arg2);
}
+36
View File
@@ -212,6 +212,8 @@ export namespace main {
delete_incomplete_files: boolean;
retry_attempts?: number;
proxy?: string;
filename_template?: string;
folder_template?: string;
static createFrom(source: any = {}) {
return new DownloadMediaWithMetadataRequest(source);
@@ -227,6 +229,8 @@ export namespace main {
this.delete_incomplete_files = source["delete_incomplete_files"];
this.retry_attempts = source["retry_attempts"];
this.proxy = source["proxy"];
this.filename_template = source["filename_template"];
this.folder_template = source["folder_template"];
}
convertValues(a: any, classs: any, asMap: boolean = false): any {
@@ -247,6 +251,26 @@ export namespace main {
return a;
}
}
export class DownloadProfileImageRequest {
url: string;
output_dir: string;
username: string;
kind: string;
proxy?: string;
static createFrom(source: any = {}) {
return new DownloadProfileImageRequest(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.url = source["url"];
this.output_dir = source["output_dir"];
this.username = source["username"];
this.kind = source["kind"];
this.proxy = source["proxy"];
}
}
export class ImportAccountResponse {
success: boolean;
username: string;
@@ -273,6 +297,12 @@ export namespace main {
media_type: string;
retweets: boolean;
cursor?: string;
include_photos: boolean;
include_videos: boolean;
include_gifs: boolean;
include_text: boolean;
video_quality?: string;
image_size?: string;
static createFrom(source: any = {}) {
return new TimelineRequest(source);
@@ -288,6 +318,12 @@ export namespace main {
this.media_type = source["media_type"];
this.retweets = source["retweets"];
this.cursor = source["cursor"];
this.include_photos = source["include_photos"];
this.include_videos = source["include_videos"];
this.include_gifs = source["include_gifs"];
this.include_text = source["include_text"];
this.video_quality = source["video_quality"];
this.image_size = source["image_size"];
}
}
+1 -1
View File
@@ -11,7 +11,7 @@
},
"info": {
"productName": "Twitter/X Media Batch Downloader",
"productVersion": "4.6"
"productVersion": "4.7"
},
"wailsjsdir": "./frontend",
"assetdir": "./frontend/dist",