Compare commits

...
14 Commits
Author SHA1 Message Date
Alvin-Zilverstand 6964753e3e f 2026-09-21 15:37:24 +02:00
afkarxyz 9c269bc8f2 v5.0.1 2026-08-18 07:51:56 +07:00
afkarxyz 70f5088574 Update README 2026-08-18 06:28:13 +07:00
afkarxyz 1f378bb356 v5.0.0 2026-07-29 14:59:28 +07:00
afkarxyz 492a318399 Update README 2026-07-16 18:41:16 +07:00
afkarxyz 2ada5da9bf v4.9 2026-07-16 18:27:23 +07:00
afkarxyz 3fb8bda2ff Update README 2026-07-15 12:26:49 +07:00
asdfghjkkly b4dfb75f5b Fix group editing and skip existing downloads (#105) 2026-07-12 10:59:29 +07:00
afkarxyz 7e584aff2c Update README 2026-07-12 10:58:42 +07:00
afkarxyz 76acb6f5e1 v4.8 2026-07-05 19:09:54 +07:00
afkarxyz 6bd03678f8 Merge pull request #103 from asdfghjkkly/fix-windows-folder-and-reposts
Fix repost folder routing and Windows folder opening
2026-07-05 17:00:37 +07:00
asdfghjkkly e400df6ea7 Fix repost folder routing and Windows folder opening 2026-07-05 05:41:36 -04:00
afkarxyz 52ffa5ba17 Update README 2026-06-22 14:31:56 +07:00
429Enjoyer c42808431c v4.7 2026-06-22 14:08:53 +07:00
47 changed files with 5352 additions and 3516 deletions

No files matched your search

-1
View File
@@ -1 +0,0 @@
ko_fi: afkarxyz
+42 -14
View File
@@ -54,7 +54,7 @@ jobs:
- name: Install frontend dependencies
working-directory: frontend
run: |
pnpm install
pnpm install --frozen-lockfile
pnpm run generate-icon
- name: Install UPX
@@ -120,7 +120,7 @@ jobs:
- name: Install frontend dependencies
working-directory: frontend
run: |
pnpm install
pnpm install --frozen-lockfile
pnpm run generate-icon
- name: Build application
@@ -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
@@ -197,11 +217,11 @@ jobs:
- name: Install frontend dependencies
working-directory: frontend
run: |
pnpm install
pnpm install --frozen-lockfile
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 }}
+42 -9
View File
@@ -1,19 +1,52 @@
# Twitter/X Media Batch Downloader
A GUI tool to download original-quality images and videos from Twitter/X accounts.
![Windows](https://img.shields.io/badge/Windows-10%2B-0078D6?style=for-the-badge&logo=data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI1MTIiIGhlaWdodD0iNTEyIiB2aWV3Qm94PSIwIDAgMjAgMjAiPjxwYXRoIGZpbGw9IiNmZmZmZmYiIGZpbGwtcnVsZT0iZXZlbm9kZCIgZD0iTTIwIDEwLjg3M1YyMEw4LjQ3OSAxOC41MzdsLjAwMS03LjY2NEgyMFptLTEzLjEyIDBsLS4wMDEgNy40NjFMMCAxNy40NjF2LTYuNTg4aDYuODhaTTIwIDkuMjczSDguNDhsLS4wMDEtNy44MUwyMCAwdjkuMjczWk02Ljg3OSAxLjY2NmwuMDAxIDcuNjA3SDBWMi41MzlsNi44NzktLjg3M1oiLz48L3N2Zz4=)
![macOS](https://img.shields.io/badge/macOS-10.13%2B-000000?style=for-the-badge&logo=apple&logoColor=white)
![Linux](https://img.shields.io/badge/Linux-Any-FCC624?style=for-the-badge&logo=linux&logoColor=white)
<div align="left">
<h1>Twitter/X Media Batch Downloader</h1>
<p>
Downloads original-quality images and videos from Twitter/X accounts.
</p>
<p>
<a href="https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/stargazers"><img
src="https://img.shields.io/github/stars/afkarxyz/Twitter-X-Media-Batch-Downloader?color=ffcb47&labelColor=black&logo=github&label=Stars" /></a><a
href="https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases"><img
src="https://img.shields.io/github/downloads/afkarxyz/Twitter-X-Media-Batch-Downloader/total?color=22c55e&labelColor=black&logo=github&label=Downloads" /></a><a
href="https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases/latest"><img
src="https://img.shields.io/github/v/release/afkarxyz/Twitter-X-Media-Batch-Downloader?color=8b5cf6&labelColor=black&logo=github&label=Latest%20Release" /></a><a href="https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases/latest"><img
src="https://img.shields.io/badge/Windows-369eff?labelColor=black&logo=data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI1MTIiIGhlaWdodD0iNTEyIiB2aWV3Qm94PSIwIDAgMjAgMjAiPjxwYXRoIGZpbGw9IiNmZmZmZmYiIGZpbGwtcnVsZT0iZXZlbm9kZCIgZD0iTTIwIDEwLjg3M1YyMEw4LjQ3OSAxOC41MzdsLjAwMS03LjY2NEgyMFptLTEzLjEyIDBsLS4wMDEgNy40NjFMMCAxNy40NjF2LTYuNTg4aDYuODhaTTIwIDkuMjczSDguNDhsLS4wMDEtNy44MUwyMCAwdjkuMjczWk02Ljg3OSAxLjY2NmwuMDAxIDcuNjA3SDBWMi41MzlsNi44NzktLjg3M1oiLz48L3N2Zz4=" /></a><a
href="https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases/latest"><img
src="https://img.shields.io/badge/macOS-FFFFFF?labelColor=black&logo=apple&logoColor=white" /></a><a
href="https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases/latest"><img
src="https://img.shields.io/badge/Linux-FCC624?labelColor=black&logo=linux&logoColor=white" /></a>
<br />
<br />
<a href="https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases/latest" target="_blank"><img
src="https://github.com/user-attachments/assets/e95586cb-35ce-4ef7-a6ce-a5a18ebf3b29" alt="Dark"
width="49%" /></a>
<a href="https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases/latest" target="_blank"><img
src="https://github.com/user-attachments/assets/7581ca58-9e15-4dd9-ae45-14c2b8f3f9d6" alt="Light"
width="49%" /></a>
</p>
</div>
### [Download](https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases)
![Image](https://github.com/user-attachments/assets/324243e4-b64b-4ea2-9f3d-8b08575a138e)
- If you're familiar with userscripts, install it [**here**](https://greasyfork.org/en/scripts/523157)
- To install the Chrome extension version, click [**here**](https://chromewebstore.google.com/detail/cboceolmgkoobpfjiojkigmihijfgmdo)
- Also available on the web at [**TwitterDL.app**](https://twitterdl.app)
## Fetch pacing
Settings includes separate **Fetch Delay** controls: a base delay and a random
extra from zero to the configured value, in seconds. Both default to zero
(disabled). A suggested starting point is 5 seconds base plus up to 5 seconds
extra; this is not a guaranteed safe rate for Twitter/X.
The delay spaces out extractor starts across batches, accounts, resumes, retries,
and date-range fetches. The first fetch starts immediately. It does not control
requests made internally by the external extractor. Stop interrupts a pending
wait, and waiting counts toward Fetch Timeout, so increase the timeout when
using longer delays.
## How to Obtain Auth Token
> [!Warning]
+134 -41
View File
@@ -5,8 +5,11 @@ import (
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"time"
"twitterxmediabatchdownloader/backend"
"github.com/wailsapp/wails/v2/pkg/runtime"
@@ -44,14 +47,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 +82,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 +162,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)
}
@@ -189,15 +227,49 @@ func (a *App) Quit() {
panic("quit")
}
func (a *App) ExportFailedLogs(content string) (string, error) {
if strings.TrimSpace(content) == "" {
return "", fmt.Errorf("no failed logs to export")
}
if a.ctx == nil {
return "", fmt.Errorf("application is not ready")
}
path, err := runtime.SaveFileDialog(a.ctx, runtime.SaveDialogOptions{
DefaultFilename: fmt.Sprintf("TwitterXMediaBatchDownloader_%s_Failed.txt", time.Now().Format("20060102_150405")),
Title: "Export Failed Logs",
Filters: []runtime.FileFilter{
{
DisplayName: "Text Files (*.txt)",
Pattern: "*.txt",
},
},
})
if err != nil {
return "", fmt.Errorf("failed to open save dialog: %v", err)
}
if path == "" {
return "", nil
}
if err := os.WriteFile(path, []byte(content), 0644); err != nil {
return "", fmt.Errorf("failed to write log file: %v", err)
}
return path, nil
}
type DownloadMediaRequest struct {
URLs []string `json:"urls"`
OutputDir string `json:"output_dir"`
Username string `json:"username"`
ConcurrentDownloads int `json:"concurrent_downloads,omitempty"`
SkipExisting bool `json:"skip_existing"`
DeleteIncompleteFiles bool `json:"delete_incomplete_files"`
RetryAttempts int `json:"retry_attempts,omitempty"`
Proxy string `json:"proxy,omitempty"`
URLs []string `json:"urls"`
OutputDir string `json:"output_dir"`
Username string `json:"username"`
ConcurrentDownloads int `json:"concurrent_downloads,omitempty"`
SkipExisting bool `json:"skip_existing"`
DeleteIncompleteFiles bool `json:"delete_incomplete_files"`
RetryAttempts int `json:"retry_attempts,omitempty"`
DownloadSpeedLimitKBps int `json:"download_speed_limit_kbps,omitempty"`
DownloadDelayMillis int `json:"download_delay_ms,omitempty"`
DownloadDelayJitterMillis int `json:"download_delay_jitter_ms,omitempty"`
Proxy string `json:"proxy,omitempty"`
}
type MediaItemRequest struct {
@@ -208,17 +280,26 @@ type MediaItemRequest struct {
Content string `json:"content,omitempty"`
OriginalFilename string `json:"original_filename,omitempty"`
AuthorUsername string `json:"author_username,omitempty"`
AccountName string `json:"account_name,omitempty"`
}
type DownloadMediaWithMetadataRequest struct {
Items []MediaItemRequest `json:"items"`
OutputDir string `json:"output_dir"`
Username string `json:"username"`
ConcurrentDownloads int `json:"concurrent_downloads,omitempty"`
SkipExisting bool `json:"skip_existing"`
DeleteIncompleteFiles bool `json:"delete_incomplete_files"`
RetryAttempts int `json:"retry_attempts,omitempty"`
Proxy string `json:"proxy,omitempty"`
Items []MediaItemRequest `json:"items"`
OutputDir string `json:"output_dir"`
Username string `json:"username"`
ConcurrentDownloads int `json:"concurrent_downloads,omitempty"`
SkipExisting bool `json:"skip_existing"`
DeleteIncompleteFiles bool `json:"delete_incomplete_files"`
RetryAttempts int `json:"retry_attempts,omitempty"`
DownloadSpeedLimitKBps int `json:"download_speed_limit_kbps,omitempty"`
DownloadDelayMillis int `json:"download_delay_ms,omitempty"`
DownloadDelayJitterMillis int `json:"download_delay_jitter_ms,omitempty"`
Proxy string `json:"proxy,omitempty"`
FilenameTemplate string `json:"filename_template,omitempty"`
FolderTemplate string `json:"folder_template,omitempty"`
AutoConvertGIFs bool `json:"auto_convert_gifs,omitempty"`
GIFQuality string `json:"gif_quality,omitempty"`
GIFResolution string `json:"gif_resolution,omitempty"`
}
type DownloadMediaResponse struct {
@@ -249,10 +330,13 @@ func (a *App) DownloadMedia(req DownloadMediaRequest) (DownloadMediaResponse, er
}
options := backend.DownloadOptions{
ConcurrentDownloads: req.ConcurrentDownloads,
SkipExistingFiles: req.SkipExisting,
DeleteIncompleteFiles: req.DeleteIncompleteFiles,
RetryAttempts: req.RetryAttempts,
ConcurrentDownloads: req.ConcurrentDownloads,
SkipExistingFiles: req.SkipExisting,
DeleteIncompleteFiles: req.DeleteIncompleteFiles,
RetryAttempts: req.RetryAttempts,
DownloadSpeedLimitKBps: req.DownloadSpeedLimitKBps,
DownloadDelayMillis: req.DownloadDelayMillis,
DownloadDelayJitterMillis: req.DownloadDelayJitterMillis,
}
downloaded, failed, err := backend.DownloadMediaFiles(req.URLs, outputDir, options, req.Proxy)
@@ -313,7 +397,7 @@ func (a *App) DownloadMediaWithMetadata(req DownloadMediaWithMetadataRequest) (D
}
username := req.Username
if item.AuthorUsername != "" {
if (req.Username == "bookmarks" || req.Username == "likes") && item.AuthorUsername != "" {
username = item.AuthorUsername
}
@@ -323,6 +407,7 @@ func (a *App) DownloadMediaWithMetadata(req DownloadMediaWithMetadataRequest) (D
TweetID: int64(item.TweetID),
Type: item.Type,
Username: username,
AccountName: item.AccountName,
Content: item.Content,
OriginalFilename: originalFilename,
}
@@ -359,10 +444,18 @@ func (a *App) DownloadMediaWithMetadata(req DownloadMediaWithMetadataRequest) (D
}
options := backend.DownloadOptions{
ConcurrentDownloads: req.ConcurrentDownloads,
SkipExistingFiles: req.SkipExisting,
DeleteIncompleteFiles: req.DeleteIncompleteFiles,
RetryAttempts: req.RetryAttempts,
ConcurrentDownloads: req.ConcurrentDownloads,
SkipExistingFiles: req.SkipExisting,
DeleteIncompleteFiles: req.DeleteIncompleteFiles,
RetryAttempts: req.RetryAttempts,
DownloadSpeedLimitKBps: req.DownloadSpeedLimitKBps,
DownloadDelayMillis: req.DownloadDelayMillis,
DownloadDelayJitterMillis: req.DownloadDelayJitterMillis,
FilenameTemplate: req.FilenameTemplate,
FolderTemplate: req.FolderTemplate,
AutoConvertGIFs: req.AutoConvertGIFs,
GIFQuality: req.GIFQuality,
GIFResolution: req.GIFResolution,
}
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 {
+388 -36
View File
@@ -5,6 +5,7 @@ import (
"errors"
"fmt"
"io"
"math/rand/v2"
"net/http"
"net/url"
"os"
@@ -20,6 +21,8 @@ const (
MaxConcurrentDownloads = 50
DefaultRetryAttempts = 2
MaxRetryAttempts = 5
MaxDownloadSpeedLimitKBps = 10 * 1024 * 1024
MaxDownloadDelayMillis = 60 * 60 * 1000
)
func NormalizeConcurrentDownloads(requested int) int {
@@ -42,25 +45,176 @@ func NormalizeRetryAttempts(requested int) int {
return requested
}
func normalizeDownloadSpeedLimit(requested int) int {
if requested < 0 {
return 0
}
if requested > MaxDownloadSpeedLimitKBps {
return MaxDownloadSpeedLimitKBps
}
return requested
}
func normalizeDownloadDelay(requested int) int {
if requested < 0 {
return 0
}
if requested > MaxDownloadDelayMillis {
return MaxDownloadDelayMillis
}
return requested
}
type DownloadOptions struct {
ConcurrentDownloads int
SkipExistingFiles bool
DeleteIncompleteFiles bool
RetryAttempts int
ConcurrentDownloads int
SkipExistingFiles bool
DeleteIncompleteFiles bool
RetryAttempts int
DownloadSpeedLimitKBps int
DownloadDelayMillis int
DownloadDelayJitterMillis int
FilenameTemplate string
FolderTemplate string
AutoConvertGIFs bool
GIFQuality string
GIFResolution string
}
func NormalizeDownloadOptions(options DownloadOptions) DownloadOptions {
options.ConcurrentDownloads = NormalizeConcurrentDownloads(options.ConcurrentDownloads)
options.RetryAttempts = NormalizeRetryAttempts(options.RetryAttempts)
options.DownloadSpeedLimitKBps = normalizeDownloadSpeedLimit(options.DownloadSpeedLimitKBps)
options.DownloadDelayMillis = normalizeDownloadDelay(options.DownloadDelayMillis)
options.DownloadDelayJitterMillis = normalizeDownloadDelay(options.DownloadDelayJitterMillis)
return options
}
type downloadThrottle struct {
speedBytesPerSecond int64
delay time.Duration
delayJitter time.Duration
requestMu sync.Mutex
nextRequestStart time.Time
requestStarted bool
bandwidthMu sync.Mutex
nextByteWriteTime time.Time
}
func newDownloadThrottle(options DownloadOptions) *downloadThrottle {
options = NormalizeDownloadOptions(options)
if options.DownloadSpeedLimitKBps == 0 && options.DownloadDelayMillis == 0 && options.DownloadDelayJitterMillis == 0 {
return nil
}
return &downloadThrottle{
speedBytesPerSecond: int64(options.DownloadSpeedLimitKBps) * 1024,
delay: time.Duration(options.DownloadDelayMillis) * time.Millisecond,
delayJitter: time.Duration(options.DownloadDelayJitterMillis) * time.Millisecond,
}
}
func waitUntil(ctx context.Context, deadline time.Time) error {
wait := time.Until(deadline)
if wait <= 0 {
return nil
}
timer := time.NewTimer(wait)
defer timer.Stop()
select {
case <-ctx.Done():
return ctx.Err()
case <-timer.C:
return nil
}
}
func (t *downloadThrottle) waitForRequest(ctx context.Context) error {
if t == nil || (t.delay == 0 && t.delayJitter == 0) {
return nil
}
t.requestMu.Lock()
now := time.Now()
startAt := now
if t.requestStarted && t.nextRequestStart.After(startAt) {
startAt = t.nextRequestStart
}
jitter := time.Duration(0)
if t.delayJitter > 0 {
jitter = time.Duration(rand.Int64N(int64(t.delayJitter) + 1))
}
t.nextRequestStart = startAt.Add(t.delay + jitter)
t.requestStarted = true
t.requestMu.Unlock()
return waitUntil(ctx, startAt)
}
func (t *downloadThrottle) waitForBytes(ctx context.Context, byteCount int) error {
if t == nil || t.speedBytesPerSecond <= 0 || byteCount <= 0 {
return nil
}
nanoseconds := (int64(byteCount)*int64(time.Second) + t.speedBytesPerSecond - 1) / t.speedBytesPerSecond
duration := time.Duration(nanoseconds)
t.bandwidthMu.Lock()
now := time.Now()
if t.nextByteWriteTime.Before(now) {
t.nextByteWriteTime = now
}
t.nextByteWriteTime = t.nextByteWriteTime.Add(duration)
writeAt := t.nextByteWriteTime
t.bandwidthMu.Unlock()
return waitUntil(ctx, writeAt)
}
type throttledWriter struct {
ctx context.Context
writer io.Writer
throttle *downloadThrottle
}
func (w throttledWriter) Write(p []byte) (int, error) {
if err := w.throttle.waitForBytes(w.ctx, len(p)); err != nil {
return 0, err
}
return w.writer.Write(p)
}
func createMediaDownloadClient(customProxy string, options DownloadOptions) *http.Client {
client, err := CreateHTTPClient(customProxy, 60*time.Second)
if err != nil {
client = &http.Client{Timeout: 60 * time.Second}
}
if options.DownloadSpeedLimitKBps > 0 {
client.Timeout = 0
if transport, ok := client.Transport.(*http.Transport); ok {
transport.ResponseHeaderTimeout = 60 * time.Second
} else if client.Transport == nil {
transport := http.DefaultTransport.(*http.Transport).Clone()
transport.ResponseHeaderTimeout = 60 * time.Second
client.Transport = transport
}
}
return client
}
type MediaItem struct {
URL string `json:"url"`
Date string `json:"date"`
TweetID int64 `json:"tweet_id"`
Type string `json:"type"`
Username string `json:"username"`
AccountName string `json:"account_name,omitempty"`
Content string `json:"content,omitempty"`
OriginalFilename string `json:"original_filename,omitempty"`
}
@@ -72,13 +226,8 @@ func DownloadMediaFiles(urls []string, outputDir string, options DownloadOptions
return 0, len(urls), fmt.Errorf("failed to create output directory: %v", err)
}
client, err := CreateHTTPClient(customProxy, 60*time.Second)
if err != nil {
client = &http.Client{
Timeout: 60 * time.Second,
}
}
client := createMediaDownloadClient(customProxy, options)
throttle := newDownloadThrottle(options)
for _, mediaURL := range urls {
filename := extractFilename(mediaURL)
@@ -91,7 +240,7 @@ func DownloadMediaFiles(urls []string, outputDir string, options DownloadOptions
}
}
if err := downloadFileWithRetry(context.Background(), client, mediaURL, outputPath, options); err != nil {
if err := downloadFileWithRetry(context.Background(), client, mediaURL, outputPath, options, throttle); err != nil {
failed++
continue
}
@@ -191,14 +340,14 @@ func waitForRetry(ctx context.Context, attempt int) error {
}
}
func downloadFileWithRetry(ctx context.Context, client *http.Client, mediaURL, outputPath string, options DownloadOptions) error {
func downloadFileWithRetry(ctx context.Context, client *http.Client, mediaURL, outputPath string, options DownloadOptions, throttle *downloadThrottle) error {
options = NormalizeDownloadOptions(options)
var lastErr error
totalAttempts := options.RetryAttempts + 1
for attempt := 1; attempt <= totalAttempts; attempt++ {
keepPartialOnFailure := !options.DeleteIncompleteFiles && attempt == totalAttempts
lastErr = downloadFileWithContext(ctx, client, mediaURL, outputPath, !options.SkipExistingFiles, keepPartialOnFailure)
lastErr = downloadFileWithContext(ctx, client, mediaURL, outputPath, !options.SkipExistingFiles, keepPartialOnFailure, throttle)
if lastErr == nil {
return nil
}
@@ -245,6 +394,13 @@ type downloadTask struct {
index int
}
type pendingDownloadTask struct {
task downloadTask
typeDir string
baseName string
ext string
}
func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir string, username string, progress ProgressCallback, itemStatus ItemStatusCallback, ctx context.Context, options DownloadOptions, customProxy string) (downloaded int, skipped int, failed int, err error) {
if ctx == nil {
ctx = context.Background()
@@ -257,7 +413,9 @@ func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir str
}
tweetMediaCount := make(map[string]map[int64]int)
tasks := make([]downloadTask, 0, total)
pendingTasks := make([]pendingDownloadTask, 0, total)
filenameCounts := make(map[string]int)
downloadDate := time.Now().Format("20060102")
for i, item := range items {
@@ -265,6 +423,10 @@ func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir str
if itemUsername == "" {
itemUsername = username
}
itemAccountName := item.AccountName
if itemAccountName == "" {
itemAccountName = itemUsername
}
if tweetMediaCount[itemUsername] == nil {
tweetMediaCount[itemUsername] = make(map[int64]int)
@@ -284,7 +446,7 @@ func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir str
subfolder = "other"
}
baseDir := filepath.Join(outputDir, itemUsername)
baseDir := filepath.Join(outputDir, renderFolder(options.FolderTemplate, itemUsername, itemAccountName, downloadDate))
if err := os.MkdirAll(baseDir, 0755); err != nil {
continue
}
@@ -301,20 +463,58 @@ 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)
outputPath := filepath.Join(typeDir, filename)
mediaID := item.OriginalFilename
if mediaID == "" {
mediaID = ExtractOriginalFilename(item.URL)
}
tasks = append(tasks, downloadTask{
item: item,
outputPath: outputPath,
index: i,
baseName := renderFilename(options.FilenameTemplate, itemUsername, itemAccountName, timestamp, item.TweetID, item.Type, mediaIndex, mediaID)
filenameCounts[filenameCollisionKey(typeDir, baseName, ext)]++
pendingTasks = append(pendingTasks, pendingDownloadTask{
task: downloadTask{
item: item,
index: i,
},
typeDir: typeDir,
baseName: baseName,
ext: ext,
})
}
filenameIndexes := make(map[string]int, len(filenameCounts))
tasks := make([]downloadTask, 0, len(pendingTasks))
for _, pending := range pendingTasks {
key := filenameCollisionKey(pending.typeDir, pending.baseName, pending.ext)
filenameIndexes[key]++
filename := formatDownloadFilename(
pending.baseName,
pending.ext,
filenameCounts[key],
filenameIndexes[key],
)
if options.SkipExistingFiles {
canonicalPath := filepath.Join(pending.typeDir, formatDownloadFilename(pending.baseName, pending.ext, 1, 1))
if exists, err := fileExists(canonicalPath); err == nil && exists {
pending.task.outputPath = canonicalPath
tasks = append(tasks, pending.task)
continue
}
}
pending.task.outputPath = filepath.Join(pending.typeDir, filename)
tasks = append(tasks, pending.task)
}
var downloadedCount int64
var skippedCount int64
var failedCount int64
var completedCount int64
var conversionWG sync.WaitGroup
taskChan := make(chan downloadTask, len(tasks))
var wg sync.WaitGroup
@@ -324,16 +524,8 @@ func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir str
numWorkers = len(tasks)
}
var sharedClient *http.Client
client, err := CreateHTTPClient(customProxy, 60*time.Second)
if err != nil {
sharedClient = &http.Client{
Timeout: 60 * time.Second,
}
} else {
sharedClient = client
}
sharedClient := createMediaDownloadClient(customProxy, options)
throttle := newDownloadThrottle(options)
for i := 0; i < numWorkers; i++ {
wg.Add(1)
@@ -389,7 +581,7 @@ func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir str
atomic.AddInt64(&downloadedCount, 1)
status = "success"
}
} else if err := downloadFileWithRetry(ctx, client, task.item.URL, task.outputPath, options); err != nil {
} else if err := downloadFileWithRetry(ctx, client, task.item.URL, task.outputPath, options, throttle); err != nil {
if ctx.Err() != nil || errors.Is(err, context.Canceled) {
if itemStatus != nil {
itemStatus(task.item.TweetID, task.index, "cancelled")
@@ -413,6 +605,15 @@ func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir str
atomic.AddInt64(&downloadedCount, 1)
status = "success"
if shouldAutoConvertGIF(task.item.Type, options) && ctx.Err() == nil {
conversionWG.Add(1)
go func(inputPath string) {
defer conversionWG.Done()
outputPath := strings.TrimSuffix(inputPath, filepath.Ext(inputPath)) + ".gif"
_ = ConvertMP4ToGIFWithContext(ctx, inputPath, outputPath, normalizeGIFQuality(options.GIFQuality), normalizeGIFResolution(options.GIFResolution))
}(task.outputPath)
}
}
if itemStatus != nil {
@@ -436,6 +637,7 @@ func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir str
close(taskChan)
wg.Wait()
conversionWG.Wait()
if err := ctx.Err(); err != nil {
return int(downloadedCount), int(skippedCount), int(failedCount), err
@@ -444,7 +646,39 @@ func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir str
return int(downloadedCount), int(skippedCount), int(failedCount), nil
}
func downloadFileWithContext(ctx context.Context, client *http.Client, url, outputPath string, allowOverwrite bool, keepPartialOnFailure bool) error {
func shouldAutoConvertGIF(mediaType string, options DownloadOptions) bool {
if !options.AutoConvertGIFs || !IsFFmpegInstalled() {
return false
}
switch mediaType {
case "gif", "animated_gif":
return true
default:
return false
}
}
func normalizeGIFQuality(quality string) string {
if quality == "better" {
return quality
}
return "fast"
}
func normalizeGIFResolution(resolution string) string {
switch resolution {
case "original", "high", "medium", "low":
return resolution
default:
return "original"
}
}
func downloadFileWithContext(ctx context.Context, client *http.Client, url, outputPath string, allowOverwrite bool, keepPartialOnFailure bool, throttle *downloadThrottle) error {
if err := throttle.waitForRequest(ctx); err != nil {
return err
}
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
if err != nil {
return err
@@ -475,7 +709,11 @@ func downloadFileWithContext(ctx context.Context, client *http.Client, url, outp
}
}()
_, err = io.Copy(out, resp.Body)
writer := io.Writer(out)
if throttle != nil && throttle.speedBytesPerSecond > 0 {
writer = throttledWriter{ctx: ctx, writer: out, throttle: throttle}
}
_, err = io.Copy(writer, resp.Body)
if err != nil {
return err
}
@@ -519,6 +757,92 @@ func formatTimestamp(dateStr string) string {
return "00000000_000000"
}
func renderFilename(template, username, accountName, timestamp string, tweetID int64, mediaType string, index int, mediaID string) string {
if strings.TrimSpace(template) == "" {
template = "{handle}_{date}_{tweet_id}"
}
replacer := strings.NewReplacer(
"{handle}", sanitizeFilenamePart(username),
"{name}", sanitizeFilenamePart(accountName),
"{username}", sanitizeFilenamePart(username),
"{account_name}", sanitizeFilenamePart(accountName),
"{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))
name = sanitizeFilenamePart(name)
if name == "" {
name = sanitizeFilenamePart(fmt.Sprintf("%s_%s_%d", username, timestamp, tweetID))
}
return name
}
func filenameCollisionKey(dir, baseName, ext string) string {
return dir + "\x00" + baseName + ext
}
func formatDownloadFilename(baseName, ext string, duplicateCount, duplicateIndex int) string {
if duplicateCount > 1 {
return fmt.Sprintf("%s_%02d%s", baseName, duplicateIndex, ext)
}
return baseName + ext
}
func renderFolder(template, username, accountName, date string) string {
if strings.TrimSpace(template) == "" {
template = "{handle}"
}
replacer := strings.NewReplacer(
"{handle}", sanitizeFilenamePart(username),
"{name}", sanitizeFilenamePart(accountName),
"{username}", sanitizeFilenamePart(username),
"{account_name}", sanitizeFilenamePart(accountName),
"{date}", date,
)
name := strings.TrimSpace(replacer.Replace(template))
name = sanitizeFilenamePart(name)
if name == "" {
name = sanitizeFilenamePart(username)
}
return name
}
func sanitizeFilenamePart(s string) string {
cleaned := strings.TrimSpace(strings.Map(func(r rune) rune {
switch r {
case '\\', '/', ':', '*', '?', '"', '<', '>', '|':
return -1
}
if r >= 0 && r < 32 {
return -1
}
return r
}, s))
cleaned = strings.TrimRight(cleaned, ". ")
if isWindowsReservedName(cleaned) {
return cleaned + "_"
}
return cleaned
}
func isWindowsReservedName(name string) bool {
base := name
if dotIndex := strings.IndexByte(base, '.'); dotIndex >= 0 {
base = base[:dotIndex]
}
base = strings.ToUpper(strings.TrimSpace(base))
switch base {
case "CON", "PRN", "AUX", "NUL":
return true
}
return len(base) == 4 &&
((strings.HasPrefix(base, "COM") && base[3] >= '1' && base[3] <= '9') ||
(strings.HasPrefix(base, "LPT") && base[3] >= '1' && base[3] <= '9'))
}
func getExtension(mediaURL string, mediaType string) string {
parsedURL, err := url.Parse(mediaURL)
if err != nil {
@@ -587,5 +911,33 @@ func downloadFile(client *http.Client, url, outputPath string) error {
SkipExistingFiles: false,
DeleteIncompleteFiles: true,
RetryAttempts: 0,
})
}, nil)
}
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
}
+8 -4
View File
@@ -32,8 +32,10 @@ type extractorVersionMetadata struct {
}
type githubRelease struct {
TagName string `json:"tag_name"`
Assets []githubReleaseAsset `json:"assets"`
TagName string `json:"tag_name"`
Draft bool `json:"draft"`
Prerelease bool `json:"prerelease"`
Assets []githubReleaseAsset `json:"assets"`
}
type githubReleaseAsset struct {
@@ -144,8 +146,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 +177,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()
+40 -10
View File
@@ -2,6 +2,7 @@ package backend
import (
"archive/zip"
"context"
"encoding/json"
"fmt"
"io"
@@ -17,9 +18,11 @@ 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"
ffmpegReleasesAPIURL = "https://api.github.com/repos/spotbye/Dependencies/releases?per_page=100"
ffmpegReleaseTagPrefix = "FFmpeg-"
ffmpegFallbackReleaseTag = "FFmpeg-9.0"
ffmpegFallbackReleaseURL = "https://github.com/spotbye/Dependencies/releases/tag/" + ffmpegFallbackReleaseTag
ffmpegFallbackDownloadBaseURL = "https://github.com/spotbye/Dependencies/releases/download/" + ffmpegFallbackReleaseTag
)
var ffmpegVersionPattern = regexp.MustCompile(`^[0-9]+(?:\.[0-9]+)+`)
@@ -205,7 +208,7 @@ func fetchLatestFFmpegRelease() (*githubRelease, error) {
return nil, fmt.Errorf("failed to configure ffmpeg network client: %v", err)
}
req, err := newFFmpegGitHubRequest(ffmpegReleaseAPIURL)
req, err := newFFmpegGitHubRequest(ffmpegReleasesAPIURL)
if err != nil {
return nil, err
}
@@ -220,12 +223,26 @@ func fetchLatestFFmpegRelease() (*githubRelease, error) {
return nil, fmt.Errorf("failed to fetch ffmpeg release info: status %d", resp.StatusCode)
}
var release githubRelease
if err := json.NewDecoder(resp.Body).Decode(&release); err != nil {
var releases []githubRelease
if err := json.NewDecoder(resp.Body).Decode(&releases); err != nil {
return nil, fmt.Errorf("failed to decode ffmpeg release info: %v", err)
}
return &release, nil
return findLatestStableFFmpegRelease(releases)
}
func findLatestStableFFmpegRelease(releases []githubRelease) (*githubRelease, error) {
for index := range releases {
release := &releases[index]
if release.Draft || release.Prerelease || !strings.HasPrefix(strings.ToLower(release.TagName), strings.ToLower(ffmpegReleaseTagPrefix)) {
continue
}
if normalizeFFmpegVersion(release.TagName) != "" {
return release, nil
}
}
return nil, fmt.Errorf("no stable ffmpeg release found")
}
func newFFmpegGitHubRequest(url string) (*http.Request, error) {
@@ -259,7 +276,7 @@ func fetchLatestFFmpegVersionFromRedirect() (string, error) {
return http.ErrUseLastResponse
}
req, err := http.NewRequest(http.MethodGet, ffmpegLatestReleaseURL, nil)
req, err := http.NewRequest(http.MethodGet, ffmpegFallbackReleaseURL, nil)
if err != nil {
return "", fmt.Errorf("failed to create ffmpeg redirect request: %v", err)
}
@@ -301,7 +318,7 @@ func parseFFmpegVersionFromReleaseURL(releaseURL string) string {
}
func buildLatestFFmpegDownloadURL(assetName string) string {
return ffmpegLatestDownloadBaseURL + "/" + assetName
return ffmpegFallbackDownloadBaseURL + "/" + assetName
}
func downloadFFmpegArchive(downloadURL string, destination *os.File, progressCallback func(downloaded, total int64)) error {
@@ -497,6 +514,9 @@ func normalizeFFmpegVersion(version string) string {
if strings.HasPrefix(lowerVersion, "ffmpeg version ") {
version = strings.TrimSpace(version[len("ffmpeg version "):])
}
if strings.HasPrefix(strings.ToLower(version), strings.ToLower(ffmpegReleaseTagPrefix)) {
version = version[len(ffmpegReleaseTagPrefix):]
}
fields := strings.Fields(version)
if len(fields) > 0 {
@@ -531,11 +551,18 @@ func normalizeFFmpegVersion(version string) string {
}
func ConvertMP4ToGIF(inputPath, outputPath, quality, resolution string) error {
return ConvertMP4ToGIFWithContext(context.Background(), inputPath, outputPath, quality, resolution)
}
func ConvertMP4ToGIFWithContext(ctx context.Context, inputPath, outputPath, quality, resolution string) error {
ffmpegPath := GetFFmpegPath()
if !IsFFmpegInstalled() {
return fmt.Errorf("ffmpeg not installed")
}
if ctx == nil {
ctx = context.Background()
}
var args []string
@@ -598,10 +625,13 @@ func ConvertMP4ToGIF(inputPath, outputPath, quality, resolution string) error {
}
}
cmd := exec.Command(ffmpegPath, args...)
cmd := exec.CommandContext(ctx, ffmpegPath, args...)
hideWindow(cmd)
output, err := cmd.CombinedOutput()
if err != nil {
if ctx.Err() != nil {
return ctx.Err()
}
return fmt.Errorf("ffmpeg error: %v, output: %s", err, string(output))
}
+2 -1
View File
@@ -11,6 +11,7 @@ import (
)
func OpenFolderInExplorer(path string) error {
os.WriteFile(filepath.Join(os.TempDir(), "openfolder.txt"), []byte(path), 0644)
info, err := os.Stat(path)
if err != nil {
return err
@@ -23,7 +24,7 @@ func OpenFolderInExplorer(path string) error {
switch runtime.GOOS {
case "windows":
cmd = exec.Command("explorer", path)
cmd = exec.Command("cmd", "/C", "start", "", path)
case "darwin":
cmd = exec.Command("open", path)
case "linux":
+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]`)
)
+441 -360
View File
@@ -9,6 +9,7 @@ import (
"os/exec"
"path/filepath"
"runtime"
"sort"
"strings"
"sync"
)
@@ -40,21 +41,33 @@ func unregisterExtractorCommand(cmd *exec.Cmd) {
activeExtractorCommands.Unlock()
}
func runTrackedExtractorCommand(cmd *exec.Cmd) ([]byte, error) {
var output bytes.Buffer
cmd.Stdout = &output
cmd.Stderr = &output
func runTrackedExtractorCommand(cmd *exec.Cmd) (stdout, stderr []byte, err error) {
var stdoutBuffer bytes.Buffer
var stderrBuffer bytes.Buffer
cmd.Stdout = &stdoutBuffer
cmd.Stderr = &stderrBuffer
hideWindow(cmd)
if err := cmd.Start(); err != nil {
return nil, err
return nil, nil, err
}
registerExtractorCommand(cmd)
defer unregisterExtractorCommand(cmd)
err := cmd.Wait()
return output.Bytes(), err
err = cmd.Wait()
return stdoutBuffer.Bytes(), stderrBuffer.Bytes(), err
}
func extractorErrorOutput(stdout, stderr []byte) string {
parts := make([]string, 0, 2)
if text := strings.TrimSpace(string(stderr)); text != "" {
parts = append(parts, text)
}
if text := strings.TrimSpace(string(stdout)); text != "" {
parts = append(parts, text)
}
return strings.Join(parts, "\n")
}
func getExecutableName() string {
@@ -110,11 +123,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 +162,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,26 +270,41 @@ 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"`
AuthorUsername string `json:"author_username,omitempty"`
AuthorName string `json:"author_name,omitempty"`
}
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 +326,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 +454,252 @@ 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,
AuthorName: t.Author.Name,
}
}
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,
AuthorName: t.Author.Name,
}
}
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 +709,20 @@ func ExtractTimeline(req TimelineRequest) (*TwitterResponse, error) {
return nil, err
}
isTextOnly := req.MediaType == "text"
wantsRetweets := req.Retweets
includeText := req.IncludeText
timelineType := req.TimelineType
if timelineType == "" {
if isTextOnly {
timelineType = "tweets"
} else if wantsRetweets {
if includeText {
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)
@@ -506,13 +730,13 @@ func ExtractTimeline(req TimelineRequest) (*TwitterResponse, error) {
args = append(args, "--guest")
}
args = append(args, "--json", "--metadata")
args = append(args, "--json", "--metadata", "--no-discord")
if req.BatchSize > 0 {
args = append(args, "--limit", fmt.Sprintf("%d", req.BatchSize))
}
if timelineType == "tweets" || timelineType == "timeline" {
if timelineType == "tweets" || timelineType == "timeline" || timelineType == "media" {
if req.Retweets {
args = append(args, "--retweets", "include")
} else {
@@ -520,21 +744,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)
}
@@ -544,10 +757,10 @@ func ExtractTimeline(req TimelineRequest) (*TwitterResponse, error) {
"PYTHONIOENCODING=utf-8",
"PYTHONUTF8=1",
)
output, err := runTrackedExtractorCommand(cmd)
stdout, stderr, err := runTrackedExtractorCommand(cmd)
if err != nil {
outputStr := string(output)
outputStr := extractorErrorOutput(stdout, stderr)
if strings.TrimSpace(outputStr) == "" {
return nil, fmt.Errorf("xtractor process terminated before returning data")
}
@@ -555,30 +768,20 @@ func ExtractTimeline(req TimelineRequest) (*TwitterResponse, error) {
return nil, fmt.Errorf("%s", errorMsg)
}
jsonStr := extractJSON(string(output))
jsonStr := strings.TrimSpace(string(stdout))
if jsonStr == "" {
outputStr := string(output)
if strings.TrimSpace(outputStr) == "" {
if strings.TrimSpace(string(stderr)) == "" {
return nil, fmt.Errorf("empty_response: Xtractor returned no data. The timeline may be empty or inaccessible")
}
return nil, fmt.Errorf("parse_error: Could not parse xtractor output. Raw output: %s", outputStr)
return nil, fmt.Errorf("empty_response: Xtractor returned no JSON. Logs: %s", strings.TrimSpace(string(stderr)))
}
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 +793,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 +811,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 +830,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)
@@ -712,7 +840,7 @@ func ExtractDateRange(req DateRangeRequest) (*TwitterResponse, error) {
args = append(args, "--guest")
}
args = append(args, "--json", "--metadata")
args = append(args, "--json", "--metadata", "--no-discord")
if req.Retweets {
args = append(args, "--retweets", "include")
@@ -730,10 +858,10 @@ func ExtractDateRange(req DateRangeRequest) (*TwitterResponse, error) {
"PYTHONIOENCODING=utf-8",
"PYTHONUTF8=1",
)
output, err := runTrackedExtractorCommand(cmd)
stdout, stderr, err := runTrackedExtractorCommand(cmd)
if err != nil {
outputStr := string(output)
outputStr := extractorErrorOutput(stdout, stderr)
if strings.TrimSpace(outputStr) == "" {
return nil, fmt.Errorf("xtractor process terminated before returning data")
}
@@ -741,58 +869,27 @@ func ExtractDateRange(req DateRangeRequest) (*TwitterResponse, error) {
return nil, fmt.Errorf("%s", errorMsg)
}
jsonStr := extractJSON(string(output))
jsonStr := strings.TrimSpace(string(stdout))
if jsonStr == "" {
outputStr := string(output)
if strings.TrimSpace(outputStr) == "" {
if strings.TrimSpace(string(stderr)) == "" {
return nil, fmt.Errorf("empty_response: Xtractor returned no data. The timeline may be empty or inaccessible")
}
return nil, fmt.Errorf("parse_error: Could not parse xtractor output. Raw output: %s", outputStr)
return nil, fmt.Errorf("empty_response: Xtractor returned no JSON. Logs: %s", strings.TrimSpace(string(stderr)))
}
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,35 +899,19 @@ 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 extractJSON(output string) string {
start := strings.Index(output, "{")
if start == -1 {
return ""
}
depth := 0
for i := start; i < len(output); i++ {
if output[i] == '{' {
depth++
} else if output[i] == '}' {
depth--
if depth == 0 {
return output[start : i+1]
}
}
}
return ""
func getExtractorPath() string {
homeDir, _ := os.UserHomeDir()
baseDir := filepath.Join(homeDir, ".twitterxmediabatchdownloader")
return filepath.Join(baseDir, getExecutableName())
}
+31 -30
View File
@@ -4,6 +4,7 @@
"version": "0.0.0",
"type": "module",
"scripts": {
"test": "node --experimental-strip-types --test scripts/*.test.mjs",
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "eslint .",
@@ -12,42 +13,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.11",
"@radix-ui/react-context-menu": "^2.3.7",
"@radix-ui/react-dialog": "^1.1.23",
"@radix-ui/react-dropdown-menu": "^2.1.24",
"@radix-ui/react-label": "^2.1.15",
"@radix-ui/react-progress": "^1.1.16",
"@radix-ui/react-select": "^2.3.7",
"@radix-ui/react-slot": "^1.3.3",
"@radix-ui/react-switch": "^1.3.7",
"@radix-ui/react-tooltip": "^1.2.16",
"@tailwindcss/vite": "^4.3.3",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"lucide-react": "^0.562.0",
"motion": "^12.23.26",
"motion": "^12.43.0",
"next-themes": "^0.4.6",
"react": "^19.2.3",
"react-dom": "^19.2.3",
"sonner": "^2.0.7",
"tailwind-merge": "^3.4.0",
"tailwindcss": "^4.1.18"
"react": "^19.2.8",
"react-dom": "^19.2.8",
"sonner": "^2.0.8",
"tailwind-merge": "^3.6.0",
"tailwindcss": "^4.3.3"
},
"devDependencies": {
"@eslint/js": "^9.39.2",
"@types/node": "^25.0.3",
"@types/react": "^19.2.7",
"@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",
"@eslint/js": "^10.0.1",
"@types/node": "^26.2.0",
"@types/react": "^19.2.18",
"@types/react-dom": "^19.2.4",
"@vitejs/plugin-react": "^6.0.5",
"eslint": "^10.8.1",
"eslint-plugin-react-hooks": "^7.1.1",
"eslint-plugin-react-refresh": "^0.5.4",
"globals": "^17.11.0",
"sharp": "^0.35.3",
"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.67.0",
"vite": "^8.2.1"
}
}
+1 -1
View File
@@ -1 +1 @@
cb4545ab700ecc9d641ab1be76b622f1
11d903f252aa57269b096713a9fa71fe
+1688 -1790
View File
File diff suppressed because it is too large. Load diff
+84
View File
@@ -0,0 +1,84 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { createFetchDelayGate, normalizeFetchDelay } from "../src/lib/fetch-delay.ts";
function clock(random = 0.5) {
let time = 0;
const waits = [];
const gate = createFetchDelayGate({
now: () => time,
random: () => random,
sleep: async (ms) => { waits.push(ms); time += ms; },
});
return { gate, waits, now: () => time, advance: (ms) => { time += ms; } };
}
test("old or invalid settings disable delay; valid settings are bounded", () => {
for (const value of [undefined, null, "5", NaN, Infinity, -1]) {
assert.equal(normalizeFetchDelay(value), 0);
}
assert.equal(normalizeFetchDelay(4000), 3600);
assert.equal(normalizeFetchDelay(1.2345), 1.235);
});
test("first fetch starts immediately; later batches/accounts share pacing", async () => {
const c = clock();
assert.equal(await c.gate(5, 5, () => false), true);
assert.equal(c.now(), 0);
c.advance(2000); // Time spent fetching the previous batch.
assert.equal(await c.gate(5, 5, () => false), true);
assert.equal(c.now(), 7500);
await c.gate(5, 5, () => false);
assert.equal(c.now(), 15000);
assert.ok(c.waits.every((ms) => ms <= 100));
});
test("disabled pacing and a long fetch do not introduce unnecessary waits", async () => {
const c = clock();
await c.gate(0, 0, () => false);
await c.gate(0, 0, () => false);
c.advance(10000);
await c.gate(5, 0, () => false);
assert.deepEqual(c.waits, []);
});
test("random-only pacing supports both ends of the random range", async () => {
for (const random of [0, 0.999]) {
const c = clock(random);
await c.gate(0, 5, () => false);
await c.gate(0, 5, () => false);
assert.equal(c.now(), random * 5000);
}
});
test("stop or timeout during a wait prevents the next fetch from starting", async () => {
const c = clock();
await c.gate(5, 0, () => false);
assert.equal(await c.gate(5, 0, () => c.now() >= 200), false);
assert.equal(c.now(), 200);
assert.equal(await c.gate(0, 0, () => true), false);
await c.gate(5, 0, () => false);
assert.equal(c.now(), 5000); // Cancellation did not reserve a future slot.
});
test("concurrent callers recheck the shared start time after waking", async () => {
let time = 0;
const sleepers = [];
const gate = createFetchDelayGate({
now: () => time,
random: () => 0,
sleep: () => new Promise((resolve) => sleepers.push(resolve)),
});
await gate(1, 0, () => false);
const starts = [];
const a = gate(1, 0, () => false).then(() => starts.push(time));
const b = gate(1, 0, () => false).then(() => starts.push(time));
time = 1000;
sleepers.splice(0).forEach((resolve) => resolve());
await a;
assert.deepEqual(starts, [1000]);
time = 2000;
sleepers.splice(0).forEach((resolve) => resolve());
await b;
assert.deepEqual(starts, [1000, 2000]);
});
+167 -49
View File
@@ -2,17 +2,20 @@ import { useState, useEffect, useRef, useCallback } from "react";
import { TooltipProvider } from "@/components/ui/tooltip";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { ArrowLeft } from "lucide-react";
import { getSettings, applyThemeMode, applyFont } from "@/lib/settings";
import { createFetchDelayGate } from "@/lib/fetch-delay";
import { applyTheme } from "@/lib/themes";
import { openExternal } from "@/lib/utils";
import { compareVersionNumbers } from "@/lib/version";
import { isNewerVersion } from "@/lib/version";
import { toastWithSound as toast } from "@/lib/toast-with-sound";
import { logger } from "@/lib/logger";
import { initDownloadProgressEvents } from "@/lib/download-state";
import { saveFetchState, getFetchState, clearFetchState, getResumableInfo, mergeTimelines, saveCursor, getCursor, clearCursor, type FetchState, } from "@/lib/fetch-state";
import { TitleBar } from "@/components/TitleBar";
import { Sidebar, type PageType } from "@/components/Sidebar";
import { Header } from "@/components/Header";
import { MarkdownLite } from "@/components/MarkdownLite";
import { extractMarkdownSection } from "@/lib/markdown";
import { SearchBar, type FetchMode, type PrivateType, type FetchType, type MultipleAccount } from "@/components/SearchBar";
import { MediaList } from "@/components/MediaList";
import { DatabaseView } from "@/components/DatabaseView";
@@ -26,22 +29,20 @@ 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;
const waitForFetch = createFetchDelayGate();
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 +52,6 @@ async function loadSavedAccountResponse(username: string, mediaType: string): Pr
return null;
}
}
function App() {
const [currentPage, setCurrentPage] = useState<PageType>("main");
const [username, setUsername] = useState("");
@@ -60,6 +60,12 @@ function App() {
const [fetchedMediaType, setFetchedMediaType] = useState<string>("all");
const [hasUpdate, setHasUpdate] = useState(false);
const [releaseDate, setReleaseDate] = useState<string | null>(null);
const [updateInfo, setUpdateInfo] = useState<{
version: string;
changelog: string;
url: string;
} | null>(null);
const [showUpdateDialog, setShowUpdateDialog] = useState(false);
const [fetchHistory, setFetchHistory] = useState<HistoryItem[]>([]);
const [resumeInfo, setResumeInfo] = useState<{
canResume: boolean;
@@ -72,6 +78,7 @@ function App() {
const fetchStartTimeRef = useRef<number | null>(null);
const timeoutIntervalRef = useRef<number | null>(null);
const [fetchType, setFetchType] = useState<FetchType>("single");
const [isResultViewActive, setIsResultViewActive] = useState(false);
const [multipleAccounts, setMultipleAccounts] = useState<MultipleAccount[]>([]);
const [isFetchingAll, setIsFetchingAll] = useState(false);
const [searchMode, setSearchMode] = useState<FetchMode>("public");
@@ -87,6 +94,9 @@ function App() {
const accountMediaCountRef = useRef<Map<string, number>>(new Map());
const accountTimeoutSecondsRef = useRef<Map<string, number>>(new Map());
const dbSaveWarningShownRef = useRef(false);
useEffect(() => {
setIsResultViewActive(result !== null && fetchType === "single");
}, [result, fetchType]);
const reportDatabaseSaveError = (scope: string, error: unknown) => {
console.error(`Failed to save ${scope} to database:`, error);
if (!dbSaveWarningShownRef.current) {
@@ -102,12 +112,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);
@@ -150,21 +168,23 @@ function App() {
useEffect(() => {
const settings = getSettings();
applyThemeMode(settings.themeMode);
applyTheme(settings.theme);
applyTheme(settings.theme, settings.baseColor);
applyFont(settings.fontFamily, settings.customFonts);
const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");
const handleChange = () => {
const currentSettings = getSettings();
if (currentSettings.themeMode === "auto") {
applyThemeMode("auto");
applyTheme(currentSettings.theme);
applyTheme(currentSettings.theme, currentSettings.baseColor);
}
};
mediaQuery.addEventListener("change", handleChange);
const cleanupDownloadProgress = initDownloadProgressEvents();
checkForUpdates();
loadHistory();
return () => {
mediaQuery.removeEventListener("change", handleChange);
cleanupDownloadProgress();
};
}, []);
useEffect(() => {
@@ -193,7 +213,6 @@ function App() {
openExternal(url.toString());
}
catch {
// Ignore invalid URLs and allow the browser/webview to handle them.
}
};
document.addEventListener("click", handleDocumentClick);
@@ -204,13 +223,27 @@ function App() {
const checkForUpdates = async () => {
try {
const response = await fetch("https://api.github.com/repos/afkarxyz/Twitter-X-Media-Batch-Downloader/releases/latest");
if (!response.ok) {
throw new Error(`GitHub release request failed: ${response.status}`);
}
const data = await response.json();
const latestVersion = data.tag_name?.replace(/^v/, "") || "";
const rawTag = typeof data.tag_name === "string" ? data.tag_name : "";
const latestVersion = rawTag.replace(/^v/, "");
if (data.published_at) {
setReleaseDate(data.published_at);
}
if (latestVersion && compareVersionNumbers(latestVersion, CURRENT_VERSION) > 0) {
if (latestVersion && isNewerVersion(latestVersion, CURRENT_VERSION)) {
setHasUpdate(true);
setUpdateInfo({
version: latestVersion,
changelog: extractMarkdownSection(typeof data.body === "string" ? data.body : "", "Changelog"),
url: typeof data.html_url === "string" && data.html_url
? data.html_url
: `https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases/tag/${encodeURIComponent(rawTag)}`,
});
if (getSettings().showUpdateNotifications) {
setShowUpdateDialog(true);
}
}
}
catch (err) {
@@ -415,6 +448,7 @@ function App() {
return;
}
}
if (!await waitForFetch(settings.fetchDelaySeconds, settings.fetchDelayJitterSeconds, () => stopFetchRef.current)) return;
const response = await ExtractDateRange({
username: username.trim(),
auth_token: authToken.trim(),
@@ -434,10 +468,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 ? "tweets" : "media";
if (isBookmarks) {
timelineType = "bookmarks";
}
@@ -446,6 +478,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 +525,8 @@ function App() {
}
}
const batchNum = page + 1;
logger.info(isSingleMode ? "Fetching all media..." : `Fetching batch ${batchNum}${cursor ? " (resuming)" : ""}...`);
if (!await waitForFetch(settings.fetchDelaySeconds, settings.fetchDelayJitterSeconds, () => stopFetchRef.current)) break;
logger.info(`Fetching batch ${batchNum}${cursor ? " (resuming)" : ""}...`);
const response = await ExtractTimeline({
username: isBookmarks ? "" : username.trim(),
auth_token: authToken.trim(),
@@ -502,6 +536,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 +564,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 +627,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`);
@@ -695,13 +743,20 @@ function App() {
toast.error("Failed to parse saved data");
}
};
const handleBackToHomeResult = () => {
setCurrentPage("main");
setResult(null);
setNewMediaCount(null);
const scrollContentToTop = () => {
const scrollElement = document.getElementById("app-content-scroll");
scrollElement?.scrollTo({ top: 0, behavior: "smooth" });
};
const handleResultBack = () => {
setIsResultViewActive(false);
scrollContentToTop();
};
const handleResultForward = () => {
if (result && fetchType === "single") {
setIsResultViewActive(true);
scrollContentToTop();
}
};
const parseUsername = (input: string): string => {
let clean = input.trim();
if (clean.startsWith("@")) {
@@ -808,7 +863,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 +937,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)) {
@@ -927,23 +981,39 @@ function App() {
}
break;
}
if (!await waitForFetch(settings.fetchDelaySeconds, settings.fetchDelayJitterSeconds, () => stopAllRef.current || !!accountStopFlagsRef.current.get(accountId))) break;
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 +1067,7 @@ function App() {
},
cursor: cursor,
completed: !hasMore,
}), selectedMediaType, cursor || "", !hasMore);
}), selectedMediaType, cursor || "", !hasMore);
}
catch (err) {
reportDatabaseSaveError("multi-account progress", err);
@@ -1123,7 +1193,7 @@ function App() {
}
const savedSettings = getSettings();
applyThemeMode(savedSettings.themeMode);
applyTheme(savedSettings.theme);
applyTheme(savedSettings.theme, savedSettings.baseColor);
applyFont(savedSettings.fontFamily, savedSettings.customFonts);
setHasUnsavedSettings(false);
if (pendingPageChange) {
@@ -1144,10 +1214,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 +1226,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 +1241,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,27 +1336,44 @@ function App() {
try {
let hasMore = true;
let page = 0;
const seenCursors = new Set<string>();
while (hasMore && !stopAllRef.current) {
if (accountStopFlagsRef.current.get(accountId)) {
break;
}
if (!await waitForFetch(settings.fetchDelaySeconds, settings.fetchDelayJitterSeconds, () => stopAllRef.current || !!accountStopFlagsRef.current.get(accountId))) break;
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);
@@ -1420,6 +1512,7 @@ function App() {
}
};
const renderPage = () => {
const showSingleResult = isResultViewActive && result !== null && fetchType === "single";
switch (currentPage) {
case "settings":
return <SettingsPage onUnsavedChangesChange={setHasUnsavedSettings} onResetRequest={setResetSettingsFn}/>;
@@ -1433,39 +1526,64 @@ 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={showSingleResult} 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);
}
}}/>
{result && fetchType === "single" && (<div className="mt-4 space-y-3">
<div className="flex justify-start">
<Button variant="outline" onClick={handleBackToHomeResult} className="flex items-center gap-2">
<ArrowLeft className="h-4 w-4"/>
Back to Home
</Button>
</div>
{showSingleResult && result && (<div className="mt-4 space-y-3">
<MediaList accountInfo={result.account_info} timeline={result.timeline} totalUrls={result.total_urls} fetchedMediaType={fetchedMediaType} newMediaCount={newMediaCount}/>
</div>)}
</>);
}
};
const hasNavigableResult = result !== null && fetchType === "single";
const usesWideContent = currentPage === "main"
? fetchType === "multiple" || (hasNavigableResult && isResultViewActive)
: !["settings", "support"].includes(currentPage);
return (<TooltipProvider>
<div className="h-screen overflow-hidden bg-background">
<DependencySetupDialog />
<TitleBar />
<TitleBar canGoBack={currentPage === "main" && hasNavigableResult && isResultViewActive} canGoForward={currentPage === "main" && hasNavigableResult && !isResultViewActive} navigationDisabled={loading} onBack={handleResultBack} onForward={handleResultForward}/>
<Sidebar currentPage={currentPage} onPageChange={handlePageChange}/>
<div id="app-content-scroll" className="fixed top-10 right-0 bottom-0 left-14 overflow-y-auto overflow-x-hidden">
<div className="p-4 md:p-8">
<div className="max-w-5xl mx-auto">
<div className={usesWideContent ? "w-full" : "max-w-5xl mx-auto"}>
{renderPage()}
</div>
</div>
</div>
<Dialog open={showUpdateDialog} onOpenChange={setShowUpdateDialog}>
<DialogContent className="sm:max-w-125 [&>button]:hidden">
<DialogHeader>
<DialogTitle>Update Available</DialogTitle>
<DialogDescription>
A new version (v{updateInfo?.version || ""}) is available. You're on v{CURRENT_VERSION}
</DialogDescription>
</DialogHeader>
{updateInfo?.changelog ? (<div className="custom-scrollbar max-h-72 overflow-y-auto rounded-md border bg-muted/40 p-3">
<MarkdownLite content={updateInfo.changelog}/>
</div>) : (<p className="text-sm text-muted-foreground">No changelog was provided for this release.</p>)}
<DialogFooter className="gap-2">
<Button variant="outline" onClick={() => setShowUpdateDialog(false)}>
Download Later
</Button>
<Button onClick={() => {
if (updateInfo) {
openExternal(updateInfo.url);
}
setShowUpdateDialog(false);
}}>
Download Now
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
<Dialog open={showUnsavedChangesDialog} onOpenChange={(open) => {
if (open) {
setShowUnsavedChangesDialog(true);
Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

+232 -147
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,8 +82,15 @@ 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 [isBulkGroupEditing, setIsBulkGroupEditing] = useState(false);
const [editGroupName, setEditGroupName] = useState("");
const [editGroupColor, setEditGroupColor] = useState("");
const [clearAllDialogOpen, setClearAllDialogOpen] = useState(false);
@@ -230,11 +235,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 +246,6 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
if (!active) {
return;
}
setFolderExistence((prev) => {
const next = new Map(prev);
for (const account of visibleAccounts) {
@@ -256,7 +258,6 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
console.error("Failed to check visible folders:", error);
}
};
void loadVisibleFolderExistence();
return () => {
active = false;
@@ -277,18 +278,53 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
};
}, [filteredAccounts.length, visibleCount, loading]);
const handleEditGroup = (account: AccountListItem) => {
setIsBulkGroupEditing(false);
setEditingAccount(account);
setEditGroupName(account.group_name || "");
setEditGroupColor(account.group_color || "#3b82f6");
};
const closeGroupEditor = () => {
setEditingAccount(null);
setIsBulkGroupEditing(false);
};
const handleBulkEditGroup = () => {
const selectedAccounts = accounts.filter((account) => selectedIds.has(account.id) && !isPrivateAccount(account.username));
if (selectedAccounts.length === 0) {
toast.error("No public accounts selected");
return;
}
const firstAccount = selectedAccounts[0];
const hasSharedGroup = selectedAccounts.every((account) => account.group_name === firstAccount.group_name && account.group_color === firstAccount.group_color);
setEditingAccount(null);
setEditGroupName(hasSharedGroup ? firstAccount.group_name || "" : "");
setEditGroupColor(hasSharedGroup ? firstAccount.group_color || "#3b82f6" : "#3b82f6");
setIsBulkGroupEditing(true);
};
const handleSaveGroup = async () => {
if (!editingAccount)
const targetAccounts = isBulkGroupEditing
? accounts.filter((account) => selectedIds.has(account.id) && !isPrivateAccount(account.username))
: editingAccount ? [editingAccount] : [];
if (targetAccounts.length === 0)
return;
try {
await UpdateAccountGroup(editingAccount.id, editGroupName, editGroupColor);
toast.success(`Updated group for @${editingAccount.username}`);
setEditingAccount(null);
await loadAccounts();
for (const account of targetAccounts) {
await UpdateAccountGroup(account.id, editGroupName, editGroupColor);
}
const targetIds = new Set(targetAccounts.map((account) => account.id));
setAccounts((currentAccounts) => currentAccounts.map((account) => targetIds.has(account.id)
? { ...account, group_name: editGroupName, group_color: editGroupColor }
: account));
toast.success(isBulkGroupEditing
? `Updated group for ${formatNumberWithComma(targetAccounts.length)} accounts`
: `Updated group for @${targetAccounts[0].username}`);
closeGroupEditor();
try {
const groupsData = await GetAllGroups();
setGroups((groupsData || []).map((group) => ({ name: group.name || "", color: group.color || "" })));
}
catch (error) {
console.error("Failed to refresh groups:", error);
}
}
catch (error) {
console.error("Failed to update group:", error);
@@ -316,17 +352,24 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
toast.error("Failed to load account data");
}
};
const handleOpenFolder = async (username: string) => {
const handleOpenFolder = async (account: AccountListItem) => {
const settings = getSettings();
let folderName = username;
if (username === "bookmarks") {
folderName = "My Bookmarks";
const basePath = settings.downloadPath || "";
if (!basePath) {
toast.error("Download folder is not set");
return;
}
else if (username === "likes") {
folderName = "My Likes";
}
const folderPath = await GetFolderPath(settings.downloadPath, folderName);
let username = account.username || account.name || "";
try {
const responseJSON = await GetAccountFromDB(account.id);
const data = JSON.parse(responseJSON);
username = data.account_info?.name || username;
}
catch {
}
const folderName = getFolderNameForAccount(username);
try {
const folderPath = await GetFolderPath(basePath, folderName);
await OpenFolder(folderPath);
}
catch (error) {
@@ -381,7 +424,12 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
skip_existing: settings.skipExistingFiles,
delete_incomplete_files: settings.deleteIncompleteFiles,
retry_attempts: settings.retryAttempts,
download_speed_limit_kbps: settings.downloadSpeedLimitKBps,
download_delay_ms: Math.round(settings.downloadDelaySeconds * 1000),
download_delay_jitter_ms: Math.round(settings.downloadDelayJitterSeconds * 1000),
proxy: settings.proxy || "",
filename_template: settings.filenameTemplate || "",
folder_template: settings.folderTemplate || "",
});
const response = await DownloadMediaWithMetadata(request);
if (response.cancelled) {
@@ -504,7 +552,12 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
skip_existing: settings.skipExistingFiles,
delete_incomplete_files: settings.deleteIncompleteFiles,
retry_attempts: settings.retryAttempts,
download_speed_limit_kbps: settings.downloadSpeedLimitKBps,
download_delay_ms: Math.round(settings.downloadDelaySeconds * 1000),
download_delay_jitter_ms: Math.round(settings.downloadDelayJitterSeconds * 1000),
proxy: settings.proxy || "",
filename_template: settings.filenameTemplate || "",
folder_template: settings.folderTemplate || "",
});
const response = await DownloadMediaWithMetadata(request);
if (response.cancelled) {
@@ -628,105 +681,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();
}
};
@@ -783,6 +837,14 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
<Tooltip>
<TooltipTrigger asChild>
<Button variant="outline" size="icon" onClick={handleBulkEditGroup} disabled={selectedIds.size === 0 || hasPrivateAccountSelected()}>
<Tag className="h-4 w-4"/>
</Button>
</TooltipTrigger>
<TooltipContent>Edit Group for Selected ({formatNumberWithComma(selectedIds.size)})</TooltipContent>
</Tooltip>
<Tooltip>
<TooltipTrigger asChild>
<Button variant="outline" size="icon" onClick={() => {
@@ -1014,9 +1076,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 size-5 cursor-pointer after:absolute after:-inset-2 after:content-['']" aria-label={`Select @${account.username}`}/>
<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 +1093,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">
@@ -1043,13 +1110,13 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
{formatNumberWithComma(account.total_media)} media
</div>
</div>
<div className="flex gap-1">
<div className="flex gap-1" onClick={(e) => e.stopPropagation()}>
{downloadingAccountId === account.id ? (<Button variant="outline" size="icon" className="h-8 w-8" onClick={handleStopDownload}>
<StopCircle className="h-4 w-4 text-destructive"/>
</Button>) : (<Button variant="default" size="icon" className="h-8 w-8" onClick={() => handleDownload(account.id, account.username)} disabled={isDownloading}>
<Download className="h-4 w-4"/>
</Button>)}
<Button variant="outline" size="icon" className="h-8 w-8" onClick={() => handleOpenFolder(account.username)} disabled={!folderExistence.get(account.id)}>
<Button variant="outline" size="icon" className="h-8 w-8" onClick={() => handleOpenFolder(account)} disabled={!folderExistence.get(account.id)}>
<FolderOpen className="h-4 w-4"/>
</Button>
<DropdownMenu>
@@ -1059,7 +1126,10 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
{!isPrivateAccount(account.username) && (<DropdownMenuItem onClick={() => handleEditGroup(account)}>
{!isPrivateAccount(account.username) && (<DropdownMenuItem onSelect={(event) => {
event.preventDefault();
handleEditGroup(account);
}}>
<Pencil className="h-4 w-4 mr-2"/>
Edit Group
</DropdownMenuItem>)}
@@ -1103,9 +1173,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 size-5 cursor-pointer after:absolute after:-inset-2 after:content-['']" aria-label={`Select @${account.username}`}/>
<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 +1190,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">
@@ -1132,13 +1207,13 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
{formatNumberWithComma(account.total_media)} media
</div>
</div>
<div className="flex gap-1">
<div className="flex gap-1" onClick={(e) => e.stopPropagation()}>
{downloadingAccountId === account.id ? (<Button variant="outline" size="icon" className="h-7 w-7" onClick={handleStopDownload}>
<StopCircle className="h-3 w-3 text-destructive"/>
</Button>) : (<Button variant="default" size="icon" className="h-7 w-7" onClick={() => handleDownload(account.id, account.username)} disabled={isDownloading}>
<Download className="h-3 w-3"/>
</Button>)}
<Button variant="outline" size="icon" className="h-7 w-7" onClick={() => handleOpenFolder(account.username)} disabled={!folderExistence.get(account.id)}>
<Button variant="outline" size="icon" className="h-7 w-7" onClick={() => handleOpenFolder(account)} disabled={!folderExistence.get(account.id)}>
<FolderOpen className="h-3 w-3"/>
</Button>
<DropdownMenu>
@@ -1148,7 +1223,10 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
{!isPrivateAccount(account.username) && (<DropdownMenuItem onClick={() => handleEditGroup(account)}>
{!isPrivateAccount(account.username) && (<DropdownMenuItem onSelect={(event) => {
event.preventDefault();
handleEditGroup(account);
}}>
<Pencil className="h-4 w-4 mr-2"/>
Edit Group
</DropdownMenuItem>)}
@@ -1192,14 +1270,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()} className="relative size-5 cursor-pointer after:absolute after:-inset-2 after:content-['']" aria-label={`Select @${account.username}`}/>
<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>
@@ -1241,7 +1321,7 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
{account.last_fetched} {getRelativeTime(account.last_fetched)}
</div>
</div>
<div className="flex items-center gap-2">
<div className="flex items-center gap-2" onClick={(e) => e.stopPropagation()}>
{downloadingAccountId === account.id ? (<Tooltip>
<TooltipTrigger asChild>
<Button variant="outline" size="icon" onClick={handleStopDownload}>
@@ -1259,7 +1339,7 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
</Tooltip>)}
<Tooltip>
<TooltipTrigger asChild>
<Button variant="outline" size="icon" onClick={() => handleOpenFolder(account.username)} disabled={!folderExistence.get(account.id)}>
<Button variant="outline" size="icon" onClick={() => handleOpenFolder(account)} disabled={!folderExistence.get(account.id)}>
<FolderOpen className="h-4 w-4"/>
</Button>
</TooltipTrigger>
@@ -1277,7 +1357,10 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
<TooltipContent>More Options</TooltipContent>
</Tooltip>
<DropdownMenuContent align="end">
{!isPrivateAccount(account.username) && (<DropdownMenuItem onClick={() => handleEditGroup(account)}>
{!isPrivateAccount(account.username) && (<DropdownMenuItem onSelect={(event) => {
event.preventDefault();
handleEditGroup(account);
}}>
<Pencil className="h-4 w-4 mr-2"/>
Edit Group
</DropdownMenuItem>)}
@@ -1354,17 +1437,19 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
</Button>)}
<Dialog open={!!editingAccount} onOpenChange={(open) => !open && setEditingAccount(null)}>
<Dialog open={isBulkGroupEditing || !!editingAccount} onOpenChange={(open) => !open && closeGroupEditor()}>
<DialogContent className="[&>button]:hidden">
<div className="absolute right-4 top-4">
<Button variant="ghost" size="icon" className="h-6 w-6 opacity-70 hover:opacity-100" onClick={() => setEditingAccount(null)}>
<Button variant="ghost" size="icon" className="h-6 w-6 opacity-70 hover:opacity-100" onClick={closeGroupEditor}>
<X className="h-4 w-4"/>
</Button>
</div>
<DialogHeader>
<DialogTitle>Edit Group for @{editingAccount?.username}</DialogTitle>
<DialogTitle>{isBulkGroupEditing
? `Edit Group for ${formatNumberWithComma(selectedIds.size)} Selected Accounts`
: `Edit Group for @${editingAccount?.username}`}</DialogTitle>
<DialogDescription>
Assign this account to a group for better organization.
Assign {isBulkGroupEditing ? "these accounts" : "this account"} to a group for better organization.
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-4">
@@ -1426,7 +1511,7 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setEditingAccount(null)}>
<Button variant="outline" onClick={closeGroupEditor}>
Cancel
</Button>
<Button onClick={handleSaveGroup}>
+34 -4
View File
@@ -1,7 +1,9 @@
import { useState, useEffect, useRef } from "react";
import { Trash2, Copy, Check } from "lucide-react";
import { Trash2, Copy, CircleCheck, FileDown } from "lucide-react";
import { Button } from "@/components/ui/button";
import { logger, type LogEntry } from "@/lib/logger";
import { ExportFailedLogs } from "../../wailsjs/go/main/App";
import { toastWithSound as toast } from "@/lib/toast-with-sound";
const levelColors: Record<string, string> = {
info: "text-blue-500",
success: "text-green-500",
@@ -21,6 +23,7 @@ export function DebugLoggerPage() {
const [logs, setLogs] = useState<LogEntry[]>(() => logger.getLogs());
const [copied, setCopied] = useState(false);
const scrollRef = useRef<HTMLDivElement>(null);
const failedLogs = logs.filter((log) => log.level === "error");
useEffect(() => {
const unsubscribe = logger.subscribe(() => {
setLogs(logger.getLogs());
@@ -50,22 +53,49 @@ export function DebugLoggerPage() {
console.error("Failed to copy logs:", err);
}
};
const handleExportFailed = async () => {
if (failedLogs.length === 0) {
toast.info("No failed logs to export");
return;
}
const lines = [
`Failed Logs Report - ${new Date().toLocaleString()}`,
"-".repeat(50),
"",
...failedLogs.map((log) => `[${formatTime(log.timestamp)}] [${log.level}] ${log.message}`),
"",
];
try {
const path = await ExportFailedLogs(lines.join("\n"));
if (path) {
toast.success(`Exported ${failedLogs.length} failed log${failedLogs.length === 1 ? "" : "s"}`);
}
}
catch (error) {
console.error("Failed to export logs:", error);
toast.error(`Failed to export logs: ${error}`);
}
};
return (<div className="space-y-6">
<div className="flex items-center justify-between">
<h1 className="text-2xl font-bold">Debug Logs</h1>
<div className="flex items-center gap-2">
<Button variant="outline" size="sm" onClick={handleExportFailed} className="gap-1.5">
<FileDown className="h-4 w-4"/>
Export Failed
</Button>
<Button variant="outline" size="sm" onClick={handleCopy} disabled={logs.length === 0} className="gap-1.5">
{copied ? <Check className="h-4 w-4"/> : <Copy className="h-4 w-4"/>}
{copied ? <CircleCheck className="h-4 w-4"/> : <Copy className="h-4 w-4"/>}
Copy
</Button>
<Button variant="outline" size="sm" onClick={handleClear} className="gap-1.5">
<Button variant="destructive" size="sm" onClick={handleClear} disabled={logs.length === 0} className="gap-1.5">
<Trash2 className="h-4 w-4"/>
Clear
</Button>
</div>
</div>
<div ref={scrollRef} className="h-[calc(100vh-220px)] overflow-y-auto bg-muted/50 rounded-md p-3 font-mono text-xs">
<div ref={scrollRef} className="h-[calc(100vh-220px)] overflow-y-auto rounded-lg bg-muted/50 p-4 font-mono text-xs">
{logs.length === 0 ? (<p className="text-muted-foreground lowercase">no logs yet...</p>) : (logs.map((log, i) => (<div key={i} className="flex gap-2 py-0.5">
<span className="text-muted-foreground shrink-0">
[{formatTime(log.timestamp)}]
@@ -4,36 +4,40 @@ import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from "@/components/ui/dialog";
import { Spinner } from "@/components/ui/spinner";
import { toastWithSound as toast } from "@/lib/toast-with-sound";
import { compareVersionNumbers } from "@/lib/version";
import { Quit } from "../../wailsjs/runtime/runtime";
import { DownloadExtractor, IsExtractorInstalled } from "../../wailsjs/go/main/App";
import { DownloadExtractor, GetExtractorVersionStatus } from "../../wailsjs/go/main/App";
interface DependencySetupDialogProps {
onInstalled?: () => void;
}
interface GithubReleaseResponse {
tag_name?: string;
interface ExtractorVersionStatus {
installed: boolean;
installed_version?: string;
latest_version?: string;
}
const extractorReleaseAPIURL = "https://api.github.com/repos/afkarxyz/xtractor-binaries/releases/latest";
export function DependencySetupDialog({ onInstalled }: DependencySetupDialogProps) {
const [open, setOpen] = useState(false);
const [checking, setChecking] = useState(true);
const [downloading, setDownloading] = useState(false);
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const [updateRequired, setUpdateRequired] = useState(false);
const [installedVersion, setInstalledVersion] = useState<string | null>(null);
const [releaseVersion, setReleaseVersion] = useState<string | null>(null);
const [releaseStatusMessage, setReleaseStatusMessage] = useState("Checking latest GitHub release...");
useEffect(() => {
let cancelled = false;
const abortController = new AbortController();
const checkDependency = async () => {
try {
const installed = await IsExtractorInstalled();
const status = await GetExtractorVersionStatus() as ExtractorVersionStatus;
const nextInstalledVersion = status.installed_version?.trim() || null;
const nextLatestVersion = status.latest_version?.trim() || null;
const nextUpdateRequired = !!(status.installed && nextLatestVersion && (!nextInstalledVersion || compareVersionNumbers(nextLatestVersion, nextInstalledVersion) > 0));
if (!cancelled) {
setOpen(!installed);
setUpdateRequired(nextUpdateRequired);
setInstalledVersion(nextInstalledVersion);
setReleaseVersion(nextLatestVersion);
setReleaseStatusMessage(nextLatestVersion ? `Latest GitHub release: ${nextLatestVersion}` : "Latest GitHub release unavailable.");
setOpen(!status.installed || nextUpdateRequired);
setErrorMessage(null);
}
}
@@ -49,56 +53,18 @@ export function DependencySetupDialog({ onInstalled }: DependencySetupDialogProp
}
}
};
const loadReleaseInfo = async () => {
try {
const response = await fetch(extractorReleaseAPIURL, {
headers: {
Accept: "application/vnd.github+json",
},
signal: abortController.signal,
});
if (!response.ok) {
throw new Error(`GitHub release status ${response.status}`);
}
const release = (await response.json()) as GithubReleaseResponse;
const version = release.tag_name?.trim();
if (!version) {
throw new Error("Missing GitHub release tag");
}
if (!cancelled) {
setReleaseVersion(version);
setReleaseStatusMessage(`Latest GitHub release: ${version}`);
}
}
catch {
if (!cancelled && !abortController.signal.aborted) {
setReleaseVersion(null);
setReleaseStatusMessage("Latest GitHub release unavailable.");
}
}
};
void checkDependency();
void loadReleaseInfo();
return () => {
cancelled = true;
abortController.abort();
};
}, []);
const handleDownload = async () => {
setDownloading(true);
setErrorMessage(null);
try {
await DownloadExtractor();
setOpen(false);
toast.success("Xtractor installed");
toast.success(updateRequired ? "Xtractor updated" : "Xtractor installed");
onInstalled?.();
}
catch (error) {
@@ -110,17 +76,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);
@@ -131,11 +94,16 @@ export function DependencySetupDialog({ onInstalled }: DependencySetupDialogProp
<div className="mb-2 flex h-12 w-12 items-center justify-center rounded-2xl border bg-muted/50">
<Package className="h-6 w-6"/>
</div>
<DialogTitle>Download Xtractor</DialogTitle>
<DialogDescription>Xtractor is required before you can use this app.</DialogDescription>
<DialogTitle>{updateRequired ? "Update Xtractor" : "Download Xtractor"}</DialogTitle>
<DialogDescription>
{updateRequired ? "A newer Xtractor binary is available or the installed version could not be verified." : "Xtractor is required before you can use this app."}
</DialogDescription>
</DialogHeader>
<div className="space-y-3">
{updateRequired && releaseVersion && (<p className="text-sm text-amber-600 dark:text-amber-400">
Installed: {installedVersion || "unknown"} - Latest: {releaseVersion}
</p>)}
<p className="text-sm text-muted-foreground">{releaseVersion ? `Latest GitHub release: ${releaseVersion}` : releaseStatusMessage}</p>
{errorMessage && (<div className="flex items-start gap-2 rounded-lg border border-destructive/40 bg-destructive/10 p-3 text-sm text-destructive">
@@ -151,10 +119,10 @@ export function DependencySetupDialog({ onInstalled }: DependencySetupDialogProp
<Button onClick={handleDownload} disabled={downloading}>
{downloading ? (<>
<Spinner />
Downloading Xtractor...
{updateRequired ? "Updating Xtractor..." : "Downloading Xtractor..."}
</>) : (<>
<Download className="h-4 w-4"/>
Download Xtractor
{updateRequired ? "Update Xtractor" : "Download Xtractor"}
</>)}
</Button>
</DialogFooter>
+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>);
}
+75
View File
@@ -0,0 +1,75 @@
import { Fragment, type ReactNode } from "react";
import { openExternal } from "@/lib/utils";
function renderInline(text: string, keyPrefix: string): ReactNode[] {
const nodes: ReactNode[] = [];
const pattern = /\[([^\]]+)\]\(([^)]+)\)|\*\*([^*]+)\*\*|\*([^*]+)\*|`([^`]+)`/g;
let lastIndex = 0;
let match: RegExpExecArray | null;
let index = 0;
while ((match = pattern.exec(text)) !== null) {
if (match.index > lastIndex) {
nodes.push(<Fragment key={`${keyPrefix}-t${index}`}>{text.slice(lastIndex, match.index)}</Fragment>);
}
if (match[1] !== undefined && match[2] !== undefined) {
const label = match[1];
const url = match[2];
nodes.push(<button key={`${keyPrefix}-l${index}`} type="button" onClick={() => openExternal(url)} className="cursor-pointer border-none bg-transparent p-0 text-primary underline hover:opacity-80">
{label}
</button>);
}
else if (match[3] !== undefined) {
nodes.push(<strong key={`${keyPrefix}-b${index}`} className="font-semibold text-foreground">{match[3]}</strong>);
}
else if (match[4] !== undefined) {
nodes.push(<em key={`${keyPrefix}-i${index}`}>{match[4]}</em>);
}
else if (match[5] !== undefined) {
nodes.push(<code key={`${keyPrefix}-c${index}`} className="rounded bg-muted px-1 py-0.5 font-mono text-xs">{match[5]}</code>);
}
lastIndex = pattern.lastIndex;
index++;
}
if (lastIndex < text.length) {
nodes.push(<Fragment key={`${keyPrefix}-t${index}`}>{text.slice(lastIndex)}</Fragment>);
}
return nodes;
}
export function MarkdownLite({ content }: {
content: string;
}) {
const lines = (content || "").replace(/\r\n/g, "\n").split("\n");
const blocks: ReactNode[] = [];
let listItems: string[] = [];
let key = 0;
const flushList = () => {
if (listItems.length === 0)
return;
const items = listItems;
listItems = [];
blocks.push(<ul key={`ul-${key++}`} className="list-disc space-y-1 pl-5">
{items.map((item, index) => (<li key={index}>{renderInline(item, `li-${key}-${index}`)}</li>))}
</ul>);
};
for (const raw of lines) {
const line = raw.trimEnd();
const bullet = line.match(/^\s*[-*]\s+(.*)$/);
if (bullet) {
listItems.push(bullet[1]);
continue;
}
flushList();
const heading = line.match(/^(#{1,6})\s+(.*)$/);
if (heading) {
blocks.push(<p key={`h-${key++}`} className="font-semibold text-foreground">
{renderInline(heading[2], `h-${key}`)}
</p>);
continue;
}
if (line.trim() === "") {
continue;
}
blocks.push(<p key={`p-${key++}`}>{renderInline(line, `p-${key}`)}</p>);
}
flushList();
return <div className="space-y-2 text-sm text-muted-foreground">{blocks}</div>;
}
+253 -356
View File
@@ -5,27 +5,17 @@ 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 { getCachedDependencyStatus, getCachedMediaFolderStatus, setCachedDependencyStatus, setCachedMediaFolderStatus } from "@/lib/runtime-cache";
import { getSettings, renderFolderTemplate } from "@/lib/settings";
import { beginDownload, finishDownload, setDownloadItemStatus, useDownloadState } from "@/lib/download-state";
import { getCachedMediaFolderStatus, setCachedMediaFolderStatus } from "@/lib/runtime-cache";
import { openExternal } from "@/lib/utils";
import { DownloadMediaWithMetadata, OpenFolder, IsFFmpegInstalled, ConvertGIFs, StopDownload, CheckFolderExists, CheckGifsFolderHasMP4 } from "../../wailsjs/go/main/App";
import { EventsOn } from "../../wailsjs/runtime/runtime";
import { DownloadMediaWithMetadata, DownloadProfileImage, OpenFolder, StopDownload, CheckFolderExists } from "../../wailsjs/go/main/App";
import { main } from "../../wailsjs/go/models";
interface DownloadProgress {
current: number;
total: number;
percent: number;
}
interface DownloadItemStatus {
tweet_id: number;
index: number;
status: "success" | "failed" | "skipped";
}
interface MediaListProps {
accountInfo: AccountInfo;
timeline: TimelineEntry[];
@@ -34,11 +24,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 +66,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 +89,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 +166,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,32 +173,53 @@ 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,
accountName: accountInfo.nick,
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);
const downloadState = useDownloadState();
const anyDownloadActive = downloadState.active;
const isDownloading = downloadState.active && downloadState.scope === "media";
const downloadProgress = isDownloading ? downloadState.progress : null;
const downloadingItem = isDownloading ? downloadState.currentItemKey : null;
const itemStatusByKey = downloadState.itemStatusByKey;
const cachedMediaFolderStatus = settings.downloadPath
? getCachedMediaFolderStatus(settings.downloadPath, folderName)
: null;
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 [isDownloading, setIsDownloading] = useState(false);
const [downloadProgress, setDownloadProgress] = useState<DownloadProgress | null>(null);
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 [hasDownloaded, setHasDownloaded] = useState(false);
const [isConverting, setIsConverting] = useState(false);
const [ffmpegInstalled, setFfmpegInstalled] = useState(() => getCachedDependencyStatus("ffmpeg").installed ?? false);
const [showScrollTop, setShowScrollTop] = useState(false);
const [folderExists, setFolderExists] = useState(cachedMediaFolderStatus?.folderExists ?? false);
const [gifsFolderHasMP4, setGifsFolderHasMP4] = useState(cachedMediaFolderStatus?.gifsFolderHasMP4 ?? false);
const [previewIndex, setPreviewIndex] = useState<number | null>(null);
const [downloadedItems, setDownloadedItems] = useState<Set<string>>(new Set());
const [failedItems, setFailedItems] = useState<Set<string>>(new Set());
const [skippedItems, setSkippedItems] = useState<Set<string>>(new Set());
const [downloadingItem, setDownloadingItem] = useState<string | null>(null);
const [visibleCount, setVisibleCount] = useState<number>(MEDIA_LIST_PAGE_SIZE);
const loadMoreRef = useRef<HTMLDivElement>(null);
useEffect(() => {
@@ -252,24 +270,19 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
setVisibleCount(MEDIA_LIST_PAGE_SIZE);
}, [filteredTimeline.length]);
useEffect(() => {
const checkFoldersAndFFmpeg = async () => {
const checkFolders = async () => {
const settings = getSettings();
const basePath = settings.downloadPath;
const installed = await IsFFmpegInstalled();
setCachedDependencyStatus("ffmpeg", { installed });
setFfmpegInstalled(installed);
if (!basePath || !accountInfo.name)
return;
const exists = await CheckFolderExists(basePath, folderName);
const hasMP4 = exists ? await CheckGifsFolderHasMP4(basePath, folderName) : false;
setCachedMediaFolderStatus(basePath, folderName, {
folderExists: exists,
gifsFolderHasMP4: hasMP4,
gifsFolderHasMP4: false,
});
setFolderExists(exists);
setGifsFolderHasMP4(hasMP4);
};
checkFoldersAndFFmpeg();
checkFolders();
}, [accountInfo.name, accountInfo.nick, folderName, hasDownloaded]);
useEffect(() => {
const sentinel = loadMoreRef.current;
@@ -310,58 +323,6 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
document.body.style.overflow = previousOverflow;
};
}, [previewIndex]);
useEffect(() => {
const unsubscribe = EventsOn("download-progress", (progress: DownloadProgress) => {
setDownloadProgress(progress);
});
return () => {
unsubscribe();
};
}, []);
const currentDownloadingItemKeyRef = useRef<string | null>(null);
const bulkDownloadKeyMapRef = useRef<Map<number, string>>(new Map());
useEffect(() => {
const unsubscribe = EventsOn("download-item-status", (status: DownloadItemStatus) => {
const currentKey = currentDownloadingItemKeyRef.current;
const keyMap = bulkDownloadKeyMapRef.current;
let itemKey: string;
if (currentKey) {
itemKey = currentKey;
}
else if (keyMap.size > 0) {
itemKey = keyMap.get(status.index) ?? `${String(status.tweet_id)}-${status.index}`;
}
else {
itemKey = `${String(status.tweet_id)}-${status.index}`;
}
if (status.status === "success") {
setDownloadedItems((prev) => new Set(prev).add(itemKey));
if (currentKey) {
toast.success("Downloaded");
}
}
else if (status.status === "failed") {
setFailedItems((prev) => new Set(prev).add(itemKey));
if (currentKey) {
toast.error("Download failed");
}
}
else if (status.status === "skipped") {
setDownloadedItems((prev) => {
const newSet = new Set(prev);
newSet.delete(itemKey);
return newSet;
});
setSkippedItems((prev) => new Set(prev).add(itemKey));
if (currentKey) {
toast.info("Already exists");
}
}
});
return () => {
unsubscribe();
};
}, []);
const goToPrevious = () => {
if (previewIndex !== null && previewIndex > 0) {
setPreviewIndex(previewIndex - 1);
@@ -429,6 +390,76 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
}
return settings.downloadPath;
};
const createMediaItemRequest = (item: TimelineEntry) => new main.MediaItemRequest({
url: item.url,
date: item.date,
tweet_id: item.tweet_id,
type: item.type,
content: item.content || "",
original_filename: item.original_filename || "",
author_username: item.author_username || "",
account_name: item.author_name || accountInfo.nick || accountInfo.name,
});
const getItemStatusFlags = (itemKey: string) => {
const status = itemStatusByKey[itemKey];
return {
isItemDownloaded: status === "success",
isItemFailed: status === "failed",
isItemSkipped: status === "skipped",
isItemDownloading: downloadingItem === itemKey,
};
};
const handleDownloadItem = async (item: TimelineEntry, itemKey: string) => {
beginDownload({ current: 0, total: 1, percent: 0 }, { scope: "media", currentItemKey: itemKey, itemKeyByIndex: { 0: itemKey } });
try {
const settings = getSettings();
const request = new main.DownloadMediaWithMetadataRequest({
items: [createMediaItemRequest(item)],
output_dir: getOutputDir(),
username: accountInfo.name,
concurrent_downloads: settings.concurrentDownloads || 10,
skip_existing: settings.skipExistingFiles,
delete_incomplete_files: settings.deleteIncompleteFiles,
retry_attempts: settings.retryAttempts,
download_speed_limit_kbps: settings.downloadSpeedLimitKBps,
download_delay_ms: Math.round(settings.downloadDelaySeconds * 1000),
download_delay_jitter_ms: Math.round(settings.downloadDelayJitterSeconds * 1000),
proxy: settings.proxy || "",
filename_template: settings.filenameTemplate || "",
folder_template: settings.folderTemplate || "",
auto_convert_gifs: settings.autoConvertGifs,
gif_quality: settings.gifQuality || "fast",
gif_resolution: settings.gifResolution || "original",
});
const response = await DownloadMediaWithMetadata(request);
if (response.cancelled) {
toast.info(response.message || "Download stopped");
}
else if (response.success) {
if (response.skipped > 0) {
setDownloadItemStatus(itemKey, "skipped");
toast.info("Already exists");
}
else if (response.downloaded > 0) {
setDownloadItemStatus(itemKey, "success");
toast.success("Downloaded");
}
setHasDownloaded(true);
}
else {
setDownloadItemStatus(itemKey, "failed");
toast.error(response.message || "Download failed");
}
}
catch (error) {
setDownloadItemStatus(itemKey, "failed");
const errorMsg = error instanceof Error ? error.message : String(error);
toast.error(`Download failed: ${errorMsg}`);
}
finally {
finishDownload();
}
};
const handleDownload = async () => {
const itemsWithIndices = selectedItems.size > 0
? filteredTimeline
@@ -439,33 +470,31 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
toast.error("No media to download");
return;
}
const keyMap = new Map<number, string>();
const keyMap: Record<number, string> = {};
itemsWithIndices.forEach((entry, backendIndex) => {
keyMap.set(backendIndex, getItemKey(entry.item));
keyMap[backendIndex] = getItemKey(entry.item);
});
bulkDownloadKeyMapRef.current = keyMap;
setIsDownloading(true);
setDownloadProgress({ current: 0, total: itemsWithIndices.length, percent: 0 });
beginDownload({ current: 0, total: itemsWithIndices.length, percent: 0 }, { scope: "media", itemKeyByIndex: keyMap });
logger.info(`Starting download of ${itemsWithIndices.length} files...`);
try {
const settings = getSettings();
const request = new main.DownloadMediaWithMetadataRequest({
items: itemsWithIndices.map(({ item }) => new main.MediaItemRequest({
url: item.url,
date: item.date,
tweet_id: item.tweet_id,
type: item.type,
content: item.content || "",
original_filename: item.original_filename || "",
author_username: item.author_username || "",
})),
items: itemsWithIndices.map(({ item }) => createMediaItemRequest(item)),
output_dir: getOutputDir(),
username: accountInfo.name,
concurrent_downloads: settings.concurrentDownloads || 10,
skip_existing: settings.skipExistingFiles,
delete_incomplete_files: settings.deleteIncompleteFiles,
retry_attempts: settings.retryAttempts,
download_speed_limit_kbps: settings.downloadSpeedLimitKBps,
download_delay_ms: Math.round(settings.downloadDelaySeconds * 1000),
download_delay_jitter_ms: Math.round(settings.downloadDelayJitterSeconds * 1000),
proxy: settings.proxy || "",
filename_template: settings.filenameTemplate || "",
folder_template: settings.folderTemplate || "",
auto_convert_gifs: settings.autoConvertGifs,
gif_quality: settings.gifQuality || "fast",
gif_resolution: settings.gifResolution || "original",
});
const response = await DownloadMediaWithMetadata(request);
if (response.cancelled) {
@@ -496,17 +525,12 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
toast.success(message);
}
setHasDownloaded(true);
const installed = await IsFFmpegInstalled();
setCachedDependencyStatus("ffmpeg", { installed });
setFfmpegInstalled(installed);
if (settings.downloadPath) {
const hasMP4 = await CheckGifsFolderHasMP4(settings.downloadPath, folderName);
setCachedMediaFolderStatus(settings.downloadPath, folderName, {
folderExists: true,
gifsFolderHasMP4: hasMP4,
gifsFolderHasMP4: false,
});
setFolderExists(true);
setGifsFolderHasMP4(hasMP4);
}
}
else {
@@ -520,15 +544,14 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
toast.error("Download failed");
}
finally {
setIsDownloading(false);
setDownloadProgress(null);
bulkDownloadKeyMapRef.current = new Map();
finishDownload();
}
};
const handleStopDownload = async () => {
try {
const stopped = await StopDownload();
if (stopped) {
finishDownload();
logger.info("Download stopped by user");
toast.info("Stopped");
}
@@ -537,6 +560,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";
@@ -551,8 +598,8 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
}
else {
folderPath = settings.downloadPath
? `${settings.downloadPath}/${accountInfo.name}`
: accountInfo.name;
? `${settings.downloadPath}/${folderName}`
: folderName;
}
try {
await OpenFolder(folderPath);
@@ -569,52 +616,6 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
const handleOpenTweet = (tweetId: string) => {
openExternal(`https://x.com/${accountInfo.name}/status/${tweetId}`);
};
const handleConvertGifs = async () => {
const settings = getSettings();
const isBookmarks = accountInfo.nick === "My Bookmarks";
const isLikes = accountInfo.nick === "My Likes";
let folderPath: string;
if (isBookmarks || isLikes) {
const separator = settings.downloadPath.includes("/") ? "/" : "\\";
const folderName = isBookmarks ? "My Bookmarks" : "My Likes";
folderPath = `${settings.downloadPath}${separator}${folderName}`;
}
else {
folderPath = `${settings.downloadPath}/${accountInfo.name}`;
}
setIsConverting(true);
logger.info("Converting GIFs...");
try {
const response = await ConvertGIFs({
folder_path: folderPath,
quality: settings.gifQuality || "fast",
resolution: settings.gifResolution || "high",
delete_original: false,
});
if (response.success) {
logger.success(`Converted ${response.converted} GIFs`);
toast.success(`${response.converted} GIFs converted`);
const hasMP4 = await CheckGifsFolderHasMP4(settings.downloadPath, folderName);
setCachedMediaFolderStatus(settings.downloadPath, folderName, {
folderExists: true,
gifsFolderHasMP4: hasMP4,
});
setGifsFolderHasMP4(hasMP4);
}
else {
logger.error(response.message);
toast.error("Convert failed");
}
}
catch (error) {
const errorMsg = error instanceof Error ? error.message : String(error);
logger.error(`Convert failed: ${errorMsg}`);
toast.error("Convert failed");
}
finally {
setIsConverting(false);
}
};
return (<div className="space-y-4">
{accountInfo.name === "bookmarks" || accountInfo.name === "likes" ? (<div className="flex items-center gap-4 p-4 bg-muted/50 rounded-lg">
@@ -633,40 +634,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 +737,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>)}
@@ -728,21 +764,12 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
<FolderOpen className="h-4 w-4"/>
Open Folder
</Button>
<Button variant="outline" onClick={handleConvertGifs} disabled={isConverting || !gifsFolderHasMP4 || !ffmpegInstalled}>
{isConverting ? (<>
<Spinner />
Converting...
</>) : (<>
<Film className="h-4 w-4"/>
Convert GIFs
</>)}
</Button>
<div className="flex items-center gap-2">
{isDownloading && (<Button variant="destructive" onClick={handleStopDownload}>
<StopCircle className="h-4 w-4"/>
Stop
</Button>)}
<Button onClick={handleDownload} disabled={isDownloading}>
<Button onClick={handleDownload} disabled={anyDownloadActive}>
{isDownloading ? (<>
<Spinner />
Downloading...
@@ -779,19 +806,18 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
{filteredTimeline.slice(0, visibleCount).map((item, index) => {
const itemKey = getItemKey(item);
const isSelected = selectedItems.has(itemKey);
const isItemDownloaded = downloadedItems.has(itemKey);
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>)}
const { isItemDownloaded, isItemFailed, isItemSkipped, isItemDownloading } = getItemStatusFlags(itemKey);
return (<div key={itemKey} onClick={() => openPreview(index)} className={`flex items-center gap-4 p-3 rounded-lg border-2 transition-all cursor-pointer ${isSelected ? "border-primary bg-primary/5" : "border-transparent hover:bg-muted/50"}`}>
<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">
@@ -819,51 +845,7 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
<div className="flex items-center gap-2 shrink-0">
<Tooltip>
<TooltipTrigger asChild>
<Button size="icon" variant="default" onClick={async () => {
setDownloadingItem(itemKey);
currentDownloadingItemKeyRef.current = itemKey;
try {
const settings = getSettings();
const request = new main.DownloadMediaWithMetadataRequest({
items: [new main.MediaItemRequest({
url: item.url,
date: item.date,
tweet_id: item.tweet_id,
type: item.type,
content: item.content || "",
original_filename: item.original_filename || "",
author_username: item.author_username || "",
})],
output_dir: getOutputDir(),
username: accountInfo.name,
concurrent_downloads: settings.concurrentDownloads || 10,
skip_existing: settings.skipExistingFiles,
delete_incomplete_files: settings.deleteIncompleteFiles,
retry_attempts: settings.retryAttempts,
proxy: settings.proxy || "",
});
const response = await DownloadMediaWithMetadata(request);
if (response.cancelled) {
toast.info(response.message || "Download stopped");
}
else if (response.success) {
setHasDownloaded(true);
}
else {
setFailedItems((prev) => new Set(prev).add(itemKey));
toast.error(response.message || "Download failed");
}
}
catch (error) {
setFailedItems((prev) => new Set(prev).add(itemKey));
const errorMsg = error instanceof Error ? error.message : String(error);
toast.error(`Download failed: ${errorMsg}`);
}
finally {
setDownloadingItem(null);
setTimeout(() => { currentDownloadingItemKeyRef.current = null; }, 1000);
}
}} disabled={downloadingItem !== null}>
<Button size="icon" variant="default" onClick={() => void handleDownloadItem(item, itemKey)} disabled={anyDownloadActive}>
{isItemDownloading ? (<Spinner />) : isItemSkipped ? (<FileCheck className="h-4 w-4"/>) : isItemDownloaded ? (<CheckCircle className="h-4 w-4"/>) : isItemFailed ? (<XCircle className="h-4 w-4"/>) : (<Download className="h-4 w-4"/>)}
</Button>
</TooltipTrigger>
@@ -877,18 +859,18 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
</div>
</div>);
})}
</div>) : (<div className={`grid gap-3 ${viewMode === "large" ? "grid-cols-4" : "grid-cols-6"}`}>
</div>) : (<div className={`grid gap-3 ${viewMode === "large" ? "grid-cols-[repeat(auto-fill,minmax(14rem,1fr))]" : "grid-cols-[repeat(auto-fill,minmax(10rem,1fr))]"}`}>
{filteredTimeline.slice(0, visibleCount).map((item, index) => {
const itemKey = getItemKey(item);
const isSelected = selectedItems.has(itemKey);
const isItemDownloaded = downloadedItems.has(itemKey);
const isItemFailed = failedItems.has(itemKey);
const isItemSkipped = skippedItems.has(itemKey);
const isItemDownloading = downloadingItem === itemKey;
const { isItemDownloaded, isItemFailed, isItemSkipped, isItemDownloading } = getItemStatusFlags(itemKey);
return (<div key={itemKey} className={`relative group rounded-lg overflow-hidden border-2 transition-all ${isSelected ? "border-primary" : "border-transparent hover:border-muted-foreground/30"}`}>
<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>)}
@@ -898,49 +880,8 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
<TooltipTrigger asChild>
<Button size="icon" variant="default" className="h-8 w-8" onClick={async (e) => {
e.stopPropagation();
setDownloadingItem(itemKey);
currentDownloadingItemKeyRef.current = itemKey;
try {
const settings = getSettings();
const request = new main.DownloadMediaWithMetadataRequest({
items: [new main.MediaItemRequest({
url: item.url,
date: item.date,
tweet_id: item.tweet_id,
type: item.type,
content: item.content || "",
author_username: item.author_username || "",
})],
output_dir: getOutputDir(),
username: accountInfo.name,
concurrent_downloads: settings.concurrentDownloads || 10,
skip_existing: settings.skipExistingFiles,
delete_incomplete_files: settings.deleteIncompleteFiles,
retry_attempts: settings.retryAttempts,
proxy: settings.proxy || "",
});
const response = await DownloadMediaWithMetadata(request);
if (response.cancelled) {
toast.info(response.message || "Download stopped");
}
else if (response.success) {
setHasDownloaded(true);
}
else {
setFailedItems((prev) => new Set(prev).add(itemKey));
toast.error(response.message || "Download failed");
}
}
catch (error) {
setFailedItems((prev) => new Set(prev).add(itemKey));
const errorMsg = error instanceof Error ? error.message : String(error);
toast.error(`Download failed: ${errorMsg}`);
}
finally {
setDownloadingItem(null);
setTimeout(() => { currentDownloadingItemKeyRef.current = null; }, 1000);
}
}} disabled={downloadingItem !== null}>
await handleDownloadItem(item, itemKey);
}} disabled={anyDownloadActive}>
{isItemDownloading ? (<Spinner />) : isItemSkipped ? (<FileCheck className="h-4 w-4"/>) : isItemDownloaded ? (<CheckCircle className="h-4 w-4"/>) : isItemFailed ? (<XCircle className="h-4 w-4"/>) : (<Download className="h-4 w-4"/>)}
</Button>
</TooltipTrigger>
@@ -1069,54 +1010,10 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
{(() => {
const item = filteredTimeline[previewIndex];
const itemKey = getItemKey(item);
const isItemDownloaded = downloadedItems.has(itemKey);
const isItemFailed = failedItems.has(itemKey);
const isItemSkipped = skippedItems.has(itemKey);
const isItemDownloading = downloadingItem === itemKey;
const { isItemDownloaded, isItemFailed, isItemSkipped, isItemDownloading } = getItemStatusFlags(itemKey);
return (<Button variant="default" size="sm" className="h-9" onClick={async () => {
setDownloadingItem(itemKey);
currentDownloadingItemKeyRef.current = itemKey;
try {
const settings = getSettings();
const request = new main.DownloadMediaWithMetadataRequest({
items: [new main.MediaItemRequest({
url: item.url,
date: item.date,
tweet_id: item.tweet_id,
type: item.type,
content: item.content || "",
original_filename: item.original_filename || "",
author_username: item.author_username || "",
})],
output_dir: getOutputDir(),
username: accountInfo.name,
concurrent_downloads: settings.concurrentDownloads || 10,
skip_existing: settings.skipExistingFiles,
delete_incomplete_files: settings.deleteIncompleteFiles,
retry_attempts: settings.retryAttempts,
proxy: settings.proxy || "",
});
const response = await DownloadMediaWithMetadata(request);
if (response.cancelled) {
toast.info(response.message || "Download stopped");
}
else if (response.success) {
setHasDownloaded(true);
}
else {
setFailedItems((prev) => new Set(prev).add(itemKey));
toast.error("Download failed");
}
}
catch {
setFailedItems((prev) => new Set(prev).add(itemKey));
toast.error("Download failed");
}
finally {
setDownloadingItem(null);
setTimeout(() => { currentDownloadingItemKeyRef.current = null; }, 1000);
}
}} disabled={downloadingItem !== null}>
await handleDownloadItem(item, itemKey);
}} disabled={anyDownloadActive}>
{isItemDownloading ? (<Spinner className="mr-1"/>) : isItemSkipped ? (<FileCheck className="h-4 w-4 mr-1"/>) : isItemDownloaded ? (<CheckCircle className="h-4 w-4 mr-1"/>) : isItemFailed ? (<XCircle className="h-4 w-4 mr-1"/>) : (<Download className="h-4 w-4 mr-1"/>)}
{isItemDownloading ? "Downloading..." : isItemSkipped ? "Already exists" : isItemDownloaded ? "Downloaded" : isItemFailed ? "Failed" : "Download"}
</Button>);
+103 -120
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, CircleQuestionMark, Clipboard, CloudDownload, Clock, Database, Eye, EyeOff, Globe, Heart, Hourglass, 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,39 @@ 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 handleClipboardPaste = async () => {
try {
const clipboardText = (await navigator.clipboard.readText()).trim();
if (clipboardText) {
onUsernameChange(clipboardText);
}
}
catch (error) {
console.error("Failed to read clipboard:", error);
}
};
const handleResume = () => {
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 +247,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 +282,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">
@@ -333,7 +325,7 @@ export function SearchBar({ username, loading, onUsernameChange, onFetch, onStop
<Label className="text-sm">Account List</Label>
<Tooltip>
<TooltipTrigger asChild>
<Info className="h-4 w-4 cursor-help text-muted-foreground"/>
<CircleQuestionMark className="h-4 w-4 cursor-help text-muted-foreground"/>
</TooltipTrigger>
<TooltipContent className="max-w-xs">
<p className="text-sm">
@@ -390,6 +382,10 @@ export function SearchBar({ username, loading, onUsernameChange, onFetch, onStop
</button>)}
</div>
<Button variant="outline" size="icon" className="shrink-0" aria-label="Paste from clipboard" onClick={() => void handleClipboardPaste()}>
<Clipboard className="h-4 w-4"/>
</Button>
<div className="flex items-center gap-2">
{loading && (<Button variant="destructive" onClick={onStopFetch}>
<StopCircle className="h-4 w-4"/>
@@ -508,11 +504,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 +559,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 +642,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,18 +692,18 @@ 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>
<Tooltip>
<TooltipTrigger asChild>
<Info className="h-4 w-4 cursor-help text-muted-foreground"/>
<CircleQuestionMark className="h-4 w-4 cursor-help text-muted-foreground"/>
</TooltipTrigger>
<TooltipContent className="max-w-sm">
<p className="text-sm">{authTokenHelpText}</p>
@@ -709,74 +711,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>
+337 -166
View File
@@ -1,4 +1,4 @@
import { useEffect, useState, useCallback } from "react";
import { useEffect, useState, useCallback, useRef } from "react";
import { flushSync } from "react-dom";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
@@ -6,31 +6,29 @@ 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, CircleQuestionMark, Download, ExternalLink, FolderOpen, 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 { baseColors, getThemesForBaseColor, normalizeThemeName, applyTheme, type BaseColorName } 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";
const THEME_PREVIEW_DEBOUNCE_MS = 50;
interface SettingsPageProps {
onUnsavedChangesChange?: (hasUnsavedChanges: boolean) => void;
onResetRequest?: (resetFn: () => void) => void;
}
function getDependencyVersionStatus(methodName: DependencyVersionMethod) {
const app = (window as Window & {
go?: {
@@ -42,14 +40,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 +57,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,32 +80,88 @@ 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 availableThemes = getThemesForBaseColor(tempSettings.baseColor);
const hasUnsavedChanges = JSON.stringify(savedSettings) !== JSON.stringify(tempSettings);
const themePreviewTimerRef = useRef<number | null>(null);
const selectedThemeConfigRef = useRef({
baseColor: tempSettings.baseColor,
theme: tempSettings.theme,
});
const cancelThemePreview = useCallback(() => {
if (themePreviewTimerRef.current !== null) {
window.clearTimeout(themePreviewTimerRef.current);
themePreviewTimerRef.current = null;
}
}, []);
const previewThemeConfig = useCallback((themeName: SettingsType["theme"], baseColorName: BaseColorName) => {
cancelThemePreview();
themePreviewTimerRef.current = window.setTimeout(() => {
themePreviewTimerRef.current = null;
applyTheme(themeName, baseColorName);
}, THEME_PREVIEW_DEBOUNCE_MS);
}, [cancelThemePreview]);
const previewTheme = useCallback((themeName: SettingsType["theme"]) => {
previewThemeConfig(themeName, selectedThemeConfigRef.current.baseColor);
}, [previewThemeConfig]);
const previewBaseColor = useCallback((baseColorName: BaseColorName) => {
const themeName = normalizeThemeName(selectedThemeConfigRef.current.theme, baseColorName);
previewThemeConfig(themeName, baseColorName);
}, [previewThemeConfig]);
const restoreSelectedTheme = useCallback(() => {
cancelThemePreview();
const selectedTheme = selectedThemeConfigRef.current;
applyTheme(selectedTheme.theme, selectedTheme.baseColor);
}, [cancelThemePreview]);
const handleThemeChange = useCallback((themeName: SettingsType["theme"]) => {
cancelThemePreview();
const baseColorName = selectedThemeConfigRef.current.baseColor;
selectedThemeConfigRef.current = { baseColor: baseColorName, theme: themeName };
applyTheme(themeName, baseColorName);
setTempSettings((prev) => ({ ...prev, theme: themeName }));
}, [cancelThemePreview]);
const handleBaseColorChange = useCallback((baseColorName: BaseColorName) => {
cancelThemePreview();
const themeName = normalizeThemeName(selectedThemeConfigRef.current.theme, baseColorName);
selectedThemeConfigRef.current = { baseColor: baseColorName, theme: themeName };
applyTheme(themeName, baseColorName);
setTempSettings((prev) => ({ ...prev, baseColor: baseColorName, theme: themeName }));
}, [cancelThemePreview]);
const resetToSaved = useCallback(() => {
cancelThemePreview();
const freshSavedSettings = getSettings();
selectedThemeConfigRef.current = {
baseColor: freshSavedSettings.baseColor,
theme: freshSavedSettings.theme,
};
flushSync(() => {
setTempSettings(freshSavedSettings);
setIsDark(document.documentElement.classList.contains("dark"));
});
}, []);
}, [cancelThemePreview]);
useEffect(() => {
selectedThemeConfigRef.current = {
baseColor: tempSettings.baseColor,
theme: tempSettings.theme,
};
}, [tempSettings.baseColor, tempSettings.theme]);
useEffect(() => () => {
cancelThemePreview();
const persistedSettings = getSettings();
applyTheme(persistedSettings.theme, persistedSettings.baseColor);
}, [cancelThemePreview]);
useEffect(() => {
if (onResetRequest) {
onResetRequest(resetToSaved);
}
}, [onResetRequest, resetToSaved]);
useEffect(() => {
onUnsavedChangesChange?.(hasUnsavedChanges);
}, [hasUnsavedChanges, onUnsavedChangesChange]);
const extractorVersionText = extractorInstalled
? extractorInstalledVersion
? extractorUpdateAvailable && extractorLatestVersion
@@ -120,10 +171,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 +192,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 +207,6 @@ export function SettingsPage({ onUnsavedChangesChange, onResetRequest }: Setting
installedVersion: nextExiftoolInstalledVersion,
latestVersion: nextExiftoolLatestVersion,
});
setExtractorInstalled(nextExtractorInstalled);
setExtractorInstalledVersion(nextExtractorInstalledVersion);
setExtractorLatestVersion(nextExtractorLatestVersion);
@@ -174,36 +221,32 @@ export function SettingsPage({ onUnsavedChangesChange, onResetRequest }: Setting
console.error("Failed to check dependency status:", error);
}
};
useEffect(() => {
applyThemeMode(savedSettings.themeMode);
applyTheme(savedSettings.theme);
applyTheme(savedSettings.theme, savedSettings.baseColor);
const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");
const handleChange = () => {
if (savedSettings.themeMode === "auto") {
applyThemeMode("auto");
applyTheme(savedSettings.theme);
applyTheme(savedSettings.theme, savedSettings.baseColor);
}
};
mediaQuery.addEventListener("change", handleChange);
return () => mediaQuery.removeEventListener("change", handleChange);
}, [savedSettings.themeMode, savedSettings.theme]);
}, [savedSettings.themeMode, savedSettings.baseColor, savedSettings.theme]);
useEffect(() => {
applyThemeMode(tempSettings.themeMode);
applyTheme(tempSettings.theme);
applyTheme(tempSettings.theme, tempSettings.baseColor);
applyFont(tempSettings.fontFamily, tempSettings.customFonts);
setTimeout(() => {
setIsDark(document.documentElement.classList.contains("dark"));
}, 0);
}, [tempSettings.themeMode, tempSettings.theme, tempSettings.fontFamily, tempSettings.customFonts]);
}, [tempSettings.themeMode, tempSettings.baseColor, 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 +258,6 @@ export function SettingsPage({ onUnsavedChangesChange, onResetRequest }: Setting
void loadDefaults();
void loadDependencyStatus();
}, []);
useEffect(() => {
const syncCustomFonts = async () => {
const customFonts = await loadCustomFonts();
@@ -224,25 +266,22 @@ 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);
setSavedSettings(defaultSettings);
applyThemeMode(defaultSettings.themeMode);
applyTheme(defaultSettings.theme);
applyTheme(defaultSettings.theme, defaultSettings.baseColor);
applyFont(defaultSettings.fontFamily, defaultSettings.customFonts);
setShowResetConfirm(false);
toast.success("Settings reset to default");
};
const handleBrowseFolder = async () => {
try {
const selectedPath = await SelectFolder(tempSettings.downloadPath || "");
@@ -255,12 +294,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 +318,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 +339,6 @@ export function SettingsPage({ onUnsavedChangesChange, onResetRequest }: Setting
}
toast.success("Font deleted");
};
const handleDownloadExtractor = async () => {
setDownloadingExtractor(true);
try {
@@ -324,7 +359,6 @@ export function SettingsPage({ onUnsavedChangesChange, onResetRequest }: Setting
setDownloadingExtractor(false);
}
};
const handleDownloadFFmpeg = async () => {
setDownloadingFFmpeg(true);
try {
@@ -345,7 +379,6 @@ export function SettingsPage({ onUnsavedChangesChange, onResetRequest }: Setting
setDownloadingFFmpeg(false);
}
};
const handleDownloadExifTool = async () => {
setDownloadingExifTool(true);
try {
@@ -366,7 +399,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 +423,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
@@ -398,33 +434,66 @@ export function SettingsPage({ onUnsavedChangesChange, onResetRequest }: Setting
</div>
<div className="pt-4">
{activeTab === "general" && (<div className="max-w-3xl space-y-4">
{activeTab === "general" && (<div className="grid grid-cols-1 gap-4 md:grid-cols-[minmax(0,1fr)_1px_minmax(0,1fr)] md:gap-6">
<div className="space-y-4">
<div className="space-y-2">
<Label htmlFor="theme-mode">Mode</Label>
<Select value={tempSettings.themeMode} onValueChange={(value: "auto" | "light" | "dark") => setTempSettings((prev) => ({ ...prev, themeMode: value }))}>
<SelectTrigger id="theme-mode">
<SelectValue placeholder="Select theme mode"/>
</SelectTrigger>
<SelectContent>
<SelectItem value="auto">Auto</SelectItem>
<SelectItem value="light">Light</SelectItem>
<SelectItem value="dark">Dark</SelectItem>
</SelectContent>
</Select>
<div className="grid grid-cols-[8rem_8rem] gap-4">
<div className="min-w-0 space-y-2">
<Label htmlFor="theme-mode">Mode</Label>
<Select value={tempSettings.themeMode} onValueChange={(value: "auto" | "light" | "dark") => setTempSettings((prev) => ({ ...prev, themeMode: value }))}>
<SelectTrigger id="theme-mode" className="w-full">
<SelectValue placeholder="Select theme mode"/>
</SelectTrigger>
<SelectContent>
<SelectItem value="auto">Auto</SelectItem>
<SelectItem value="light">Light</SelectItem>
<SelectItem value="dark">Dark</SelectItem>
</SelectContent>
</Select>
</div>
<div className="min-w-0 space-y-2">
<Label htmlFor="base-color">Base Color</Label>
<Select value={tempSettings.baseColor} onValueChange={(value) => handleBaseColorChange(value as BaseColorName)} onOpenChange={(open) => {
if (!open) {
restoreSelectedTheme();
}
}}>
<SelectTrigger id="base-color" className="w-full">
<SelectValue placeholder="Select a base color"/>
</SelectTrigger>
<SelectContent onMouseLeave={restoreSelectedTheme}>
{baseColors.map((baseColor) => (<SelectItem key={baseColor.name} value={baseColor.name} onMouseMove={() => previewBaseColor(baseColor.name)} onFocus={() => previewBaseColor(baseColor.name)}>
<span className="flex items-center gap-2">
<span className="h-3 w-3 rounded-full border border-border" style={{
backgroundColor: isDark
? baseColor.cssVars.dark["muted-foreground"]
: baseColor.cssVars.light["muted-foreground"],
}}/>
{baseColor.label}
</span>
</SelectItem>))}
</SelectContent>
</Select>
</div>
</div>
<div className="space-y-2">
<Label htmlFor="theme">Accent</Label>
<Select value={tempSettings.theme} onValueChange={(value) => setTempSettings((prev) => ({ ...prev, theme: value }))}>
<SelectTrigger id="theme">
<Label htmlFor="theme">Theme</Label>
<Select value={tempSettings.theme} onValueChange={(value) => handleThemeChange(value as SettingsType["theme"])} onOpenChange={(open) => {
if (!open) {
restoreSelectedTheme();
}
}}>
<SelectTrigger id="theme" className="w-32">
<SelectValue placeholder="Select a theme"/>
</SelectTrigger>
<SelectContent>
{themes.map((theme) => (<SelectItem key={theme.name} value={theme.name}>
<SelectContent onMouseLeave={restoreSelectedTheme}>
{availableThemes.map((theme) => (<SelectItem key={theme.name} value={theme.name} onMouseMove={() => previewTheme(theme.name)} onFocus={() => previewTheme(theme.name)}>
<span className="flex items-center gap-2">
<span className="h-3 w-3 rounded-full border border-border" style={{
backgroundColor: isDark ? theme.cssVars.dark.primary : theme.cssVars.light.primary
backgroundColor: isDark
? theme.cssVars.dark[theme.name === tempSettings.baseColor ? "muted-foreground" : "primary"]
: theme.cssVars.light[theme.name === tempSettings.baseColor ? "muted-foreground" : "primary"],
}}/>
{theme.label}
</span>
@@ -470,14 +539,19 @@ export function SettingsPage({ onUnsavedChangesChange, onResetRequest }: Setting
</div>
<div className="flex items-center gap-3 pt-2">
<Label htmlFor="sfx-enabled" className="cursor-pointer text-sm">Sound Effects</Label>
<Switch id="sfx-enabled" checked={tempSettings.sfxEnabled} onCheckedChange={(checked) => setTempSettings((prev) => ({ ...prev, sfxEnabled: checked }))}/>
<Label htmlFor="sfx-enabled" className="cursor-pointer text-sm">Sound Effects</Label>
</div>
<div className="flex items-center gap-3 pt-1">
<Switch id="show-update-notifications" checked={tempSettings.showUpdateNotifications} onCheckedChange={(checked) => setTempSettings((prev) => ({ ...prev, showUpdateNotifications: checked }))}/>
<Label htmlFor="show-update-notifications" className="cursor-pointer text-sm">Update Notifications</Label>
</div>
</div>
</div>)}
{activeTab === "downloads" && (<div className="grid grid-cols-1 gap-4 md:grid-cols-[minmax(0,1fr)_1px_minmax(0,1fr)] md:gap-6">
<div className="space-y-4">
<div aria-hidden="true" className="hidden bg-border md:block"/>
<div className="space-y-6">
<div className="space-y-2">
<Label htmlFor="download-path">Download Path</Label>
<div className="flex gap-2">
@@ -490,54 +564,165 @@ 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>
</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>
</div>
<div className="flex items-center justify-between gap-4">
<Label htmlFor="skip-existing-files" className="cursor-pointer">Skip Existing Files</Label>
<Label>File Handling</Label>
<div className="flex items-center gap-3">
<Switch id="skip-existing-files" checked={tempSettings.skipExistingFiles} onCheckedChange={(checked) => setTempSettings((prev) => ({ ...prev, skipExistingFiles: checked }))}/>
<Label htmlFor="skip-existing-files" className="cursor-pointer font-normal">Skip Existing Files</Label>
</div>
<div className="flex items-center justify-between gap-4">
<Label htmlFor="delete-incomplete-files" className="cursor-pointer">Delete Incomplete Files</Label>
<div className="flex items-center gap-3">
<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>
<Label htmlFor="delete-incomplete-files" className="cursor-pointer font-normal">Delete Incomplete Files</Label>
</div>
</div>
<div className="space-y-3">
<Label className="flex items-center gap-2">
GIF Conversion
<Tooltip>
<TooltipTrigger asChild>
<CircleQuestionMark className="h-3.5 w-3.5 cursor-help text-muted-foreground"/>
</TooltipTrigger>
<TooltipContent side="top">
<p>Quality settings for converting Twitter's MP4 into actual GIF files.</p>
</TooltipContent>
</Tooltip>
</Label>
<div className="flex items-center gap-3">
<Switch id="auto-convert-gifs" checked={tempSettings.autoConvertGifs} onCheckedChange={(checked) => setTempSettings((prev) => ({ ...prev, autoConvertGifs: checked }))} disabled={!ffmpegInstalled}/>
<Label htmlFor="auto-convert-gifs" className={!ffmpegInstalled ? "text-muted-foreground" : "cursor-pointer"}>Auto Convert GIFs</Label>
</div>
<div className="flex items-center justify-between gap-4">
<Label htmlFor="gif-quality" className={!ffmpegInstalled || !tempSettings.autoConvertGifs ? "text-muted-foreground" : undefined}>GIF Quality</Label>
<div className="flex items-center gap-2">
<Select value={tempSettings.gifQuality} onValueChange={(value: GifQuality) => {
setTempSettings((prev) => ({
...prev,
gifQuality: value,
}));
}} disabled={!ffmpegInstalled || !tempSettings.autoConvertGifs}>
<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 || !tempSettings.autoConvertGifs}>
<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>)}
{activeTab === "downloads" && (<div className="grid grid-cols-1 gap-4 md:grid-cols-[minmax(0,1fr)_1px_minmax(0,1fr)] md:gap-6">
<div className="space-y-4">
<div className="flex items-center gap-2">
<Label>Download Controls</Label>
<Tooltip>
<TooltipTrigger asChild>
<CircleQuestionMark className="h-3.5 w-3.5 cursor-help text-muted-foreground"/>
</TooltipTrigger>
<TooltipContent side="top" className="max-w-xs">
<p>The speed limit is shared by all concurrent downloads. Delay spaces out media requests and adds an optional random variation.</p>
</TooltipContent>
</Tooltip>
</div>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-1.5">
<Label htmlFor="concurrent-downloads" className="flex items-center gap-2 text-xs">
Concurrent Downloads
<Tooltip>
<TooltipTrigger asChild>
<CircleQuestionMark 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-24">
<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-1.5">
<Label htmlFor="retry-attempts" className="flex items-center gap-2 text-xs">
Retry Attempts
<Tooltip>
<TooltipTrigger asChild>
<CircleQuestionMark 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-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 className="grid grid-cols-1 gap-3 sm:grid-cols-3">
<div className="space-y-1.5">
<Label htmlFor="download-speed-limit" className="text-xs">Speed Limit</Label>
<div className="flex items-center gap-2">
<InputWithContext id="download-speed-limit" type="number" min="0" max="10485760" step="1" value={tempSettings.downloadSpeedLimitKBps} onChange={(e) => {
const value = Number(e.target.value);
setTempSettings((prev) => ({ ...prev, downloadSpeedLimitKBps: Number.isFinite(value) ? Math.min(10485760, Math.max(0, Math.round(value))) : 0 }));
}} className="w-24"/>
<span className="text-xs text-muted-foreground">KB/s</span>
</div>
</div>
<div className="space-y-1.5">
<Label htmlFor="download-delay" className="text-xs">Base Delay</Label>
<div className="flex items-center gap-2">
<InputWithContext id="download-delay" type="number" min="0" max="3600" step="0.1" value={tempSettings.downloadDelaySeconds} onChange={(e) => {
const value = Number(e.target.value);
setTempSettings((prev) => ({ ...prev, downloadDelaySeconds: Number.isFinite(value) ? Math.min(3600, Math.max(0, value)) : 0 }));
}} className="w-24"/>
<span className="text-xs text-muted-foreground">sec</span>
</div>
</div>
<div className="space-y-1.5">
<Label htmlFor="download-delay-jitter" className="text-xs">Random Extra</Label>
<div className="flex items-center gap-2">
<InputWithContext id="download-delay-jitter" type="number" min="0" max="3600" step="0.1" value={tempSettings.downloadDelayJitterSeconds} onChange={(e) => {
const value = Number(e.target.value);
setTempSettings((prev) => ({ ...prev, downloadDelayJitterSeconds: Number.isFinite(value) ? Math.min(3600, Math.max(0, value)) : 0 }));
}} className="w-24"/>
<span className="text-xs text-muted-foreground">sec</span>
</div>
</div>
</div>
</div>
<div aria-hidden="true" className="hidden bg-border md:block"/>
@@ -548,7 +733,7 @@ export function SettingsPage({ onUnsavedChangesChange, onResetRequest }: Setting
Proxy
<Tooltip>
<TooltipTrigger asChild>
<Info className="h-3.5 w-3.5 cursor-help text-muted-foreground"/>
<CircleQuestionMark className="h-3.5 w-3.5 cursor-help text-muted-foreground"/>
</TooltipTrigger>
<TooltipContent side="top">
<p>Supports one proxy or multiple proxies separated by commas. Requests will rotate through them.</p>
@@ -558,12 +743,36 @@ export function SettingsPage({ onUnsavedChangesChange, onResetRequest }: Setting
<InputWithContext id="proxy" value={tempSettings.proxy || ""} onChange={(e) => setTempSettings((prev) => ({ ...prev, proxy: e.target.value }))} placeholder="http://proxy1:port, socks5://proxy2:port (optional)" className="max-w-md"/>
</div>
<div className="space-y-2">
<Label>Fetch Delay</Label>
<div className="flex flex-wrap gap-4">
{([
["fetchDelaySeconds", "Base Delay"],
["fetchDelayJitterSeconds", "Random Extra"],
] as const).map(([key, label]) => (
<div key={key} className="space-y-1.5">
<Label htmlFor={key} className="text-xs">{label}</Label>
<div className="flex items-center gap-2">
<InputWithContext id={key} type="number" min="0" max="3600" step="0.1" value={tempSettings[key]} onChange={(e) => {
const value = Number(e.target.value);
setTempSettings((prev) => ({ ...prev, [key]: Number.isFinite(value) ? Math.min(3600, Math.max(0, value)) : 0 }));
}} className="w-24"/>
<span className="text-xs text-muted-foreground">sec</span>
</div>
</div>
))}
</div>
<p className="text-xs text-muted-foreground">Spaces out fetch batch starts, including account switches and retries. Random Extra adds between 0 and the chosen number of seconds. Set both to 0 to disable.</p>
<p className="text-xs text-muted-foreground">Suggested starting point: 5 sec base + 5 sec random extra. No delay guarantees avoidance of rate limits. Waiting counts toward Fetch Timeout; increase it for longer delays.</p>
<p className="text-xs text-muted-foreground">Applies between extractor runs, including date-range fetches, rather than individual requests inside the extractor.</p>
</div>
<div className="space-y-2">
<Label htmlFor="fetch-timeout" className="flex items-center gap-2">
Fetch Timeout
<Tooltip>
<TooltipTrigger asChild>
<Info className="h-3.5 w-3.5 cursor-help text-muted-foreground"/>
<CircleQuestionMark className="h-3.5 w-3.5 cursor-help text-muted-foreground"/>
</TooltipTrigger>
<TooltipContent side="top">
<p>Timeout in seconds. Fetch stops automatically when reached</p>
@@ -591,53 +800,15 @@ export function SettingsPage({ onUnsavedChangesChange, onResetRequest }: Setting
}} placeholder="60" className="w-24"/>
</div>
<div className="space-y-4">
<div className="space-y-3">
<Label className="flex items-center gap-2">
GIF Conversion
<Tooltip>
<TooltipTrigger asChild>
<Info className="h-3.5 w-3.5 cursor-help text-muted-foreground"/>
</TooltipTrigger>
<TooltipContent side="top">
<p>Quality settings for converting Twitter's MP4 into actual GIF files.</p>
</TooltipContent>
</Tooltip>
</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>
</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>
</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>)}
@@ -647,13 +818,13 @@ export function SettingsPage({ onUnsavedChangesChange, onResetRequest }: Setting
<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>
<TooltipTrigger asChild>
<Info className="h-3.5 w-3.5 cursor-help text-muted-foreground"/>
<CircleQuestionMark className="h-3.5 w-3.5 cursor-help text-muted-foreground"/>
</TooltipTrigger>
<TooltipContent side="top">
<p>Required to fetch media from Twitter/X. Downloaded from the xtractor-binaries GitHub releases.</p>
@@ -681,13 +852,13 @@ 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>
<TooltipTrigger asChild>
<Info className="h-3.5 w-3.5 cursor-help text-muted-foreground"/>
<CircleQuestionMark className="h-3.5 w-3.5 cursor-help text-muted-foreground"/>
</TooltipTrigger>
<TooltipContent side="top">
<p>FFmpeg is required to convert Twitter's MP4 to actual GIF format</p>
@@ -715,13 +886,13 @@ 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>
<TooltipTrigger asChild>
<Info className="h-3.5 w-3.5 cursor-help text-muted-foreground"/>
<CircleQuestionMark className="h-3.5 w-3.5 cursor-help text-muted-foreground"/>
</TooltipTrigger>
<TooltipContent side="top">
<p>ExifTool is required to embed tweet URL and original filename into media file metadata</p>
+1 -1
View File
@@ -131,7 +131,7 @@ export function Sidebar({ currentPage, onPageChange }: SidebarProps) {
</Button>
</TooltipTrigger>
<TooltipContent side="right">
<p>Support me on Ko-fi</p>
<p>Support Me</p>
</TooltipContent>
</Tooltip>
</div>
+84 -45
View File
@@ -1,59 +1,98 @@
import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { CircleCheck, Copy } from "lucide-react";
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";
import UsdtTronQr from "@/assets/usdt.jpg";
import UsdtEvmQr from "@/assets/usdt_evm.jpg";
import UsdcEvmQr from "@/assets/usdc.jpg";
type CryptoCoin = "usdt" | "usdc";
type CryptoNetwork = "ethereum" | "bsc" | "polygon" | "base" | "tron";
const EVM_ADDRESS = "0xB563a7F39770C151e2FacE26926081a00c5EF349";
const TRON_ADDRESS = "THnzAAwZgp2Sq5CAXLP2njQDhTvgZG9EWs";
const EVM_NETWORKS: Array<{
value: CryptoNetwork;
label: string;
shortLabel: string;
}> = [
{ value: "bsc", label: "BNB Smart Chain (BEP20)", shortLabel: "BEP20" },
{ value: "polygon", label: "Polygon", shortLabel: "Polygon" },
{ value: "ethereum", label: "Ethereum (ERC20)", shortLabel: "ERC20" },
{ value: "base", label: "Base", shortLabel: "Base" },
];
const USDT_NETWORKS: Array<{
value: CryptoNetwork;
label: string;
shortLabel: string;
}> = [
{ value: "ethereum", label: "Ethereum (ERC20)", shortLabel: "ERC20" },
{ value: "bsc", label: "BNB Smart Chain (BEP20)", shortLabel: "BEP20" },
{ value: "tron", label: "Tron (TRC20)", shortLabel: "TRC20" },
{ value: "polygon", label: "Polygon", shortLabel: "Polygon" },
];
export function SupportPage() {
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">
<div className="flex flex-col items-center space-y-4">
<div className="relative flex h-32 w-full items-center justify-center">
<img src={KofiLogo} className="pointer-events-none absolute w-72" alt="Ko-fi"/>
</div>
<h4 className="font-semibold text-foreground">Support via Ko-fi</h4>
<p className="px-4 text-center text-sm text-muted-foreground">
Enjoying the project? You can support ongoing development by buying me a coffee.
</p>
</div>
<Button className="h-10 w-full gap-2 bg-[#72a4f2] text-sm font-semibold text-white hover:bg-[#5f8cd6]" onClick={() => openExternal("https://ko-fi.com/afkarxyz")}>
<img src={KofiSvg} className="h-5 w-5 shrink-0" alt="" aria-hidden="true"/>
Support me on Ko-fi
</Button>
</div>
<div className="flex flex-1 flex-col items-center justify-between space-y-6 p-6">
<div className="flex w-full flex-col items-center space-y-4">
<div className="flex h-32 items-center justify-center">
const [selectedCoin, setSelectedCoin] = useState<CryptoCoin>("usdt");
const [selectedNetwork, setSelectedNetwork] = useState<CryptoNetwork>("tron");
const [copiedAddress, setCopiedAddress] = useState(false);
const networkOptions = selectedCoin === "usdt" ? USDT_NETWORKS : EVM_NETWORKS;
const activeNetwork = networkOptions.find((network) => network.value === selectedNetwork) || EVM_NETWORKS[0];
const isTron = selectedNetwork === "tron";
const cryptoAddress = isTron ? TRON_ADDRESS : EVM_ADDRESS;
const cryptoQr = isTron ? UsdtTronQr : selectedCoin === "usdt" ? UsdtEvmQr : UsdcEvmQr;
const handleCoinChange = (coin: CryptoCoin) => {
setSelectedCoin(coin);
setCopiedAddress(false);
const nextNetworks = coin === "usdt" ? USDT_NETWORKS : EVM_NETWORKS;
if (!nextNetworks.some((network) => network.value === selectedNetwork)) {
setSelectedNetwork("ethereum");
}
};
return (<div className="mx-auto flex min-h-[70vh] w-full max-w-lg flex-col items-center justify-center space-y-4 p-6">
<div className="flex w-full flex-col items-center space-y-3">
<div className="flex h-40 items-center justify-center">
<div className="rounded-xl border bg-white p-2 shadow-sm">
<img src={UsdtBarcode} className="h-24 w-24 object-contain" alt="USDT Barcode"/>
<img src={cryptoQr} className="h-32 w-32 object-contain" alt={`${selectedCoin.toUpperCase()} ${activeNetwork.label} QR code`}/>
</div>
</div>
<h4 className="font-semibold text-foreground">USDT (TRC20)</h4>
<h4 className="font-semibold text-foreground">Support via Crypto</h4>
<p className="px-4 text-center text-sm text-muted-foreground">
Crypto donations are also accepted. Scan the QR code or copy the address.
Scan the QR code or copy the address to support the project.
</p>
</div>
<div className="flex h-10 w-full items-center justify-between gap-2 rounded-lg border bg-muted/50 py-1.5 pr-1.5 pl-3">
<code className="truncate text-xs font-mono text-muted-foreground" title={USDT_ADDRESS}>
{USDT_ADDRESS}
</code>
<Button variant="ghost" size="icon" className="h-7 w-7 shrink-0 hover:bg-background" onClick={() => {
navigator.clipboard.writeText(USDT_ADDRESS);
setCopiedUsdt(true);
setTimeout(() => setCopiedUsdt(false), 500);
<div className="w-full space-y-2">
<div className="grid grid-cols-2 gap-2">
<Select value={selectedCoin} onValueChange={(value: CryptoCoin) => handleCoinChange(value)}>
<SelectTrigger size="sm" className="w-full" aria-label="Coin">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="usdt">USDT</SelectItem>
<SelectItem value="usdc">USDC</SelectItem>
</SelectContent>
</Select>
<Select value={selectedNetwork} onValueChange={(value: CryptoNetwork) => {
setSelectedNetwork(value);
setCopiedAddress(false);
}}>
{copiedUsdt ? <CircleCheck className="h-3.5 w-3.5 text-green-500"/> : <Copy className="h-3.5 w-3.5"/>}
</Button>
<SelectTrigger size="sm" className="w-full" aria-label="Network">
<SelectValue>{activeNetwork.shortLabel}</SelectValue>
</SelectTrigger>
<SelectContent>
{networkOptions.map((network) => (<SelectItem key={network.value} value={network.value}>{network.label}</SelectItem>))}
</SelectContent>
</Select>
</div>
<div className="flex h-10 w-full items-center justify-between gap-2 rounded-lg border bg-muted/50 py-1.5 pr-1.5 pl-3">
<code className="min-w-0 flex-1 truncate text-xs font-mono text-muted-foreground" title={cryptoAddress}>
{cryptoAddress}
</code>
<Button variant="ghost" size="icon" className="h-7 w-7 shrink-0 hover:bg-background" aria-label="Copy wallet address" onClick={() => {
navigator.clipboard.writeText(cryptoAddress);
setCopiedAddress(true);
setTimeout(() => setCopiedAddress(false), 500);
}}>
{copiedAddress ? <CircleCheck className="h-3.5 w-3.5 text-green-500"/> : <Copy className="h-3.5 w-3.5"/>}
</Button>
</div>
</div>
</div>
</div>
</div>);
}
+42 -9
View File
@@ -1,6 +1,20 @@
import { X, Minus, Maximize } from "lucide-react";
import { X, Minus, Maximize, Sparkles, Puzzle, FileCode2, Globe, ArrowLeft, ArrowRight, RotateCw } from "lucide-react";
import { WindowMinimise, WindowToggleMaximise, Quit } from "../../wailsjs/runtime/runtime";
export function TitleBar() {
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://twitterdl.app" },
];
interface TitleBarProps {
canGoBack?: boolean;
canGoForward?: boolean;
navigationDisabled?: boolean;
onBack?: () => void;
onForward?: () => void;
}
export function TitleBar({ canGoBack = false, canGoForward = false, navigationDisabled = false, onBack, onForward }: TitleBarProps) {
const handleMinimize = () => {
WindowMinimise();
};
@@ -11,18 +25,37 @@ 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 left-16 z-50 flex h-7 items-center gap-0.5" style={{ "--wails-draggable": "no-drag" } as React.CSSProperties}>
<button type="button" onClick={onBack} disabled={!canGoBack || navigationDisabled} className="flex size-7 items-center justify-center rounded transition-colors hover:bg-muted disabled:cursor-default disabled:opacity-35 disabled:hover:bg-transparent" aria-label="Go back"><ArrowLeft className="h-3.5 w-3.5"/></button>
<button type="button" onClick={onForward} disabled={!canGoForward || navigationDisabled} className="flex size-7 items-center justify-center rounded transition-colors hover:bg-muted disabled:cursor-default disabled:opacity-35 disabled:hover:bg-transparent" aria-label="Go forward"><ArrowRight className="h-3.5 w-3.5"/></button>
<button type="button" onClick={() => window.location.reload()} className="flex size-7 items-center justify-center rounded transition-colors hover:bg-muted" aria-label="Reload"><RotateCw className="h-3.5 w-3.5"/></button>
</div>
<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="size-7 flex items-center justify-center hover:bg-muted transition-colors rounded" aria-label="Info">
<Sparkles className="h-3.5 w-3.5 text-primary"/>
</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="size-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="size-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="size-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 };
+112
View File
@@ -0,0 +1,112 @@
import { useSyncExternalStore } from "react";
import { EventsOn } from "../../wailsjs/runtime/runtime";
export interface DownloadProgress {
current: number;
total: number;
percent: number;
}
export interface DownloadItemStatus {
tweet_id: number;
index: number;
status: "success" | "failed" | "skipped" | "cancelled";
}
export type DownloadScope = "media" | "database" | "database-bulk";
export type DownloadItemResult = "success" | "failed" | "skipped";
export interface DownloadState {
active: boolean;
scope: DownloadScope | null;
accountId: number | null;
progress: DownloadProgress | null;
currentItemKey: string | null;
itemKeyByIndex: Record<number, string>;
itemStatusByKey: Record<string, DownloadItemResult>;
}
const listeners = new Set<() => void>();
let state: DownloadState = {
active: false,
scope: null,
accountId: null,
progress: null,
currentItemKey: null,
itemKeyByIndex: {},
itemStatusByKey: {},
};
let unsubscribeEvents: (() => void) | null = null;
function emit() {
for (const listener of listeners) {
listener();
}
}
function setState(next: Partial<DownloadState>) {
state = { ...state, ...next };
emit();
}
export function initDownloadProgressEvents() {
if (unsubscribeEvents) {
return unsubscribeEvents;
}
const unsubscribeProgress = EventsOn("download-progress", (progress: DownloadProgress) => {
if (!state.scope) {
return;
}
setState({ progress });
});
const unsubscribeItemStatus = EventsOn("download-item-status", (status: DownloadItemStatus) => {
if (status.status === "cancelled") {
return;
}
const itemKey = state.currentItemKey || state.itemKeyByIndex[status.index] || `${String(status.tweet_id)}-${status.index}`;
setState({
itemStatusByKey: {
...state.itemStatusByKey,
[itemKey]: status.status,
},
});
});
unsubscribeEvents = () => {
unsubscribeProgress();
unsubscribeItemStatus();
unsubscribeEvents = null;
};
return unsubscribeEvents;
}
export function beginDownload(progress: DownloadProgress, meta: Pick<DownloadState, "scope"> & Partial<Pick<DownloadState, "accountId" | "currentItemKey" | "itemKeyByIndex">>) {
setState({
active: true,
scope: meta.scope,
accountId: meta.accountId ?? null,
progress,
currentItemKey: meta.currentItemKey ?? null,
itemKeyByIndex: meta.itemKeyByIndex ?? {},
});
}
export function finishDownload() {
setState({
active: false,
scope: null,
accountId: null,
progress: null,
currentItemKey: null,
itemKeyByIndex: {},
});
}
export function setDownloadItemStatus(itemKey: string, status: DownloadItemResult) {
setState({
itemStatusByKey: {
...state.itemStatusByKey,
[itemKey]: status,
},
});
}
export function subscribeDownloadState(listener: () => void) {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
}
export function getDownloadState() {
return state;
}
export function useDownloadState() {
return useSyncExternalStore(subscribeDownloadState, getDownloadState, getDownloadState);
}
+27
View File
@@ -0,0 +1,27 @@
export function normalizeFetchDelay(value: unknown): number {
return typeof value === "number" && Number.isFinite(value)
? Math.round(Math.min(3600, Math.max(0, value)) * 1000) / 1000
: 0;
}
// One gate shared by all fetch paths, so switching accounts also respects pacing.
export function createFetchDelayGate({
now = () => performance.now(),
random = Math.random,
sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)),
} = {}) {
let lastStarted: number | null = null;
return async (baseSeconds: number, extraSeconds: number, stopped: () => boolean): Promise<boolean> => {
const delay = (normalizeFetchDelay(baseSeconds) + random() * normalizeFetchDelay(extraSeconds)) * 1000;
while (!stopped()) {
const remaining = lastStarted === null ? 0 : lastStarted + delay - now();
if (remaining <= 0) {
lastStarted = now();
return true;
}
// Recheck the shared timestamp after each wait to space concurrent callers too.
await sleep(Math.min(remaining, 100));
}
return false;
};
}
-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 {
+24
View File
@@ -0,0 +1,24 @@
export function extractMarkdownSection(body: string, heading: string): string {
const text = (body || "").replace(/\r\n/g, "\n");
const lines = text.split("\n");
const target = heading.trim().toLowerCase();
let start = -1;
for (let i = 0; i < lines.length; i++) {
const match = lines[i].match(/^#{1,6}\s+(.*)$/);
if (match && match[1].trim().toLowerCase() === target) {
start = i + 1;
break;
}
}
if (start === -1) {
return text.trim();
}
const collected: string[] = [];
for (let i = start; i < lines.length; i++) {
if (/^#{1,6}\s+/.test(lines[i])) {
break;
}
collected.push(lines[i]);
}
return collected.join("\n").trim();
}
-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);
}
+210 -63
View File
@@ -1,92 +1,226 @@
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";
import { normalizeFetchDelay } from "./fetch-delay";
import { normalizeBaseColorName, normalizeThemeName, type BaseColorName, type ThemeName } from "./themes";
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 = "{handle}_{date}_{tweet_id}";
export interface TemplateToken {
key: string;
description: string;
example: string;
}
export const FILENAME_TEMPLATE_VARIABLES: TemplateToken[] = [
{ key: "{handle}", description: "Author handle", example: "elonmusk" },
{ key: "{name}", description: "Author display name", example: "Elon Musk" },
{ key: "{date}", description: "Tweet date & time", example: "20250620_104556" },
{ key: "{tweet_id}", description: "Tweet ID", example: "1989033613824815258" },
{ key: "{media_id}", description: "Unique media ID (prevents overwrites)", example: "Gx1aB2cXkAA7Yz9" },
{ key: "{type}", description: "Media type", example: "photo" },
];
export interface FilenameTemplateData {
username?: string;
accountName?: string;
date?: string;
tweetId?: string;
index?: number;
mediaID?: string;
type?: string;
}
export const SAMPLE_FILENAME_DATA: FilenameTemplateData = {
username: "elonmusk",
accountName: "Elon Musk",
date: "20250620_104556",
tweetId: "1989033613824815258",
index: 1,
mediaID: "Gx1aB2cXkAA7Yz9",
type: "photo",
};
function sanitizeTemplatePart(input: string): string {
const cleaned = input
.replace(/[\u0000-\u001f\\/:*?"<>|]/g, "")
.trim()
.replace(/[. ]+$/g, "");
return /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i.test(cleaned) ? `${cleaned}_` : cleaned;
}
export function renderFilenameTemplate(template: string, data: FilenameTemplateData): string {
if (!template)
return "";
return sanitizeTemplatePart(template
.replace(/\{handle\}/g, sanitizeTemplatePart(data.username ?? ""))
.replace(/\{name\}/g, sanitizeTemplatePart(data.accountName ?? ""))
.replace(/\{username\}/g, sanitizeTemplatePart(data.username ?? ""))
.replace(/\{account_name\}/g, sanitizeTemplatePart(data.accountName ?? ""))
.replace(/\{date\}/g, sanitizeTemplatePart(data.date ?? ""))
.replace(/\{tweet_id\}/g, sanitizeTemplatePart(data.tweetId ?? ""))
.replace(/\{index\}/g, String(data.index ?? 1).padStart(2, "0"))
.replace(/\{media_id\}/g, sanitizeTemplatePart(data.mediaID ?? ""))
.replace(/\{type\}/g, sanitizeTemplatePart(data.type ?? ""))
.trim());
}
export const DEFAULT_FOLDER_TEMPLATE = "{handle}";
export const FOLDER_TEMPLATE_VARIABLES: TemplateToken[] = [
{ key: "{handle}", description: "Author handle", example: "elonmusk" },
{ key: "{name}", description: "Author display name", example: "Elon Musk" },
{ key: "{date}", description: "Download date", example: "20250620" },
];
export interface FolderTemplateData {
username?: string;
accountName?: string;
date?: string;
}
export const SAMPLE_FOLDER_DATA: FolderTemplateData = {
username: "elonmusk",
accountName: "Elon Musk",
date: "20250620",
};
export function renderFolderTemplate(template: string, data: FolderTemplateData): string {
if (!template)
return "";
return sanitizeTemplatePart(template
.replace(/\{handle\}/g, sanitizeTemplatePart(data.username ?? ""))
.replace(/\{name\}/g, sanitizeTemplatePart(data.accountName ?? ""))
.replace(/\{username\}/g, sanitizeTemplatePart(data.username ?? ""))
.replace(/\{account_name\}/g, sanitizeTemplatePart(data.accountName ?? ""))
.replace(/\{date\}/g, sanitizeTemplatePart(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;
const DEFAULT_DOWNLOAD_SPEED_LIMIT_KBPS = 0;
const MAX_DOWNLOAD_SPEED_LIMIT_KBPS = 10 * 1024 * 1024;
const DEFAULT_DOWNLOAD_DELAY_SECONDS = 0;
const MAX_DOWNLOAD_DELAY_SECONDS = 60 * 60;
export interface Settings {
downloadPath: string;
concurrentDownloads: number;
skipExistingFiles: boolean;
deleteIncompleteFiles: boolean;
retryAttempts: number;
theme: string;
downloadSpeedLimitKBps: number;
downloadDelaySeconds: number;
downloadDelayJitterSeconds: number;
baseColor: BaseColorName;
theme: ThemeName;
themeMode: "auto" | "light" | "dark";
fontFamily: FontFamily;
customFonts: CustomFontOption[];
sfxEnabled: boolean;
showUpdateNotifications: boolean;
autoConvertGifs: boolean;
gifQuality: GifQuality;
gifResolution: GifResolution;
proxy: string;
fetchTimeout: number;
fetchMode: FetchMode;
mediaType: MediaType;
fetchDelaySeconds: number;
fetchDelayJitterSeconds: number;
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,
skipExistingFiles: true,
deleteIncompleteFiles: true,
retryAttempts: DEFAULT_RETRY_ATTEMPTS,
downloadSpeedLimitKBps: DEFAULT_DOWNLOAD_SPEED_LIMIT_KBPS,
downloadDelaySeconds: DEFAULT_DOWNLOAD_DELAY_SECONDS,
downloadDelayJitterSeconds: DEFAULT_DOWNLOAD_DELAY_SECONDS,
baseColor: "neutral",
theme: "yellow",
themeMode: "auto",
fontFamily: "google-sans",
customFonts: [],
sfxEnabled: true,
showUpdateNotifications: true,
autoConvertGifs: false,
gifQuality: "fast",
gifResolution: "original",
proxy: "",
fetchTimeout: 60,
fetchMode: "batch",
mediaType: "all",
fetchDelaySeconds: 0,
fetchDelayJitterSeconds: 0,
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 +308,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 +325,6 @@ function extractGoogleFontInputUrl(input: string): string {
}
return trimmed;
}
function coerceGoogleFontUrl(rawUrl: string): string {
const trimmed = rawUrl.trim();
if (/^https?:\/\//i.test(trimmed)) {
@@ -204,34 +335,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 +382,6 @@ function normalizeGoogleFontCssUrl(rawUrl: string): string | null {
return null;
}
}
export function parseGoogleFontUrl(rawUrl: string): CustomFontOption | null {
const normalizedUrl = normalizeGoogleFontCssUrl(rawUrl);
if (!normalizedUrl) {
@@ -276,7 +400,6 @@ export function parseGoogleFontUrl(rawUrl: string): CustomFontOption | null {
url: normalizedUrl,
};
}
function normalizeCustomFonts(customFonts: unknown): CustomFontOption[] {
if (!Array.isArray(customFonts)) {
return [];
@@ -288,7 +411,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 +427,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 +437,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 +450,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 +469,37 @@ function normalizeRetryAttempts(value: unknown): number {
}
return rounded;
}
function normalizeDownloadSpeedLimit(value: unknown): number {
if (typeof value !== "number" || !Number.isFinite(value)) {
return DEFAULT_DOWNLOAD_SPEED_LIMIT_KBPS;
}
return Math.min(MAX_DOWNLOAD_SPEED_LIMIT_KBPS, Math.max(0, Math.round(value)));
}
function normalizeDownloadDelay(value: unknown): number {
if (typeof value !== "number" || !Number.isFinite(value)) {
return DEFAULT_DOWNLOAD_DELAY_SECONDS;
}
const milliseconds = Math.round(Math.min(MAX_DOWNLOAD_DELAY_SECONDS, Math.max(0, value)) * 1000);
return milliseconds / 1000;
}
function normalizeTemplateTokens(value: unknown, fallback: string): string {
if (typeof value !== "string") {
return fallback;
}
return value
.replace(/\{username\}/g, "{handle}")
.replace(/\{account_name\}/g, "{name}");
}
function normalizeFilenameTemplate(value: unknown): string {
const template = normalizeTemplateTokens(value, DEFAULT_FILENAME_TEMPLATE);
return template === "{handle}_{date}_{tweet_id}_{index}" ? DEFAULT_FILENAME_TEMPLATE : template;
}
function normalizeFolderTemplate(value: unknown): string {
return normalizeTemplateTokens(value, DEFAULT_FOLDER_TEMPLATE);
}
export function getFontOptions(customFonts: CustomFontOption[] = []): FontOption[] {
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 +516,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 +530,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,21 +540,31 @@ async function fetchDefaultPath(): Promise<string> {
return "";
}
}
function toNormalizedSettings(settings: Partial<Settings>): Settings {
const customFonts = normalizeCustomFonts(settings.customFonts);
const baseColor = normalizeBaseColorName(settings.baseColor);
return {
...DEFAULT_SETTINGS,
...settings,
baseColor,
theme: normalizeThemeName(settings.theme, baseColor),
concurrentDownloads: normalizeConcurrentDownloads(settings.concurrentDownloads),
skipExistingFiles: normalizeBoolean(settings.skipExistingFiles, DEFAULT_SETTINGS.skipExistingFiles),
deleteIncompleteFiles: normalizeBoolean(settings.deleteIncompleteFiles, DEFAULT_SETTINGS.deleteIncompleteFiles),
retryAttempts: normalizeRetryAttempts(settings.retryAttempts),
downloadSpeedLimitKBps: normalizeDownloadSpeedLimit(settings.downloadSpeedLimitKBps),
downloadDelaySeconds: normalizeDownloadDelay(settings.downloadDelaySeconds),
downloadDelayJitterSeconds: normalizeDownloadDelay(settings.downloadDelayJitterSeconds),
fetchDelaySeconds: normalizeFetchDelay(settings.fetchDelaySeconds),
fetchDelayJitterSeconds: normalizeFetchDelay(settings.fetchDelayJitterSeconds),
showUpdateNotifications: normalizeBoolean(settings.showUpdateNotifications, DEFAULT_SETTINGS.showUpdateNotifications),
autoConvertGifs: normalizeBoolean(settings.autoConvertGifs, DEFAULT_SETTINGS.autoConvertGifs),
filenameTemplate: normalizeFilenameTemplate(settings.filenameTemplate),
folderTemplate: normalizeFolderTemplate(settings.folderTemplate),
customFonts,
fontFamily: normalizeFontFamily(settings.fontFamily, customFonts),
};
}
export function getSettings(): Settings {
try {
const stored = localStorage.getItem(SETTINGS_KEY);
@@ -423,7 +577,6 @@ export function getSettings(): Settings {
}
return DEFAULT_SETTINGS;
}
export async function getSettingsWithDefaults(): Promise<Settings> {
const settings = getSettings();
if (!settings.downloadPath) {
@@ -431,7 +584,6 @@ export async function getSettingsWithDefaults(): Promise<Settings> {
}
return toNormalizedSettings(settings);
}
export function saveSettings(settings: Settings): void {
try {
const normalizedSettings = toNormalizedSettings(settings);
@@ -441,14 +593,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 +608,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 +621,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;
+397 -95
View File
@@ -1,11 +1,19 @@
export const BASE_COLOR_NAMES = ["neutral", "stone", "zinc", "mauve", "olive", "mist", "taupe"] as const;
export const ACCENT_COLOR_NAMES = ["amber", "blue", "cyan", "emerald", "fuchsia", "green", "indigo", "lime", "orange", "pink", "purple", "red", "rose", "sky", "teal", "violet", "yellow"] as const;
export type BaseColorName = (typeof BASE_COLOR_NAMES)[number];
export type AccentColorName = (typeof ACCENT_COLOR_NAMES)[number];
export type ThemeName = BaseColorName | AccentColorName;
export interface Theme {
name: string;
name: ThemeName;
label: string;
cssVars: {
light: Record<string, string>;
dark: Record<string, string>;
};
}
export interface BaseColor extends Theme {
name: BaseColorName;
}
const baseLightColors: Record<string, string> = {
background: "oklch(1 0 0)",
foreground: "oklch(0.145 0 0)",
@@ -13,13 +21,15 @@ const baseLightColors: Record<string, string> = {
"card-foreground": "oklch(0.145 0 0)",
popover: "oklch(1 0 0)",
"popover-foreground": "oklch(0.145 0 0)",
secondary: "oklch(0.967 0.001 286.375)",
"secondary-foreground": "oklch(0.21 0.006 285.885)",
primary: "oklch(0.205 0 0)",
"primary-foreground": "oklch(0.985 0 0)",
secondary: "oklch(0.97 0 0)",
"secondary-foreground": "oklch(0.205 0 0)",
muted: "oklch(0.97 0 0)",
"muted-foreground": "oklch(0.556 0 0)",
accent: "oklch(0.97 0 0)",
"accent-foreground": "oklch(0.205 0 0)",
destructive: "oklch(0.58 0.22 27)",
destructive: "oklch(0.577 0.245 27.325)",
border: "oklch(0.922 0 0)",
input: "oklch(0.922 0 0)",
ring: "oklch(0.708 0 0)",
@@ -31,17 +41,280 @@ const baseDarkColors: Record<string, string> = {
"card-foreground": "oklch(0.985 0 0)",
popover: "oklch(0.205 0 0)",
"popover-foreground": "oklch(0.985 0 0)",
secondary: "oklch(0.274 0.006 286.033)",
primary: "oklch(0.922 0 0)",
"primary-foreground": "oklch(0.205 0 0)",
secondary: "oklch(0.269 0 0)",
"secondary-foreground": "oklch(0.985 0 0)",
muted: "oklch(0.269 0 0)",
"muted-foreground": "oklch(0.708 0 0)",
accent: "oklch(0.371 0 0)",
accent: "oklch(0.269 0 0)",
"accent-foreground": "oklch(0.985 0 0)",
destructive: "oklch(0.704 0.191 22.216)",
border: "oklch(1 0 0 / 10%)",
input: "oklch(1 0 0 / 15%)",
ring: "oklch(0.556 0 0)",
};
function createBaseColor(name: BaseColorName, label: string, cssVars: Theme["cssVars"]): BaseColor {
return { name, label, cssVars };
}
export const baseColors: BaseColor[] = [
createBaseColor("neutral", "Neutral", {
light: baseLightColors,
dark: baseDarkColors,
}),
createBaseColor("stone", "Stone", {
light: {
background: "oklch(1 0 0)",
foreground: "oklch(0.147 0.004 49.25)",
card: "oklch(1 0 0)",
"card-foreground": "oklch(0.147 0.004 49.25)",
popover: "oklch(1 0 0)",
"popover-foreground": "oklch(0.147 0.004 49.25)",
primary: "oklch(0.216 0.006 56.043)",
"primary-foreground": "oklch(0.985 0.001 106.423)",
secondary: "oklch(0.97 0.001 106.424)",
"secondary-foreground": "oklch(0.216 0.006 56.043)",
muted: "oklch(0.97 0.001 106.424)",
"muted-foreground": "oklch(0.553 0.013 58.071)",
accent: "oklch(0.97 0.001 106.424)",
"accent-foreground": "oklch(0.216 0.006 56.043)",
destructive: "oklch(0.577 0.245 27.325)",
border: "oklch(0.923 0.003 48.717)",
input: "oklch(0.923 0.003 48.717)",
ring: "oklch(0.709 0.01 56.259)",
},
dark: {
background: "oklch(0.147 0.004 49.25)",
foreground: "oklch(0.985 0.001 106.423)",
card: "oklch(0.216 0.006 56.043)",
"card-foreground": "oklch(0.985 0.001 106.423)",
popover: "oklch(0.216 0.006 56.043)",
"popover-foreground": "oklch(0.985 0.001 106.423)",
primary: "oklch(0.923 0.003 48.717)",
"primary-foreground": "oklch(0.216 0.006 56.043)",
secondary: "oklch(0.268 0.007 34.298)",
"secondary-foreground": "oklch(0.985 0.001 106.423)",
muted: "oklch(0.268 0.007 34.298)",
"muted-foreground": "oklch(0.709 0.01 56.259)",
accent: "oklch(0.268 0.007 34.298)",
"accent-foreground": "oklch(0.985 0.001 106.423)",
destructive: "oklch(0.704 0.191 22.216)",
border: "oklch(1 0 0 / 10%)",
input: "oklch(1 0 0 / 15%)",
ring: "oklch(0.553 0.013 58.071)",
},
}),
createBaseColor("zinc", "Zinc", {
light: {
background: "oklch(1 0 0)",
foreground: "oklch(0.141 0.005 285.823)",
card: "oklch(1 0 0)",
"card-foreground": "oklch(0.141 0.005 285.823)",
popover: "oklch(1 0 0)",
"popover-foreground": "oklch(0.141 0.005 285.823)",
primary: "oklch(0.21 0.006 285.885)",
"primary-foreground": "oklch(0.985 0 0)",
secondary: "oklch(0.967 0.001 286.375)",
"secondary-foreground": "oklch(0.21 0.006 285.885)",
muted: "oklch(0.967 0.001 286.375)",
"muted-foreground": "oklch(0.552 0.016 285.938)",
accent: "oklch(0.967 0.001 286.375)",
"accent-foreground": "oklch(0.21 0.006 285.885)",
destructive: "oklch(0.577 0.245 27.325)",
border: "oklch(0.92 0.004 286.32)",
input: "oklch(0.92 0.004 286.32)",
ring: "oklch(0.705 0.015 286.067)",
},
dark: {
background: "oklch(0.141 0.005 285.823)",
foreground: "oklch(0.985 0 0)",
card: "oklch(0.21 0.006 285.885)",
"card-foreground": "oklch(0.985 0 0)",
popover: "oklch(0.21 0.006 285.885)",
"popover-foreground": "oklch(0.985 0 0)",
primary: "oklch(0.92 0.004 286.32)",
"primary-foreground": "oklch(0.21 0.006 285.885)",
secondary: "oklch(0.274 0.006 286.033)",
"secondary-foreground": "oklch(0.985 0 0)",
muted: "oklch(0.274 0.006 286.033)",
"muted-foreground": "oklch(0.705 0.015 286.067)",
accent: "oklch(0.274 0.006 286.033)",
"accent-foreground": "oklch(0.985 0 0)",
destructive: "oklch(0.704 0.191 22.216)",
border: "oklch(1 0 0 / 10%)",
input: "oklch(1 0 0 / 15%)",
ring: "oklch(0.552 0.016 285.938)",
},
}),
createBaseColor("mauve", "Mauve", {
light: {
background: "oklch(1 0 0)",
foreground: "oklch(0.145 0.008 326)",
card: "oklch(1 0 0)",
"card-foreground": "oklch(0.145 0.008 326)",
popover: "oklch(1 0 0)",
"popover-foreground": "oklch(0.145 0.008 326)",
primary: "oklch(0.212 0.019 322.12)",
"primary-foreground": "oklch(0.985 0 0)",
secondary: "oklch(0.96 0.003 325.6)",
"secondary-foreground": "oklch(0.212 0.019 322.12)",
muted: "oklch(0.96 0.003 325.6)",
"muted-foreground": "oklch(0.542 0.034 322.5)",
accent: "oklch(0.96 0.003 325.6)",
"accent-foreground": "oklch(0.212 0.019 322.12)",
destructive: "oklch(0.577 0.245 27.325)",
border: "oklch(0.922 0.005 325.62)",
input: "oklch(0.922 0.005 325.62)",
ring: "oklch(0.711 0.019 323.02)",
},
dark: {
background: "oklch(0.145 0.008 326)",
foreground: "oklch(0.985 0 0)",
card: "oklch(0.212 0.019 322.12)",
"card-foreground": "oklch(0.985 0 0)",
popover: "oklch(0.212 0.019 322.12)",
"popover-foreground": "oklch(0.985 0 0)",
primary: "oklch(0.922 0.005 325.62)",
"primary-foreground": "oklch(0.212 0.019 322.12)",
secondary: "oklch(0.263 0.024 320.12)",
"secondary-foreground": "oklch(0.985 0 0)",
muted: "oklch(0.263 0.024 320.12)",
"muted-foreground": "oklch(0.711 0.019 323.02)",
accent: "oklch(0.263 0.024 320.12)",
"accent-foreground": "oklch(0.985 0 0)",
destructive: "oklch(0.704 0.191 22.216)",
border: "oklch(1 0 0 / 10%)",
input: "oklch(1 0 0 / 15%)",
ring: "oklch(0.542 0.034 322.5)",
},
}),
createBaseColor("olive", "Olive", {
light: {
background: "oklch(1 0 0)",
foreground: "oklch(0.153 0.006 107.1)",
card: "oklch(1 0 0)",
"card-foreground": "oklch(0.153 0.006 107.1)",
popover: "oklch(1 0 0)",
"popover-foreground": "oklch(0.153 0.006 107.1)",
primary: "oklch(0.228 0.013 107.4)",
"primary-foreground": "oklch(0.988 0.003 106.5)",
secondary: "oklch(0.966 0.005 106.5)",
"secondary-foreground": "oklch(0.228 0.013 107.4)",
muted: "oklch(0.966 0.005 106.5)",
"muted-foreground": "oklch(0.58 0.031 107.3)",
accent: "oklch(0.966 0.005 106.5)",
"accent-foreground": "oklch(0.228 0.013 107.4)",
destructive: "oklch(0.577 0.245 27.325)",
border: "oklch(0.93 0.007 106.5)",
input: "oklch(0.93 0.007 106.5)",
ring: "oklch(0.737 0.021 106.9)",
},
dark: {
background: "oklch(0.153 0.006 107.1)",
foreground: "oklch(0.988 0.003 106.5)",
card: "oklch(0.228 0.013 107.4)",
"card-foreground": "oklch(0.988 0.003 106.5)",
popover: "oklch(0.228 0.013 107.4)",
"popover-foreground": "oklch(0.988 0.003 106.5)",
primary: "oklch(0.93 0.007 106.5)",
"primary-foreground": "oklch(0.228 0.013 107.4)",
secondary: "oklch(0.286 0.016 107.4)",
"secondary-foreground": "oklch(0.988 0.003 106.5)",
muted: "oklch(0.286 0.016 107.4)",
"muted-foreground": "oklch(0.737 0.021 106.9)",
accent: "oklch(0.286 0.016 107.4)",
"accent-foreground": "oklch(0.988 0.003 106.5)",
destructive: "oklch(0.704 0.191 22.216)",
border: "oklch(1 0 0 / 10%)",
input: "oklch(1 0 0 / 15%)",
ring: "oklch(0.58 0.031 107.3)",
},
}),
createBaseColor("mist", "Mist", {
light: {
background: "oklch(1 0 0)",
foreground: "oklch(0.148 0.004 228.8)",
card: "oklch(1 0 0)",
"card-foreground": "oklch(0.148 0.004 228.8)",
popover: "oklch(1 0 0)",
"popover-foreground": "oklch(0.148 0.004 228.8)",
primary: "oklch(0.218 0.008 223.9)",
"primary-foreground": "oklch(0.987 0.002 197.1)",
secondary: "oklch(0.963 0.002 197.1)",
"secondary-foreground": "oklch(0.218 0.008 223.9)",
muted: "oklch(0.963 0.002 197.1)",
"muted-foreground": "oklch(0.56 0.021 213.5)",
accent: "oklch(0.963 0.002 197.1)",
"accent-foreground": "oklch(0.218 0.008 223.9)",
destructive: "oklch(0.577 0.245 27.325)",
border: "oklch(0.925 0.005 214.3)",
input: "oklch(0.925 0.005 214.3)",
ring: "oklch(0.723 0.014 214.4)",
},
dark: {
background: "oklch(0.148 0.004 228.8)",
foreground: "oklch(0.987 0.002 197.1)",
card: "oklch(0.218 0.008 223.9)",
"card-foreground": "oklch(0.987 0.002 197.1)",
popover: "oklch(0.218 0.008 223.9)",
"popover-foreground": "oklch(0.987 0.002 197.1)",
primary: "oklch(0.925 0.005 214.3)",
"primary-foreground": "oklch(0.218 0.008 223.9)",
secondary: "oklch(0.275 0.011 216.9)",
"secondary-foreground": "oklch(0.987 0.002 197.1)",
muted: "oklch(0.275 0.011 216.9)",
"muted-foreground": "oklch(0.723 0.014 214.4)",
accent: "oklch(0.275 0.011 216.9)",
"accent-foreground": "oklch(0.987 0.002 197.1)",
destructive: "oklch(0.704 0.191 22.216)",
border: "oklch(1 0 0 / 10%)",
input: "oklch(1 0 0 / 15%)",
ring: "oklch(0.56 0.021 213.5)",
},
}),
createBaseColor("taupe", "Taupe", {
light: {
background: "oklch(1 0 0)",
foreground: "oklch(0.147 0.004 49.3)",
card: "oklch(1 0 0)",
"card-foreground": "oklch(0.147 0.004 49.3)",
popover: "oklch(1 0 0)",
"popover-foreground": "oklch(0.147 0.004 49.3)",
primary: "oklch(0.214 0.009 43.1)",
"primary-foreground": "oklch(0.986 0.002 67.8)",
secondary: "oklch(0.96 0.002 17.2)",
"secondary-foreground": "oklch(0.214 0.009 43.1)",
muted: "oklch(0.96 0.002 17.2)",
"muted-foreground": "oklch(0.547 0.021 43.1)",
accent: "oklch(0.96 0.002 17.2)",
"accent-foreground": "oklch(0.214 0.009 43.1)",
destructive: "oklch(0.577 0.245 27.325)",
border: "oklch(0.922 0.005 34.3)",
input: "oklch(0.922 0.005 34.3)",
ring: "oklch(0.714 0.014 41.2)",
},
dark: {
background: "oklch(0.147 0.004 49.3)",
foreground: "oklch(0.986 0.002 67.8)",
card: "oklch(0.214 0.009 43.1)",
"card-foreground": "oklch(0.986 0.002 67.8)",
popover: "oklch(0.214 0.009 43.1)",
"popover-foreground": "oklch(0.986 0.002 67.8)",
primary: "oklch(0.922 0.005 34.3)",
"primary-foreground": "oklch(0.214 0.009 43.1)",
secondary: "oklch(0.268 0.011 36.5)",
"secondary-foreground": "oklch(0.986 0.002 67.8)",
muted: "oklch(0.268 0.011 36.5)",
"muted-foreground": "oklch(0.714 0.014 41.2)",
accent: "oklch(0.268 0.011 36.5)",
"accent-foreground": "oklch(0.986 0.002 67.8)",
destructive: "oklch(0.704 0.191 22.216)",
border: "oklch(1 0 0 / 10%)",
input: "oklch(1 0 0 / 15%)",
ring: "oklch(0.547 0.021 43.1)",
},
}),
];
interface PrimaryColors {
light: {
primary: string;
@@ -52,15 +325,15 @@ interface PrimaryColors {
"primary-foreground": string;
};
}
const primaryColors: Record<string, PrimaryColors> = {
const primaryColors: Record<AccentColorName, PrimaryColors> = {
amber: {
light: {
primary: "oklch(0.67 0.16 58)",
"primary-foreground": "oklch(0.99 0.02 95)",
primary: "oklch(0.555 0.163 48.998)",
"primary-foreground": "oklch(0.987 0.022 95.277)",
},
dark: {
primary: "oklch(0.77 0.16 70)",
"primary-foreground": "oklch(0.28 0.07 46)",
primary: "oklch(0.473 0.137 46.201)",
"primary-foreground": "oklch(0.987 0.022 95.277)",
},
},
blue: {
@@ -69,157 +342,147 @@ const primaryColors: Record<string, PrimaryColors> = {
"primary-foreground": "oklch(0.97 0.014 254.604)",
},
dark: {
primary: "oklch(0.42 0.18 266)",
primary: "oklch(0.424 0.199 265.638)",
"primary-foreground": "oklch(0.97 0.014 254.604)",
},
},
cyan: {
light: {
primary: "oklch(0.61 0.11 222)",
"primary-foreground": "oklch(0.98 0.02 201)",
primary: "oklch(0.52 0.105 223.128)",
"primary-foreground": "oklch(0.984 0.019 200.873)",
},
dark: {
primary: "oklch(0.71 0.13 215)",
"primary-foreground": "oklch(0.30 0.05 230)",
primary: "oklch(0.45 0.085 224.283)",
"primary-foreground": "oklch(0.984 0.019 200.873)",
},
},
emerald: {
light: {
primary: "oklch(0.60 0.13 163)",
"primary-foreground": "oklch(0.98 0.02 166)",
primary: "oklch(0.508 0.118 165.612)",
"primary-foreground": "oklch(0.979 0.021 166.113)",
},
dark: {
primary: "oklch(0.70 0.15 162)",
"primary-foreground": "oklch(0.26 0.05 173)",
primary: "oklch(0.432 0.095 166.913)",
"primary-foreground": "oklch(0.979 0.021 166.113)",
},
},
fuchsia: {
light: {
primary: "oklch(0.59 0.26 323)",
"primary-foreground": "oklch(0.98 0.02 320)",
primary: "oklch(0.518 0.253 323.949)",
"primary-foreground": "oklch(0.977 0.017 320.058)",
},
dark: {
primary: "oklch(0.67 0.26 322)",
"primary-foreground": "oklch(0.98 0.02 320)",
primary: "oklch(0.452 0.211 324.591)",
"primary-foreground": "oklch(0.977 0.017 320.058)",
},
},
green: {
light: {
primary: "oklch(0.648 0.2 131.684)",
"primary-foreground": "oklch(0.986 0.031 120.757)",
primary: "oklch(0.527 0.154 150.069)",
"primary-foreground": "oklch(0.982 0.018 155.826)",
},
dark: {
primary: "oklch(0.648 0.2 131.684)",
"primary-foreground": "oklch(0.986 0.031 120.757)",
primary: "oklch(0.448 0.119 151.328)",
"primary-foreground": "oklch(0.982 0.018 155.826)",
},
},
indigo: {
light: {
primary: "oklch(0.51 0.23 277)",
"primary-foreground": "oklch(0.96 0.02 272)",
primary: "oklch(0.457 0.24 277.023)",
"primary-foreground": "oklch(0.962 0.018 272.314)",
},
dark: {
primary: "oklch(0.59 0.20 277)",
"primary-foreground": "oklch(0.96 0.02 272)",
primary: "oklch(0.398 0.195 277.366)",
"primary-foreground": "oklch(0.962 0.018 272.314)",
},
},
lime: {
light: {
primary: "oklch(0.65 0.18 132)",
"primary-foreground": "oklch(0.99 0.03 121)",
primary: "oklch(0.841 0.238 128.85)",
"primary-foreground": "oklch(0.405 0.101 131.063)",
},
dark: {
primary: "oklch(0.77 0.20 131)",
"primary-foreground": "oklch(0.27 0.07 132)",
},
},
neutral: {
light: {
primary: "oklch(0.205 0 0)",
"primary-foreground": "oklch(0.985 0 0)",
},
dark: {
primary: "oklch(0.922 0 0)",
"primary-foreground": "oklch(0.205 0 0)",
primary: "oklch(0.768 0.233 130.85)",
"primary-foreground": "oklch(0.405 0.101 131.063)",
},
},
orange: {
light: {
primary: "oklch(0.646 0.222 41.116)",
primary: "oklch(0.553 0.195 38.402)",
"primary-foreground": "oklch(0.98 0.016 73.684)",
},
dark: {
primary: "oklch(0.705 0.213 47.604)",
primary: "oklch(0.47 0.157 37.304)",
"primary-foreground": "oklch(0.98 0.016 73.684)",
},
},
pink: {
light: {
primary: "oklch(0.59 0.22 1)",
"primary-foreground": "oklch(0.97 0.01 343)",
primary: "oklch(0.525 0.223 3.958)",
"primary-foreground": "oklch(0.971 0.014 343.198)",
},
dark: {
primary: "oklch(0.66 0.21 354)",
"primary-foreground": "oklch(0.97 0.01 343)",
primary: "oklch(0.459 0.187 3.815)",
"primary-foreground": "oklch(0.971 0.014 343.198)",
},
},
purple: {
light: {
primary: "oklch(0.56 0.25 302)",
"primary-foreground": "oklch(0.98 0.01 308)",
primary: "oklch(0.496 0.265 301.924)",
"primary-foreground": "oklch(0.977 0.014 308.299)",
},
dark: {
primary: "oklch(0.63 0.23 304)",
"primary-foreground": "oklch(0.98 0.01 308)",
primary: "oklch(0.438 0.218 303.724)",
"primary-foreground": "oklch(0.977 0.014 308.299)",
},
},
red: {
light: {
primary: "oklch(0.577 0.245 27.325)",
primary: "oklch(0.505 0.213 27.518)",
"primary-foreground": "oklch(0.971 0.013 17.38)",
},
dark: {
primary: "oklch(0.637 0.237 25.331)",
primary: "oklch(0.444 0.177 26.899)",
"primary-foreground": "oklch(0.971 0.013 17.38)",
},
},
rose: {
light: {
primary: "oklch(0.586 0.253 17.585)",
primary: "oklch(0.514 0.222 16.935)",
"primary-foreground": "oklch(0.969 0.015 12.422)",
},
dark: {
primary: "oklch(0.645 0.246 16.439)",
primary: "oklch(0.455 0.188 13.697)",
"primary-foreground": "oklch(0.969 0.015 12.422)",
},
},
sky: {
light: {
primary: "oklch(0.59 0.14 242)",
"primary-foreground": "oklch(0.98 0.01 237)",
primary: "oklch(0.5 0.134 242.749)",
"primary-foreground": "oklch(0.977 0.013 236.62)",
},
dark: {
primary: "oklch(0.68 0.15 237)",
"primary-foreground": "oklch(0.29 0.06 243)",
primary: "oklch(0.443 0.11 240.79)",
"primary-foreground": "oklch(0.977 0.013 236.62)",
},
},
teal: {
light: {
primary: "oklch(0.60 0.10 185)",
"primary-foreground": "oklch(0.98 0.01 181)",
primary: "oklch(0.511 0.096 186.391)",
"primary-foreground": "oklch(0.984 0.014 180.72)",
},
dark: {
primary: "oklch(0.70 0.12 183)",
"primary-foreground": "oklch(0.28 0.04 193)",
primary: "oklch(0.437 0.078 188.216)",
"primary-foreground": "oklch(0.984 0.014 180.72)",
},
},
violet: {
light: {
primary: "oklch(0.541 0.281 293.009)",
primary: "oklch(0.491 0.27 292.581)",
"primary-foreground": "oklch(0.969 0.016 293.756)",
},
dark: {
primary: "oklch(0.606 0.25 292.717)",
primary: "oklch(0.432 0.232 292.759)",
"primary-foreground": "oklch(0.969 0.016 293.756)",
},
},
@@ -234,38 +497,77 @@ const primaryColors: Record<string, PrimaryColors> = {
},
},
};
function createTheme(name: string, label: string, primary: PrimaryColors): Theme {
const coloredThemeLightColors: Record<string, string> = {
secondary: "oklch(0.967 0.001 286.375)",
"secondary-foreground": "oklch(0.21 0.006 285.885)",
};
const coloredThemeDarkColors: Record<string, string> = {
secondary: "oklch(0.274 0.006 286.033)",
"secondary-foreground": "oklch(0.985 0 0)",
};
function createAccentTheme(name: AccentColorName, label: string, primary: PrimaryColors): Theme {
return {
name,
label,
cssVars: {
light: { ...baseLightColors, ...primary.light },
dark: { ...baseDarkColors, ...primary.dark },
light: { ...coloredThemeLightColors, ...primary.light },
dark: { ...coloredThemeDarkColors, ...primary.dark },
},
};
}
export const themes: Theme[] = [
createTheme("amber", "Amber", primaryColors.amber),
createTheme("blue", "Blue", primaryColors.blue),
createTheme("cyan", "Cyan", primaryColors.cyan),
createTheme("emerald", "Emerald", primaryColors.emerald),
createTheme("fuchsia", "Fuchsia", primaryColors.fuchsia),
createTheme("green", "Green", primaryColors.green),
createTheme("indigo", "Indigo", primaryColors.indigo),
createTheme("lime", "Lime", primaryColors.lime),
createTheme("neutral", "Neutral", primaryColors.neutral),
createTheme("orange", "Orange", primaryColors.orange),
createTheme("pink", "Pink", primaryColors.pink),
createTheme("purple", "Purple", primaryColors.purple),
createTheme("red", "Red", primaryColors.red),
createTheme("rose", "Rose", primaryColors.rose),
createTheme("sky", "Sky", primaryColors.sky),
createTheme("teal", "Teal", primaryColors.teal),
createTheme("violet", "Violet", primaryColors.violet),
createTheme("yellow", "Yellow", primaryColors.yellow),
].sort((a, b) => a.name.localeCompare(b.name));
export function applyTheme(themeName: string) {
const theme = themes.find((t) => t.name === themeName) || themes[0];
const accentThemes: Theme[] = [
createAccentTheme("amber", "Amber", primaryColors.amber),
createAccentTheme("blue", "Blue", primaryColors.blue),
createAccentTheme("cyan", "Cyan", primaryColors.cyan),
createAccentTheme("emerald", "Emerald", primaryColors.emerald),
createAccentTheme("fuchsia", "Fuchsia", primaryColors.fuchsia),
createAccentTheme("green", "Green", primaryColors.green),
createAccentTheme("indigo", "Indigo", primaryColors.indigo),
createAccentTheme("lime", "Lime", primaryColors.lime),
createAccentTheme("orange", "Orange", primaryColors.orange),
createAccentTheme("pink", "Pink", primaryColors.pink),
createAccentTheme("purple", "Purple", primaryColors.purple),
createAccentTheme("red", "Red", primaryColors.red),
createAccentTheme("rose", "Rose", primaryColors.rose),
createAccentTheme("sky", "Sky", primaryColors.sky),
createAccentTheme("teal", "Teal", primaryColors.teal),
createAccentTheme("violet", "Violet", primaryColors.violet),
createAccentTheme("yellow", "Yellow", primaryColors.yellow),
];
export function normalizeBaseColorName(baseColorName: unknown): BaseColorName {
return typeof baseColorName === "string" && BASE_COLOR_NAMES.includes(baseColorName as BaseColorName)
? baseColorName as BaseColorName
: "neutral";
}
const themesByBaseColor = Object.fromEntries(baseColors.map((baseColor) => [
baseColor.name,
[
baseColor,
...accentThemes.map((accentTheme) => ({
...accentTheme,
cssVars: {
light: { ...baseColor.cssVars.light, ...accentTheme.cssVars.light },
dark: { ...baseColor.cssVars.dark, ...accentTheme.cssVars.dark },
},
})),
],
])) as Record<BaseColorName, Theme[]>;
export function getThemesForBaseColor(baseColorName: unknown): Theme[] {
return themesByBaseColor[normalizeBaseColorName(baseColorName)];
}
export function normalizeThemeName(themeName: unknown, baseColorName: unknown): ThemeName {
const normalizedBaseColor = normalizeBaseColorName(baseColorName);
const availableThemes = getThemesForBaseColor(normalizedBaseColor);
return typeof themeName === "string" && availableThemes.some((theme) => theme.name === themeName)
? themeName as ThemeName
: normalizedBaseColor;
}
export const themes = getThemesForBaseColor("neutral");
export function applyTheme(themeName: unknown, baseColorName: unknown = "neutral") {
const normalizedBaseColor = normalizeBaseColorName(baseColorName);
const availableThemes = getThemesForBaseColor(normalizedBaseColor);
const normalizedTheme = normalizeThemeName(themeName, normalizedBaseColor);
const theme = availableThemes.find((candidate) => candidate.name === normalizedTheme) || availableThemes[0];
const root = document.documentElement;
const isDark = root.classList.contains("dark");
const vars = isDark ? theme.cssVars.dark : theme.cssVars.light;
+64
View File
@@ -20,3 +20,67 @@ export function compareVersionNumbers(left: string, right: string) {
}
return 0;
}
interface ParsedVersion {
core: number[];
prerelease: Array<number | string>;
}
const VERSION_IDENTIFIER_PATTERN = /^[0-9A-Za-z-]+$/;
function parseVersion(value: string): ParsedVersion | null {
let normalized = value.trim().replace(/^v/i, "");
if (!normalized)
return null;
const buildIndex = normalized.indexOf("+");
if (buildIndex >= 0) {
const build = normalized.slice(buildIndex + 1);
if (!build || build.split(".").some((identifier) => !VERSION_IDENTIFIER_PATTERN.test(identifier)))
return null;
normalized = normalized.slice(0, buildIndex);
}
const prereleaseIndex = normalized.indexOf("-");
const corePart = prereleaseIndex >= 0 ? normalized.slice(0, prereleaseIndex) : normalized;
const prereleasePart = prereleaseIndex >= 0 ? normalized.slice(prereleaseIndex + 1) : "";
const coreIdentifiers = corePart.split(".");
if (coreIdentifiers.length === 0 || coreIdentifiers.some((identifier) => !/^\d+$/.test(identifier)))
return null;
const core = coreIdentifiers.map(Number);
if (core.some((identifier) => !Number.isSafeInteger(identifier)))
return null;
if (prereleaseIndex >= 0 && (!prereleasePart || prereleasePart.split(".").some((identifier) => !VERSION_IDENTIFIER_PATTERN.test(identifier))))
return null;
const prerelease = prereleasePart
? prereleasePart.split(".").map((identifier) => /^\d+$/.test(identifier) ? Number(identifier) : identifier)
: [];
return { core, prerelease };
}
export function isNewerVersion(latestValue: string, currentValue: string): boolean {
const latest = parseVersion(latestValue);
const current = parseVersion(currentValue);
if (!latest || !current)
return false;
for (let i = 0; i < Math.max(latest.core.length, current.core.length); i++) {
const latestIdentifier = latest.core[i] ?? 0;
const currentIdentifier = current.core[i] ?? 0;
if (latestIdentifier !== currentIdentifier)
return latestIdentifier > currentIdentifier;
}
if (latest.prerelease.length === 0 || current.prerelease.length === 0)
return latest.prerelease.length === 0 && current.prerelease.length > 0;
for (let i = 0; i < Math.max(latest.prerelease.length, current.prerelease.length); i++) {
const latestIdentifier = latest.prerelease[i];
const currentIdentifier = current.prerelease[i];
if (latestIdentifier === undefined)
return false;
if (currentIdentifier === undefined)
return true;
if (latestIdentifier === currentIdentifier)
continue;
const latestIsNumber = typeof latestIdentifier === "number";
const currentIsNumber = typeof currentIdentifier === "number";
if (latestIsNumber && currentIsNumber)
return latestIdentifier > currentIdentifier;
if (latestIsNumber !== currentIsNumber)
return !latestIsNumber;
return latestIdentifier > currentIdentifier;
}
return false;
}
+21
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,16 +30,21 @@ 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;
author_username?: string;
author_name?: string;
}
export interface ExtractMetadata {
new_entries: number;
@@ -63,7 +82,9 @@ export interface DateRangeRequest {
}
export interface Settings {
downloadPath: string;
baseColor: string;
theme: string;
themeMode: "auto" | "light" | "dark";
sfxEnabled: boolean;
showUpdateNotifications: boolean;
}
+1
View File
@@ -1,5 +1,6 @@
{
"compilerOptions": {
"ignoreDeprecations": "6.0",
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "ES2022",
"useDefineForClassFields": true,
+3
View File
@@ -8,6 +8,9 @@ const wailsJson = JSON.parse(fs.readFileSync(wailsJsonPath, "utf-8"));
const appVersion = wailsJson.info.productVersion;
export default defineConfig({
plugins: [react(), tailwindcss()],
build: {
target: "safari15",
},
resolve: {
alias: {
"@": path.resolve(__dirname, "./src"),
+4
View File
@@ -31,10 +31,14 @@ 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>;
export function ExportFailedLogs(arg1:string):Promise<string>;
export function ExtractDateRange(arg1:main.DateRangeRequest):Promise<string>;
export function ExtractTimeline(arg1:main.TimelineRequest):Promise<string>;
+8
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);
}
@@ -66,6 +70,10 @@ export function ExportAccountsTXT(arg1, arg2) {
return window['go']['main']['App']['ExportAccountsTXT'](arg1, arg2);
}
export function ExportFailedLogs(arg1) {
return window['go']['main']['App']['ExportFailedLogs'](arg1);
}
export function ExtractDateRange(arg1) {
return window['go']['main']['App']['ExtractDateRange'](arg1);
}
+56
View File
@@ -139,6 +139,9 @@ export namespace main {
skip_existing: boolean;
delete_incomplete_files: boolean;
retry_attempts?: number;
download_speed_limit_kbps?: number;
download_delay_ms?: number;
download_delay_jitter_ms?: number;
proxy?: string;
static createFrom(source: any = {}) {
@@ -154,6 +157,9 @@ export namespace main {
this.skip_existing = source["skip_existing"];
this.delete_incomplete_files = source["delete_incomplete_files"];
this.retry_attempts = source["retry_attempts"];
this.download_speed_limit_kbps = source["download_speed_limit_kbps"];
this.download_delay_ms = source["download_delay_ms"];
this.download_delay_jitter_ms = source["download_delay_jitter_ms"];
this.proxy = source["proxy"];
}
}
@@ -187,6 +193,7 @@ export namespace main {
content?: string;
original_filename?: string;
author_username?: string;
account_name?: string;
static createFrom(source: any = {}) {
return new MediaItemRequest(source);
@@ -201,6 +208,7 @@ export namespace main {
this.content = source["content"];
this.original_filename = source["original_filename"];
this.author_username = source["author_username"];
this.account_name = source["account_name"];
}
}
export class DownloadMediaWithMetadataRequest {
@@ -211,7 +219,15 @@ export namespace main {
skip_existing: boolean;
delete_incomplete_files: boolean;
retry_attempts?: number;
download_speed_limit_kbps?: number;
download_delay_ms?: number;
download_delay_jitter_ms?: number;
proxy?: string;
filename_template?: string;
folder_template?: string;
auto_convert_gifs?: boolean;
gif_quality?: string;
gif_resolution?: string;
static createFrom(source: any = {}) {
return new DownloadMediaWithMetadataRequest(source);
@@ -226,7 +242,15 @@ export namespace main {
this.skip_existing = source["skip_existing"];
this.delete_incomplete_files = source["delete_incomplete_files"];
this.retry_attempts = source["retry_attempts"];
this.download_speed_limit_kbps = source["download_speed_limit_kbps"];
this.download_delay_ms = source["download_delay_ms"];
this.download_delay_jitter_ms = source["download_delay_jitter_ms"];
this.proxy = source["proxy"];
this.filename_template = source["filename_template"];
this.folder_template = source["folder_template"];
this.auto_convert_gifs = source["auto_convert_gifs"];
this.gif_quality = source["gif_quality"];
this.gif_resolution = source["gif_resolution"];
}
convertValues(a: any, classs: any, asMap: boolean = false): any {
@@ -247,6 +271,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 +317,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 +338,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"];
}
}
+13 -13
View File
@@ -3,9 +3,9 @@ module twitterxmediabatchdownloader
go 1.25.4
require (
github.com/wailsapp/wails/v2 v2.12.0
github.com/wailsapp/wails/v2 v2.13.0
github.com/zalando/go-keyring v0.2.8
modernc.org/sqlite v1.50.1
modernc.org/sqlite v1.56.0
)
require (
@@ -18,30 +18,30 @@ require (
github.com/google/uuid v1.6.0 // indirect
github.com/gorilla/websocket v1.5.3 // indirect
github.com/jchv/go-winloader v0.0.0-20250406163304-c1995be93bd1 // indirect
github.com/labstack/echo/v4 v4.13.4 // indirect
github.com/labstack/gommon v0.4.2 // indirect
github.com/labstack/echo/v4 v4.15.4 // indirect
github.com/labstack/gommon v0.5.0 // indirect
github.com/leaanthony/go-ansi-parser v1.6.1 // indirect
github.com/leaanthony/gosod v1.0.4 // indirect
github.com/leaanthony/slicer v1.6.0 // indirect
github.com/leaanthony/u v1.1.1 // indirect
github.com/mattn/go-colorable v0.1.14 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mattn/go-colorable v0.1.15 // indirect
github.com/mattn/go-isatty v0.0.24 // indirect
github.com/ncruces/go-strftime v1.0.0 // indirect
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
github.com/rivo/uniseg v0.4.7 // indirect
github.com/samber/lo v1.52.0 // indirect
github.com/samber/lo v1.53.0 // indirect
github.com/tkrajina/go-reflector v0.5.8 // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect
github.com/valyala/fasttemplate v1.2.2 // indirect
github.com/wailsapp/go-webview2 v1.0.23 // indirect
github.com/wailsapp/mimetype v1.4.1 // indirect
golang.org/x/crypto v0.45.0 // indirect
golang.org/x/net v0.47.0 // indirect
golang.org/x/sys v0.42.0 // indirect
golang.org/x/text v0.31.0 // indirect
modernc.org/libc v1.72.3 // indirect
golang.org/x/crypto v0.55.0 // indirect
golang.org/x/net v0.58.0 // indirect
golang.org/x/sys v0.47.0 // indirect
golang.org/x/text v0.41.0 // indirect
modernc.org/libc v1.75.3 // indirect
modernc.org/mathutil v1.7.1 // indirect
modernc.org/memory v1.11.0 // indirect
modernc.org/memory v1.12.0 // indirect
)
+40 -41
View File
@@ -12,8 +12,8 @@ github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE=
github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78=
github.com/godbus/dbus/v5 v5.2.2 h1:TUR3TgtSVDmjiXOgAAyaZbYmIeP3DPkld3jgKGV8mXQ=
github.com/godbus/dbus/v5 v5.2.2/go.mod h1:3AAv2+hPq5rdnr5txxxRwiGjPXamgoIHgz9FPBfOp3c=
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs=
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA=
github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3 h1:LMLX+LgTNWpfvCBdFebv6EsYotImrt/Ppc5cXIriCSo=
github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3/go.mod h1:jl5iWTm0/hd5PjEYEOuwAJ57L/CibdZfrqZ5XA5GrCk=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
@@ -22,10 +22,10 @@ github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
github.com/jchv/go-winloader v0.0.0-20250406163304-c1995be93bd1 h1:njuLRcjAuMKr7kI3D85AXWkw6/+v9PwtV6M6o11sWHQ=
github.com/jchv/go-winloader v0.0.0-20250406163304-c1995be93bd1/go.mod h1:alcuEEnZsY1WQsagKhZDsoPCRoOijYqhZvPwLG0kzVs=
github.com/labstack/echo/v4 v4.13.4 h1:oTZZW+T3s9gAu5L8vmzihV7/lkXGZuITzTQkTEhcXEA=
github.com/labstack/echo/v4 v4.13.4/go.mod h1:g63b33BZ5vZzcIUF8AtRH40DrTlXnx4UMC8rBdndmjQ=
github.com/labstack/gommon v0.4.2 h1:F8qTUNXgG1+6WQmqoUWnz8WiEU60mXVVw0P4ht1WRA0=
github.com/labstack/gommon v0.4.2/go.mod h1:QlUFxVM+SNXhDL/Z7YhocGIBYOiwB0mXm1+1bAPHPyU=
github.com/labstack/echo/v4 v4.15.4 h1:DL45vVYa+BWE+XuW+zZNd9H0YEdZ80UAWJGcTVW4EVs=
github.com/labstack/echo/v4 v4.15.4/go.mod h1:CuMetKIRwsuO/qlAgMq+KTAalwGoB/h4tC+yPdrTj1g=
github.com/labstack/gommon v0.5.0 h1:6VSQ2NOzsnEJ5W6+84E0RbcaDDmgB6NIAzWCczTEe6c=
github.com/labstack/gommon v0.5.0/go.mod h1:Rzlg7HHy1maLfzBYGg9NZcVuz1sA68HHhLjhcEllYE0=
github.com/leaanthony/debme v1.2.1 h1:9Tgwf+kjcrbMQ4WnPcEIUcQuIZYqdWftzZkBr+i/oOc=
github.com/leaanthony/debme v1.2.1/go.mod h1:3V+sCm5tYAgQymvSOfYQ5Xx2JCr+OXiD9Jkw3otUjiA=
github.com/leaanthony/go-ansi-parser v1.6.1 h1:xd8bzARK3dErqkPFtoF9F3/HgN8UQk0ed1YDKpEz01A=
@@ -39,10 +39,10 @@ github.com/leaanthony/u v1.1.1/go.mod h1:9+o6hejoRljvZ3BzdYlVL0JYCwtnAsVuN9pVTQc
github.com/matryer/is v1.4.0/go.mod h1:8I/i5uYgLzgsgEloJE1U6xx5HkBQpAZvepWuujKwMRU=
github.com/matryer/is v1.4.1 h1:55ehd8zaGABKLXQUe2awZ99BD/PTc2ls+KV/dXphgEQ=
github.com/matryer/is v1.4.1/go.mod h1:8I/i5uYgLzgsgEloJE1U6xx5HkBQpAZvepWuujKwMRU=
github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=
github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-colorable v0.1.15 h1:+u9SLTRGnXv73cEsnsmoZBom+dMU88B2M0aDcWy0/jY=
github.com/mattn/go-colorable v0.1.15/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI=
github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=
github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ=
@@ -56,8 +56,8 @@ github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qq
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
github.com/samber/lo v1.52.0 h1:Rvi+3BFHES3A8meP33VPAxiBZX/Aws5RxrschYGjomw=
github.com/samber/lo v1.52.0/go.mod h1:4+MXEGsJzbKGaUEQFKBq2xtfuznW9oz/WrgyzMzRoM0=
github.com/samber/lo v1.53.0 h1:t975lj2py4kJPQ6haz1QMgtId2gtmfktACxIXArw3HM=
github.com/samber/lo v1.53.0/go.mod h1:4+MXEGsJzbKGaUEQFKBq2xtfuznW9oz/WrgyzMzRoM0=
github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY=
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
@@ -72,59 +72,58 @@ github.com/wailsapp/go-webview2 v1.0.23 h1:jmv8qhz1lHibCc79bMM/a/FqOnnzOGEisLav+
github.com/wailsapp/go-webview2 v1.0.23/go.mod h1:qJmWAmAmaniuKGZPWwne+uor3AHMB5PFhqiK0Bbj8kc=
github.com/wailsapp/mimetype v1.4.1 h1:pQN9ycO7uo4vsUUuPeHEYoUkLVkaRntMnHJxVwYhwHs=
github.com/wailsapp/mimetype v1.4.1/go.mod h1:9aV5k31bBOv5z6u+QP8TltzvNGJPmNJD4XlAL3U+j3o=
github.com/wailsapp/wails/v2 v2.12.0 h1:BHO/kLNWFHYjCzucxbzAYZWUjub1Tvb4cSguQozHn5c=
github.com/wailsapp/wails/v2 v2.12.0/go.mod h1:mo1bzK1DEJrobt7YrBjgxvb5Sihb1mhAY09hppbibQg=
github.com/wailsapp/wails/v2 v2.13.0 h1:S7OgXWpj72V91unF8iDWJKbcS9ZpwCT3R0QVru4v2Mg=
github.com/wailsapp/wails/v2 v2.13.0/go.mod h1:nVr/wSIEZ7xxKPkzK65mjpKpaOPQI2k4pvLwGR/i4kc=
github.com/zalando/go-keyring v0.2.8 h1:6sD/Ucpl7jNq10rM2pgqTs0sZ9V3qMrqfIIy5YPccHs=
github.com/zalando/go-keyring v0.2.8/go.mod h1:tsMo+VpRq5NGyKfxoBVjCuMrG47yj8cmakZDO5QGii0=
golang.org/x/crypto v0.45.0 h1:jMBrvKuj23MTlT0bQEOBcAE0mjg8mK9RXFhRH6nyF3Q=
golang.org/x/crypto v0.45.0/go.mod h1:XTGrrkGJve7CYK7J8PEww4aY7gM3qMCElcJQ8n8JdX4=
golang.org/x/mod v0.33.0 h1:tHFzIWbBifEmbwtGz65eaWyGiGZatSrT9prnU8DbVL8=
golang.org/x/mod v0.33.0/go.mod h1:swjeQEj+6r7fODbD2cqrnje9PnziFuw4bmLbBZFrQ5w=
golang.org/x/crypto v0.55.0 h1:+KWHjbgOaAQ66dh/YlkZKHlz9ZUlq61AFirAR9ntP8M=
golang.org/x/crypto v0.55.0/go.mod h1:uq0V9dE/fzQuJtbnL+2EhWOE63vo164FY8xqEnV9xis=
golang.org/x/mod v0.38.0 h1:MECBjubtXD7yj4HrhIUcywNaGeNVUdfVnxmPajOk4yk=
golang.org/x/mod v0.38.0/go.mod h1:V6Xz0pq8TQ3dGqVQ1FVHuelZpAL0uNhSkk9ogYP3c40=
golang.org/x/net v0.0.0-20210505024714-0287a6fb4125/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY=
golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU=
golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/net v0.58.0 h1:ynWG7rqYi4ccpTEuPZ2QGWHktVEM9DMCj9yzDE0Q7To=
golang.org/x/net v0.58.0/go.mod h1:YwCddHnFlT7eLQqVprV19OnhLGtc5xOKgE0RyqgfWAU=
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.0.0-20200810151505-1b9f1253b3ed/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=
golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.31.0 h1:aC8ghyu4JhP8VojJ2lEHBnochRno1sgL6nEi9WGFGMM=
golang.org/x/text v0.31.0/go.mod h1:tKRAlv61yKIjGGHX/4tP1LTbc13YSec1pxVEWXzfoeM=
golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8=
golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.42.0 h1:uNgphsn75Tdz5Ji2q36v/nsFSfR/9BRFvqhGBaJGd5k=
golang.org/x/tools v0.42.0/go.mod h1:Ma6lCIwGZvHK6XtgbswSoWroEkhugApmsXyrUmBhfr0=
golang.org/x/tools v0.48.0 h1:3+hClM1aLL5mjMKm5ovokw9epgRXPuu2tILgismM6RE=
golang.org/x/tools v0.48.0/go.mod h1:08xX0orndb/F7jJxGDicx061tyd5pcMto75YMAXr6lk=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
modernc.org/cc/v4 v4.28.2 h1:3tQ0lf2ADtoby2EtSP+J7IE2SHwEJdP8ioR59wx7XpY=
modernc.org/cc/v4 v4.28.2/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI=
modernc.org/ccgo/v4 v4.34.0 h1:yRLPFZieg532OT4rp4JFNIVcquwalMX26G95WQDqwCQ=
modernc.org/ccgo/v4 v4.34.0/go.mod h1:AS5WYMyBakQ+fhsHhtP8mWB82KTGPkNNJDGfGQCe0/A=
modernc.org/cc/v4 v4.29.2 h1:h6+9ciCnPKutf4I03CvheAvDLX7+IHlqR6Iy6J+cgd8=
modernc.org/cc/v4 v4.29.2/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI=
modernc.org/ccgo/v4 v4.35.0 h1:F+TUsmw09QxLzmi3aeYYGxjAXarmZaKgj3mKQHNaA8w=
modernc.org/ccgo/v4 v4.35.0/go.mod h1:qrVGs9S3Sr2Ztcg9ve+kTAYMp5a3YvWjo+SoN06kJ5I=
modernc.org/fileutil v1.4.0 h1:j6ZzNTftVS054gi281TyLjHPp6CPHr2KCxEXjEbD6SM=
modernc.org/fileutil v1.4.0/go.mod h1:EqdKFDxiByqxLk8ozOxObDSfcVOv/54xDs/DUHdvCUU=
modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI=
modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito=
modernc.org/gc/v3 v3.1.2 h1:ZtDCnhonXSZexk/AYsegNRV1lJGgaNZJuKjJSWKyEqo=
modernc.org/gc/v3 v3.1.2/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY=
modernc.org/gc/v3 v3.1.5 h1:21ldfPfRYE31Tb7B3mwAK8gy1AxP4+dKjrOQPfqakoc=
modernc.org/gc/v3 v3.1.5/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY=
modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks=
modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI=
modernc.org/libc v1.72.3 h1:ZnDF4tXn4NBXFutMMQC4vtbTFSXhhKzR73fv0beZEAU=
modernc.org/libc v1.72.3/go.mod h1:dn0dZNnnn1clLyvRxLxYExxiKRZIRENOfqQ8XEeg4Qs=
modernc.org/libc v1.75.3 h1:vCqT5+R0jPXMnvMkGo0T2zXvFNth+lYXVCx5X7CCX/g=
modernc.org/libc v1.75.3/go.mod h1:MjAX68G+0oufI+hNuh0QXcK+Ap+sL8bNPPcIC6EqOfo=
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI=
modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
modernc.org/memory v1.12.0 h1:twkmYNkGXCvtYWzoux02jtK6eovjZbdI0uHFUYp6kuU=
modernc.org/memory v1.12.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
modernc.org/opt v0.2.0 h1:tGyef5ApycA7FSEOMraay9SaTk5zmbx7Tu+cJs4QKZg=
modernc.org/opt v0.2.0/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=
modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=
modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=
modernc.org/sqlite v1.50.1 h1:l+cQvn0sd0zJJtfygGHuQJ5AjlrwXmWPw4KP3ZMwr9w=
modernc.org/sqlite v1.50.1/go.mod h1:tcNzv5p84E0skkmJn038y+hWJbLQXQqEnQfeh5r2JLM=
modernc.org/sqlite v1.56.0 h1:/D8e2RfFqoy/Zc6PuC76U28zFwmI/sYx1Kjm4yEn9e0=
modernc.org/sqlite v1.56.0/go.mod h1:yCJ2cmAaIkHQ25oXWrF8H4O1lIfPYPR26yCEDj2P3pQ=
modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=
modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
+2 -2
View File
@@ -2,7 +2,7 @@
"$schema": "https://wails.io/schemas/config.v2.json",
"name": "TwitterXMediaBatchDownloader",
"outputfilename": "TwitterXMediaBatchDownloader",
"frontend:install": "pnpm install",
"frontend:install": "pnpm install --frozen-lockfile",
"frontend:build": "pnpm run build",
"frontend:dev:watcher": "pnpm run dev",
"frontend:dev:serverUrl": "auto",
@@ -11,7 +11,7 @@
},
"info": {
"productName": "Twitter/X Media Batch Downloader",
"productVersion": "4.6"
"productVersion": "5.0.1"
},
"wailsjsdir": "./frontend",
"assetdir": "./frontend/dist",