Compare commits

...
15 Commits
Author SHA1 Message Date
afkarxyz 2ada5da9bf v4.9 2026-07-16 18:27:23 +07:00
afkarxyz 3fb8bda2ff Update README 2026-07-15 12:26:49 +07:00
asdfghjkkly b4dfb75f5b Fix group editing and skip existing downloads (#105) 2026-07-12 10:59:29 +07:00
afkarxyz 7e584aff2c Update README 2026-07-12 10:58:42 +07:00
afkarxyz 76acb6f5e1 v4.8 2026-07-05 19:09:54 +07:00
afkarxyz 6bd03678f8 Merge pull request #103 from asdfghjkkly/fix-windows-folder-and-reposts
Fix repost folder routing and Windows folder opening
2026-07-05 17:00:37 +07:00
asdfghjkkly e400df6ea7 Fix repost folder routing and Windows folder opening 2026-07-05 05:41:36 -04:00
afkarxyz 52ffa5ba17 Update README 2026-06-22 14:31:56 +07:00
429Enjoyer c42808431c v4.7 2026-06-22 14:08:53 +07:00
429Enjoyer e05a9379fc v4.6 2026-05-19 14:28:05 +07:00
afkarxyz 33be717065 Update README 2026-05-19 14:26:35 +07:00
429Enjoyer c3ae949a38 Update README 2026-05-13 08:56:18 +07:00
429Enjoyer e67d09a248 v4.5 2026-05-13 08:49:42 +07:00
afkarxyz 84b067ebd4 Update README 2026-05-13 08:40:23 +07:00
afkarxyz eba8288a4e Update README 2026-05-12 11:28:56 +07:00
64 changed files with 8308 additions and 4154 deletions

No files matched your search

+68
View File
@@ -0,0 +1,68 @@
name: Bug Report
description: Report a bug in Twitter/X Media Batch Downloader
title: "[Bug Report] "
labels: ["bug"]
body:
- type: markdown
attributes:
value: |
> **WARNING: Issues that do not follow this template will be deleted without review.**
>
> **Please keep `[Bug Report]` in the issue title and only continue after it.**
- type: textarea
id: problem
attributes:
label: Problem
placeholder: "e.g. Fetching @username/media stops after a few items, or GIF conversion fails with no clear error."
validations:
required: true
- type: input
id: target
attributes:
label: X/Twitter URL or Username
placeholder: "e.g. https://x.com/username/media or @username"
validations:
required: true
- type: textarea
id: steps
attributes:
label: Steps to Reproduce
placeholder: |
1. Open ...
2. Enter ...
3. Click ...
4. See error ...
validations:
required: true
- type: textarea
id: logs
attributes:
label: Error Message / Logs / Screenshot
placeholder: "e.g. failed to extract timeline: parse_error ..."
validations:
required: true
- type: markdown
attributes:
value: "### Environment"
- type: input
id: version
attributes:
label: Twitter/X Media Batch Downloader Version
placeholder: "e.g. v4.4"
validations:
required: true
- type: input
id: os
attributes:
label: OS
placeholder: "e.g. Windows 11 23H2"
validations:
required: true
+1
View File
@@ -0,0 +1 @@
blank_issues_enabled: false
@@ -0,0 +1,34 @@
name: Feature Request
description: Request a feature for Twitter/X Media Batch Downloader
title: "[Feature Request] "
labels: ["enhancement"]
body:
- type: markdown
attributes:
value: |
> **WARNING: Issues that do not follow this template will be deleted without review.**
>
> **Please keep `[Feature Request]` in the issue title and only continue after it.**
- type: textarea
id: description
attributes:
label: Description
placeholder: e.g. Add an option to rotate between multiple auth tokens or export filtered results directly from Saved Accounts.
validations:
required: true
- type: textarea
id: use-case
attributes:
label: Why is this needed?
placeholder: e.g. I manage multiple accounts and want a faster way to retry only failed fetches without re-running the whole batch.
validations:
required: true
- type: textarea
id: additional-context
attributes:
label: Additional Context
placeholder: e.g. Mockup, similar app behavior, workflow notes, or screenshots if needed.
+39 -11
View File
@@ -151,8 +151,28 @@ jobs:
retention-days: 7 retention-days: 7
build-linux: build-linux:
name: Build Linux name: Build Linux (${{ matrix.display_name }})
runs-on: ubuntu-24.04 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: steps:
- name: Checkout code - name: Checkout code
uses: actions/checkout@v4 uses: actions/checkout@v4
@@ -189,7 +209,7 @@ jobs:
run: | run: |
sudo apt-get update sudo apt-get update
sudo apt-get install -y libgtk-3-dev libwebkit2gtk-4.1-dev libfuse2 imagemagick upx-ucl 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 - name: Install Wails CLI
run: go install github.com/wailsapp/wails/v2/cmd/wails@latest run: go install github.com/wailsapp/wails/v2/cmd/wails@latest
@@ -201,7 +221,7 @@ jobs:
pnpm run generate-icon pnpm run generate-icon
- name: Build application - name: Build application
run: wails build -platform linux/amd64 run: wails build -platform ${{ matrix.wails_platform }}
- name: Compress with UPX - name: Compress with UPX
run: upx --best --lzma "build/bin/${{ env.APP_NAME }}" run: upx --best --lzma "build/bin/${{ env.APP_NAME }}"
@@ -211,13 +231,13 @@ jobs:
uses: actions/cache@v4 uses: actions/cache@v4
with: with:
path: appimagetool path: appimagetool
key: appimagetool-x86_64-v2 key: appimagetool-${{ matrix.appimagetool_arch }}-v2
- name: Download appimagetool - name: Download appimagetool
if: steps.cache-appimagetool.outputs.cache-hit != 'true' if: steps.cache-appimagetool.outputs.cache-hit != 'true'
run: | 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/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-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-${{ matrix.appimagetool_arch }}.AppImage"
- name: Make appimagetool executable - name: Make appimagetool executable
run: chmod +x appimagetool run: chmod +x appimagetool
@@ -266,13 +286,13 @@ jobs:
chmod +x AppDir/AppRun chmod +x AppDir/AppRun
mkdir -p dist 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 - name: Upload artifacts
uses: actions/upload-artifact@v4 uses: actions/upload-artifact@v4
with: with:
name: linux-portable name: ${{ matrix.artifact_name }}
path: dist/${{ env.APP_NAME }}.AppImage path: dist/${{ matrix.output_name }}
retention-days: 7 retention-days: 7
create-release: create-release:
@@ -307,7 +327,8 @@ jobs:
- `TwitterXMediaBatchDownloader.exe` - Windows - `TwitterXMediaBatchDownloader.exe` - Windows
- `TwitterXMediaBatchDownloader.dmg` - macOS - `TwitterXMediaBatchDownloader.dmg` - macOS
- `TwitterXMediaBatchDownloader.AppImage` - Linux - `TwitterXMediaBatchDownloader.AppImage` - Linux AMD64
- `TwitterXMediaBatchDownloader-ARM.AppImage` - Linux ARM64
<details> <details>
<summary><b>Linux Requirements</b></summary> <summary><b>Linux Requirements</b></summary>
@@ -335,10 +356,17 @@ jobs:
./TwitterXMediaBatchDownloader.AppImage ./TwitterXMediaBatchDownloader.AppImage
``` ```
For ARM64:
```bash
chmod +x TwitterXMediaBatchDownloader-ARM.AppImage
./TwitterXMediaBatchDownloader-ARM.AppImage
```
</details> </details>
files: | files: |
artifacts/windows-portable/${{ env.APP_NAME }}.exe artifacts/windows-portable/${{ env.APP_NAME }}.exe
artifacts/macos-portable/${{ env.APP_NAME }}.dmg artifacts/macos-portable/${{ env.APP_NAME }}.dmg
artifacts/linux-portable/${{ env.APP_NAME }}.AppImage artifacts/linux-portable/${{ env.APP_NAME }}.AppImage
artifacts/linux-portable-arm/${{ env.APP_NAME }}-ARM.AppImage
env: env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+59
View File
@@ -0,0 +1,59 @@
# Wails Build
build/
*.exe
*.dll
*.dylib
*.so
# Wails Generated Files
frontend/wailsjs/
# Go
*.test
*.out
go.work
go.work.sum
# Node / Frontend
node_modules/
frontend/node_modules/
frontend/dist/
frontend/.vite/
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
.pnpm-store/
.npm
.yarn
*.tsbuildinfo
# IDE / Editors
.vscode/
.idea/
*.swp
*.swo
*~
.DS_Store
# OS
Thumbs.db
desktop.ini
# Environment
.env
.env.local
.env.*.local
# Logs
*.log
logs/
# Temporary files
tmp/
temp/
*.tmp
*.bak
*.old
*.bat
+27 -12
View File
@@ -1,18 +1,35 @@
# Twitter/X Media Batch Downloader <div align="left">
<h1>Twitter/X Media Batch Downloader</h1>
A GUI tool to download original-quality images and videos from Twitter/X accounts, powered by gallery-dl by @mikf <p>
Downloads original-quality images and videos from Twitter/X accounts.
![Windows](https://img.shields.io/badge/Windows-10%2B-0078D6?style=for-the-badge&logo=data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI1MTIiIGhlaWdodD0iNTEyIiB2aWV3Qm94PSIwIDAgMjAgMjAiPjxwYXRoIGZpbGw9IiNmZmZmZmYiIGZpbGwtcnVsZT0iZXZlbm9kZCIgZD0iTTIwIDEwLjg3M1YyMEw4LjQ3OSAxOC41MzdsLjAwMS03LjY2NEgyMFptLTEzLjEyIDBsLS4wMDEgNy40NjFMMCAxNy40NjF2LTYuNTg4aDYuODhaTTIwIDkuMjczSDguNDhsLS4wMDEtNy44MUwyMCAwdjkuMjczWk02Ljg3OSAxLjY2NmwuMDAxIDcuNjA3SDBWMi41MzlsNi44NzktLjg3M1oiLz48L3N2Zz4=) </p>
![macOS](https://img.shields.io/badge/macOS-10.13%2B-000000?style=for-the-badge&logo=apple&logoColor=white) <p>
![Linux](https://img.shields.io/badge/Linux-Any-FCC624?style=for-the-badge&logo=linux&logoColor=white) <a href="https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/stargazers"><img
src="https://img.shields.io/github/stars/afkarxyz/Twitter-X-Media-Batch-Downloader?color=ffcb47&labelColor=black&logo=github&label=Stars" /></a><a
href="https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases"><img
src="https://img.shields.io/github/downloads/afkarxyz/Twitter-X-Media-Batch-Downloader/total?color=22c55e&labelColor=black&logo=github&label=Downloads" /></a><a
href="https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases/latest"><img
src="https://img.shields.io/github/v/release/afkarxyz/Twitter-X-Media-Batch-Downloader?color=8b5cf6&labelColor=black&logo=github&label=Latest%20Release" /></a><a
href="https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases/latest"><img
src="https://img.shields.io/badge/Windows-10%2B-369eff?labelColor=black&logo=data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI1MTIiIGhlaWdodD0iNTEyIiB2aWV3Qm94PSIwIDAgMjAgMjAiPjxwYXRoIGZpbGw9IiNmZmZmZmYiIGZpbGwtcnVsZT0iZXZlbm9kZCIgZD0iTTIwIDEwLjg3M1YyMEw4LjQ3OSAxOC41MzdsLjAwMS03LjY2NEgyMFptLTEzLjEyIDBsLS4wMDEgNy40NjFMMCAxNy40NjF2LTYuNTg4aDYuODhaTTIwIDkuMjczSDguNDhsLS4wMDEtNy44MUwyMCAwdjkuMjczWk02Ljg3OSAxLjY2NmwuMDAxIDcuNjA3SDBWMi41MzlsNi44NzktLjg3M1oiLz48L3N2Zz4=" /></a><a
href="https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases/latest"><img
src="https://img.shields.io/badge/macOS-10.13%2B-FFFFFF?labelColor=black&logo=apple&logoColor=white" /></a><a
href="https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases/latest"><img
src="https://img.shields.io/badge/Linux-Any-FCC624?labelColor=black&logo=linux&logoColor=white" /></a>
<br />
<br />
<a href="https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases/latest" target="_blank"><img
src="https://github.com/user-attachments/assets/cef7b7e6-5a64-497a-91fe-b6fb549f3b09" alt="Twitter/X Media Batch Downloader" /></a>
</p>
</div>
### [Download](https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases) ### [Download](https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases)
![Image](https://github.com/user-attachments/assets/a3ade39c-d611-49ce-81bb-121f30488ae2) - If you're familiar with userscripts, install it [**here**](https://greasyfork.org/en/scripts/523157)
- If you're familiar with userscripts, install it [**here**](https://greasyfork.org/en/scripts/551198) - To install the Chrome extension version, click [**here**](https://chromewebstore.google.com/detail/cboceolmgkoobpfjiojkigmihijfgmdo)
- To install the Chrome extension version, click [**here**](https://chromewebstore.google.com/detail/aboccmnimgpjehlplnanplbhlccohhhn) - Also available on the web at [**TwitterDL.app**](https://twitterdl.app)
## How to Obtain Auth Token ## How to Obtain Auth Token
@@ -22,8 +39,6 @@ A GUI tool to download original-quality images and videos from Twitter/X account
> - Using an auth token or cookies has the potential to get the **account suspended.** > - Using an auth token or cookies has the potential to get the **account suspended.**
> - If too many media files are fetched, it may trigger a **rate limit**, and the media retrieval will fail. > - If too many media files are fetched, it may trigger a **rate limit**, and the media retrieval will fail.
### [Video Tutorial](https://www.patreon.com/posts/how-to-obtain-127206894)
1. Go to [Twitter's website](https://www.x.com/) 1. Go to [Twitter's website](https://www.x.com/)
2. Log into your account 2. Log into your account
3. Open the Developer Tools by pressing <kbd>F12</kbd> 3. Open the Developer Tools by pressing <kbd>F12</kbd>
+212 -41
View File
@@ -3,8 +3,10 @@ package main
import ( import (
"context" "context"
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
"path/filepath" "path/filepath"
"sync"
"twitterxmediabatchdownloader/backend" "twitterxmediabatchdownloader/backend"
"github.com/wailsapp/wails/v2/pkg/runtime" "github.com/wailsapp/wails/v2/pkg/runtime"
@@ -12,8 +14,9 @@ import (
type App struct { type App struct {
ctx context.Context ctx context.Context
downloadCtx context.Context downloadMu sync.Mutex
downloadCancel context.CancelFunc downloadCancel context.CancelFunc
downloadActive bool
} }
func NewApp() *App { func NewApp() *App {
@@ -41,14 +44,20 @@ func (a *App) CleanupExtractorProcesses() {
} }
type TimelineRequest struct { type TimelineRequest struct {
Username string `json:"username"` Username string `json:"username"`
AuthToken string `json:"auth_token"` AuthToken string `json:"auth_token"`
TimelineType string `json:"timeline_type"` TimelineType string `json:"timeline_type"`
BatchSize int `json:"batch_size"` BatchSize int `json:"batch_size"`
Page int `json:"page"` Page int `json:"page"`
MediaType string `json:"media_type"` MediaType string `json:"media_type"`
Retweets bool `json:"retweets"` Retweets bool `json:"retweets"`
Cursor string `json:"cursor,omitempty"` 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 { type DateRangeRequest struct {
@@ -70,14 +79,20 @@ func (a *App) ExtractTimeline(req TimelineRequest) (string, error) {
} }
backendReq := backend.TimelineRequest{ backendReq := backend.TimelineRequest{
Username: req.Username, Username: req.Username,
AuthToken: req.AuthToken, AuthToken: req.AuthToken,
TimelineType: req.TimelineType, TimelineType: req.TimelineType,
BatchSize: req.BatchSize, BatchSize: req.BatchSize,
Page: req.Page, Page: req.Page,
MediaType: req.MediaType, MediaType: req.MediaType,
Retweets: req.Retweets, Retweets: req.Retweets,
Cursor: req.Cursor, 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) response, err := backend.ExtractTimeline(backendReq)
@@ -144,6 +159,29 @@ func (a *App) OpenFolder(path string) error {
return nil 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) { func (a *App) SelectFolder(defaultPath string) (string, error) {
return backend.SelectFolderDialog(a.ctx, defaultPath) return backend.SelectFolderDialog(a.ctx, defaultPath)
} }
@@ -154,6 +192,18 @@ func (a *App) GetDefaults() map[string]string {
} }
} }
func (a *App) GetStoredAuthToken(slot string) (string, error) {
return backend.GetStoredAuthToken(slot)
}
func (a *App) SetStoredAuthToken(slot, token string) error {
return backend.SetStoredAuthToken(slot, token)
}
func (a *App) ClearStoredAuthToken(slot string) error {
return backend.ClearStoredAuthToken(slot)
}
func (a *App) IsExtractorInstalled() bool { func (a *App) IsExtractorInstalled() bool {
return backend.IsExtractorInstalled() return backend.IsExtractorInstalled()
} }
@@ -162,15 +212,27 @@ func (a *App) DownloadExtractor() error {
return backend.DownloadExtractor(nil) return backend.DownloadExtractor(nil)
} }
func (a *App) GetExtractorVersionStatus() backend.ExtractorVersionStatus {
return backend.GetExtractorVersionStatus()
}
func (a *App) Quit() { func (a *App) Quit() {
if a.ctx != nil {
runtime.Quit(a.ctx)
return
}
panic("quit") panic("quit")
} }
type DownloadMediaRequest struct { type DownloadMediaRequest struct {
URLs []string `json:"urls"` URLs []string `json:"urls"`
OutputDir string `json:"output_dir"` OutputDir string `json:"output_dir"`
Username string `json:"username"` Username string `json:"username"`
Proxy string `json:"proxy,omitempty"` 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"`
} }
type MediaItemRequest struct { type MediaItemRequest struct {
@@ -181,17 +243,28 @@ type MediaItemRequest struct {
Content string `json:"content,omitempty"` Content string `json:"content,omitempty"`
OriginalFilename string `json:"original_filename,omitempty"` OriginalFilename string `json:"original_filename,omitempty"`
AuthorUsername string `json:"author_username,omitempty"` AuthorUsername string `json:"author_username,omitempty"`
AccountName string `json:"account_name,omitempty"`
} }
type DownloadMediaWithMetadataRequest struct { type DownloadMediaWithMetadataRequest struct {
Items []MediaItemRequest `json:"items"` Items []MediaItemRequest `json:"items"`
OutputDir string `json:"output_dir"` OutputDir string `json:"output_dir"`
Username string `json:"username"` Username string `json:"username"`
Proxy string `json:"proxy,omitempty"` 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"`
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 { type DownloadMediaResponse struct {
Success bool `json:"success"` Success bool `json:"success"`
Cancelled bool `json:"cancelled"`
Downloaded int `json:"downloaded"` Downloaded int `json:"downloaded"`
Skipped int `json:"skipped"` Skipped int `json:"skipped"`
Failed int `json:"failed"` Failed int `json:"failed"`
@@ -201,8 +274,9 @@ type DownloadMediaResponse struct {
func (a *App) DownloadMedia(req DownloadMediaRequest) (DownloadMediaResponse, error) { func (a *App) DownloadMedia(req DownloadMediaRequest) (DownloadMediaResponse, error) {
if len(req.URLs) == 0 { if len(req.URLs) == 0 {
return DownloadMediaResponse{ return DownloadMediaResponse{
Success: false, Success: false,
Message: "No URLs provided", Cancelled: false,
Message: "No URLs provided",
}, fmt.Errorf("no URLs provided") }, fmt.Errorf("no URLs provided")
} }
@@ -215,10 +289,18 @@ func (a *App) DownloadMedia(req DownloadMediaRequest) (DownloadMediaResponse, er
outputDir = filepath.Join(outputDir, req.Username) outputDir = filepath.Join(outputDir, req.Username)
} }
downloaded, failed, err := backend.DownloadMediaFiles(req.URLs, outputDir, req.Proxy) options := backend.DownloadOptions{
ConcurrentDownloads: req.ConcurrentDownloads,
SkipExistingFiles: req.SkipExisting,
DeleteIncompleteFiles: req.DeleteIncompleteFiles,
RetryAttempts: req.RetryAttempts,
}
downloaded, failed, err := backend.DownloadMediaFiles(req.URLs, outputDir, options, req.Proxy)
if err != nil { if err != nil {
return DownloadMediaResponse{ return DownloadMediaResponse{
Success: false, Success: false,
Cancelled: false,
Downloaded: downloaded, Downloaded: downloaded,
Skipped: 0, Skipped: 0,
Failed: failed, Failed: failed,
@@ -228,6 +310,7 @@ func (a *App) DownloadMedia(req DownloadMediaRequest) (DownloadMediaResponse, er
return DownloadMediaResponse{ return DownloadMediaResponse{
Success: true, Success: true,
Cancelled: false,
Downloaded: downloaded, Downloaded: downloaded,
Skipped: 0, Skipped: 0,
Failed: failed, Failed: failed,
@@ -250,8 +333,9 @@ type DownloadItemStatus struct {
func (a *App) DownloadMediaWithMetadata(req DownloadMediaWithMetadataRequest) (DownloadMediaResponse, error) { func (a *App) DownloadMediaWithMetadata(req DownloadMediaWithMetadataRequest) (DownloadMediaResponse, error) {
if len(req.Items) == 0 { if len(req.Items) == 0 {
return DownloadMediaResponse{ return DownloadMediaResponse{
Success: false, Success: false,
Message: "No items provided", Cancelled: false,
Message: "No items provided",
}, fmt.Errorf("no items provided") }, fmt.Errorf("no items provided")
} }
@@ -270,7 +354,7 @@ func (a *App) DownloadMediaWithMetadata(req DownloadMediaWithMetadataRequest) (D
} }
username := req.Username username := req.Username
if item.AuthorUsername != "" { if (req.Username == "bookmarks" || req.Username == "likes") && item.AuthorUsername != "" {
username = item.AuthorUsername username = item.AuthorUsername
} }
@@ -280,12 +364,21 @@ func (a *App) DownloadMediaWithMetadata(req DownloadMediaWithMetadataRequest) (D
TweetID: int64(item.TweetID), TweetID: int64(item.TweetID),
Type: item.Type, Type: item.Type,
Username: username, Username: username,
AccountName: item.AccountName,
Content: item.Content, Content: item.Content,
OriginalFilename: originalFilename, OriginalFilename: originalFilename,
} }
} }
a.downloadCtx, a.downloadCancel = context.WithCancel(context.Background()) downloadCtx, err := a.startDownloadOperation()
if err != nil {
return DownloadMediaResponse{
Success: false,
Cancelled: false,
Message: err.Error(),
}, err
}
defer a.finishDownloadOperation()
progressCallback := func(current, total int) { progressCallback := func(current, total int) {
percent := 0 percent := 0
@@ -307,10 +400,43 @@ func (a *App) DownloadMediaWithMetadata(req DownloadMediaWithMetadataRequest) (D
}) })
} }
downloaded, skipped, failed, err := backend.DownloadMediaWithMetadataProgressAndStatus(items, outputDir, req.Username, progressCallback, itemStatusCallback, a.downloadCtx, req.Proxy) options := backend.DownloadOptions{
ConcurrentDownloads: req.ConcurrentDownloads,
SkipExistingFiles: req.SkipExisting,
DeleteIncompleteFiles: req.DeleteIncompleteFiles,
RetryAttempts: req.RetryAttempts,
FilenameTemplate: req.FilenameTemplate,
FolderTemplate: req.FolderTemplate,
AutoConvertGIFs: req.AutoConvertGIFs,
GIFQuality: req.GIFQuality,
GIFResolution: req.GIFResolution,
}
downloaded, skipped, failed, err := backend.DownloadMediaWithMetadataProgressAndStatus(
items,
outputDir,
req.Username,
progressCallback,
itemStatusCallback,
downloadCtx,
options,
req.Proxy,
)
if err != nil { if err != nil {
if errors.Is(err, context.Canceled) {
return DownloadMediaResponse{
Success: false,
Cancelled: true,
Downloaded: downloaded,
Skipped: skipped,
Failed: failed,
Message: "Download stopped",
}, nil
}
return DownloadMediaResponse{ return DownloadMediaResponse{
Success: false, Success: false,
Cancelled: false,
Downloaded: downloaded, Downloaded: downloaded,
Skipped: skipped, Skipped: skipped,
Failed: failed, Failed: failed,
@@ -318,10 +444,9 @@ func (a *App) DownloadMediaWithMetadata(req DownloadMediaWithMetadataRequest) (D
}, err }, err
} }
a.downloadCancel = nil
return DownloadMediaResponse{ return DownloadMediaResponse{
Success: true, Success: true,
Cancelled: false,
Downloaded: downloaded, Downloaded: downloaded,
Skipped: skipped, Skipped: skipped,
Failed: failed, Failed: failed,
@@ -329,13 +454,39 @@ func (a *App) DownloadMediaWithMetadata(req DownloadMediaWithMetadataRequest) (D
}, nil }, nil
} }
func (a *App) StopDownload() bool { func (a *App) startDownloadOperation() (context.Context, error) {
if a.downloadCancel != nil { a.downloadMu.Lock()
a.downloadCancel() defer a.downloadMu.Unlock()
a.downloadCancel = nil
return true if a.downloadActive {
return nil, fmt.Errorf("another download is already in progress")
} }
return false
ctx, cancel := context.WithCancel(context.Background())
a.downloadCancel = cancel
a.downloadActive = true
return ctx, nil
}
func (a *App) finishDownloadOperation() {
a.downloadMu.Lock()
defer a.downloadMu.Unlock()
a.downloadCancel = nil
a.downloadActive = false
}
func (a *App) StopDownload() bool {
a.downloadMu.Lock()
defer a.downloadMu.Unlock()
if !a.downloadActive || a.downloadCancel == nil {
return false
}
a.downloadCancel()
return true
} }
func (a *App) SaveAccountToDB(username, name, profileImage string, totalMedia int, responseJSON string, mediaType string) error { func (a *App) SaveAccountToDB(username, name, profileImage string, totalMedia int, responseJSON string, mediaType string) error {
@@ -358,6 +509,14 @@ func (a *App) GetAccountFromDB(id int64) (string, error) {
return acc.ResponseJSON, nil return acc.ResponseJSON, nil
} }
func (a *App) GetSavedAccountFromDB(username, mediaType string) (string, error) {
acc, err := backend.GetAccountByUsernameAndMediaType(username, mediaType)
if err != nil {
return "", err
}
return acc.ResponseJSON, nil
}
func (a *App) DeleteAccountFromDB(id int64) error { func (a *App) DeleteAccountFromDB(id int64) error {
return backend.DeleteAccount(id) return backend.DeleteAccount(id)
} }
@@ -382,6 +541,10 @@ func (a *App) GetAllGroups() ([]map[string]string, error) {
return backend.GetAllGroups() return backend.GetAllGroups()
} }
func (a *App) CheckFoldersExist(basePath string, usernames []string) map[string]bool {
return backend.CheckFoldersExist(basePath, usernames)
}
func (a *App) IsFFmpegInstalled() bool { func (a *App) IsFFmpegInstalled() bool {
return backend.IsFFmpegInstalled() return backend.IsFFmpegInstalled()
} }
@@ -390,6 +553,10 @@ func (a *App) DownloadFFmpeg() error {
return backend.DownloadFFmpeg(nil) return backend.DownloadFFmpeg(nil)
} }
func (a *App) GetFFmpegVersionStatus() backend.DependencyVersionStatus {
return backend.GetFFmpegVersionStatus()
}
func (a *App) IsExifToolInstalled() bool { func (a *App) IsExifToolInstalled() bool {
return backend.IsExifToolInstalled() return backend.IsExifToolInstalled()
} }
@@ -398,6 +565,10 @@ func (a *App) DownloadExifTool() error {
return backend.DownloadExifTool(nil) return backend.DownloadExifTool(nil)
} }
func (a *App) GetExifToolVersionStatus() backend.DependencyVersionStatus {
return backend.GetExifToolVersionStatus()
}
type ConvertGIFsRequest struct { type ConvertGIFsRequest struct {
FolderPath string `json:"folder_path"` FolderPath string `json:"folder_path"`
Quality string `json:"quality"` Quality string `json:"quality"`
+70
View File
@@ -0,0 +1,70 @@
package backend
import (
"errors"
"fmt"
"strings"
"github.com/zalando/go-keyring"
)
const authTokenKeyringService = "TwitterXMediaBatchDownloader"
func normalizeAuthTokenSlot(slot string) (string, error) {
switch strings.ToLower(strings.TrimSpace(slot)) {
case "public":
return "public", nil
case "private":
return "private", nil
default:
return "", fmt.Errorf("invalid auth token slot: %q", slot)
}
}
func authTokenKeyringUser(slot string) string {
return "auth-token-" + slot
}
func GetStoredAuthToken(slot string) (string, error) {
normalizedSlot, err := normalizeAuthTokenSlot(slot)
if err != nil {
return "", err
}
token, err := keyring.Get(authTokenKeyringService, authTokenKeyringUser(normalizedSlot))
if errors.Is(err, keyring.ErrNotFound) {
return "", nil
}
if err != nil {
return "", err
}
return token, nil
}
func SetStoredAuthToken(slot, token string) error {
normalizedSlot, err := normalizeAuthTokenSlot(slot)
if err != nil {
return err
}
if strings.TrimSpace(token) == "" {
return ClearStoredAuthToken(normalizedSlot)
}
return keyring.Set(authTokenKeyringService, authTokenKeyringUser(normalizedSlot), token)
}
func ClearStoredAuthToken(slot string) error {
normalizedSlot, err := normalizeAuthTokenSlot(slot)
if err != nil {
return err
}
err = keyring.Delete(authTokenKeyringService, authTokenKeyringUser(normalizedSlot))
if errors.Is(err, keyring.ErrNotFound) {
return nil
}
return err
}
+20 -2
View File
@@ -2,8 +2,26 @@
package backend package backend
import "os/exec" import (
"errors"
"os/exec"
"syscall"
)
func hideWindow(cmd *exec.Cmd) { func hideWindow(cmd *exec.Cmd) {
cmd.SysProcAttr = &syscall.SysProcAttr{
Setpgid: true,
}
}
func terminateCommandProcess(cmd *exec.Cmd) error {
if cmd == nil || cmd.Process == nil {
return nil
}
if err := syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL); err != nil && !errors.Is(err, syscall.ESRCH) {
return err
}
return nil
} }
+15
View File
@@ -4,6 +4,7 @@ package backend
import ( import (
"os/exec" "os/exec"
"strconv"
"syscall" "syscall"
) )
@@ -13,3 +14,17 @@ func hideWindow(cmd *exec.Cmd) {
CreationFlags: 0x08000000, CreationFlags: 0x08000000,
} }
} }
func terminateCommandProcess(cmd *exec.Cmd) error {
if cmd == nil || cmd.Process == nil {
return nil
}
taskkill := exec.Command("taskkill", "/T", "/F", "/PID", strconv.Itoa(cmd.Process.Pid))
hideWindow(taskkill)
if err := taskkill.Run(); err == nil {
return nil
}
return cmd.Process.Kill()
}
+62 -13
View File
@@ -6,6 +6,8 @@ import (
"net/url" "net/url"
"os" "os"
"path/filepath" "path/filepath"
"strings"
"sync/atomic"
"time" "time"
) )
@@ -20,14 +22,42 @@ func GetDefaultDownloadPath() string {
return filepath.Join(homeDir, "Pictures") return filepath.Join(homeDir, "Pictures")
} }
func GetProxyURL(customProxy string) (*url.URL, error) { func parseProxyURLs(rawValue string, sourceName string) ([]*url.URL, error) {
if strings.TrimSpace(rawValue) == "" {
return nil, nil
}
parts := strings.Split(rawValue, ",")
proxyURLs := make([]*url.URL, 0, len(parts))
for _, part := range parts {
trimmed := strings.TrimSpace(part)
if trimmed == "" {
continue
}
proxyURL, err := url.Parse(trimmed)
if err != nil {
return nil, fmt.Errorf("invalid proxy URL in %s: %v", sourceName, err)
}
if proxyURL.Scheme == "" || proxyURL.Host == "" {
return nil, fmt.Errorf("invalid proxy URL in %s: %q", sourceName, trimmed)
}
proxyURLs = append(proxyURLs, proxyURL)
}
if len(proxyURLs) == 0 {
return nil, nil
}
return proxyURLs, nil
}
func GetProxyURLs(customProxy string) ([]*url.URL, error) {
if customProxy != "" { if customProxy != "" {
proxyURL, err := url.Parse(customProxy) return parseProxyURLs(customProxy, "custom proxy setting")
if err != nil {
return nil, fmt.Errorf("invalid custom proxy URL: %v", err)
}
return proxyURL, nil
} }
proxyEnv := os.Getenv("HTTPS_PROXY") proxyEnv := os.Getenv("HTTPS_PROXY")
@@ -42,24 +72,43 @@ func GetProxyURL(customProxy string) (*url.URL, error) {
} }
if proxyEnv != "" { if proxyEnv != "" {
proxyURL, err := url.Parse(proxyEnv) return parseProxyURLs(proxyEnv, "proxy environment variable")
if err != nil {
return nil, fmt.Errorf("invalid proxy URL from environment: %v", err)
}
return proxyURL, nil
} }
return nil, nil return nil, nil
} }
func GetProxyURL(customProxy string) (*url.URL, error) {
proxyURLs, err := GetProxyURLs(customProxy)
if err != nil || len(proxyURLs) == 0 {
return nil, err
}
return proxyURLs[0], nil
}
func buildProxySelector(proxyURLs []*url.URL) func(*http.Request) (*url.URL, error) {
if len(proxyURLs) == 0 {
return nil
}
if len(proxyURLs) == 1 {
return http.ProxyURL(proxyURLs[0])
}
var requestCount uint64
return func(*http.Request) (*url.URL, error) {
index := atomic.AddUint64(&requestCount, 1) - 1
return proxyURLs[index%uint64(len(proxyURLs))], nil
}
}
func CreateHTTPClient(customProxy string, timeout time.Duration) (*http.Client, error) { func CreateHTTPClient(customProxy string, timeout time.Duration) (*http.Client, error) {
proxyURL, err := GetProxyURL(customProxy) proxyURLs, err := GetProxyURLs(customProxy)
if err != nil { if err != nil {
return nil, err return nil, err
} }
transport := &http.Transport{ transport := &http.Transport{
Proxy: http.ProxyURL(proxyURL), Proxy: buildProxySelector(proxyURLs),
} }
client := &http.Client{ client := &http.Client{
+212 -65
View File
@@ -6,6 +6,8 @@ import (
"fmt" "fmt"
"os" "os"
"path/filepath" "path/filepath"
"strings"
"sync"
"time" "time"
_ "modernc.org/sqlite" _ "modernc.org/sqlite"
@@ -41,6 +43,33 @@ type AccountListItem struct {
} }
var db *sql.DB var db *sql.DB
var dbInitMu sync.Mutex
var dbInitialized bool
func ensureDB() error {
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 {
AccountInfo struct {
FollowersCount int `json:"followers_count"`
StatusesCount int `json:"statuses_count"`
} `json:"account_info"`
Followers int `json:"followers"`
Posts int `json:"posts"`
}
func GetDBPath() string { func GetDBPath() string {
homeDir, err := os.UserHomeDir() homeDir, err := os.UserHomeDir()
@@ -51,6 +80,10 @@ func GetDBPath() string {
} }
func InitDB() error { func InitDB() error {
return ensureDB()
}
func initDBInternal() error {
dbPath := GetDBPath() dbPath := GetDBPath()
dir := filepath.Dir(dbPath) dir := filepath.Dir(dbPath)
@@ -82,6 +115,8 @@ func InitDB() error {
media_type TEXT DEFAULT 'all', media_type TEXT DEFAULT 'all',
cursor TEXT DEFAULT '', cursor TEXT DEFAULT '',
completed INTEGER DEFAULT 1, completed INTEGER DEFAULT 1,
followers_count INTEGER DEFAULT 0,
statuses_count INTEGER DEFAULT 0,
UNIQUE(username, media_type) UNIQUE(username, media_type)
) )
`) `)
@@ -89,14 +124,47 @@ func InitDB() error {
return err return err
} }
db.Exec("ALTER TABLE accounts ADD COLUMN group_name TEXT DEFAULT ''")
db.Exec("ALTER TABLE accounts ADD COLUMN group_color TEXT DEFAULT ''")
db.Exec("ALTER TABLE accounts ADD COLUMN media_type TEXT DEFAULT 'all'")
db.Exec("ALTER TABLE accounts ADD COLUMN cursor TEXT DEFAULT ''")
db.Exec("ALTER TABLE accounts ADD COLUMN completed INTEGER DEFAULT 1")
db.Exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_username_media_type ON accounts(username, media_type)") db.Exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_username_media_type ON accounts(username, media_type)")
if err := runMigrations(); err != nil {
return err
}
if err := backfillAccountMetrics(); err != nil {
return err
}
return nil
}
func runMigrations() error {
var version int
if err := db.QueryRow("PRAGMA user_version").Scan(&version); err != nil {
return err
}
migrations := []string{
"ALTER TABLE accounts ADD COLUMN group_name TEXT DEFAULT ''",
"ALTER TABLE accounts ADD COLUMN group_color TEXT DEFAULT ''",
"ALTER TABLE accounts ADD COLUMN media_type TEXT DEFAULT 'all'",
"ALTER TABLE accounts ADD COLUMN cursor TEXT DEFAULT ''",
"ALTER TABLE accounts ADD COLUMN completed INTEGER DEFAULT 1",
"ALTER TABLE accounts ADD COLUMN followers_count INTEGER DEFAULT 0",
"ALTER TABLE accounts ADD COLUMN statuses_count INTEGER DEFAULT 0",
}
for i := version; i < len(migrations); i++ {
if _, err := db.Exec(migrations[i]); err != nil {
if !strings.Contains(err.Error(), "duplicate column name") {
return fmt.Errorf("migration %d failed: %w", i, err)
}
}
}
if _, err := db.Exec(fmt.Sprintf("PRAGMA user_version = %d", len(migrations))); err != nil {
return err
}
return nil return nil
} }
@@ -111,10 +179,8 @@ func SaveAccount(username, name, profileImage string, totalMedia int, responseJS
} }
func SaveAccountWithStatus(username, name, profileImage string, totalMedia int, responseJSON string, mediaType string, cursor string, completed bool) error { func SaveAccountWithStatus(username, name, profileImage string, totalMedia int, responseJSON string, mediaType string, cursor string, completed bool) error {
if db == nil { if err := ensureDB(); err != nil {
if err := InitDB(); err != nil { return err
return err
}
} }
if mediaType == "" { if mediaType == "" {
@@ -126,9 +192,11 @@ func SaveAccountWithStatus(username, name, profileImage string, totalMedia int,
completedInt = 1 completedInt = 1
} }
followersCount, statusesCount := extractAccountMetrics(responseJSON)
_, err := db.Exec(` _, err := db.Exec(`
INSERT INTO accounts (username, name, profile_image, total_media, last_fetched, response_json, media_type, cursor, completed) INSERT INTO accounts (username, name, profile_image, total_media, last_fetched, response_json, media_type, cursor, completed, followers_count, statuses_count)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(username, media_type) DO UPDATE SET ON CONFLICT(username, media_type) DO UPDATE SET
name = excluded.name, name = excluded.name,
profile_image = excluded.profile_image, profile_image = excluded.profile_image,
@@ -136,17 +204,17 @@ func SaveAccountWithStatus(username, name, profileImage string, totalMedia int,
last_fetched = excluded.last_fetched, last_fetched = excluded.last_fetched,
response_json = excluded.response_json, response_json = excluded.response_json,
cursor = excluded.cursor, cursor = excluded.cursor,
completed = excluded.completed completed = excluded.completed,
`, username, name, profileImage, totalMedia, time.Now(), responseJSON, mediaType, cursor, completedInt) followers_count = excluded.followers_count,
statuses_count = excluded.statuses_count
`, username, name, profileImage, totalMedia, time.Now(), responseJSON, mediaType, cursor, completedInt, followersCount, statusesCount)
return err return err
} }
func GetAllAccounts() ([]AccountListItem, error) { func GetAllAccounts() ([]AccountListItem, error) {
if db == nil { if err := ensureDB(); err != nil {
if err := InitDB(); err != nil { return nil, err
return nil, err
}
} }
rows, err := db.Query(` rows, err := db.Query(`
@@ -154,7 +222,8 @@ func GetAllAccounts() ([]AccountListItem, error) {
COALESCE(group_name, '') as group_name, COALESCE(group_color, '') as group_color, COALESCE(group_name, '') as group_name, COALESCE(group_color, '') as group_color,
COALESCE(media_type, 'all') as media_type, COALESCE(media_type, 'all') as media_type,
COALESCE(cursor, '') as cursor, COALESCE(completed, 1) as completed, COALESCE(cursor, '') as cursor, COALESCE(completed, 1) as completed,
COALESCE(response_json, '') as response_json COALESCE(followers_count, 0) as followers_count,
COALESCE(statuses_count, 0) as statuses_count
FROM accounts FROM accounts
ORDER BY group_name ASC, last_fetched DESC ORDER BY group_name ASC, last_fetched DESC
`) `)
@@ -168,49 +237,108 @@ func GetAllAccounts() ([]AccountListItem, error) {
var acc AccountListItem var acc AccountListItem
var lastFetched time.Time var lastFetched time.Time
var completedInt int var completedInt int
var responseJSON string if err := rows.Scan(&acc.ID, &acc.Username, &acc.Name, &acc.ProfileImage, &acc.TotalMedia, &lastFetched, &acc.GroupName, &acc.GroupColor, &acc.MediaType, &acc.Cursor, &completedInt, &acc.FollowersCount, &acc.StatusesCount); err != nil {
if err := rows.Scan(&acc.ID, &acc.Username, &acc.Name, &acc.ProfileImage, &acc.TotalMedia, &lastFetched, &acc.GroupName, &acc.GroupColor, &acc.MediaType, &acc.Cursor, &completedInt, &responseJSON); err != nil {
continue continue
} }
acc.LastFetched = lastFetched.Format("2006-01-02 15:04") acc.LastFetched = lastFetched.Format("2006-01-02 15:04")
acc.Completed = completedInt == 1 acc.Completed = completedInt == 1
if responseJSON != "" {
var parsed map[string]interface{}
if err := json.Unmarshal([]byte(responseJSON), &parsed); err == nil {
if accountInfo, ok := parsed["account_info"].(map[string]interface{}); ok {
if followers, ok := accountInfo["followers_count"].(float64); ok {
acc.FollowersCount = int(followers)
}
if statuses, ok := accountInfo["statuses_count"].(float64); ok {
acc.StatusesCount = int(statuses)
}
}
}
}
accounts = append(accounts, acc) accounts = append(accounts, acc)
} }
return accounts, nil return accounts, nil
} }
func UpdateAccountGroup(id int64, groupName, groupColor string) error { func extractAccountMetrics(responseJSON string) (followersCount int, statusesCount int) {
if db == nil { if responseJSON == "" {
if err := InitDB(); err != nil { return 0, 0
}
var payload accountMetricsPayload
if err := json.Unmarshal([]byte(responseJSON), &payload); err != nil {
return 0, 0
}
followersCount = payload.AccountInfo.FollowersCount
statusesCount = payload.AccountInfo.StatusesCount
if followersCount == 0 {
followersCount = payload.Followers
}
if statusesCount == 0 {
statusesCount = payload.Posts
}
return followersCount, statusesCount
}
func backfillAccountMetrics() error {
rows, err := db.Query(`
SELECT id, COALESCE(response_json, '') as response_json
FROM accounts
WHERE COALESCE(response_json, '') != ''
AND (COALESCE(followers_count, 0) = 0 OR COALESCE(statuses_count, 0) = 0)
`)
if err != nil {
return err
}
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
SET followers_count = ?, statuses_count = ?
WHERE id = ?
`)
if err != nil {
return err
}
defer stmt.Close()
for _, u := range updates {
if _, err := stmt.Exec(u.followersCount, u.statusesCount, u.id); err != nil {
return err return err
} }
} }
return nil
}
func UpdateAccountGroup(id int64, groupName, groupColor string) error {
if err := ensureDB(); err != nil {
return err
}
_, err := db.Exec("UPDATE accounts SET group_name = ?, group_color = ? WHERE id = ?", groupName, groupColor, id) _, err := db.Exec("UPDATE accounts SET group_name = ?, group_color = ? WHERE id = ?", groupName, groupColor, id)
return err return err
} }
func GetAllGroups() ([]map[string]string, error) { func GetAllGroups() ([]map[string]string, error) {
if db == nil { if err := ensureDB(); err != nil {
if err := InitDB(); err != nil { return nil, err
return nil, err
}
} }
rows, err := db.Query(` rows, err := db.Query(`
@@ -237,10 +365,8 @@ func GetAllGroups() ([]map[string]string, error) {
} }
func ClearAllAccounts() error { func ClearAllAccounts() error {
if db == nil { if err := ensureDB(); err != nil {
if err := InitDB(); err != nil { return err
return err
}
} }
_, err := db.Exec("DELETE FROM accounts") _, err := db.Exec("DELETE FROM accounts")
@@ -248,10 +374,8 @@ func ClearAllAccounts() error {
} }
func GetAccountByID(id int64) (*AccountDB, error) { func GetAccountByID(id int64) (*AccountDB, error) {
if db == nil { if err := ensureDB(); err != nil {
if err := InitDB(); err != nil { return nil, err
return nil, err
}
} }
var acc AccountDB var acc AccountDB
@@ -276,11 +400,42 @@ func GetAccountByID(id int64) (*AccountDB, error) {
return &acc, nil return &acc, nil
} }
func GetAccountByUsernameAndMediaType(username, mediaType string) (*AccountDB, error) {
if err := ensureDB(); err != nil {
return nil, err
}
if mediaType == "" {
mediaType = "all"
}
var acc AccountDB
var lastFetched time.Time
var completedInt int
err := db.QueryRow(`
SELECT id, username, name, profile_image, total_media, last_fetched, response_json,
COALESCE(media_type, 'all') as media_type,
COALESCE(cursor, '') as cursor, COALESCE(completed, 1) as completed
FROM accounts
WHERE LOWER(username) = LOWER(?) AND COALESCE(media_type, 'all') = ?
`, username, mediaType).Scan(&acc.ID, &acc.Username, &acc.Name, &acc.ProfileImage, &acc.TotalMedia, &lastFetched, &acc.ResponseJSON, &acc.MediaType, &acc.Cursor, &completedInt)
if err != nil {
return nil, err
}
acc.LastFetched = lastFetched
acc.Completed = completedInt == 1
if converted, err := ConvertLegacyToNewFormat(acc.ResponseJSON); err == nil {
acc.ResponseJSON = converted
}
return &acc, nil
}
func DeleteAccount(id int64) error { func DeleteAccount(id int64) error {
if db == nil { if err := ensureDB(); err != nil {
if err := InitDB(); err != nil { return err
return err
}
} }
_, err := db.Exec("DELETE FROM accounts WHERE id = ?", id) _, err := db.Exec("DELETE FROM accounts WHERE id = ?", id)
@@ -420,13 +575,7 @@ func ExportAccountsToTXT(ids []int64, outputDir string) (string, error) {
return "", fmt.Errorf("no valid usernames found") return "", fmt.Errorf("no valid usernames found")
} }
txtContent := "" txtContent := strings.Join(usernames, "\n")
for i, username := range usernames {
if i > 0 {
txtContent += "\n"
}
txtContent += username
}
filePath := filepath.Join(exportDir, "twitterxmediabatchdownloader_multiple.txt") filePath := filepath.Join(exportDir, "twitterxmediabatchdownloader_multiple.txt")
@@ -438,10 +587,8 @@ func ExportAccountsToTXT(ids []int64, outputDir string) (string, error) {
} }
func ImportAccountFromFile(filePath string) (string, error) { func ImportAccountFromFile(filePath string) (string, error) {
if db == nil { if err := ensureDB(); err != nil {
if err := InitDB(); err != nil { return "", err
return "", err
}
} }
data, err := os.ReadFile(filePath) data, err := os.ReadFile(filePath)
+7
View File
@@ -0,0 +1,7 @@
package backend
type DependencyVersionStatus struct {
Installed bool `json:"installed"`
InstalledVersion string `json:"installed_version,omitempty"`
LatestVersion string `json:"latest_version,omitempty"`
}
+486 -57
View File
@@ -2,6 +2,7 @@ package backend
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
"io" "io"
"net/http" "net/http"
@@ -15,20 +16,63 @@ import (
) )
const ( const (
MaxConcurrentDownloads = 10 DefaultConcurrentDownloads = 10
MaxConcurrentDownloads = 50
DefaultRetryAttempts = 2
MaxRetryAttempts = 5
) )
func NormalizeConcurrentDownloads(requested int) int {
if requested <= 0 {
return DefaultConcurrentDownloads
}
if requested > MaxConcurrentDownloads {
return MaxConcurrentDownloads
}
return requested
}
func NormalizeRetryAttempts(requested int) int {
if requested < 0 {
return 0
}
if requested > MaxRetryAttempts {
return MaxRetryAttempts
}
return requested
}
type DownloadOptions struct {
ConcurrentDownloads int
SkipExistingFiles bool
DeleteIncompleteFiles bool
RetryAttempts int
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)
return options
}
type MediaItem struct { type MediaItem struct {
URL string `json:"url"` URL string `json:"url"`
Date string `json:"date"` Date string `json:"date"`
TweetID int64 `json:"tweet_id"` TweetID int64 `json:"tweet_id"`
Type string `json:"type"` Type string `json:"type"`
Username string `json:"username"` Username string `json:"username"`
AccountName string `json:"account_name,omitempty"`
Content string `json:"content,omitempty"` Content string `json:"content,omitempty"`
OriginalFilename string `json:"original_filename,omitempty"` OriginalFilename string `json:"original_filename,omitempty"`
} }
func DownloadMediaFiles(urls []string, outputDir string, customProxy string) (downloaded int, failed int, err error) { func DownloadMediaFiles(urls []string, outputDir string, options DownloadOptions, customProxy string) (downloaded int, failed int, err error) {
options = NormalizeDownloadOptions(options)
if err := os.MkdirAll(outputDir, 0755); err != nil { if err := os.MkdirAll(outputDir, 0755); err != nil {
return 0, len(urls), fmt.Errorf("failed to create output directory: %v", err) return 0, len(urls), fmt.Errorf("failed to create output directory: %v", err)
@@ -46,12 +90,14 @@ func DownloadMediaFiles(urls []string, outputDir string, customProxy string) (do
filename := extractFilename(mediaURL) filename := extractFilename(mediaURL)
outputPath := filepath.Join(outputDir, filename) outputPath := filepath.Join(outputDir, filename)
if _, err := os.Stat(outputPath); err == nil { if options.SkipExistingFiles {
downloaded++ if _, err := os.Stat(outputPath); err == nil {
continue downloaded++
continue
}
} }
if err := downloadFile(client, mediaURL, outputPath); err != nil { if err := downloadFileWithRetry(context.Background(), client, mediaURL, outputPath, options); err != nil {
failed++ failed++
continue continue
} }
@@ -61,6 +107,140 @@ func DownloadMediaFiles(urls []string, outputDir string, customProxy string) (do
return downloaded, failed, nil return downloaded, failed, nil
} }
func fileExists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
}
if errors.Is(err, os.ErrNotExist) {
return false, nil
}
return false, err
}
func cleanupIncompleteDownload(outputPath string) {
_ = os.Remove(outputPath)
}
func replaceFile(tempPath, outputPath string, allowOverwrite bool) error {
if !allowOverwrite {
return os.Rename(tempPath, outputPath)
}
exists, err := fileExists(outputPath)
if err != nil {
return err
}
if !exists {
return os.Rename(tempPath, outputPath)
}
backupPath := fmt.Sprintf("%s.bak.%d", outputPath, time.Now().UnixNano())
if err := os.Rename(outputPath, backupPath); err != nil {
return err
}
if err := os.Rename(tempPath, outputPath); err != nil {
restoreErr := os.Rename(backupPath, outputPath)
if restoreErr != nil {
return fmt.Errorf("failed to replace existing file: %v (restore failed: %v)", err, restoreErr)
}
return err
}
_ = os.Remove(backupPath)
return nil
}
func writeFileAtomically(outputPath string, data []byte, allowOverwrite bool, keepPartialOnFailure bool) error {
out, err := os.CreateTemp(filepath.Dir(outputPath), filepath.Base(outputPath)+".*.part")
if err != nil {
return err
}
tempPath := out.Name()
cleanupTemp := !keepPartialOnFailure
defer func() {
if out != nil {
_ = out.Close()
}
if cleanupTemp {
_ = os.Remove(tempPath)
}
}()
if _, err := out.Write(data); err != nil {
return err
}
if err := out.Close(); err != nil {
return err
}
out = nil
if err := replaceFile(tempPath, outputPath, allowOverwrite); err != nil {
return err
}
cleanupTemp = false
return nil
}
func waitForRetry(ctx context.Context, attempt int) error {
timer := time.NewTimer(time.Duration(attempt) * 500 * time.Millisecond)
defer timer.Stop()
select {
case <-ctx.Done():
return ctx.Err()
case <-timer.C:
return nil
}
}
func downloadFileWithRetry(ctx context.Context, client *http.Client, mediaURL, outputPath string, options DownloadOptions) error {
options = NormalizeDownloadOptions(options)
var lastErr error
totalAttempts := options.RetryAttempts + 1
for attempt := 1; attempt <= totalAttempts; attempt++ {
keepPartialOnFailure := !options.DeleteIncompleteFiles && attempt == totalAttempts
lastErr = downloadFileWithContext(ctx, client, mediaURL, outputPath, !options.SkipExistingFiles, keepPartialOnFailure)
if lastErr == nil {
return nil
}
if ctx.Err() != nil || errors.Is(lastErr, context.Canceled) {
if options.DeleteIncompleteFiles {
cleanupIncompleteDownload(outputPath)
}
return lastErr
}
if options.DeleteIncompleteFiles {
cleanupIncompleteDownload(outputPath)
}
if attempt < totalAttempts {
if err := waitForRetry(ctx, attempt); err != nil {
if options.DeleteIncompleteFiles {
cleanupIncompleteDownload(outputPath)
}
return err
}
}
}
return lastErr
}
func writeTextFileWithOptions(outputPath string, content string, options DownloadOptions) error {
keepPartialOnFailure := !options.DeleteIncompleteFiles
if err := writeFileAtomically(outputPath, []byte(content), !options.SkipExistingFiles, keepPartialOnFailure); err != nil {
if options.DeleteIncompleteFiles {
cleanupIncompleteDownload(outputPath)
}
return err
}
return nil
}
type ProgressCallback func(current, total int) type ProgressCallback func(current, total int)
type ItemStatusCallback func(tweetID int64, index int, status string) // status: "success", "failed", "skipped" type ItemStatusCallback func(tweetID int64, index int, status string) // status: "success", "failed", "skipped"
@@ -71,10 +251,18 @@ type downloadTask struct {
index int index int
} }
func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir string, username string, progress ProgressCallback, itemStatus ItemStatusCallback, ctx context.Context, customProxy string) (downloaded int, skipped int, failed int, err error) { 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 { if ctx == nil {
ctx = context.Background() ctx = context.Background()
} }
options = NormalizeDownloadOptions(options)
total := len(items) total := len(items)
if total == 0 { if total == 0 {
@@ -82,7 +270,9 @@ func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir str
} }
tweetMediaCount := make(map[string]map[int64]int) tweetMediaCount := make(map[string]map[int64]int)
tasks := make([]downloadTask, 0, total) pendingTasks := make([]pendingDownloadTask, 0, total)
filenameCounts := make(map[string]int)
downloadDate := time.Now().Format("20060102")
for i, item := range items { for i, item := range items {
@@ -90,6 +280,10 @@ func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir str
if itemUsername == "" { if itemUsername == "" {
itemUsername = username itemUsername = username
} }
itemAccountName := item.AccountName
if itemAccountName == "" {
itemAccountName = itemUsername
}
if tweetMediaCount[itemUsername] == nil { if tweetMediaCount[itemUsername] == nil {
tweetMediaCount[itemUsername] = make(map[int64]int) tweetMediaCount[itemUsername] = make(map[int64]int)
@@ -109,7 +303,7 @@ func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir str
subfolder = "other" 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 { if err := os.MkdirAll(baseDir, 0755); err != nil {
continue continue
} }
@@ -126,25 +320,63 @@ func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir str
tweetMediaCount[itemUsername][item.TweetID]++ tweetMediaCount[itemUsername][item.TweetID]++
mediaIndex := tweetMediaCount[itemUsername][item.TweetID] mediaIndex := tweetMediaCount[itemUsername][item.TweetID]
filename := fmt.Sprintf("%s_%s_%d_%02d%s", itemUsername, timestamp, item.TweetID, mediaIndex, ext) mediaID := item.OriginalFilename
outputPath := filepath.Join(typeDir, filename) if mediaID == "" {
mediaID = ExtractOriginalFilename(item.URL)
}
tasks = append(tasks, downloadTask{ baseName := renderFilename(options.FilenameTemplate, itemUsername, itemAccountName, timestamp, item.TweetID, item.Type, mediaIndex, mediaID)
item: item, filenameCounts[filenameCollisionKey(typeDir, baseName, ext)]++
outputPath: outputPath,
index: i, 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 downloadedCount int64
var skippedCount int64 var skippedCount int64
var failedCount int64 var failedCount int64
var completedCount int64 var completedCount int64
var conversionWG sync.WaitGroup
taskChan := make(chan downloadTask, len(tasks)) taskChan := make(chan downloadTask, len(tasks))
var wg sync.WaitGroup var wg sync.WaitGroup
numWorkers := MaxConcurrentDownloads numWorkers := options.ConcurrentDownloads
if numWorkers > len(tasks) { if numWorkers > len(tasks) {
numWorkers = len(tasks) numWorkers = len(tasks)
} }
@@ -167,33 +399,61 @@ func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir str
client := sharedClient client := sharedClient
for task := range taskChan { for task := range taskChan {
markCompleted := func() {
completed := atomic.AddInt64(&completedCount, 1)
if progress != nil {
progress(int(completed), total)
}
}
select { if ctx.Err() != nil {
case <-ctx.Done(): if itemStatus != nil {
return itemStatus(task.item.TweetID, task.index, "cancelled")
default: }
markCompleted()
continue
} }
var status string var status string
if _, err := os.Stat(task.outputPath); err == nil { if options.SkipExistingFiles {
status = "skipped" exists, err := fileExists(task.outputPath)
if err == nil && exists {
status = "skipped"
if itemStatus != nil { if itemStatus != nil {
itemStatus(task.item.TweetID, task.index, status) itemStatus(task.item.TweetID, task.index, status)
}
atomic.AddInt64(&skippedCount, 1)
markCompleted()
continue
} }
atomic.AddInt64(&skippedCount, 1) }
continue
} else if task.item.Type == "text" {
if err := os.WriteFile(task.outputPath, []byte(task.item.Content), 0644); err != nil { if task.item.Type == "text" {
if ctx.Err() != nil {
if itemStatus != nil {
itemStatus(task.item.TweetID, task.index, "cancelled")
}
markCompleted()
continue
}
if err := writeTextFileWithOptions(task.outputPath, task.item.Content, options); err != nil {
atomic.AddInt64(&failedCount, 1) atomic.AddInt64(&failedCount, 1)
status = "failed" status = "failed"
} else { } else {
atomic.AddInt64(&downloadedCount, 1) atomic.AddInt64(&downloadedCount, 1)
status = "success" status = "success"
} }
} else if err := downloadFileWithContext(ctx, client, task.item.URL, task.outputPath); err != nil { } else if err := downloadFileWithRetry(ctx, client, task.item.URL, task.outputPath, options); err != nil {
if ctx.Err() != nil || errors.Is(err, context.Canceled) {
if itemStatus != nil {
itemStatus(task.item.TweetID, task.index, "cancelled")
}
markCompleted()
continue
}
atomic.AddInt64(&failedCount, 1) atomic.AddInt64(&failedCount, 1)
status = "failed" status = "failed"
} else { } else {
@@ -202,22 +462,30 @@ func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir str
originalFilename := ExtractOriginalFilename(task.item.URL) originalFilename := ExtractOriginalFilename(task.item.URL)
if err := EmbedMetadata(task.outputPath, task.item.Content, tweetURL, originalFilename); err != nil { if ctx.Err() == nil {
if err := EmbedMetadata(ctx, task.outputPath, task.item.Content, tweetURL, originalFilename); err != nil && !errors.Is(err, context.Canceled) {
}
} }
atomic.AddInt64(&downloadedCount, 1) atomic.AddInt64(&downloadedCount, 1)
status = "success" status = "success"
if shouldAutoConvertGIF(task.item.Type, options) && ctx.Err() == nil {
conversionWG.Add(1)
go func(inputPath string) {
defer conversionWG.Done()
outputPath := strings.TrimSuffix(inputPath, filepath.Ext(inputPath)) + ".gif"
_ = ConvertMP4ToGIFWithContext(ctx, inputPath, outputPath, normalizeGIFQuality(options.GIFQuality), normalizeGIFResolution(options.GIFResolution))
}(task.outputPath)
}
} }
if itemStatus != nil { if itemStatus != nil {
itemStatus(task.item.TweetID, task.index, status) itemStatus(task.item.TweetID, task.index, status)
} }
completed := atomic.AddInt64(&completedCount, 1) markCompleted()
if progress != nil {
progress(int(completed), total)
}
} }
}() }()
} }
@@ -227,18 +495,51 @@ func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir str
case <-ctx.Done(): case <-ctx.Done():
close(taskChan) close(taskChan)
wg.Wait() wg.Wait()
return int(downloadedCount), int(skippedCount), int(failedCount) + (total - int(completedCount)), ctx.Err() return int(downloadedCount), int(skippedCount), int(failedCount), ctx.Err()
case taskChan <- task: case taskChan <- task:
} }
} }
close(taskChan) close(taskChan)
wg.Wait() wg.Wait()
conversionWG.Wait()
if err := ctx.Err(); err != nil {
return int(downloadedCount), int(skippedCount), int(failedCount), err
}
return int(downloadedCount), int(skippedCount), int(failedCount), nil return int(downloadedCount), int(skippedCount), int(failedCount), nil
} }
func downloadFileWithContext(ctx context.Context, client *http.Client, url, outputPath string) 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) error {
req, err := http.NewRequestWithContext(ctx, "GET", url, nil) req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
if err != nil { if err != nil {
return err return err
@@ -254,14 +555,41 @@ func downloadFileWithContext(ctx context.Context, client *http.Client, url, outp
return fmt.Errorf("bad status: %s", resp.Status) return fmt.Errorf("bad status: %s", resp.Status)
} }
out, err := os.Create(outputPath) out, err := os.CreateTemp(filepath.Dir(outputPath), filepath.Base(outputPath)+".*.part")
if err != nil { if err != nil {
return err return err
} }
defer out.Close() tempPath := out.Name()
cleanupTemp := !keepPartialOnFailure
defer func() {
if out != nil {
_ = out.Close()
}
if cleanupTemp {
_ = os.Remove(tempPath)
}
}()
_, err = io.Copy(out, resp.Body) _, err = io.Copy(out, resp.Body)
return err if err != nil {
return err
}
if err := out.Close(); err != nil {
return err
}
out = nil
if ctx.Err() != nil {
return ctx.Err()
}
if err := replaceFile(tempPath, outputPath, allowOverwrite); err != nil {
return err
}
cleanupTemp = false
return nil
} }
func formatTimestamp(dateStr string) string { func formatTimestamp(dateStr string) string {
@@ -286,6 +614,92 @@ func formatTimestamp(dateStr string) string {
return "00000000_000000" 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 { func getExtension(mediaURL string, mediaType string) string {
parsedURL, err := url.Parse(mediaURL) parsedURL, err := url.Parse(mediaURL)
if err != nil { if err != nil {
@@ -350,22 +764,37 @@ func extractFilename(mediaURL string) string {
} }
func downloadFile(client *http.Client, url, outputPath string) error { func downloadFile(client *http.Client, url, outputPath string) error {
resp, err := client.Get(url) return downloadFileWithRetry(context.Background(), client, url, outputPath, DownloadOptions{
if err != nil { SkipExistingFiles: false,
return err DeleteIncompleteFiles: true,
} RetryAttempts: 0,
defer resp.Body.Close() })
}
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("bad status: %s", resp.Status) func DownloadProfileImage(imageURL, outputDir, username, kind, customProxy string) (string, error) {
} if strings.TrimSpace(imageURL) == "" {
return "", fmt.Errorf("no %s url available", kind)
out, err := os.Create(outputPath) }
if err != nil {
return err baseDir := outputDir
} if username != "" {
defer out.Close() baseDir = filepath.Join(outputDir, username)
}
_, err = io.Copy(out, resp.Body) if err := os.MkdirAll(baseDir, 0755); err != nil {
return err 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
} }
+356 -106
View File
@@ -2,32 +2,56 @@ package backend
import ( import (
"archive/zip" "archive/zip"
"crypto/sha256" "encoding/json"
"encoding/hex" "encoding/xml"
"fmt" "fmt"
"html"
"io" "io"
"net/http" "net/http"
"os" "os"
"os/exec" "os/exec"
"path/filepath" "path/filepath"
"regexp"
"runtime" "runtime"
"strings" "strings"
"time"
) )
const ( const (
exiftoolWindows64URL = "https://sourceforge.net/projects/exiftool/files/exiftool-13.43_64.zip/download" exiftoolBestReleaseAPIURL = "https://sourceforge.net/projects/exiftool/best_release.json"
exiftoolRSSURL = "https://sourceforge.net/projects/exiftool/rss?path=/"
exiftoolWindows32URL = "https://sourceforge.net/projects/exiftool/files/exiftool-13.43_32.zip/download" exiftoolFilesBaseURL = "https://sourceforge.net/projects/exiftool/files"
sourceForgeUserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36"
exiftoolUnixURL = "https://sourceforge.net/projects/exiftool/files/Image-ExifTool-13.43.tar.gz/download"
) )
const ( var (
exiftoolWindows64Hash = "" exiftoolVersionPattern = regexp.MustCompile(`(?i)(?:exiftool|image-exiftool)-([0-9]+(?:\.[0-9]+)+)`)
exiftoolWindows32Hash = "" sourceForgeMirrorMetaPattern = regexp.MustCompile(`(?i)url=(https?://downloads\.sourceforge\.net/project/[^"'<> ]+)`)
exiftoolUnixHash = "" sourceForgeMirrorURLPattern = regexp.MustCompile(`https?://downloads\.sourceforge\.net/project/[^"'<> ]+`)
) )
type sourceForgeBestRelease struct {
Release sourceForgeBestReleaseFile `json:"release"`
}
type sourceForgeBestReleaseFile struct {
Filename string `json:"filename"`
URL string `json:"url"`
}
type sourceForgeRSS struct {
Channel sourceForgeRSSChannel `xml:"channel"`
}
type sourceForgeRSSChannel struct {
Items []sourceForgeRSSItem `xml:"item"`
}
type sourceForgeRSSItem struct {
Title string `xml:"title"`
Link string `xml:"link"`
}
func GetExifToolPath() string { func GetExifToolPath() string {
homeDir, _ := os.UserHomeDir() homeDir, _ := os.UserHomeDir()
baseDir := filepath.Join(homeDir, ".twitterxmediabatchdownloader") baseDir := filepath.Join(homeDir, ".twitterxmediabatchdownloader")
@@ -36,11 +60,9 @@ func GetExifToolPath() string {
case "windows": case "windows":
return filepath.Join(baseDir, "exiftool.exe") return filepath.Join(baseDir, "exiftool.exe")
default: default:
pattern := filepath.Join(baseDir, "Image-ExifTool-*") pattern := filepath.Join(baseDir, "Image-ExifTool-*")
matches, err := filepath.Glob(pattern) matches, err := filepath.Glob(pattern)
if err == nil && len(matches) > 0 { if err == nil && len(matches) > 0 {
exiftoolPath := filepath.Join(matches[0], "exiftool") exiftoolPath := filepath.Join(matches[0], "exiftool")
if _, err := os.Stat(exiftoolPath); err == nil { if _, err := os.Stat(exiftoolPath); err == nil {
return exiftoolPath return exiftoolPath
@@ -52,44 +74,74 @@ func GetExifToolPath() string {
} }
func IsExifToolInstalled() bool { func IsExifToolInstalled() bool {
exiftoolPath := GetExifToolPath() _, err := getInstalledExifToolVersion()
if _, err := os.Stat(exiftoolPath); err == nil { return err == nil
}
cmd := exec.Command(exiftoolPath, "-ver") func GetExifToolVersionStatus() DependencyVersionStatus {
hideWindow(cmd) status := DependencyVersionStatus{
if err := cmd.Run(); err == nil { Installed: IsExifToolInstalled(),
return true }
if status.Installed {
if installedVersion, err := getInstalledExifToolVersion(); err == nil {
status.InstalledVersion = installedVersion
} }
} }
return false
if latestVersion, err := fetchLatestExifToolVersion(); err == nil {
status.LatestVersion = latestVersion
}
return status
} }
func calculateSHA256(filePath string) (string, error) { func getInstalledExifToolVersion() (string, error) {
file, err := os.Open(filePath) exiftoolPath := GetExifToolPath()
if _, err := os.Stat(exiftoolPath); err != nil {
return "", fmt.Errorf("exiftool not installed")
}
cmd := exec.Command(exiftoolPath, "-ver")
hideWindow(cmd)
output, err := cmd.Output()
if err != nil { if err != nil {
return "", err return "", fmt.Errorf("failed to determine exiftool version: %v", err)
}
defer file.Close()
hash := sha256.New()
if _, err := io.Copy(hash, file); err != nil {
return "", err
} }
return hex.EncodeToString(hash.Sum(nil)), nil version := normalizeExifToolVersion(string(output))
if version == "" {
return "", fmt.Errorf("failed to determine exiftool version")
}
return version, nil
} }
func verifyHash(filePath, expectedHash string) error { func normalizeExifToolVersion(version string) string {
actualHash, err := calculateSHA256(filePath) version = strings.TrimSpace(version)
if err != nil { if version == "" {
return fmt.Errorf("failed to calculate hash: %v", err) return ""
} }
if !strings.EqualFold(actualHash, expectedHash) { fields := strings.Fields(version)
return fmt.Errorf("hash verification failed: expected %s, got %s", expectedHash, actualHash) if len(fields) > 0 {
version = fields[0]
} }
return nil if strings.HasPrefix(strings.ToLower(version), "v") {
version = strings.TrimPrefix(strings.TrimPrefix(version, "v"), "V")
}
if version == "" {
return ""
}
first := version[0]
if first >= '0' && first <= '9' {
return "v" + version
}
return version
} }
func is64Bit() bool { func is64Bit() bool {
@@ -97,24 +149,14 @@ func is64Bit() bool {
} }
func DownloadExifTool(progressCallback func(downloaded, total int64)) error { func DownloadExifTool(progressCallback func(downloaded, total int64)) error {
var downloadURL string latestVersion, err := fetchLatestExifToolVersion()
var expectedHash string if err != nil {
return err
}
switch runtime.GOOS { downloadURL, err := buildLatestExifToolDownloadURL(latestVersion)
case "windows": if err != nil {
if is64Bit() { return err
downloadURL = exiftoolWindows64URL
expectedHash = exiftoolWindows64Hash
} else {
downloadURL = exiftoolWindows32URL
expectedHash = exiftoolWindows32Hash
}
case "linux", "darwin":
downloadURL = exiftoolUnixURL
expectedHash = exiftoolUnixHash
default:
return fmt.Errorf("unsupported platform: %s", runtime.GOOS)
} }
tempFile, err := os.CreateTemp("", "exiftool-*") tempFile, err := os.CreateTemp("", "exiftool-*")
@@ -123,47 +165,12 @@ func DownloadExifTool(progressCallback func(downloaded, total int64)) error {
} }
tempPath := tempFile.Name() tempPath := tempFile.Name()
defer os.Remove(tempPath) defer os.Remove(tempPath)
defer tempFile.Close() if err := tempFile.Close(); err != nil {
return fmt.Errorf("failed to prepare temp file: %v", err)
resp, err := http.Get(downloadURL)
if err != nil {
return fmt.Errorf("failed to download exiftool: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("failed to download exiftool: status %d", resp.StatusCode)
} }
total := resp.ContentLength if err := downloadSourceForgeFile(downloadURL, tempPath, progressCallback); err != nil {
var downloaded int64 return err
buf := make([]byte, 32*1024)
for {
n, err := resp.Body.Read(buf)
if n > 0 {
_, writeErr := tempFile.Write(buf[:n])
if writeErr != nil {
return fmt.Errorf("failed to write temp file: %v", writeErr)
}
downloaded += int64(n)
if progressCallback != nil {
progressCallback(downloaded, total)
}
}
if err == io.EOF {
break
}
if err != nil {
return fmt.Errorf("failed to download: %v", err)
}
}
tempFile.Close()
if expectedHash != "" {
if err := verifyHash(tempPath, expectedHash); err != nil {
return fmt.Errorf("hash verification failed: %v", err)
}
} }
exiftoolPath := GetExifToolPath() exiftoolPath := GetExifToolPath()
@@ -176,13 +183,254 @@ func DownloadExifTool(progressCallback func(downloaded, total int64)) error {
case "windows": case "windows":
return extractExifToolFromZip(tempPath, exiftoolPath) return extractExifToolFromZip(tempPath, exiftoolPath)
case "linux", "darwin": case "linux", "darwin":
return extractExifToolFromTarGz(tempPath, exiftoolPath) return extractExifToolFromTarGz(tempPath, exiftoolPath)
} }
return nil return nil
} }
func fetchLatestExifToolVersion() (string, error) {
version, err := fetchLatestExifToolVersionFromBestRelease()
if err == nil {
return version, nil
}
fallbackVersion, fallbackErr := fetchLatestExifToolVersionFromRSS()
if fallbackErr == nil {
return fallbackVersion, nil
}
return "", fmt.Errorf("failed to fetch latest exiftool version: %v; fallback failed: %v", err, fallbackErr)
}
func fetchLatestExifToolVersionFromBestRelease() (string, error) {
client, err := CreateHTTPClient("", 30*time.Second)
if err != nil {
return "", fmt.Errorf("failed to configure exiftool release client: %v", err)
}
req, err := http.NewRequest(http.MethodGet, exiftoolBestReleaseAPIURL, nil)
if err != nil {
return "", fmt.Errorf("failed to create exiftool release request: %v", err)
}
req.Header.Set("Accept", "application/json")
req.Header.Set("User-Agent", sourceForgeUserAgent)
resp, err := client.Do(req)
if err != nil {
return "", fmt.Errorf("failed to fetch exiftool release info: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("failed to fetch exiftool release info: status %d", resp.StatusCode)
}
var bestRelease sourceForgeBestRelease
if err := json.NewDecoder(resp.Body).Decode(&bestRelease); err != nil {
return "", fmt.Errorf("failed to decode exiftool release info: %v", err)
}
version := parseExifToolVersion(bestRelease.Release.Filename)
if version == "" {
version = parseExifToolVersion(bestRelease.Release.URL)
}
if version == "" {
return "", fmt.Errorf("failed to parse exiftool version from best_release.json")
}
return version, nil
}
func fetchLatestExifToolVersionFromRSS() (string, error) {
client, err := CreateHTTPClient("", 30*time.Second)
if err != nil {
return "", fmt.Errorf("failed to configure exiftool RSS client: %v", err)
}
req, err := http.NewRequest(http.MethodGet, exiftoolRSSURL, nil)
if err != nil {
return "", fmt.Errorf("failed to create exiftool RSS request: %v", err)
}
req.Header.Set("Accept", "application/rss+xml, application/xml, text/xml")
req.Header.Set("User-Agent", sourceForgeUserAgent)
resp, err := client.Do(req)
if err != nil {
return "", fmt.Errorf("failed to fetch exiftool RSS: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("failed to fetch exiftool RSS: status %d", resp.StatusCode)
}
var feed sourceForgeRSS
if err := xml.NewDecoder(resp.Body).Decode(&feed); err != nil {
return "", fmt.Errorf("failed to decode exiftool RSS: %v", err)
}
for _, item := range feed.Channel.Items {
version := parseExifToolVersion(item.Title)
if version == "" {
version = parseExifToolVersion(item.Link)
}
if version != "" {
return version, nil
}
}
return "", fmt.Errorf("failed to find exiftool version in RSS feed")
}
func parseExifToolVersion(value string) string {
matches := exiftoolVersionPattern.FindStringSubmatch(value)
if len(matches) < 2 {
return ""
}
return normalizeExifToolVersion(matches[1])
}
func buildLatestExifToolDownloadURL(version string) (string, error) {
version = normalizeExifToolVersion(version)
if version == "" {
return "", fmt.Errorf("missing exiftool version")
}
version = strings.TrimPrefix(strings.TrimPrefix(version, "v"), "V")
switch runtime.GOOS {
case "windows":
if is64Bit() {
return fmt.Sprintf("%s/exiftool-%s_64.zip/download", exiftoolFilesBaseURL, version), nil
}
return fmt.Sprintf("%s/exiftool-%s_32.zip/download", exiftoolFilesBaseURL, version), nil
case "linux", "darwin":
return fmt.Sprintf("%s/Image-ExifTool-%s.tar.gz/download", exiftoolFilesBaseURL, version), nil
default:
return "", fmt.Errorf("unsupported platform: %s", runtime.GOOS)
}
}
func downloadSourceForgeFile(downloadURL, destinationPath string, progressCallback func(downloaded, total int64)) error {
client, err := CreateHTTPClient("", 10*time.Minute)
if err != nil {
return fmt.Errorf("failed to configure SourceForge download client: %v", err)
}
err = downloadSourceForgeURL(client, downloadURL, destinationPath, progressCallback, 0)
if err == nil {
return nil
}
if runtime.GOOS == "windows" {
if fallbackErr := downloadSourceForgeFileWithCurl(downloadURL, destinationPath); fallbackErr == nil {
return nil
} else {
return fmt.Errorf("%v; curl fallback failed: %v", err, fallbackErr)
}
}
return err
}
func downloadSourceForgeURL(client *http.Client, downloadURL, destinationPath string, progressCallback func(downloaded, total int64), depth int) error {
if depth > 4 {
return fmt.Errorf("failed to resolve SourceForge mirror URL")
}
req, err := http.NewRequest(http.MethodGet, downloadURL, nil)
if err != nil {
return fmt.Errorf("failed to create SourceForge download request: %v", err)
}
req.Header.Set("User-Agent", sourceForgeUserAgent)
resp, err := client.Do(req)
if err != nil {
return fmt.Errorf("failed to download exiftool: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("failed to download exiftool: status %d", resp.StatusCode)
}
contentType := strings.ToLower(resp.Header.Get("Content-Type"))
if strings.Contains(contentType, "text/html") {
body, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("failed to read SourceForge download page: %v", err)
}
resolvedURL := extractSourceForgeMirrorURL(string(body))
if resolvedURL == "" {
return fmt.Errorf("failed to resolve SourceForge mirror URL from download page")
}
return downloadSourceForgeURL(client, resolvedURL, destinationPath, progressCallback, depth+1)
}
destination, err := os.OpenFile(destinationPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)
if err != nil {
return fmt.Errorf("failed to create exiftool archive: %v", err)
}
defer destination.Close()
total := resp.ContentLength
var downloaded int64
buf := make([]byte, 32*1024)
for {
n, err := resp.Body.Read(buf)
if n > 0 {
if _, writeErr := destination.Write(buf[:n]); writeErr != nil {
return fmt.Errorf("failed to write exiftool archive: %v", writeErr)
}
downloaded += int64(n)
if progressCallback != nil {
progressCallback(downloaded, total)
}
}
if err == io.EOF {
break
}
if err != nil {
return fmt.Errorf("failed to download exiftool: %v", err)
}
}
return nil
}
func downloadSourceForgeFileWithCurl(downloadURL, destinationPath string) error {
curlPath, err := exec.LookPath("curl.exe")
if err != nil {
curlPath, err = exec.LookPath("curl")
if err != nil {
return fmt.Errorf("curl executable not found")
}
}
cmd := exec.Command(curlPath, "-L", "-o", destinationPath, downloadURL)
hideWindow(cmd)
output, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("failed to download via curl: %v, output: %s", err, string(output))
}
return nil
}
func extractSourceForgeMirrorURL(page string) string {
page = html.UnescapeString(page)
if matches := sourceForgeMirrorMetaPattern.FindStringSubmatch(page); len(matches) > 1 {
return strings.TrimSpace(matches[1])
}
return strings.TrimSpace(sourceForgeMirrorURLPattern.FindString(page))
}
func extractExifToolFromZip(zipPath, destPath string) error { func extractExifToolFromZip(zipPath, destPath string) error {
r, err := zip.OpenReader(zipPath) r, err := zip.OpenReader(zipPath)
if err != nil { if err != nil {
@@ -221,10 +469,12 @@ func extractExifToolFromZip(zipPath, destPath string) error {
} }
libDir := filepath.Join(filepath.Dir(destPath), "exiftool_files") libDir := filepath.Join(filepath.Dir(destPath), "exiftool_files")
libDirAbs, err := filepath.Abs(libDir)
if err != nil {
return fmt.Errorf("failed to resolve libDir: %v", err)
}
for _, f := range r.File { for _, f := range r.File {
if strings.Contains(f.Name, "exiftool_files") && !strings.HasSuffix(f.Name, "/") { if strings.Contains(f.Name, "exiftool_files") && !strings.HasSuffix(f.Name, "/") {
parts := strings.Split(f.Name, "exiftool_files/") parts := strings.Split(f.Name, "exiftool_files/")
if len(parts) < 2 { if len(parts) < 2 {
continue continue
@@ -236,6 +486,14 @@ func extractExifToolFromZip(zipPath, destPath string) error {
targetPath := filepath.Join(libDir, relPath) targetPath := filepath.Join(libDir, relPath)
targetAbs, err := filepath.Abs(targetPath)
if err != nil {
continue
}
if !strings.HasPrefix(targetAbs+string(os.PathSeparator), libDirAbs+string(os.PathSeparator)) && targetAbs != libDirAbs {
continue
}
if err := os.MkdirAll(filepath.Dir(targetPath), 0755); err != nil { if err := os.MkdirAll(filepath.Dir(targetPath), 0755); err != nil {
continue continue
} }
@@ -266,7 +524,6 @@ func extractExifToolFromZip(zipPath, destPath string) error {
} }
func extractExifToolFromTarGz(tarGzPath, destPath string) error { func extractExifToolFromTarGz(tarGzPath, destPath string) error {
baseDir := filepath.Dir(destPath) baseDir := filepath.Dir(destPath)
cmd := exec.Command("tar", "-xzf", tarGzPath, "-C", baseDir) cmd := exec.Command("tar", "-xzf", tarGzPath, "-C", baseDir)
@@ -282,22 +539,15 @@ func extractExifToolFromTarGz(tarGzPath, destPath string) error {
pattern := filepath.Join(baseDir, "Image-ExifTool-*") pattern := filepath.Join(baseDir, "Image-ExifTool-*")
matches, err := filepath.Glob(pattern) matches, err := filepath.Glob(pattern)
if err == nil && len(matches) > 0 { if err == nil && len(matches) > 0 {
extractedDir = matches[0] extractedDir = matches[0]
exiftoolScript = filepath.Join(extractedDir, "exiftool") exiftoolScript = filepath.Join(extractedDir, "exiftool")
} else { } else {
extractedDir = filepath.Join(baseDir, "exiftool")
extractedDir = filepath.Join(baseDir, "Image-ExifTool-13.43")
exiftoolScript = filepath.Join(extractedDir, "exiftool") exiftoolScript = filepath.Join(extractedDir, "exiftool")
} }
if _, err := os.Stat(exiftoolScript); err != nil { if _, err := os.Stat(exiftoolScript); err != nil {
return fmt.Errorf("exiftool script not found in extracted archive (searched in: %s and %s)", pattern, extractedDir)
extractedDir = filepath.Join(baseDir, "exiftool")
exiftoolScript = filepath.Join(extractedDir, "exiftool")
if _, err := os.Stat(exiftoolScript); err != nil {
return fmt.Errorf("exiftool script not found in extracted archive (searched in: %s and %s)", pattern, extractedDir)
}
} }
if err := os.Chmod(exiftoolScript, 0755); err != nil { if err := os.Chmod(exiftoolScript, 0755); err != nil {
+253 -6
View File
@@ -17,6 +17,19 @@ import (
) )
const extractorReleaseAPIURL = "https://api.github.com/repos/afkarxyz/xtractor-binaries/releases/latest" const extractorReleaseAPIURL = "https://api.github.com/repos/afkarxyz/xtractor-binaries/releases/latest"
const extractorReleasesAPIURL = "https://api.github.com/repos/afkarxyz/xtractor-binaries/releases"
const extractorReleasePageSize = 20
type ExtractorVersionStatus struct {
Installed bool `json:"installed"`
InstalledVersion string `json:"installed_version,omitempty"`
LatestVersion string `json:"latest_version,omitempty"`
}
type extractorVersionMetadata struct {
Version string `json:"version"`
AssetName string `json:"asset_name,omitempty"`
}
type githubRelease struct { type githubRelease struct {
TagName string `json:"tag_name"` TagName string `json:"tag_name"`
@@ -34,6 +47,25 @@ func IsExtractorInstalled() bool {
return err == nil && !info.IsDir() return err == nil && !info.IsDir()
} }
func GetExtractorVersionStatus() ExtractorVersionStatus {
status := ExtractorVersionStatus{
Installed: IsExtractorInstalled(),
}
assetName, assetErr := getExtractorAssetName()
if status.Installed && assetErr == nil {
if installedVersion, err := getInstalledExtractorVersion(assetName); err == nil {
status.InstalledVersion = installedVersion
}
}
if latestRelease, err := fetchLatestExtractorRelease(); err == nil {
status.LatestVersion = normalizeExtractorVersion(latestRelease.TagName)
}
return status
}
func DownloadExtractor(progressCallback func(downloaded, total int64)) error { func DownloadExtractor(progressCallback func(downloaded, total int64)) error {
assetName, err := getExtractorAssetName() assetName, err := getExtractorAssetName()
if err != nil { if err != nil {
@@ -82,6 +114,10 @@ func DownloadExtractor(progressCallback func(downloaded, total int64)) error {
} }
_ = removeLegacyExtractorBinary() _ = removeLegacyExtractorBinary()
_ = writeExtractorVersionMetadata(extractorVersionMetadata{
Version: normalizeExtractorVersion(release.TagName),
AssetName: asset.Name,
})
return nil return nil
} }
@@ -108,8 +144,11 @@ func getExtractorAssetName() (string, error) {
return "windows-amd64.zip", nil return "windows-amd64.zip", nil
} }
case "linux": case "linux":
if runtime.GOARCH == "amd64" { switch runtime.GOARCH {
case "amd64":
return "linux-amd64.zip", nil return "linux-amd64.zip", nil
case "arm64":
return "linux-arm64.zip", nil
} }
case "darwin": case "darwin":
switch resolveMacOSExtractorArch(runtime.GOARCH, detectMacOSHardwareArch()) { switch resolveMacOSExtractorArch(runtime.GOARCH, detectMacOSHardwareArch()) {
@@ -136,7 +175,6 @@ func detectMacOSHardwareArch() string {
return "" return ""
} }
// On Apple Silicon, this stays "1" even if the app itself runs under Rosetta.
cmd := exec.Command("sysctl", "-in", "hw.optional.arm64") cmd := exec.Command("sysctl", "-in", "hw.optional.arm64")
hideWindow(cmd) hideWindow(cmd)
output, err := cmd.Output() output, err := cmd.Output()
@@ -157,12 +195,10 @@ func fetchLatestExtractorRelease() (*githubRelease, error) {
return nil, fmt.Errorf("failed to configure xtractor network client: %v", err) return nil, fmt.Errorf("failed to configure xtractor network client: %v", err)
} }
req, err := http.NewRequest(http.MethodGet, extractorReleaseAPIURL, nil) req, err := newExtractorGitHubRequest(extractorReleaseAPIURL)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to create xtractor release request: %v", err) return nil, err
} }
req.Header.Set("Accept", "application/vnd.github+json")
req.Header.Set("User-Agent", "Twitter-X-Media-Batch-Downloader")
resp, err := client.Do(req) resp, err := client.Do(req)
if err != nil { if err != nil {
@@ -182,6 +218,46 @@ func fetchLatestExtractorRelease() (*githubRelease, error) {
return &release, nil return &release, nil
} }
func fetchExtractorReleases(limit int) ([]githubRelease, error) {
client, err := CreateHTTPClient("", 60*time.Second)
if err != nil {
return nil, fmt.Errorf("failed to configure xtractor release client: %v", err)
}
req, err := newExtractorGitHubRequest(fmt.Sprintf("%s?per_page=%d", extractorReleasesAPIURL, limit))
if err != nil {
return nil, err
}
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to fetch xtractor releases: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("failed to fetch xtractor releases: status %d", resp.StatusCode)
}
var releases []githubRelease
if err := json.NewDecoder(resp.Body).Decode(&releases); err != nil {
return nil, fmt.Errorf("failed to decode xtractor releases: %v", err)
}
return releases, nil
}
func newExtractorGitHubRequest(url string) (*http.Request, error) {
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return nil, fmt.Errorf("failed to create xtractor GitHub request: %v", err)
}
req.Header.Set("Accept", "application/vnd.github+json")
req.Header.Set("User-Agent", "Twitter-X-Media-Batch-Downloader")
return req, nil
}
func findExtractorAsset(assets []githubReleaseAsset, assetName string) (*githubReleaseAsset, error) { func findExtractorAsset(assets []githubReleaseAsset, assetName string) (*githubReleaseAsset, error) {
for i := range assets { for i := range assets {
if assets[i].Name == assetName { if assets[i].Name == assetName {
@@ -348,6 +424,177 @@ func findExtractorBinaryEntry(entries []*zip.File) (*zip.File, error) {
return nil, fmt.Errorf("xtractor binary not found in archive") return nil, fmt.Errorf("xtractor binary not found in archive")
} }
func getInstalledExtractorVersion(assetName string) (string, error) {
metadata, err := readExtractorVersionMetadata()
if err == nil {
version := normalizeExtractorVersion(metadata.Version)
if version != "" && (metadata.AssetName == "" || strings.EqualFold(metadata.AssetName, assetName)) {
return version, nil
}
}
version, err := resolveInstalledExtractorVersionByHash(assetName)
if err != nil {
return "", err
}
version = normalizeExtractorVersion(version)
if version != "" {
_ = writeExtractorVersionMetadata(extractorVersionMetadata{
Version: version,
AssetName: assetName,
})
}
return version, nil
}
func resolveInstalledExtractorVersionByHash(assetName string) (string, error) {
exePath, err := requireExtractorPath()
if err != nil {
return "", err
}
installedHash, err := hashFileSHA256(exePath)
if err != nil {
return "", fmt.Errorf("failed to hash installed xtractor: %v", err)
}
releases, err := fetchExtractorReleases(extractorReleasePageSize)
if err != nil {
return "", err
}
for _, release := range releases {
asset, err := findExtractorAsset(release.Assets, assetName)
if err != nil {
continue
}
matches, err := archiveMatchesExtractorHash(asset.BrowserDownloadURL, installedHash)
if err != nil {
continue
}
if matches {
return release.TagName, nil
}
}
return "", nil
}
func archiveMatchesExtractorHash(downloadURL, installedHash string) (bool, error) {
tempFile, err := os.CreateTemp("", "xtractor-version-*.zip")
if err != nil {
return false, fmt.Errorf("failed to create temp archive for version check: %v", err)
}
tempPath := tempFile.Name()
defer os.Remove(tempPath)
defer tempFile.Close()
if err := downloadExtractorArchive(downloadURL, tempFile, nil); err != nil {
return false, err
}
if err := tempFile.Close(); err != nil {
return false, fmt.Errorf("failed to finalize version archive: %v", err)
}
archiveHash, err := hashExtractorBinaryInArchive(tempPath)
if err != nil {
return false, err
}
return archiveHash == installedHash, nil
}
func hashExtractorBinaryInArchive(zipPath string) (string, error) {
reader, err := zip.OpenReader(zipPath)
if err != nil {
return "", fmt.Errorf("failed to open xtractor archive for version check: %v", err)
}
defer reader.Close()
entry, err := findExtractorBinaryEntry(reader.File)
if err != nil {
return "", err
}
in, err := entry.Open()
if err != nil {
return "", fmt.Errorf("failed to open xtractor binary from archive for version check: %v", err)
}
defer in.Close()
return hashReaderSHA256(in)
}
func hashFileSHA256(filePath string) (string, error) {
file, err := os.Open(filePath)
if err != nil {
return "", fmt.Errorf("failed to open xtractor binary: %v", err)
}
defer file.Close()
return hashReaderSHA256(file)
}
func hashReaderSHA256(reader io.Reader) (string, error) {
hash := sha256.New()
if _, err := io.Copy(hash, reader); err != nil {
return "", err
}
return hex.EncodeToString(hash.Sum(nil)), nil
}
func getExtractorVersionMetadataPath() string {
return filepath.Join(filepath.Dir(getExtractorPath()), "xtractor-version.json")
}
func readExtractorVersionMetadata() (extractorVersionMetadata, error) {
data, err := os.ReadFile(getExtractorVersionMetadataPath())
if err != nil {
return extractorVersionMetadata{}, err
}
var metadata extractorVersionMetadata
if err := json.Unmarshal(data, &metadata); err != nil {
return extractorVersionMetadata{}, err
}
return metadata, nil
}
func writeExtractorVersionMetadata(metadata extractorVersionMetadata) error {
metadata.Version = normalizeExtractorVersion(metadata.Version)
if metadata.Version == "" {
return nil
}
path := getExtractorVersionMetadataPath()
if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
return fmt.Errorf("failed to create xtractor metadata directory: %v", err)
}
data, err := json.Marshal(metadata)
if err != nil {
return fmt.Errorf("failed to encode xtractor metadata: %v", err)
}
if err := os.WriteFile(path, data, 0644); err != nil {
return fmt.Errorf("failed to write xtractor metadata: %v", err)
}
return nil
}
func normalizeExtractorVersion(version string) string {
return strings.TrimSpace(version)
}
func getLegacyExtractorPath() string { func getLegacyExtractorPath() string {
homeDir, _ := os.UserHomeDir() homeDir, _ := os.UserHomeDir()
baseDir := filepath.Join(homeDir, ".twitterxmediabatchdownloader") baseDir := filepath.Join(homeDir, ".twitterxmediabatchdownloader")
+439 -95
View File
@@ -1,26 +1,42 @@
package backend package backend
import ( import (
"archive/tar"
"archive/zip" "archive/zip"
"context"
"encoding/json"
"fmt" "fmt"
"io" "io"
"net/http" "net/http"
neturl "net/url"
"os" "os"
"os/exec" "os/exec"
"path/filepath" "path/filepath"
"regexp"
"runtime" "runtime"
"strings" "strings"
"time"
"github.com/ulikunitz/xz"
) )
const ( const (
ffmpegWindowsURL = "https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/ffmpeg-master-latest-win64-gpl.zip" ffmpegReleaseAPIURL = "https://api.github.com/repos/spotbye/Dependencies/releases/tags/FFmpeg-8.1"
ffmpegLinuxURL = "https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/ffmpeg-master-latest-linux64-gpl.tar.xz" ffmpegLatestReleaseURL = "https://github.com/spotbye/Dependencies/releases/tag/FFmpeg-8.1"
ffmpegMacOSURL = "https://evermeet.cx/ffmpeg/getrelease/ffmpeg/zip" ffmpegLatestDownloadBaseURL = "https://github.com/spotbye/Dependencies/releases/download/FFmpeg-8.1"
) )
var ffmpegVersionPattern = regexp.MustCompile(`^[0-9]+(?:\.[0-9]+)+`)
type ffmpegVersionMetadata struct {
Version string `json:"version"`
AssetName string `json:"asset_name,omitempty"`
}
type ffmpegResolvedRelease struct {
Version string
AssetURL string
AssetName string
Digest string
}
func GetFFmpegPath() string { func GetFFmpegPath() string {
homeDir, _ := os.UserHomeDir() homeDir, _ := os.UserHomeDir()
baseDir := filepath.Join(homeDir, ".twitterxmediabatchdownloader") baseDir := filepath.Join(homeDir, ".twitterxmediabatchdownloader")
@@ -35,27 +51,45 @@ func GetFFmpegPath() string {
func IsFFmpegInstalled() bool { func IsFFmpegInstalled() bool {
ffmpegPath := GetFFmpegPath() ffmpegPath := GetFFmpegPath()
if _, err := os.Stat(ffmpegPath); err == nil { if _, err := os.Stat(ffmpegPath); err != nil {
return true return false
} }
return false
cmd := exec.Command(ffmpegPath, "-version")
hideWindow(cmd)
return cmd.Run() == nil
}
func GetFFmpegVersionStatus() DependencyVersionStatus {
status := DependencyVersionStatus{
Installed: IsFFmpegInstalled(),
}
if status.Installed {
if installedVersion, err := getInstalledFFmpegVersion(); err == nil {
status.InstalledVersion = installedVersion
}
}
if latestVersion, err := fetchLatestFFmpegVersion(); err == nil {
status.LatestVersion = latestVersion
}
return status
} }
func DownloadFFmpeg(progressCallback func(downloaded, total int64)) error { func DownloadFFmpeg(progressCallback func(downloaded, total int64)) error {
var downloadURL string assetName, err := getFFmpegAssetName()
if err != nil {
switch runtime.GOOS { return err
case "windows":
downloadURL = ffmpegWindowsURL
case "linux":
downloadURL = ffmpegLinuxURL
case "darwin":
downloadURL = ffmpegMacOSURL
default:
return fmt.Errorf("unsupported platform: %s", runtime.GOOS)
} }
tempFile, err := os.CreateTemp("", "ffmpeg-*") releaseInfo, err := resolveLatestFFmpegRelease(assetName)
if err != nil {
return err
}
tempFile, err := os.CreateTemp("", "ffmpeg-*.zip")
if err != nil { if err != nil {
return fmt.Errorf("failed to create temp file: %v", err) return fmt.Errorf("failed to create temp file: %v", err)
} }
@@ -63,7 +97,227 @@ func DownloadFFmpeg(progressCallback func(downloaded, total int64)) error {
defer os.Remove(tempPath) defer os.Remove(tempPath)
defer tempFile.Close() defer tempFile.Close()
resp, err := http.Get(downloadURL) if err := downloadFFmpegArchive(releaseInfo.AssetURL, tempFile, progressCallback); err != nil {
return err
}
if err := tempFile.Close(); err != nil {
return fmt.Errorf("failed to finalize ffmpeg archive: %v", err)
}
if releaseInfo.Digest != "" {
if err := verifyDownloadedDigest(tempPath, releaseInfo.Digest); err != nil {
return err
}
}
ffmpegPath := GetFFmpegPath()
baseDir := filepath.Dir(ffmpegPath)
if err := os.MkdirAll(baseDir, 0755); err != nil {
return fmt.Errorf("failed to create ffmpeg directory: %v", err)
}
if err := extractFFmpegFromZip(tempPath, ffmpegPath); err != nil {
return err
}
_ = writeFFmpegVersionMetadata(ffmpegVersionMetadata{
Version: releaseInfo.Version,
AssetName: releaseInfo.AssetName,
})
return nil
}
func getFFmpegAssetName() (string, error) {
switch runtime.GOOS {
case "windows":
return "ffmpeg-windows.zip", nil
case "linux":
switch runtime.GOARCH {
case "amd64":
return "ffmpeg-linux-amd64.zip", nil
case "arm64":
return "ffmpeg-linux-arm64v8.zip", nil
}
case "darwin":
switch runtime.GOARCH {
case "amd64":
return "ffmpeg-macos-amd64.zip", nil
case "arm64":
return "ffmpeg-macos-arm64.zip", nil
}
}
return "", fmt.Errorf("unsupported platform for ffmpeg binary: %s/%s", runtime.GOOS, runtime.GOARCH)
}
func resolveLatestFFmpegRelease(assetName string) (ffmpegResolvedRelease, error) {
release, apiErr := fetchLatestFFmpegRelease()
if apiErr == nil {
asset, assetErr := findFFmpegAsset(release.Assets, assetName)
if assetErr == nil {
return ffmpegResolvedRelease{
Version: normalizeFFmpegVersion(release.TagName),
AssetURL: asset.BrowserDownloadURL,
AssetName: asset.Name,
Digest: asset.Digest,
}, nil
}
apiErr = assetErr
}
fallbackVersion, fallbackErr := fetchLatestFFmpegVersionFromRedirect()
if fallbackErr != nil {
return ffmpegResolvedRelease{}, fmt.Errorf("failed to resolve latest ffmpeg release: %v; fallback failed: %v", apiErr, fallbackErr)
}
return ffmpegResolvedRelease{
Version: fallbackVersion,
AssetURL: buildLatestFFmpegDownloadURL(assetName),
AssetName: assetName,
}, nil
}
func fetchLatestFFmpegVersion() (string, error) {
release, err := fetchLatestFFmpegRelease()
if err == nil {
version := normalizeFFmpegVersion(release.TagName)
if version != "" {
return version, nil
}
}
fallbackVersion, fallbackErr := fetchLatestFFmpegVersionFromRedirect()
if fallbackErr == nil {
return fallbackVersion, nil
}
if err != nil {
return "", fmt.Errorf("failed to fetch latest ffmpeg version: %v; fallback failed: %v", err, fallbackErr)
}
return "", fmt.Errorf("failed to determine latest ffmpeg version")
}
func fetchLatestFFmpegRelease() (*githubRelease, error) {
client, err := CreateHTTPClient("", 30*time.Second)
if err != nil {
return nil, fmt.Errorf("failed to configure ffmpeg network client: %v", err)
}
req, err := newFFmpegGitHubRequest(ffmpegReleaseAPIURL)
if err != nil {
return nil, err
}
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to fetch ffmpeg release info: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
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 {
return nil, fmt.Errorf("failed to decode ffmpeg release info: %v", err)
}
return &release, nil
}
func newFFmpegGitHubRequest(url string) (*http.Request, error) {
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return nil, fmt.Errorf("failed to create ffmpeg GitHub request: %v", err)
}
req.Header.Set("Accept", "application/vnd.github+json")
req.Header.Set("User-Agent", "Twitter-X-Media-Batch-Downloader")
return req, nil
}
func findFFmpegAsset(assets []githubReleaseAsset, assetName string) (*githubReleaseAsset, error) {
for i := range assets {
if assets[i].Name == assetName {
return &assets[i], nil
}
}
return nil, fmt.Errorf("ffmpeg asset %q not found in latest release", assetName)
}
func fetchLatestFFmpegVersionFromRedirect() (string, error) {
client, err := CreateHTTPClient("", 30*time.Second)
if err != nil {
return "", fmt.Errorf("failed to configure ffmpeg redirect client: %v", err)
}
client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
}
req, err := http.NewRequest(http.MethodGet, ffmpegLatestReleaseURL, nil)
if err != nil {
return "", fmt.Errorf("failed to create ffmpeg redirect request: %v", err)
}
req.Header.Set("User-Agent", "Twitter-X-Media-Batch-Downloader")
resp, err := client.Do(req)
if err != nil {
return "", fmt.Errorf("failed to resolve latest ffmpeg redirect: %v", err)
}
defer resp.Body.Close()
location := resp.Header.Get("Location")
if location == "" && resp.Request != nil && resp.Request.URL != nil {
location = resp.Request.URL.String()
}
version := parseFFmpegVersionFromReleaseURL(location)
if version == "" {
return "", fmt.Errorf("failed to parse ffmpeg version from redirect URL")
}
return version, nil
}
func parseFFmpegVersionFromReleaseURL(releaseURL string) string {
parsed, err := neturl.Parse(strings.TrimSpace(releaseURL))
if err != nil {
return ""
}
segments := strings.Split(strings.Trim(parsed.Path, "/"), "/")
for index, segment := range segments {
if (segment == "tag" || segment == "download") && index+1 < len(segments) {
return normalizeFFmpegVersion(segments[index+1])
}
}
return ""
}
func buildLatestFFmpegDownloadURL(assetName string) string {
return ffmpegLatestDownloadBaseURL + "/" + assetName
}
func downloadFFmpegArchive(downloadURL string, destination *os.File, progressCallback func(downloaded, total int64)) error {
client, err := CreateHTTPClient("", 10*time.Minute)
if err != nil {
return fmt.Errorf("failed to configure ffmpeg download client: %v", err)
}
req, err := http.NewRequest(http.MethodGet, downloadURL, nil)
if err != nil {
return fmt.Errorf("failed to create ffmpeg download request: %v", err)
}
req.Header.Set("User-Agent", "Twitter-X-Media-Batch-Downloader")
resp, err := client.Do(req)
if err != nil { if err != nil {
return fmt.Errorf("failed to download ffmpeg: %v", err) return fmt.Errorf("failed to download ffmpeg: %v", err)
} }
@@ -80,9 +334,8 @@ func DownloadFFmpeg(progressCallback func(downloaded, total int64)) error {
for { for {
n, err := resp.Body.Read(buf) n, err := resp.Body.Read(buf)
if n > 0 { if n > 0 {
_, writeErr := tempFile.Write(buf[:n]) if _, writeErr := destination.Write(buf[:n]); writeErr != nil {
if writeErr != nil { return fmt.Errorf("failed to write ffmpeg archive: %v", writeErr)
return fmt.Errorf("failed to write temp file: %v", writeErr)
} }
downloaded += int64(n) downloaded += int64(n)
if progressCallback != nil { if progressCallback != nil {
@@ -93,28 +346,14 @@ func DownloadFFmpeg(progressCallback func(downloaded, total int64)) error {
break break
} }
if err != nil { if err != nil {
return fmt.Errorf("failed to download: %v", err) return fmt.Errorf("failed to download ffmpeg: %v", err)
} }
} }
tempFile.Close()
ffmpegPath := GetFFmpegPath()
baseDir := filepath.Dir(ffmpegPath)
if err := os.MkdirAll(baseDir, 0755); err != nil {
return fmt.Errorf("failed to create directory: %v", err)
}
switch runtime.GOOS {
case "windows", "darwin":
return extractFromZip(tempPath, ffmpegPath)
case "linux":
return extractFromTarXz(tempPath, ffmpegPath)
}
return nil return nil
} }
func extractFromZip(zipPath, destPath string) error { func extractFFmpegFromZip(zipPath, destPath string) error {
r, err := zip.OpenReader(zipPath) r, err := zip.OpenReader(zipPath)
if err != nil { if err != nil {
return fmt.Errorf("failed to open zip: %v", err) return fmt.Errorf("failed to open zip: %v", err)
@@ -122,90 +361,193 @@ func extractFromZip(zipPath, destPath string) error {
defer r.Close() defer r.Close()
for _, f := range r.File { for _, f := range r.File {
name := filepath.Base(f.Name) name := filepath.Base(f.Name)
if name == "ffmpeg" || name == "ffmpeg.exe" { if name != "ffmpeg" && name != "ffmpeg.exe" {
rc, err := f.Open() continue
if err != nil {
return fmt.Errorf("failed to open file in zip: %v", err)
}
defer rc.Close()
out, err := os.Create(destPath)
if err != nil {
return fmt.Errorf("failed to create output file: %v", err)
}
defer out.Close()
if _, err := io.Copy(out, rc); err != nil {
return fmt.Errorf("failed to extract file: %v", err)
}
if runtime.GOOS != "windows" {
os.Chmod(destPath, 0755)
}
return nil
} }
rc, err := f.Open()
if err != nil {
return fmt.Errorf("failed to open file in zip: %v", err)
}
defer rc.Close()
out, err := os.Create(destPath)
if err != nil {
return fmt.Errorf("failed to create output file: %v", err)
}
defer out.Close()
if _, err := io.Copy(out, rc); err != nil {
return fmt.Errorf("failed to extract file: %v", err)
}
if runtime.GOOS != "windows" {
if err := os.Chmod(destPath, 0755); err != nil {
return fmt.Errorf("failed to make ffmpeg executable: %v", err)
}
}
return nil
} }
return fmt.Errorf("ffmpeg binary not found in archive") return fmt.Errorf("ffmpeg binary not found in archive")
} }
func extractFromTarXz(tarXzPath, destPath string) error { func getInstalledFFmpegVersion() (string, error) {
file, err := os.Open(tarXzPath) ffmpegPath := GetFFmpegPath()
if _, err := os.Stat(ffmpegPath); err != nil {
return "", fmt.Errorf("ffmpeg not installed")
}
cmd := exec.Command(ffmpegPath, "-version")
hideWindow(cmd)
output, err := cmd.Output()
if err == nil {
version := normalizeFFmpegVersionOutput(string(output))
if version != "" {
return version, nil
}
}
metadata, metadataErr := readFFmpegVersionMetadata()
if metadataErr == nil {
version := normalizeFFmpegVersion(metadata.Version)
if version != "" {
return version, nil
}
}
if err != nil { if err != nil {
return fmt.Errorf("failed to open tar.xz: %v", err) return "", fmt.Errorf("failed to determine ffmpeg version: %v", err)
} }
defer file.Close()
xzReader, err := xz.NewReader(file) return "", fmt.Errorf("failed to determine ffmpeg version")
}
func normalizeFFmpegVersionOutput(output string) string {
line := strings.TrimSpace(output)
if line == "" {
return ""
}
line = strings.Split(line, "\n")[0]
line = strings.TrimSpace(line)
lowerLine := strings.ToLower(line)
const prefix = "ffmpeg version "
if strings.HasPrefix(lowerLine, prefix) {
line = strings.TrimSpace(line[len(prefix):])
}
fields := strings.Fields(line)
if len(fields) > 0 {
line = fields[0]
}
return normalizeFFmpegVersion(line)
}
func getFFmpegVersionMetadataPath() string {
return filepath.Join(filepath.Dir(GetFFmpegPath()), "ffmpeg-version.json")
}
func readFFmpegVersionMetadata() (ffmpegVersionMetadata, error) {
data, err := os.ReadFile(getFFmpegVersionMetadataPath())
if err != nil { if err != nil {
return fmt.Errorf("failed to create xz reader: %v", err) return ffmpegVersionMetadata{}, err
} }
tarReader := tar.NewReader(xzReader) var metadata ffmpegVersionMetadata
if err := json.Unmarshal(data, &metadata); err != nil {
return ffmpegVersionMetadata{}, err
}
for { return metadata, nil
header, err := tarReader.Next() }
if err == io.EOF {
break
}
if err != nil {
return fmt.Errorf("failed to read tar: %v", err)
}
name := filepath.Base(header.Name) func writeFFmpegVersionMetadata(metadata ffmpegVersionMetadata) error {
if name == "ffmpeg" && header.Typeflag == tar.TypeReg { metadata.Version = normalizeFFmpegVersion(metadata.Version)
out, err := os.Create(destPath) if metadata.Version == "" {
if err != nil { return nil
return fmt.Errorf("failed to create output file: %v", err) }
}
defer out.Close()
if _, err := io.Copy(out, tarReader); err != nil { path := getFFmpegVersionMetadataPath()
return fmt.Errorf("failed to extract file: %v", err) if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
} return fmt.Errorf("failed to create ffmpeg metadata directory: %v", err)
}
os.Chmod(destPath, 0755) data, err := json.Marshal(metadata)
return nil if err != nil {
return fmt.Errorf("failed to encode ffmpeg metadata: %v", err)
}
if err := os.WriteFile(path, data, 0644); err != nil {
return fmt.Errorf("failed to write ffmpeg metadata: %v", err)
}
return nil
}
func normalizeFFmpegVersion(version string) string {
version = strings.TrimSpace(version)
if version == "" {
return ""
}
lowerVersion := strings.ToLower(version)
if strings.HasPrefix(lowerVersion, "ffmpeg version ") {
version = strings.TrimSpace(version[len("ffmpeg version "):])
}
fields := strings.Fields(version)
if len(fields) > 0 {
version = fields[0]
}
if strings.HasPrefix(strings.ToLower(version), "n") && len(version) > 1 {
next := version[1]
if next >= '0' && next <= '9' {
version = version[1:]
} }
} }
return fmt.Errorf("ffmpeg binary not found in archive") if strings.HasPrefix(strings.ToLower(version), "v") {
version = strings.TrimPrefix(strings.TrimPrefix(version, "v"), "V")
}
if version == "" {
return ""
}
if numericVersion := ffmpegVersionPattern.FindString(version); numericVersion != "" {
version = numericVersion
}
first := version[0]
if first >= '0' && first <= '9' {
return "v" + version
}
return version
} }
func ConvertMP4ToGIF(inputPath, outputPath, quality, resolution string) error { func ConvertMP4ToGIF(inputPath, outputPath, quality, resolution string) error {
return ConvertMP4ToGIFWithContext(context.Background(), inputPath, outputPath, quality, resolution)
}
func ConvertMP4ToGIFWithContext(ctx context.Context, inputPath, outputPath, quality, resolution string) error {
ffmpegPath := GetFFmpegPath() ffmpegPath := GetFFmpegPath()
if !IsFFmpegInstalled() { if !IsFFmpegInstalled() {
return fmt.Errorf("ffmpeg not installed") return fmt.Errorf("ffmpeg not installed")
} }
if ctx == nil {
ctx = context.Background()
}
var args []string var args []string
if quality == "fast" { if quality == "fast" {
var scaleFilter string var scaleFilter string
switch resolution { switch resolution {
case "high": case "high":
@@ -235,7 +577,6 @@ func ConvertMP4ToGIF(inputPath, outputPath, quality, resolution string) error {
} }
} }
} else { } else {
var filter string var filter string
switch resolution { switch resolution {
@@ -265,10 +606,13 @@ func ConvertMP4ToGIF(inputPath, outputPath, quality, resolution string) error {
} }
} }
cmd := exec.Command(ffmpegPath, args...) cmd := exec.CommandContext(ctx, ffmpegPath, args...)
hideWindow(cmd) hideWindow(cmd)
output, err := cmd.CombinedOutput() output, err := cmd.CombinedOutput()
if err != nil { if err != nil {
if ctx.Err() != nil {
return ctx.Err()
}
return fmt.Errorf("ffmpeg error: %v, output: %s", err, string(output)) return fmt.Errorf("ffmpeg error: %v, output: %s", err, string(output))
} }
+29 -2
View File
@@ -11,12 +11,20 @@ import (
) )
func OpenFolderInExplorer(path string) error { func OpenFolderInExplorer(path string) error {
os.WriteFile(filepath.Join(os.TempDir(), "openfolder.txt"), []byte(path), 0644)
info, err := os.Stat(path)
if err != nil {
return err
}
if !info.IsDir() {
return os.ErrInvalid
}
var cmd *exec.Cmd var cmd *exec.Cmd
switch runtime.GOOS { switch runtime.GOOS {
case "windows": case "windows":
cmd = exec.Command("cmd", "/C", "start", "", path)
cmd = exec.Command("cmd", "/c", "start", "", path)
case "darwin": case "darwin":
cmd = exec.Command("open", path) cmd = exec.Command("open", path)
case "linux": case "linux":
@@ -61,6 +69,25 @@ func CheckFolderExists(basePath, username string) bool {
return info.IsDir() return info.IsDir()
} }
func CheckFoldersExist(basePath string, usernames []string) map[string]bool {
results := make(map[string]bool, len(usernames))
if basePath == "" {
return results
}
checked := make(map[string]bool, len(usernames))
for _, username := range usernames {
if _, alreadyChecked := checked[username]; alreadyChecked {
continue
}
exists := CheckFolderExists(basePath, username)
checked[username] = exists
results[username] = exists
}
return results
}
func CheckGifsFolderExists(basePath, username string) bool { func CheckGifsFolderExists(basePath, username string) bool {
gifsPath := filepath.Join(basePath, username, "gifs") gifsPath := filepath.Join(basePath, username, "gifs")
info, err := os.Stat(gifsPath) info, err := os.Stat(gifsPath)
+34 -14
View File
@@ -1,6 +1,7 @@
package backend package backend
import ( import (
"context"
"fmt" "fmt"
"net/url" "net/url"
"os" "os"
@@ -11,6 +12,11 @@ import (
"strings" "strings"
) )
var (
filenameSafeRegex = regexp.MustCompile(`^[A-Za-z0-9_]+$`)
filenameLetterRegex = regexp.MustCompile(`[A-Za-z]`)
)
func ExtractOriginalFilename(mediaURL string) string { func ExtractOriginalFilename(mediaURL string) string {
parsedURL, err := url.Parse(mediaURL) parsedURL, err := url.Parse(mediaURL)
if err != nil { if err != nil {
@@ -29,7 +35,7 @@ func ExtractOriginalFilename(mediaURL string) string {
filename = filename[:idx] filename = filename[:idx]
} }
if matched, _ := regexp.MatchString(`^[A-Za-z0-9_]+$`, filename); matched && len(filename) > 0 { if filenameSafeRegex.MatchString(filename) && len(filename) > 0 {
return filename return filename
} }
} }
@@ -44,7 +50,7 @@ func ExtractOriginalFilename(mediaURL string) string {
filename = filename[:idx] filename = filename[:idx]
} }
if matched, _ := regexp.MatchString(`^[A-Za-z0-9_]+$`, filename); matched && len(filename) > 0 { if filenameSafeRegex.MatchString(filename) && len(filename) > 0 {
return filename return filename
} }
} }
@@ -58,9 +64,8 @@ func ExtractOriginalFilename(mediaURL string) string {
filename = filename[:idx] filename = filename[:idx]
} }
if matched, _ := regexp.MatchString(`^[A-Za-z0-9_]+$`, filename); matched { if filenameSafeRegex.MatchString(filename) {
hasLetter, _ := regexp.MatchString(`[A-Za-z]`, filename) if filenameLetterRegex.MatchString(filename) && len(filename) >= 8 {
if hasLetter && len(filename) >= 8 {
return filename return filename
} }
} }
@@ -70,21 +75,24 @@ func ExtractOriginalFilename(mediaURL string) string {
return "" return ""
} }
func EmbedMetadata(filePath string, tweetContent string, tweetURL string, originalFilename string) error { func EmbedMetadata(ctx context.Context, filePath string, tweetContent string, tweetURL string, originalFilename string) error {
ext := strings.ToLower(filepath.Ext(filePath)) ext := strings.ToLower(filepath.Ext(filePath))
switch ext { switch ext {
case ".jpg", ".jpeg": case ".jpg", ".jpeg":
return embedImageMetadata(filePath, tweetContent, tweetURL, originalFilename) return embedImageMetadata(ctx, filePath, tweetContent, tweetURL, originalFilename)
case ".mp4": case ".mp4":
return embedVideoMetadata(filePath, tweetContent, tweetURL, originalFilename) return embedVideoMetadata(ctx, filePath, tweetContent, tweetURL, originalFilename)
default: default:
return nil return nil
} }
} }
func embedImageMetadata(filePath string, tweetContent string, tweetURL string, originalFilename string) error { func embedImageMetadata(ctx context.Context, filePath string, tweetContent string, tweetURL string, originalFilename string) error {
if ctx == nil {
ctx = context.Background()
}
exiftoolPath := findExifTool() exiftoolPath := findExifTool()
if exiftoolPath == "" { if exiftoolPath == "" {
@@ -100,10 +108,13 @@ func embedImageMetadata(filePath string, tweetContent string, tweetURL string, o
filePath, filePath,
} }
cmd := exec.Command(exiftoolPath, args...) cmd := exec.CommandContext(ctx, exiftoolPath, args...)
hideWindow(cmd) hideWindow(cmd)
output, err := cmd.CombinedOutput() output, err := cmd.CombinedOutput()
if err != nil { if err != nil {
if ctx.Err() != nil {
return ctx.Err()
}
return fmt.Errorf("exiftool error (non-fatal): %v, output: %s", err, string(output)) return fmt.Errorf("exiftool error (non-fatal): %v, output: %s", err, string(output))
} }
@@ -112,7 +123,10 @@ func embedImageMetadata(filePath string, tweetContent string, tweetURL string, o
return nil return nil
} }
func embedVideoMetadata(filePath string, tweetContent string, tweetURL string, originalFilename string) error { func embedVideoMetadata(ctx context.Context, filePath string, tweetContent string, tweetURL string, originalFilename string) error {
if ctx == nil {
ctx = context.Background()
}
exiftoolPath := findExifTool() exiftoolPath := findExifTool()
if exiftoolPath == "" { if exiftoolPath == "" {
@@ -120,10 +134,13 @@ func embedVideoMetadata(filePath string, tweetContent string, tweetURL string, o
return nil return nil
} }
return embedVideoMetadataWithExifTool(exiftoolPath, filePath, tweetContent, tweetURL, originalFilename) return embedVideoMetadataWithExifTool(ctx, exiftoolPath, filePath, tweetContent, tweetURL, originalFilename)
} }
func embedVideoMetadataWithExifTool(exiftoolPath string, filePath string, tweetContent string, tweetURL string, originalFilename string) error { func embedVideoMetadataWithExifTool(ctx context.Context, exiftoolPath string, filePath string, tweetContent string, tweetURL string, originalFilename string) error {
if ctx == nil {
ctx = context.Background()
}
metadataComment := buildMetadataComment(tweetContent, tweetURL, originalFilename) metadataComment := buildMetadataComment(tweetContent, tweetURL, originalFilename)
@@ -133,10 +150,13 @@ func embedVideoMetadataWithExifTool(exiftoolPath string, filePath string, tweetC
filePath, filePath,
} }
cmd := exec.Command(exiftoolPath, args...) cmd := exec.CommandContext(ctx, exiftoolPath, args...)
hideWindow(cmd) hideWindow(cmd)
output, err := cmd.CombinedOutput() output, err := cmd.CombinedOutput()
if err != nil { if err != nil {
if ctx.Err() != nil {
return ctx.Err()
}
return fmt.Errorf("exiftool error (non-fatal): %v, output: %s", err, string(output)) return fmt.Errorf("exiftool error (non-fatal): %v, output: %s", err, string(output))
} }
+476 -350
View File
File diff suppressed because it is too large. Load diff
+7 -1
View File
@@ -5,7 +5,7 @@ import reactRefresh from 'eslint-plugin-react-refresh';
import tseslint from 'typescript-eslint'; import tseslint from 'typescript-eslint';
import { defineConfig, globalIgnores } from 'eslint/config'; import { defineConfig, globalIgnores } from 'eslint/config';
export default defineConfig([ export default defineConfig([
globalIgnores(['dist']), globalIgnores(['dist', 'wailsjs']),
{ {
files: ['**/*.{ts,tsx}'], files: ['**/*.{ts,tsx}'],
extends: [ extends: [
@@ -19,4 +19,10 @@ export default defineConfig([
globals: globals.browser, globals: globals.browser,
}, },
}, },
{
files: ['src/components/ui/badge.tsx', 'src/components/ui/button.tsx'],
rules: {
'react-refresh/only-export-components': 'off',
},
},
]); ]);
+1 -1
View File
@@ -6,7 +6,7 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@300..800&family=Figtree:wght@300..900&family=Geist:wght@100..900&family=Google+Sans+Code:ital,wght@0,300..800;1,300..800&family=Google+Sans+Flex:opsz,wght@6..144,1..1000&family=Inter:wght@300..800&family=JetBrains+Mono:ital,wght@0,100..800;1,100..800&family=Manrope:wght@300..800&family=Noto+Sans:wght@100..900&family=Nunito+Sans:opsz,wght@6..12,200..1000&family=Outfit:wght@100..900&family=Plus+Jakarta+Sans:wght@300..800&family=Poppins:wght@300;400;500;600;700;800&family=Public+Sans:ital,wght@0,100..900;1,100..900&family=Raleway:wght@100..900&family=Roboto:wght@300;400;500;700;900&family=Space+Grotesk:wght@300..700&display=swap" rel="stylesheet"> <link href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,200..800&family=DM+Sans:wght@300..800&family=Figtree:wght@300..900&family=Geist:wght@100..900&family=Google+Sans+Code:ital,wght@0,300..800;1,300..800&family=Google+Sans+Flex:opsz,wght@6..144,1..1000&family=Inter:wght@300..800&family=JetBrains+Mono:ital,wght@0,100..800;1,100..800&family=Manrope:wght@300..800&family=Noto+Sans:wght@100..900&family=Nunito+Sans:opsz,wght@6..12,200..1000&family=Outfit:wght@100..900&family=Plus+Jakarta+Sans:wght@300..800&family=Poppins:wght@300;400;500;600;700;800&family=Public+Sans:ital,wght@0,100..900;1,100..900&family=Raleway:wght@100..900&family=Roboto:wght@300;400;500;700;900&family=Space+Grotesk:wght@300..700&display=swap" rel="stylesheet">
<title>Twitter/X Media Batch Downloader</title> <title>Twitter/X Media Batch Downloader</title>
</head> </head>
<body> <body>
+28 -28
View File
@@ -12,42 +12,42 @@
"postinstall": "node scripts/generate-icon.js" "postinstall": "node scripts/generate-icon.js"
}, },
"dependencies": { "dependencies": {
"@radix-ui/react-checkbox": "^1.3.3", "@radix-ui/react-checkbox": "^1.3.5",
"@radix-ui/react-context-menu": "^2.2.16", "@radix-ui/react-context-menu": "^2.3.1",
"@radix-ui/react-dialog": "^1.1.15", "@radix-ui/react-dialog": "^1.1.17",
"@radix-ui/react-dropdown-menu": "^2.1.16", "@radix-ui/react-dropdown-menu": "^2.1.18",
"@radix-ui/react-label": "^2.1.8", "@radix-ui/react-label": "^2.1.10",
"@radix-ui/react-progress": "^1.1.8", "@radix-ui/react-progress": "^1.1.10",
"@radix-ui/react-select": "^2.2.6", "@radix-ui/react-select": "^2.3.1",
"@radix-ui/react-slot": "^1.2.4", "@radix-ui/react-slot": "^1.3.0",
"@radix-ui/react-switch": "^1.2.6", "@radix-ui/react-switch": "^1.3.1",
"@radix-ui/react-tooltip": "^1.2.8", "@radix-ui/react-tooltip": "^1.2.10",
"@tailwindcss/vite": "^4.1.18", "@tailwindcss/vite": "^4.3.1",
"class-variance-authority": "^0.7.1", "class-variance-authority": "^0.7.1",
"clsx": "^2.1.1", "clsx": "^2.1.1",
"lucide-react": "^0.562.0", "lucide-react": "^0.562.0",
"motion": "^12.23.26", "motion": "^12.40.0",
"next-themes": "^0.4.6", "next-themes": "^0.4.6",
"react": "^19.2.3", "react": "^19.2.7",
"react-dom": "^19.2.3", "react-dom": "^19.2.7",
"sonner": "^2.0.7", "sonner": "^2.0.7",
"tailwind-merge": "^3.4.0", "tailwind-merge": "^3.6.0",
"tailwindcss": "^4.1.18" "tailwindcss": "^4.3.1"
}, },
"devDependencies": { "devDependencies": {
"@eslint/js": "^9.39.2", "@eslint/js": "^10.0.1",
"@types/node": "^25.0.3", "@types/node": "^26.0.0",
"@types/react": "^19.2.7", "@types/react": "^19.2.17",
"@types/react-dom": "^19.2.3", "@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^5.1.2", "@vitejs/plugin-react": "^6.0.2",
"eslint": "^9.39.2", "eslint": "^10.5.0",
"eslint-plugin-react-hooks": "^7.0.1", "eslint-plugin-react-hooks": "^7.1.1",
"eslint-plugin-react-refresh": "^0.4.26", "eslint-plugin-react-refresh": "^0.5.3",
"globals": "^16.5.0", "globals": "^17.6.0",
"sharp": "^0.34.5", "sharp": "^0.35.2",
"tw-animate-css": "^1.4.0", "tw-animate-css": "^1.4.0",
"typescript": "~5.9.3", "typescript": "~6.0.3",
"typescript-eslint": "^8.50.0", "typescript-eslint": "^8.61.1",
"vite": "^7.3.0" "vite": "^8.0.16"
} }
} }
+1 -1
View File
@@ -1 +1 @@
cb4545ab700ecc9d641ab1be76b622f1 b9015b5860764ef52b634f74fd0f1180
+1678 -1858
View File
File diff suppressed because it is too large. Load diff
+3
View File
@@ -0,0 +1,3 @@
allowBuilds:
esbuild: true
sharp: true
+413 -174
View File
@@ -1,10 +1,16 @@
import { useState, useEffect, useRef, useCallback } from "react"; import { useState, useEffect, useRef, useCallback } from "react";
import { TooltipProvider } from "@/components/ui/tooltip"; 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 { getSettings, applyThemeMode, applyFont } from "@/lib/settings";
import { applyTheme } from "@/lib/themes"; import { applyTheme } from "@/lib/themes";
import { openExternal } from "@/lib/utils";
import { compareVersionNumbers } from "@/lib/version";
import { toastWithSound as toast } from "@/lib/toast-with-sound"; import { toastWithSound as toast } from "@/lib/toast-with-sound";
import { logger } from "@/lib/logger"; import { logger } from "@/lib/logger";
import { saveFetchState, getFetchState, clearFetchState, getResumableInfo, stateToResponse, mergeTimelines, saveCursor, getCursor, clearCursor, type FetchState, } from "@/lib/fetch-state"; 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 { TitleBar } from "@/components/TitleBar";
import { Sidebar, type PageType } from "@/components/Sidebar"; import { Sidebar, type PageType } from "@/components/Sidebar";
import { Header } from "@/components/Header"; import { Header } from "@/components/Header";
@@ -13,17 +19,36 @@ import { MediaList } from "@/components/MediaList";
import { DatabaseView } from "@/components/DatabaseView"; import { DatabaseView } from "@/components/DatabaseView";
import { SettingsPage } from "@/components/SettingsPage"; import { SettingsPage } from "@/components/SettingsPage";
import { DebugLoggerPage } from "@/components/DebugLoggerPage"; import { DebugLoggerPage } from "@/components/DebugLoggerPage";
import { SupportPage } from "@/components/SupportPage";
import { DependencySetupDialog } from "@/components/DependencySetupDialog"; import { DependencySetupDialog } from "@/components/DependencySetupDialog";
import type { HistoryItem } from "@/components/FetchHistory"; import type { HistoryItem } from "@/components/FetchHistory";
import type { TwitterResponse } from "@/types/api"; import type { TwitterResponse } from "@/types/api";
import { ExtractTimeline, ExtractDateRange, SaveAccountToDBWithStatus, CleanupExtractorProcesses, GetAllAccountsFromDB } from "../wailsjs/go/main/App"; import { ExtractTimeline, ExtractDateRange, SaveAccountToDBWithStatus, CleanupExtractorProcesses, GetAllAccountsFromDB, GetSavedAccountFromDB } from "../wailsjs/go/main/App";
const HISTORY_KEY = "twitter_media_fetch_history"; const HISTORY_KEY = "twitter_media_fetch_history";
const MAX_HISTORY = 10; const MAX_HISTORY = 10;
const CURRENT_VERSION = __APP_VERSION__; const CURRENT_VERSION = __APP_VERSION__;
const BATCH_SIZE = 200; const BATCH_SIZE = 100;
function formatNumberWithComma(num: number): string { function formatNumberWithComma(num: number): string {
return num.toLocaleString(); 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);
return normalizeTwitterResponse(JSON.parse(savedResponseJSON) as TwitterResponse);
}
catch {
return null;
}
}
function App() { function App() {
const [currentPage, setCurrentPage] = useState<PageType>("main"); const [currentPage, setCurrentPage] = useState<PageType>("main");
const [username, setUsername] = useState(""); const [username, setUsername] = useState("");
@@ -48,6 +73,10 @@ function App() {
const [isFetchingAll, setIsFetchingAll] = useState(false); const [isFetchingAll, setIsFetchingAll] = useState(false);
const [searchMode, setSearchMode] = useState<FetchMode>("public"); const [searchMode, setSearchMode] = useState<FetchMode>("public");
const [searchPrivateType, setSearchPrivateType] = useState<PrivateType>("bookmarks"); const [searchPrivateType, setSearchPrivateType] = useState<PrivateType>("bookmarks");
const [hasUnsavedSettings, setHasUnsavedSettings] = useState(false);
const [pendingPageChange, setPendingPageChange] = useState<PageType | null>(null);
const [showUnsavedChangesDialog, setShowUnsavedChangesDialog] = useState(false);
const [resetSettingsFn, setResetSettingsFn] = useState<(() => void) | null>(null);
const stopAllRef = useRef(false); const stopAllRef = useRef(false);
const accountTimersRef = useRef<Map<string, number>>(new Map()); const accountTimersRef = useRef<Map<string, number>>(new Map());
const accountStartTimesRef = useRef<Map<string, number>>(new Map()); const accountStartTimesRef = useRef<Map<string, number>>(new Map());
@@ -62,18 +91,62 @@ function App() {
toast.warning("Fetch completed, but saving to Saved Accounts failed"); toast.warning("Fetch completed, but saving to Saved Accounts failed");
} }
}; };
const restorePartialFetchState = async (cleanUsername: string, mediaType: string, showStoppedToast: boolean) => {
const savedState = getFetchState(cleanUsername);
if (!savedState || savedState.totalFetched <= 0) {
if (showStoppedToast) {
toast.info("Fetch stopped");
}
return;
}
const canResume = !!savedState.cursor && !savedState.completed;
if (!canResume) {
clearFetchState(cleanUsername);
clearCursor(cleanUsername);
setResumeInfo(null);
}
const partialResponse = await loadSavedAccountResponse(cleanUsername, savedState.mediaType || mediaType);
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 || "", savedState.completed);
}
catch (dbErr) {
reportDatabaseSaveError("partial fetch data", dbErr);
}
}
if (showStoppedToast) {
toast.info(`Stopped at ${formatNumberWithComma(savedState.totalFetched)} items`);
}
};
const stopMultipleFetches = (showToast: boolean) => {
stopAllRef.current = true;
setIsFetchingAll(false);
accountTimersRef.current.forEach((interval) => clearInterval(interval));
accountTimersRef.current.clear();
accountStartTimesRef.current.clear();
accountTimeoutSecondsRef.current.clear();
setMultipleAccounts((prev) => prev.map((acc) => {
if (acc.status === "fetching") {
const mediaCount = accountMediaCountRef.current.get(acc.id) || acc.mediaCount || 0;
return { ...acc, status: "incomplete" as const, mediaCount, remainingTime: 0 };
}
return acc;
}));
CleanupExtractorProcesses().catch(() => { });
if (showToast) {
toast.info("Stopped all fetches");
}
};
const handleFetchTypeChange = (type: FetchType) => { const handleFetchTypeChange = (type: FetchType) => {
setFetchType(type); setFetchType(type);
if (type === "single") { if (type === "single") {
setMultipleAccounts([]); if (isFetchingAll || multipleAccounts.some((acc) => acc.status === "fetching")) {
setIsFetchingAll(false); stopMultipleFetches(false);
stopAllRef.current = true; }
accountTimersRef.current.forEach((interval) => clearInterval(interval));
accountTimersRef.current.clear();
accountStartTimesRef.current.clear();
accountTimeoutSecondsRef.current.clear();
accountStopFlagsRef.current.clear();
accountMediaCountRef.current.clear();
} }
else { else {
setResult(null); setResult(null);
@@ -83,7 +156,7 @@ function App() {
const settings = getSettings(); const settings = getSettings();
applyThemeMode(settings.themeMode); applyThemeMode(settings.themeMode);
applyTheme(settings.theme); applyTheme(settings.theme);
applyFont(settings.fontFamily); applyFont(settings.fontFamily, settings.customFonts);
const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)"); const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");
const handleChange = () => { const handleChange = () => {
const currentSettings = getSettings(); const currentSettings = getSettings();
@@ -93,10 +166,45 @@ function App() {
} }
}; };
mediaQuery.addEventListener("change", handleChange); mediaQuery.addEventListener("change", handleChange);
const cleanupDownloadProgress = initDownloadProgressEvents();
checkForUpdates(); checkForUpdates();
loadHistory(); loadHistory();
return () => { return () => {
mediaQuery.removeEventListener("change", handleChange); mediaQuery.removeEventListener("change", handleChange);
cleanupDownloadProgress();
};
}, []);
useEffect(() => {
const handleDocumentClick = (event: MouseEvent) => {
if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) {
return;
}
const target = event.target;
if (!(target instanceof Element)) {
return;
}
const anchor = target.closest("a[href]");
if (!(anchor instanceof HTMLAnchorElement)) {
return;
}
const href = anchor.getAttribute("href");
if (!href || href.startsWith("#") || href.startsWith("javascript:")) {
return;
}
try {
const url = new URL(href, window.location.href);
if (url.protocol !== "http:" && url.protocol !== "https:") {
return;
}
event.preventDefault();
openExternal(url.toString());
}
catch {
}
};
document.addEventListener("click", handleDocumentClick);
return () => {
document.removeEventListener("click", handleDocumentClick);
}; };
}, []); }, []);
const checkForUpdates = async () => { const checkForUpdates = async () => {
@@ -107,7 +215,7 @@ function App() {
if (data.published_at) { if (data.published_at) {
setReleaseDate(data.published_at); setReleaseDate(data.published_at);
} }
if (latestVersion && latestVersion > CURRENT_VERSION) { if (latestVersion && compareVersionNumbers(latestVersion, CURRENT_VERSION) > 0) {
setHasUpdate(true); setHasUpdate(true);
} }
} }
@@ -188,7 +296,8 @@ function App() {
try { try {
await CleanupExtractorProcesses(); await CleanupExtractorProcesses();
} }
catch { catch (cleanupError) {
console.error("Failed to stop extractor processes:", cleanupError);
} }
}, []); }, []);
useEffect(() => { useEffect(() => {
@@ -254,7 +363,8 @@ function App() {
try { try {
await CleanupExtractorProcesses(); await CleanupExtractorProcesses();
} }
catch { catch (cleanupError) {
console.error("Failed to clean extractor processes before fetch:", cleanupError);
} }
const fetchTarget = isBookmarks const fetchTarget = isBookmarks
? "your bookmarks" ? "your bookmarks"
@@ -262,6 +372,7 @@ function App() {
? "your likes" ? "your likes"
: `@${username}`; : `@${username}`;
const cleanUsername = isBookmarks ? "bookmarks" : isLikes ? "likes" : username.trim(); const cleanUsername = isBookmarks ? "bookmarks" : isLikes ? "likes" : username.trim();
const requestedMediaType = mediaType || "all";
let existingState: FetchState | null = null; let existingState: FetchState | null = null;
let cursor: string | undefined; let cursor: string | undefined;
let allTimeline: TwitterResponse["timeline"] = []; let allTimeline: TwitterResponse["timeline"] = [];
@@ -270,17 +381,18 @@ function App() {
existingState = getFetchState(cleanUsername); existingState = getFetchState(cleanUsername);
if (existingState && existingState.cursor && !existingState.completed) { if (existingState && existingState.cursor && !existingState.completed) {
cursor = existingState.cursor; cursor = existingState.cursor;
allTimeline = existingState.timeline; const savedResponse = await loadSavedAccountResponse(cleanUsername, existingState.mediaType || requestedMediaType);
accountInfo = existingState.accountInfo; if (!savedResponse) {
logger.info(`Resuming ${fetchTarget} from ${allTimeline.length} items...`); clearFetchState(cleanUsername);
if (accountInfo) { clearCursor(cleanUsername);
setResult({ toast.error("Resume data is no longer available");
account_info: accountInfo, setLoading(false);
timeline: allTimeline, return;
total_urls: allTimeline.length,
metadata: { new_entries: 0, page: 0, batch_size: 0, has_more: true },
});
} }
allTimeline = savedResponse.timeline;
accountInfo = savedResponse.account_info;
logger.info(`Resuming ${fetchTarget} from ${existingState.totalFetched} items...`);
setResult(savedResponse);
} }
else { else {
toast.error("No resumable fetch found"); toast.error("No resumable fetch found");
@@ -314,21 +426,13 @@ function App() {
auth_token: authToken.trim(), auth_token: authToken.trim(),
start_date: startDate, start_date: startDate,
end_date: endDate, end_date: endDate,
media_filter: mediaType || "all", media_filter: requestedMediaType,
retweets: retweets || false, retweets: retweets || false,
}); });
finalData = JSON.parse(response); finalData = normalizeTwitterResponse(JSON.parse(response) as TwitterResponse);
if (finalData && finalData.account_info) { if (finalData && finalData.account_info) {
try { try {
await SaveAccountToDBWithStatus(finalData.account_info.name, finalData.account_info.nick, finalData.account_info.profile_image, finalData.total_urls, JSON.stringify(finalData), mediaType || "all", finalData.cursor || "", finalData.completed ?? true); await SaveAccountToDBWithStatus(finalData.account_info.name, finalData.account_info.nick, finalData.account_info.profile_image, finalData.total_urls, JSON.stringify(finalData), requestedMediaType, finalData.cursor || "", finalData.completed ?? true);
}
catch (err) {
reportDatabaseSaveError("date range data", err);
}
}
if (finalData && finalData.account_info) {
try {
await SaveAccountToDBWithStatus(finalData.account_info.name, finalData.account_info.nick, finalData.account_info.profile_image, finalData.total_urls, JSON.stringify(finalData), mediaType || "all", finalData.cursor || "", finalData.completed ?? true);
} }
catch (err) { catch (err) {
reportDatabaseSaveError("date range data", err); reportDatabaseSaveError("date range data", err);
@@ -336,10 +440,8 @@ function App() {
} }
} }
else { else {
const settings = getSettings(); const batchSize = BATCH_SIZE;
const isSingleMode = settings.fetchMode === "single"; let timelineType = settings.includeText ? "tweets" : "media";
const batchSize = isSingleMode ? 0 : BATCH_SIZE;
let timelineType = "timeline";
if (isBookmarks) { if (isBookmarks) {
timelineType = "bookmarks"; timelineType = "bookmarks";
} }
@@ -348,6 +450,7 @@ function App() {
} }
let hasMore = true; let hasMore = true;
let page = 0; let page = 0;
const seenCursors = new Set<string>();
while (hasMore && !stopFetchRef.current) { while (hasMore && !stopFetchRef.current) {
if (fetchStartTimeRef.current !== null) { if (fetchStartTimeRef.current !== null) {
const settings = getSettings(); const settings = getSettings();
@@ -361,12 +464,9 @@ function App() {
saveFetchState({ saveFetchState({
username: cleanUsername, username: cleanUsername,
cursor: cursor || "", cursor: cursor || "",
timeline: allTimeline,
accountInfo: accountInfo,
totalFetched: allTimeline.length, totalFetched: allTimeline.length,
completed: false, completed: false,
authToken: authToken.trim(), mediaType: requestedMediaType,
mediaType: mediaType || "all",
retweets: retweets || false, retweets: retweets || false,
timelineType: timelineType, timelineType: timelineType,
}); });
@@ -386,7 +486,7 @@ function App() {
completed: false, completed: false,
}; };
try { try {
await SaveAccountToDBWithStatus(accountInfo.name, accountInfo.nick, accountInfo.profile_image, allTimeline.length, JSON.stringify(timeoutResponse), mediaType || "all", cursor || "", false); await SaveAccountToDBWithStatus(accountInfo.name, accountInfo.nick, accountInfo.profile_image, allTimeline.length, JSON.stringify(timeoutResponse), requestedMediaType, cursor || "", false);
logger.info(`Saved ${allTimeline.length} items before timeout`); logger.info(`Saved ${allTimeline.length} items before timeout`);
} }
catch (err) { catch (err) {
@@ -397,18 +497,24 @@ function App() {
} }
} }
const batchNum = page + 1; const batchNum = page + 1;
logger.info(isSingleMode ? "Fetching all media..." : `Fetching batch ${batchNum}${cursor ? " (resuming)" : ""}...`); logger.info(`Fetching batch ${batchNum}${cursor ? " (resuming)" : ""}...`);
const response = await ExtractTimeline({ const response = await ExtractTimeline({
username: isBookmarks ? "" : username.trim(), username: isBookmarks ? "" : username.trim(),
auth_token: authToken.trim(), auth_token: authToken.trim(),
timeline_type: timelineType, timeline_type: timelineType,
batch_size: batchSize, batch_size: batchSize,
page: page, page: page,
media_type: mediaType || "all", media_type: requestedMediaType,
retweets: retweets || false, retweets: retweets || false,
cursor: cursor, 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: TwitterResponse = JSON.parse(response); const data = normalizeTwitterResponse(JSON.parse(response) as TwitterResponse);
if (!accountInfo && data.account_info) { if (!accountInfo && data.account_info) {
accountInfo = data.account_info; accountInfo = data.account_info;
if (isBookmarks) { if (isBookmarks) {
@@ -429,6 +535,14 @@ function App() {
} }
cursor = data.cursor; cursor = data.cursor;
hasMore = !!data.cursor && !data.completed; 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++; page++;
if (cursor) { if (cursor) {
saveCursor(cleanUsername, cursor); saveCursor(cleanUsername, cursor);
@@ -454,12 +568,9 @@ function App() {
saveFetchState({ saveFetchState({
username: cleanUsername, username: cleanUsername,
cursor: cursor || "", cursor: cursor || "",
timeline: allTimeline,
accountInfo: accountInfo,
totalFetched: allTimeline.length, totalFetched: allTimeline.length,
completed: !hasMore, completed: !hasMore,
authToken: authToken.trim(), mediaType: requestedMediaType,
mediaType: mediaType || "all",
retweets: retweets || false, retweets: retweets || false,
timelineType: timelineType, timelineType: timelineType,
}); });
@@ -480,14 +591,14 @@ function App() {
completed: !hasMore, completed: !hasMore,
}; };
try { try {
await SaveAccountToDBWithStatus(accountInfo.name, accountInfo.nick, accountInfo.profile_image, allTimeline.length, JSON.stringify(currentResponse), mediaType || "all", cursor || "", !hasMore); await SaveAccountToDBWithStatus(accountInfo.name, accountInfo.nick, accountInfo.profile_image, allTimeline.length, JSON.stringify(currentResponse), requestedMediaType, cursor || "", !hasMore);
} }
catch (err) { catch (err) {
reportDatabaseSaveError("fetch progress", err); reportDatabaseSaveError("fetch progress", err);
} }
} }
} }
if (stopFetchRef.current) { if (stopFetchRef.current && hasMore && cursor) {
const elapsedSecs = fetchStartTimeRef.current ? Math.floor((Date.now() - fetchStartTimeRef.current) / 1000) : 0; const elapsedSecs = fetchStartTimeRef.current ? Math.floor((Date.now() - fetchStartTimeRef.current) / 1000) : 0;
logger.info(`Stopped at ${allTimeline.length} items - can resume later (${elapsedSecs}s)`); logger.info(`Stopped at ${allTimeline.length} items - can resume later (${elapsedSecs}s)`);
toast.info(`Stopped at ${formatNumberWithComma(allTimeline.length)} items`); toast.info(`Stopped at ${formatNumberWithComma(allTimeline.length)} items`);
@@ -523,7 +634,7 @@ function App() {
} }
if (!useDateRange) { if (!useDateRange) {
try { try {
await SaveAccountToDBWithStatus(finalData.account_info.name, finalData.account_info.nick, finalData.account_info.profile_image, finalData.total_urls, JSON.stringify(finalData), mediaType || "all", finalData.cursor || "", finalData.completed ?? true); await SaveAccountToDBWithStatus(finalData.account_info.name, finalData.account_info.nick, finalData.account_info.profile_image, finalData.total_urls, JSON.stringify(finalData), requestedMediaType, finalData.cursor || "", finalData.completed ?? true);
} }
catch (err) { catch (err) {
reportDatabaseSaveError("final fetch status", err); reportDatabaseSaveError("final fetch status", err);
@@ -539,6 +650,11 @@ function App() {
catch (error) { catch (error) {
const errorMsg = error instanceof Error ? error.message : String(error); const errorMsg = error instanceof Error ? error.message : String(error);
const elapsedSecs = fetchStartTimeRef.current ? Math.floor((Date.now() - fetchStartTimeRef.current) / 1000) : 0; const elapsedSecs = fetchStartTimeRef.current ? Math.floor((Date.now() - fetchStartTimeRef.current) / 1000) : 0;
if (stopFetchRef.current) {
logger.info(`Stopped fetch after ${elapsedSecs}s`);
await restorePartialFetchState(cleanUsername, requestedMediaType, true);
return;
}
logger.error(`Failed to fetch: ${errorMsg} (${elapsedSecs}s)`); logger.error(`Failed to fetch: ${errorMsg} (${elapsedSecs}s)`);
if (errorMsg.toLowerCase().includes("xtractor dependency") || errorMsg.toLowerCase().includes("extractor dependency")) { if (errorMsg.toLowerCase().includes("xtractor dependency") || errorMsg.toLowerCase().includes("extractor dependency")) {
toast.error(errorMsg); toast.error(errorMsg);
@@ -547,19 +663,9 @@ function App() {
toast.error("Failed to fetch media"); toast.error("Failed to fetch media");
} }
const savedState = getFetchState(cleanUsername); const savedState = getFetchState(cleanUsername);
if (savedState && savedState.timeline.length > 0) { if (savedState && savedState.totalFetched > 0) {
const partialResponse = stateToResponse(savedState); await restorePartialFetchState(cleanUsername, requestedMediaType, false);
if (partialResponse) { toast.info(`Saved ${formatNumberWithComma(savedState.totalFetched)} items - can resume`);
setResult(partialResponse);
setResumeInfo({ canResume: true, mediaCount: savedState.timeline.length });
toast.info(`Saved ${formatNumberWithComma(savedState.timeline.length)} items - can resume`);
try {
await SaveAccountToDBWithStatus(partialResponse.account_info.name, partialResponse.account_info.nick, partialResponse.account_info.profile_image, partialResponse.total_urls, JSON.stringify(partialResponse), mediaType || "all", savedState.cursor || "", false);
}
catch (dbErr) {
reportDatabaseSaveError("partial fetch data", dbErr);
}
}
} }
} }
finally { finally {
@@ -575,13 +681,14 @@ function App() {
const handleClearResume = () => { const handleClearResume = () => {
if (username.trim()) { if (username.trim()) {
clearFetchState(username.trim()); clearFetchState(username.trim());
clearCursor(username.trim());
setResumeInfo(null); setResumeInfo(null);
toast.info("Resume data cleared"); toast.info("Resume data cleared");
} }
}; };
const handleLoadFromDB = (responseJSON: string, loadedUsername: string) => { const handleLoadFromDB = (responseJSON: string, loadedUsername: string) => {
try { try {
const data: TwitterResponse = JSON.parse(responseJSON); const data = normalizeTwitterResponse(JSON.parse(responseJSON) as TwitterResponse);
setResult(data); setResult(data);
setUsername(loadedUsername); setUsername(loadedUsername);
setCurrentPage("main"); setCurrentPage("main");
@@ -603,9 +710,17 @@ function App() {
toast.success(`Loaded @${loadedUsername} from database`); toast.success(`Loaded @${loadedUsername} from database`);
} }
catch (error) { catch (error) {
console.error("Failed to parse saved data:", error);
toast.error("Failed to parse saved data"); toast.error("Failed to parse saved data");
} }
}; };
const handleBackToHomeResult = () => {
setCurrentPage("main");
setResult(null);
setNewMediaCount(null);
const scrollElement = document.getElementById("app-content-scroll");
scrollElement?.scrollTo({ top: 0, behavior: "smooth" });
};
const parseUsername = (input: string): string => { const parseUsername = (input: string): string => {
let clean = input.trim(); let clean = input.trim();
if (clean.startsWith("@")) { if (clean.startsWith("@")) {
@@ -645,58 +760,75 @@ function App() {
setCurrentPage("main"); setCurrentPage("main");
toast.success(`Added ${formatNumberWithComma(accounts.length)} account(s) to multiple fetch`); toast.success(`Added ${formatNumberWithComma(accounts.length)} account(s) to multiple fetch`);
}; };
const handleImportFile = () => { const handleImportAccounts = (entries: string[]) => {
const input = document.createElement("input"); const seenUsernames = new Set<string>();
input.type = "file"; const uniqueUsernames = entries
input.accept = ".txt"; .map((entry) => parseUsername(entry))
input.onchange = async (e) => { .filter((entry) => entry.length > 0)
const file = (e.target as HTMLInputElement).files?.[0]; .filter((entry) => {
if (!file) const normalized = entry.toLowerCase();
return; if (seenUsernames.has(normalized)) {
try { return false;
const text = await file.text();
const lines = text.split("\n").map((line) => line.trim()).filter((line) => line.length > 0);
if (lines.length === 0) {
toast.error("File is empty");
return;
}
const accounts: MultipleAccount[] = lines.map((line) => {
const username = parseUsername(line);
return {
id: crypto.randomUUID(),
username,
status: "pending",
mediaCount: 0,
previousMediaCount: 0,
elapsedTime: 0,
remainingTime: null,
showDiff: false,
};
});
setMultipleAccounts(accounts);
toast.success(`Imported ${formatNumberWithComma(accounts.length)} account(s)`);
} }
catch (error) { seenUsernames.add(normalized);
toast.error("Failed to read file"); return true;
} });
}; if (uniqueUsernames.length === 0) {
input.click(); toast.error("No valid accounts found");
return;
}
const accounts: MultipleAccount[] = uniqueUsernames.map((entry) => ({
id: crypto.randomUUID(),
username: entry,
status: "pending",
mediaCount: 0,
previousMediaCount: 0,
elapsedTime: 0,
remainingTime: null,
showDiff: false,
}));
setMultipleAccounts(accounts);
toast.success(`Imported ${formatNumberWithComma(accounts.length)} account(s)`);
}; };
const handleFetchAll = async () => { const handleClearMultipleAccounts = () => {
accountTimersRef.current.forEach((interval) => clearInterval(interval));
accountTimersRef.current.clear();
accountStartTimesRef.current.clear();
accountTimeoutSecondsRef.current.clear();
accountStopFlagsRef.current.clear();
accountMediaCountRef.current.clear();
stopAllRef.current = false;
setIsFetchingAll(false);
setMultipleAccounts([]);
toast.info("Multiple fetch list cleared");
};
const handleRemoveMultipleAccount = (accountId: string) => {
const account = multipleAccounts.find((entry) => entry.id === accountId);
accountTimersRef.current.delete(accountId);
accountStartTimesRef.current.delete(accountId);
accountTimeoutSecondsRef.current.delete(accountId);
accountStopFlagsRef.current.delete(accountId);
accountMediaCountRef.current.delete(accountId);
setMultipleAccounts((prev) => prev.filter((entry) => entry.id !== accountId));
if (account) {
toast.info(`Removed @${account.username} from list`);
}
};
const handleFetchAll = async (authToken: string) => {
if (multipleAccounts.length === 0) { if (multipleAccounts.length === 0) {
toast.error("No accounts to fetch"); toast.error("No accounts to fetch");
return; return;
} }
setIsFetchingAll(true); setIsFetchingAll(true);
stopAllRef.current = false; stopAllRef.current = false;
const PUBLIC_AUTH_TOKEN_KEY = "twitter_public_auth_token";
const authToken = localStorage.getItem(PUBLIC_AUTH_TOKEN_KEY) || "";
if (!authToken.trim()) { if (!authToken.trim()) {
toast.error("Please enter your auth token"); toast.error("Please enter your auth token");
setIsFetchingAll(false); setIsFetchingAll(false);
return; return;
} }
const settings = getSettings(); const settings = getSettings();
const selectedMediaType = "all";
setFetchedMediaType(selectedMediaType);
const timeoutSeconds = settings.fetchTimeout || 60; const timeoutSeconds = settings.fetchTimeout || 60;
setMultipleAccounts((prev) => prev.map((acc) => ({ setMultipleAccounts((prev) => prev.map((acc) => ({
...acc, ...acc,
@@ -708,7 +840,7 @@ function App() {
error: undefined, error: undefined,
showDiff: false, showDiff: false,
}))); })));
let currentAccounts = [...multipleAccounts]; const currentAccounts = [...multipleAccounts];
for (let i = 0; i < currentAccounts.length; i++) { for (let i = 0; i < currentAccounts.length; i++) {
if (stopAllRef.current) { if (stopAllRef.current) {
break; break;
@@ -769,15 +901,14 @@ function App() {
})); }));
continue; continue;
} }
const fetchSettings = getSettings(); const batchSizeMultiple = BATCH_SIZE;
const isSingleModeMultiple = fetchSettings.fetchMode === "single";
const batchSizeMultiple = isSingleModeMultiple ? 0 : BATCH_SIZE;
const cleanUsername = account.username.trim(); const cleanUsername = account.username.trim();
let allTimeline: TwitterResponse["timeline"] = []; let allTimeline: TwitterResponse["timeline"] = [];
let accountInfo: TwitterResponse["account_info"] | null = null; let accountInfo: TwitterResponse["account_info"] | null = null;
let cursor: string | undefined; let cursor: string | undefined;
let hasMore = true; let hasMore = true;
let page = 0; let page = 0;
const seenCursors = new Set<string>();
let previousMediaCount = account.mediaCount || 0; let previousMediaCount = account.mediaCount || 0;
while (hasMore && !stopAllRef.current) { while (hasMore && !stopAllRef.current) {
if (accountStopFlagsRef.current.get(accountId)) { if (accountStopFlagsRef.current.get(accountId)) {
@@ -785,12 +916,9 @@ function App() {
saveFetchState({ saveFetchState({
username: cleanUsername, username: cleanUsername,
cursor: cursor || "", cursor: cursor || "",
timeline: allTimeline,
accountInfo: accountInfo,
totalFetched: allTimeline.length, totalFetched: allTimeline.length,
completed: false, completed: false,
authToken: authToken.trim(), mediaType: selectedMediaType,
mediaType: fetchedMediaType || "all",
retweets: false, retweets: false,
timelineType: "timeline", timelineType: "timeline",
}); });
@@ -809,7 +937,7 @@ function App() {
}, },
cursor: cursor, cursor: cursor,
completed: false, completed: false,
}), fetchedMediaType || "all", cursor || "", false); }), selectedMediaType, cursor || "", false);
} }
catch (err) { catch (err) {
reportDatabaseSaveError("multi-account timeout state", err); reportDatabaseSaveError("multi-account timeout state", err);
@@ -820,20 +948,35 @@ function App() {
const response = await ExtractTimeline({ const response = await ExtractTimeline({
username: cleanUsername, username: cleanUsername,
auth_token: authToken.trim(), auth_token: authToken.trim(),
timeline_type: "timeline", timeline_type: (settings.includeText || settings.includeRetweets) ? "tweets" : "media",
batch_size: batchSizeMultiple, batch_size: batchSizeMultiple,
page: page, page: page,
media_type: fetchedMediaType || "all", media_type: selectedMediaType,
retweets: false, retweets: settings.includeRetweets,
cursor: cursor, 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: TwitterResponse = JSON.parse(response); const data = normalizeTwitterResponse(JSON.parse(response) as TwitterResponse);
if (!accountInfo && data.account_info) { if (!accountInfo && data.account_info) {
accountInfo = data.account_info; accountInfo = data.account_info;
} }
const previousMergeCount = allTimeline.length;
allTimeline = mergeTimelines(allTimeline, data.timeline); allTimeline = mergeTimelines(allTimeline, data.timeline);
cursor = data.cursor; cursor = data.cursor;
hasMore = !!data.cursor && !data.completed; 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++; page++;
if (cursor) { if (cursor) {
saveCursor(cleanUsername, cursor); saveCursor(cleanUsername, cursor);
@@ -864,12 +1007,9 @@ function App() {
saveFetchState({ saveFetchState({
username: cleanUsername, username: cleanUsername,
cursor: cursor || "", cursor: cursor || "",
timeline: allTimeline,
accountInfo: accountInfo,
totalFetched: allTimeline.length, totalFetched: allTimeline.length,
completed: !hasMore, completed: !hasMore,
authToken: authToken.trim(), mediaType: selectedMediaType,
mediaType: fetchedMediaType || "all",
retweets: false, retweets: false,
timelineType: "timeline", timelineType: "timeline",
}); });
@@ -890,7 +1030,7 @@ function App() {
}, },
cursor: cursor, cursor: cursor,
completed: !hasMore, completed: !hasMore,
}), fetchedMediaType || "all", cursor || "", !hasMore); }), selectedMediaType, cursor || "", !hasMore);
} }
catch (err) { catch (err) {
reportDatabaseSaveError("multi-account progress", err); reportDatabaseSaveError("multi-account progress", err);
@@ -943,6 +1083,19 @@ function App() {
accountTimeoutSecondsRef.current.delete(accountId); accountTimeoutSecondsRef.current.delete(accountId);
const errorMsg = error instanceof Error ? error.message : String(error); const errorMsg = error instanceof Error ? error.message : String(error);
const mediaCount = accountMediaCountRef.current.get(accountId) || 0; const mediaCount = accountMediaCountRef.current.get(accountId) || 0;
if (stopAllRef.current || accountStopFlagsRef.current.get(accountId)) {
accountMediaCountRef.current.delete(accountId);
setMultipleAccounts((prev) => prev.map((acc) => acc.id === accountId
? {
...acc,
status: "incomplete" as const,
error: undefined,
mediaCount,
}
: acc));
logger.info(`@${account.username}: stopped - ${mediaCount} items (${elapsedSecs}s)`);
continue;
}
const isAuthError = errorMsg.toLowerCase().includes("401") || const isAuthError = errorMsg.toLowerCase().includes("401") ||
errorMsg.toLowerCase().includes("unauthorized") || errorMsg.toLowerCase().includes("unauthorized") ||
errorMsg.toLowerCase().includes("auth token may be invalid") || errorMsg.toLowerCase().includes("auth token may be invalid") ||
@@ -967,30 +1120,14 @@ function App() {
} }
}; };
const handleStopAll = () => { const handleStopAll = () => {
stopAllRef.current = true; stopMultipleFetches(true);
setIsFetchingAll(false);
accountTimersRef.current.forEach((interval) => clearInterval(interval));
accountTimersRef.current.clear();
accountStartTimesRef.current.clear();
accountTimeoutSecondsRef.current.clear();
setMultipleAccounts((prev) => prev.map((acc) => {
if (acc.status === "fetching") {
const mediaCount = accountMediaCountRef.current.get(acc.id) || acc.mediaCount || 0;
const status = mediaCount === 0 ? ("failed" as const) : ("incomplete" as const);
return { ...acc, status, mediaCount };
}
return acc;
}));
CleanupExtractorProcesses().catch(() => { });
toast.info("Stopped all fetches");
}; };
const handleStopAccount = (accountId: string) => { const handleStopAccount = (accountId: string) => {
accountStopFlagsRef.current.set(accountId, true); accountStopFlagsRef.current.set(accountId, true);
setMultipleAccounts((prev) => prev.map((acc) => { setMultipleAccounts((prev) => prev.map((acc) => {
if (acc.id === accountId && acc.status === "fetching") { if (acc.id === accountId && acc.status === "fetching") {
const mediaCount = accountMediaCountRef.current.get(accountId) || acc.mediaCount || 0; const mediaCount = accountMediaCountRef.current.get(accountId) || acc.mediaCount || 0;
const status = mediaCount === 0 ? ("failed" as const) : ("incomplete" as const); return { ...acc, status: "incomplete" as const, mediaCount };
return { ...acc, status, mediaCount };
} }
return acc; return acc;
})); }));
@@ -1004,19 +1141,45 @@ function App() {
CleanupExtractorProcesses().catch(() => { }); CleanupExtractorProcesses().catch(() => { });
toast.info("Stopped account fetch"); toast.info("Stopped account fetch");
}; };
const handleRetryAccount = async (accountId: string) => { const handlePageChange = (page: PageType) => {
if (currentPage === "settings" && hasUnsavedSettings && page !== "settings") {
setPendingPageChange(page);
setShowUnsavedChangesDialog(true);
return;
}
setCurrentPage(page);
};
const handleDiscardChanges = () => {
setShowUnsavedChangesDialog(false);
if (resetSettingsFn) {
resetSettingsFn();
}
const savedSettings = getSettings();
applyThemeMode(savedSettings.themeMode);
applyTheme(savedSettings.theme);
applyFont(savedSettings.fontFamily, savedSettings.customFonts);
setHasUnsavedSettings(false);
if (pendingPageChange) {
setCurrentPage(pendingPageChange);
setPendingPageChange(null);
}
};
const handleCancelNavigation = () => {
setShowUnsavedChangesDialog(false);
setPendingPageChange(null);
};
const handleRetryAccount = async (accountId: string, authToken: string) => {
const account = multipleAccounts.find((acc) => acc.id === accountId); const account = multipleAccounts.find((acc) => acc.id === accountId);
if (!account) if (!account)
return; return;
const PUBLIC_AUTH_TOKEN_KEY = "twitter_public_auth_token";
const authToken = localStorage.getItem(PUBLIC_AUTH_TOKEN_KEY) || "";
if (!authToken.trim()) { if (!authToken.trim()) {
toast.error("Please enter your auth token"); toast.error("Please enter your auth token");
return; return;
} }
const retrySettings = getSettings(); const retrySettings = getSettings();
const isSingleModeRetry = retrySettings.fetchMode === "single"; const selectedMediaType = fetchedMediaType || "all";
const batchSizeRetry = isSingleModeRetry ? 0 : BATCH_SIZE; setFetchedMediaType(selectedMediaType);
const batchSizeRetry = BATCH_SIZE;
const cleanUsername = account.username.trim(); const cleanUsername = account.username.trim();
let existingState: FetchState | null = null; let existingState: FetchState | null = null;
let cursor: string | undefined = account.cursor; let cursor: string | undefined = account.cursor;
@@ -1026,12 +1189,28 @@ function App() {
existingState = getFetchState(cleanUsername); existingState = getFetchState(cleanUsername);
if (existingState && existingState.cursor && !existingState.completed) { if (existingState && existingState.cursor && !existingState.completed) {
cursor = existingState.cursor; cursor = existingState.cursor;
allTimeline = existingState.timeline; const resumeMediaType = existingState.mediaType || selectedMediaType;
if (existingState.accountInfo) { const canonicalHandle = account.accountInfo?.name?.trim();
accountInfo = existingState.accountInfo; 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;
previousMediaCount = existingState.totalFetched;
logger.info(`Resuming @${cleanUsername} from ${existingState.totalFetched} items...`);
}
else {
clearFetchState(cleanUsername);
clearCursor(cleanUsername);
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;
previousMediaCount = 0;
} }
previousMediaCount = existingState.timeline.length;
logger.info(`Resuming @${cleanUsername} from ${allTimeline.length} items...`);
} }
else { else {
if (!cursor) { if (!cursor) {
@@ -1044,7 +1223,7 @@ function App() {
else { else {
try { try {
const accounts = await GetAllAccountsFromDB(); const accounts = await GetAllAccountsFromDB();
const dbAccount = accounts.find((acc) => acc.username.toLowerCase() === cleanUsername.toLowerCase()); const dbAccount = accounts.find((acc) => acc.username.toLowerCase() === cleanUsername.toLowerCase() && (acc.media_type || "all") === selectedMediaType);
if (dbAccount?.cursor) { if (dbAccount?.cursor) {
cursor = dbAccount.cursor; cursor = dbAccount.cursor;
previousMediaCount = account.mediaCount || 0; previousMediaCount = account.mediaCount || 0;
@@ -1120,6 +1299,7 @@ function App() {
try { try {
let hasMore = true; let hasMore = true;
let page = 0; let page = 0;
const seenCursors = new Set<string>();
while (hasMore && !stopAllRef.current) { while (hasMore && !stopAllRef.current) {
if (accountStopFlagsRef.current.get(accountId)) { if (accountStopFlagsRef.current.get(accountId)) {
break; break;
@@ -1127,20 +1307,35 @@ function App() {
const response = await ExtractTimeline({ const response = await ExtractTimeline({
username: cleanUsername, username: cleanUsername,
auth_token: authToken.trim(), auth_token: authToken.trim(),
timeline_type: "timeline", timeline_type: (retrySettings.includeText || retrySettings.includeRetweets) ? "tweets" : "media",
batch_size: batchSizeRetry, batch_size: batchSizeRetry,
page: page, page: page,
media_type: fetchedMediaType || "all", media_type: selectedMediaType,
retweets: false, retweets: retrySettings.includeRetweets,
cursor: cursor, 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: TwitterResponse = JSON.parse(response); const data = normalizeTwitterResponse(JSON.parse(response) as TwitterResponse);
if (!accountInfo && data.account_info) { if (!accountInfo && data.account_info) {
accountInfo = data.account_info; accountInfo = data.account_info;
} }
const previousRetryCount = allTimeline.length;
allTimeline = mergeTimelines(allTimeline, data.timeline); allTimeline = mergeTimelines(allTimeline, data.timeline);
cursor = data.cursor; cursor = data.cursor;
hasMore = !!data.cursor && !data.completed; 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++; page++;
if (cursor) { if (cursor) {
saveCursor(cleanUsername, cursor); saveCursor(cleanUsername, cursor);
@@ -1165,12 +1360,9 @@ function App() {
saveFetchState({ saveFetchState({
username: cleanUsername, username: cleanUsername,
cursor: cursor || "", cursor: cursor || "",
timeline: allTimeline,
accountInfo: accountInfo,
totalFetched: allTimeline.length, totalFetched: allTimeline.length,
completed: !hasMore, completed: !hasMore,
authToken: authToken.trim(), mediaType: selectedMediaType,
mediaType: fetchedMediaType || "all",
retweets: false, retweets: false,
timelineType: "timeline", timelineType: "timeline",
}); });
@@ -1197,7 +1389,7 @@ function App() {
}, },
cursor: cursor, cursor: cursor,
completed: !hasMore, completed: !hasMore,
}), fetchedMediaType || "all", cursor || "", !hasMore); }), selectedMediaType, cursor || "", !hasMore);
} }
catch (err) { catch (err) {
reportDatabaseSaveError("retry progress", err); reportDatabaseSaveError("retry progress", err);
@@ -1250,6 +1442,19 @@ function App() {
accountTimeoutSecondsRef.current.delete(accountId); accountTimeoutSecondsRef.current.delete(accountId);
const errorMsg = error instanceof Error ? error.message : String(error); const errorMsg = error instanceof Error ? error.message : String(error);
const mediaCount = accountMediaCountRef.current.get(accountId) || 0; const mediaCount = accountMediaCountRef.current.get(accountId) || 0;
if (stopAllRef.current || accountStopFlagsRef.current.get(accountId)) {
accountMediaCountRef.current.delete(accountId);
setMultipleAccounts((prev) => prev.map((acc) => acc.id === accountId
? {
...acc,
status: "incomplete" as const,
error: undefined,
mediaCount,
}
: acc));
logger.info(`@${account.username}: stopped - ${mediaCount} items (${elapsedSecs}s)`);
return;
}
const isAuthError = errorMsg.toLowerCase().includes("401") || const isAuthError = errorMsg.toLowerCase().includes("401") ||
errorMsg.toLowerCase().includes("unauthorized") || errorMsg.toLowerCase().includes("unauthorized") ||
errorMsg.toLowerCase().includes("auth token may be invalid") || errorMsg.toLowerCase().includes("auth token may be invalid") ||
@@ -1271,40 +1476,74 @@ function App() {
const renderPage = () => { const renderPage = () => {
switch (currentPage) { switch (currentPage) {
case "settings": case "settings":
return <SettingsPage />; return <SettingsPage onUnsavedChangesChange={setHasUnsavedSettings} onResetRequest={setResetSettingsFn}/>;
case "debug": case "debug":
return <DebugLoggerPage />; return <DebugLoggerPage />;
case "database": case "database":
return (<DatabaseView onBack={() => setCurrentPage("main")} onLoadAccount={handleLoadFromDB} onUpdateSelected={handleUpdateSelected}/>); return (<DatabaseView onBack={() => setCurrentPage("main")} onLoadAccount={handleLoadFromDB} onUpdateSelected={handleUpdateSelected}/>);
case "support":
return <SupportPage />;
default: default:
return (<> return (<>
<Header version={CURRENT_VERSION} hasUpdate={hasUpdate} releaseDate={releaseDate}/> <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} onImportFile={handleImportFile} onFetchAll={handleFetchAll} onStopAll={handleStopAll} onStopAccount={handleStopAccount} onRetryAccount={handleRetryAccount} isFetchingAll={isFetchingAll} mode={searchMode} privateType={searchPrivateType} onModeChange={(mode, privateType) => { <SearchBar username={username} loading={loading} onUsernameChange={setUsername} onFetch={handleFetch} onStopFetch={handleStopFetch} onResume={handleResume} onClearResume={handleClearResume} resumeInfo={resumeInfo} history={fetchHistory} onHistorySelect={handleHistorySelect} onHistoryRemove={removeFromHistory} hasResult={!!result} elapsedTime={elapsedTime} remainingTime={remainingTime} fetchType={fetchType} onFetchTypeChange={handleFetchTypeChange} multipleAccounts={multipleAccounts} onImportAccounts={handleImportAccounts} onFetchAll={handleFetchAll} onStopAll={handleStopAll} onStopAccount={handleStopAccount} onRetryAccount={handleRetryAccount} onClearMultipleAccounts={handleClearMultipleAccounts} onRemoveMultipleAccount={handleRemoveMultipleAccount} onOpenSavedAccounts={() => setCurrentPage("database")} isFetchingAll={isFetchingAll} mode={searchMode} privateType={searchPrivateType} onModeChange={(mode, privateType) => {
setSearchMode(mode); setSearchMode(mode);
if (privateType) { if (privateType) {
setSearchPrivateType(privateType); setSearchPrivateType(privateType);
} }
}}/> }}/>
{result && fetchType === "single" && (<div className="mt-4"> {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>
<MediaList accountInfo={result.account_info} timeline={result.timeline} totalUrls={result.total_urls} fetchedMediaType={fetchedMediaType} newMediaCount={newMediaCount}/> <MediaList accountInfo={result.account_info} timeline={result.timeline} totalUrls={result.total_urls} fetchedMediaType={fetchedMediaType} newMediaCount={newMediaCount}/>
</div>)} </div>)}
</>); </>);
} }
}; };
return (<TooltipProvider> return (<TooltipProvider>
<div className="min-h-screen bg-background flex flex-col"> <div className="h-screen overflow-hidden bg-background">
<DependencySetupDialog /> <DependencySetupDialog />
<TitleBar /> <TitleBar />
<Sidebar currentPage={currentPage} onPageChange={setCurrentPage}/> <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="flex-1 ml-14 mt-10 p-4 md:p-8"> <div className="p-4 md:p-8">
<div className="max-w-5xl mx-auto"> <div className="max-w-5xl mx-auto">
{renderPage()} {renderPage()}
</div>
</div> </div>
</div> </div>
<Dialog open={showUnsavedChangesDialog} onOpenChange={(open) => {
if (open) {
setShowUnsavedChangesDialog(true);
return;
}
handleCancelNavigation();
}}>
<DialogContent className="sm:max-w-106.25 [&>button]:hidden">
<DialogHeader>
<DialogTitle>Unsaved Changes</DialogTitle>
<DialogDescription>
You have unsaved changes in Settings. If you leave now, your changes will be lost.
</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button variant="outline" onClick={handleCancelNavigation}>
Cancel
</Button>
<Button variant="destructive" onClick={handleDiscardChanges}>
Discard Changes
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div> </div>
</TooltipProvider>); </TooltipProvider>);
} }
Binary file not shown.

After

Width:  |  Height:  |  Size: 903 KiB

+13
View File
@@ -0,0 +1,13 @@
<svg width="241" height="194" viewBox="0 0 241 194" fill="none" xmlns="http://www.w3.org/2000/svg">
<mask id="mask0_1_219" style="mask-type:luminance" maskUnits="userSpaceOnUse" x="-1" y="0" width="242" height="194">
<path d="M240.469 0.958984H-0.00585938V193.918H240.469V0.958984Z" fill="white"/>
</mask>
<g mask="url(#mask0_1_219)">
<path d="M96.1344 193.911C61.1312 193.911 32.6597 178.256 15.9721 149.829C1.19788 124.912 -0.00585938 97.9229 -0.00585938 67.7662C-0.00585938 49.8876 5.37293 34.3215 15.5413 22.7466C24.8861 12.1157 38.1271 5.22907 52.8317 3.35378C70.2858 1.14271 91.9848 0.958984 114.545 0.958984C151.259 0.958984 161.63 1.4088 176.075 2.85328C195.29 4.76026 211.458 11.932 222.824 23.5955C234.368 35.4428 240.469 51.2624 240.469 69.3627V72.9994C240.469 103.885 219.821 129.733 191.046 136.759C188.898 141.827 186.237 146.871 183.089 151.837L183.006 151.964C172.869 167.632 149.042 193.918 103.401 193.918H96.1281L96.1344 193.911Z" fill="white"/>
<path d="M174.568 17.9772C160.927 16.6151 151.38 16.1589 114.552 16.1589C90.908 16.1589 70.9008 16.387 54.7644 18.4334C33.3949 21.164 15.2058 37.5285 15.2058 67.7674C15.2058 98.0066 16.796 121.422 29.0741 142.107C42.9425 165.751 66.1302 178.707 96.1412 178.707H103.414C140.242 178.707 160.25 159.156 170.253 143.698C174.574 136.874 177.754 130.058 179.801 123.234C205.947 120.96 225.27 99.3624 225.27 72.9941V69.3577C225.27 40.9432 206.631 21.164 174.574 17.9772H174.568Z" fill="white"/>
<path d="M15.1975 67.7674C15.1975 37.5285 33.3866 21.164 54.7559 18.4334C70.8987 16.387 90.906 16.1589 114.544 16.1589C151.372 16.1589 160.919 16.6151 174.559 17.9772C206.617 21.1576 225.255 40.937 225.255 69.3577V72.9941C225.255 99.3687 205.932 120.966 179.786 123.234C177.74 130.058 174.559 136.874 170.238 143.698C160.235 159.156 140.228 178.707 103.4 178.707H96.1264C66.1155 178.707 42.9277 165.751 29.0595 142.107C16.7814 121.422 15.1912 98.4563 15.1912 67.7674" fill="#202020"/>
<path d="M32.2469 67.9899C32.2469 97.3168 34.0654 116.184 43.6127 133.689C54.5225 153.924 74.3018 161.653 96.8117 161.653H103.857C133.411 161.653 147.736 147.329 155.693 134.829C159.558 128.462 162.966 121.417 164.784 112.547L166.147 106.864H174.332C192.521 106.864 208.208 92.09 208.208 73.2166V69.8082C208.208 48.6669 195.024 37.5228 172.058 34.7987C159.102 33.6646 151.372 33.2084 114.538 33.2084C89.7602 33.2084 72.0272 33.4364 58.6152 35.4828C39.7483 38.2134 32.2407 48.8951 32.2407 67.9899" fill="white"/>
<path d="M166.158 83.6801C166.158 86.4107 168.204 88.4572 171.841 88.4572C183.435 88.4572 189.802 81.8619 189.802 70.9523C189.802 60.0427 183.435 53.2195 171.841 53.2195C168.204 53.2195 166.158 55.2657 166.158 57.9963V83.6866V83.6801Z" fill="#202020"/>
<path d="M54.5321 82.3198C54.5321 95.732 62.0332 107.326 71.5807 116.424C77.9478 122.562 87.9515 128.93 94.7685 133.022C96.8147 134.157 98.8611 134.841 101.136 134.841C103.866 134.841 106.134 134.157 107.959 133.022C114.782 128.93 124.779 122.562 130.919 116.424C140.694 107.332 148.195 95.7383 148.195 82.3198C148.195 67.7673 137.286 54.8115 121.599 54.8115C112.28 54.8115 105.912 59.5882 101.136 66.1772C96.8147 59.582 90.2259 54.8115 80.9001 54.8115C64.9855 54.8115 54.5256 67.7673 54.5256 82.3198" fill="#FF5A16"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 3.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

+335 -221
View File
@@ -1,4 +1,4 @@
import { useState, useEffect, useRef } from "react"; import { useState, useEffect, useRef, useCallback, useMemo, useDeferredValue } from "react";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge"; import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
@@ -15,8 +15,8 @@ import { Trash2, FileInput, FileOutput, Pencil, Tag, Shuffle, X, XCircle, Downlo
import { toastWithSound as toast } from "@/lib/toast-with-sound"; import { toastWithSound as toast } from "@/lib/toast-with-sound";
import { getSettings } from "@/lib/settings"; import { getSettings } from "@/lib/settings";
import { openExternal } from "@/lib/utils"; import { openExternal } from "@/lib/utils";
import { GetAllAccountsFromDB, GetAccountFromDB, DeleteAccountFromDB, SaveAccountToDB, ExportAccountJSON, ExportAccountsTXT, UpdateAccountGroup, GetAllGroups, DownloadMediaWithMetadata, StopDownload, CheckFolderExists, OpenFolder, GetFolderPath, } from "../../wailsjs/go/main/App"; import { GetAllAccountsFromDB, GetAccountFromDB, DeleteAccountFromDB, SaveAccountToDB, ExportAccountJSON, ExportAccountsTXT, UpdateAccountGroup, GetAllGroups, DownloadMediaWithMetadata, StopDownload, CheckFoldersExist, OpenFolder, GetFolderPath, } from "../../wailsjs/go/main/App";
import { EventsOn, EventsOff } from "../../wailsjs/runtime/runtime"; import { EventsOn } from "../../wailsjs/runtime/runtime";
import { main } from "../../wailsjs/go/models"; import { main } from "../../wailsjs/go/models";
interface DownloadProgress { interface DownloadProgress {
current: number; current: number;
@@ -66,6 +66,9 @@ interface DatabaseViewProps {
} }
const INITIAL_LOAD_COUNT = 12; const INITIAL_LOAD_COUNT = 12;
const LOAD_MORE_COUNT = 12; const LOAD_MORE_COUNT = 12;
function getContentScrollElement(): HTMLElement | null {
return document.getElementById("app-content-scroll");
}
export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewProps) { export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewProps) {
const [accounts, setAccounts] = useState<AccountListItem[]>([]); const [accounts, setAccounts] = useState<AccountListItem[]>([]);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
@@ -77,8 +80,15 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
const [filterMediaType, setFilterMediaType] = useState<string>("all"); const [filterMediaType, setFilterMediaType] = useState<string>("all");
const [accountViewMode, setAccountViewMode] = useState<"public" | "private">("public"); const [accountViewMode, setAccountViewMode] = useState<"public" | "private">("public");
const [searchQuery, setSearchQuery] = useState<string>(""); 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 [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 [editingAccount, setEditingAccount] = useState<AccountListItem | null>(null);
const [editGroupName, setEditGroupName] = useState(""); const [editGroupName, setEditGroupName] = useState("");
const [editGroupColor, setEditGroupColor] = useState(""); const [editGroupColor, setEditGroupColor] = useState("");
@@ -92,26 +102,16 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
const stopBulkDownloadRef = useRef(false); const stopBulkDownloadRef = useRef(false);
const loadMoreRef = useRef<HTMLDivElement>(null); const loadMoreRef = useRef<HTMLDivElement>(null);
const [folderExistence, setFolderExistence] = useState<Map<number, boolean>>(new Map()); const [folderExistence, setFolderExistence] = useState<Map<number, boolean>>(new Map());
const checkFolderExistence = async (accountsList: AccountListItem[]) => { const getFolderNameForAccount = (username: string) => {
const settings = getSettings(); if (username === "bookmarks") {
const basePath = settings.downloadPath; return "My Bookmarks";
if (!basePath)
return;
const folderMap = new Map<number, boolean>();
for (const account of accountsList) {
let folderName = account.username;
if (account.username === "bookmarks") {
folderName = "My Bookmarks";
}
else if (account.username === "likes") {
folderName = "My Likes";
}
const exists = await CheckFolderExists(basePath, folderName);
folderMap.set(account.id, exists);
} }
setFolderExistence(folderMap); if (username === "likes") {
return "My Likes";
}
return username;
}; };
const loadAccounts = async () => { const loadAccounts = useCallback(async () => {
setLoading(true); setLoading(true);
try { try {
const data = await GetAllAccountsFromDB(); const data = await GetAllAccountsFromDB();
@@ -120,9 +120,6 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
if (groupsData) { if (groupsData) {
setGroups(groupsData.map((g) => ({ name: g.name || "", color: g.color || "" }))); setGroups(groupsData.map((g) => ({ name: g.name || "", color: g.color || "" })));
} }
if (data && data.length > 0) {
checkFolderExistence(data);
}
} }
catch (error) { catch (error) {
console.error("Failed to load accounts:", error); console.error("Failed to load accounts:", error);
@@ -131,96 +128,140 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
finally { finally {
setLoading(false); setLoading(false);
} }
};
useEffect(() => {
loadAccounts();
}, []); }, []);
useEffect(() => {
void loadAccounts();
}, [loadAccounts]);
useEffect(() => { useEffect(() => {
setVisibleCount(INITIAL_LOAD_COUNT); setVisibleCount(INITIAL_LOAD_COUNT);
}, [gridView, searchQuery, filterGroup, filterMediaType, accountViewMode, sortOrder]); }, [gridView, searchQuery, filterGroup, filterMediaType, accountViewMode, sortOrder]);
useEffect(() => { useEffect(() => {
const scrollElement = getContentScrollElement();
if (!scrollElement) {
return;
}
const handleScroll = () => { const handleScroll = () => {
setShowScrollTop(window.scrollY > 300); setShowScrollTop(scrollElement.scrollTop > 300);
}; };
window.addEventListener("scroll", handleScroll); handleScroll();
return () => window.removeEventListener("scroll", handleScroll); scrollElement.addEventListener("scroll", handleScroll);
return () => scrollElement.removeEventListener("scroll", handleScroll);
}, []); }, []);
useEffect(() => { useEffect(() => {
const unsubscribe = EventsOn("download-progress", (progress: DownloadProgress) => { const unsubscribe = EventsOn("download-progress", (progress: DownloadProgress) => {
setDownloadProgress(progress); setDownloadProgress(progress);
}); });
return () => { return () => {
EventsOff("download-progress");
unsubscribe(); unsubscribe();
}; };
}, []); }, []);
const scrollToTop = () => { const scrollToTop = () => {
window.scrollTo({ top: 0, behavior: "smooth" }); getContentScrollElement()?.scrollTo({ top: 0, behavior: "smooth" });
}; };
const isPrivateAccount = (username: string) => username === "bookmarks" || username === "likes"; const isPrivateAccount = (username: string) => username === "bookmarks" || username === "likes";
const publicAccounts = accounts.filter((acc) => !isPrivateAccount(acc.username)); const currentDownloadPath = getSettings().downloadPath || "";
const privateAccounts = accounts.filter((acc) => isPrivateAccount(acc.username)); const publicAccounts = useMemo(() => accounts.filter((acc) => !isPrivateAccount(acc.username)), [accounts]);
const baseAccounts = accountViewMode === "public" ? publicAccounts : privateAccounts; const privateAccounts = useMemo(() => accounts.filter((acc) => isPrivateAccount(acc.username)), [accounts]);
const filteredAccounts = baseAccounts const filteredAccounts = useMemo(() => {
.filter((acc) => { const baseAccounts = accountViewMode === "public" ? publicAccounts : privateAccounts;
if (searchQuery) { return baseAccounts
const query = searchQuery.toLowerCase(); .filter((acc) => {
const matchesUsername = acc.username.toLowerCase().includes(query); if (deferredSearchQuery) {
const matchesName = acc.name.toLowerCase().includes(query); const query = deferredSearchQuery.toLowerCase();
if (!matchesUsername && !matchesName) const matchesUsername = acc.username.toLowerCase().includes(query);
return false; const matchesName = acc.name.toLowerCase().includes(query);
} if (!matchesUsername && !matchesName)
if (filterGroup !== "all") {
if (filterGroup === "ungrouped" && acc.group_name)
return false;
if (filterGroup !== "ungrouped" && acc.group_name !== filterGroup)
return false;
}
if (filterMediaType !== "all") {
const accMediaType = acc.media_type || "all";
if (filterMediaType === "all-media") {
if (accMediaType !== "all")
return false; return false;
} }
else { if (filterGroup !== "all") {
if (accMediaType !== filterMediaType) if (filterGroup === "ungrouped" && acc.group_name)
return false;
if (filterGroup !== "ungrouped" && acc.group_name !== filterGroup)
return false; return false;
} }
} if (filterMediaType !== "all") {
return true; const accMediaType = acc.media_type || "all";
}) if (filterMediaType === "all-media") {
.sort((a, b) => { if (accMediaType !== "all")
switch (sortOrder) { return false;
case "newest": { }
const dateA = new Date(a.last_fetched).getTime(); else if (accMediaType !== filterMediaType) {
const dateB = new Date(b.last_fetched).getTime(); return false;
return dateB - dateA; }
} }
case "oldest": { return true;
const dateA = new Date(a.last_fetched).getTime(); })
const dateB = new Date(b.last_fetched).getTime(); .sort((a, b) => {
return dateA - dateB; switch (sortOrder) {
case "newest": {
const dateA = new Date(a.last_fetched).getTime();
const dateB = new Date(b.last_fetched).getTime();
return dateB - dateA;
}
case "oldest": {
const dateA = new Date(a.last_fetched).getTime();
const dateB = new Date(b.last_fetched).getTime();
return dateA - dateB;
}
case "username-asc":
return a.username.toLowerCase().localeCompare(b.username.toLowerCase());
case "username-desc":
return b.username.toLowerCase().localeCompare(a.username.toLowerCase());
case "followers-high":
return (b.followers_count || 0) - (a.followers_count || 0);
case "followers-low":
return (a.followers_count || 0) - (b.followers_count || 0);
case "posts-high":
return (b.statuses_count || 0) - (a.statuses_count || 0);
case "posts-low":
return (a.statuses_count || 0) - (b.statuses_count || 0);
case "media-high":
return (b.total_media || 0) - (a.total_media || 0);
case "media-low":
return (a.total_media || 0) - (b.total_media || 0);
default:
return 0;
} }
case "username-asc": });
return a.username.toLowerCase().localeCompare(b.username.toLowerCase()); }, [accountViewMode, filterGroup, filterMediaType, privateAccounts, publicAccounts, deferredSearchQuery, sortOrder]);
case "username-desc": const visibleAccounts = useMemo(() => filteredAccounts.slice(0, visibleCount), [filteredAccounts, visibleCount]);
return b.username.toLowerCase().localeCompare(a.username.toLowerCase()); const visibleAccountsKey = visibleAccounts
case "followers-high": .map((account) => `${account.id}:${account.username}`)
return (b.followers_count || 0) - (a.followers_count || 0); .join("|");
case "followers-low": useEffect(() => {
return (a.followers_count || 0) - (b.followers_count || 0); const basePath = currentDownloadPath;
case "posts-high": if (!basePath) {
return (b.statuses_count || 0) - (a.statuses_count || 0); setFolderExistence(new Map());
case "posts-low": return;
return (a.statuses_count || 0) - (b.statuses_count || 0);
case "media-high":
return (b.total_media || 0) - (a.total_media || 0);
case "media-low":
return (a.total_media || 0) - (b.total_media || 0);
default:
return 0;
} }
}); if (visibleAccounts.length === 0) {
return;
}
let active = true;
const loadVisibleFolderExistence = async () => {
try {
const folderNames = visibleAccounts.map((account) => getFolderNameForAccount(account.username));
const results = await CheckFoldersExist(basePath, folderNames);
if (!active) {
return;
}
setFolderExistence((prev) => {
const next = new Map(prev);
for (const account of visibleAccounts) {
next.set(account.id, results[getFolderNameForAccount(account.username)] ?? false);
}
return next;
});
}
catch (error) {
console.error("Failed to check visible folders:", error);
}
};
void loadVisibleFolderExistence();
return () => {
active = false;
};
}, [currentDownloadPath, visibleAccounts, visibleAccountsKey]);
useEffect(() => { useEffect(() => {
const currentRef = loadMoreRef.current; const currentRef = loadMoreRef.current;
if (!currentRef) if (!currentRef)
@@ -247,9 +288,10 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
await UpdateAccountGroup(editingAccount.id, editGroupName, editGroupColor); await UpdateAccountGroup(editingAccount.id, editGroupName, editGroupColor);
toast.success(`Updated group for @${editingAccount.username}`); toast.success(`Updated group for @${editingAccount.username}`);
setEditingAccount(null); setEditingAccount(null);
loadAccounts(); await loadAccounts();
} }
catch (error) { catch (error) {
console.error("Failed to update group:", error);
toast.error("Failed to update group"); toast.error("Failed to update group");
} }
}; };
@@ -257,9 +299,10 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
try { try {
await DeleteAccountFromDB(id); await DeleteAccountFromDB(id);
toast.success(`Deleted @${username}`); toast.success(`Deleted @${username}`);
loadAccounts(); await loadAccounts();
} }
catch (error) { catch (error) {
console.error(`Failed to delete @${username}:`, error);
toast.error("Failed to delete account"); toast.error("Failed to delete account");
} }
}; };
@@ -269,23 +312,32 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
onLoadAccount(responseJSON, username); onLoadAccount(responseJSON, username);
} }
catch (error) { catch (error) {
console.error(`Failed to load @${username} from database:`, error);
toast.error("Failed to load account data"); toast.error("Failed to load account data");
} }
}; };
const handleOpenFolder = async (username: string) => { const handleOpenFolder = async (account: AccountListItem) => {
const settings = getSettings(); const settings = getSettings();
let folderName = username; const basePath = settings.downloadPath || "";
if (username === "bookmarks") { if (!basePath) {
folderName = "My Bookmarks"; toast.error("Download folder is not set");
return;
} }
else if (username === "likes") { let username = account.username || account.name || "";
folderName = "My Likes";
}
const folderPath = await GetFolderPath(settings.downloadPath, folderName);
try { try {
const responseJSON = await GetAccountFromDB(account.id);
const data = JSON.parse(responseJSON);
username = data.account_info?.name || username;
}
catch {
}
const folderName = getFolderNameForAccount(username);
try {
const folderPath = await GetFolderPath(basePath, folderName);
await OpenFolder(folderPath); await OpenFolder(folderPath);
} }
catch (error) { catch (error) {
console.error(`Failed to open folder for @${username}:`, error);
toast.error("Failed to open folder"); toast.error("Failed to open folder");
} }
}; };
@@ -332,10 +384,22 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
})), })),
output_dir: outputDir, output_dir: outputDir,
username: actualUsername, username: actualUsername,
concurrent_downloads: settings.concurrentDownloads || 10,
skip_existing: settings.skipExistingFiles,
delete_incomplete_files: settings.deleteIncompleteFiles,
retry_attempts: settings.retryAttempts,
proxy: settings.proxy || "", proxy: settings.proxy || "",
filename_template: settings.filenameTemplate || "",
folder_template: settings.folderTemplate || "",
}); });
const response = await DownloadMediaWithMetadata(request); const response = await DownloadMediaWithMetadata(request);
if (response.success) { if (response.cancelled) {
const message = response.downloaded > 0 || response.skipped > 0
? `Download stopped for @${username} after ${response.downloaded + response.skipped} items`
: `Download stopped for @${username}`;
toast.info(message);
}
else if (response.success) {
const parts: string[] = []; const parts: string[] = [];
if (response.downloaded > 0) { if (response.downloaded > 0) {
parts.push(`${response.downloaded} file${response.downloaded !== 1 ? 's' : ''} downloaded`); parts.push(`${response.downloaded} file${response.downloaded !== 1 ? 's' : ''} downloaded`);
@@ -445,9 +509,20 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
})), })),
output_dir: outputDir, output_dir: outputDir,
username: actualUsername, username: actualUsername,
concurrent_downloads: settings.concurrentDownloads || 10,
skip_existing: settings.skipExistingFiles,
delete_incomplete_files: settings.deleteIncompleteFiles,
retry_attempts: settings.retryAttempts,
proxy: settings.proxy || "", proxy: settings.proxy || "",
filename_template: settings.filenameTemplate || "",
folder_template: settings.folderTemplate || "",
}); });
const response = await DownloadMediaWithMetadata(request); const response = await DownloadMediaWithMetadata(request);
if (response.cancelled) {
toast.info(`Stopped while downloading @${account.username}`);
stopBulkDownloadRef.current = true;
break;
}
if (response.success) { if (response.success) {
totalDownloaded += response.downloaded; totalDownloaded += response.downloaded;
totalSkipped += response.skipped || 0; totalSkipped += response.skipped || 0;
@@ -521,6 +596,7 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
toast.success(`Exported ${exported} account(s) to ${outputDir}\\twitterxmediabatchdownloader_backups`); toast.success(`Exported ${exported} account(s) to ${outputDir}\\twitterxmediabatchdownloader_backups`);
} }
catch (error) { catch (error) {
console.error("Failed to export JSON backups:", error);
toast.error("Failed to export"); toast.error("Failed to export");
} }
}; };
@@ -537,6 +613,7 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
toast.success(`Exported ${formatNumberWithComma(idsToExport.length)} account(s) to ${outputDir}\\twitterxmediabatchdownloader_backups\\twitterxmediabatchdownloader_multiple.txt`); toast.success(`Exported ${formatNumberWithComma(idsToExport.length)} account(s) to ${outputDir}\\twitterxmediabatchdownloader_backups\\twitterxmediabatchdownloader_multiple.txt`);
} }
catch (error) { catch (error) {
console.error("Failed to export TXT backup:", error);
toast.error("Failed to export"); toast.error("Failed to export");
} }
}; };
@@ -553,104 +630,116 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
input.type = "file"; input.type = "file";
input.accept = ".json"; input.accept = ".json";
input.multiple = true; input.multiple = true;
input.style.display = "none";
document.body.appendChild(input);
const cleanup = () => {
if (input.parentNode) {
input.parentNode.removeChild(input);
}
};
input.onchange = async (e) => { input.onchange = async (e) => {
const files = (e.target as HTMLInputElement).files; try {
if (!files || files.length === 0) const files = (e.target as HTMLInputElement).files;
return; if (!files || files.length === 0)
let imported = 0; return;
for (const file of Array.from(files)) { let imported = 0;
try { for (const file of Array.from(files)) {
const text = await file.text(); try {
const data = JSON.parse(text); const text = await file.text();
let detectedMediaType = "all"; const data = JSON.parse(text);
if (data.media_type) { let detectedMediaType = "all";
detectedMediaType = data.media_type; 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;
} }
} else if (data.media_list && Array.isArray(data.media_list)) {
else if (data.timeline && Array.isArray(data.timeline)) { const types = new Set(data.media_list.map((item: {
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; media_type?: string;
}) => ({ type?: string;
url: item.url, }) => item.media_type || item.type).filter(Boolean));
date: item.date, if (types.size === 1) {
tweet_id: item.tweet_id, const singleType = Array.from(types)[0] as string;
type: item.media_type || item.type, if (singleType === "photo")
is_retweet: false, detectedMediaType = "image";
})), else if (singleType === "video")
metadata: { detectedMediaType = "video";
new_entries: data.media_list.length, else if (singleType === "animated_gif")
page: 0, detectedMediaType = "gif";
batch_size: 0, else
has_more: false, detectedMediaType = singleType;
}, }
}; }
await SaveAccountToDB(convertedData.account_info.name, convertedData.account_info.nick, convertedData.account_info.profile_image, convertedData.total_urls, JSON.stringify(convertedData), detectedMediaType); else if (data.timeline && Array.isArray(data.timeline)) {
imported++; 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) { if (imported > 0) {
console.error(`Failed to import ${file.name}:`, err); toast.success(`Imported ${imported} account(s)`);
loadAccounts();
}
else {
toast.error("No valid files imported");
} }
} }
if (imported > 0) { finally {
toast.success(`Imported ${imported} account(s)`); cleanup();
loadAccounts();
}
else {
toast.error("No valid files imported");
} }
}; };
input.click(); input.click();
@@ -782,9 +871,10 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
toast.success(`Deleted ${formatNumberWithComma(idsToDelete.length)} account${idsToDelete.length !== 1 ? 's' : ''}`); toast.success(`Deleted ${formatNumberWithComma(idsToDelete.length)} account${idsToDelete.length !== 1 ? 's' : ''}`);
setClearAllDialogOpen(false); setClearAllDialogOpen(false);
setSelectedIds(new Set()); setSelectedIds(new Set());
loadAccounts(); await loadAccounts();
} }
catch (error) { catch (error) {
console.error("Failed to delete selected accounts:", error);
toast.error("Failed to delete accounts"); toast.error("Failed to delete accounts");
} }
}}> }}>
@@ -936,9 +1026,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"> {gridView === "large" && (<div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
{filteredAccounts {filteredAccounts
.slice(0, visibleCount) .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"}`}> .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)} className="absolute top-2 left-2 z-10"/> <Checkbox checked={selectedIds.has(account.id)} onCheckedChange={() => toggleSelect(account.id)} onClick={(e) => e.stopPropagation()} className="absolute top-2 left-2 z-10"/>
<div className="absolute top-2 right-2 z-10 flex gap-1"> <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")}> <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")}>
@@ -953,9 +1043,14 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
</Badge>)} </Badge>)}
</div> </div>
<div className="flex flex-col items-center text-center gap-3 pt-4"> <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)}> <div className="relative">
{account.username === "bookmarks" ? (<Bookmark className="h-10 w-10 text-primary"/>) : (<Heart className="h-10 w-10 text-primary"/>)} <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">
</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)}/>)} {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="w-full min-w-0">
<div className="font-medium truncate">{account.name}</div> <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"> {!isPrivateAccount(account.username) && (<button type="button" onClick={() => openExternal(`https://x.com/${account.username}`)} className="text-sm text-muted-foreground hover:text-primary hover:underline">
@@ -965,13 +1060,13 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
{formatNumberWithComma(account.total_media)} media {formatNumberWithComma(account.total_media)} media
</div> </div>
</div> </div>
<div className="flex gap-1"> <div className="flex gap-1" onClick={(e) => e.stopPropagation()}>
{downloadingAccountId === account.id ? (<Button variant="outline" size="icon" className="h-8 w-8" onClick={handleStopDownload}> {downloadingAccountId === account.id ? (<Button variant="outline" size="icon" className="h-8 w-8" onClick={handleStopDownload}>
<StopCircle className="h-4 w-4 text-destructive"/> <StopCircle className="h-4 w-4 text-destructive"/>
</Button>) : (<Button variant="default" size="icon" className="h-8 w-8" onClick={() => handleDownload(account.id, account.username)} disabled={isDownloading}> </Button>) : (<Button variant="default" size="icon" className="h-8 w-8" onClick={() => handleDownload(account.id, account.username)} disabled={isDownloading}>
<Download className="h-4 w-4"/> <Download className="h-4 w-4"/>
</Button>)} </Button>)}
<Button variant="outline" size="icon" className="h-8 w-8" onClick={() => handleOpenFolder(account.username)} disabled={!folderExistence.get(account.id)}> <Button variant="outline" size="icon" className="h-8 w-8" onClick={() => handleOpenFolder(account)} disabled={!folderExistence.get(account.id)}>
<FolderOpen className="h-4 w-4"/> <FolderOpen className="h-4 w-4"/>
</Button> </Button>
<DropdownMenu> <DropdownMenu>
@@ -981,7 +1076,10 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
</Button> </Button>
</DropdownMenuTrigger> </DropdownMenuTrigger>
<DropdownMenuContent align="end"> <DropdownMenuContent align="end">
{!isPrivateAccount(account.username) && (<DropdownMenuItem onClick={() => handleEditGroup(account)}> {!isPrivateAccount(account.username) && (<DropdownMenuItem onSelect={(event) => {
event.preventDefault();
handleEditGroup(account);
}}>
<Pencil className="h-4 w-4 mr-2"/> <Pencil className="h-4 w-4 mr-2"/>
Edit Group Edit Group
</DropdownMenuItem>)} </DropdownMenuItem>)}
@@ -993,6 +1091,7 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
toast.success(`Exported @${account.username}`); toast.success(`Exported @${account.username}`);
} }
catch (error) { catch (error) {
console.error(`Failed to export @${account.username}:`, error);
toast.error("Failed to export"); toast.error("Failed to export");
} }
}}> }}>
@@ -1024,9 +1123,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"> {gridView === "small" && (<div className="grid grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-3">
{filteredAccounts {filteredAccounts
.slice(0, visibleCount) .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"}`}> .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)} className="absolute top-1.5 left-1.5 z-10"/> <Checkbox checked={selectedIds.has(account.id)} onCheckedChange={() => toggleSelect(account.id)} onClick={(e) => e.stopPropagation()} className="absolute top-1.5 left-1.5 z-10"/>
<div className="absolute top-1.5 right-1.5 z-10 flex gap-1"> <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")}> <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")}>
@@ -1041,9 +1140,14 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
</Badge>)} </Badge>)}
</div> </div>
<div className="flex flex-col items-center text-center gap-2 pt-4"> <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)}> <div className="relative">
{account.username === "bookmarks" ? (<Bookmark className="h-7 w-7 text-primary"/>) : (<Heart className="h-7 w-7 text-primary"/>)} <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">
</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)}/>)} {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="w-full min-w-0">
<div className="text-xs font-medium truncate">{account.name}</div> <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"> {!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">
@@ -1053,13 +1157,13 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
{formatNumberWithComma(account.total_media)} media {formatNumberWithComma(account.total_media)} media
</div> </div>
</div> </div>
<div className="flex gap-1"> <div className="flex gap-1" onClick={(e) => e.stopPropagation()}>
{downloadingAccountId === account.id ? (<Button variant="outline" size="icon" className="h-7 w-7" onClick={handleStopDownload}> {downloadingAccountId === account.id ? (<Button variant="outline" size="icon" className="h-7 w-7" onClick={handleStopDownload}>
<StopCircle className="h-3 w-3 text-destructive"/> <StopCircle className="h-3 w-3 text-destructive"/>
</Button>) : (<Button variant="default" size="icon" className="h-7 w-7" onClick={() => handleDownload(account.id, account.username)} disabled={isDownloading}> </Button>) : (<Button variant="default" size="icon" className="h-7 w-7" onClick={() => handleDownload(account.id, account.username)} disabled={isDownloading}>
<Download className="h-3 w-3"/> <Download className="h-3 w-3"/>
</Button>)} </Button>)}
<Button variant="outline" size="icon" className="h-7 w-7" onClick={() => handleOpenFolder(account.username)} disabled={!folderExistence.get(account.id)}> <Button variant="outline" size="icon" className="h-7 w-7" onClick={() => handleOpenFolder(account)} disabled={!folderExistence.get(account.id)}>
<FolderOpen className="h-3 w-3"/> <FolderOpen className="h-3 w-3"/>
</Button> </Button>
<DropdownMenu> <DropdownMenu>
@@ -1069,7 +1173,10 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
</Button> </Button>
</DropdownMenuTrigger> </DropdownMenuTrigger>
<DropdownMenuContent align="end"> <DropdownMenuContent align="end">
{!isPrivateAccount(account.username) && (<DropdownMenuItem onClick={() => handleEditGroup(account)}> {!isPrivateAccount(account.username) && (<DropdownMenuItem onSelect={(event) => {
event.preventDefault();
handleEditGroup(account);
}}>
<Pencil className="h-4 w-4 mr-2"/> <Pencil className="h-4 w-4 mr-2"/>
Edit Group Edit Group
</DropdownMenuItem>)} </DropdownMenuItem>)}
@@ -1081,6 +1188,7 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
toast.success(`Exported @${account.username}`); toast.success(`Exported @${account.username}`);
} }
catch (error) { catch (error) {
console.error(`Failed to export @${account.username}:`, error);
toast.error("Failed to export"); toast.error("Failed to export");
} }
}}> }}>
@@ -1112,14 +1220,16 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
{gridView === "list" && filteredAccounts {gridView === "list" && filteredAccounts
.slice(0, visibleCount) .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"}`}> .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"> <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)}/> <Checkbox checked={selectedIds.has(account.id)} onCheckedChange={() => toggleSelect(account.id)} onClick={(e) => e.stopPropagation()}/>
<span className="text-sm text-muted-foreground w-8 text-center shrink-0"> <div className="relative shrink-0">
{index + 1} <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">
</span> {index + 1}
{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)}> </span>
{account.username === "bookmarks" ? (<Bookmark className="h-6 w-6 text-primary"/>) : (<Heart className="h-6 w-6 text-primary"/>)} {isPrivateAccount(account.username) ? (<div className="w-12 h-12 rounded-full bg-primary/10 flex items-center justify-center">
</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)}/>)} {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-1 min-w-0">
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<span className="truncate">{account.name}</span> <span className="truncate">{account.name}</span>
@@ -1161,7 +1271,7 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
{account.last_fetched} {getRelativeTime(account.last_fetched)} {account.last_fetched} {getRelativeTime(account.last_fetched)}
</div> </div>
</div> </div>
<div className="flex items-center gap-2"> <div className="flex items-center gap-2" onClick={(e) => e.stopPropagation()}>
{downloadingAccountId === account.id ? (<Tooltip> {downloadingAccountId === account.id ? (<Tooltip>
<TooltipTrigger asChild> <TooltipTrigger asChild>
<Button variant="outline" size="icon" onClick={handleStopDownload}> <Button variant="outline" size="icon" onClick={handleStopDownload}>
@@ -1179,7 +1289,7 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
</Tooltip>)} </Tooltip>)}
<Tooltip> <Tooltip>
<TooltipTrigger asChild> <TooltipTrigger asChild>
<Button variant="outline" size="icon" onClick={() => handleOpenFolder(account.username)} disabled={!folderExistence.get(account.id)}> <Button variant="outline" size="icon" onClick={() => handleOpenFolder(account)} disabled={!folderExistence.get(account.id)}>
<FolderOpen className="h-4 w-4"/> <FolderOpen className="h-4 w-4"/>
</Button> </Button>
</TooltipTrigger> </TooltipTrigger>
@@ -1197,7 +1307,10 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
<TooltipContent>More Options</TooltipContent> <TooltipContent>More Options</TooltipContent>
</Tooltip> </Tooltip>
<DropdownMenuContent align="end"> <DropdownMenuContent align="end">
{!isPrivateAccount(account.username) && (<DropdownMenuItem onClick={() => handleEditGroup(account)}> {!isPrivateAccount(account.username) && (<DropdownMenuItem onSelect={(event) => {
event.preventDefault();
handleEditGroup(account);
}}>
<Pencil className="h-4 w-4 mr-2"/> <Pencil className="h-4 w-4 mr-2"/>
Edit Group Edit Group
</DropdownMenuItem>)} </DropdownMenuItem>)}
@@ -1209,6 +1322,7 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
toast.success(`Exported @${account.username} to ${outputDir}\\twitterxmediabatchdownloader_backups`); toast.success(`Exported @${account.username} to ${outputDir}\\twitterxmediabatchdownloader_backups`);
} }
catch (error) { catch (error) {
console.error(`Failed to export @${account.username}:`, error);
toast.error("Failed to export"); toast.error("Failed to export");
} }
}}> }}>
+1 -2
View File
@@ -18,14 +18,13 @@ function formatTime(date: Date): string {
}); });
} }
export function DebugLoggerPage() { export function DebugLoggerPage() {
const [logs, setLogs] = useState<LogEntry[]>([]); const [logs, setLogs] = useState<LogEntry[]>(() => logger.getLogs());
const [copied, setCopied] = useState(false); const [copied, setCopied] = useState(false);
const scrollRef = useRef<HTMLDivElement>(null); const scrollRef = useRef<HTMLDivElement>(null);
useEffect(() => { useEffect(() => {
const unsubscribe = logger.subscribe(() => { const unsubscribe = logger.subscribe(() => {
setLogs(logger.getLogs()); setLogs(logger.getLogs());
}); });
setLogs(logger.getLogs());
return () => { return () => {
unsubscribe(); unsubscribe();
}; };
@@ -4,29 +4,47 @@ import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from "@/components/ui/dialog"; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from "@/components/ui/dialog";
import { Spinner } from "@/components/ui/spinner"; import { Spinner } from "@/components/ui/spinner";
import { toastWithSound as toast } from "@/lib/toast-with-sound"; import { toastWithSound as toast } from "@/lib/toast-with-sound";
import { DownloadExtractor, IsExtractorInstalled } from "../../wailsjs/go/main/App"; import { compareVersionNumbers } from "@/lib/version";
import { Quit } from "../../wailsjs/runtime/runtime";
import { DownloadExtractor, GetExtractorVersionStatus } from "../../wailsjs/go/main/App";
interface DependencySetupDialogProps { interface DependencySetupDialogProps {
onInstalled?: () => void; onInstalled?: () => void;
} }
interface ExtractorVersionStatus {
installed: boolean;
installed_version?: string;
latest_version?: string;
}
export function DependencySetupDialog({ onInstalled }: DependencySetupDialogProps) { export function DependencySetupDialog({ onInstalled }: DependencySetupDialogProps) {
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
const [checking, setChecking] = useState(true); const [checking, setChecking] = useState(true);
const [downloading, setDownloading] = useState(false); const [downloading, setDownloading] = useState(false);
const [errorMessage, setErrorMessage] = useState<string | null>(null); const [errorMessage, setErrorMessage] = useState<string | null>(null);
const [updateRequired, setUpdateRequired] = useState(false);
const [installedVersion, setInstalledVersion] = useState<string | null>(null);
const [releaseVersion, setReleaseVersion] = useState<string | null>(null);
const [releaseStatusMessage, setReleaseStatusMessage] = useState("Checking latest GitHub release...");
useEffect(() => { useEffect(() => {
let cancelled = false; let cancelled = false;
const checkDependency = async () => { const checkDependency = async () => {
try { try {
const installed = await IsExtractorInstalled(); const status = await GetExtractorVersionStatus() as ExtractorVersionStatus;
const nextInstalledVersion = status.installed_version?.trim() || null;
const nextLatestVersion = status.latest_version?.trim() || null;
const nextUpdateRequired = !!(status.installed && nextLatestVersion && (!nextInstalledVersion || compareVersionNumbers(nextLatestVersion, nextInstalledVersion) > 0));
if (!cancelled) { if (!cancelled) {
setOpen(!installed); setUpdateRequired(nextUpdateRequired);
setInstalledVersion(nextInstalledVersion);
setReleaseVersion(nextLatestVersion);
setReleaseStatusMessage(nextLatestVersion ? `Latest GitHub release: ${nextLatestVersion}` : "Latest GitHub release unavailable.");
setOpen(!status.installed || nextUpdateRequired);
setErrorMessage(null); setErrorMessage(null);
} }
} }
catch { catch {
if (!cancelled) { if (!cancelled) {
setOpen(true); setOpen(true);
setErrorMessage("Couldn't verify the core dependency. You can install it now."); setErrorMessage("Couldn't verify Xtractor. Download it to continue.");
} }
} }
finally { finally {
@@ -35,7 +53,7 @@ export function DependencySetupDialog({ onInstalled }: DependencySetupDialogProp
} }
} }
}; };
checkDependency(); void checkDependency();
return () => { return () => {
cancelled = true; cancelled = true;
}; };
@@ -46,37 +64,47 @@ export function DependencySetupDialog({ onInstalled }: DependencySetupDialogProp
try { try {
await DownloadExtractor(); await DownloadExtractor();
setOpen(false); setOpen(false);
toast.success("Core dependency installed"); toast.success(updateRequired ? "Xtractor updated" : "Xtractor installed");
onInstalled?.(); onInstalled?.();
} }
catch (error) { catch (error) {
const message = error instanceof Error ? error.message : String(error); const message = error instanceof Error ? error.message : String(error);
setErrorMessage(message || "Failed to download dependency."); setErrorMessage(message || "Failed to download Xtractor.");
toast.error("Failed to download dependency"); toast.error("Failed to download Xtractor");
} }
finally { finally {
setDownloading(false); setDownloading(false);
} }
}; };
const handleExit = () => {
if (!downloading) {
void Quit();
}
};
if (checking && !open) { if (checking && !open) {
return null; return null;
} }
return (<Dialog open={open} onOpenChange={(nextOpen) => !downloading && setOpen(nextOpen)}> return (<Dialog open={open} onOpenChange={(nextOpen) => {
<DialogContent className="max-w-xl [&>button]:hidden" showCloseButton={false}> if (nextOpen) {
setOpen(true);
}
}}>
<DialogContent className="max-w-xl [&>button]:hidden" showCloseButton={false} onEscapeKeyDown={(event) => event.preventDefault()} onInteractOutside={(event) => event.preventDefault()}>
<DialogHeader> <DialogHeader>
<div className="mb-2 flex h-12 w-12 items-center justify-center rounded-2xl border bg-muted/50"> <div className="mb-2 flex h-12 w-12 items-center justify-center rounded-2xl border bg-muted/50">
<Package className="h-6 w-6"/> <Package className="h-6 w-6"/>
</div> </div>
<DialogTitle>Download Core Dependency</DialogTitle> <DialogTitle>{updateRequired ? "Update Xtractor" : "Download Xtractor"}</DialogTitle>
<DialogDescription> <DialogDescription>
This app now uses a prebuilt xtractor binary from GitHub releases. Download it once so fetching can work on this device. {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> </DialogDescription>
</DialogHeader> </DialogHeader>
<div className="space-y-3"> <div className="space-y-3">
<div className="rounded-lg border bg-muted/40 p-3 text-sm text-muted-foreground"> {updateRequired && releaseVersion && (<p className="text-sm text-amber-600 dark:text-amber-400">
The binary is stored in the app data folder and reused on the next launch. Optional tools like FFmpeg and ExifTool stay available in Settings. Installed: {installedVersion || "unknown"} - Latest: {releaseVersion}
</div> </p>)}
<p className="text-sm text-muted-foreground">{releaseVersion ? `Latest GitHub release: ${releaseVersion}` : releaseStatusMessage}</p>
{errorMessage && (<div className="flex items-start gap-2 rounded-lg border border-destructive/40 bg-destructive/10 p-3 text-sm text-destructive"> {errorMessage && (<div className="flex items-start gap-2 rounded-lg border border-destructive/40 bg-destructive/10 p-3 text-sm text-destructive">
<AlertCircle className="mt-0.5 h-4 w-4 shrink-0"/> <AlertCircle className="mt-0.5 h-4 w-4 shrink-0"/>
@@ -85,16 +113,16 @@ export function DependencySetupDialog({ onInstalled }: DependencySetupDialogProp
</div> </div>
<DialogFooter> <DialogFooter>
<Button variant="outline" onClick={() => setOpen(false)} disabled={downloading}> <Button variant="outline" onClick={handleExit} disabled={downloading}>
Later Exit App
</Button> </Button>
<Button onClick={handleDownload} disabled={downloading}> <Button onClick={handleDownload} disabled={downloading}>
{downloading ? (<> {downloading ? (<>
<Spinner /> <Spinner />
Downloading... {updateRequired ? "Updating Xtractor..." : "Downloading Xtractor..."}
</>) : (<> </>) : (<>
<Download className="h-4 w-4"/> <Download className="h-4 w-4"/>
Download Dependency {updateRequired ? "Update Xtractor" : "Download Xtractor"}
</>)} </>)}
</Button> </Button>
</DialogFooter> </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>);
}
+2 -2
View File
@@ -11,8 +11,8 @@ export function Header({ version, hasUpdate, releaseDate }: HeaderProps) {
return (<div className="relative"> return (<div className="relative">
<div className="text-center space-y-2"> <div className="text-center space-y-2">
<div className="flex items-center justify-center gap-3"> <div className="flex items-center justify-center gap-3">
<img src="/icon.svg" alt="Twitter/X Media Batch Downloader" className="w-12 h-12 cursor-pointer" onClick={() => window.location.reload()}/> <img src="/icon.svg" alt="Twitter/X Media Batch Downloader" className="w-12 h-12"/>
<h1 className="text-3xl font-bold cursor-pointer" onClick={() => window.location.reload()}> <h1 className="text-3xl font-bold">
Twitter/X Media Batch Downloader Twitter/X Media Batch Downloader
</h1> </h1>
<div className="relative"> <div className="relative">
+332 -376
View File
@@ -5,26 +5,17 @@ import { Badge } from "@/components/ui/badge";
import { Progress } from "@/components/ui/progress"; import { Progress } from "@/components/ui/progress";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select";
import { Tooltip, TooltipContent, TooltipTrigger, } from "@/components/ui/tooltip"; 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 { Spinner } from "@/components/ui/spinner";
import type { TimelineEntry, AccountInfo } from "@/types/api"; import type { TimelineEntry, AccountInfo } from "@/types/api";
import { logger } from "@/lib/logger"; import { logger } from "@/lib/logger";
import { toastWithSound as toast } from "@/lib/toast-with-sound"; import { toastWithSound as toast } from "@/lib/toast-with-sound";
import { getSettings } from "@/lib/settings"; 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 { openExternal } from "@/lib/utils";
import { DownloadMediaWithMetadata, OpenFolder, IsFFmpegInstalled, ConvertGIFs, StopDownload, CheckFolderExists, CheckGifsFolderHasMP4 } from "../../wailsjs/go/main/App"; import { DownloadMediaWithMetadata, DownloadProfileImage, OpenFolder, StopDownload, CheckFolderExists } from "../../wailsjs/go/main/App";
import { EventsOn, EventsOff } from "../../wailsjs/runtime/runtime";
import { main } from "../../wailsjs/go/models"; import { main } from "../../wailsjs/go/models";
interface DownloadProgress {
current: number;
total: number;
percent: number;
}
interface DownloadItemStatus {
tweet_id: number;
index: number;
status: "success" | "failed" | "skipped";
}
interface MediaListProps { interface MediaListProps {
accountInfo: AccountInfo; accountInfo: AccountInfo;
timeline: TimelineEntry[]; timeline: TimelineEntry[];
@@ -32,9 +23,13 @@ interface MediaListProps {
fetchedMediaType?: string; fetchedMediaType?: string;
newMediaCount?: number | null; newMediaCount?: number | null;
} }
const MEDIA_LIST_PAGE_SIZE = 30;
function getContentScrollElement(): HTMLElement | null {
return document.getElementById("app-content-scroll");
}
function getThumbnailUrl(url: string): string { function getThumbnailUrl(url: string): string {
if (url.includes("video.twimg.com/tweet_video/")) { if (url.includes("video.twimg.com/tweet_video/")) {
const match = url.match(/tweet_video\/([^\/]+)\.mp4/); const match = url.match(/tweet_video\/([^/]+)\.mp4/);
if (match && match[1]) { if (match && match[1]) {
const filename = match[1]; const filename = match[1];
return `https://pbs.twimg.com/tweet_video_thumb/${filename}?format=jpg&name=360x360`; return `https://pbs.twimg.com/tweet_video_thumb/${filename}?format=jpg&name=360x360`;
@@ -71,6 +66,12 @@ function getPreviewUrl(url: string): string {
} }
return url; return url;
} }
function getEntryThumbnail(item: TimelineEntry): string {
if (item.thumbnail) {
return item.thumbnail;
}
return getThumbnailUrl(item.url);
}
function getMediaIcon(type: string) { function getMediaIcon(type: string) {
switch (type) { switch (type) {
case "photo": case "photo":
@@ -88,10 +89,14 @@ function getMediaIcon(type: string) {
} }
function formatDate(dateStr: string): string { function formatDate(dateStr: string): string {
try { try {
if (dateStr.includes("T")) { const d = new Date(dateStr);
const [datePart, timePart] = dateStr.split("T"); if (!Number.isNaN(d.getTime())) {
const timeClean = timePart.split("+")[0].split("Z")[0]; const year = d.getFullYear();
return `${datePart} • ${timeClean}`; 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; return dateStr;
} }
@@ -161,32 +166,73 @@ function formatJoinDate(dateStr: string): string {
return dateStr; return dateStr;
} }
} }
function getAccountFolderName(accountInfo: AccountInfo): string {
if (accountInfo.nick === "My Bookmarks" || accountInfo.name === "bookmarks") {
return "My Bookmarks";
}
if (accountInfo.nick === "My Likes" || accountInfo.name === "likes") {
return "My Likes";
}
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) { export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType = "all", newMediaCount = null, }: MediaListProps) {
const [selectedItems, setSelectedItems] = useState<Set<number>>(new Set()); 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 [sortBy, setSortBy] = useState<string>("date-desc");
const [filterType, setFilterType] = useState<string>("all"); const [filterType, setFilterType] = useState<string>("all");
const [viewMode, setViewMode] = useState<"large" | "small" | "list">("list"); const [viewMode, setViewMode] = useState<"large" | "small" | "list">(() => {
const [isDownloading, setIsDownloading] = useState(false); const stored = localStorage.getItem("resultViewMode");
const [downloadProgress, setDownloadProgress] = useState<DownloadProgress | null>(null); return stored === "large" || stored === "small" || stored === "list" ? stored : "list";
});
useEffect(() => {
localStorage.setItem("resultViewMode", viewMode);
}, [viewMode]);
const [hasDownloaded, setHasDownloaded] = useState(false); const [hasDownloaded, setHasDownloaded] = useState(false);
const [isConverting, setIsConverting] = useState(false);
const [ffmpegInstalled, setFfmpegInstalled] = useState(false);
const [showScrollTop, setShowScrollTop] = useState(false); const [showScrollTop, setShowScrollTop] = useState(false);
const [folderExists, setFolderExists] = useState(false); const [folderExists, setFolderExists] = useState(cachedMediaFolderStatus?.folderExists ?? false);
const [gifsFolderHasMP4, setGifsFolderHasMP4] = useState(false);
const [previewIndex, setPreviewIndex] = useState<number | null>(null); const [previewIndex, setPreviewIndex] = useState<number | null>(null);
const [downloadedItems, setDownloadedItems] = useState<Set<string>>(new Set()); const [visibleCount, setVisibleCount] = useState<number>(MEDIA_LIST_PAGE_SIZE);
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>(10);
const loadMoreRef = useRef<HTMLDivElement>(null); const loadMoreRef = useRef<HTMLDivElement>(null);
useEffect(() => { useEffect(() => {
const scrollElement = getContentScrollElement();
if (!scrollElement) {
return;
}
const handleScroll = () => { const handleScroll = () => {
setShowScrollTop(window.scrollY > 300); setShowScrollTop(scrollElement.scrollTop > 300);
}; };
window.addEventListener("scroll", handleScroll); handleScroll();
return () => window.removeEventListener("scroll", handleScroll); scrollElement.addEventListener("scroll", handleScroll);
return () => scrollElement.removeEventListener("scroll", handleScroll);
}, []); }, []);
const filteredTimeline = useMemo(() => { const filteredTimeline = useMemo(() => {
let filtered = [...timeline]; let filtered = [...timeline];
@@ -221,55 +267,45 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
return filtered; return filtered;
}, [timeline, filterType, sortBy]); }, [timeline, filterType, sortBy]);
useEffect(() => { useEffect(() => {
setVisibleCount(10); setVisibleCount(MEDIA_LIST_PAGE_SIZE);
}, [filteredTimeline.length]); }, [filteredTimeline.length]);
useEffect(() => { useEffect(() => {
const checkFoldersAndFFmpeg = async () => { const checkFolders = async () => {
const settings = getSettings(); const settings = getSettings();
const basePath = settings.downloadPath; const basePath = settings.downloadPath;
const installed = await IsFFmpegInstalled();
setFfmpegInstalled(installed);
if (!basePath || !accountInfo.name) if (!basePath || !accountInfo.name)
return; return;
let folderName = accountInfo.name;
if (accountInfo.nick === "My Bookmarks" || accountInfo.name === "bookmarks") {
folderName = "My Bookmarks";
}
else if (accountInfo.nick === "My Likes" || accountInfo.name === "likes") {
folderName = "My Likes";
}
const exists = await CheckFolderExists(basePath, folderName); const exists = await CheckFolderExists(basePath, folderName);
setCachedMediaFolderStatus(basePath, folderName, {
folderExists: exists,
gifsFolderHasMP4: false,
});
setFolderExists(exists); setFolderExists(exists);
if (exists) {
const hasMP4 = await CheckGifsFolderHasMP4(basePath, folderName);
setGifsFolderHasMP4(hasMP4);
}
else {
setGifsFolderHasMP4(false);
}
}; };
checkFoldersAndFFmpeg(); checkFolders();
}, [accountInfo.name, accountInfo.nick, hasDownloaded]); }, [accountInfo.name, accountInfo.nick, folderName, hasDownloaded]);
useEffect(() => { useEffect(() => {
if (!loadMoreRef.current) const sentinel = loadMoreRef.current;
if (!sentinel || visibleCount >= filteredTimeline.length)
return; return;
const observer = new IntersectionObserver((entries) => { const observer = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting) { if (entries.some((entry) => entry.isIntersecting)) {
setVisibleCount((prev) => { setVisibleCount((prev) => {
const filteredLength = filteredTimeline.length; const filteredLength = filteredTimeline.length;
return Math.min(prev + 10, filteredLength); return Math.min(prev + MEDIA_LIST_PAGE_SIZE, filteredLength);
}); });
} }
}, { threshold: 0.1 }); }, {
observer.observe(loadMoreRef.current); rootMargin: "400px 0px",
threshold: 0,
});
observer.observe(sentinel);
return () => { return () => {
if (loadMoreRef.current) { observer.disconnect();
observer.unobserve(loadMoreRef.current);
}
}; };
}, [filteredTimeline.length]); }, [visibleCount, filteredTimeline.length]);
const scrollToTop = () => { const scrollToTop = () => {
window.scrollTo({ top: 0, behavior: "smooth" }); getContentScrollElement()?.scrollTo({ top: 0, behavior: "smooth" });
}; };
const openPreview = (index: number) => { const openPreview = (index: number) => {
setPreviewIndex(index); setPreviewIndex(index);
@@ -278,70 +314,15 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
setPreviewIndex(null); setPreviewIndex(null);
}; };
useEffect(() => { useEffect(() => {
if (previewIndex !== null) { if (previewIndex === null) {
document.body.style.overflow = "hidden"; return;
}
else {
document.body.style.overflow = "";
} }
const previousOverflow = document.body.style.overflow;
document.body.style.overflow = "hidden";
return () => { return () => {
document.body.style.overflow = ""; document.body.style.overflow = previousOverflow;
}; };
}, [previewIndex]); }, [previewIndex]);
useEffect(() => {
const unsubscribe = EventsOn("download-progress", (progress: DownloadProgress) => {
setDownloadProgress(progress);
});
return () => {
EventsOff("download-progress");
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 () => {
EventsOff("download-item-status");
unsubscribe();
};
}, []);
const goToPrevious = () => { const goToPrevious = () => {
if (previewIndex !== null && previewIndex > 0) { if (previewIndex !== null && previewIndex > 0) {
setPreviewIndex(previewIndex - 1); setPreviewIndex(previewIndex - 1);
@@ -385,16 +366,16 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
setSelectedItems(new Set()); setSelectedItems(new Set());
} }
else { else {
setSelectedItems(new Set(filteredTimeline.map((_, i) => i))); setSelectedItems(new Set(filteredTimeline.map((item) => getItemKey(item))));
} }
}; };
const toggleItem = (index: number) => { const toggleItem = (key: string) => {
const newSelected = new Set(selectedItems); const newSelected = new Set(selectedItems);
if (newSelected.has(index)) { if (newSelected.has(key)) {
newSelected.delete(index); newSelected.delete(key);
} }
else { else {
newSelected.add(index); newSelected.add(key);
} }
setSelectedItems(newSelected); setSelectedItems(newSelected);
}; };
@@ -409,40 +390,115 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
} }
return settings.downloadPath; return settings.downloadPath;
}; };
const createMediaItemRequest = (item: TimelineEntry) => new main.MediaItemRequest({
url: item.url,
date: item.date,
tweet_id: item.tweet_id,
type: item.type,
content: item.content || "",
original_filename: item.original_filename || "",
author_username: item.author_username || "",
account_name: item.author_name || accountInfo.nick || accountInfo.name,
});
const getItemStatusFlags = (itemKey: string) => {
const status = itemStatusByKey[itemKey];
return {
isItemDownloaded: status === "success",
isItemFailed: status === "failed",
isItemSkipped: status === "skipped",
isItemDownloading: downloadingItem === itemKey,
};
};
const handleDownloadItem = async (item: TimelineEntry, itemKey: string) => {
beginDownload({ current: 0, total: 1, percent: 0 }, { scope: "media", currentItemKey: itemKey, itemKeyByIndex: { 0: itemKey } });
try {
const settings = getSettings();
const request = new main.DownloadMediaWithMetadataRequest({
items: [createMediaItemRequest(item)],
output_dir: getOutputDir(),
username: accountInfo.name,
concurrent_downloads: settings.concurrentDownloads || 10,
skip_existing: settings.skipExistingFiles,
delete_incomplete_files: settings.deleteIncompleteFiles,
retry_attempts: settings.retryAttempts,
proxy: settings.proxy || "",
filename_template: settings.filenameTemplate || "",
folder_template: settings.folderTemplate || "",
auto_convert_gifs: settings.autoConvertGifs,
gif_quality: settings.gifQuality || "fast",
gif_resolution: settings.gifResolution || "original",
});
const response = await DownloadMediaWithMetadata(request);
if (response.cancelled) {
toast.info(response.message || "Download stopped");
}
else if (response.success) {
if (response.skipped > 0) {
setDownloadItemStatus(itemKey, "skipped");
toast.info("Already exists");
}
else if (response.downloaded > 0) {
setDownloadItemStatus(itemKey, "success");
toast.success("Downloaded");
}
setHasDownloaded(true);
}
else {
setDownloadItemStatus(itemKey, "failed");
toast.error(response.message || "Download failed");
}
}
catch (error) {
setDownloadItemStatus(itemKey, "failed");
const errorMsg = error instanceof Error ? error.message : String(error);
toast.error(`Download failed: ${errorMsg}`);
}
finally {
finishDownload();
}
};
const handleDownload = async () => { const handleDownload = async () => {
const itemsWithIndices = selectedItems.size > 0 const itemsWithIndices = selectedItems.size > 0
? Array.from(selectedItems).map((i) => ({ item: filteredTimeline[i], originalIndex: i })) ? filteredTimeline
.map((item, i) => ({ item, originalIndex: i }))
.filter((entry) => selectedItems.has(getItemKey(entry.item)))
: filteredTimeline.map((item, i) => ({ item, originalIndex: i })); : filteredTimeline.map((item, i) => ({ item, originalIndex: i }));
if (itemsWithIndices.length === 0) { if (itemsWithIndices.length === 0) {
toast.error("No media to download"); toast.error("No media to download");
return; return;
} }
const keyMap = new Map<number, string>(); const keyMap: Record<number, string> = {};
itemsWithIndices.forEach((entry, backendIndex) => { itemsWithIndices.forEach((entry, backendIndex) => {
keyMap.set(backendIndex, getItemKey(entry.item)); keyMap[backendIndex] = getItemKey(entry.item);
}); });
bulkDownloadKeyMapRef.current = keyMap; beginDownload({ current: 0, total: itemsWithIndices.length, percent: 0 }, { scope: "media", itemKeyByIndex: keyMap });
setIsDownloading(true);
setDownloadProgress({ current: 0, total: itemsWithIndices.length, percent: 0 });
logger.info(`Starting download of ${itemsWithIndices.length} files...`); logger.info(`Starting download of ${itemsWithIndices.length} files...`);
try { try {
const settings = getSettings(); const settings = getSettings();
const request = new main.DownloadMediaWithMetadataRequest({ const request = new main.DownloadMediaWithMetadataRequest({
items: itemsWithIndices.map(({ item }) => new main.MediaItemRequest({ items: itemsWithIndices.map(({ item }) => createMediaItemRequest(item)),
url: item.url,
date: item.date,
tweet_id: item.tweet_id,
type: item.type,
content: item.content || "",
original_filename: item.original_filename || "",
author_username: item.author_username || "",
})),
output_dir: getOutputDir(), output_dir: getOutputDir(),
username: accountInfo.name, username: accountInfo.name,
concurrent_downloads: settings.concurrentDownloads || 10,
skip_existing: settings.skipExistingFiles,
delete_incomplete_files: settings.deleteIncompleteFiles,
retry_attempts: settings.retryAttempts,
proxy: settings.proxy || "", 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); const response = await DownloadMediaWithMetadata(request);
if (response.success) { if (response.cancelled) {
logger.info(response.message || "Download stopped");
toast.info(response.message || "Download stopped");
if (response.downloaded > 0 || response.skipped > 0) {
setHasDownloaded(true);
}
}
else if (response.success) {
const parts: string[] = []; const parts: string[] = [];
if (response.downloaded > 0) { if (response.downloaded > 0) {
parts.push(`${response.downloaded} file${response.downloaded !== 1 ? 's' : ''} downloaded`); parts.push(`${response.downloaded} file${response.downloaded !== 1 ? 's' : ''} downloaded`);
@@ -463,8 +519,13 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
toast.success(message); toast.success(message);
} }
setHasDownloaded(true); setHasDownloaded(true);
const installed = await IsFFmpegInstalled(); if (settings.downloadPath) {
setFfmpegInstalled(installed); setCachedMediaFolderStatus(settings.downloadPath, folderName, {
folderExists: true,
gifsFolderHasMP4: false,
});
setFolderExists(true);
}
} }
else { else {
logger.error(response.message); logger.error(response.message);
@@ -477,15 +538,14 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
toast.error("Download failed"); toast.error("Download failed");
} }
finally { finally {
setIsDownloading(false); finishDownload();
setDownloadProgress(null);
bulkDownloadKeyMapRef.current = new Map();
} }
}; };
const handleStopDownload = async () => { const handleStopDownload = async () => {
try { try {
const stopped = await StopDownload(); const stopped = await StopDownload();
if (stopped) { if (stopped) {
finishDownload();
logger.info("Download stopped by user"); logger.info("Download stopped by user");
toast.info("Stopped"); toast.info("Stopped");
} }
@@ -494,6 +554,30 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
console.error("Failed to stop download:", error); 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 handleOpenFolder = async () => {
const settings = getSettings(); const settings = getSettings();
const isBookmarks = accountInfo.nick === "My Bookmarks"; const isBookmarks = accountInfo.nick === "My Bookmarks";
@@ -508,8 +592,8 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
} }
else { else {
folderPath = settings.downloadPath folderPath = settings.downloadPath
? `${settings.downloadPath}/${accountInfo.name}` ? `${settings.downloadPath}/${folderName}`
: accountInfo.name; : folderName;
} }
try { try {
await OpenFolder(folderPath); await OpenFolder(folderPath);
@@ -526,56 +610,6 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
const handleOpenTweet = (tweetId: string) => { const handleOpenTweet = (tweetId: string) => {
openExternal(`https://x.com/${accountInfo.name}/status/${tweetId}`); openExternal(`https://x.com/${accountInfo.name}/status/${tweetId}`);
}; };
const handleConvertGifs = async () => {
const settings = getSettings();
const isBookmarks = accountInfo.nick === "My Bookmarks";
const isLikes = accountInfo.nick === "My Likes";
let folderPath: string;
if (isBookmarks || isLikes) {
const separator = settings.downloadPath.includes("/") ? "/" : "\\";
const folderName = isBookmarks ? "My Bookmarks" : "My Likes";
folderPath = `${settings.downloadPath}${separator}${folderName}`;
}
else {
folderPath = `${settings.downloadPath}/${accountInfo.name}`;
}
setIsConverting(true);
logger.info("Converting GIFs...");
try {
const response = await ConvertGIFs({
folder_path: folderPath,
quality: settings.gifQuality || "fast",
resolution: settings.gifResolution || "high",
delete_original: false,
});
if (response.success) {
logger.success(`Converted ${response.converted} GIFs`);
toast.success(`${response.converted} GIFs converted`);
const settings = getSettings();
let folderName = accountInfo.name;
if (accountInfo.nick === "My Bookmarks" || accountInfo.name === "bookmarks") {
folderName = "My Bookmarks";
}
else if (accountInfo.nick === "My Likes" || accountInfo.name === "likes") {
folderName = "My Likes";
}
const hasMP4 = await CheckGifsFolderHasMP4(settings.downloadPath, folderName);
setGifsFolderHasMP4(hasMP4);
}
else {
logger.error(response.message);
toast.error("Convert failed");
}
}
catch (error) {
const errorMsg = error instanceof Error ? error.message : String(error);
logger.error(`Convert failed: ${errorMsg}`);
toast.error("Convert failed");
}
finally {
setIsConverting(false);
}
};
return (<div className="space-y-4"> return (<div className="space-y-4">
{accountInfo.name === "bookmarks" || accountInfo.name === "likes" ? (<div className="flex items-center gap-4 p-4 bg-muted/50 rounded-lg"> {accountInfo.name === "bookmarks" || accountInfo.name === "likes" ? (<div className="flex items-center gap-4 p-4 bg-muted/50 rounded-lg">
@@ -594,40 +628,69 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
</div> </div>
<div className="text-sm text-muted-foreground">items found</div> <div className="text-sm text-muted-foreground">items found</div>
</div> </div>
</div>) : (<div className="flex items-center gap-4 p-4 bg-muted/50 rounded-lg"> </div>) : (<div className="rounded-lg overflow-hidden bg-muted/50 border">
<img src={accountInfo.profile_image} alt={accountInfo.nick} className="w-16 h-16 rounded-full"/> {accountInfo.banner && (<div className="group/banner relative h-24 w-full bg-cover bg-center" style={{ backgroundImage: `url("${accountInfo.banner}")` }}>
<div className="flex-1"> <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">
<div className="flex items-center gap-2"> <Download className="h-4 w-4"/>
<h2 className="text-xl">{accountInfo.nick}</h2> </button>
<span className="text-muted-foreground">@{accountInfo.name}</span> </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>
<div className="flex items-center gap-4 text-sm text-muted-foreground mt-1">
<span className="flex items-center gap-1"> {accountInfo.bio && (<p className="text-sm mt-3 whitespace-pre-wrap wrap-break-word">{accountInfo.bio}</p>)}
<Users className="h-3.5 w-3.5"/>
{formatNumber(accountInfo.followers_count)} followers <div className="flex flex-wrap items-center gap-x-4 gap-y-1 text-sm text-muted-foreground mt-3">
</span> {accountInfo.location && (<span className="flex items-center gap-1">
<span className="flex items-center gap-1"> <MapPin className="h-3.5 w-3.5"/>
<UserPlus className="h-3.5 w-3.5"/> {accountInfo.location}
{formatNumber(accountInfo.friends_count)} following </span>)}
</span> {accountInfo.url && (<button type="button" onClick={() => openExternal(accountInfo.url!)} className="flex items-center gap-1 hover:underline">
<span className="flex items-center gap-1"> <Link2 className="h-3.5 w-3.5"/>
<MessageSquare className="h-3.5 w-3.5"/> {accountInfo.url.replace(/^https?:\/\//, "").replace(/\/+$/, "")}
{formatNumber(accountInfo.statuses_count)} posts </button>)}
</span>
{accountInfo.date && (<span className="flex items-center gap-1"> {accountInfo.date && (<span className="flex items-center gap-1">
<Calendar className="h-3.5 w-3.5"/> <Calendar className="h-3.5 w-3.5"/>
Joined {formatJoinDate(accountInfo.date)} Joined {formatJoinDate(accountInfo.date)}
</span>)} </span>)}
</div> </div>
</div>
<div className="text-right"> <div className="flex flex-wrap items-center gap-x-2 gap-y-1 text-sm mt-3">
<div className="flex items-center justify-end gap-2"> <span><strong className="text-foreground">{formatNumber(accountInfo.statuses_count)}</strong> <span className="text-muted-foreground">posts</span></span>
{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"> <span className="text-muted-foreground">·</span>
{formatNumberWithComma(newMediaCount)}+ <span><strong className="text-foreground">{formatNumber(accountInfo.friends_count)}</strong> <span className="text-muted-foreground">following</span></span>
</div>)} <span className="text-muted-foreground">·</span>
<div className="text-2xl font-bold text-primary">{formatNumberWithComma(totalUrls)}</div> <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>
<div className="text-sm text-muted-foreground">items found</div>
</div> </div>
</div>)} </div>)}
@@ -668,6 +731,12 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
GIFs ({formatNumberWithComma(mediaCounts.gif)}) GIFs ({formatNumberWithComma(mediaCounts.gif)})
</span> </span>
</SelectItem>)} </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> </SelectContent>
</Select>)} </Select>)}
@@ -689,21 +758,12 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
<FolderOpen className="h-4 w-4"/> <FolderOpen className="h-4 w-4"/>
Open Folder Open Folder
</Button> </Button>
<Button variant="outline" onClick={handleConvertGifs} disabled={isConverting || !gifsFolderHasMP4 || !ffmpegInstalled}>
{isConverting ? (<>
<Spinner />
Converting...
</>) : (<>
<Film className="h-4 w-4"/>
Convert GIFs
</>)}
</Button>
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
{isDownloading && (<Button variant="destructive" onClick={handleStopDownload}> {isDownloading && (<Button variant="destructive" onClick={handleStopDownload}>
<StopCircle className="h-4 w-4"/> <StopCircle className="h-4 w-4"/>
Stop Stop
</Button>)} </Button>)}
<Button onClick={handleDownload} disabled={isDownloading}> <Button onClick={handleDownload} disabled={anyDownloadActive}>
{isDownloading ? (<> {isDownloading ? (<>
<Spinner /> <Spinner />
Downloading... Downloading...
@@ -738,21 +798,20 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
{viewMode === "list" ? (<div className="space-y-2"> {viewMode === "list" ? (<div className="space-y-2">
{filteredTimeline.slice(0, visibleCount).map((item, index) => { {filteredTimeline.slice(0, visibleCount).map((item, index) => {
const isSelected = selectedItems.has(index);
const itemKey = getItemKey(item); const itemKey = getItemKey(item);
const isItemDownloaded = downloadedItems.has(itemKey); const isSelected = selectedItems.has(itemKey);
const isItemFailed = failedItems.has(itemKey); const { isItemDownloaded, isItemFailed, isItemSkipped, isItemDownloading } = getItemStatusFlags(itemKey);
const isItemSkipped = skippedItems.has(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"}`}>
const isItemDownloading = downloadingItem === itemKey; <Checkbox checked={isSelected} onCheckedChange={() => toggleItem(itemKey)} onClick={(e) => e.stopPropagation()}/>
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"}`}> <div className="relative shrink-0">
<Checkbox checked={isSelected} onCheckedChange={() => toggleItem(index)}/> <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">
<span className="text-sm text-muted-foreground w-8 text-center shrink-0"> {index + 1}
{index + 1} </span>
</span> <div className="w-16 h-16 rounded overflow-hidden bg-muted">
<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 !== "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">
{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)}
{getMediaIcon(item.type)} </div>)}
</div>)} </div>
</div> </div>
<div className="flex-1 min-w-0"> <div className="flex-1 min-w-0">
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
@@ -780,44 +839,7 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
<div className="flex items-center gap-2 shrink-0"> <div className="flex items-center gap-2 shrink-0">
<Tooltip> <Tooltip>
<TooltipTrigger asChild> <TooltipTrigger asChild>
<Button size="icon" variant="default" onClick={async () => { <Button size="icon" variant="default" onClick={() => void handleDownloadItem(item, itemKey)} disabled={anyDownloadActive}>
setDownloadingItem(itemKey);
currentDownloadingItemKeyRef.current = itemKey;
try {
const settings = getSettings();
const request = new main.DownloadMediaWithMetadataRequest({
items: [new main.MediaItemRequest({
url: item.url,
date: item.date,
tweet_id: item.tweet_id,
type: item.type,
content: item.content || "",
original_filename: item.original_filename || "",
author_username: item.author_username || "",
})],
output_dir: getOutputDir(),
username: accountInfo.name,
proxy: settings.proxy || "",
});
const response = await DownloadMediaWithMetadata(request);
if (response.success) {
setHasDownloaded(true);
}
else {
setFailedItems((prev) => new Set(prev).add(itemKey));
toast.error(response.message || "Download failed");
}
}
catch (error) {
setFailedItems((prev) => new Set(prev).add(itemKey));
const errorMsg = error instanceof Error ? error.message : String(error);
toast.error(`Download failed: ${errorMsg}`);
}
finally {
setDownloadingItem(null);
setTimeout(() => { currentDownloadingItemKeyRef.current = null; }, 1000);
}
}} disabled={downloadingItem !== null}>
{isItemDownloading ? (<Spinner />) : isItemSkipped ? (<FileCheck className="h-4 w-4"/>) : isItemDownloaded ? (<CheckCircle className="h-4 w-4"/>) : isItemFailed ? (<XCircle className="h-4 w-4"/>) : (<Download className="h-4 w-4"/>)} {isItemDownloading ? (<Spinner />) : isItemSkipped ? (<FileCheck className="h-4 w-4"/>) : isItemDownloaded ? (<CheckCircle className="h-4 w-4"/>) : isItemFailed ? (<XCircle className="h-4 w-4"/>) : (<Download className="h-4 w-4"/>)}
</Button> </Button>
</TooltipTrigger> </TooltipTrigger>
@@ -833,16 +855,16 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
})} })}
</div>) : (<div className={`grid gap-3 ${viewMode === "large" ? "grid-cols-4" : "grid-cols-6"}`}> </div>) : (<div className={`grid gap-3 ${viewMode === "large" ? "grid-cols-4" : "grid-cols-6"}`}>
{filteredTimeline.slice(0, visibleCount).map((item, index) => { {filteredTimeline.slice(0, visibleCount).map((item, index) => {
const isSelected = selectedItems.has(index);
const itemKey = getItemKey(item); const itemKey = getItemKey(item);
const isItemDownloaded = downloadedItems.has(itemKey); const isSelected = selectedItems.has(itemKey);
const isItemFailed = failedItems.has(itemKey); const { isItemDownloaded, isItemFailed, isItemSkipped, isItemDownloading } = getItemStatusFlags(itemKey);
const isItemSkipped = skippedItems.has(itemKey);
const isItemDownloading = downloadingItem === itemKey;
return (<div key={itemKey} className={`relative group rounded-lg overflow-hidden border-2 transition-all ${isSelected ? "border-primary" : "border-transparent hover:border-muted-foreground/30"}`}> return (<div key={itemKey} className={`relative group rounded-lg overflow-hidden border-2 transition-all ${isSelected ? "border-primary" : "border-transparent hover:border-muted-foreground/30"}`}>
<div className="aspect-square bg-muted relative cursor-pointer" onClick={() => openPreview(index)}> <div className="aspect-square bg-muted relative cursor-pointer" onClick={() => openPreview(index)}>
{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)} {getMediaIcon(item.type)}
</div>)} </div>)}
@@ -852,42 +874,8 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
<TooltipTrigger asChild> <TooltipTrigger asChild>
<Button size="icon" variant="default" className="h-8 w-8" onClick={async (e) => { <Button size="icon" variant="default" className="h-8 w-8" onClick={async (e) => {
e.stopPropagation(); e.stopPropagation();
setDownloadingItem(itemKey); await handleDownloadItem(item, itemKey);
currentDownloadingItemKeyRef.current = itemKey; }} disabled={anyDownloadActive}>
try {
const settings = getSettings();
const request = new main.DownloadMediaWithMetadataRequest({
items: [new main.MediaItemRequest({
url: item.url,
date: item.date,
tweet_id: item.tweet_id,
type: item.type,
content: item.content || "",
author_username: item.author_username || "",
})],
output_dir: getOutputDir(),
username: accountInfo.name,
proxy: settings.proxy || "",
});
const response = await DownloadMediaWithMetadata(request);
if (response.success) {
setHasDownloaded(true);
}
else {
setFailedItems((prev) => new Set(prev).add(itemKey));
toast.error(response.message || "Download failed");
}
}
catch (error) {
setFailedItems((prev) => new Set(prev).add(itemKey));
const errorMsg = error instanceof Error ? error.message : String(error);
toast.error(`Download failed: ${errorMsg}`);
}
finally {
setDownloadingItem(null);
setTimeout(() => { currentDownloadingItemKeyRef.current = null; }, 1000);
}
}} disabled={downloadingItem !== null}>
{isItemDownloading ? (<Spinner />) : isItemSkipped ? (<FileCheck className="h-4 w-4"/>) : isItemDownloaded ? (<CheckCircle className="h-4 w-4"/>) : isItemFailed ? (<XCircle className="h-4 w-4"/>) : (<Download className="h-4 w-4"/>)} {isItemDownloading ? (<Spinner />) : isItemSkipped ? (<FileCheck className="h-4 w-4"/>) : isItemDownloaded ? (<CheckCircle className="h-4 w-4"/>) : isItemFailed ? (<XCircle className="h-4 w-4"/>) : (<Download className="h-4 w-4"/>)}
</Button> </Button>
</TooltipTrigger> </TooltipTrigger>
@@ -905,7 +893,7 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
<div className="absolute top-2 left-2" onClick={(e) => e.stopPropagation()}> <div className="absolute top-2 left-2" onClick={(e) => e.stopPropagation()}>
<Checkbox checked={isSelected} onCheckedChange={() => toggleItem(index)} className="bg-background/80"/> <Checkbox checked={isSelected} onCheckedChange={() => toggleItem(itemKey)} className="bg-background/80"/>
</div> </div>
@@ -946,8 +934,13 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
</div>)} </div>)}
{visibleCount < filteredTimeline.length && (<div ref={loadMoreRef} className="h-20 flex items-center justify-center w-full"> {visibleCount < filteredTimeline.length && (<div ref={loadMoreRef} className="flex w-full flex-col items-center justify-center gap-3 py-6">
<Spinner /> <Spinner />
<Button variant="outline" size="sm" onClick={() => {
setVisibleCount((prev) => Math.min(prev + MEDIA_LIST_PAGE_SIZE, filteredTimeline.length));
}}>
Load More ({formatNumberWithComma(Math.max(filteredTimeline.length - visibleCount, 0))} remaining)
</Button>
</div>)} </div>)}
@@ -1011,47 +1004,10 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
{(() => { {(() => {
const item = filteredTimeline[previewIndex]; const item = filteredTimeline[previewIndex];
const itemKey = getItemKey(item); const itemKey = getItemKey(item);
const isItemDownloaded = downloadedItems.has(itemKey); const { isItemDownloaded, isItemFailed, isItemSkipped, isItemDownloading } = getItemStatusFlags(itemKey);
const isItemFailed = failedItems.has(itemKey);
const isItemSkipped = skippedItems.has(itemKey);
const isItemDownloading = downloadingItem === itemKey;
return (<Button variant="default" size="sm" className="h-9" onClick={async () => { return (<Button variant="default" size="sm" className="h-9" onClick={async () => {
setDownloadingItem(itemKey); await handleDownloadItem(item, itemKey);
currentDownloadingItemKeyRef.current = itemKey; }} disabled={anyDownloadActive}>
try {
const settings = getSettings();
const request = new main.DownloadMediaWithMetadataRequest({
items: [new main.MediaItemRequest({
url: item.url,
date: item.date,
tweet_id: item.tweet_id,
type: item.type,
content: item.content || "",
original_filename: item.original_filename || "",
author_username: item.author_username || "",
})],
output_dir: getOutputDir(),
username: accountInfo.name,
proxy: settings.proxy || "",
});
const response = await DownloadMediaWithMetadata(request);
if (response.success) {
setHasDownloaded(true);
}
else {
setFailedItems((prev) => new Set(prev).add(itemKey));
toast.error("Download failed");
}
}
catch {
setFailedItems((prev) => new Set(prev).add(itemKey));
toast.error("Download failed");
}
finally {
setDownloadingItem(null);
setTimeout(() => { currentDownloadingItemKeyRef.current = null; }, 1000);
}
}} disabled={downloadingItem !== null}>
{isItemDownloading ? (<Spinner className="mr-1"/>) : isItemSkipped ? (<FileCheck className="h-4 w-4 mr-1"/>) : isItemDownloaded ? (<CheckCircle className="h-4 w-4 mr-1"/>) : isItemFailed ? (<XCircle className="h-4 w-4 mr-1"/>) : (<Download className="h-4 w-4 mr-1"/>)} {isItemDownloading ? (<Spinner className="mr-1"/>) : isItemSkipped ? (<FileCheck className="h-4 w-4 mr-1"/>) : isItemDownloaded ? (<CheckCircle className="h-4 w-4 mr-1"/>) : isItemFailed ? (<XCircle className="h-4 w-4 mr-1"/>) : (<Download className="h-4 w-4 mr-1"/>)}
{isItemDownloading ? "Downloading..." : isItemSkipped ? "Already exists" : isItemDownloaded ? "Downloaded" : isItemFailed ? "Failed" : "Download"} {isItemDownloading ? "Downloading..." : isItemSkipped ? "Already exists" : isItemDownloaded ? "Downloaded" : isItemFailed ? "Failed" : "Download"}
</Button>); </Button>);
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+63 -15
View File
@@ -1,18 +1,33 @@
import { useState } from "react";
import { HomeIcon } from "@/components/ui/home"; import { HomeIcon } from "@/components/ui/home";
import { SettingsIcon } from "@/components/ui/settings"; import { SettingsIcon } from "@/components/ui/settings";
import { ArchiveIcon } from "@/components/ui/archive"; import { ArchiveIcon } from "@/components/ui/archive";
import { TerminalIcon } from "@/components/ui/terminal"; import { TerminalIcon } from "@/components/ui/terminal";
import { GithubIcon } from "@/components/ui/github"; import { BugReportIcon } from "@/components/ui/bug-report-icon";
import { CoffeeIcon } from "@/components/ui/coffee"; import { CoffeeIcon } from "@/components/ui/coffee";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Checkbox } from "@/components/ui/checkbox";
import { Tooltip, TooltipContent, TooltipTrigger, } from "@/components/ui/tooltip"; import { Tooltip, TooltipContent, TooltipTrigger, } from "@/components/ui/tooltip";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { openExternal } from "@/lib/utils"; import { openExternal } from "@/lib/utils";
export type PageType = "main" | "settings" | "debug" | "database"; export type PageType = "main" | "settings" | "debug" | "database" | "support";
interface SidebarProps { interface SidebarProps {
currentPage: PageType; currentPage: PageType;
onPageChange: (page: PageType) => void; onPageChange: (page: PageType) => void;
} }
export function Sidebar({ currentPage, onPageChange }: SidebarProps) { export function Sidebar({ currentPage, onPageChange }: SidebarProps) {
const [isIssuesDialogOpen, setIsIssuesDialogOpen] = useState(false);
const [hasIssueAgreement, setHasIssueAgreement] = useState(false);
const handleIssuesDialogChange = (open: boolean) => {
setIsIssuesDialogOpen(open);
if (!open) {
setHasIssueAgreement(false);
}
};
const handleOpenIssues = () => {
openExternal("https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/issues");
handleIssuesDialogChange(false);
};
return (<div className="fixed left-0 top-0 h-full w-14 bg-card border-r border-border flex flex-col items-center py-14 z-30"> return (<div className="fixed left-0 top-0 h-full w-14 bg-card border-r border-border flex flex-col items-center py-14 z-30">
<div className="flex flex-col gap-2 flex-1"> <div className="flex flex-col gap-2 flex-1">
@@ -55,7 +70,7 @@ export function Sidebar({ currentPage, onPageChange }: SidebarProps) {
<Tooltip delayDuration={0}> <Tooltip delayDuration={0}>
<TooltipTrigger asChild> <TooltipTrigger asChild>
<Button variant={currentPage === "debug" ? "secondary" : "ghost"} size="icon" className="h-10 w-10" onClick={() => onPageChange("debug")}> <Button variant={currentPage === "debug" ? "secondary" : "ghost"} size="icon" className="h-10 w-10" onClick={() => onPageChange("debug")}>
<TerminalIcon size={20}/> <TerminalIcon size={20} loop={true}/>
</Button> </Button>
</TooltipTrigger> </TooltipTrigger>
<TooltipContent side="right"> <TooltipContent side="right">
@@ -66,20 +81,53 @@ export function Sidebar({ currentPage, onPageChange }: SidebarProps) {
<div className="mt-auto flex flex-col gap-2"> <div className="mt-auto flex flex-col gap-2">
<Dialog open={isIssuesDialogOpen} onOpenChange={handleIssuesDialogChange}>
<Tooltip delayDuration={0}>
<TooltipTrigger asChild>
<Button variant="ghost" size="icon" className="h-10 w-10 hover:bg-primary/10 hover:text-primary" onClick={() => setIsIssuesDialogOpen(true)}>
<BugReportIcon size={20} loop={true}/>
</Button>
</TooltipTrigger>
<TooltipContent side="right">
<p>Report Bugs or Request Features</p>
</TooltipContent>
</Tooltip>
<DialogContent className="max-w-xl">
<DialogHeader>
<DialogTitle>Before Opening GitHub Issues</DialogTitle>
<DialogDescription />
</DialogHeader>
<div className="space-y-4 text-sm">
<div className="rounded-lg border border-amber-500/40 bg-amber-500/10 p-4">
<p className="font-semibold text-amber-900 dark:text-amber-200">Important</p>
<p className="mt-1 text-amber-950/90 dark:text-amber-100/90">
Search existing issues first and use the issue template when opening a new bug report or feature request.
</p>
</div>
<label className="flex cursor-pointer items-center gap-3 rounded-lg border p-4">
<Checkbox className="shrink-0" checked={hasIssueAgreement} onCheckedChange={(checked) => setHasIssueAgreement(checked === true)}/>
<span className="leading-5 text-foreground/90">
I understand that I should use the issue template and avoid duplicate issues.
</span>
</label>
</div>
<DialogFooter className="sm:justify-between gap-2">
<Button variant="outline" onClick={() => handleIssuesDialogChange(false)}>
Cancel
</Button>
<Button disabled={!hasIssueAgreement} onClick={handleOpenIssues}>
Open Issues
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
<Tooltip delayDuration={0}> <Tooltip delayDuration={0}>
<TooltipTrigger asChild> <TooltipTrigger asChild>
<Button variant="ghost" size="icon" className="h-10 w-10" onClick={() => openExternal("https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/issues")}> <Button variant={currentPage === "support" ? "secondary" : "ghost"} size="icon" className="h-10 w-10" onClick={() => onPageChange("support")}>
<GithubIcon size={20}/> <CoffeeIcon size={20} loop={true}/>
</Button>
</TooltipTrigger>
<TooltipContent side="right">
<p>Report Bug</p>
</TooltipContent>
</Tooltip>
<Tooltip delayDuration={0}>
<TooltipTrigger asChild>
<Button variant="ghost" size="icon" className="h-10 w-10" onClick={() => openExternal("https://ko-fi.com/afkarxyz")}>
<CoffeeIcon size={20}/>
</Button> </Button>
</TooltipTrigger> </TooltipTrigger>
<TooltipContent side="right"> <TooltipContent side="right">
+121
View File
@@ -0,0 +1,121 @@
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 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 [selectedCoin, setSelectedCoin] = useState<CryptoCoin>("usdt");
const [selectedNetwork, setSelectedNetwork] = useState<CryptoNetwork>("tron");
const [copiedAddress, setCopiedAddress] = useState(false);
const networkOptions = selectedCoin === "usdt" ? USDT_NETWORKS : EVM_NETWORKS;
const activeNetwork = networkOptions.find((network) => network.value === selectedNetwork) || EVM_NETWORKS[0];
const isTron = selectedNetwork === "tron";
const cryptoAddress = isTron ? TRON_ADDRESS : EVM_ADDRESS;
const cryptoQr = isTron ? UsdtTronQr : selectedCoin === "usdt" ? UsdtEvmQr : UsdcEvmQr;
const handleCoinChange = (coin: CryptoCoin) => {
setSelectedCoin(coin);
setCopiedAddress(false);
const nextNetworks = coin === "usdt" ? USDT_NETWORKS : EVM_NETWORKS;
if (!nextNetworks.some((network) => network.value === selectedNetwork)) {
setSelectedNetwork("ethereum");
}
};
return (<div className="flex min-h-[70vh] items-center justify-center p-4">
<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 min-w-0 flex-1 basis-0 flex-col items-center justify-between space-y-6 border-b p-6 md:border-r md:border-b-0">
<div className="flex flex-col items-center space-y-4">
<div className="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-9 w-4/5 gap-2 bg-[#72a4f2] text-sm font-semibold text-white hover:bg-[#5f8cd6]" onClick={() => openExternal("https://ko-fi.com/afkarxyz")}>
<img src={KofiSvg} className="h-6 w-6 shrink-0" alt="" aria-hidden="true"/>
Support me on Ko-fi
</Button>
</div>
<div className="flex min-w-0 flex-1 basis-0 flex-col items-center justify-between space-y-4 p-6">
<div className="flex w-full flex-col items-center space-y-3">
<div className="flex h-32 items-center justify-center">
<div className="rounded-xl border bg-white p-2 shadow-sm">
<img src={cryptoQr} className="h-24 w-24 object-contain" alt={`${selectedCoin.toUpperCase()} ${activeNetwork.label} QR code`}/>
</div>
</div>
<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.
</p>
</div>
<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);
}}>
<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>);
}
+28 -8
View File
@@ -1,5 +1,12 @@
import { X, Minus, Maximize } from "lucide-react"; import { X, Minus, Maximize, Info, Puzzle, FileCode2, Globe } from "lucide-react";
import { WindowMinimise, WindowToggleMaximise, Quit } from "../../wailsjs/runtime/runtime"; import { WindowMinimise, WindowToggleMaximise, Quit } from "../../wailsjs/runtime/runtime";
import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem } from "@/components/ui/dropdown-menu";
import { openExternal } from "@/lib/utils";
const INFO_LINKS = [
{ label: "Chrome Extension", icon: Puzzle, url: "https://chromewebstore.google.com/detail/cboceolmgkoobpfjiojkigmihijfgmdo" },
{ label: "Userscript", icon: FileCode2, url: "https://greasyfork.org/en/scripts/523157" },
{ label: "Website", icon: Globe, url: "https://twitterdl.app" },
];
export function TitleBar() { export function TitleBar() {
const handleMinimize = () => { const handleMinimize = () => {
WindowMinimise(); WindowMinimise();
@@ -11,18 +18,31 @@ export function TitleBar() {
Quit(); Quit();
}; };
return (<> 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-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"> <div className="fixed top-1.5 right-2 z-50 flex h-7 gap-0.5" style={{ "--wails-draggable": "no-drag" } as React.CSSProperties}>
<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"> <DropdownMenu>
<DropdownMenuTrigger asChild>
<button className="w-8 h-7 flex items-center justify-center hover:bg-muted transition-colors rounded" aria-label="Info">
<Info className="w-3.5 h-3.5"/>
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
{INFO_LINKS.map(({ label, icon: Icon, url }) => (<DropdownMenuItem key={label} onClick={() => openExternal(url)} className="gap-2 cursor-pointer">
<Icon className="w-4 h-4 text-muted-foreground"/>
{label}
</DropdownMenuItem>))}
</DropdownMenuContent>
</DropdownMenu>
<button onClick={handleMinimize} className="w-8 h-7 flex items-center justify-center hover:bg-muted transition-colors rounded" aria-label="Minimize">
<Minus className="w-3.5 h-3.5"/> <Minus className="w-3.5 h-3.5"/>
</button> </button>
<button onClick={handleMaximize} className="w-8 h-7 flex items-center justify-center hover:bg-muted transition-colors rounded" style={{ "--wails-draggable": "no-drag" } as React.CSSProperties} aria-label="Maximize"> <button onClick={handleMaximize} className="w-8 h-7 flex items-center justify-center hover:bg-muted transition-colors rounded" aria-label="Maximize">
<Maximize className="w-3.5 h-3.5"/> <Maximize className="w-3.5 h-3.5"/>
</button> </button>
<button onClick={handleClose} className="w-8 h-7 flex items-center justify-center hover:bg-destructive hover:text-white transition-colors rounded" style={{ "--wails-draggable": "no-drag" } as React.CSSProperties} aria-label="Close"> <button onClick={handleClose} className="w-8 h-7 flex items-center justify-center hover:bg-destructive hover:text-white transition-colors rounded" aria-label="Close">
<X className="w-3.5 h-3.5"/> <X className="w-3.5 h-3.5"/>
</button> </button>
</div> </div>
@@ -0,0 +1,116 @@
"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,
},
visible: {
opacity: 1,
transition: {
duration: 0.2,
ease: [0, 0, 0.2, 1],
},
},
exit: {
opacity: 0,
transition: {
duration: 0.18,
ease: [0.4, 0, 1, 1],
},
},
};
const DRAW_VARIANTS: Variants = {
hidden: {
pathLength: 0,
opacity: 0,
},
visible: {
pathLength: 1,
opacity: 1,
},
exit: {
pathLength: 1,
opacity: 0,
},
};
function createDrawTransition(delay = 0, duration = 0.36): Transition {
return {
duration,
delay,
ease: [0.4, 0, 0.2, 1],
opacity: { delay },
};
}
function BugPaths() {
return (<>
<motion.path d="m8 2 1.88 1.88" transition={createDrawTransition(0)} variants={DRAW_VARIANTS}/>
<motion.path d="M14.12 3.88 16 2" transition={createDrawTransition(0.04)} variants={DRAW_VARIANTS}/>
<motion.path d="M9 7.13V6a3 3 0 1 1 6 0v1.13" transition={createDrawTransition(0.08)} variants={DRAW_VARIANTS}/>
<motion.path d="M6.53 9A4 4 0 0 1 3 5" transition={createDrawTransition(0.14)} variants={DRAW_VARIANTS}/>
<motion.path d="M17.47 9A4 4 0 0 0 21 5" transition={createDrawTransition(0.18)} variants={DRAW_VARIANTS}/>
<motion.path d="M12 20v-9" transition={createDrawTransition(0.24)} variants={DRAW_VARIANTS}/>
<motion.path d="M14 7a4 4 0 0 1 4 4v3a6 6 0 0 1-12 0v-3a4 4 0 0 1 4-4z" transition={createDrawTransition(0.3, 0.42)} variants={DRAW_VARIANTS}/>
<motion.path d="M22 13h-4" transition={createDrawTransition(0.42)} variants={DRAW_VARIANTS}/>
<motion.path d="M6 13H2" transition={createDrawTransition(0.46)} variants={DRAW_VARIANTS}/>
<motion.path d="M21 21a4 4 0 0 0-3.81-4" transition={createDrawTransition(0.52)} variants={DRAW_VARIANTS}/>
<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}/>
<motion.path d="M9 18h6" transition={createDrawTransition(0.16)} variants={DRAW_VARIANTS}/>
<motion.path d="M10 22h4" transition={createDrawTransition(0.24)} variants={DRAW_VARIANTS}/>
</>);
}
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"/>
<path d="M14.12 3.88 16 2"/>
<path d="M9 7.13V6a3 3 0 1 1 6 0v1.13"/>
<path d="M6.53 9A4 4 0 0 1 3 5"/>
<path d="M17.47 9A4 4 0 0 0 21 5"/>
<path d="M12 20v-9"/>
<path d="M14 7a4 4 0 0 1 4 4v3a6 6 0 0 1-12 0v-3a4 4 0 0 1 4-4z"/>
<path d="M22 13h-4"/>
<path d="M6 13H2"/>
<path d="M21 21a4 4 0 0 0-3.81-4"/>
<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}/>
</AnimatePresence>) : (<StaticBugIcon />)}
</svg>
</div>);
}
export { BugReportIcon };
+5 -4
View File
@@ -10,6 +10,7 @@ export interface CoffeeIconHandle {
} }
interface CoffeeIconProps extends HTMLAttributes<HTMLDivElement> { interface CoffeeIconProps extends HTMLAttributes<HTMLDivElement> {
size?: number; size?: number;
loop?: boolean;
} }
const PATH_VARIANTS: Variants = { const PATH_VARIANTS: Variants = {
normal: { normal: {
@@ -27,7 +28,7 @@ const PATH_VARIANTS: Variants = {
}, },
}), }),
}; };
const CoffeeIcon = forwardRef<CoffeeIconHandle, CoffeeIconProps>(({ onMouseEnter, onMouseLeave, className, size = 28, ...props }, ref) => { const CoffeeIcon = forwardRef<CoffeeIconHandle, CoffeeIconProps>(({ onMouseEnter, onMouseLeave, className, size = 28, loop = false, ...props }, ref) => {
const controls = useAnimation(); const controls = useAnimation();
const isControlledRef = useRef(false); const isControlledRef = useRef(false);
useImperativeHandle(ref, () => { useImperativeHandle(ref, () => {
@@ -55,9 +56,9 @@ const CoffeeIcon = forwardRef<CoffeeIconHandle, CoffeeIconProps>(({ onMouseEnter
}, [controls, onMouseLeave]); }, [controls, onMouseLeave]);
return (<div className={cn(className)} onMouseEnter={handleMouseEnter} onMouseLeave={handleMouseLeave} {...props}> return (<div className={cn(className)} onMouseEnter={handleMouseEnter} onMouseLeave={handleMouseLeave} {...props}>
<svg xmlns="http://www.w3.org/2000/svg" width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ overflow: 'visible' }}> <svg xmlns="http://www.w3.org/2000/svg" width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ overflow: 'visible' }}>
<motion.path d="M10 2v2" animate={controls} variants={PATH_VARIANTS} custom={0.2}/> <motion.path d="M10 2v2" animate={loop ? 'animate' : controls} variants={PATH_VARIANTS} custom={0.2}/>
<motion.path d="M14 2v2" animate={controls} variants={PATH_VARIANTS} custom={0.4}/> <motion.path d="M14 2v2" animate={loop ? 'animate' : controls} variants={PATH_VARIANTS} custom={0.4}/>
<motion.path d="M6 2v2" animate={controls} variants={PATH_VARIANTS} custom={0}/> <motion.path d="M6 2v2" animate={loop ? 'animate' : controls} variants={PATH_VARIANTS} custom={0}/>
<path d="M16 8a1 1 0 0 1 1 1v8a4 4 0 0 1-4 4H7a4 4 0 0 1-4-4V9a1 1 0 0 1 1-1h14a4 4 0 1 1 0 8h-1"/> <path d="M16 8a1 1 0 0 1 1 1v8a4 4 0 0 1-4 4H7a4 4 0 0 1-4-4V9a1 1 0 0 1 1-1h14a4 4 0 1 1 0 8h-1"/>
</svg> </svg>
</div>); </div>);
@@ -9,6 +9,13 @@ const InputWithContext = React.forwardRef<HTMLInputElement, InputWithContextProp
const inputRef = React.useRef<HTMLInputElement>(null); const inputRef = React.useRef<HTMLInputElement>(null);
const [hasSelection, setHasSelection] = React.useState(false); const [hasSelection, setHasSelection] = React.useState(false);
const [canPaste, setCanPaste] = React.useState(false); const [canPaste, setCanPaste] = React.useState(false);
const [uncontrolledHasValue, setUncontrolledHasValue] = React.useState(() => {
const defaultValue = props.defaultValue;
return defaultValue !== undefined && defaultValue !== null && String(defaultValue).length > 0;
});
const hasValue = props.value !== undefined && props.value !== null
? String(props.value).length > 0
: uncontrolledHasValue;
React.useImperativeHandle(ref, () => inputRef.current as HTMLInputElement); React.useImperativeHandle(ref, () => inputRef.current as HTMLInputElement);
const updateSelectionState = () => { const updateSelectionState = () => {
const input = inputRef.current; const input = inputRef.current;
@@ -50,6 +57,9 @@ const InputWithContext = React.forwardRef<HTMLInputElement, InputWithContextProp
if (onValueChange) { if (onValueChange) {
onValueChange(newValue); onValueChange(newValue);
} }
if (props.value === undefined) {
setUncontrolledHasValue(newValue.length > 0);
}
input.focus(); input.focus();
} }
catch (err) { catch (err) {
@@ -96,6 +106,9 @@ const InputWithContext = React.forwardRef<HTMLInputElement, InputWithContextProp
if (onValueChange) { if (onValueChange) {
onValueChange(newValue); onValueChange(newValue);
} }
if (props.value === undefined) {
setUncontrolledHasValue(newValue.length > 0);
}
input.focus(); input.focus();
await checkClipboard(); await checkClipboard();
} }
@@ -118,6 +131,9 @@ const InputWithContext = React.forwardRef<HTMLInputElement, InputWithContextProp
if (onValueChange) { if (onValueChange) {
onValueChange(e.target.value); onValueChange(e.target.value);
} }
if (props.value === undefined) {
setUncontrolledHasValue(e.target.value.length > 0);
}
}; };
return (<ContextMenu onOpenChange={(open) => { return (<ContextMenu onOpenChange={(open) => {
if (open) { if (open) {
@@ -144,7 +160,7 @@ const InputWithContext = React.forwardRef<HTMLInputElement, InputWithContextProp
<span className="ml-auto text-xs text-muted-foreground">Ctrl+V</span> <span className="ml-auto text-xs text-muted-foreground">Ctrl+V</span>
</ContextMenuItem> </ContextMenuItem>
<ContextMenuSeparator /> <ContextMenuSeparator />
<ContextMenuItem onSelect={handleSelectAll} disabled={!inputRef.current?.value || props.disabled}> <ContextMenuItem onSelect={handleSelectAll} disabled={!hasValue || props.disabled}>
<Type className="mr-2 h-4 w-4"/> <Type className="mr-2 h-4 w-4"/>
Select All Select All
<span className="ml-auto text-xs text-muted-foreground">Ctrl+A</span> <span className="ml-auto text-xs text-muted-foreground">Ctrl+A</span>
+3 -2
View File
@@ -10,6 +10,7 @@ export interface TerminalIconHandle {
} }
interface TerminalIconProps extends HTMLAttributes<HTMLDivElement> { interface TerminalIconProps extends HTMLAttributes<HTMLDivElement> {
size?: number; size?: number;
loop?: boolean;
} }
const LINE_VARIANTS: Variants = { const LINE_VARIANTS: Variants = {
normal: { opacity: 1 }, normal: { opacity: 1 },
@@ -22,7 +23,7 @@ const LINE_VARIANTS: Variants = {
}, },
}, },
}; };
const TerminalIcon = forwardRef<TerminalIconHandle, TerminalIconProps>(({ onMouseEnter, onMouseLeave, className, size = 28, ...props }, ref) => { const TerminalIcon = forwardRef<TerminalIconHandle, TerminalIconProps>(({ onMouseEnter, onMouseLeave, className, size = 28, loop = false, ...props }, ref) => {
const controls = useAnimation(); const controls = useAnimation();
const isControlledRef = useRef(false); const isControlledRef = useRef(false);
useImperativeHandle(ref, () => { useImperativeHandle(ref, () => {
@@ -51,7 +52,7 @@ const TerminalIcon = forwardRef<TerminalIconHandle, TerminalIconProps>(({ onMous
return (<div className={cn(className)} onMouseEnter={handleMouseEnter} onMouseLeave={handleMouseLeave} {...props}> return (<div className={cn(className)} onMouseEnter={handleMouseEnter} onMouseLeave={handleMouseLeave} {...props}>
<svg xmlns="http://www.w3.org/2000/svg" width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"> <svg xmlns="http://www.w3.org/2000/svg" width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<polyline points="4 17 10 11 4 5"/> <polyline points="4 17 10 11 4 5"/>
<motion.line x1="12" x2="20" y1="19" y2="19" variants={LINE_VARIANTS} animate={controls} initial="normal"/> <motion.line x1="12" x2="20" y1="19" y2="19" variants={LINE_VARIANTS} animate={loop ? 'animate' : controls} initial="normal"/>
</svg> </svg>
</div>); </div>);
}); });
+39
View File
@@ -72,6 +72,13 @@
} }
@layer base { @layer base {
html,
body,
#root {
height: 100%;
overflow: hidden;
}
* { * {
@apply border-border outline-ring/50; @apply border-border outline-ring/50;
} }
@@ -234,6 +241,38 @@
scrollbar-color: var(--primary) var(--secondary); scrollbar-color: var(--primary) var(--secondary);
} }
input::-ms-reveal,
input::-ms-clear {
display: none;
}
input[type="number"],
input[type="date"],
input[type="datetime-local"],
input[type="time"],
input[type="month"],
input[type="week"] {
color-scheme: light;
}
.dark input[type="number"],
.dark input[type="date"],
.dark input[type="datetime-local"],
.dark input[type="time"],
.dark input[type="month"],
.dark input[type="week"] {
color-scheme: dark;
}
input[type="number"]::-webkit-outer-spin-button,
input[type="number"]::-webkit-inner-spin-button {
margin: 0;
background: transparent;
border: 0;
box-shadow: none;
opacity: 1;
}
/* Custom scrollbar class untuk komponen tertentu */ /* Custom scrollbar class untuk komponen tertentu */
.custom-scrollbar::-webkit-scrollbar { .custom-scrollbar::-webkit-scrollbar {
width: 6px; width: 6px;
+9 -1
View File
@@ -2,7 +2,15 @@ class AudioManager {
private audioContext: AudioContext | null = null; private audioContext: AudioContext | null = null;
private getAudioContext(): AudioContext { private getAudioContext(): AudioContext {
if (!this.audioContext) { if (!this.audioContext) {
this.audioContext = new (window.AudioContext || (window as any).webkitAudioContext)(); const AudioContextConstructor = window.AudioContext || (window as Window & {
webkitAudioContext?: typeof AudioContext;
}).webkitAudioContext;
if (!AudioContextConstructor) {
throw new Error("Web Audio API is not supported in this browser");
}
const context = new AudioContextConstructor();
this.audioContext = context;
return context;
} }
return this.audioContext; return this.audioContext;
} }
+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);
}
+33 -33
View File
@@ -1,19 +1,29 @@
import type { TwitterResponse, TimelineEntry, AccountInfo } from "@/types/api"; import type { TimelineEntry } from "@/types/api";
const FETCH_STATE_KEY = "twitter_fetch_state"; const FETCH_STATE_KEY = "twitter_fetch_state";
const CURSOR_STATE_KEY = "twitter_cursor_state"; const CURSOR_STATE_KEY = "twitter_cursor_state";
export interface FetchState { export interface FetchState {
username: string; username: string;
cursor: string; cursor: string;
timeline: TimelineEntry[];
accountInfo: AccountInfo | null;
totalFetched: number; totalFetched: number;
completed: boolean; completed: boolean;
lastUpdated: number; lastUpdated: number;
authToken: string;
mediaType: string; mediaType: string;
retweets: boolean; retweets: boolean;
timelineType: string; timelineType: string;
} }
function normalizeFetchState(state: FetchState | null | undefined): FetchState | null {
if (!state) {
return null;
}
return {
...state,
cursor: state.cursor || "",
totalFetched: state.totalFetched ?? 0,
mediaType: state.mediaType || "all",
retweets: state.retweets ?? false,
timelineType: state.timelineType || "timeline",
};
}
export function saveFetchState(state: Partial<FetchState> & { export function saveFetchState(state: Partial<FetchState> & {
username: string; username: string;
}): void { }): void {
@@ -22,12 +32,9 @@ export function saveFetchState(state: Partial<FetchState> & {
const updated: FetchState = { const updated: FetchState = {
username: state.username, username: state.username,
cursor: state.cursor || "", cursor: state.cursor || "",
timeline: state.timeline || existing?.timeline || [],
accountInfo: state.accountInfo || existing?.accountInfo || null,
totalFetched: state.totalFetched ?? existing?.totalFetched ?? 0, totalFetched: state.totalFetched ?? existing?.totalFetched ?? 0,
completed: state.completed ?? false, completed: state.completed ?? false,
lastUpdated: Date.now(), lastUpdated: Date.now(),
authToken: state.authToken || existing?.authToken || "",
mediaType: state.mediaType || existing?.mediaType || "all", mediaType: state.mediaType || existing?.mediaType || "all",
retweets: state.retweets ?? existing?.retweets ?? false, retweets: state.retweets ?? existing?.retweets ?? false,
timelineType: state.timelineType || existing?.timelineType || "timeline", timelineType: state.timelineType || existing?.timelineType || "timeline",
@@ -43,7 +50,7 @@ export function saveFetchState(state: Partial<FetchState> & {
export function getFetchState(username: string): FetchState | null { export function getFetchState(username: string): FetchState | null {
try { try {
const allStates = getAllFetchStates(); const allStates = getAllFetchStates();
return allStates[username.toLowerCase()] || null; return normalizeFetchState(allStates[username.toLowerCase()]);
} }
catch (error) { catch (error) {
console.error("Failed to get fetch state:", error); console.error("Failed to get fetch state:", error);
@@ -54,7 +61,17 @@ export function getAllFetchStates(): Record<string, FetchState> {
try { try {
const stored = localStorage.getItem(FETCH_STATE_KEY); const stored = localStorage.getItem(FETCH_STATE_KEY);
if (stored) { if (stored) {
return JSON.parse(stored); const parsed = JSON.parse(stored);
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
const normalized: Record<string, FetchState> = {};
for (const [key, value] of Object.entries(parsed as Record<string, FetchState | null | undefined>)) {
const state = normalizeFetchState(value);
if (state) {
normalized[key] = state;
}
}
return normalized;
}
} }
} }
catch (error) { catch (error) {
@@ -66,7 +83,7 @@ export function hasResumableFetch(username: string): boolean {
const state = getFetchState(username); const state = getFetchState(username);
if (!state) if (!state)
return false; return false;
return !!state.cursor && !state.completed && state.timeline.length > 0; return !!state.cursor && !state.completed && state.totalFetched > 0;
} }
export function getResumableInfo(username: string): { export function getResumableInfo(username: string): {
canResume: boolean; canResume: boolean;
@@ -79,7 +96,7 @@ export function getResumableInfo(username: string): {
} }
return { return {
canResume: true, canResume: true,
mediaCount: state.timeline.length, mediaCount: state.totalFetched,
lastUpdated: new Date(state.lastUpdated), lastUpdated: new Date(state.lastUpdated),
}; };
} }
@@ -108,25 +125,6 @@ export function clearAllIncompleteFetchStates(): void {
console.error("Failed to clear fetch states:", error); console.error("Failed to clear fetch states:", error);
} }
} }
export function stateToResponse(state: FetchState): TwitterResponse | null {
if (!state.accountInfo)
return null;
return {
account_info: state.accountInfo,
total_urls: state.timeline.length,
timeline: state.timeline,
metadata: {
new_entries: state.timeline.length,
page: 0,
batch_size: 0,
has_more: !state.completed,
cursor: state.cursor,
completed: state.completed,
},
cursor: state.cursor,
completed: state.completed,
};
}
export function saveCursor(username: string, cursor: string): void { export function saveCursor(username: string, cursor: string): void {
try { try {
const allCursors = getAllCursors(); const allCursors = getAllCursors();
@@ -176,7 +174,9 @@ export function clearCursor(username: string): void {
} }
} }
export function mergeTimelines(existing: TimelineEntry[], newEntries: TimelineEntry[]): TimelineEntry[] { export function mergeTimelines(existing: TimelineEntry[], newEntries: TimelineEntry[]): TimelineEntry[] {
const seenIds = new Set(existing.map((e) => e.tweet_id)); const existingTimeline = Array.isArray(existing) ? existing : [];
const unique = newEntries.filter((e) => !seenIds.has(e.tweet_id)); const incomingTimeline = Array.isArray(newEntries) ? newEntries : [];
return [...existing, ...unique]; const seenIds = new Set(existingTimeline.map((e) => e.tweet_id));
const unique = incomingTimeline.filter((e) => !seenIds.has(e.tweet_id));
return [...existingTimeline, ...unique];
} }
+46
View File
@@ -0,0 +1,46 @@
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,
installedVersion: null,
latestVersion: null,
},
ffmpeg: {
installed: null,
installedVersion: null,
latestVersion: null,
},
exiftool: {
installed: null,
installedVersion: null,
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);
}
+503 -39
View File
@@ -1,63 +1,499 @@
import { GetDefaults } from "../../wailsjs/go/main/App"; import { GetDefaults } from "../../wailsjs/go/main/App";
export type FontFamily = "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"; 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 GifQuality = "fast" | "better";
export type GifResolution = "original" | "high" | "medium" | "low"; export type GifResolution = "original" | "high" | "medium" | "low";
export type FetchMode = "single" | "batch"; export type VideoQuality = "highest" | "720" | "480" | "360" | "lowest";
export type MediaType = "all" | "image" | "video" | "gif" | "text"; 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;
export interface Settings { export interface Settings {
downloadPath: string; downloadPath: string;
concurrentDownloads: number;
skipExistingFiles: boolean;
deleteIncompleteFiles: boolean;
retryAttempts: number;
theme: string; theme: string;
themeMode: "auto" | "light" | "dark"; themeMode: "auto" | "light" | "dark";
fontFamily: FontFamily; fontFamily: FontFamily;
customFonts: CustomFontOption[];
sfxEnabled: boolean; sfxEnabled: boolean;
autoConvertGifs: boolean;
gifQuality: GifQuality; gifQuality: GifQuality;
gifResolution: GifResolution; gifResolution: GifResolution;
proxy: string; proxy: string;
fetchTimeout: number; fetchTimeout: number;
fetchMode: FetchMode; includePhotos: boolean;
mediaType: MediaType; includeVideos: boolean;
includeGifs: boolean;
includeText: boolean;
includeRetweets: boolean; includeRetweets: boolean;
videoQuality: VideoQuality;
imageSize: ImageSize;
avatarSize: AvatarSize;
bannerSize: BannerSize;
filenameTemplate: string;
folderTemplate: string;
} }
export const DEFAULT_SETTINGS: Settings = { export const DEFAULT_SETTINGS: Settings = {
downloadPath: "", downloadPath: "",
concurrentDownloads: DEFAULT_CONCURRENT_DOWNLOADS,
skipExistingFiles: true,
deleteIncompleteFiles: true,
retryAttempts: DEFAULT_RETRY_ATTEMPTS,
theme: "yellow", theme: "yellow",
themeMode: "auto", themeMode: "auto",
fontFamily: "google-sans", fontFamily: "google-sans",
customFonts: [],
sfxEnabled: true, sfxEnabled: true,
autoConvertGifs: false,
gifQuality: "fast", gifQuality: "fast",
gifResolution: "original", gifResolution: "original",
proxy: "", proxy: "",
fetchTimeout: 60, fetchTimeout: 60,
fetchMode: "batch", includePhotos: true,
mediaType: "all", includeVideos: true,
includeGifs: true,
includeText: false,
includeRetweets: false, includeRetweets: false,
videoQuality: "highest",
imageSize: "orig",
avatarSize: "orig",
bannerSize: "orig",
filenameTemplate: DEFAULT_FILENAME_TEMPLATE,
folderTemplate: DEFAULT_FOLDER_TEMPLATE,
}; };
export const FONT_OPTIONS: { export const FONT_OPTIONS: FontOption[] = [
value: FontFamily; {
label: string; value: "bricolage-grotesque",
fontFamily: string; label: "Bricolage Grotesque",
}[] = [ fontFamily: '"Bricolage Grotesque", system-ui, sans-serif',
{ value: "dm-sans", label: "DM Sans", fontFamily: '"DM Sans", system-ui, sans-serif' }, },
{ value: "figtree", label: "Figtree", fontFamily: '"Figtree", system-ui, sans-serif' }, {
{ value: "geist-sans", label: "Geist Sans", fontFamily: '"Geist", system-ui, sans-serif' }, value: "dm-sans",
{ value: "google-sans", label: "Google Sans Flex", fontFamily: '"Google Sans Flex", system-ui, sans-serif' }, label: "DM Sans",
{ value: "inter", label: "Inter", fontFamily: '"Inter", system-ui, sans-serif' }, fontFamily: '"DM Sans", system-ui, sans-serif',
{ value: "jetbrains-mono", label: "JetBrains Mono", fontFamily: '"JetBrains Mono", ui-monospace, monospace' }, },
{ value: "manrope", label: "Manrope", fontFamily: '"Manrope", system-ui, sans-serif' }, {
{ value: "noto-sans", label: "Noto Sans", fontFamily: '"Noto Sans", system-ui, sans-serif' }, value: "figtree",
{ value: "nunito-sans", label: "Nunito Sans", fontFamily: '"Nunito Sans", system-ui, sans-serif' }, label: "Figtree",
{ value: "outfit", label: "Outfit", fontFamily: '"Outfit", system-ui, sans-serif' }, fontFamily: '"Figtree", system-ui, sans-serif',
{ value: "plus-jakarta-sans", label: "Plus Jakarta Sans", fontFamily: '"Plus Jakarta Sans", system-ui, sans-serif' }, },
{ value: "poppins", label: "Poppins", fontFamily: '"Poppins", system-ui, sans-serif' }, {
{ value: "public-sans", label: "Public Sans", fontFamily: '"Public Sans", system-ui, sans-serif' }, value: "geist-sans",
{ value: "raleway", label: "Raleway", fontFamily: '"Raleway", system-ui, sans-serif' }, label: "Geist Sans",
{ value: "roboto", label: "Roboto", fontFamily: '"Roboto", system-ui, sans-serif' }, fontFamily: '"Geist", system-ui, sans-serif',
{ value: "space-grotesk", label: "Space Grotesk", fontFamily: '"Space Grotesk", system-ui, sans-serif' }, },
{
value: "google-sans",
label: "Google Sans",
fontFamily: '"Google Sans Flex", system-ui, sans-serif',
},
{
value: "inter",
label: "Inter",
fontFamily: '"Inter", system-ui, sans-serif',
},
{
value: "jetbrains-mono",
label: "JetBrains Mono",
fontFamily: '"JetBrains Mono", ui-monospace, monospace',
},
{
value: "manrope",
label: "Manrope",
fontFamily: '"Manrope", system-ui, sans-serif',
},
{
value: "noto-sans",
label: "Noto Sans",
fontFamily: '"Noto Sans", system-ui, sans-serif',
},
{
value: "nunito-sans",
label: "Nunito Sans",
fontFamily: '"Nunito Sans", system-ui, sans-serif',
},
{
value: "outfit",
label: "Outfit",
fontFamily: '"Outfit", system-ui, sans-serif',
},
{
value: "plus-jakarta-sans",
label: "Plus Jakarta Sans",
fontFamily: '"Plus Jakarta Sans", system-ui, sans-serif',
},
{
value: "poppins",
label: "Poppins",
fontFamily: '"Poppins", system-ui, sans-serif',
},
{
value: "public-sans",
label: "Public Sans",
fontFamily: '"Public Sans", system-ui, sans-serif',
},
{
value: "raleway",
label: "Raleway",
fontFamily: '"Raleway", system-ui, sans-serif',
},
{
value: "roboto",
label: "Roboto",
fontFamily: '"Roboto", system-ui, sans-serif',
},
{
value: "space-grotesk",
label: "Space Grotesk",
fontFamily: '"Space Grotesk", system-ui, sans-serif',
},
]; ];
export function applyFont(fontFamily: FontFamily): void { const BUILT_IN_FONT_VALUES = new Set(FONT_OPTIONS.map((font) => font.value));
const font = FONT_OPTIONS.find(f => f.value === fontFamily); 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);
if (hrefMatch?.[1]) {
return hrefMatch[1];
}
const importMatch = trimmed.match(/@import\s+url\(["']?([^"')]+)["']?\)/i);
if (importMatch?.[1]) {
return importMatch[1];
}
return trimmed;
}
function coerceGoogleFontUrl(rawUrl: string): string {
const trimmed = rawUrl.trim();
if (/^https?:\/\//i.test(trimmed)) {
return trimmed;
}
if (/^(fonts\.googleapis\.com|fonts\.google\.com)\//i.test(trimmed)) {
return `https://${trimmed}`;
}
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)));
if (parsed.protocol !== "https:") {
return null;
}
if (parsed.hostname === GOOGLE_FONTS_SPECIMEN_HOST) {
const label = extractSpecimenFontLabel(parsed);
return label ? buildGoogleFontsCssUrl(label) : null;
}
if (parsed.hostname !== GOOGLE_FONTS_CSS_HOST || (parsed.pathname !== "/css" && parsed.pathname !== "/css2")) {
return null;
}
if (parsed.searchParams.getAll("family").length === 0) {
return null;
}
if (!parsed.searchParams.has("display")) {
parsed.searchParams.set("display", "swap");
}
return parsed.toString();
}
catch {
return null;
}
}
export function parseGoogleFontUrl(rawUrl: string): CustomFontOption | null {
const normalizedUrl = normalizeGoogleFontCssUrl(rawUrl);
if (!normalizedUrl) {
return null;
}
const parsed = new URL(normalizedUrl);
const family = parsed.searchParams.getAll("family")[0];
const label = normalizeFontLabel((family || "").split(":")[0] || "");
if (!label) {
return null;
}
return {
value: `custom-${slugifyFontLabel(label)}` as CustomFontFamily,
label,
fontFamily: toFontFamilyCss(label),
url: normalizedUrl,
};
}
function normalizeCustomFonts(customFonts: unknown): CustomFontOption[] {
if (!Array.isArray(customFonts)) {
return [];
}
const normalizedFonts: CustomFontOption[] = [];
const seenValues = new Set<string>();
const seenUrls = new Set<string>();
for (const item of customFonts) {
if (!item || typeof item !== "object") {
continue;
}
const rawUrl = (item as {
url?: unknown;
}).url;
if (typeof rawUrl !== "string") {
continue;
}
const parsed = parseGoogleFontUrl(rawUrl);
if (!parsed || seenValues.has(parsed.value) || seenUrls.has(parsed.url)) {
continue;
}
seenValues.add(parsed.value);
seenUrls.add(parsed.url);
normalizedFonts.push(parsed);
}
return normalizedFonts;
}
function normalizeFontFamily(fontFamily: unknown, customFonts: CustomFontOption[]): FontFamily {
if (typeof fontFamily !== "string") {
return DEFAULT_SETTINGS.fontFamily;
}
if (BUILT_IN_FONT_VALUES.has(fontFamily as BuiltInFontFamily)) {
return fontFamily as BuiltInFontFamily;
}
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;
}
const rounded = Math.round(value);
if (rounded < MIN_CONCURRENT_DOWNLOADS) {
return MIN_CONCURRENT_DOWNLOADS;
}
if (rounded > MAX_CONCURRENT_DOWNLOADS) {
return MAX_CONCURRENT_DOWNLOADS;
}
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;
}
const rounded = Math.round(value);
if (rounded < MIN_RETRY_ATTEMPTS) {
return MIN_RETRY_ATTEMPTS;
}
if (rounded > MAX_RETRY_ATTEMPTS) {
return MAX_RETRY_ATTEMPTS;
}
return rounded;
}
function normalizeTemplateTokens(value: unknown, fallback: string): string {
if (typeof value !== "string") {
return fallback;
}
return value
.replace(/\{username\}/g, "{handle}")
.replace(/\{account_name\}/g, "{name}");
}
function normalizeFilenameTemplate(value: unknown): string {
const template = normalizeTemplateTokens(value, DEFAULT_FILENAME_TEMPLATE);
return template === "{handle}_{date}_{tweet_id}_{index}" ? DEFAULT_FILENAME_TEMPLATE : template;
}
function normalizeFolderTemplate(value: unknown): string {
return normalizeTemplateTokens(value, DEFAULT_FOLDER_TEMPLATE);
}
export function getFontOptions(customFonts: CustomFontOption[] = []): FontOption[] {
return [...FONT_OPTIONS, ...normalizeCustomFonts(customFonts)];
}
export function loadGoogleFontUrl(url: string, id = `${GOOGLE_FONT_LINK_ID_PREFIX}preview`): void {
const normalizedUrl = normalizeGoogleFontCssUrl(url);
if (!normalizedUrl) {
return;
}
let link = document.getElementById(id) as HTMLLinkElement | null;
if (!link) {
link = document.createElement("link");
link.id = id;
link.rel = "stylesheet";
document.head.appendChild(link);
}
if (link.href !== normalizedUrl) {
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);
const font = fontOptions.find((option) => option.value === fontFamily) || FONT_OPTIONS.find((option) => option.value === DEFAULT_SETTINGS.fontFamily);
if (font) { if (font) {
document.documentElement.style.setProperty('--font-sans', font.fontFamily); document.documentElement.style.setProperty("--font-sans", font.fontFamily);
document.body.style.fontFamily = font.fontFamily; document.body.style.fontFamily = font.fontFamily;
} }
} }
@@ -71,13 +507,27 @@ async function fetchDefaultPath(): Promise<string> {
return ""; return "";
} }
} }
const SETTINGS_KEY = "twitter-media-downloader-settings"; function toNormalizedSettings(settings: Partial<Settings>): Settings {
const customFonts = normalizeCustomFonts(settings.customFonts);
return {
...DEFAULT_SETTINGS,
...settings,
concurrentDownloads: normalizeConcurrentDownloads(settings.concurrentDownloads),
skipExistingFiles: normalizeBoolean(settings.skipExistingFiles, DEFAULT_SETTINGS.skipExistingFiles),
deleteIncompleteFiles: normalizeBoolean(settings.deleteIncompleteFiles, DEFAULT_SETTINGS.deleteIncompleteFiles),
retryAttempts: normalizeRetryAttempts(settings.retryAttempts),
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 { export function getSettings(): Settings {
try { try {
const stored = localStorage.getItem(SETTINGS_KEY); const stored = localStorage.getItem(SETTINGS_KEY);
if (stored) { if (stored) {
const parsed = JSON.parse(stored); return toNormalizedSettings(JSON.parse(stored) as Partial<Settings>);
return { ...DEFAULT_SETTINGS, ...parsed };
} }
} }
catch (error) { catch (error) {
@@ -90,11 +540,12 @@ export async function getSettingsWithDefaults(): Promise<Settings> {
if (!settings.downloadPath) { if (!settings.downloadPath) {
settings.downloadPath = await fetchDefaultPath(); settings.downloadPath = await fetchDefaultPath();
} }
return settings; return toNormalizedSettings(settings);
} }
export function saveSettings(settings: Settings): void { export function saveSettings(settings: Settings): void {
try { try {
localStorage.setItem(SETTINGS_KEY, JSON.stringify(settings)); const normalizedSettings = toNormalizedSettings(settings);
localStorage.setItem(SETTINGS_KEY, JSON.stringify(normalizedSettings));
} }
catch (error) { catch (error) {
console.error("Failed to save settings:", error); console.error("Failed to save settings:", error);
@@ -102,19 +553,32 @@ export function saveSettings(settings: Settings): void {
} }
export function updateSettings(partial: Partial<Settings>): Settings { export function updateSettings(partial: Partial<Settings>): Settings {
const current = getSettings(); const current = getSettings();
const updated = { ...current, ...partial }; const updated = toNormalizedSettings({ ...current, ...partial });
saveSettings(updated); saveSettings(updated);
return updated; return updated;
} }
export async function resetToDefaultSettings(): Promise<Settings> { export async function resetToDefaultSettings(): Promise<Settings> {
const defaultPath = await fetchDefaultPath(); const defaultPath = await fetchDefaultPath();
const defaultSettings = { const defaultSettings = toNormalizedSettings({
...DEFAULT_SETTINGS, ...DEFAULT_SETTINGS,
downloadPath: defaultPath, downloadPath: defaultPath,
}; });
saveSettings(defaultSettings); saveSettings(defaultSettings);
return 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();
saveSettings({
...settings,
customFonts: normalizedFonts,
fontFamily: normalizeFontFamily(settings.fontFamily, normalizedFonts),
});
return normalizedFonts;
}
export function applyThemeMode(mode: "auto" | "light" | "dark"): void { export function applyThemeMode(mode: "auto" | "light" | "dark"): void {
if (mode === "auto") { if (mode === "auto") {
const prefersDark = window.matchMedia("(prefers-color-scheme: dark)").matches; const prefersDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
+6 -6
View File
@@ -1,4 +1,4 @@
import { toast } from "sonner"; import { toast, type ExternalToast } from "sonner";
import { playSuccessSound, playErrorSound, playWarningSound, playInfoSound, } from "./audio"; import { playSuccessSound, playErrorSound, playWarningSound, playInfoSound, } from "./audio";
import { logger } from "./logger"; import { logger } from "./logger";
import { getSettings } from "./settings"; import { getSettings } from "./settings";
@@ -7,35 +7,35 @@ const toastStyle = {
}; };
const isSfxEnabled = () => getSettings().sfxEnabled; const isSfxEnabled = () => getSettings().sfxEnabled;
export const toastWithSound = { export const toastWithSound = {
success: (message: string, data?: any) => { success: (message: string, data?: ExternalToast) => {
const msg = message.toLowerCase(); const msg = message.toLowerCase();
logger.success(msg); logger.success(msg);
if (isSfxEnabled()) if (isSfxEnabled())
playSuccessSound(); playSuccessSound();
return toast.success(msg, { ...toastStyle, ...data }); return toast.success(msg, { ...toastStyle, ...data });
}, },
error: (message: string, data?: any) => { error: (message: string, data?: ExternalToast) => {
const msg = message.toLowerCase(); const msg = message.toLowerCase();
logger.error(msg); logger.error(msg);
if (isSfxEnabled()) if (isSfxEnabled())
playErrorSound(); playErrorSound();
return toast.error(msg, { ...toastStyle, ...data }); return toast.error(msg, { ...toastStyle, ...data });
}, },
warning: (message: string, data?: any) => { warning: (message: string, data?: ExternalToast) => {
const msg = message.toLowerCase(); const msg = message.toLowerCase();
logger.warning(msg); logger.warning(msg);
if (isSfxEnabled()) if (isSfxEnabled())
playWarningSound(); playWarningSound();
return toast.warning(msg, { ...toastStyle, ...data }); return toast.warning(msg, { ...toastStyle, ...data });
}, },
info: (message: string, data?: any) => { info: (message: string, data?: ExternalToast) => {
const msg = message.toLowerCase(); const msg = message.toLowerCase();
logger.info(msg); logger.info(msg);
if (isSfxEnabled()) if (isSfxEnabled())
playInfoSound(); playInfoSound();
return toast.info(msg, { ...toastStyle, ...data }); return toast.info(msg, { ...toastStyle, ...data });
}, },
message: (message: string, data?: any) => { message: (message: string, data?: ExternalToast) => {
const msg = message.toLowerCase(); const msg = message.toLowerCase();
logger.info(msg); logger.info(msg);
if (isSfxEnabled()) if (isSfxEnabled())
+1 -1
View File
@@ -32,7 +32,7 @@ export function openExternal(url: string) {
try { try {
BrowserOpenURL(url); BrowserOpenURL(url);
} }
catch (error) { catch {
if (typeof window !== "undefined") { if (typeof window !== "undefined") {
window.open(url, "_blank", "noopener,noreferrer"); window.open(url, "_blank", "noopener,noreferrer");
} }
+22
View File
@@ -0,0 +1,22 @@
export function compareVersionNumbers(left: string, right: string) {
const toParts = (value: string) => value
.trim()
.replace(/^[^\d]*/, "")
.split(/[^0-9]+/)
.filter(Boolean)
.map((part) => Number.parseInt(part, 10));
const leftParts = toParts(left);
const rightParts = toParts(right);
const maxLength = Math.max(leftParts.length, rightParts.length);
for (let index = 0; index < maxLength; index += 1) {
const leftPart = leftParts[index] ?? 0;
const rightPart = rightParts[index] ?? 0;
if (leftPart > rightPart) {
return 1;
}
if (leftPart < rightPart) {
return -1;
}
}
return 0;
}
+19
View File
@@ -1,3 +1,7 @@
export interface Thumb {
name: string;
url: string;
}
export interface AccountInfo { export interface AccountInfo {
name: string; name: string;
nick: string; nick: string;
@@ -6,6 +10,16 @@ export interface AccountInfo {
friends_count: number; friends_count: number;
profile_image: string; profile_image: string;
statuses_count: number; 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 { export interface TimelineEntry {
url: string; url: string;
@@ -16,16 +30,21 @@ export interface TimelineEntry {
extension: string; extension: string;
width: number; width: number;
height: number; height: number;
thumbnail?: string;
duration_ms?: number;
alt_text?: string;
content?: string; content?: string;
view_count?: number; view_count?: number;
bookmark_count?: number; bookmark_count?: number;
favorite_count?: number; favorite_count?: number;
retweet_count?: number; retweet_count?: number;
reply_count?: number; reply_count?: number;
quote_count?: number;
source?: string; source?: string;
verified?: boolean; verified?: boolean;
original_filename?: string; original_filename?: string;
author_username?: string; author_username?: string;
author_name?: string;
} }
export interface ExtractMetadata { export interface ExtractMetadata {
new_entries: number; new_entries: number;
+1
View File
@@ -1,5 +1,6 @@
{ {
"compilerOptions": { "compilerOptions": {
"ignoreDeprecations": "6.0",
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo", "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "ES2022", "target": "ES2022",
"useDefineForClassFields": true, "useDefineForClassFields": true,
+18
View File
@@ -5,6 +5,8 @@ import {backend} from '../models';
export function CheckFolderExists(arg1:string,arg2:string):Promise<boolean>; export function CheckFolderExists(arg1:string,arg2:string):Promise<boolean>;
export function CheckFoldersExist(arg1:string,arg2:Array<string>):Promise<Record<string, boolean>>;
export function CheckGifsFolderExists(arg1:string,arg2:string):Promise<boolean>; export function CheckGifsFolderExists(arg1:string,arg2:string):Promise<boolean>;
export function CheckGifsFolderHasMP4(arg1:string,arg2:string):Promise<boolean>; export function CheckGifsFolderHasMP4(arg1:string,arg2:string):Promise<boolean>;
@@ -13,6 +15,8 @@ export function CleanupExtractorProcesses():Promise<void>;
export function ClearAllAccountsFromDB():Promise<void>; export function ClearAllAccountsFromDB():Promise<void>;
export function ClearStoredAuthToken(arg1:string):Promise<void>;
export function ConvertGIFs(arg1:main.ConvertGIFsRequest):Promise<main.ConvertGIFsResponse>; export function ConvertGIFs(arg1:main.ConvertGIFsRequest):Promise<main.ConvertGIFsResponse>;
export function DeleteAccountFromDB(arg1:number):Promise<void>; export function DeleteAccountFromDB(arg1:number):Promise<void>;
@@ -27,6 +31,8 @@ export function DownloadMedia(arg1:main.DownloadMediaRequest):Promise<main.Downl
export function DownloadMediaWithMetadata(arg1:main.DownloadMediaWithMetadataRequest):Promise<main.DownloadMediaResponse>; 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 ExportAccountJSON(arg1:number,arg2:string):Promise<string>;
export function ExportAccountsTXT(arg1:Array<number>,arg2:string):Promise<string>; export function ExportAccountsTXT(arg1:Array<number>,arg2:string):Promise<string>;
@@ -43,10 +49,20 @@ export function GetAllGroups():Promise<Array<Record<string, string>>>;
export function GetDefaults():Promise<Record<string, string>>; export function GetDefaults():Promise<Record<string, string>>;
export function GetExifToolVersionStatus():Promise<backend.DependencyVersionStatus>;
export function GetExtractorVersionStatus():Promise<backend.ExtractorVersionStatus>;
export function GetFFmpegVersionStatus():Promise<backend.DependencyVersionStatus>;
export function GetFolderPath(arg1:string,arg2:string):Promise<string>; export function GetFolderPath(arg1:string,arg2:string):Promise<string>;
export function GetGifsFolderPath(arg1:string,arg2:string):Promise<string>; export function GetGifsFolderPath(arg1:string,arg2:string):Promise<string>;
export function GetSavedAccountFromDB(arg1:string,arg2:string):Promise<string>;
export function GetStoredAuthToken(arg1:string):Promise<string>;
export function ImportAccountFromJSON():Promise<main.ImportAccountResponse>; export function ImportAccountFromJSON():Promise<main.ImportAccountResponse>;
export function IsExifToolInstalled():Promise<boolean>; export function IsExifToolInstalled():Promise<boolean>;
@@ -65,6 +81,8 @@ export function SaveAccountToDBWithStatus(arg1:string,arg2:string,arg3:string,ar
export function SelectFolder(arg1:string):Promise<string>; export function SelectFolder(arg1:string):Promise<string>;
export function SetStoredAuthToken(arg1:string,arg2:string):Promise<void>;
export function StopDownload():Promise<boolean>; export function StopDownload():Promise<boolean>;
export function UpdateAccountGroup(arg1:number,arg2:string,arg3:string):Promise<void>; export function UpdateAccountGroup(arg1:number,arg2:string,arg3:string):Promise<void>;
+36
View File
@@ -6,6 +6,10 @@ export function CheckFolderExists(arg1, arg2) {
return window['go']['main']['App']['CheckFolderExists'](arg1, arg2); return window['go']['main']['App']['CheckFolderExists'](arg1, arg2);
} }
export function CheckFoldersExist(arg1, arg2) {
return window['go']['main']['App']['CheckFoldersExist'](arg1, arg2);
}
export function CheckGifsFolderExists(arg1, arg2) { export function CheckGifsFolderExists(arg1, arg2) {
return window['go']['main']['App']['CheckGifsFolderExists'](arg1, arg2); return window['go']['main']['App']['CheckGifsFolderExists'](arg1, arg2);
} }
@@ -22,6 +26,10 @@ export function ClearAllAccountsFromDB() {
return window['go']['main']['App']['ClearAllAccountsFromDB'](); return window['go']['main']['App']['ClearAllAccountsFromDB']();
} }
export function ClearStoredAuthToken(arg1) {
return window['go']['main']['App']['ClearStoredAuthToken'](arg1);
}
export function ConvertGIFs(arg1) { export function ConvertGIFs(arg1) {
return window['go']['main']['App']['ConvertGIFs'](arg1); return window['go']['main']['App']['ConvertGIFs'](arg1);
} }
@@ -50,6 +58,10 @@ export function DownloadMediaWithMetadata(arg1) {
return window['go']['main']['App']['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) { export function ExportAccountJSON(arg1, arg2) {
return window['go']['main']['App']['ExportAccountJSON'](arg1, arg2); return window['go']['main']['App']['ExportAccountJSON'](arg1, arg2);
} }
@@ -82,6 +94,18 @@ export function GetDefaults() {
return window['go']['main']['App']['GetDefaults'](); return window['go']['main']['App']['GetDefaults']();
} }
export function GetExifToolVersionStatus() {
return window['go']['main']['App']['GetExifToolVersionStatus']();
}
export function GetExtractorVersionStatus() {
return window['go']['main']['App']['GetExtractorVersionStatus']();
}
export function GetFFmpegVersionStatus() {
return window['go']['main']['App']['GetFFmpegVersionStatus']();
}
export function GetFolderPath(arg1, arg2) { export function GetFolderPath(arg1, arg2) {
return window['go']['main']['App']['GetFolderPath'](arg1, arg2); return window['go']['main']['App']['GetFolderPath'](arg1, arg2);
} }
@@ -90,6 +114,14 @@ export function GetGifsFolderPath(arg1, arg2) {
return window['go']['main']['App']['GetGifsFolderPath'](arg1, arg2); return window['go']['main']['App']['GetGifsFolderPath'](arg1, arg2);
} }
export function GetSavedAccountFromDB(arg1, arg2) {
return window['go']['main']['App']['GetSavedAccountFromDB'](arg1, arg2);
}
export function GetStoredAuthToken(arg1) {
return window['go']['main']['App']['GetStoredAuthToken'](arg1);
}
export function ImportAccountFromJSON() { export function ImportAccountFromJSON() {
return window['go']['main']['App']['ImportAccountFromJSON'](); return window['go']['main']['App']['ImportAccountFromJSON']();
} }
@@ -126,6 +158,10 @@ export function SelectFolder(arg1) {
return window['go']['main']['App']['SelectFolder'](arg1); return window['go']['main']['App']['SelectFolder'](arg1);
} }
export function SetStoredAuthToken(arg1, arg2) {
return window['go']['main']['App']['SetStoredAuthToken'](arg1, arg2);
}
export function StopDownload() { export function StopDownload() {
return window['go']['main']['App']['StopDownload'](); return window['go']['main']['App']['StopDownload']();
} }
+94
View File
@@ -36,6 +36,38 @@ export namespace backend {
this.statuses_count = source["statuses_count"]; this.statuses_count = source["statuses_count"];
} }
} }
export class DependencyVersionStatus {
installed: boolean;
installed_version?: string;
latest_version?: string;
static createFrom(source: any = {}) {
return new DependencyVersionStatus(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.installed = source["installed"];
this.installed_version = source["installed_version"];
this.latest_version = source["latest_version"];
}
}
export class ExtractorVersionStatus {
installed: boolean;
installed_version?: string;
latest_version?: string;
static createFrom(source: any = {}) {
return new ExtractorVersionStatus(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.installed = source["installed"];
this.installed_version = source["installed_version"];
this.latest_version = source["latest_version"];
}
}
} }
@@ -103,6 +135,10 @@ export namespace main {
urls: string[]; urls: string[];
output_dir: string; output_dir: string;
username: string; username: string;
concurrent_downloads?: number;
skip_existing: boolean;
delete_incomplete_files: boolean;
retry_attempts?: number;
proxy?: string; proxy?: string;
static createFrom(source: any = {}) { static createFrom(source: any = {}) {
@@ -114,11 +150,16 @@ export namespace main {
this.urls = source["urls"]; this.urls = source["urls"];
this.output_dir = source["output_dir"]; this.output_dir = source["output_dir"];
this.username = source["username"]; this.username = source["username"];
this.concurrent_downloads = source["concurrent_downloads"];
this.skip_existing = source["skip_existing"];
this.delete_incomplete_files = source["delete_incomplete_files"];
this.retry_attempts = source["retry_attempts"];
this.proxy = source["proxy"]; this.proxy = source["proxy"];
} }
} }
export class DownloadMediaResponse { export class DownloadMediaResponse {
success: boolean; success: boolean;
cancelled: boolean;
downloaded: number; downloaded: number;
skipped: number; skipped: number;
failed: number; failed: number;
@@ -131,6 +172,7 @@ export namespace main {
constructor(source: any = {}) { constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source); if ('string' === typeof source) source = JSON.parse(source);
this.success = source["success"]; this.success = source["success"];
this.cancelled = source["cancelled"];
this.downloaded = source["downloaded"]; this.downloaded = source["downloaded"];
this.skipped = source["skipped"]; this.skipped = source["skipped"];
this.failed = source["failed"]; this.failed = source["failed"];
@@ -145,6 +187,7 @@ export namespace main {
content?: string; content?: string;
original_filename?: string; original_filename?: string;
author_username?: string; author_username?: string;
account_name?: string;
static createFrom(source: any = {}) { static createFrom(source: any = {}) {
return new MediaItemRequest(source); return new MediaItemRequest(source);
@@ -159,13 +202,23 @@ export namespace main {
this.content = source["content"]; this.content = source["content"];
this.original_filename = source["original_filename"]; this.original_filename = source["original_filename"];
this.author_username = source["author_username"]; this.author_username = source["author_username"];
this.account_name = source["account_name"];
} }
} }
export class DownloadMediaWithMetadataRequest { export class DownloadMediaWithMetadataRequest {
items: MediaItemRequest[]; items: MediaItemRequest[];
output_dir: string; output_dir: string;
username: string; username: string;
concurrent_downloads?: number;
skip_existing: boolean;
delete_incomplete_files: boolean;
retry_attempts?: number;
proxy?: string; proxy?: string;
filename_template?: string;
folder_template?: string;
auto_convert_gifs?: boolean;
gif_quality?: string;
gif_resolution?: string;
static createFrom(source: any = {}) { static createFrom(source: any = {}) {
return new DownloadMediaWithMetadataRequest(source); return new DownloadMediaWithMetadataRequest(source);
@@ -176,7 +229,16 @@ export namespace main {
this.items = this.convertValues(source["items"], MediaItemRequest); this.items = this.convertValues(source["items"], MediaItemRequest);
this.output_dir = source["output_dir"]; this.output_dir = source["output_dir"];
this.username = source["username"]; this.username = source["username"];
this.concurrent_downloads = source["concurrent_downloads"];
this.skip_existing = source["skip_existing"];
this.delete_incomplete_files = source["delete_incomplete_files"];
this.retry_attempts = source["retry_attempts"];
this.proxy = source["proxy"]; 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 { convertValues(a: any, classs: any, asMap: boolean = false): any {
@@ -197,6 +259,26 @@ export namespace main {
return a; 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 { export class ImportAccountResponse {
success: boolean; success: boolean;
username: string; username: string;
@@ -223,6 +305,12 @@ export namespace main {
media_type: string; media_type: string;
retweets: boolean; retweets: boolean;
cursor?: string; cursor?: string;
include_photos: boolean;
include_videos: boolean;
include_gifs: boolean;
include_text: boolean;
video_quality?: string;
image_size?: string;
static createFrom(source: any = {}) { static createFrom(source: any = {}) {
return new TimelineRequest(source); return new TimelineRequest(source);
@@ -238,6 +326,12 @@ export namespace main {
this.media_type = source["media_type"]; this.media_type = source["media_type"];
this.retweets = source["retweets"]; this.retweets = source["retweets"];
this.cursor = source["cursor"]; 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"];
} }
} }
+3 -2
View File
@@ -3,17 +3,18 @@ module twitterxmediabatchdownloader
go 1.25.4 go 1.25.4
require ( require (
github.com/ulikunitz/xz v0.5.15
github.com/wailsapp/wails/v2 v2.12.0 github.com/wailsapp/wails/v2 v2.12.0
github.com/zalando/go-keyring v0.2.8
modernc.org/sqlite v1.50.1 modernc.org/sqlite v1.50.1
) )
require ( require (
git.sr.ht/~jackmordaunt/go-toast/v2 v2.0.3 // indirect git.sr.ht/~jackmordaunt/go-toast/v2 v2.0.3 // indirect
github.com/bep/debounce v1.2.1 // indirect github.com/bep/debounce v1.2.1 // indirect
github.com/danieljoos/wincred v1.2.3 // indirect
github.com/dustin/go-humanize v1.0.1 // indirect github.com/dustin/go-humanize v1.0.1 // indirect
github.com/go-ole/go-ole v1.3.0 // indirect github.com/go-ole/go-ole v1.3.0 // indirect
github.com/godbus/dbus/v5 v5.2.0 // indirect github.com/godbus/dbus/v5 v5.2.2 // indirect
github.com/google/uuid v1.6.0 // indirect github.com/google/uuid v1.6.0 // indirect
github.com/gorilla/websocket v1.5.3 // indirect github.com/gorilla/websocket v1.5.3 // indirect
github.com/jchv/go-winloader v0.0.0-20250406163304-c1995be93bd1 // indirect github.com/jchv/go-winloader v0.0.0-20250406163304-c1995be93bd1 // indirect
+10 -6
View File
@@ -2,14 +2,16 @@ git.sr.ht/~jackmordaunt/go-toast/v2 v2.0.3 h1:N3IGoHHp9pb6mj1cbXbuaSXV/UMKwmbKLf
git.sr.ht/~jackmordaunt/go-toast/v2 v2.0.3/go.mod h1:QtOLZGz8olr4qH2vWK0QH0w0O4T9fEIjMuWpKUsH7nc= git.sr.ht/~jackmordaunt/go-toast/v2 v2.0.3/go.mod h1:QtOLZGz8olr4qH2vWK0QH0w0O4T9fEIjMuWpKUsH7nc=
github.com/bep/debounce v1.2.1 h1:v67fRdBA9UQu2NhLFXrSg0Brw7CexQekrBwDMM8bzeY= github.com/bep/debounce v1.2.1 h1:v67fRdBA9UQu2NhLFXrSg0Brw7CexQekrBwDMM8bzeY=
github.com/bep/debounce v1.2.1/go.mod h1:H8yggRPQKLUhUoqrJC1bO2xNya7vanpDl7xR3ISbCJ0= github.com/bep/debounce v1.2.1/go.mod h1:H8yggRPQKLUhUoqrJC1bO2xNya7vanpDl7xR3ISbCJ0=
github.com/danieljoos/wincred v1.2.3 h1:v7dZC2x32Ut3nEfRH+vhoZGvN72+dQ/snVXo/vMFLdQ=
github.com/danieljoos/wincred v1.2.3/go.mod h1:6qqX0WNrS4RzPZ1tnroDzq9kY3fu1KwE7MRLQK4X0bs=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE= 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/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78=
github.com/godbus/dbus/v5 v5.2.0 h1:3WexO+U+yg9T70v9FdHr9kCxYlazaAXUhx2VMkbfax8= github.com/godbus/dbus/v5 v5.2.2 h1:TUR3TgtSVDmjiXOgAAyaZbYmIeP3DPkld3jgKGV8mXQ=
github.com/godbus/dbus/v5 v5.2.0/go.mod h1:3AAv2+hPq5rdnr5txxxRwiGjPXamgoIHgz9FPBfOp3c= 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 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-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
@@ -56,12 +58,12 @@ github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= 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 h1:Rvi+3BFHES3A8meP33VPAxiBZX/Aws5RxrschYGjomw=
github.com/samber/lo v1.52.0/go.mod h1:4+MXEGsJzbKGaUEQFKBq2xtfuznW9oz/WrgyzMzRoM0= github.com/samber/lo v1.52.0/go.mod h1:4+MXEGsJzbKGaUEQFKBq2xtfuznW9oz/WrgyzMzRoM0=
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY=
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= 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=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/tkrajina/go-reflector v0.5.8 h1:yPADHrwmUbMq4RGEyaOUpz2H90sRsETNVpjzo3DLVQQ= github.com/tkrajina/go-reflector v0.5.8 h1:yPADHrwmUbMq4RGEyaOUpz2H90sRsETNVpjzo3DLVQQ=
github.com/tkrajina/go-reflector v0.5.8/go.mod h1:ECbqLgccecY5kPmPmXg1MrHW585yMcDkVl6IvJe64T4= github.com/tkrajina/go-reflector v0.5.8/go.mod h1:ECbqLgccecY5kPmPmXg1MrHW585yMcDkVl6IvJe64T4=
github.com/ulikunitz/xz v0.5.15 h1:9DNdB5s+SgV3bQ2ApL10xRc35ck0DuIX/isZvIk+ubY=
github.com/ulikunitz/xz v0.5.15/go.mod h1:nbz6k7qbPmH4IRqmfOplQw/tblSgqTqBwxkY0oWt/14=
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw= github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
github.com/valyala/fasttemplate v1.2.2 h1:lxLXG0uE3Qnshl9QyaK6XJxMXlQZELvChBOCmQD0Loo= github.com/valyala/fasttemplate v1.2.2 h1:lxLXG0uE3Qnshl9QyaK6XJxMXlQZELvChBOCmQD0Loo=
@@ -72,6 +74,8 @@ github.com/wailsapp/mimetype v1.4.1 h1:pQN9ycO7uo4vsUUuPeHEYoUkLVkaRntMnHJxVwYhw
github.com/wailsapp/mimetype v1.4.1/go.mod h1:9aV5k31bBOv5z6u+QP8TltzvNGJPmNJD4XlAL3U+j3o= 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 h1:BHO/kLNWFHYjCzucxbzAYZWUjub1Tvb4cSguQozHn5c=
github.com/wailsapp/wails/v2 v2.12.0/go.mod h1:mo1bzK1DEJrobt7YrBjgxvb5Sihb1mhAY09hppbibQg= github.com/wailsapp/wails/v2 v2.12.0/go.mod h1:mo1bzK1DEJrobt7YrBjgxvb5Sihb1mhAY09hppbibQg=
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 h1:jMBrvKuj23MTlT0bQEOBcAE0mjg8mK9RXFhRH6nyF3Q=
golang.org/x/crypto v0.45.0/go.mod h1:XTGrrkGJve7CYK7J8PEww4aY7gM3qMCElcJQ8n8JdX4= 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 h1:tHFzIWbBifEmbwtGz65eaWyGiGZatSrT9prnU8DbVL8=
+1 -1
View File
@@ -11,7 +11,7 @@
}, },
"info": { "info": {
"productName": "Twitter/X Media Batch Downloader", "productName": "Twitter/X Media Batch Downloader",
"productVersion": "4.4" "productVersion": "4.9"
}, },
"wailsjsdir": "./frontend", "wailsjsdir": "./frontend",
"assetdir": "./frontend/dist", "assetdir": "./frontend/dist",