Compare commits

..
5 Commits
Author SHA1 Message Date
429Enjoyer 4794fac099 v4.4 2026-05-12 11:19:59 +07:00
afkarxyz 8cbf7c979b Create FUNDING.yml 2026-01-15 17:59:49 +07:00
afkarxyz de402efe6b v4.3 2025-12-20 12:12:11 +07:00
afkarxyz 2f51a118e4 v4.3 2025-12-20 12:10:45 +07:00
afkarxyz b611632c30 v4.2 2025-12-17 18:25:41 +07:00
83 changed files with 8072 additions and 9637 deletions

No files matched your search

+1
View File
@@ -0,0 +1 @@
ko_fi: afkarxyz
+344
View File
@@ -0,0 +1,344 @@
name: Build Multi-Platform
on:
push:
tags:
- 'v*'
workflow_dispatch:
env:
NODE_VERSION: '24'
PNPM_VERSION: '10'
APP_NAME: TwitterXMediaBatchDownloader
jobs:
build-windows:
name: Build Windows
runs-on: windows-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Go
uses: actions/setup-go@v5
with:
go-version-file: go.mod
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: ${{ env.NODE_VERSION }}
- name: Install pnpm
uses: pnpm/action-setup@v4
with:
version: ${{ env.PNPM_VERSION }}
- name: Get pnpm store directory
shell: bash
run: |
echo "STORE_PATH=$(pnpm store path --silent)" >> $GITHUB_ENV
- name: Setup pnpm cache
continue-on-error: true
uses: actions/cache@v4
with:
path: ${{ env.STORE_PATH }}
key: ${{ runner.os }}-pnpm-store-${{ hashFiles('frontend/pnpm-lock.yaml') }}
restore-keys: |
${{ runner.os }}-pnpm-store-
- name: Install Wails CLI
run: go install github.com/wailsapp/wails/v2/cmd/wails@latest
- name: Install frontend dependencies
working-directory: frontend
run: |
pnpm install
pnpm run generate-icon
- name: Install UPX
run: choco install upx -y
- name: Build application
run: wails build -platform windows/amd64
- name: Compress with UPX
run: upx --best --lzma "build\bin\${{ env.APP_NAME }}.exe"
- name: Prepare artifacts
shell: pwsh
run: |
New-Item -ItemType Directory -Force -Path dist | Out-Null
Copy-Item -Path "build\bin\${{ env.APP_NAME }}.exe" -Destination "dist\${{ env.APP_NAME }}.exe"
- name: Upload artifacts
uses: actions/upload-artifact@v4
with:
name: windows-portable
path: dist/${{ env.APP_NAME }}.exe
retention-days: 7
build-macos:
name: Build macOS
runs-on: macos-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Go
uses: actions/setup-go@v5
with:
go-version-file: go.mod
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: ${{ env.NODE_VERSION }}
- name: Install pnpm
uses: pnpm/action-setup@v4
with:
version: ${{ env.PNPM_VERSION }}
- name: Get pnpm store directory
run: |
echo "STORE_PATH=$(pnpm store path --silent)" >> $GITHUB_ENV
- name: Setup pnpm cache
continue-on-error: true
uses: actions/cache@v4
with:
path: ${{ env.STORE_PATH }}
key: ${{ runner.os }}-pnpm-store-${{ hashFiles('frontend/pnpm-lock.yaml') }}
restore-keys: |
${{ runner.os }}-pnpm-store-
- name: Install Wails CLI
run: go install github.com/wailsapp/wails/v2/cmd/wails@latest
- name: Install frontend dependencies
working-directory: frontend
run: |
pnpm install
pnpm run generate-icon
- name: Build application
run: wails build -platform darwin/universal
- name: Create DMG
run: |
mkdir -p dist
brew install create-dmg || true
create-dmg \
--volname "${{ env.APP_NAME }}" \
--window-pos 200 120 \
--window-size 600 400 \
--icon-size 100 \
--icon "${{ env.APP_NAME }}.app" 175 120 \
--hide-extension "${{ env.APP_NAME }}.app" \
--app-drop-link 425 120 \
"dist/${{ env.APP_NAME }}.dmg" \
"build/bin/${{ env.APP_NAME }}.app" || \
hdiutil create -volname "${{ env.APP_NAME }}" -srcfolder "build/bin/${{ env.APP_NAME }}.app" -ov -format UDZO "dist/${{ env.APP_NAME }}.dmg"
- name: Upload artifacts
uses: actions/upload-artifact@v4
with:
name: macos-portable
path: dist/${{ env.APP_NAME }}.dmg
retention-days: 7
build-linux:
name: Build Linux
runs-on: ubuntu-24.04
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Go
uses: actions/setup-go@v5
with:
go-version-file: go.mod
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: ${{ env.NODE_VERSION }}
- name: Install pnpm
uses: pnpm/action-setup@v4
with:
version: ${{ env.PNPM_VERSION }}
- name: Get pnpm store directory
run: |
echo "STORE_PATH=$(pnpm store path --silent)" >> $GITHUB_ENV
- name: Setup pnpm cache
continue-on-error: true
uses: actions/cache@v4
with:
path: ${{ env.STORE_PATH }}
key: ${{ runner.os }}-pnpm-store-${{ hashFiles('frontend/pnpm-lock.yaml') }}
restore-keys: |
${{ runner.os }}-pnpm-store-
- name: Install dependencies
run: |
sudo apt-get update
sudo apt-get install -y libgtk-3-dev libwebkit2gtk-4.1-dev libfuse2 imagemagick upx-ucl
sudo ln -sf /usr/lib/x86_64-linux-gnu/pkgconfig/webkit2gtk-4.1.pc /usr/lib/x86_64-linux-gnu/pkgconfig/webkit2gtk-4.0.pc
- name: Install Wails CLI
run: go install github.com/wailsapp/wails/v2/cmd/wails@latest
- name: Install frontend dependencies
working-directory: frontend
run: |
pnpm install
pnpm run generate-icon
- name: Build application
run: wails build -platform linux/amd64
- name: Compress with UPX
run: upx --best --lzma "build/bin/${{ env.APP_NAME }}"
- name: Cache appimagetool
id: cache-appimagetool
uses: actions/cache@v4
with:
path: appimagetool
key: appimagetool-x86_64-v2
- name: Download appimagetool
if: steps.cache-appimagetool.outputs.cache-hit != 'true'
run: |
wget --timeout=30 --tries=5 --retry-connrefused --waitretry=5 -O appimagetool "https://github.com/AppImage/appimagetool/releases/download/continuous/appimagetool-x86_64.AppImage" || \
wget --timeout=30 --tries=5 --retry-connrefused --waitretry=5 -O appimagetool "https://github.com/AppImage/appimagetool/releases/download/1.9.1/appimagetool-x86_64.AppImage"
- name: Make appimagetool executable
run: chmod +x appimagetool
- name: Create AppImage
run: |
mkdir -p AppDir/usr/bin
mkdir -p AppDir/usr/share/applications
mkdir -p AppDir/usr/share/icons/hicolor/256x256/apps
cp "build/bin/${{ env.APP_NAME }}" AppDir/usr/bin/
cat > AppDir/twitterxmediabatchdownloader.desktop << 'EOF'
[Desktop Entry]
Name=Twitter/X Media Batch Downloader
Exec=TwitterXMediaBatchDownloader
Icon=twitterxmediabatchdownloader
Type=Application
Categories=Network;Utility;
Comment=Download Twitter/X media in batches
EOF
cp AppDir/twitterxmediabatchdownloader.desktop AppDir/usr/share/applications/
if [ -f "build/appicon.png" ]; then
convert build/appicon.png -resize 256x256 AppDir/twitterxmediabatchdownloader.png
elif [ -f "frontend/public/icon.svg" ]; then
convert -background none -size 256x256 frontend/public/icon.svg AppDir/twitterxmediabatchdownloader.png
else
echo "Warning: No icon found, building without icon"
fi
if [ -f "AppDir/twitterxmediabatchdownloader.png" ]; then
cp AppDir/twitterxmediabatchdownloader.png AppDir/usr/share/icons/hicolor/256x256/apps/
cp AppDir/twitterxmediabatchdownloader.png AppDir/.DirIcon
fi
cat > AppDir/AppRun << 'EOF'
#!/bin/sh
SELF=$(readlink -f "$0")
HERE=${SELF%/*}
export PATH="${HERE}/usr/bin/:${PATH}"
export LD_LIBRARY_PATH="${HERE}/usr/lib/:${LD_LIBRARY_PATH}"
exec "${HERE}/usr/bin/TwitterXMediaBatchDownloader" "$@"
EOF
chmod +x AppDir/AppRun
mkdir -p dist
ARCH=x86_64 ./appimagetool --no-appstream AppDir "dist/${{ env.APP_NAME }}.AppImage"
- name: Upload artifacts
uses: actions/upload-artifact@v4
with:
name: linux-portable
path: dist/${{ env.APP_NAME }}.AppImage
retention-days: 7
create-release:
name: Create Release
needs: [build-windows, build-macos, build-linux]
runs-on: ubuntu-latest
if: startsWith(github.ref, 'refs/tags/v')
permissions:
contents: write
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Download all artifacts
uses: actions/download-artifact@v4
with:
path: artifacts
- name: Display structure of downloaded files
run: ls -R artifacts
- name: Create Release
uses: softprops/action-gh-release@v2
with:
draft: true
prerelease: false
generate_release_notes: false
body: |
## Changelog
## Downloads
- `TwitterXMediaBatchDownloader.exe` - Windows
- `TwitterXMediaBatchDownloader.dmg` - macOS
- `TwitterXMediaBatchDownloader.AppImage` - Linux
<details>
<summary><b>Linux Requirements</b></summary>
The AppImage requires `webkit2gtk-4.1` to be installed on your system:
**Ubuntu/Debian:**
```bash
sudo apt install libwebkit2gtk-4.1-0
```
**Arch Linux:**
```bash
sudo pacman -S webkit2gtk-4.1
```
**Fedora:**
```bash
sudo dnf install webkit2gtk4.1
```
After installing the dependency, make the AppImage executable:
```bash
chmod +x TwitterXMediaBatchDownloader.AppImage
./TwitterXMediaBatchDownloader.AppImage
```
</details>
files: |
artifacts/windows-portable/${{ env.APP_NAME }}.exe
artifacts/macos-portable/${{ env.APP_NAME }}.dmg
artifacts/linux-portable/${{ env.APP_NAME }}.AppImage
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
-62
View File
@@ -1,62 +0,0 @@
# Wails Build
build/
backend/bin/
*.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
# Build notes (optional - uncomment if you don't want to commit)
# BUILD_NOTES.md
build.txt
+4 -14
View File
@@ -1,8 +1,4 @@
[![GitHub All Releases](https://img.shields.io/github/downloads/afkarxyz/Twitter-X-Media-Batch-Downloader/total?style=for-the-badge)](https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases) # Twitter/X Media Batch Downloader
![TwitterXMediaBatchDownloader](https://github.com/user-attachments/assets/354d7470-c01c-4aa6-9da1-ea6c42d27330)
<div align="center">
A GUI tool to download original-quality images and videos from Twitter/X accounts, powered by gallery-dl by @mikf A GUI tool to download original-quality images and videos from Twitter/X accounts, powered by gallery-dl by @mikf
@@ -10,17 +6,13 @@ A GUI tool to download original-quality images and videos from Twitter/X account
![macOS](https://img.shields.io/badge/macOS-10.13%2B-000000?style=for-the-badge&logo=apple&logoColor=white) ![macOS](https://img.shields.io/badge/macOS-10.13%2B-000000?style=for-the-badge&logo=apple&logoColor=white)
![Linux](https://img.shields.io/badge/Linux-Any-FCC624?style=for-the-badge&logo=linux&logoColor=white) ![Linux](https://img.shields.io/badge/Linux-Any-FCC624?style=for-the-badge&logo=linux&logoColor=white)
</div> ### [Download](https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases)
### [Download](https://github.com/afkarxyz/SpotiFLAC/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/551198) - If you're familiar with userscripts, install it [**here**](https://greasyfork.org/en/scripts/551198)
- To install the Chrome extension version, click [**here**](https://www.patreon.com/posts/chrome-extension-139296789) - To install the Chrome extension version, click [**here**](https://chromewebstore.google.com/detail/aboccmnimgpjehlplnanplbhlccohhhn)
## Screenshot
![Image](https://github.com/user-attachments/assets/d0ad4af2-5e50-413b-8d52-7dd54bff38c9)
## How to Obtain Auth Token ## How to Obtain Auth Token
@@ -40,5 +32,3 @@ A GUI tool to download original-quality images and videos from Twitter/X account
6. Do not log out of your account, as a new `auth_token` will be generated by Twitter 6. Do not log out of your account, as a new `auth_token` will be generated by Twitter
![image](https://github.com/user-attachments/assets/8e81dd8f-f8be-4254-9cf6-cacfa97743e9) ![image](https://github.com/user-attachments/assets/8e81dd8f-f8be-4254-9cf6-cacfa97743e9)
[![Ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/afkarxyz)
+27 -81
View File
@@ -10,42 +10,36 @@ import (
"github.com/wailsapp/wails/v2/pkg/runtime" "github.com/wailsapp/wails/v2/pkg/runtime"
) )
// App struct
type App struct { type App struct {
ctx context.Context ctx context.Context
downloadCtx context.Context downloadCtx context.Context
downloadCancel context.CancelFunc downloadCancel context.CancelFunc
} }
// NewApp creates a new App application struct
func NewApp() *App { func NewApp() *App {
return &App{} return &App{}
} }
// startup is called when the app starts. The context is saved
// so we can call the runtime methods
func (a *App) startup(ctx context.Context) { func (a *App) startup(ctx context.Context) {
a.ctx = ctx a.ctx = ctx
// Initialize database
backend.InitDB() if err := backend.InitDB(); err != nil {
// Kill any leftover extractor processes from previous session runtime.LogErrorf(ctx, "failed to initialize database: %v", err)
}
backend.KillAllExtractorProcesses() backend.KillAllExtractorProcesses()
} }
// shutdown is called when the app is closing
func (a *App) shutdown(ctx context.Context) { func (a *App) shutdown(ctx context.Context) {
backend.CloseDB() backend.CloseDB()
// Kill any running extractor processes
backend.KillAllExtractorProcesses() backend.KillAllExtractorProcesses()
} }
// CleanupExtractorProcesses kills all running extractor processes
// Can be called from frontend when user wants to stop/reset
func (a *App) CleanupExtractorProcesses() { func (a *App) CleanupExtractorProcesses() {
backend.KillAllExtractorProcesses() backend.KillAllExtractorProcesses()
} }
// TimelineRequest represents the request structure for timeline extraction
type TimelineRequest struct { type TimelineRequest struct {
Username string `json:"username"` Username string `json:"username"`
AuthToken string `json:"auth_token"` AuthToken string `json:"auth_token"`
@@ -54,10 +48,9 @@ type TimelineRequest struct {
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"` // Resume from this cursor position Cursor string `json:"cursor,omitempty"`
} }
// DateRangeRequest represents the request structure for date range extraction
type DateRangeRequest struct { type DateRangeRequest struct {
Username string `json:"username"` Username string `json:"username"`
AuthToken string `json:"auth_token"` AuthToken string `json:"auth_token"`
@@ -67,9 +60,8 @@ type DateRangeRequest struct {
Retweets bool `json:"retweets"` Retweets bool `json:"retweets"`
} }
// ExtractTimeline extracts media from user timeline
func (a *App) ExtractTimeline(req TimelineRequest) (string, error) { func (a *App) ExtractTimeline(req TimelineRequest) (string, error) {
// Username not required for bookmarks only
if req.Username == "" && req.TimelineType != "bookmarks" { if req.Username == "" && req.TimelineType != "bookmarks" {
return "", fmt.Errorf("username is required") return "", fmt.Errorf("username is required")
} }
@@ -101,7 +93,6 @@ func (a *App) ExtractTimeline(req TimelineRequest) (string, error) {
return string(jsonData), nil return string(jsonData), nil
} }
// ExtractDateRange extracts media based on date range
func (a *App) ExtractDateRange(req DateRangeRequest) (string, error) { func (a *App) ExtractDateRange(req DateRangeRequest) (string, error) {
if req.Username == "" { if req.Username == "" {
return "", fmt.Errorf("username is required") return "", fmt.Errorf("username is required")
@@ -138,13 +129,11 @@ func (a *App) ExtractDateRange(req DateRangeRequest) (string, error) {
return string(jsonData), nil return string(jsonData), nil
} }
// OpenFolder opens a folder in the file explorer
func (a *App) OpenFolder(path string) error { func (a *App) OpenFolder(path string) error {
if path == "" { if path == "" {
return fmt.Errorf("path is required") return fmt.Errorf("path is required")
} }
// Clean the path to use correct separators for the OS
cleanPath := filepath.Clean(path) cleanPath := filepath.Clean(path)
err := backend.OpenFolderInExplorer(cleanPath) err := backend.OpenFolderInExplorer(cleanPath)
@@ -155,51 +144,52 @@ func (a *App) OpenFolder(path string) error {
return nil return nil
} }
// SelectFolder opens a folder selection dialog and returns the selected path
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)
} }
// GetDefaults returns the default configuration
func (a *App) GetDefaults() map[string]string { func (a *App) GetDefaults() map[string]string {
return map[string]string{ return map[string]string{
"downloadPath": backend.GetDefaultDownloadPath(), "downloadPath": backend.GetDefaultDownloadPath(),
} }
} }
// Quit closes the application func (a *App) IsExtractorInstalled() bool {
return backend.IsExtractorInstalled()
}
func (a *App) DownloadExtractor() error {
return backend.DownloadExtractor(nil)
}
func (a *App) Quit() { func (a *App) Quit() {
panic("quit") panic("quit")
} }
// DownloadMediaRequest represents the request for downloading media (legacy)
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"` // Optional proxy URL (e.g., http://proxy:port or socks5://proxy:port) Proxy string `json:"proxy,omitempty"`
} }
// MediaItemRequest represents a media item with metadata
type MediaItemRequest struct { type MediaItemRequest struct {
URL string `json:"url"` URL string `json:"url"`
Date string `json:"date"` Date string `json:"date"`
TweetID backend.TweetIDString `json:"tweet_id"` TweetID backend.TweetIDString `json:"tweet_id"`
Type string `json:"type"` Type string `json:"type"`
Content string `json:"content,omitempty"` // Tweet text content (for text-only tweets) Content string `json:"content,omitempty"`
OriginalFilename string `json:"original_filename,omitempty"` // Original filename from API OriginalFilename string `json:"original_filename,omitempty"`
AuthorUsername string `json:"author_username,omitempty"` // Username of tweet author (for bookmarks and likes) AuthorUsername string `json:"author_username,omitempty"`
} }
// DownloadMediaWithMetadataRequest represents the request for downloading media with metadata
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"` // Optional proxy URL (e.g., http://proxy:port or socks5://proxy:port) Proxy string `json:"proxy,omitempty"`
} }
// DownloadMediaResponse represents the response for download operation
type DownloadMediaResponse struct { type DownloadMediaResponse struct {
Success bool `json:"success"` Success bool `json:"success"`
Downloaded int `json:"downloaded"` Downloaded int `json:"downloaded"`
@@ -208,7 +198,6 @@ type DownloadMediaResponse struct {
Message string `json:"message"` Message string `json:"message"`
} }
// DownloadMedia downloads media files from URLs (legacy)
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{
@@ -222,7 +211,6 @@ func (a *App) DownloadMedia(req DownloadMediaRequest) (DownloadMediaResponse, er
outputDir = backend.GetDefaultDownloadPath() outputDir = backend.GetDefaultDownloadPath()
} }
// Create subfolder for username if provided
if req.Username != "" { if req.Username != "" {
outputDir = filepath.Join(outputDir, req.Username) outputDir = filepath.Join(outputDir, req.Username)
} }
@@ -247,21 +235,18 @@ func (a *App) DownloadMedia(req DownloadMediaRequest) (DownloadMediaResponse, er
}, nil }, nil
} }
// DownloadProgress represents download progress event data
type DownloadProgress struct { type DownloadProgress struct {
Current int `json:"current"` Current int `json:"current"`
Total int `json:"total"` Total int `json:"total"`
Percent int `json:"percent"` Percent int `json:"percent"`
} }
// DownloadItemStatus represents per-item download status event data
type DownloadItemStatus struct { type DownloadItemStatus struct {
TweetID int64 `json:"tweet_id"` TweetID int64 `json:"tweet_id"`
Index int `json:"index"` Index int `json:"index"`
Status string `json:"status"` // "success", "failed", "skipped" Status string `json:"status"`
} }
// DownloadMediaWithMetadata downloads media files with proper naming and categorization
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{
@@ -275,18 +260,15 @@ func (a *App) DownloadMediaWithMetadata(req DownloadMediaWithMetadataRequest) (D
outputDir = backend.GetDefaultDownloadPath() outputDir = backend.GetDefaultDownloadPath()
} }
// Convert request items to backend items
// For bookmarks and likes, use author_username from each item if available
items := make([]backend.MediaItem, len(req.Items)) items := make([]backend.MediaItem, len(req.Items))
for i, item := range req.Items { for i, item := range req.Items {
// Use original filename from API if available, otherwise extract from URL
originalFilename := item.OriginalFilename originalFilename := item.OriginalFilename
if originalFilename == "" { if originalFilename == "" {
// Fallback: extract from URL if not provided in API response
originalFilename = backend.ExtractOriginalFilename(item.URL) originalFilename = backend.ExtractOriginalFilename(item.URL)
} }
// For bookmarks and likes, use author_username from item, otherwise use req.Username
username := req.Username username := req.Username
if item.AuthorUsername != "" { if item.AuthorUsername != "" {
username = item.AuthorUsername username = item.AuthorUsername
@@ -303,10 +285,8 @@ func (a *App) DownloadMediaWithMetadata(req DownloadMediaWithMetadataRequest) (D
} }
} }
// Create cancellable context
a.downloadCtx, a.downloadCancel = context.WithCancel(context.Background()) a.downloadCtx, a.downloadCancel = context.WithCancel(context.Background())
// Progress callback
progressCallback := func(current, total int) { progressCallback := func(current, total int) {
percent := 0 percent := 0
if total > 0 { if total > 0 {
@@ -319,7 +299,6 @@ func (a *App) DownloadMediaWithMetadata(req DownloadMediaWithMetadataRequest) (D
}) })
} }
// Per-item status callback
itemStatusCallback := func(tweetID int64, index int, status string) { itemStatusCallback := func(tweetID int64, index int, status string) {
runtime.EventsEmit(a.ctx, "download-item-status", DownloadItemStatus{ runtime.EventsEmit(a.ctx, "download-item-status", DownloadItemStatus{
TweetID: tweetID, TweetID: tweetID,
@@ -339,7 +318,6 @@ func (a *App) DownloadMediaWithMetadata(req DownloadMediaWithMetadataRequest) (D
}, err }, err
} }
// Clear cancel function
a.downloadCancel = nil a.downloadCancel = nil
return DownloadMediaResponse{ return DownloadMediaResponse{
@@ -351,7 +329,6 @@ func (a *App) DownloadMediaWithMetadata(req DownloadMediaWithMetadataRequest) (D
}, nil }, nil
} }
// StopDownload cancels the current download operation
func (a *App) StopDownload() bool { func (a *App) StopDownload() bool {
if a.downloadCancel != nil { if a.downloadCancel != nil {
a.downloadCancel() a.downloadCancel()
@@ -361,24 +338,18 @@ func (a *App) StopDownload() bool {
return false return false
} }
// Database functions
// SaveAccountToDB saves account data to database
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 {
return backend.SaveAccount(username, name, profileImage, totalMedia, responseJSON, mediaType) return backend.SaveAccount(username, name, profileImage, totalMedia, responseJSON, mediaType)
} }
// SaveAccountToDBWithStatus saves account data with cursor and completion status for resume capability
func (a *App) SaveAccountToDBWithStatus(username, name, profileImage string, totalMedia int, responseJSON string, mediaType string, cursor string, completed bool) error { func (a *App) SaveAccountToDBWithStatus(username, name, profileImage string, totalMedia int, responseJSON string, mediaType string, cursor string, completed bool) error {
return backend.SaveAccountWithStatus(username, name, profileImage, totalMedia, responseJSON, mediaType, cursor, completed) return backend.SaveAccountWithStatus(username, name, profileImage, totalMedia, responseJSON, mediaType, cursor, completed)
} }
// GetAllAccountsFromDB returns all saved accounts
func (a *App) GetAllAccountsFromDB() ([]backend.AccountListItem, error) { func (a *App) GetAllAccountsFromDB() ([]backend.AccountListItem, error) {
return backend.GetAllAccounts() return backend.GetAllAccounts()
} }
// GetAccountFromDB returns account data by ID
func (a *App) GetAccountFromDB(id int64) (string, error) { func (a *App) GetAccountFromDB(id int64) (string, error) {
acc, err := backend.GetAccountByID(id) acc, err := backend.GetAccountByID(id)
if err != nil { if err != nil {
@@ -387,67 +358,53 @@ func (a *App) GetAccountFromDB(id int64) (string, error) {
return acc.ResponseJSON, nil return acc.ResponseJSON, nil
} }
// DeleteAccountFromDB deletes an account from database
func (a *App) DeleteAccountFromDB(id int64) error { func (a *App) DeleteAccountFromDB(id int64) error {
return backend.DeleteAccount(id) return backend.DeleteAccount(id)
} }
// ClearAllAccountsFromDB deletes all accounts from database
func (a *App) ClearAllAccountsFromDB() error { func (a *App) ClearAllAccountsFromDB() error {
return backend.ClearAllAccounts() return backend.ClearAllAccounts()
} }
// ExportAccountJSON exports account to JSON file in specified directory
func (a *App) ExportAccountJSON(id int64, outputDir string) (string, error) { func (a *App) ExportAccountJSON(id int64, outputDir string) (string, error) {
return backend.ExportAccountToFile(id, outputDir) return backend.ExportAccountToFile(id, outputDir)
} }
// ExportAccountsTXT exports selected accounts to TXT file in specified directory
func (a *App) ExportAccountsTXT(ids []int64, outputDir string) (string, error) { func (a *App) ExportAccountsTXT(ids []int64, outputDir string) (string, error) {
return backend.ExportAccountsToTXT(ids, outputDir) return backend.ExportAccountsToTXT(ids, outputDir)
} }
// UpdateAccountGroup updates the group for an account
func (a *App) UpdateAccountGroup(id int64, groupName, groupColor string) error { func (a *App) UpdateAccountGroup(id int64, groupName, groupColor string) error {
return backend.UpdateAccountGroup(id, groupName, groupColor) return backend.UpdateAccountGroup(id, groupName, groupColor)
} }
// GetAllGroups returns all unique groups
func (a *App) GetAllGroups() ([]map[string]string, error) { func (a *App) GetAllGroups() ([]map[string]string, error) {
return backend.GetAllGroups() return backend.GetAllGroups()
} }
// FFmpeg functions
// IsFFmpegInstalled checks if ffmpeg is available
func (a *App) IsFFmpegInstalled() bool { func (a *App) IsFFmpegInstalled() bool {
return backend.IsFFmpegInstalled() return backend.IsFFmpegInstalled()
} }
// DownloadFFmpeg downloads ffmpeg binary
func (a *App) DownloadFFmpeg() error { func (a *App) DownloadFFmpeg() error {
return backend.DownloadFFmpeg(nil) return backend.DownloadFFmpeg(nil)
} }
// IsExifToolInstalled checks if exiftool is available
func (a *App) IsExifToolInstalled() bool { func (a *App) IsExifToolInstalled() bool {
return backend.IsExifToolInstalled() return backend.IsExifToolInstalled()
} }
// DownloadExifTool downloads exiftool binary
func (a *App) DownloadExifTool() error { func (a *App) DownloadExifTool() error {
return backend.DownloadExifTool(nil) return backend.DownloadExifTool(nil)
} }
// ConvertGIFsRequest represents request for converting GIFs
type ConvertGIFsRequest struct { type ConvertGIFsRequest struct {
FolderPath string `json:"folder_path"` FolderPath string `json:"folder_path"`
Quality string `json:"quality"` // "fast" or "better" Quality string `json:"quality"`
Resolution string `json:"resolution"` // "original", "high", "medium", "low" Resolution string `json:"resolution"`
DeleteOriginal bool `json:"delete_original"` DeleteOriginal bool `json:"delete_original"`
} }
// ConvertGIFsResponse represents response for GIF conversion
type ConvertGIFsResponse struct { type ConvertGIFsResponse struct {
Success bool `json:"success"` Success bool `json:"success"`
Converted int `json:"converted"` Converted int `json:"converted"`
@@ -455,7 +412,6 @@ type ConvertGIFsResponse struct {
Message string `json:"message"` Message string `json:"message"`
} }
// ConvertGIFs converts MP4 files in gifs folder to actual GIF format
func (a *App) ConvertGIFs(req ConvertGIFsRequest) (ConvertGIFsResponse, error) { func (a *App) ConvertGIFs(req ConvertGIFsRequest) (ConvertGIFsResponse, error) {
if !backend.IsFFmpegInstalled() { if !backend.IsFFmpegInstalled() {
return ConvertGIFsResponse{ return ConvertGIFsResponse{
@@ -464,7 +420,6 @@ func (a *App) ConvertGIFs(req ConvertGIFsRequest) (ConvertGIFsResponse, error) {
}, nil }, nil
} }
// Default values if not provided
quality := req.Quality quality := req.Quality
if quality == "" { if quality == "" {
quality = "fast" quality = "fast"
@@ -490,41 +445,34 @@ func (a *App) ConvertGIFs(req ConvertGIFsRequest) (ConvertGIFsResponse, error) {
}, nil }, nil
} }
// ImportAccountResponse represents the response for import operation
type ImportAccountResponse struct { type ImportAccountResponse struct {
Success bool `json:"success"` Success bool `json:"success"`
Username string `json:"username"` Username string `json:"username"`
Message string `json:"message"` Message string `json:"message"`
} }
// CheckFolderExists checks if a folder exists for the given username
func (a *App) CheckFolderExists(basePath, username string) bool { func (a *App) CheckFolderExists(basePath, username string) bool {
return backend.CheckFolderExists(basePath, username) return backend.CheckFolderExists(basePath, username)
} }
// CheckGifsFolderExists checks if a gifs subfolder exists for the given username
func (a *App) CheckGifsFolderExists(basePath, username string) bool { func (a *App) CheckGifsFolderExists(basePath, username string) bool {
return backend.CheckGifsFolderExists(basePath, username) return backend.CheckGifsFolderExists(basePath, username)
} }
// CheckGifsFolderHasMP4 checks if the gifs folder has any MP4 files to convert
func (a *App) CheckGifsFolderHasMP4(basePath, username string) bool { func (a *App) CheckGifsFolderHasMP4(basePath, username string) bool {
return backend.CheckGifsFolderHasMP4(basePath, username) return backend.CheckGifsFolderHasMP4(basePath, username)
} }
// GetFolderPath returns the full path for a username folder
func (a *App) GetFolderPath(basePath, username string) string { func (a *App) GetFolderPath(basePath, username string) string {
return backend.GetFolderPath(basePath, username) return backend.GetFolderPath(basePath, username)
} }
// GetGifsFolderPath returns the full path for a username's gifs folder
func (a *App) GetGifsFolderPath(basePath, username string) string { func (a *App) GetGifsFolderPath(basePath, username string) string {
return backend.GetGifsFolderPath(basePath, username) return backend.GetGifsFolderPath(basePath, username)
} }
// ImportAccountFromJSON imports account from JSON file (supports both old and new format)
func (a *App) ImportAccountFromJSON() (ImportAccountResponse, error) { func (a *App) ImportAccountFromJSON() (ImportAccountResponse, error) {
// Open file dialog
filePath, err := runtime.OpenFileDialog(a.ctx, runtime.OpenDialogOptions{ filePath, err := runtime.OpenFileDialog(a.ctx, runtime.OpenDialogOptions{
Title: "Import Account JSON", Title: "Import Account JSON",
Filters: []runtime.FileFilter{ Filters: []runtime.FileFilter{
@@ -535,12 +483,10 @@ func (a *App) ImportAccountFromJSON() (ImportAccountResponse, error) {
return ImportAccountResponse{Success: false, Message: err.Error()}, err return ImportAccountResponse{Success: false, Message: err.Error()}, err
} }
// User cancelled
if filePath == "" { if filePath == "" {
return ImportAccountResponse{Success: false, Message: "Cancelled"}, nil return ImportAccountResponse{Success: false, Message: "Cancelled"}, nil
} }
// Import the file
username, err := backend.ImportAccountFromFile(filePath) username, err := backend.ImportAccountFromFile(filePath)
if err != nil { if err != nil {
return ImportAccountResponse{Success: false, Message: err.Error()}, err return ImportAccountResponse{Success: false, Message: err.Error()}, err
+1 -2
View File
@@ -4,7 +4,6 @@ package backend
import "os/exec" import "os/exec"
// hideWindow is a no-op on non-Windows platforms
func hideWindow(cmd *exec.Cmd) { func hideWindow(cmd *exec.Cmd) {
// No action needed on Unix-like systems
} }
+1 -2
View File
@@ -7,10 +7,9 @@ import (
"syscall" "syscall"
) )
// hideWindow sets the command to run without showing a console window on Windows
func hideWindow(cmd *exec.Cmd) { func hideWindow(cmd *exec.Cmd) {
cmd.SysProcAttr = &syscall.SysProcAttr{ cmd.SysProcAttr = &syscall.SysProcAttr{
HideWindow: true, HideWindow: true,
CreationFlags: 0x08000000, // CREATE_NO_WINDOW CreationFlags: 0x08000000,
} }
} }
+4 -9
View File
@@ -10,21 +10,18 @@ import (
) )
func GetDefaultDownloadPath() string { func GetDefaultDownloadPath() string {
// Get user's home directory
homeDir, err := os.UserHomeDir() homeDir, err := os.UserHomeDir()
if err != nil { if err != nil {
// Fallback to Public Pictures if can't get home dir
return "C:\\Users\\Public\\Pictures" return "C:\\Users\\Public\\Pictures"
} }
// Return path to user's Pictures folder
return filepath.Join(homeDir, "Pictures") return filepath.Join(homeDir, "Pictures")
} }
// GetProxyURL gets proxy URL from environment variables or custom proxy setting
// Priority: customProxy > HTTP_PROXY/HTTPS_PROXY > http_proxy/https_proxy
func GetProxyURL(customProxy string) (*url.URL, error) { func GetProxyURL(customProxy string) (*url.URL, error) {
// First, check custom proxy setting
if customProxy != "" { if customProxy != "" {
proxyURL, err := url.Parse(customProxy) proxyURL, err := url.Parse(customProxy)
if err != nil { if err != nil {
@@ -33,7 +30,6 @@ func GetProxyURL(customProxy string) (*url.URL, error) {
return proxyURL, nil return proxyURL, nil
} }
// Check environment variables (case-insensitive on Windows)
proxyEnv := os.Getenv("HTTPS_PROXY") proxyEnv := os.Getenv("HTTPS_PROXY")
if proxyEnv == "" { if proxyEnv == "" {
proxyEnv = os.Getenv("https_proxy") proxyEnv = os.Getenv("https_proxy")
@@ -53,10 +49,9 @@ func GetProxyURL(customProxy string) (*url.URL, error) {
return proxyURL, nil return proxyURL, nil
} }
return nil, nil // No proxy return nil, nil
} }
// CreateHTTPClient creates an HTTP client with proxy support
func CreateHTTPClient(customProxy string, timeout time.Duration) (*http.Client, error) { func CreateHTTPClient(customProxy string, timeout time.Duration) (*http.Client, error) {
proxyURL, err := GetProxyURL(customProxy) proxyURL, err := GetProxyURL(customProxy)
if err != nil { if err != nil {
+41 -61
View File
@@ -8,10 +8,9 @@ import (
"path/filepath" "path/filepath"
"time" "time"
_ "github.com/mattn/go-sqlite3" _ "modernc.org/sqlite"
) )
// AccountDB represents a saved account in the database
type AccountDB struct { type AccountDB struct {
ID int64 `json:"id"` ID int64 `json:"id"`
Username string `json:"username"` Username string `json:"username"`
@@ -25,24 +24,24 @@ type AccountDB struct {
Completed bool `json:"completed"` Completed bool `json:"completed"`
} }
// AccountListItem represents a simplified account for listing
type AccountListItem struct { type AccountListItem struct {
ID int64 `json:"id"` ID int64 `json:"id"`
Username string `json:"username"` Username string `json:"username"`
Name string `json:"name"` Name string `json:"name"`
ProfileImage string `json:"profile_image"` ProfileImage string `json:"profile_image"`
TotalMedia int `json:"total_media"` TotalMedia int `json:"total_media"`
LastFetched string `json:"last_fetched"` LastFetched string `json:"last_fetched"`
GroupName string `json:"group_name"` GroupName string `json:"group_name"`
GroupColor string `json:"group_color"` GroupColor string `json:"group_color"`
MediaType string `json:"media_type"` MediaType string `json:"media_type"`
Cursor string `json:"cursor"` Cursor string `json:"cursor"`
Completed bool `json:"completed"` Completed bool `json:"completed"`
FollowersCount int `json:"followers_count"`
StatusesCount int `json:"statuses_count"`
} }
var db *sql.DB var db *sql.DB
// GetDBPath returns the database file path
func GetDBPath() string { func GetDBPath() string {
homeDir, err := os.UserHomeDir() homeDir, err := os.UserHomeDir()
if err != nil { if err != nil {
@@ -51,23 +50,24 @@ func GetDBPath() string {
return filepath.Join(homeDir, ".twitterxmediabatchdownloader", "accounts.db") return filepath.Join(homeDir, ".twitterxmediabatchdownloader", "accounts.db")
} }
// InitDB initializes the database connection
func InitDB() error { func InitDB() error {
dbPath := GetDBPath() dbPath := GetDBPath()
// Create directory if not exists
dir := filepath.Dir(dbPath) dir := filepath.Dir(dbPath)
if err := os.MkdirAll(dir, 0755); err != nil { if err := os.MkdirAll(dir, 0755); err != nil {
return err return err
} }
var err error var err error
db, err = sql.Open("sqlite3", dbPath) db, err = sql.Open("sqlite", dbPath)
if err != nil { if err != nil {
return err return err
} }
// Create tables if err := db.Ping(); err != nil {
return err
}
_, err = db.Exec(` _, err = db.Exec(`
CREATE TABLE IF NOT EXISTS accounts ( CREATE TABLE IF NOT EXISTS accounts (
id INTEGER PRIMARY KEY AUTOINCREMENT, id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -89,33 +89,27 @@ func InitDB() error {
return err return err
} }
// Add group columns if they don't exist (migration for existing databases)
db.Exec("ALTER TABLE accounts ADD COLUMN group_name TEXT DEFAULT ''") 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 group_color TEXT DEFAULT ''")
db.Exec("ALTER TABLE accounts ADD COLUMN media_type TEXT DEFAULT 'all'") 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 cursor TEXT DEFAULT ''")
db.Exec("ALTER TABLE accounts ADD COLUMN completed INTEGER DEFAULT 1") db.Exec("ALTER TABLE accounts ADD COLUMN completed INTEGER DEFAULT 1")
// Migration: Update unique constraint for existing databases
// This allows same username with different media types
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)")
return nil return nil
} }
// CloseDB closes the database connection
func CloseDB() { func CloseDB() {
if db != nil { if db != nil {
db.Close() db.Close()
} }
} }
// SaveAccount saves or updates an account in the database
func SaveAccount(username, name, profileImage string, totalMedia int, responseJSON string, mediaType string) error { func SaveAccount(username, name, profileImage string, totalMedia int, responseJSON string, mediaType string) error {
return SaveAccountWithStatus(username, name, profileImage, totalMedia, responseJSON, mediaType, "", true) return SaveAccountWithStatus(username, name, profileImage, totalMedia, responseJSON, mediaType, "", true)
} }
// SaveAccountWithStatus saves or updates an account with cursor and completion status
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 db == nil {
if err := InitDB(); err != nil { if err := InitDB(); err != nil {
@@ -123,7 +117,6 @@ func SaveAccountWithStatus(username, name, profileImage string, totalMedia int,
} }
} }
// Default to "all" if not specified
if mediaType == "" { if mediaType == "" {
mediaType = "all" mediaType = "all"
} }
@@ -149,7 +142,6 @@ func SaveAccountWithStatus(username, name, profileImage string, totalMedia int,
return err return err
} }
// GetAllAccounts returns all saved accounts
func GetAllAccounts() ([]AccountListItem, error) { func GetAllAccounts() ([]AccountListItem, error) {
if db == nil { if db == nil {
if err := InitDB(); err != nil { if err := InitDB(); err != nil {
@@ -161,7 +153,8 @@ func GetAllAccounts() ([]AccountListItem, error) {
SELECT id, username, name, profile_image, total_media, last_fetched, SELECT id, username, name, profile_image, total_media, last_fetched,
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
FROM accounts FROM accounts
ORDER BY group_name ASC, last_fetched DESC ORDER BY group_name ASC, last_fetched DESC
`) `)
@@ -175,18 +168,33 @@ func GetAllAccounts() ([]AccountListItem, error) {
var acc AccountListItem var acc AccountListItem
var lastFetched time.Time var lastFetched time.Time
var completedInt int var completedInt int
if err := rows.Scan(&acc.ID, &acc.Username, &acc.Name, &acc.ProfileImage, &acc.TotalMedia, &lastFetched, &acc.GroupName, &acc.GroupColor, &acc.MediaType, &acc.Cursor, &completedInt); err != nil { 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, &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
} }
// UpdateAccountGroup updates the group for an account
func UpdateAccountGroup(id int64, groupName, groupColor string) error { func UpdateAccountGroup(id int64, groupName, groupColor string) error {
if db == nil { if db == nil {
if err := InitDB(); err != nil { if err := InitDB(); err != nil {
@@ -198,7 +206,6 @@ func UpdateAccountGroup(id int64, groupName, groupColor string) error {
return err return err
} }
// GetAllGroups returns all unique groups
func GetAllGroups() ([]map[string]string, error) { func GetAllGroups() ([]map[string]string, error) {
if db == nil { if db == nil {
if err := InitDB(); err != nil { if err := InitDB(); err != nil {
@@ -229,7 +236,6 @@ func GetAllGroups() ([]map[string]string, error) {
return groups, nil return groups, nil
} }
// ClearAllAccounts deletes all accounts from the database
func ClearAllAccounts() error { func ClearAllAccounts() error {
if db == nil { if db == nil {
if err := InitDB(); err != nil { if err := InitDB(); err != nil {
@@ -241,8 +247,6 @@ func ClearAllAccounts() error {
return err return err
} }
// GetAccountByID returns a specific account by ID
func GetAccountByID(id int64) (*AccountDB, error) { func GetAccountByID(id int64) (*AccountDB, error) {
if db == nil { if db == nil {
if err := InitDB(); err != nil { if err := InitDB(); err != nil {
@@ -265,7 +269,6 @@ func GetAccountByID(id int64) (*AccountDB, error) {
acc.LastFetched = lastFetched acc.LastFetched = lastFetched
acc.Completed = completedInt == 1 acc.Completed = completedInt == 1
// Convert legacy format if needed
if converted, err := ConvertLegacyToNewFormat(acc.ResponseJSON); err == nil { if converted, err := ConvertLegacyToNewFormat(acc.ResponseJSON); err == nil {
acc.ResponseJSON = converted acc.ResponseJSON = converted
} }
@@ -273,7 +276,6 @@ func GetAccountByID(id int64) (*AccountDB, error) {
return &acc, nil return &acc, nil
} }
// DeleteAccount deletes an account from the database
func DeleteAccount(id int64) error { func DeleteAccount(id int64) error {
if db == nil { if db == nil {
if err := InitDB(); err != nil { if err := InitDB(); err != nil {
@@ -284,7 +286,7 @@ func DeleteAccount(id int64) error {
_, err := db.Exec("DELETE FROM accounts WHERE id = ?", id) _, err := db.Exec("DELETE FROM accounts WHERE id = ?", id)
return err return err
} }
// LegacyMediaEntry represents media entry in old format
type LegacyMediaEntry struct { type LegacyMediaEntry struct {
TweetID string `json:"tweet_id"` TweetID string `json:"tweet_id"`
URL string `json:"url"` URL string `json:"url"`
@@ -292,7 +294,6 @@ type LegacyMediaEntry struct {
Type string `json:"type"` Type string `json:"type"`
} }
// LegacyAccountFormat represents the old saved account format
type LegacyAccountFormat struct { type LegacyAccountFormat struct {
Username string `json:"username"` Username string `json:"username"`
Nick string `json:"nick"` Nick string `json:"nick"`
@@ -307,20 +308,17 @@ type LegacyAccountFormat struct {
MediaList []LegacyMediaEntry `json:"media_list"` MediaList []LegacyMediaEntry `json:"media_list"`
} }
// ConvertLegacyToNewFormat converts old format to new TwitterResponse format
func ConvertLegacyToNewFormat(jsonStr string) (string, error) { func ConvertLegacyToNewFormat(jsonStr string) (string, error) {
// First check if it's already in new format (has account_info key)
var check map[string]interface{} var check map[string]interface{}
if err := json.Unmarshal([]byte(jsonStr), &check); err != nil { if err := json.Unmarshal([]byte(jsonStr), &check); err != nil {
return jsonStr, err return jsonStr, err
} }
// If already has account_info, it's new format - return as is
if _, hasAccountInfo := check["account_info"]; hasAccountInfo { if _, hasAccountInfo := check["account_info"]; hasAccountInfo {
return jsonStr, nil return jsonStr, nil
} }
// Check if it's legacy format (has username and media_list)
if _, hasUsername := check["username"]; !hasUsername { if _, hasUsername := check["username"]; !hasUsername {
return jsonStr, nil return jsonStr, nil
} }
@@ -328,13 +326,11 @@ func ConvertLegacyToNewFormat(jsonStr string) (string, error) {
return jsonStr, nil return jsonStr, nil
} }
// Parse as legacy format
var legacy LegacyAccountFormat var legacy LegacyAccountFormat
if err := json.Unmarshal([]byte(jsonStr), &legacy); err != nil { if err := json.Unmarshal([]byte(jsonStr), &legacy); err != nil {
return jsonStr, err return jsonStr, err
} }
// Convert timeline entries
timeline := make([]map[string]interface{}, len(legacy.MediaList)) timeline := make([]map[string]interface{}, len(legacy.MediaList))
for i, media := range legacy.MediaList { for i, media := range legacy.MediaList {
timeline[i] = map[string]interface{}{ timeline[i] = map[string]interface{}{
@@ -346,7 +342,6 @@ func ConvertLegacyToNewFormat(jsonStr string) (string, error) {
} }
} }
// Build new format
newFormat := map[string]interface{}{ newFormat := map[string]interface{}{
"account_info": map[string]interface{}{ "account_info": map[string]interface{}{
"name": legacy.Username, "name": legacy.Username,
@@ -367,7 +362,6 @@ func ConvertLegacyToNewFormat(jsonStr string) (string, error) {
}, },
} }
// Convert back to JSON
newJSON, err := json.Marshal(newFormat) newJSON, err := json.Marshal(newFormat)
if err != nil { if err != nil {
return jsonStr, err return jsonStr, err
@@ -376,20 +370,17 @@ func ConvertLegacyToNewFormat(jsonStr string) (string, error) {
return string(newJSON), nil return string(newJSON), nil
} }
// ExportAccountToFile exports account JSON to a file
func ExportAccountToFile(id int64, outputDir string) (string, error) { func ExportAccountToFile(id int64, outputDir string) (string, error) {
acc, err := GetAccountByID(id) acc, err := GetAccountByID(id)
if err != nil { if err != nil {
return "", err return "", err
} }
// Create export directory if not exists
exportDir := filepath.Join(outputDir, "twitterxmediabatchdownloader_backups") exportDir := filepath.Join(outputDir, "twitterxmediabatchdownloader_backups")
if err := os.MkdirAll(exportDir, 0755); err != nil { if err := os.MkdirAll(exportDir, 0755); err != nil {
return "", err return "", err
} }
// Use username (nick) for filename
filename := acc.Username filename := acc.Username
if filename == "" { if filename == "" {
filename = acc.Name filename = acc.Name
@@ -404,24 +395,21 @@ func ExportAccountToFile(id int64, outputDir string) (string, error) {
return filePath, nil return filePath, nil
} }
// ExportAccountsToTXT exports selected accounts to TXT file (one username per line)
func ExportAccountsToTXT(ids []int64, outputDir string) (string, error) { func ExportAccountsToTXT(ids []int64, outputDir string) (string, error) {
if len(ids) == 0 { if len(ids) == 0 {
return "", fmt.Errorf("no accounts to export") return "", fmt.Errorf("no accounts to export")
} }
// Create export directory if not exists
exportDir := filepath.Join(outputDir, "twitterxmediabatchdownloader_backups") exportDir := filepath.Join(outputDir, "twitterxmediabatchdownloader_backups")
if err := os.MkdirAll(exportDir, 0755); err != nil { if err := os.MkdirAll(exportDir, 0755); err != nil {
return "", err return "", err
} }
// Get all accounts by IDs
var usernames []string var usernames []string
for _, id := range ids { for _, id := range ids {
acc, err := GetAccountByID(id) acc, err := GetAccountByID(id)
if err != nil { if err != nil {
continue // Skip if account not found continue
} }
if acc.Username != "" { if acc.Username != "" {
usernames = append(usernames, acc.Username) usernames = append(usernames, acc.Username)
@@ -432,7 +420,6 @@ func ExportAccountsToTXT(ids []int64, outputDir string) (string, error) {
return "", fmt.Errorf("no valid usernames found") return "", fmt.Errorf("no valid usernames found")
} }
// Create TXT content (one username per line)
txtContent := "" txtContent := ""
for i, username := range usernames { for i, username := range usernames {
if i > 0 { if i > 0 {
@@ -441,7 +428,6 @@ func ExportAccountsToTXT(ids []int64, outputDir string) (string, error) {
txtContent += username txtContent += username
} }
// Filename: twitterxmediabatchdownloader_multiple.txt
filePath := filepath.Join(exportDir, "twitterxmediabatchdownloader_multiple.txt") filePath := filepath.Join(exportDir, "twitterxmediabatchdownloader_multiple.txt")
if err := os.WriteFile(filePath, []byte(txtContent), 0644); err != nil { if err := os.WriteFile(filePath, []byte(txtContent), 0644); err != nil {
@@ -451,7 +437,6 @@ func ExportAccountsToTXT(ids []int64, outputDir string) (string, error) {
return filePath, nil return filePath, nil
} }
// ImportAccountFromFile imports account from JSON file (supports both old and new format)
func ImportAccountFromFile(filePath string) (string, error) { func ImportAccountFromFile(filePath string) (string, error) {
if db == nil { if db == nil {
if err := InitDB(); err != nil { if err := InitDB(); err != nil {
@@ -459,7 +444,6 @@ func ImportAccountFromFile(filePath string) (string, error) {
} }
} }
// Read file
data, err := os.ReadFile(filePath) data, err := os.ReadFile(filePath)
if err != nil { if err != nil {
return "", err return "", err
@@ -467,19 +451,16 @@ func ImportAccountFromFile(filePath string) (string, error) {
jsonStr := string(data) jsonStr := string(data)
// Convert legacy format if needed
convertedJSON, err := ConvertLegacyToNewFormat(jsonStr) convertedJSON, err := ConvertLegacyToNewFormat(jsonStr)
if err != nil { if err != nil {
return "", err return "", err
} }
// Parse the converted JSON to extract account info
var parsed map[string]interface{} var parsed map[string]interface{}
if err := json.Unmarshal([]byte(convertedJSON), &parsed); err != nil { if err := json.Unmarshal([]byte(convertedJSON), &parsed); err != nil {
return "", err return "", err
} }
// Extract account info
accountInfo, ok := parsed["account_info"].(map[string]interface{}) accountInfo, ok := parsed["account_info"].(map[string]interface{})
if !ok { if !ok {
return "", fmt.Errorf("invalid JSON format: missing account_info") return "", fmt.Errorf("invalid JSON format: missing account_info")
@@ -498,7 +479,6 @@ func ImportAccountFromFile(filePath string) (string, error) {
return "", fmt.Errorf("invalid JSON format: missing username") return "", fmt.Errorf("invalid JSON format: missing username")
} }
// Save to database with default media type "all" for imported files
err = SaveAccount(username, name, profileImage, totalURLs, convertedJSON, "all") err = SaveAccount(username, name, profileImage, totalURLs, convertedJSON, "all")
if err != nil { if err != nil {
return "", err return "", err
+27 -75
View File
@@ -15,32 +15,28 @@ import (
) )
const ( const (
// MaxConcurrentDownloads is the number of parallel downloads
MaxConcurrentDownloads = 10 MaxConcurrentDownloads = 10
) )
// MediaItem represents a media item with metadata for download
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"`
Content string `json:"content,omitempty"` // Tweet text content (for text-only tweets) Content string `json:"content,omitempty"`
OriginalFilename string `json:"original_filename,omitempty"` // Original Twitter media filename (15 char alphanumeric) OriginalFilename string `json:"original_filename,omitempty"`
} }
// DownloadMediaFiles downloads media files from URLs to the output directory (legacy)
func DownloadMediaFiles(urls []string, outputDir string, customProxy string) (downloaded int, failed int, err error) { func DownloadMediaFiles(urls []string, outputDir string, customProxy string) (downloaded int, failed int, err error) {
// Create output directory if it doesn't exist
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)
} }
// Create HTTP client with proxy support
client, err := CreateHTTPClient(customProxy, 60*time.Second) client, err := CreateHTTPClient(customProxy, 60*time.Second)
if err != nil { if err != nil {
// If proxy setup fails, use default client without proxy
client = &http.Client{ client = &http.Client{
Timeout: 60 * time.Second, Timeout: 60 * time.Second,
} }
@@ -50,7 +46,6 @@ 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)
// Skip if file already exists
if _, err := os.Stat(outputPath); err == nil { if _, err := os.Stat(outputPath); err == nil {
downloaded++ downloaded++
continue continue
@@ -66,21 +61,16 @@ func DownloadMediaFiles(urls []string, outputDir string, customProxy string) (do
return downloaded, failed, nil return downloaded, failed, nil
} }
// ProgressCallback is a function type for progress updates
type ProgressCallback func(current, total int) type ProgressCallback func(current, total int)
// ItemStatusCallback is a function type for per-item status updates
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"
// downloadTask represents a single download task
type downloadTask struct { type downloadTask struct {
item MediaItem item MediaItem
outputPath string outputPath string
index int index int
} }
// DownloadMediaWithMetadataProgressAndStatus downloads media files with progress and per-item status callbacks
// Returns: downloaded count, skipped count, failed count, error
func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir string, username string, progress ProgressCallback, itemStatus ItemStatusCallback, ctx context.Context, customProxy string) (downloaded int, skipped int, failed int, err error) { func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir string, username string, progress ProgressCallback, itemStatus ItemStatusCallback, ctx context.Context, customProxy string) (downloaded int, skipped int, failed int, err error) {
if ctx == nil { if ctx == nil {
ctx = context.Background() ctx = context.Background()
@@ -91,24 +81,20 @@ func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir str
return 0, 0, 0, nil return 0, 0, 0, nil
} }
// Prepare all tasks first (sequential to handle tweet media count) tweetMediaCount := make(map[string]map[int64]int)
// For bookmarks and likes, each item may have different username, so we track per username
tweetMediaCount := make(map[string]map[int64]int) // username -> tweet_id -> count
tasks := make([]downloadTask, 0, total) tasks := make([]downloadTask, 0, total)
for i, item := range items { for i, item := range items {
// Use item.Username if available (for bookmarks/likes with different authors), otherwise use provided username
itemUsername := item.Username itemUsername := item.Username
if itemUsername == "" { if itemUsername == "" {
itemUsername = username itemUsername = username
} }
// Initialize tweet media count for this username if needed
if tweetMediaCount[itemUsername] == nil { if tweetMediaCount[itemUsername] == nil {
tweetMediaCount[itemUsername] = make(map[int64]int) tweetMediaCount[itemUsername] = make(map[int64]int)
} }
// Determine subfolder based on type
var subfolder string var subfolder string
switch item.Type { switch item.Type {
case "photo": case "photo":
@@ -123,29 +109,23 @@ func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir str
subfolder = "other" subfolder = "other"
} }
// Create base directory for this username
baseDir := filepath.Join(outputDir, itemUsername) baseDir := filepath.Join(outputDir, itemUsername)
if err := os.MkdirAll(baseDir, 0755); err != nil { if err := os.MkdirAll(baseDir, 0755); err != nil {
continue continue
} }
// Create type subfolder
typeDir := filepath.Join(baseDir, subfolder) typeDir := filepath.Join(baseDir, subfolder)
if err := os.MkdirAll(typeDir, 0755); err != nil { if err := os.MkdirAll(typeDir, 0755); err != nil {
continue continue
} }
// Format timestamp from date
timestamp := formatTimestamp(item.Date) timestamp := formatTimestamp(item.Date)
// Get file extension
ext := getExtension(item.URL, item.Type) ext := getExtension(item.URL, item.Type)
// Increment counter for this username and tweet_id
tweetMediaCount[itemUsername][item.TweetID]++ tweetMediaCount[itemUsername][item.TweetID]++
mediaIndex := tweetMediaCount[itemUsername][item.TweetID] mediaIndex := tweetMediaCount[itemUsername][item.TweetID]
// Create filename: {username}_{timestamp}_{tweet_id}_{index}.{ext}
filename := fmt.Sprintf("%s_%s_%d_%02d%s", itemUsername, timestamp, item.TweetID, mediaIndex, ext) filename := fmt.Sprintf("%s_%s_%d_%02d%s", itemUsername, timestamp, item.TweetID, mediaIndex, ext)
outputPath := filepath.Join(typeDir, filename) outputPath := filepath.Join(typeDir, filename)
@@ -156,27 +136,23 @@ func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir str
}) })
} }
// Counters for parallel downloads
var downloadedCount int64 var downloadedCount int64
var skippedCount int64 var skippedCount int64
var failedCount int64 var failedCount int64
var completedCount int64 var completedCount int64
// Create worker pool
taskChan := make(chan downloadTask, len(tasks)) taskChan := make(chan downloadTask, len(tasks))
var wg sync.WaitGroup var wg sync.WaitGroup
// Start workers
numWorkers := MaxConcurrentDownloads numWorkers := MaxConcurrentDownloads
if numWorkers > len(tasks) { if numWorkers > len(tasks) {
numWorkers = len(tasks) numWorkers = len(tasks)
} }
// Create HTTP client once for all workers (shared client is more efficient)
var sharedClient *http.Client var sharedClient *http.Client
client, err := CreateHTTPClient(customProxy, 60*time.Second) client, err := CreateHTTPClient(customProxy, 60*time.Second)
if err != nil { if err != nil {
// If proxy setup fails, use default client without proxy
sharedClient = &http.Client{ sharedClient = &http.Client{
Timeout: 60 * time.Second, Timeout: 60 * time.Second,
} }
@@ -191,7 +167,7 @@ func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir str
client := sharedClient client := sharedClient
for task := range taskChan { for task := range taskChan {
// Check for cancellation
select { select {
case <-ctx.Done(): case <-ctx.Done():
return return
@@ -199,17 +175,17 @@ func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir str
} }
var status string var status string
// Skip if file already exists
if _, err := os.Stat(task.outputPath); err == nil { if _, err := os.Stat(task.outputPath); err == nil {
status = "skipped" status = "skipped"
// Emit status immediately for skipped files
if itemStatus != nil { if itemStatus != nil {
itemStatus(task.item.TweetID, task.index, status) itemStatus(task.item.TweetID, task.index, status)
} }
atomic.AddInt64(&skippedCount, 1) atomic.AddInt64(&skippedCount, 1)
continue // Skip to next task continue
} else if task.item.Type == "text" { } else if task.item.Type == "text" {
// For text tweets, write content to file
if err := os.WriteFile(task.outputPath, []byte(task.item.Content), 0644); err != nil { if err := os.WriteFile(task.outputPath, []byte(task.item.Content), 0644); err != nil {
atomic.AddInt64(&failedCount, 1) atomic.AddInt64(&failedCount, 1)
status = "failed" status = "failed"
@@ -221,30 +197,23 @@ func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir str
atomic.AddInt64(&failedCount, 1) atomic.AddInt64(&failedCount, 1)
status = "failed" status = "failed"
} else { } else {
// Embed metadata after successful download
tweetURL := fmt.Sprintf("https://x.com/i/status/%d", task.item.TweetID) tweetURL := fmt.Sprintf("https://x.com/i/status/%d", task.item.TweetID)
// Always extract original filename from URL (simpler approach)
originalFilename := ExtractOriginalFilename(task.item.URL) originalFilename := ExtractOriginalFilename(task.item.URL)
// For debugging: if original filename is still empty for video, it means it's not in the URL
// This is acceptable - video URLs from Twitter may not contain original filename
// Embed metadata (non-fatal: if it fails, file is still downloaded)
if err := EmbedMetadata(task.outputPath, task.item.Content, tweetURL, originalFilename); err != nil { if err := EmbedMetadata(task.outputPath, task.item.Content, tweetURL, originalFilename); err != nil {
// Log error but don't fail the download
// Metadata embedding is optional
} }
atomic.AddInt64(&downloadedCount, 1) atomic.AddInt64(&downloadedCount, 1)
status = "success" status = "success"
} }
// Emit per-item status
if itemStatus != nil { if itemStatus != nil {
itemStatus(task.item.TweetID, task.index, status) itemStatus(task.item.TweetID, task.index, status)
} }
// Update progress
completed := atomic.AddInt64(&completedCount, 1) completed := atomic.AddInt64(&completedCount, 1)
if progress != nil { if progress != nil {
progress(int(completed), total) progress(int(completed), total)
@@ -253,7 +222,6 @@ func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir str
}() }()
} }
// Send tasks to workers
for _, task := range tasks { for _, task := range tasks {
select { select {
case <-ctx.Done(): case <-ctx.Done():
@@ -265,13 +233,11 @@ func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir str
} }
close(taskChan) close(taskChan)
// Wait for all workers to finish
wg.Wait() wg.Wait()
return int(downloadedCount), int(skippedCount), int(failedCount), nil return int(downloadedCount), int(skippedCount), int(failedCount), nil
} }
// downloadFileWithContext downloads a single file with context support for cancellation
func downloadFileWithContext(ctx context.Context, client *http.Client, url, outputPath string) error { func downloadFileWithContext(ctx context.Context, client *http.Client, url, outputPath string) error {
req, err := http.NewRequestWithContext(ctx, "GET", url, nil) req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
if err != nil { if err != nil {
@@ -298,14 +264,13 @@ func downloadFileWithContext(ctx context.Context, client *http.Client, url, outp
return err return err
} }
// formatTimestamp converts date string to timestamp format
func formatTimestamp(dateStr string) string { func formatTimestamp(dateStr string) string {
// Try parsing various date formats
formats := []string{ formats := []string{
"2006-01-02T15:04:05", // ISO 8601 without timezone (from extractor) "2006-01-02T15:04:05",
"2006-01-02T15:04:05+00:00", // ISO 8601 with timezone "2006-01-02T15:04:05+00:00",
"2006-01-02T15:04:05-07:00", // ISO 8601 with timezone offset "2006-01-02T15:04:05-07:00",
time.RFC3339, // Standard RFC3339 time.RFC3339,
"2006-01-02T15:04:05.000Z", "2006-01-02T15:04:05.000Z",
"2006-01-02T15:04:05Z", "2006-01-02T15:04:05Z",
"2006-01-02 15:04:05", "2006-01-02 15:04:05",
@@ -318,35 +283,30 @@ func formatTimestamp(dateStr string) string {
} }
} }
// Fallback: use empty string to indicate parsing failed
return "00000000_000000" return "00000000_000000"
} }
// getExtension determines file extension from URL and type
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 {
return ".jpg" return ".jpg"
} }
// Check format query param for Twitter images
if format := parsedURL.Query().Get("format"); format != "" { if format := parsedURL.Query().Get("format"); format != "" {
return "." + format return "." + format
} }
// Get extension from path
path := parsedURL.Path path := parsedURL.Path
ext := filepath.Ext(path) ext := filepath.Ext(path)
if ext != "" { if ext != "" {
return ext return ext
} }
// Default based on type
switch mediaType { switch mediaType {
case "video": case "video":
return ".mp4" return ".mp4"
case "gif", "animated_gif": case "gif", "animated_gif":
return ".mp4" // Twitter GIFs are actually MP4 return ".mp4"
case "text": case "text":
return ".txt" return ".txt"
default: default:
@@ -354,28 +314,23 @@ func getExtension(mediaURL string, mediaType string) string {
} }
} }
// extractFilename extracts filename from URL (legacy)
func extractFilename(mediaURL string) string { func extractFilename(mediaURL string) string {
parsedURL, err := url.Parse(mediaURL) parsedURL, err := url.Parse(mediaURL)
if err != nil { if err != nil {
return fmt.Sprintf("media_%d", time.Now().UnixNano()) return fmt.Sprintf("media_%d", time.Now().UnixNano())
} }
// Get the path part
path := parsedURL.Path path := parsedURL.Path
// Extract base filename
base := filepath.Base(path) base := filepath.Base(path)
// Handle Twitter image URLs: /media/XXX -> XXX.jpg
if strings.Contains(mediaURL, "pbs.twimg.com/media/") { if strings.Contains(mediaURL, "pbs.twimg.com/media/") {
// Get format from query params
format := parsedURL.Query().Get("format") format := parsedURL.Query().Get("format")
if format == "" { if format == "" {
format = "jpg" format = "jpg"
} }
// Remove any existing extension
if idx := strings.LastIndex(base, "."); idx > 0 { if idx := strings.LastIndex(base, "."); idx > 0 {
base = base[:idx] base = base[:idx]
} }
@@ -383,12 +338,10 @@ func extractFilename(mediaURL string) string {
return base + "." + format return base + "." + format
} }
// Handle Twitter video URLs
if strings.Contains(mediaURL, "video.twimg.com") { if strings.Contains(mediaURL, "video.twimg.com") {
return base return base
} }
// Default: use base name or generate one
if base == "" || base == "." { if base == "" || base == "." {
return fmt.Sprintf("media_%d", time.Now().UnixNano()) return fmt.Sprintf("media_%d", time.Now().UnixNano())
} }
@@ -396,7 +349,6 @@ func extractFilename(mediaURL string) string {
return base return base
} }
// downloadFile downloads a single file from URL
func downloadFile(client *http.Client, url, outputPath string) error { func downloadFile(client *http.Client, url, outputPath string) error {
resp, err := client.Get(url) resp, err := client.Get(url)
if err != nil { if err != nil {
-8
View File
@@ -1,8 +0,0 @@
//go:build linux || darwin
package backend
import _ "embed"
//go:embed bin/extractor
var extractorBin []byte
-8
View File
@@ -1,8 +0,0 @@
//go:build windows
package backend
import _ "embed"
//go:embed bin/extractor.exe
var extractorBin []byte
+18 -58
View File
@@ -14,26 +14,20 @@ import (
"strings" "strings"
) )
// ExifTool download URLs (SourceForge)
const ( const (
// Windows 64-bit
exiftoolWindows64URL = "https://sourceforge.net/projects/exiftool/files/exiftool-13.43_64.zip/download" exiftoolWindows64URL = "https://sourceforge.net/projects/exiftool/files/exiftool-13.43_64.zip/download"
// Windows 32-bit
exiftoolWindows32URL = "https://sourceforge.net/projects/exiftool/files/exiftool-13.43_32.zip/download" exiftoolWindows32URL = "https://sourceforge.net/projects/exiftool/files/exiftool-13.43_32.zip/download"
// Unix (Linux/macOS): tar.gz
exiftoolUnixURL = "https://sourceforge.net/projects/exiftool/files/Image-ExifTool-13.43.tar.gz/download" exiftoolUnixURL = "https://sourceforge.net/projects/exiftool/files/Image-ExifTool-13.43.tar.gz/download"
) )
// ExifTool SHA256 hashes for verification
// Note: Hashes will be calculated during download if not provided
// For now, we'll skip hash verification for version 13.43 (can be added later if needed)
const ( const (
exiftoolWindows64Hash = "" // Hash not provided, will skip verification exiftoolWindows64Hash = ""
exiftoolWindows32Hash = "" // Hash not provided, will skip verification exiftoolWindows32Hash = ""
exiftoolUnixHash = "" // Hash not provided, will skip verification exiftoolUnixHash = ""
) )
// GetExifToolPath returns the path to exiftool binary
func GetExifToolPath() string { func GetExifToolPath() string {
homeDir, _ := os.UserHomeDir() homeDir, _ := os.UserHomeDir()
baseDir := filepath.Join(homeDir, ".twitterxmediabatchdownloader") baseDir := filepath.Join(homeDir, ".twitterxmediabatchdownloader")
@@ -42,27 +36,25 @@ func GetExifToolPath() string {
case "windows": case "windows":
return filepath.Join(baseDir, "exiftool.exe") return filepath.Join(baseDir, "exiftool.exe")
default: default:
// For Unix (Linux/macOS), exiftool is in Image-ExifTool-VERSION/exiftool
// We need to find the folder dynamically since version may vary
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 {
// Use the first match (should only be one)
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
} }
} }
// Fallback: return path that will be created after extraction
return filepath.Join(baseDir, "exiftool") return filepath.Join(baseDir, "exiftool")
} }
} }
// IsExifToolInstalled checks if exiftool is available
func IsExifToolInstalled() bool { func IsExifToolInstalled() bool {
exiftoolPath := GetExifToolPath() exiftoolPath := GetExifToolPath()
if _, err := os.Stat(exiftoolPath); err == nil { if _, err := os.Stat(exiftoolPath); err == nil {
// Test if it's executable by running version command
cmd := exec.Command(exiftoolPath, "-ver") cmd := exec.Command(exiftoolPath, "-ver")
hideWindow(cmd) hideWindow(cmd)
if err := cmd.Run(); err == nil { if err := cmd.Run(); err == nil {
@@ -72,7 +64,6 @@ func IsExifToolInstalled() bool {
return false return false
} }
// calculateSHA256 calculates SHA256 hash of a file
func calculateSHA256(filePath string) (string, error) { func calculateSHA256(filePath string) (string, error) {
file, err := os.Open(filePath) file, err := os.Open(filePath)
if err != nil { if err != nil {
@@ -88,7 +79,6 @@ func calculateSHA256(filePath string) (string, error) {
return hex.EncodeToString(hash.Sum(nil)), nil return hex.EncodeToString(hash.Sum(nil)), nil
} }
// verifyHash verifies the SHA256 hash of a downloaded file
func verifyHash(filePath, expectedHash string) error { func verifyHash(filePath, expectedHash string) error {
actualHash, err := calculateSHA256(filePath) actualHash, err := calculateSHA256(filePath)
if err != nil { if err != nil {
@@ -102,12 +92,10 @@ func verifyHash(filePath, expectedHash string) error {
return nil return nil
} }
// is64Bit checks if the system is 64-bit
func is64Bit() bool { func is64Bit() bool {
return runtime.GOARCH == "amd64" || runtime.GOARCH == "arm64" return runtime.GOARCH == "amd64" || runtime.GOARCH == "arm64"
} }
// DownloadExifTool downloads exiftool binary for current platform
func DownloadExifTool(progressCallback func(downloaded, total int64)) error { func DownloadExifTool(progressCallback func(downloaded, total int64)) error {
var downloadURL string var downloadURL string
var expectedHash string var expectedHash string
@@ -122,14 +110,13 @@ func DownloadExifTool(progressCallback func(downloaded, total int64)) error {
expectedHash = exiftoolWindows32Hash expectedHash = exiftoolWindows32Hash
} }
case "linux", "darwin": case "linux", "darwin":
// Linux and macOS use the same tar.gz archive
downloadURL = exiftoolUnixURL downloadURL = exiftoolUnixURL
expectedHash = exiftoolUnixHash expectedHash = exiftoolUnixHash
default: default:
return fmt.Errorf("unsupported platform: %s", runtime.GOOS) return fmt.Errorf("unsupported platform: %s", runtime.GOOS)
} }
// Create temp file for download
tempFile, err := os.CreateTemp("", "exiftool-*") tempFile, err := os.CreateTemp("", "exiftool-*")
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)
@@ -138,7 +125,6 @@ func DownloadExifTool(progressCallback func(downloaded, total int64)) error {
defer os.Remove(tempPath) defer os.Remove(tempPath)
defer tempFile.Close() defer tempFile.Close()
// Download file
resp, err := http.Get(downloadURL) resp, err := http.Get(downloadURL)
if err != nil { if err != nil {
return fmt.Errorf("failed to download exiftool: %v", err) return fmt.Errorf("failed to download exiftool: %v", err)
@@ -149,7 +135,6 @@ func DownloadExifTool(progressCallback func(downloaded, total int64)) error {
return fmt.Errorf("failed to download exiftool: status %d", resp.StatusCode) return fmt.Errorf("failed to download exiftool: status %d", resp.StatusCode)
} }
// Copy with progress
total := resp.ContentLength total := resp.ContentLength
var downloaded int64 var downloaded int64
buf := make([]byte, 32*1024) buf := make([]byte, 32*1024)
@@ -175,14 +160,12 @@ func DownloadExifTool(progressCallback func(downloaded, total int64)) error {
} }
tempFile.Close() tempFile.Close()
// Verify hash before extraction
if expectedHash != "" { if expectedHash != "" {
if err := verifyHash(tempPath, expectedHash); err != nil { if err := verifyHash(tempPath, expectedHash); err != nil {
return fmt.Errorf("hash verification failed: %v", err) return fmt.Errorf("hash verification failed: %v", err)
} }
} }
// Extract exiftool binary
exiftoolPath := GetExifToolPath() exiftoolPath := GetExifToolPath()
baseDir := filepath.Dir(exiftoolPath) baseDir := filepath.Dir(exiftoolPath)
if err := os.MkdirAll(baseDir, 0755); err != nil { if err := os.MkdirAll(baseDir, 0755); err != nil {
@@ -193,15 +176,13 @@ 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":
// For Linux/macOS, we need to extract and build
// For simplicity, we'll extract the exiftool script from tar.gz
return extractExifToolFromTarGz(tempPath, exiftoolPath) return extractExifToolFromTarGz(tempPath, exiftoolPath)
} }
return nil return nil
} }
// extractExifToolFromZip extracts exiftool from Windows zip archive
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 {
@@ -209,11 +190,10 @@ func extractExifToolFromZip(zipPath, destPath string) error {
} }
defer r.Close() defer r.Close()
// Look for exiftool(-k).exe or exiftool.exe in the zip
var exiftoolFile *zip.File var exiftoolFile *zip.File
for _, f := range r.File { for _, f := range r.File {
name := filepath.Base(f.Name) name := filepath.Base(f.Name)
// ExifTool Windows zip contains exiftool(-k).exe
if name == "exiftool(-k).exe" || name == "exiftool.exe" { if name == "exiftool(-k).exe" || name == "exiftool.exe" {
exiftoolFile = f exiftoolFile = f
break break
@@ -240,12 +220,11 @@ func extractExifToolFromZip(zipPath, destPath string) error {
return fmt.Errorf("failed to extract file: %v", err) return fmt.Errorf("failed to extract file: %v", err)
} }
// Also need to extract the lib directory for Windows (exiftool_files folder)
libDir := filepath.Join(filepath.Dir(destPath), "exiftool_files") libDir := filepath.Join(filepath.Dir(destPath), "exiftool_files")
for _, f := range r.File { for _, f := range r.File {
// Check if file is in exiftool_files directory
if strings.Contains(f.Name, "exiftool_files") && !strings.HasSuffix(f.Name, "/") { if strings.Contains(f.Name, "exiftool_files") && !strings.HasSuffix(f.Name, "/") {
// Extract relative path from exiftool_files
parts := strings.Split(f.Name, "exiftool_files/") parts := strings.Split(f.Name, "exiftool_files/")
if len(parts) < 2 { if len(parts) < 2 {
continue continue
@@ -257,21 +236,18 @@ func extractExifToolFromZip(zipPath, destPath string) error {
targetPath := filepath.Join(libDir, relPath) targetPath := filepath.Join(libDir, relPath)
// Create directory structure
if err := os.MkdirAll(filepath.Dir(targetPath), 0755); err != nil { if err := os.MkdirAll(filepath.Dir(targetPath), 0755); err != nil {
continue continue
} }
// Skip if it's a directory entry
if f.FileInfo().IsDir() { if f.FileInfo().IsDir() {
os.MkdirAll(targetPath, 0755) os.MkdirAll(targetPath, 0755)
continue continue
} }
// Extract file
rc, err := f.Open() rc, err := f.Open()
if err != nil { if err != nil {
continue // Skip on error continue
} }
outFile, err := os.Create(targetPath) outFile, err := os.Create(targetPath)
@@ -289,15 +265,10 @@ func extractExifToolFromZip(zipPath, destPath string) error {
return nil return nil
} }
// extractExifToolFromTarGz extracts exiftool from tar.gz archive (Linux/macOS)
func extractExifToolFromTarGz(tarGzPath, destPath string) error { func extractExifToolFromTarGz(tarGzPath, destPath string) error {
// For Linux/macOS, ExifTool is a Perl script that requires the lib directory
// We'll extract the entire folder and use exiftool directly from Image-ExifTool-VERSION/exiftool
// This is simpler than implementing tar.gz extraction in Go
baseDir := filepath.Dir(destPath) baseDir := filepath.Dir(destPath)
// Use system tar command to extract
cmd := exec.Command("tar", "-xzf", tarGzPath, "-C", baseDir) cmd := exec.Command("tar", "-xzf", tarGzPath, "-C", baseDir)
hideWindow(cmd) hideWindow(cmd)
output, err := cmd.CombinedOutput() output, err := cmd.CombinedOutput()
@@ -305,28 +276,23 @@ func extractExifToolFromTarGz(tarGzPath, destPath string) error {
return fmt.Errorf("failed to extract tar.gz: %v, output: %s", err, string(output)) return fmt.Errorf("failed to extract tar.gz: %v, output: %s", err, string(output))
} }
// Find the extracted exiftool script
// The archive extracts to Image-ExifTool-VERSION/exiftool
// We need to find the folder dynamically since version may vary
var extractedDir string var extractedDir string
var exiftoolScript string var exiftoolScript string
// Use glob pattern to find Image-ExifTool-* directories
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 {
// Use the first match (should only be one)
extractedDir = matches[0] extractedDir = matches[0]
exiftoolScript = filepath.Join(extractedDir, "exiftool") exiftoolScript = filepath.Join(extractedDir, "exiftool")
} else { } else {
// Fallback: try common version or alternative location
extractedDir = filepath.Join(baseDir, "Image-ExifTool-13.43") extractedDir = filepath.Join(baseDir, "Image-ExifTool-13.43")
exiftoolScript = filepath.Join(extractedDir, "exiftool") exiftoolScript = filepath.Join(extractedDir, "exiftool")
} }
// Check if exiftool script exists
if _, err := os.Stat(exiftoolScript); err != nil { if _, err := os.Stat(exiftoolScript); err != nil {
// Try alternative location
extractedDir = filepath.Join(baseDir, "exiftool") extractedDir = filepath.Join(baseDir, "exiftool")
exiftoolScript = filepath.Join(extractedDir, "exiftool") exiftoolScript = filepath.Join(extractedDir, "exiftool")
if _, err := os.Stat(exiftoolScript); err != nil { if _, err := os.Stat(exiftoolScript); err != nil {
@@ -334,15 +300,9 @@ func extractExifToolFromTarGz(tarGzPath, destPath string) error {
} }
} }
// Make exiftool executable (required for Unix systems)
if err := os.Chmod(exiftoolScript, 0755); err != nil { if err := os.Chmod(exiftoolScript, 0755); err != nil {
return fmt.Errorf("failed to make exiftool executable: %v", err) return fmt.Errorf("failed to make exiftool executable: %v", err)
} }
// For Unix, we keep the entire folder structure and use exiftool directly from it
// The folder will remain in baseDir and GetExifToolPath() will find it via glob pattern
// No need to copy or remove anything
return nil return nil
} }
+369
View File
@@ -0,0 +1,369 @@
package backend
import (
"archive/zip"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"time"
)
const extractorReleaseAPIURL = "https://api.github.com/repos/afkarxyz/xtractor-binaries/releases/latest"
type githubRelease struct {
TagName string `json:"tag_name"`
Assets []githubReleaseAsset `json:"assets"`
}
type githubReleaseAsset struct {
Name string `json:"name"`
BrowserDownloadURL string `json:"browser_download_url"`
Digest string `json:"digest"`
}
func IsExtractorInstalled() bool {
info, err := os.Stat(getExtractorPath())
return err == nil && !info.IsDir()
}
func DownloadExtractor(progressCallback func(downloaded, total int64)) error {
assetName, err := getExtractorAssetName()
if err != nil {
return err
}
release, err := fetchLatestExtractorRelease()
if err != nil {
return err
}
asset, err := findExtractorAsset(release.Assets, assetName)
if err != nil {
return err
}
tempFile, err := os.CreateTemp("", "xtractor-*.zip")
if err != nil {
return fmt.Errorf("failed to create temp file: %v", err)
}
tempPath := tempFile.Name()
defer os.Remove(tempPath)
defer tempFile.Close()
if err := downloadExtractorArchive(asset.BrowserDownloadURL, tempFile, progressCallback); err != nil {
return err
}
if err := tempFile.Close(); err != nil {
return fmt.Errorf("failed to finalize xtractor archive: %v", err)
}
if err := verifyDownloadedDigest(tempPath, asset.Digest); err != nil {
return err
}
KillAllExtractorProcesses()
exePath := getExtractorPath()
if err := os.MkdirAll(filepath.Dir(exePath), 0755); err != nil {
return fmt.Errorf("failed to create xtractor directory: %v", err)
}
if err := extractExtractorArchive(tempPath, exePath); err != nil {
return err
}
_ = removeLegacyExtractorBinary()
return nil
}
func requireExtractorPath() (string, error) {
exePath := getExtractorPath()
info, err := os.Stat(exePath)
if err != nil || info.IsDir() {
return "", fmt.Errorf("xtractor dependency is not installed. Please download it from the startup prompt or Settings > Core Xtractor")
}
if runtime.GOOS != "windows" {
_ = os.Chmod(exePath, 0755)
}
return exePath, nil
}
func getExtractorAssetName() (string, error) {
switch runtime.GOOS {
case "windows":
switch runtime.GOARCH {
case "amd64", "arm64":
return "windows-amd64.zip", nil
}
case "linux":
if runtime.GOARCH == "amd64" {
return "linux-amd64.zip", nil
}
case "darwin":
switch resolveMacOSExtractorArch(runtime.GOARCH, detectMacOSHardwareArch()) {
case "amd64":
return "macos-amd64.zip", nil
case "arm64":
return "macos-arm64.zip", nil
}
}
return "", fmt.Errorf("unsupported platform for prebuilt xtractor: %s/%s", runtime.GOOS, runtime.GOARCH)
}
func resolveMacOSExtractorArch(processArch, hardwareArch string) string {
if hardwareArch == "arm64" {
return "arm64"
}
return processArch
}
func detectMacOSHardwareArch() string {
if runtime.GOOS != "darwin" {
return ""
}
// On Apple Silicon, this stays "1" even if the app itself runs under Rosetta.
cmd := exec.Command("sysctl", "-in", "hw.optional.arm64")
hideWindow(cmd)
output, err := cmd.Output()
if err != nil {
return ""
}
if strings.TrimSpace(string(output)) == "1" {
return "arm64"
}
return ""
}
func fetchLatestExtractorRelease() (*githubRelease, error) {
client, err := CreateHTTPClient("", 30*time.Second)
if err != nil {
return nil, fmt.Errorf("failed to configure xtractor network client: %v", err)
}
req, err := http.NewRequest(http.MethodGet, extractorReleaseAPIURL, nil)
if err != nil {
return nil, fmt.Errorf("failed to create xtractor release request: %v", err)
}
req.Header.Set("Accept", "application/vnd.github+json")
req.Header.Set("User-Agent", "Twitter-X-Media-Batch-Downloader")
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to fetch xtractor release info: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("failed to fetch xtractor 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 xtractor release info: %v", err)
}
return &release, nil
}
func findExtractorAsset(assets []githubReleaseAsset, assetName string) (*githubReleaseAsset, error) {
for i := range assets {
if assets[i].Name == assetName {
return &assets[i], nil
}
}
return nil, fmt.Errorf("xtractor asset %q not found in latest release", assetName)
}
func downloadExtractorArchive(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 xtractor download client: %v", err)
}
req, err := http.NewRequest(http.MethodGet, downloadURL, nil)
if err != nil {
return fmt.Errorf("failed to create xtractor download 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 download xtractor: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("failed to download xtractor: status %d", resp.StatusCode)
}
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 xtractor 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 xtractor: %v", err)
}
}
return nil
}
func verifyDownloadedDigest(filePath, digest string) error {
digest = strings.TrimSpace(digest)
if digest == "" {
return nil
}
expectedHash := strings.TrimPrefix(strings.ToLower(digest), "sha256:")
file, err := os.Open(filePath)
if err != nil {
return fmt.Errorf("failed to open downloaded xtractor archive: %v", err)
}
defer file.Close()
hash := sha256.New()
if _, err := io.Copy(hash, file); err != nil {
return fmt.Errorf("failed to verify xtractor archive: %v", err)
}
actualHash := hex.EncodeToString(hash.Sum(nil))
if actualHash != expectedHash {
return fmt.Errorf("xtractor archive checksum mismatch")
}
return nil
}
func extractExtractorArchive(zipPath, destPath string) error {
reader, err := zip.OpenReader(zipPath)
if err != nil {
return fmt.Errorf("failed to open xtractor archive: %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: %v", err)
}
defer in.Close()
tempDest := destPath + ".download"
removeTemp := true
defer func() {
if removeTemp {
_ = os.Remove(tempDest)
}
}()
out, err := os.OpenFile(tempDest, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0755)
if err != nil {
return fmt.Errorf("failed to create xtractor binary: %v", err)
}
if _, err := io.Copy(out, in); err != nil {
out.Close()
return fmt.Errorf("failed to extract xtractor binary: %v", err)
}
if err := out.Close(); err != nil {
return fmt.Errorf("failed to finalize xtractor binary: %v", err)
}
if err := os.Chmod(tempDest, 0755); err != nil && runtime.GOOS != "windows" {
return fmt.Errorf("failed to make xtractor executable: %v", err)
}
if err := os.Remove(destPath); err != nil && !os.IsNotExist(err) {
return fmt.Errorf("failed to replace existing xtractor: %v", err)
}
if err := os.Rename(tempDest, destPath); err != nil {
return fmt.Errorf("failed to install xtractor: %v", err)
}
removeTemp = false
return nil
}
func findExtractorBinaryEntry(entries []*zip.File) (*zip.File, error) {
var fallback *zip.File
for _, entry := range entries {
if entry.FileInfo().IsDir() {
continue
}
if fallback == nil {
fallback = entry
}
name := strings.ToLower(filepath.Base(entry.Name))
if strings.Contains(name, "xtractor") || strings.Contains(name, "extractor") {
return entry, nil
}
}
if fallback != nil {
return fallback, nil
}
return nil, fmt.Errorf("xtractor binary not found in archive")
}
func getLegacyExtractorPath() string {
homeDir, _ := os.UserHomeDir()
baseDir := filepath.Join(homeDir, ".twitterxmediabatchdownloader")
return filepath.Join(baseDir, getLegacyExecutableName())
}
func removeLegacyExtractorBinary() error {
oldPath := getLegacyExtractorPath()
info, err := os.Stat(oldPath)
if err != nil || info.IsDir() {
return nil
}
if err := os.Remove(oldPath); err != nil && !os.IsNotExist(err) {
return fmt.Errorf("failed to remove legacy extractor binary: %v", err)
}
return nil
}
+6 -24
View File
@@ -15,14 +15,12 @@ import (
"github.com/ulikunitz/xz" "github.com/ulikunitz/xz"
) )
// FFmpeg download URLs
const ( const (
ffmpegWindowsURL = "https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/ffmpeg-master-latest-win64-gpl.zip" ffmpegWindowsURL = "https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/ffmpeg-master-latest-win64-gpl.zip"
ffmpegLinuxURL = "https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/ffmpeg-master-latest-linux64-gpl.tar.xz" ffmpegLinuxURL = "https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/ffmpeg-master-latest-linux64-gpl.tar.xz"
ffmpegMacOSURL = "https://evermeet.cx/ffmpeg/getrelease/ffmpeg/zip" ffmpegMacOSURL = "https://evermeet.cx/ffmpeg/getrelease/ffmpeg/zip"
) )
// GetFFmpegPath returns the path to ffmpeg binary
func GetFFmpegPath() string { func GetFFmpegPath() string {
homeDir, _ := os.UserHomeDir() homeDir, _ := os.UserHomeDir()
baseDir := filepath.Join(homeDir, ".twitterxmediabatchdownloader") baseDir := filepath.Join(homeDir, ".twitterxmediabatchdownloader")
@@ -35,7 +33,6 @@ func GetFFmpegPath() string {
} }
} }
// IsFFmpegInstalled checks if ffmpeg is available
func IsFFmpegInstalled() bool { func IsFFmpegInstalled() bool {
ffmpegPath := GetFFmpegPath() ffmpegPath := GetFFmpegPath()
if _, err := os.Stat(ffmpegPath); err == nil { if _, err := os.Stat(ffmpegPath); err == nil {
@@ -44,7 +41,6 @@ func IsFFmpegInstalled() bool {
return false return false
} }
// DownloadFFmpeg downloads ffmpeg binary for current platform
func DownloadFFmpeg(progressCallback func(downloaded, total int64)) error { func DownloadFFmpeg(progressCallback func(downloaded, total int64)) error {
var downloadURL string var downloadURL string
@@ -59,7 +55,6 @@ func DownloadFFmpeg(progressCallback func(downloaded, total int64)) error {
return fmt.Errorf("unsupported platform: %s", runtime.GOOS) return fmt.Errorf("unsupported platform: %s", runtime.GOOS)
} }
// Create temp file for download
tempFile, err := os.CreateTemp("", "ffmpeg-*") tempFile, err := os.CreateTemp("", "ffmpeg-*")
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)
@@ -68,7 +63,6 @@ func DownloadFFmpeg(progressCallback func(downloaded, total int64)) error {
defer os.Remove(tempPath) defer os.Remove(tempPath)
defer tempFile.Close() defer tempFile.Close()
// Download file
resp, err := http.Get(downloadURL) resp, err := http.Get(downloadURL)
if err != nil { if err != nil {
return fmt.Errorf("failed to download ffmpeg: %v", err) return fmt.Errorf("failed to download ffmpeg: %v", err)
@@ -79,7 +73,6 @@ func DownloadFFmpeg(progressCallback func(downloaded, total int64)) error {
return fmt.Errorf("failed to download ffmpeg: status %d", resp.StatusCode) return fmt.Errorf("failed to download ffmpeg: status %d", resp.StatusCode)
} }
// Copy with progress
total := resp.ContentLength total := resp.ContentLength
var downloaded int64 var downloaded int64
buf := make([]byte, 32*1024) buf := make([]byte, 32*1024)
@@ -105,7 +98,6 @@ func DownloadFFmpeg(progressCallback func(downloaded, total int64)) error {
} }
tempFile.Close() tempFile.Close()
// Extract ffmpeg binary
ffmpegPath := GetFFmpegPath() ffmpegPath := GetFFmpegPath()
baseDir := filepath.Dir(ffmpegPath) baseDir := filepath.Dir(ffmpegPath)
if err := os.MkdirAll(baseDir, 0755); err != nil { if err := os.MkdirAll(baseDir, 0755); err != nil {
@@ -122,7 +114,6 @@ func DownloadFFmpeg(progressCallback func(downloaded, total int64)) error {
return nil return nil
} }
// extractFromZip extracts ffmpeg from zip archive
func extractFromZip(zipPath, destPath string) error { func extractFromZip(zipPath, destPath string) error {
r, err := zip.OpenReader(zipPath) r, err := zip.OpenReader(zipPath)
if err != nil { if err != nil {
@@ -131,7 +122,7 @@ func extractFromZip(zipPath, destPath string) error {
defer r.Close() defer r.Close()
for _, f := range r.File { for _, f := range r.File {
// Look for ffmpeg binary
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() rc, err := f.Open()
@@ -150,7 +141,6 @@ func extractFromZip(zipPath, destPath string) error {
return fmt.Errorf("failed to extract file: %v", err) return fmt.Errorf("failed to extract file: %v", err)
} }
// Make executable on Unix
if runtime.GOOS != "windows" { if runtime.GOOS != "windows" {
os.Chmod(destPath, 0755) os.Chmod(destPath, 0755)
} }
@@ -162,7 +152,6 @@ func extractFromZip(zipPath, destPath string) error {
return fmt.Errorf("ffmpeg binary not found in archive") return fmt.Errorf("ffmpeg binary not found in archive")
} }
// extractFromTarXz extracts ffmpeg from tar.xz archive
func extractFromTarXz(tarXzPath, destPath string) error { func extractFromTarXz(tarXzPath, destPath string) error {
file, err := os.Open(tarXzPath) file, err := os.Open(tarXzPath)
if err != nil { if err != nil {
@@ -186,7 +175,6 @@ func extractFromTarXz(tarXzPath, destPath string) error {
return fmt.Errorf("failed to read tar: %v", err) return fmt.Errorf("failed to read tar: %v", err)
} }
// Look for ffmpeg binary
name := filepath.Base(header.Name) name := filepath.Base(header.Name)
if name == "ffmpeg" && header.Typeflag == tar.TypeReg { if name == "ffmpeg" && header.Typeflag == tar.TypeReg {
out, err := os.Create(destPath) out, err := os.Create(destPath)
@@ -207,9 +195,6 @@ func extractFromTarXz(tarXzPath, destPath string) error {
return fmt.Errorf("ffmpeg binary not found in archive") return fmt.Errorf("ffmpeg binary not found in archive")
} }
// ConvertMP4ToGIF converts an MP4 file to GIF using ffmpeg
// quality: "fast" for simple conversion, "better" for optimized palette
// resolution: "original", "high" (800px), "medium" (600px), "low" (400px)
func ConvertMP4ToGIF(inputPath, outputPath, quality, resolution string) error { func ConvertMP4ToGIF(inputPath, outputPath, quality, resolution string) error {
ffmpegPath := GetFFmpegPath() ffmpegPath := GetFFmpegPath()
@@ -220,7 +205,7 @@ func ConvertMP4ToGIF(inputPath, outputPath, quality, resolution string) error {
var args []string var args []string
if quality == "fast" { if quality == "fast" {
// Fast mode: simple conversion with resolution scaling
var scaleFilter string var scaleFilter string
switch resolution { switch resolution {
case "high": case "high":
@@ -229,7 +214,7 @@ func ConvertMP4ToGIF(inputPath, outputPath, quality, resolution string) error {
scaleFilter = "scale=600:-1" scaleFilter = "scale=600:-1"
case "low": case "low":
scaleFilter = "scale=400:-1" scaleFilter = "scale=400:-1"
default: // original - no scaling default:
scaleFilter = "" scaleFilter = ""
} }
@@ -250,7 +235,7 @@ func ConvertMP4ToGIF(inputPath, outputPath, quality, resolution string) error {
} }
} }
} else { } else {
// Better mode: optimized palette with dithering
var filter string var filter string
switch resolution { switch resolution {
@@ -260,11 +245,10 @@ func ConvertMP4ToGIF(inputPath, outputPath, quality, resolution string) error {
filter = "scale=600:-1:flags=lanczos,palettegen=stats_mode=full[palette];[0:v]scale=600:-1:flags=lanczos[scaled];[scaled][palette]paletteuse=dither=sierra2_4a" filter = "scale=600:-1:flags=lanczos,palettegen=stats_mode=full[palette];[0:v]scale=600:-1:flags=lanczos[scaled];[scaled][palette]paletteuse=dither=sierra2_4a"
case "low": case "low":
filter = "scale=400:-1:flags=lanczos,palettegen=stats_mode=full[palette];[0:v]scale=400:-1:flags=lanczos[scaled];[scaled][palette]paletteuse=dither=sierra2_4a" filter = "scale=400:-1:flags=lanczos,palettegen=stats_mode=full[palette];[0:v]scale=400:-1:flags=lanczos[scaled];[scaled][palette]paletteuse=dither=sierra2_4a"
default: // original default:
filter = "palettegen=stats_mode=full[palette];[0:v][palette]paletteuse=dither=sierra2_4a" filter = "palettegen=stats_mode=full[palette];[0:v][palette]paletteuse=dither=sierra2_4a"
} }
// Set FPS based on resolution
fps := "15" fps := "15"
if resolution == "medium" { if resolution == "medium" {
fps = "10" fps = "10"
@@ -282,7 +266,7 @@ func ConvertMP4ToGIF(inputPath, outputPath, quality, resolution string) error {
} }
cmd := exec.Command(ffmpegPath, args...) cmd := exec.Command(ffmpegPath, args...)
hideWindow(cmd) // Hide console window on Windows hideWindow(cmd)
output, err := cmd.CombinedOutput() output, err := cmd.CombinedOutput()
if err != nil { if err != nil {
return fmt.Errorf("ffmpeg error: %v, output: %s", err, string(output)) return fmt.Errorf("ffmpeg error: %v, output: %s", err, string(output))
@@ -291,13 +275,11 @@ func ConvertMP4ToGIF(inputPath, outputPath, quality, resolution string) error {
return nil return nil
} }
// ConvertGIFsInFolder converts all MP4 files in gifs folder to actual GIF format
func ConvertGIFsInFolder(folderPath, quality, resolution string, deleteOriginal bool) (converted int, failed int, err error) { func ConvertGIFsInFolder(folderPath, quality, resolution string, deleteOriginal bool) (converted int, failed int, err error) {
if !IsFFmpegInstalled() { if !IsFFmpegInstalled() {
return 0, 0, fmt.Errorf("ffmpeg not installed") return 0, 0, fmt.Errorf("ffmpeg not installed")
} }
// Clean the path to handle cross-platform path separators
cleanPath := filepath.Clean(folderPath) cleanPath := filepath.Clean(folderPath)
gifsFolder := filepath.Join(cleanPath, "gifs") gifsFolder := filepath.Join(cleanPath, "gifs")
if _, err := os.Stat(gifsFolder); os.IsNotExist(err) { if _, err := os.Stat(gifsFolder); os.IsNotExist(err) {
+4 -10
View File
@@ -15,9 +15,9 @@ func OpenFolderInExplorer(path string) error {
switch runtime.GOOS { switch runtime.GOOS {
case "windows": case "windows":
// Use cmd /c start to open explorer - more reliable
cmd = exec.Command("cmd", "/c", "start", "", path) cmd = exec.Command("cmd", "/c", "start", "", path)
case "darwin": // macOS case "darwin":
cmd = exec.Command("open", path) cmd = exec.Command("open", path)
case "linux": case "linux":
cmd = exec.Command("xdg-open", path) cmd = exec.Command("xdg-open", path)
@@ -25,12 +25,12 @@ func OpenFolderInExplorer(path string) error {
cmd = exec.Command("xdg-open", path) cmd = exec.Command("xdg-open", path)
} }
hideWindow(cmd) // Hide console window on Windows hideWindow(cmd)
return cmd.Run() return cmd.Run()
} }
func SelectFolderDialog(ctx context.Context, defaultPath string) (string, error) { func SelectFolderDialog(ctx context.Context, defaultPath string) (string, error) {
// If defaultPath is empty, use default download path
if defaultPath == "" { if defaultPath == "" {
defaultPath = GetDefaultDownloadPath() defaultPath = GetDefaultDownloadPath()
} }
@@ -45,7 +45,6 @@ func SelectFolderDialog(ctx context.Context, defaultPath string) (string, error)
return "", err return "", err
} }
// If user cancelled, selectedPath will be empty
if selectedPath == "" { if selectedPath == "" {
return "", nil return "", nil
} }
@@ -53,7 +52,6 @@ func SelectFolderDialog(ctx context.Context, defaultPath string) (string, error)
return selectedPath, nil return selectedPath, nil
} }
// CheckFolderExists checks if a folder exists at the given path
func CheckFolderExists(basePath, username string) bool { func CheckFolderExists(basePath, username string) bool {
folderPath := filepath.Join(basePath, username) folderPath := filepath.Join(basePath, username)
info, err := os.Stat(folderPath) info, err := os.Stat(folderPath)
@@ -63,7 +61,6 @@ func CheckFolderExists(basePath, username string) bool {
return info.IsDir() return info.IsDir()
} }
// CheckGifsFolderExists checks if a gifs subfolder exists for the given username
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)
@@ -73,7 +70,6 @@ func CheckGifsFolderExists(basePath, username string) bool {
return info.IsDir() return info.IsDir()
} }
// CheckGifsFolderHasMP4 checks if the gifs folder has any MP4 files to convert
func CheckGifsFolderHasMP4(basePath, username string) bool { func CheckGifsFolderHasMP4(basePath, username string) bool {
gifsPath := filepath.Join(basePath, username, "gifs") gifsPath := filepath.Join(basePath, username, "gifs")
@@ -93,12 +89,10 @@ func CheckGifsFolderHasMP4(basePath, username string) bool {
return false return false
} }
// GetFolderPath returns the full path for a username folder
func GetFolderPath(basePath, username string) string { func GetFolderPath(basePath, username string) string {
return filepath.Join(basePath, username) return filepath.Join(basePath, username)
} }
// GetGifsFolderPath returns the full path for a username's gifs folder
func GetGifsFolderPath(basePath, username string) string { func GetGifsFolderPath(basePath, username string) string {
return filepath.Join(basePath, username, "gifs") return filepath.Join(basePath, username, "gifs")
} }
+19 -48
View File
@@ -11,11 +11,6 @@ import (
"strings" "strings"
) )
// ExtractOriginalFilename extracts the original filename from Twitter media URL
// Supports 3 formats:
// 1. animated_gif: https://video.twimg.com/tweet_video/GzstJyDbIAAPuX9.mp4 -> GzstJyDbIAAPuX9
// 2. photo: https://pbs.twimg.com/media/GynjhU0bYAAA_I4?format=jpg -> GynjhU0bYAAA_I4
// 3. video: https://video.twimg.com/amplify_video/.../Jpo0cDa7aNtjSv7o.mp4 -> Jpo0cDa7aNtjSv7o
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 {
@@ -25,16 +20,15 @@ func ExtractOriginalFilename(mediaURL string) string {
path := parsedURL.Path path := parsedURL.Path
parts := strings.Split(path, "/") parts := strings.Split(path, "/")
// 1. animated_gif: video.twimg.com/tweet_video/XXX.mp4
if strings.Contains(mediaURL, "/tweet_video/") { if strings.Contains(mediaURL, "/tweet_video/") {
for i, part := range parts { for i, part := range parts {
if part == "tweet_video" && i+1 < len(parts) { if part == "tweet_video" && i+1 < len(parts) {
filename := parts[i+1] filename := parts[i+1]
// Remove extension
if idx := strings.LastIndex(filename, "."); idx > 0 { if idx := strings.LastIndex(filename, "."); idx > 0 {
filename = filename[:idx] filename = filename[:idx]
} }
// Validate alphanumeric + underscore (Twitter filenames can contain _)
if matched, _ := regexp.MatchString(`^[A-Za-z0-9_]+$`, filename); matched && len(filename) > 0 { if matched, _ := regexp.MatchString(`^[A-Za-z0-9_]+$`, filename); matched && len(filename) > 0 {
return filename return filename
} }
@@ -42,32 +36,28 @@ func ExtractOriginalFilename(mediaURL string) string {
} }
} }
// 2. photo: pbs.twimg.com/media/XXX
if strings.Contains(mediaURL, "pbs.twimg.com/media/") { if strings.Contains(mediaURL, "pbs.twimg.com/media/") {
if len(parts) > 0 { if len(parts) > 0 {
filename := parts[len(parts)-1] filename := parts[len(parts)-1]
// Remove extension if present
if idx := strings.LastIndex(filename, "."); idx > 0 { if idx := strings.LastIndex(filename, "."); idx > 0 {
filename = filename[:idx] filename = filename[:idx]
} }
// Validate alphanumeric + underscore (Twitter filenames can contain _)
if matched, _ := regexp.MatchString(`^[A-Za-z0-9_]+$`, filename); matched && len(filename) > 0 { if matched, _ := regexp.MatchString(`^[A-Za-z0-9_]+$`, filename); matched && len(filename) > 0 {
return filename return filename
} }
} }
} }
// 3. video: video.twimg.com/amplify_video/.../XXX.mp4 or video.twimg.com/ext_tw_video/.../XXX.mp4
// Filename is the last segment (before extension)
// Note: Skip if already handled by tweet_video above
if strings.Contains(mediaURL, "video.twimg.com") && !strings.Contains(mediaURL, "/tweet_video/") { if strings.Contains(mediaURL, "video.twimg.com") && !strings.Contains(mediaURL, "/tweet_video/") {
if len(parts) > 0 { if len(parts) > 0 {
filename := parts[len(parts)-1] filename := parts[len(parts)-1]
// Remove extension
if idx := strings.LastIndex(filename, "."); idx > 0 { if idx := strings.LastIndex(filename, "."); idx > 0 {
filename = filename[:idx] filename = filename[:idx]
} }
// Validate: alphanumeric + underscore with at least one letter (to exclude pure numeric IDs)
if matched, _ := regexp.MatchString(`^[A-Za-z0-9_]+$`, filename); matched { if matched, _ := regexp.MatchString(`^[A-Za-z0-9_]+$`, filename); matched {
hasLetter, _ := regexp.MatchString(`[A-Za-z]`, filename) hasLetter, _ := regexp.MatchString(`[A-Za-z]`, filename)
if hasLetter && len(filename) >= 8 { if hasLetter && len(filename) >= 8 {
@@ -80,8 +70,6 @@ func ExtractOriginalFilename(mediaURL string) string {
return "" return ""
} }
// EmbedMetadata embeds metadata into a media file
// Only supports JPG (images) and MP4 (videos)
func EmbedMetadata(filePath string, tweetContent string, tweetURL string, originalFilename string) error { func EmbedMetadata(filePath string, tweetContent string, tweetURL string, originalFilename string) error {
ext := strings.ToLower(filepath.Ext(filePath)) ext := strings.ToLower(filepath.Ext(filePath))
@@ -91,28 +79,21 @@ func EmbedMetadata(filePath string, tweetContent string, tweetURL string, origin
case ".mp4": case ".mp4":
return embedVideoMetadata(filePath, tweetContent, tweetURL, originalFilename) return embedVideoMetadata(filePath, tweetContent, tweetURL, originalFilename)
default: default:
// For unsupported formats, skip metadata embedding
return nil return nil
} }
} }
// embedImageMetadata embeds metadata into image files using exiftool or similar
// Since we don't want to add heavy dependencies, we'll use a simple approach:
// For JPEG: We can use exiftool if available, or skip if not
// For PNG: Limited support, skip for now
func embedImageMetadata(filePath string, tweetContent string, tweetURL string, originalFilename string) error { func embedImageMetadata(filePath string, tweetContent string, tweetURL string, originalFilename string) error {
// Try to use exiftool if available (common tool for metadata)
exiftoolPath := findExifTool() exiftoolPath := findExifTool()
if exiftoolPath == "" { if exiftoolPath == "" {
// exiftool not found, skip metadata embedding for images
// This is acceptable as it's an optional feature
return nil return nil
} }
// Build metadata comment
metadataComment := buildMetadataComment(tweetContent, tweetURL, originalFilename) metadataComment := buildMetadataComment(tweetContent, tweetURL, originalFilename)
// Use exiftool to add comment only (URL | filename)
args := []string{ args := []string{
"-overwrite_original", "-overwrite_original",
"-Comment=" + metadataComment, "-Comment=" + metadataComment,
@@ -123,32 +104,29 @@ func embedImageMetadata(filePath string, tweetContent string, tweetURL string, o
hideWindow(cmd) hideWindow(cmd)
output, err := cmd.CombinedOutput() output, err := cmd.CombinedOutput()
if err != nil { if err != nil {
// Non-fatal: if exiftool fails, just skip metadata
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))
} }
_ = output // Suppress unused variable warning _ = output
return nil return nil
} }
// embedVideoMetadata embeds metadata into video/GIF files using ExifTool
func embedVideoMetadata(filePath string, tweetContent string, tweetURL string, originalFilename string) error { func embedVideoMetadata(filePath string, tweetContent string, tweetURL string, originalFilename string) error {
// Use ExifTool for video metadata (works well for MP4)
exiftoolPath := findExifTool() exiftoolPath := findExifTool()
if exiftoolPath == "" { if exiftoolPath == "" {
// ExifTool not available, skip metadata embedding (non-fatal)
return nil return nil
} }
return embedVideoMetadataWithExifTool(exiftoolPath, filePath, tweetContent, tweetURL, originalFilename) return embedVideoMetadataWithExifTool(exiftoolPath, filePath, tweetContent, tweetURL, originalFilename)
} }
// embedVideoMetadataWithExifTool embeds metadata using ExifTool (preferred for MP4)
func embedVideoMetadataWithExifTool(exiftoolPath string, filePath string, tweetContent string, tweetURL string, originalFilename string) error { func embedVideoMetadataWithExifTool(exiftoolPath string, filePath string, tweetContent string, tweetURL string, originalFilename string) error {
// Build metadata comment
metadataComment := buildMetadataComment(tweetContent, tweetURL, originalFilename) metadataComment := buildMetadataComment(tweetContent, tweetURL, originalFilename)
// Use exiftool to add comment only (URL | filename)
args := []string{ args := []string{
"-overwrite_original", "-overwrite_original",
"-Comment=" + metadataComment, "-Comment=" + metadataComment,
@@ -159,16 +137,14 @@ func embedVideoMetadataWithExifTool(exiftoolPath string, filePath string, tweetC
hideWindow(cmd) hideWindow(cmd)
output, err := cmd.CombinedOutput() output, err := cmd.CombinedOutput()
if err != nil { if err != nil {
// Non-fatal: if exiftool fails, skip metadata (file still downloaded)
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))
} }
_ = output // Suppress unused variable warning _ = output
return nil return nil
} }
// buildMetadataComment builds a formatted metadata comment string
func buildMetadataComment(tweetContent string, tweetURL string, originalFilename string) string { func buildMetadataComment(tweetContent string, tweetURL string, originalFilename string) string {
var parts []string var parts []string
@@ -179,7 +155,6 @@ func buildMetadataComment(tweetContent string, tweetURL string, originalFilename
parts = append(parts, originalFilename) parts = append(parts, originalFilename)
} }
// If no original filename, just return URL (don't add empty part)
if len(parts) == 0 { if len(parts) == 0 {
return "" return ""
} }
@@ -187,14 +162,12 @@ func buildMetadataComment(tweetContent string, tweetURL string, originalFilename
return strings.Join(parts, " | ") return strings.Join(parts, " | ")
} }
// findExifTool searches for exiftool, prioritizing the installed version in .twitterxmediabatchdownloader
func findExifTool() string { func findExifTool() string {
// First, check if exiftool is installed in .twitterxmediabatchdownloader
if IsExifToolInstalled() { if IsExifToolInstalled() {
return GetExifToolPath() return GetExifToolPath()
} }
// Fallback: check common system locations
commonPaths := []string{ commonPaths := []string{
"exiftool", "exiftool",
"/usr/bin/exiftool", "/usr/bin/exiftool",
@@ -205,23 +178,21 @@ func findExifTool() string {
for _, path := range commonPaths { for _, path := range commonPaths {
if runtime.GOOS == "windows" { if runtime.GOOS == "windows" {
// On Windows, try .exe extension
if _, err := exec.LookPath(path); err == nil { if _, err := exec.LookPath(path); err == nil {
return path return path
} }
} else { } else {
// On Unix, check if executable
if _, err := os.Stat(path); err == nil { if _, err := os.Stat(path); err == nil {
return path return path
} }
} }
} }
// Try to find in PATH
if path, err := exec.LookPath("exiftool"); err == nil { if path, err := exec.LookPath("exiftool"); err == nil {
return path return path
} }
return "" return ""
} }
+128 -243
View File
@@ -1,8 +1,6 @@
package backend package backend
import ( import (
"crypto/sha256"
"encoding/hex"
"encoding/json" "encoding/json"
"fmt" "fmt"
"net/url" "net/url"
@@ -13,38 +11,47 @@ import (
"strings" "strings"
) )
// getExecutableName returns the appropriate executable name for the current OS
func getExecutableName() string { func getExecutableName() string {
if runtime.GOOS == "windows" {
return "xtractor.exe"
}
return "xtractor"
}
func getLegacyExecutableName() string {
if runtime.GOOS == "windows" { if runtime.GOOS == "windows" {
return "extractor.exe" return "extractor.exe"
} }
return "extractor" return "extractor"
} }
// KillAllExtractorProcesses kills all running extractor processes
// This is useful for cleanup when starting fresh or when user stops fetch
func KillAllExtractorProcesses() { func KillAllExtractorProcesses() {
exeName := getExecutableName() names := []string{getExecutableName(), getLegacyExecutableName()}
seen := make(map[string]bool)
var cmd *exec.Cmd for _, exeName := range names {
if runtime.GOOS == "windows" { if seen[exeName] {
// Use taskkill on Windows continue
cmd = exec.Command("taskkill", "/F", "/IM", exeName) }
} else { seen[exeName] = true
// Use pkill on Unix
cmd = exec.Command("pkill", "-f", exeName) var cmd *exec.Cmd
if runtime.GOOS == "windows" {
cmd = exec.Command("taskkill", "/F", "/IM", exeName)
} else {
cmd = exec.Command("pkill", "-f", exeName)
}
hideWindow(cmd)
cmd.CombinedOutput()
} }
hideWindow(cmd)
cmd.CombinedOutput() // Ignore errors - it's okay if no processes found
} }
// parseExtractorError parses the extractor output and returns a user-friendly error message
// while preserving the original error from gallery-dl
func parseExtractorError(output string, username string) string { func parseExtractorError(output string, username string) string {
outputLower := strings.ToLower(output) outputLower := strings.ToLower(output)
// Extract the actual error line from gallery-dl output
lines := strings.Split(output, "\n") lines := strings.Split(output, "\n")
var errorLine string var errorLine string
for _, line := range lines { for _, line := range lines {
@@ -58,12 +65,10 @@ func parseExtractorError(output string, username string) string {
errorLine = strings.TrimSpace(output) errorLine = strings.TrimSpace(output)
} }
// Truncate if too long
if len(errorLine) > 300 { if len(errorLine) > 300 {
errorLine = errorLine[:300] + "..." errorLine = errorLine[:300] + "..."
} }
// Add context hint based on error type, but keep original message
var hint string var hint string
if strings.Contains(outputLower, "unable to retrieve tweets from this timeline") { if strings.Contains(outputLower, "unable to retrieve tweets from this timeline") {
hint = " [Hint: End of timeline reached or rate limited - data already fetched has been saved]" hint = " [Hint: End of timeline reached or rate limited - data already fetched has been saved]"
@@ -80,23 +85,20 @@ func parseExtractorError(output string, username string) string {
return errorLine + hint return errorLine + hint
} }
// TweetIDString is a custom type that unmarshals int64 but marshals as string
type TweetIDString int64 type TweetIDString int64
// MarshalJSON converts TweetIDString to JSON string to preserve precision in JavaScript
func (t TweetIDString) MarshalJSON() ([]byte, error) { func (t TweetIDString) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%d"`, t)), nil return []byte(fmt.Sprintf(`"%d"`, t)), nil
} }
// UnmarshalJSON accepts both number and string from JSON
func (t *TweetIDString) UnmarshalJSON(data []byte) error { func (t *TweetIDString) UnmarshalJSON(data []byte) error {
// Try to unmarshal as number first (from extractor)
var num int64 var num int64
if err := json.Unmarshal(data, &num); err == nil { if err := json.Unmarshal(data, &num); err == nil {
*t = TweetIDString(num) *t = TweetIDString(num)
return nil return nil
} }
// Try as string (for future compatibility)
var str string var str string
if err := json.Unmarshal(data, &str); err == nil { if err := json.Unmarshal(data, &str); err == nil {
parsed, err := fmt.Sscanf(str, "%d", &num) parsed, err := fmt.Sscanf(str, "%d", &num)
@@ -109,14 +111,12 @@ func (t *TweetIDString) UnmarshalJSON(data []byte) error {
return fmt.Errorf("tweet_id must be number or string") return fmt.Errorf("tweet_id must be number or string")
} }
// Author represents tweet author information from extractor
type Author struct { type Author struct {
ID int64 `json:"id"` ID int64 `json:"id"`
Name string `json:"name"` Name string `json:"name"`
Nick string `json:"nick"` Nick string `json:"nick"`
} }
// UserInfo represents full user information from extractor
type UserInfo struct { type UserInfo struct {
ID int64 `json:"id"` ID int64 `json:"id"`
Name string `json:"name"` Name string `json:"name"`
@@ -137,7 +137,6 @@ type UserInfo struct {
URL string `json:"url"` URL string `json:"url"`
} }
// CLIMediaItem represents a single media entry from extractor CLI
type CLIMediaItem struct { type CLIMediaItem struct {
URL string `json:"url"` URL string `json:"url"`
TweetID TweetIDString `json:"tweet_id"` TweetID TweetIDString `json:"tweet_id"`
@@ -165,7 +164,6 @@ type CLIMediaItem struct {
Sensitive bool `json:"sensitive"` Sensitive bool `json:"sensitive"`
} }
// TweetMetadata represents tweet metadata from extractor
type TweetMetadata struct { type TweetMetadata struct {
TweetID TweetIDString `json:"tweet_id"` TweetID TweetIDString `json:"tweet_id"`
RetweetID TweetIDString `json:"retweet_id,omitempty"` RetweetID TweetIDString `json:"retweet_id,omitempty"`
@@ -186,38 +184,35 @@ type TweetMetadata struct {
Sensitive bool `json:"sensitive,omitempty"` Sensitive bool `json:"sensitive,omitempty"`
} }
// CLIResponse represents the raw response from extractor CLI
type CLIResponse struct { type CLIResponse struct {
Media []CLIMediaItem `json:"media"` Media []CLIMediaItem `json:"media"`
Metadata []TweetMetadata `json:"metadata"` Metadata []TweetMetadata `json:"metadata"`
Cursor string `json:"cursor,omitempty"` // Cursor for resume Cursor string `json:"cursor,omitempty"`
Total int `json:"total,omitempty"` // Total items fetched Total int `json:"total,omitempty"`
Completed bool `json:"completed,omitempty"` // True if all fetched Completed bool `json:"completed,omitempty"`
} }
// TimelineEntry represents a single media entry for frontend (converted from MediaItem)
type TimelineEntry struct { type TimelineEntry struct {
URL string `json:"url"` URL string `json:"url"`
Date string `json:"date"` Date string `json:"date"`
TweetID TweetIDString `json:"tweet_id"` TweetID TweetIDString `json:"tweet_id"`
Type string `json:"type"` Type string `json:"type"`
IsRetweet bool `json:"is_retweet"` IsRetweet bool `json:"is_retweet"`
Extension string `json:"extension"` Extension string `json:"extension"`
Width int `json:"width"` Width int `json:"width"`
Height int `json:"height"` Height int `json:"height"`
Content string `json:"content,omitempty"` Content string `json:"content,omitempty"`
ViewCount int `json:"view_count,omitempty"` ViewCount int `json:"view_count,omitempty"`
BookmarkCount int `json:"bookmark_count,omitempty"` BookmarkCount int `json:"bookmark_count,omitempty"`
FavoriteCount int `json:"favorite_count,omitempty"` FavoriteCount int `json:"favorite_count,omitempty"`
RetweetCount int `json:"retweet_count,omitempty"` RetweetCount int `json:"retweet_count,omitempty"`
ReplyCount int `json:"reply_count,omitempty"` ReplyCount int `json:"reply_count,omitempty"`
Source string `json:"source,omitempty"` Source string `json:"source,omitempty"`
Verified bool `json:"verified,omitempty"` Verified bool `json:"verified,omitempty"`
OriginalFilename string `json:"original_filename,omitempty"` // Original filename from API OriginalFilename string `json:"original_filename,omitempty"`
AuthorUsername string `json:"author_username,omitempty"` // Username of tweet author (for bookmarks and likes) AuthorUsername string `json:"author_username,omitempty"`
} }
// AccountInfo represents Twitter account information (derived from metadata)
type AccountInfo struct { type AccountInfo struct {
Name string `json:"name"` Name string `json:"name"`
Nick string `json:"nick"` Nick string `json:"nick"`
@@ -228,65 +223,58 @@ type AccountInfo struct {
StatusesCount int `json:"statuses_count"` StatusesCount int `json:"statuses_count"`
} }
// ExtractMetadata represents extraction metadata
type ExtractMetadata struct { type ExtractMetadata struct {
NewEntries int `json:"new_entries"` NewEntries int `json:"new_entries"`
Page int `json:"page"` Page int `json:"page"`
BatchSize int `json:"batch_size"` BatchSize int `json:"batch_size"`
HasMore bool `json:"has_more"` HasMore bool `json:"has_more"`
Cursor string `json:"cursor,omitempty"` // Cursor for resume capability Cursor string `json:"cursor,omitempty"`
Completed bool `json:"completed,omitempty"` // True if all media fetched Completed bool `json:"completed,omitempty"`
} }
// TwitterResponse represents the full response for frontend
type TwitterResponse struct { type TwitterResponse struct {
AccountInfo AccountInfo `json:"account_info"` AccountInfo AccountInfo `json:"account_info"`
TotalURLs int `json:"total_urls"` TotalURLs int `json:"total_urls"`
Timeline []TimelineEntry `json:"timeline"` Timeline []TimelineEntry `json:"timeline"`
Metadata ExtractMetadata `json:"metadata"` Metadata ExtractMetadata `json:"metadata"`
Cursor string `json:"cursor,omitempty"` // Cursor for next fetch Cursor string `json:"cursor,omitempty"`
Completed bool `json:"completed,omitempty"` // True if fetch completed Completed bool `json:"completed,omitempty"`
} }
// TimelineRequest represents request parameters for timeline extraction
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"` // media, timeline, tweets, with_replies, likes, bookmarks TimelineType string `json:"timeline_type"`
BatchSize int `json:"batch_size"` // 0 = all BatchSize int `json:"batch_size"`
Page int `json:"page"` Page int `json:"page"`
MediaType string `json:"media_type"` // all, image, video, gif MediaType string `json:"media_type"`
Retweets bool `json:"retweets"` Retweets bool `json:"retweets"`
Cursor string `json:"cursor,omitempty"` // Resume from this cursor position Cursor string `json:"cursor,omitempty"`
} }
// DateRangeRequest represents request parameters for date range extraction
type DateRangeRequest struct { type DateRangeRequest struct {
Username string `json:"username"` Username string `json:"username"`
AuthToken string `json:"auth_token"` AuthToken string `json:"auth_token"`
StartDate string `json:"start_date"` // YYYY-MM-DD StartDate string `json:"start_date"`
EndDate string `json:"end_date"` // YYYY-MM-DD EndDate string `json:"end_date"`
MediaFilter string `json:"media_filter"` MediaFilter string `json:"media_filter"`
Retweets bool `json:"retweets"` Retweets bool `json:"retweets"`
} }
// buildTwitterURL constructs the Twitter URL based on username and timeline type
func buildTwitterURL(username, timelineType string) string { func buildTwitterURL(username, timelineType string) string {
// Special case: bookmarks don't need username
if timelineType == "bookmarks" { if timelineType == "bookmarks" {
return "https://x.com/i/bookmarks" return "https://x.com/i/bookmarks"
} }
// Clean username - extract handle from URL if needed
username = cleanUsername(username) username = cleanUsername(username)
// Build URL based on timeline type
baseURL := "https://x.com/" + username baseURL := "https://x.com/" + username
switch timelineType { switch timelineType {
case "media": case "media":
return baseURL + "/media" return baseURL + "/media"
case "timeline": case "timeline":
return baseURL + "/timeline" // Best for cursor support return baseURL + "/timeline"
case "tweets": case "tweets":
return baseURL + "/tweets" return baseURL + "/tweets"
case "with_replies": case "with_replies":
@@ -294,12 +282,10 @@ func buildTwitterURL(username, timelineType string) string {
case "likes": case "likes":
return baseURL + "/likes" return baseURL + "/likes"
default: default:
return baseURL + "/timeline" // Default to timeline for reliable cursor return baseURL + "/timeline"
} }
} }
// cleanUsername extracts the handle from different input formats
// Handles: @username, username, https://x.com/username, https://x.com/username/media, etc.
func cleanUsername(username string) string { func cleanUsername(username string) string {
username = strings.TrimSpace(username) username = strings.TrimSpace(username)
username = strings.TrimPrefix(username, "@") username = strings.TrimPrefix(username, "@")
@@ -311,12 +297,12 @@ func cleanUsername(username string) string {
} }
if u, err := url.Parse(parsed); err == nil { if u, err := url.Parse(parsed); err == nil {
segments := strings.Split(strings.Trim(u.Path, "/"), "/") segments := strings.Split(strings.Trim(u.Path, "/"), "/")
// Skip special paths like /i/bookmarks, /search, /home, /explore
if len(segments) > 0 && segments[0] != "" { if len(segments) > 0 && segments[0] != "" {
firstSegment := strings.ToLower(segments[0]) firstSegment := strings.ToLower(segments[0])
// These are not usernames
if firstSegment == "i" || firstSegment == "search" || firstSegment == "home" || firstSegment == "explore" || firstSegment == "settings" || firstSegment == "messages" || firstSegment == "notifications" { if firstSegment == "i" || firstSegment == "search" || firstSegment == "home" || firstSegment == "explore" || firstSegment == "settings" || firstSegment == "messages" || firstSegment == "notifications" {
return username // Return as-is, let caller handle return username
} }
return segments[0] return segments[0]
} }
@@ -326,7 +312,6 @@ func cleanUsername(username string) string {
return username return username
} }
// ensureURLScheme normalises URLs so the CLI accepts them
func ensureURLScheme(raw string) string { func ensureURLScheme(raw string) string {
raw = strings.TrimSpace(raw) raw = strings.TrimSpace(raw)
if raw == "" { if raw == "" {
@@ -341,7 +326,6 @@ func ensureURLScheme(raw string) string {
return "https://" + strings.TrimPrefix(raw, "//") return "https://" + strings.TrimPrefix(raw, "//")
} }
// buildSearchURL assembles an X.com search URL for date range queries
func buildSearchURL(username, startDate, endDate, mediaFilter string, includeRetweets bool) string { func buildSearchURL(username, startDate, endDate, mediaFilter string, includeRetweets bool) string {
trimmed := strings.TrimSpace(username) trimmed := strings.TrimSpace(username)
lower := strings.ToLower(trimmed) lower := strings.ToLower(trimmed)
@@ -380,31 +364,28 @@ func buildSearchURL(username, startDate, endDate, mediaFilter string, includeRet
return fmt.Sprintf("https://x.com/search?q=%s&src=typed_query&f=live", query) return fmt.Sprintf("https://x.com/search?q=%s&src=typed_query&f=live", query)
} }
// convertMetadataToTimelineEntry converts metadata-only tweets to timeline entries
func convertMetadataToTimelineEntry(meta TweetMetadata) TimelineEntry { func convertMetadataToTimelineEntry(meta TweetMetadata) TimelineEntry {
return TimelineEntry{ return TimelineEntry{
URL: "", URL: "",
Date: meta.Date, Date: meta.Date,
TweetID: meta.TweetID, TweetID: meta.TweetID,
Type: "text", Type: "text",
IsRetweet: meta.RetweetID != 0, IsRetweet: meta.RetweetID != 0,
Extension: "txt", Extension: "txt",
Width: 0, Width: 0,
Height: 0, Height: 0,
Content: meta.Content, Content: meta.Content,
ViewCount: meta.ViewCount, ViewCount: meta.ViewCount,
BookmarkCount: meta.BookmarkCount, BookmarkCount: meta.BookmarkCount,
FavoriteCount: meta.FavoriteCount, FavoriteCount: meta.FavoriteCount,
RetweetCount: meta.RetweetCount, RetweetCount: meta.RetweetCount,
ReplyCount: meta.ReplyCount, ReplyCount: meta.ReplyCount,
AuthorUsername: meta.Author.Name, AuthorUsername: meta.Author.Name,
} }
} }
// convertToTimelineEntry converts CLIMediaItem to TimelineEntry
func convertToTimelineEntry(media CLIMediaItem) TimelineEntry { func convertToTimelineEntry(media CLIMediaItem) TimelineEntry {
// Get username from Author field (preferred for bookmarks/likes) or User field
// Author field always contains the tweet author, while User might be the account fetching for likes
authorUsername := "" authorUsername := ""
if media.Author.Name != "" { if media.Author.Name != "" {
authorUsername = media.Author.Name authorUsername = media.Author.Name
@@ -413,26 +394,24 @@ func convertToTimelineEntry(media CLIMediaItem) TimelineEntry {
} }
entry := TimelineEntry{ entry := TimelineEntry{
URL: media.URL, URL: media.URL,
TweetID: media.TweetID, TweetID: media.TweetID,
Date: media.Date, Date: media.Date,
Extension: media.Extension, Extension: media.Extension,
Width: media.Width, Width: media.Width,
Height: media.Height, Height: media.Height,
IsRetweet: media.RetweetID != 0, IsRetweet: media.RetweetID != 0,
Content: media.Content, Content: media.Content,
ViewCount: media.ViewCount, ViewCount: media.ViewCount,
BookmarkCount: media.BookmarkCount, BookmarkCount: media.BookmarkCount,
FavoriteCount: media.FavoriteCount, FavoriteCount: media.FavoriteCount,
RetweetCount: media.RetweetCount, RetweetCount: media.RetweetCount,
ReplyCount: media.ReplyCount, ReplyCount: media.ReplyCount,
Source: media.Source, Source: media.Source,
Verified: media.Author.Verified, Verified: media.Author.Verified,
AuthorUsername: authorUsername, AuthorUsername: authorUsername,
// OriginalFilename will be extracted from URL in download.go
} }
// Determine type - media item already has type from CLI
if media.Type != "" { if media.Type != "" {
entry.Type = media.Type entry.Type = media.Type
} else { } else {
@@ -449,119 +428,52 @@ func convertToTimelineEntry(media CLIMediaItem) TimelineEntry {
return entry return entry
} }
// getExtractorPath returns the path to extractor binary
// Binary is stored in ~/.twitterxmediabatchdownloader/ (same as ffmpeg and database)
func getExtractorPath() string { func getExtractorPath() string {
homeDir, _ := os.UserHomeDir() homeDir, _ := os.UserHomeDir()
baseDir := filepath.Join(homeDir, ".twitterxmediabatchdownloader") baseDir := filepath.Join(homeDir, ".twitterxmediabatchdownloader")
return filepath.Join(baseDir, getExecutableName()) return filepath.Join(baseDir, getExecutableName())
} }
// getHashFilePath returns the path to the hash file for version checking
func getHashFilePath() string {
homeDir, _ := os.UserHomeDir()
baseDir := filepath.Join(homeDir, ".twitterxmediabatchdownloader")
return filepath.Join(baseDir, "extractor.sha256")
}
// calculateHash calculates SHA256 hash of data
func calculateHash(data []byte) string {
hash := sha256.Sum256(data)
return hex.EncodeToString(hash[:])
}
// ensureExtractor ensures the extractor binary exists
// Extracts from embedded binary if not present or if hash differs (update)
func ensureExtractor() (string, error) {
exePath := getExtractorPath()
hashPath := getHashFilePath()
baseDir := filepath.Dir(exePath)
// Create directory if not exists
if err := os.MkdirAll(baseDir, 0755); err != nil {
return "", fmt.Errorf("failed to create directory: %v", err)
}
// Calculate hash of embedded binary
embeddedHash := calculateHash(extractorBin)
// Check if binary and hash file exist
if _, err := os.Stat(exePath); err == nil {
// Binary exists - check hash
if storedHash, err := os.ReadFile(hashPath); err == nil {
if string(storedHash) == embeddedHash {
return exePath, nil // Already extracted and up to date
}
}
// Hash differs or missing - need to update
os.Remove(exePath)
}
// Extract binary
if err := os.WriteFile(exePath, extractorBin, 0755); err != nil {
return "", fmt.Errorf("failed to write extractor: %v", err)
}
// Save hash for future comparison
if err := os.WriteFile(hashPath, []byte(embeddedHash), 0644); err != nil {
// Non-fatal - binary still works, just won't skip next time
fmt.Printf("Warning: failed to save hash file: %v\n", err)
}
return exePath, nil
}
// ExtractTimeline extracts media from user timeline using the new CLI
func ExtractTimeline(req TimelineRequest) (*TwitterResponse, error) { func ExtractTimeline(req TimelineRequest) (*TwitterResponse, error) {
// Get or extract extractor binary (persistent, not temp)
exePath, err := ensureExtractor() exePath, err := requireExtractorPath()
if err != nil { if err != nil {
return nil, err return nil, err
} }
// Determine the right endpoint based on what user wants:
// - Media (all/image/video/gif): Use /media endpoint - fastest and most reliable
// - Text tweets: Use /tweets endpoint with --text-tweets
// - With retweets: Use /tweets endpoint (retweets not available on /media)
isTextOnly := req.MediaType == "text" isTextOnly := req.MediaType == "text"
wantsRetweets := req.Retweets wantsRetweets := req.Retweets
timelineType := req.TimelineType timelineType := req.TimelineType
if timelineType == "" { if timelineType == "" {
if isTextOnly { if isTextOnly {
// Text-only tweets need /tweets endpoint
timelineType = "tweets" timelineType = "tweets"
} else if wantsRetweets { } else if wantsRetweets {
// Retweets need /tweets endpoint (not available on /media)
timelineType = "tweets" timelineType = "tweets"
} else { } else {
// Default: /media endpoint - fastest for media-only fetch
timelineType = "media" timelineType = "media"
} }
} }
url := buildTwitterURL(req.Username, timelineType) url := buildTwitterURL(req.Username, timelineType)
// Build command arguments for new CLI format
// Format: extractor.exe URL --auth-token TOKEN --json [options]
args := []string{url} args := []string{url}
// Add auth token
if req.AuthToken != "" { if req.AuthToken != "" {
args = append(args, "--auth-token", req.AuthToken) args = append(args, "--auth-token", req.AuthToken)
} else { } else {
args = append(args, "--guest") args = append(args, "--guest")
} }
// Always request JSON output with metadata
args = append(args, "--json", "--metadata") args = append(args, "--json", "--metadata")
// Add limit if specified
if req.BatchSize > 0 { if req.BatchSize > 0 {
args = append(args, "--limit", fmt.Sprintf("%d", req.BatchSize)) args = append(args, "--limit", fmt.Sprintf("%d", req.BatchSize))
} }
// Handle retweets - only relevant when using /tweets endpoint
if timelineType == "tweets" || timelineType == "timeline" { if timelineType == "tweets" || timelineType == "timeline" {
if req.Retweets { if req.Retweets {
args = append(args, "--retweets", "include") args = append(args, "--retweets", "include")
@@ -570,12 +482,10 @@ func ExtractTimeline(req TimelineRequest) (*TwitterResponse, error) {
} }
} }
// Only add --text-tweets when explicitly requesting text content
if isTextOnly { if isTextOnly {
args = append(args, "--text-tweets") args = append(args, "--text-tweets")
} }
// Handle media type filter using --type parameter
if req.MediaType != "" && req.MediaType != "all" && !isTextOnly { if req.MediaType != "" && req.MediaType != "all" && !isTextOnly {
switch req.MediaType { switch req.MediaType {
case "image": case "image":
@@ -587,21 +497,18 @@ func ExtractTimeline(req TimelineRequest) (*TwitterResponse, error) {
} }
} }
// Add cursor for resume capability
if req.Cursor != "" { if req.Cursor != "" {
args = append(args, "--cursor", req.Cursor) args = append(args, "--cursor", req.Cursor)
} }
// Execute command with UTF-8 encoding
cmd := exec.Command(exePath, args...) cmd := exec.Command(exePath, args...)
cmd.Env = append(os.Environ(), cmd.Env = append(os.Environ(),
"PYTHONIOENCODING=utf-8", "PYTHONIOENCODING=utf-8",
"PYTHONUTF8=1", "PYTHONUTF8=1",
) )
hideWindow(cmd) // Hide console window on Windows hideWindow(cmd)
output, err := cmd.CombinedOutput() output, err := cmd.CombinedOutput()
// Ensure process is killed after completion
if cmd.Process != nil { if cmd.Process != nil {
cmd.Process.Kill() cmd.Process.Kill()
} }
@@ -612,36 +519,31 @@ func ExtractTimeline(req TimelineRequest) (*TwitterResponse, error) {
return nil, fmt.Errorf("%s", errorMsg) return nil, fmt.Errorf("%s", errorMsg)
} }
// Find JSON in output (skip any info messages)
jsonStr := extractJSON(string(output)) jsonStr := extractJSON(string(output))
if jsonStr == "" { if jsonStr == "" {
outputStr := string(output) outputStr := string(output)
if strings.TrimSpace(outputStr) == "" { if strings.TrimSpace(outputStr) == "" {
return nil, fmt.Errorf("empty_response: Extractor returned no data. The timeline may be empty or inaccessible") return nil, fmt.Errorf("empty_response: Xtractor returned no data. The timeline may be empty or inaccessible")
} }
return nil, fmt.Errorf("parse_error: Could not parse extractor output. Raw output: %s", outputStr) return nil, fmt.Errorf("parse_error: Could not parse xtractor output. Raw output: %s", outputStr)
} }
// Parse CLI response
var cliResponse CLIResponse var cliResponse CLIResponse
if err := json.Unmarshal([]byte(jsonStr), &cliResponse); err != nil { if err := json.Unmarshal([]byte(jsonStr), &cliResponse); err != nil {
return nil, fmt.Errorf("json_error: Failed to parse JSON response: %v", err) return nil, fmt.Errorf("json_error: Failed to parse JSON response: %v", err)
} }
// Convert to frontend format
var timeline []TimelineEntry var timeline []TimelineEntry
accountInfo := AccountInfo{ accountInfo := AccountInfo{
Name: req.Username, Name: req.Username,
Nick: req.Username, Nick: req.Username,
} }
// Build a set of tweet IDs that have media
mediaTweetIDs := make(map[int64]bool) mediaTweetIDs := make(map[int64]bool)
for _, media := range cliResponse.Media { for _, media := range cliResponse.Media {
mediaTweetIDs[int64(media.TweetID)] = true mediaTweetIDs[int64(media.TweetID)] = true
} }
// For bookmarks and likes, keep name as "bookmarks"/"likes" (not from author tweet)
isBookmarks := req.TimelineType == "bookmarks" isBookmarks := req.TimelineType == "bookmarks"
isLikes := req.TimelineType == "likes" isLikes := req.TimelineType == "likes"
if isBookmarks { if isBookmarks {
@@ -653,7 +555,7 @@ func ExtractTimeline(req TimelineRequest) (*TwitterResponse, error) {
} }
if isTextOnly { if isTextOnly {
// Text-only mode: get tweets from metadata that don't have media
timeline = make([]TimelineEntry, 0) timeline = make([]TimelineEntry, 0)
for _, meta := range cliResponse.Metadata { for _, meta := range cliResponse.Metadata {
if !mediaTweetIDs[int64(meta.TweetID)] { if !mediaTweetIDs[int64(meta.TweetID)] {
@@ -661,7 +563,6 @@ func ExtractTimeline(req TimelineRequest) (*TwitterResponse, error) {
} }
} }
// Get account info from first media item if available, otherwise from metadata
if !isBookmarks && !isLikes { if !isBookmarks && !isLikes {
if len(cliResponse.Media) > 0 { if len(cliResponse.Media) > 0 {
user := cliResponse.Media[0].User user := cliResponse.Media[0].User
@@ -678,7 +579,7 @@ func ExtractTimeline(req TimelineRequest) (*TwitterResponse, error) {
accountInfo.Nick = firstMeta.Author.Nick accountInfo.Nick = firstMeta.Author.Nick
} }
} else { } else {
// For bookmarks and likes, get other info from first media item if available
if len(cliResponse.Media) > 0 { if len(cliResponse.Media) > 0 {
user := cliResponse.Media[0].User user := cliResponse.Media[0].User
accountInfo.Date = user.Date accountInfo.Date = user.Date
@@ -689,15 +590,13 @@ func ExtractTimeline(req TimelineRequest) (*TwitterResponse, error) {
} }
} }
} else if len(cliResponse.Media) > 0 { } else if len(cliResponse.Media) > 0 {
// Normal media items only (text tweets handled separately with "text" media type)
timeline = make([]TimelineEntry, 0, len(cliResponse.Media)) timeline = make([]TimelineEntry, 0, len(cliResponse.Media))
// Add media items
for _, media := range cliResponse.Media { for _, media := range cliResponse.Media {
timeline = append(timeline, convertToTimelineEntry(media)) timeline = append(timeline, convertToTimelineEntry(media))
} }
// Get account info from first media item
user := cliResponse.Media[0].User user := cliResponse.Media[0].User
if !isBookmarks && !isLikes { if !isBookmarks && !isLikes {
accountInfo.Name = user.Name accountInfo.Name = user.Name
@@ -709,29 +608,29 @@ func ExtractTimeline(req TimelineRequest) (*TwitterResponse, error) {
accountInfo.ProfileImage = user.ProfileImage accountInfo.ProfileImage = user.ProfileImage
accountInfo.StatusesCount = user.StatusesCount accountInfo.StatusesCount = user.StatusesCount
} else if len(cliResponse.Metadata) > 0 { } else if len(cliResponse.Metadata) > 0 {
// Fallback: Text-only tweets (no media) - convert metadata to timeline entries
timeline = make([]TimelineEntry, 0, len(cliResponse.Metadata)) timeline = make([]TimelineEntry, 0, len(cliResponse.Metadata))
for _, meta := range cliResponse.Metadata { for _, meta := range cliResponse.Metadata {
entry := TimelineEntry{ entry := TimelineEntry{
URL: "", // No media URL for text tweets URL: "",
TweetID: meta.TweetID, TweetID: meta.TweetID,
Date: meta.Date, Date: meta.Date,
Type: "text", Type: "text",
IsRetweet: meta.RetweetID != 0, IsRetweet: meta.RetweetID != 0,
Extension: "txt", Extension: "txt",
Width: 0, Width: 0,
Height: 0, Height: 0,
Content: meta.Content, Content: meta.Content,
ViewCount: meta.ViewCount, ViewCount: meta.ViewCount,
BookmarkCount: meta.BookmarkCount, BookmarkCount: meta.BookmarkCount,
FavoriteCount: meta.FavoriteCount, FavoriteCount: meta.FavoriteCount,
RetweetCount: meta.RetweetCount, RetweetCount: meta.RetweetCount,
ReplyCount: meta.ReplyCount, ReplyCount: meta.ReplyCount,
AuthorUsername: meta.Author.Name, AuthorUsername: meta.Author.Name,
} }
timeline = append(timeline, entry) timeline = append(timeline, entry)
} }
// Get account info from first metadata
if !isBookmarks && !isLikes { if !isBookmarks && !isLikes {
firstMeta := cliResponse.Metadata[0] firstMeta := cliResponse.Metadata[0]
accountInfo.Name = firstMeta.Author.Name accountInfo.Name = firstMeta.Author.Name
@@ -739,7 +638,6 @@ func ExtractTimeline(req TimelineRequest) (*TwitterResponse, error) {
} }
} }
// Determine if there's more data to fetch
hasMore := cliResponse.Cursor != "" && !cliResponse.Completed hasMore := cliResponse.Cursor != "" && !cliResponse.Completed
response := &TwitterResponse{ response := &TwitterResponse{
@@ -761,10 +659,9 @@ func ExtractTimeline(req TimelineRequest) (*TwitterResponse, error) {
return response, nil return response, nil
} }
// ExtractDateRange extracts media based on date range using the new CLI
func ExtractDateRange(req DateRangeRequest) (*TwitterResponse, error) { func ExtractDateRange(req DateRangeRequest) (*TwitterResponse, error) {
// Get or extract extractor binary (persistent, not temp)
exePath, err := ensureExtractor() exePath, err := requireExtractorPath()
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -772,17 +669,14 @@ func ExtractDateRange(req DateRangeRequest) (*TwitterResponse, error) {
mediaFilter := strings.ToLower(strings.TrimSpace(req.MediaFilter)) mediaFilter := strings.ToLower(strings.TrimSpace(req.MediaFilter))
url := buildSearchURL(req.Username, req.StartDate, req.EndDate, mediaFilter, req.Retweets) url := buildSearchURL(req.Username, req.StartDate, req.EndDate, mediaFilter, req.Retweets)
// Build command arguments
args := []string{url} args := []string{url}
// Add auth token
if req.AuthToken != "" { if req.AuthToken != "" {
args = append(args, "--auth-token", req.AuthToken) args = append(args, "--auth-token", req.AuthToken)
} else { } else {
args = append(args, "--guest") args = append(args, "--guest")
} }
// Always request JSON output with metadata
args = append(args, "--json", "--metadata") args = append(args, "--json", "--metadata")
if req.Retweets { if req.Retweets {
@@ -796,7 +690,6 @@ func ExtractDateRange(req DateRangeRequest) (*TwitterResponse, error) {
args = append(args, "--text-tweets") args = append(args, "--text-tweets")
} }
// Execute command with UTF-8 encoding
cmd := exec.Command(exePath, args...) cmd := exec.Command(exePath, args...)
cmd.Env = append(os.Environ(), cmd.Env = append(os.Environ(),
"PYTHONIOENCODING=utf-8", "PYTHONIOENCODING=utf-8",
@@ -805,7 +698,6 @@ func ExtractDateRange(req DateRangeRequest) (*TwitterResponse, error) {
hideWindow(cmd) hideWindow(cmd)
output, err := cmd.CombinedOutput() output, err := cmd.CombinedOutput()
// Ensure process is killed after completion
if cmd.Process != nil { if cmd.Process != nil {
cmd.Process.Kill() cmd.Process.Kill()
} }
@@ -816,23 +708,20 @@ func ExtractDateRange(req DateRangeRequest) (*TwitterResponse, error) {
return nil, fmt.Errorf("%s", errorMsg) return nil, fmt.Errorf("%s", errorMsg)
} }
// Find JSON in output (skip any info messages)
jsonStr := extractJSON(string(output)) jsonStr := extractJSON(string(output))
if jsonStr == "" { if jsonStr == "" {
outputStr := string(output) outputStr := string(output)
if strings.TrimSpace(outputStr) == "" { if strings.TrimSpace(outputStr) == "" {
return nil, fmt.Errorf("empty_response: Extractor returned no data. The timeline may be empty or inaccessible") return nil, fmt.Errorf("empty_response: Xtractor returned no data. The timeline may be empty or inaccessible")
} }
return nil, fmt.Errorf("parse_error: Could not parse extractor output. Raw output: %s", outputStr) return nil, fmt.Errorf("parse_error: Could not parse xtractor output. Raw output: %s", outputStr)
} }
// Parse CLI response
var cliResponse CLIResponse var cliResponse CLIResponse
if err := json.Unmarshal([]byte(jsonStr), &cliResponse); err != nil { if err := json.Unmarshal([]byte(jsonStr), &cliResponse); err != nil {
return nil, fmt.Errorf("json_error: Failed to parse JSON response: %v", err) return nil, fmt.Errorf("json_error: Failed to parse JSON response: %v", err)
} }
// Convert to frontend format
mediaTweetIDs := make(map[int64]bool) mediaTweetIDs := make(map[int64]bool)
for _, media := range cliResponse.Media { for _, media := range cliResponse.Media {
mediaTweetIDs[int64(media.TweetID)] = true mediaTweetIDs[int64(media.TweetID)] = true
@@ -851,7 +740,6 @@ func ExtractDateRange(req DateRangeRequest) (*TwitterResponse, error) {
} }
} }
// Build account info from first media item (has full user info)
accountInfo := AccountInfo{ accountInfo := AccountInfo{
Name: req.Username, Name: req.Username,
Nick: req.Username, Nick: req.Username,
@@ -871,7 +759,6 @@ func ExtractDateRange(req DateRangeRequest) (*TwitterResponse, error) {
accountInfo.Nick = firstMeta.Author.Nick accountInfo.Nick = firstMeta.Author.Nick
} }
// Determine if there's more data to fetch
hasMore := cliResponse.Cursor != "" && !cliResponse.Completed hasMore := cliResponse.Cursor != "" && !cliResponse.Completed
response := &TwitterResponse{ response := &TwitterResponse{
@@ -893,15 +780,13 @@ func ExtractDateRange(req DateRangeRequest) (*TwitterResponse, error) {
return response, nil return response, nil
} }
// extractJSON finds and extracts JSON object from output string
func extractJSON(output string) string { func extractJSON(output string) string {
// Find the start of JSON object
start := strings.Index(output, "{") start := strings.Index(output, "{")
if start == -1 { if start == -1 {
return "" return ""
} }
// Find the matching closing brace
depth := 0 depth := 0
for i := start; i < len(output); i++ { for i := start; i < len(output); i++ {
if output[i] == '{' { if output[i] == '{' {
+3 -1
View File
@@ -18,5 +18,7 @@
"lib": "@/lib", "lib": "@/lib",
"hooks": "@/hooks" "hooks": "@/hooks"
}, },
"registries": {} "registries": {
"@lucide-animated": "https://lucide-animated.com/r/{name}.json"
}
} }
+20 -21
View File
@@ -1,23 +1,22 @@
import js from '@eslint/js' import js from '@eslint/js';
import globals from 'globals' import globals from 'globals';
import reactHooks from 'eslint-plugin-react-hooks' import reactHooks from 'eslint-plugin-react-hooks';
import reactRefresh from 'eslint-plugin-react-refresh' 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']),
{ {
files: ['**/*.{ts,tsx}'], files: ['**/*.{ts,tsx}'],
extends: [ extends: [
js.configs.recommended, js.configs.recommended,
tseslint.configs.recommended, tseslint.configs.recommended,
reactHooks.configs.flat.recommended, reactHooks.configs.flat.recommended,
reactRefresh.configs.vite, reactRefresh.configs.vite,
], ],
languageOptions: { languageOptions: {
ecmaVersion: 2020, ecmaVersion: 2020,
globals: globals.browser, globals: globals.browser,
},
}, },
}, ]);
])
+4 -6
View File
@@ -12,23 +12,21 @@
"postinstall": "node scripts/generate-icon.js" "postinstall": "node scripts/generate-icon.js"
}, },
"dependencies": { "dependencies": {
"@radix-ui/react-accordion": "^1.2.12",
"@radix-ui/react-checkbox": "^1.3.3", "@radix-ui/react-checkbox": "^1.3.3",
"@radix-ui/react-context-menu": "^2.2.16", "@radix-ui/react-context-menu": "^2.2.16",
"@radix-ui/react-dialog": "^1.1.15", "@radix-ui/react-dialog": "^1.1.15",
"@radix-ui/react-dropdown-menu": "^2.1.16", "@radix-ui/react-dropdown-menu": "^2.1.16",
"@radix-ui/react-label": "^2.1.8", "@radix-ui/react-label": "^2.1.8",
"@radix-ui/react-progress": "^1.1.8", "@radix-ui/react-progress": "^1.1.8",
"@radix-ui/react-radio-group": "^1.3.8",
"@radix-ui/react-select": "^2.2.6", "@radix-ui/react-select": "^2.2.6",
"@radix-ui/react-slot": "^1.2.4", "@radix-ui/react-slot": "^1.2.4",
"@radix-ui/react-switch": "^1.2.6", "@radix-ui/react-switch": "^1.2.6",
"@radix-ui/react-tabs": "^1.1.13",
"@radix-ui/react-tooltip": "^1.2.8", "@radix-ui/react-tooltip": "^1.2.8",
"@tailwindcss/vite": "^4.1.18", "@tailwindcss/vite": "^4.1.18",
"class-variance-authority": "^0.7.1", "class-variance-authority": "^0.7.1",
"clsx": "^2.1.1", "clsx": "^2.1.1",
"lucide-react": "^0.561.0", "lucide-react": "^0.562.0",
"motion": "^12.23.26",
"next-themes": "^0.4.6", "next-themes": "^0.4.6",
"react": "^19.2.3", "react": "^19.2.3",
"react-dom": "^19.2.3", "react-dom": "^19.2.3",
@@ -38,13 +36,13 @@
}, },
"devDependencies": { "devDependencies": {
"@eslint/js": "^9.39.2", "@eslint/js": "^9.39.2",
"@types/node": "^25.0.2", "@types/node": "^25.0.3",
"@types/react": "^19.2.7", "@types/react": "^19.2.7",
"@types/react-dom": "^19.2.3", "@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^5.1.2", "@vitejs/plugin-react": "^5.1.2",
"eslint": "^9.39.2", "eslint": "^9.39.2",
"eslint-plugin-react-hooks": "^7.0.1", "eslint-plugin-react-hooks": "^7.0.1",
"eslint-plugin-react-refresh": "^0.4.25", "eslint-plugin-react-refresh": "^0.4.26",
"globals": "^16.5.0", "globals": "^16.5.0",
"sharp": "^0.34.5", "sharp": "^0.34.5",
"tw-animate-css": "^1.4.0", "tw-animate-css": "^1.4.0",
+1 -1
View File
@@ -1 +1 @@
fac81d3fc08563d82c20da44a49a8efa cb4545ab700ecc9d641ab1be76b622f1
+204 -272
View File
@@ -8,9 +8,6 @@ importers:
.: .:
dependencies: dependencies:
'@radix-ui/react-accordion':
specifier: ^1.2.12
version: 1.2.12(@types/react-dom@19.2.3(@types/react@19.2.7))(@types/react@19.2.7)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
'@radix-ui/react-checkbox': '@radix-ui/react-checkbox':
specifier: ^1.3.3 specifier: ^1.3.3
version: 1.3.3(@types/react-dom@19.2.3(@types/react@19.2.7))(@types/react@19.2.7)(react-dom@19.2.3(react@19.2.3))(react@19.2.3) version: 1.3.3(@types/react-dom@19.2.3(@types/react@19.2.7))(@types/react@19.2.7)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
@@ -29,9 +26,6 @@ importers:
'@radix-ui/react-progress': '@radix-ui/react-progress':
specifier: ^1.1.8 specifier: ^1.1.8
version: 1.1.8(@types/react-dom@19.2.3(@types/react@19.2.7))(@types/react@19.2.7)(react-dom@19.2.3(react@19.2.3))(react@19.2.3) version: 1.1.8(@types/react-dom@19.2.3(@types/react@19.2.7))(@types/react@19.2.7)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
'@radix-ui/react-radio-group':
specifier: ^1.3.8
version: 1.3.8(@types/react-dom@19.2.3(@types/react@19.2.7))(@types/react@19.2.7)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
'@radix-ui/react-select': '@radix-ui/react-select':
specifier: ^2.2.6 specifier: ^2.2.6
version: 2.2.6(@types/react-dom@19.2.3(@types/react@19.2.7))(@types/react@19.2.7)(react-dom@19.2.3(react@19.2.3))(react@19.2.3) version: 2.2.6(@types/react-dom@19.2.3(@types/react@19.2.7))(@types/react@19.2.7)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
@@ -41,15 +35,12 @@ importers:
'@radix-ui/react-switch': '@radix-ui/react-switch':
specifier: ^1.2.6 specifier: ^1.2.6
version: 1.2.6(@types/react-dom@19.2.3(@types/react@19.2.7))(@types/react@19.2.7)(react-dom@19.2.3(react@19.2.3))(react@19.2.3) version: 1.2.6(@types/react-dom@19.2.3(@types/react@19.2.7))(@types/react@19.2.7)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
'@radix-ui/react-tabs':
specifier: ^1.1.13
version: 1.1.13(@types/react-dom@19.2.3(@types/react@19.2.7))(@types/react@19.2.7)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
'@radix-ui/react-tooltip': '@radix-ui/react-tooltip':
specifier: ^1.2.8 specifier: ^1.2.8
version: 1.2.8(@types/react-dom@19.2.3(@types/react@19.2.7))(@types/react@19.2.7)(react-dom@19.2.3(react@19.2.3))(react@19.2.3) version: 1.2.8(@types/react-dom@19.2.3(@types/react@19.2.7))(@types/react@19.2.7)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
'@tailwindcss/vite': '@tailwindcss/vite':
specifier: ^4.1.18 specifier: ^4.1.18
version: 4.1.18(vite@7.3.0(@types/node@25.0.2)(jiti@2.6.1)(lightningcss@1.30.2)) version: 4.1.18(vite@7.3.0(@types/node@25.0.3)(jiti@2.6.1)(lightningcss@1.30.2))
class-variance-authority: class-variance-authority:
specifier: ^0.7.1 specifier: ^0.7.1
version: 0.7.1 version: 0.7.1
@@ -57,8 +48,11 @@ importers:
specifier: ^2.1.1 specifier: ^2.1.1
version: 2.1.1 version: 2.1.1
lucide-react: lucide-react:
specifier: ^0.561.0 specifier: ^0.562.0
version: 0.561.0(react@19.2.3) version: 0.562.0(react@19.2.3)
motion:
specifier: ^12.23.26
version: 12.23.26(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
next-themes: next-themes:
specifier: ^0.4.6 specifier: ^0.4.6
version: 0.4.6(react-dom@19.2.3(react@19.2.3))(react@19.2.3) version: 0.4.6(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
@@ -82,8 +76,8 @@ importers:
specifier: ^9.39.2 specifier: ^9.39.2
version: 9.39.2 version: 9.39.2
'@types/node': '@types/node':
specifier: ^25.0.2 specifier: ^25.0.3
version: 25.0.2 version: 25.0.3
'@types/react': '@types/react':
specifier: ^19.2.7 specifier: ^19.2.7
version: 19.2.7 version: 19.2.7
@@ -92,7 +86,7 @@ importers:
version: 19.2.3(@types/react@19.2.7) version: 19.2.3(@types/react@19.2.7)
'@vitejs/plugin-react': '@vitejs/plugin-react':
specifier: ^5.1.2 specifier: ^5.1.2
version: 5.1.2(vite@7.3.0(@types/node@25.0.2)(jiti@2.6.1)(lightningcss@1.30.2)) version: 5.1.2(vite@7.3.0(@types/node@25.0.3)(jiti@2.6.1)(lightningcss@1.30.2))
eslint: eslint:
specifier: ^9.39.2 specifier: ^9.39.2
version: 9.39.2(jiti@2.6.1) version: 9.39.2(jiti@2.6.1)
@@ -100,8 +94,8 @@ importers:
specifier: ^7.0.1 specifier: ^7.0.1
version: 7.0.1(eslint@9.39.2(jiti@2.6.1)) version: 7.0.1(eslint@9.39.2(jiti@2.6.1))
eslint-plugin-react-refresh: eslint-plugin-react-refresh:
specifier: ^0.4.25 specifier: ^0.4.26
version: 0.4.25(eslint@9.39.2(jiti@2.6.1)) version: 0.4.26(eslint@9.39.2(jiti@2.6.1))
globals: globals:
specifier: ^16.5.0 specifier: ^16.5.0
version: 16.5.0 version: 16.5.0
@@ -119,7 +113,7 @@ importers:
version: 8.50.0(eslint@9.39.2(jiti@2.6.1))(typescript@5.9.3) version: 8.50.0(eslint@9.39.2(jiti@2.6.1))(typescript@5.9.3)
vite: vite:
specifier: ^7.3.0 specifier: ^7.3.0
version: 7.3.0(@types/node@25.0.2)(jiti@2.6.1)(lightningcss@1.30.2) version: 7.3.0(@types/node@25.0.3)(jiti@2.6.1)(lightningcss@1.30.2)
packages: packages:
@@ -209,158 +203,158 @@ packages:
'@emnapi/runtime@1.7.1': '@emnapi/runtime@1.7.1':
resolution: {integrity: sha512-PVtJr5CmLwYAU9PZDMITZoR5iAOShYREoR45EyyLrbntV50mdePTgUn4AmOw90Ifcj+x2kRjdzr1HP3RrNiHGA==} resolution: {integrity: sha512-PVtJr5CmLwYAU9PZDMITZoR5iAOShYREoR45EyyLrbntV50mdePTgUn4AmOw90Ifcj+x2kRjdzr1HP3RrNiHGA==}
'@esbuild/aix-ppc64@0.27.1': '@esbuild/aix-ppc64@0.27.2':
resolution: {integrity: sha512-HHB50pdsBX6k47S4u5g/CaLjqS3qwaOVE5ILsq64jyzgMhLuCuZ8rGzM9yhsAjfjkbgUPMzZEPa7DAp7yz6vuA==} resolution: {integrity: sha512-GZMB+a0mOMZs4MpDbj8RJp4cw+w1WV5NYD6xzgvzUJ5Ek2jerwfO2eADyI6ExDSUED+1X8aMbegahsJi+8mgpw==}
engines: {node: '>=18'} engines: {node: '>=18'}
cpu: [ppc64] cpu: [ppc64]
os: [aix] os: [aix]
'@esbuild/android-arm64@0.27.1': '@esbuild/android-arm64@0.27.2':
resolution: {integrity: sha512-45fuKmAJpxnQWixOGCrS+ro4Uvb4Re9+UTieUY2f8AEc+t7d4AaZ6eUJ3Hva7dtrxAAWHtlEFsXFMAgNnGU9uQ==} resolution: {integrity: sha512-pvz8ZZ7ot/RBphf8fv60ljmaoydPU12VuXHImtAs0XhLLw+EXBi2BLe3OYSBslR4rryHvweW5gmkKFwTiFy6KA==}
engines: {node: '>=18'} engines: {node: '>=18'}
cpu: [arm64] cpu: [arm64]
os: [android] os: [android]
'@esbuild/android-arm@0.27.1': '@esbuild/android-arm@0.27.2':
resolution: {integrity: sha512-kFqa6/UcaTbGm/NncN9kzVOODjhZW8e+FRdSeypWe6j33gzclHtwlANs26JrupOntlcWmB0u8+8HZo8s7thHvg==} resolution: {integrity: sha512-DVNI8jlPa7Ujbr1yjU2PfUSRtAUZPG9I1RwW4F4xFB1Imiu2on0ADiI/c3td+KmDtVKNbi+nffGDQMfcIMkwIA==}
engines: {node: '>=18'} engines: {node: '>=18'}
cpu: [arm] cpu: [arm]
os: [android] os: [android]
'@esbuild/android-x64@0.27.1': '@esbuild/android-x64@0.27.2':
resolution: {integrity: sha512-LBEpOz0BsgMEeHgenf5aqmn/lLNTFXVfoWMUox8CtWWYK9X4jmQzWjoGoNb8lmAYml/tQ/Ysvm8q7szu7BoxRQ==} resolution: {integrity: sha512-z8Ank4Byh4TJJOh4wpz8g2vDy75zFL0TlZlkUkEwYXuPSgX8yzep596n6mT7905kA9uHZsf/o2OJZubl2l3M7A==}
engines: {node: '>=18'} engines: {node: '>=18'}
cpu: [x64] cpu: [x64]
os: [android] os: [android]
'@esbuild/darwin-arm64@0.27.1': '@esbuild/darwin-arm64@0.27.2':
resolution: {integrity: sha512-veg7fL8eMSCVKL7IW4pxb54QERtedFDfY/ASrumK/SbFsXnRazxY4YykN/THYqFnFwJ0aVjiUrVG2PwcdAEqQQ==} resolution: {integrity: sha512-davCD2Zc80nzDVRwXTcQP/28fiJbcOwvdolL0sOiOsbwBa72kegmVU0Wrh1MYrbuCL98Omp5dVhQFWRKR2ZAlg==}
engines: {node: '>=18'} engines: {node: '>=18'}
cpu: [arm64] cpu: [arm64]
os: [darwin] os: [darwin]
'@esbuild/darwin-x64@0.27.1': '@esbuild/darwin-x64@0.27.2':
resolution: {integrity: sha512-+3ELd+nTzhfWb07Vol7EZ+5PTbJ/u74nC6iv4/lwIU99Ip5uuY6QoIf0Hn4m2HoV0qcnRivN3KSqc+FyCHjoVQ==} resolution: {integrity: sha512-ZxtijOmlQCBWGwbVmwOF/UCzuGIbUkqB1faQRf5akQmxRJ1ujusWsb3CVfk/9iZKr2L5SMU5wPBi1UWbvL+VQA==}
engines: {node: '>=18'} engines: {node: '>=18'}
cpu: [x64] cpu: [x64]
os: [darwin] os: [darwin]
'@esbuild/freebsd-arm64@0.27.1': '@esbuild/freebsd-arm64@0.27.2':
resolution: {integrity: sha512-/8Rfgns4XD9XOSXlzUDepG8PX+AVWHliYlUkFI3K3GB6tqbdjYqdhcb4BKRd7C0BhZSoaCxhv8kTcBrcZWP+xg==} resolution: {integrity: sha512-lS/9CN+rgqQ9czogxlMcBMGd+l8Q3Nj1MFQwBZJyoEKI50XGxwuzznYdwcav6lpOGv5BqaZXqvBSiB/kJ5op+g==}
engines: {node: '>=18'} engines: {node: '>=18'}
cpu: [arm64] cpu: [arm64]
os: [freebsd] os: [freebsd]
'@esbuild/freebsd-x64@0.27.1': '@esbuild/freebsd-x64@0.27.2':
resolution: {integrity: sha512-GITpD8dK9C+r+5yRT/UKVT36h/DQLOHdwGVwwoHidlnA168oD3uxA878XloXebK4Ul3gDBBIvEdL7go9gCUFzQ==} resolution: {integrity: sha512-tAfqtNYb4YgPnJlEFu4c212HYjQWSO/w/h/lQaBK7RbwGIkBOuNKQI9tqWzx7Wtp7bTPaGC6MJvWI608P3wXYA==}
engines: {node: '>=18'} engines: {node: '>=18'}
cpu: [x64] cpu: [x64]
os: [freebsd] os: [freebsd]
'@esbuild/linux-arm64@0.27.1': '@esbuild/linux-arm64@0.27.2':
resolution: {integrity: sha512-W9//kCrh/6in9rWIBdKaMtuTTzNj6jSeG/haWBADqLLa9P8O5YSRDzgD5y9QBok4AYlzS6ARHifAb75V6G670Q==} resolution: {integrity: sha512-hYxN8pr66NsCCiRFkHUAsxylNOcAQaxSSkHMMjcpx0si13t1LHFphxJZUiGwojB1a/Hd5OiPIqDdXONia6bhTw==}
engines: {node: '>=18'} engines: {node: '>=18'}
cpu: [arm64] cpu: [arm64]
os: [linux] os: [linux]
'@esbuild/linux-arm@0.27.1': '@esbuild/linux-arm@0.27.2':
resolution: {integrity: sha512-ieMID0JRZY/ZeCrsFQ3Y3NlHNCqIhTprJfDgSB3/lv5jJZ8FX3hqPyXWhe+gvS5ARMBJ242PM+VNz/ctNj//eA==} resolution: {integrity: sha512-vWfq4GaIMP9AIe4yj1ZUW18RDhx6EPQKjwe7n8BbIecFtCQG4CfHGaHuh7fdfq+y3LIA2vGS/o9ZBGVxIDi9hw==}
engines: {node: '>=18'} engines: {node: '>=18'}
cpu: [arm] cpu: [arm]
os: [linux] os: [linux]
'@esbuild/linux-ia32@0.27.1': '@esbuild/linux-ia32@0.27.2':
resolution: {integrity: sha512-VIUV4z8GD8rtSVMfAj1aXFahsi/+tcoXXNYmXgzISL+KB381vbSTNdeZHHHIYqFyXcoEhu9n5cT+05tRv13rlw==} resolution: {integrity: sha512-MJt5BRRSScPDwG2hLelYhAAKh9imjHK5+NE/tvnRLbIqUWa+0E9N4WNMjmp/kXXPHZGqPLxggwVhz7QP8CTR8w==}
engines: {node: '>=18'} engines: {node: '>=18'}
cpu: [ia32] cpu: [ia32]
os: [linux] os: [linux]
'@esbuild/linux-loong64@0.27.1': '@esbuild/linux-loong64@0.27.2':
resolution: {integrity: sha512-l4rfiiJRN7sTNI//ff65zJ9z8U+k6zcCg0LALU5iEWzY+a1mVZ8iWC1k5EsNKThZ7XCQ6YWtsZ8EWYm7r1UEsg==} resolution: {integrity: sha512-lugyF1atnAT463aO6KPshVCJK5NgRnU4yb3FUumyVz+cGvZbontBgzeGFO1nF+dPueHD367a2ZXe1NtUkAjOtg==}
engines: {node: '>=18'} engines: {node: '>=18'}
cpu: [loong64] cpu: [loong64]
os: [linux] os: [linux]
'@esbuild/linux-mips64el@0.27.1': '@esbuild/linux-mips64el@0.27.2':
resolution: {integrity: sha512-U0bEuAOLvO/DWFdygTHWY8C067FXz+UbzKgxYhXC0fDieFa0kDIra1FAhsAARRJbvEyso8aAqvPdNxzWuStBnA==} resolution: {integrity: sha512-nlP2I6ArEBewvJ2gjrrkESEZkB5mIoaTswuqNFRv/WYd+ATtUpe9Y09RnJvgvdag7he0OWgEZWhviS1OTOKixw==}
engines: {node: '>=18'} engines: {node: '>=18'}
cpu: [mips64el] cpu: [mips64el]
os: [linux] os: [linux]
'@esbuild/linux-ppc64@0.27.1': '@esbuild/linux-ppc64@0.27.2':
resolution: {integrity: sha512-NzdQ/Xwu6vPSf/GkdmRNsOfIeSGnh7muundsWItmBsVpMoNPVpM61qNzAVY3pZ1glzzAxLR40UyYM23eaDDbYQ==} resolution: {integrity: sha512-C92gnpey7tUQONqg1n6dKVbx3vphKtTHJaNG2Ok9lGwbZil6DrfyecMsp9CrmXGQJmZ7iiVXvvZH6Ml5hL6XdQ==}
engines: {node: '>=18'} engines: {node: '>=18'}
cpu: [ppc64] cpu: [ppc64]
os: [linux] os: [linux]
'@esbuild/linux-riscv64@0.27.1': '@esbuild/linux-riscv64@0.27.2':
resolution: {integrity: sha512-7zlw8p3IApcsN7mFw0O1Z1PyEk6PlKMu18roImfl3iQHTnr/yAfYv6s4hXPidbDoI2Q0pW+5xeoM4eTCC0UdrQ==} resolution: {integrity: sha512-B5BOmojNtUyN8AXlK0QJyvjEZkWwy/FKvakkTDCziX95AowLZKR6aCDhG7LeF7uMCXEJqwa8Bejz5LTPYm8AvA==}
engines: {node: '>=18'} engines: {node: '>=18'}
cpu: [riscv64] cpu: [riscv64]
os: [linux] os: [linux]
'@esbuild/linux-s390x@0.27.1': '@esbuild/linux-s390x@0.27.2':
resolution: {integrity: sha512-cGj5wli+G+nkVQdZo3+7FDKC25Uh4ZVwOAK6A06Hsvgr8WqBBuOy/1s+PUEd/6Je+vjfm6stX0kmib5b/O2Ykw==} resolution: {integrity: sha512-p4bm9+wsPwup5Z8f4EpfN63qNagQ47Ua2znaqGH6bqLlmJ4bx97Y9JdqxgGZ6Y8xVTixUnEkoKSHcpRlDnNr5w==}
engines: {node: '>=18'} engines: {node: '>=18'}
cpu: [s390x] cpu: [s390x]
os: [linux] os: [linux]
'@esbuild/linux-x64@0.27.1': '@esbuild/linux-x64@0.27.2':
resolution: {integrity: sha512-z3H/HYI9MM0HTv3hQZ81f+AKb+yEoCRlUby1F80vbQ5XdzEMyY/9iNlAmhqiBKw4MJXwfgsh7ERGEOhrM1niMA==} resolution: {integrity: sha512-uwp2Tip5aPmH+NRUwTcfLb+W32WXjpFejTIOWZFw/v7/KnpCDKG66u4DLcurQpiYTiYwQ9B7KOeMJvLCu/OvbA==}
engines: {node: '>=18'} engines: {node: '>=18'}
cpu: [x64] cpu: [x64]
os: [linux] os: [linux]
'@esbuild/netbsd-arm64@0.27.1': '@esbuild/netbsd-arm64@0.27.2':
resolution: {integrity: sha512-wzC24DxAvk8Em01YmVXyjl96Mr+ecTPyOuADAvjGg+fyBpGmxmcr2E5ttf7Im8D0sXZihpxzO1isus8MdjMCXQ==} resolution: {integrity: sha512-Kj6DiBlwXrPsCRDeRvGAUb/LNrBASrfqAIok+xB0LxK8CHqxZ037viF13ugfsIpePH93mX7xfJp97cyDuTZ3cw==}
engines: {node: '>=18'} engines: {node: '>=18'}
cpu: [arm64] cpu: [arm64]
os: [netbsd] os: [netbsd]
'@esbuild/netbsd-x64@0.27.1': '@esbuild/netbsd-x64@0.27.2':
resolution: {integrity: sha512-1YQ8ybGi2yIXswu6eNzJsrYIGFpnlzEWRl6iR5gMgmsrR0FcNoV1m9k9sc3PuP5rUBLshOZylc9nqSgymI+TYg==} resolution: {integrity: sha512-HwGDZ0VLVBY3Y+Nw0JexZy9o/nUAWq9MlV7cahpaXKW6TOzfVno3y3/M8Ga8u8Yr7GldLOov27xiCnqRZf0tCA==}
engines: {node: '>=18'} engines: {node: '>=18'}
cpu: [x64] cpu: [x64]
os: [netbsd] os: [netbsd]
'@esbuild/openbsd-arm64@0.27.1': '@esbuild/openbsd-arm64@0.27.2':
resolution: {integrity: sha512-5Z+DzLCrq5wmU7RDaMDe2DVXMRm2tTDvX2KU14JJVBN2CT/qov7XVix85QoJqHltpvAOZUAc3ndU56HSMWrv8g==} resolution: {integrity: sha512-DNIHH2BPQ5551A7oSHD0CKbwIA/Ox7+78/AWkbS5QoRzaqlev2uFayfSxq68EkonB+IKjiuxBFoV8ESJy8bOHA==}
engines: {node: '>=18'} engines: {node: '>=18'}
cpu: [arm64] cpu: [arm64]
os: [openbsd] os: [openbsd]
'@esbuild/openbsd-x64@0.27.1': '@esbuild/openbsd-x64@0.27.2':
resolution: {integrity: sha512-Q73ENzIdPF5jap4wqLtsfh8YbYSZ8Q0wnxplOlZUOyZy7B4ZKW8DXGWgTCZmF8VWD7Tciwv5F4NsRf6vYlZtqg==} resolution: {integrity: sha512-/it7w9Nb7+0KFIzjalNJVR5bOzA9Vay+yIPLVHfIQYG/j+j9VTH84aNB8ExGKPU4AzfaEvN9/V4HV+F+vo8OEg==}
engines: {node: '>=18'} engines: {node: '>=18'}
cpu: [x64] cpu: [x64]
os: [openbsd] os: [openbsd]
'@esbuild/openharmony-arm64@0.27.1': '@esbuild/openharmony-arm64@0.27.2':
resolution: {integrity: sha512-ajbHrGM/XiK+sXM0JzEbJAen+0E+JMQZ2l4RR4VFwvV9JEERx+oxtgkpoKv1SevhjavK2z2ReHk32pjzktWbGg==} resolution: {integrity: sha512-LRBbCmiU51IXfeXk59csuX/aSaToeG7w48nMwA6049Y4J4+VbWALAuXcs+qcD04rHDuSCSRKdmY63sruDS5qag==}
engines: {node: '>=18'} engines: {node: '>=18'}
cpu: [arm64] cpu: [arm64]
os: [openharmony] os: [openharmony]
'@esbuild/sunos-x64@0.27.1': '@esbuild/sunos-x64@0.27.2':
resolution: {integrity: sha512-IPUW+y4VIjuDVn+OMzHc5FV4GubIwPnsz6ubkvN8cuhEqH81NovB53IUlrlBkPMEPxvNnf79MGBoz8rZ2iW8HA==} resolution: {integrity: sha512-kMtx1yqJHTmqaqHPAzKCAkDaKsffmXkPHThSfRwZGyuqyIeBvf08KSsYXl+abf5HDAPMJIPnbBfXvP2ZC2TfHg==}
engines: {node: '>=18'} engines: {node: '>=18'}
cpu: [x64] cpu: [x64]
os: [sunos] os: [sunos]
'@esbuild/win32-arm64@0.27.1': '@esbuild/win32-arm64@0.27.2':
resolution: {integrity: sha512-RIVRWiljWA6CdVu8zkWcRmGP7iRRIIwvhDKem8UMBjPql2TXM5PkDVvvrzMtj1V+WFPB4K7zkIGM7VzRtFkjdg==} resolution: {integrity: sha512-Yaf78O/B3Kkh+nKABUF++bvJv5Ijoy9AN1ww904rOXZFLWVc5OLOfL56W+C8F9xn5JQZa3UX6m+IktJnIb1Jjg==}
engines: {node: '>=18'} engines: {node: '>=18'}
cpu: [arm64] cpu: [arm64]
os: [win32] os: [win32]
'@esbuild/win32-ia32@0.27.1': '@esbuild/win32-ia32@0.27.2':
resolution: {integrity: sha512-2BR5M8CPbptC1AK5JbJT1fWrHLvejwZidKx3UMSF0ecHMa+smhi16drIrCEggkgviBwLYd5nwrFLSl5Kho96RQ==} resolution: {integrity: sha512-Iuws0kxo4yusk7sw70Xa2E2imZU5HoixzxfGCdxwBdhiDgt9vX9VUCBhqcwY7/uh//78A1hMkkROMJq9l27oLQ==}
engines: {node: '>=18'} engines: {node: '>=18'}
cpu: [ia32] cpu: [ia32]
os: [win32] os: [win32]
'@esbuild/win32-x64@0.27.1': '@esbuild/win32-x64@0.27.2':
resolution: {integrity: sha512-d5X6RMYv6taIymSk8JBP+nxv8DQAMY6A51GPgusqLdK9wBz5wWIXy1KjTck6HnjE9hqJzJRdk+1p/t5soSbCtw==} resolution: {integrity: sha512-sRdU18mcKf7F+YgheI/zGf5alZatMUTKj/jNS6l744f9u3WFu4v7twcUI9vu4mknF4Y9aDlblIie0IM+5xxaqQ==}
engines: {node: '>=18'} engines: {node: '>=18'}
cpu: [x64] cpu: [x64]
os: [win32] os: [win32]
@@ -593,19 +587,6 @@ packages:
'@radix-ui/primitive@1.1.3': '@radix-ui/primitive@1.1.3':
resolution: {integrity: sha512-JTF99U/6XIjCBo0wqkU5sK10glYe27MRRsfwoiq5zzOEZLHU3A3KCMa5X/azekYRCJ0HlwI0crAXS/5dEHTzDg==} resolution: {integrity: sha512-JTF99U/6XIjCBo0wqkU5sK10glYe27MRRsfwoiq5zzOEZLHU3A3KCMa5X/azekYRCJ0HlwI0crAXS/5dEHTzDg==}
'@radix-ui/react-accordion@1.2.12':
resolution: {integrity: sha512-T4nygeh9YE9dLRPhAHSeOZi7HBXo+0kYIPJXayZfvWOWA0+n3dESrZbjfDPUABkUNym6Hd+f2IR113To8D2GPA==}
peerDependencies:
'@types/react': '*'
'@types/react-dom': '*'
react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
peerDependenciesMeta:
'@types/react':
optional: true
'@types/react-dom':
optional: true
'@radix-ui/react-arrow@1.1.7': '@radix-ui/react-arrow@1.1.7':
resolution: {integrity: sha512-F+M1tLhO+mlQaOWspE8Wstg+z6PwxwRd8oQ8IXceWz92kfAmalTRf0EjrouQeo7QssEPfCn05B4Ihs1K9WQ/7w==} resolution: {integrity: sha512-F+M1tLhO+mlQaOWspE8Wstg+z6PwxwRd8oQ8IXceWz92kfAmalTRf0EjrouQeo7QssEPfCn05B4Ihs1K9WQ/7w==}
peerDependencies: peerDependencies:
@@ -632,19 +613,6 @@ packages:
'@types/react-dom': '@types/react-dom':
optional: true optional: true
'@radix-ui/react-collapsible@1.1.12':
resolution: {integrity: sha512-Uu+mSh4agx2ib1uIGPP4/CKNULyajb3p92LsVXmH2EHVMTfZWpll88XJ0j4W0z3f8NK1eYl1+Mf/szHPmcHzyA==}
peerDependencies:
'@types/react': '*'
'@types/react-dom': '*'
react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
peerDependenciesMeta:
'@types/react':
optional: true
'@types/react-dom':
optional: true
'@radix-ui/react-collection@1.1.7': '@radix-ui/react-collection@1.1.7':
resolution: {integrity: sha512-Fh9rGN0MoI4ZFUNyfFVNU4y9LUz93u9/0K+yLgA2bwRojxM8JU1DyvvMBabnZPBgMWREAJvU2jjVzq+LrFUglw==} resolution: {integrity: sha512-Fh9rGN0MoI4ZFUNyfFVNU4y9LUz93u9/0K+yLgA2bwRojxM8JU1DyvvMBabnZPBgMWREAJvU2jjVzq+LrFUglw==}
peerDependencies: peerDependencies:
@@ -881,19 +849,6 @@ packages:
'@types/react-dom': '@types/react-dom':
optional: true optional: true
'@radix-ui/react-radio-group@1.3.8':
resolution: {integrity: sha512-VBKYIYImA5zsxACdisNQ3BjCBfmbGH3kQlnFVqlWU4tXwjy7cGX8ta80BcrO+WJXIn5iBylEH3K6ZTlee//lgQ==}
peerDependencies:
'@types/react': '*'
'@types/react-dom': '*'
react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
peerDependenciesMeta:
'@types/react':
optional: true
'@types/react-dom':
optional: true
'@radix-ui/react-roving-focus@1.1.11': '@radix-ui/react-roving-focus@1.1.11':
resolution: {integrity: sha512-7A6S9jSgm/S+7MdtNDSb+IU859vQqJ/QAtcYQcfFC6W8RS4IxIZDldLR0xqCFZ6DCyrQLjLPsxtTNch5jVA4lA==} resolution: {integrity: sha512-7A6S9jSgm/S+7MdtNDSb+IU859vQqJ/QAtcYQcfFC6W8RS4IxIZDldLR0xqCFZ6DCyrQLjLPsxtTNch5jVA4lA==}
peerDependencies: peerDependencies:
@@ -951,19 +906,6 @@ packages:
'@types/react-dom': '@types/react-dom':
optional: true optional: true
'@radix-ui/react-tabs@1.1.13':
resolution: {integrity: sha512-7xdcatg7/U+7+Udyoj2zodtI9H/IIopqo+YOIcZOq1nJwXWBZ9p8xiu5llXlekDbZkca79a/fozEYQXIA4sW6A==}
peerDependencies:
'@types/react': '*'
'@types/react-dom': '*'
react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
peerDependenciesMeta:
'@types/react':
optional: true
'@types/react-dom':
optional: true
'@radix-ui/react-tooltip@1.2.8': '@radix-ui/react-tooltip@1.2.8':
resolution: {integrity: sha512-tY7sVt1yL9ozIxvmbtN5qtmH2krXcBCfjEiCgKGLqunJHvgvZG2Pcl2oQ3kbcZARb1BGEHdkLzcYGO8ynVlieg==} resolution: {integrity: sha512-tY7sVt1yL9ozIxvmbtN5qtmH2krXcBCfjEiCgKGLqunJHvgvZG2Pcl2oQ3kbcZARb1BGEHdkLzcYGO8ynVlieg==}
peerDependencies: peerDependencies:
@@ -1286,8 +1228,8 @@ packages:
'@types/json-schema@7.0.15': '@types/json-schema@7.0.15':
resolution: {integrity: sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==} resolution: {integrity: sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==}
'@types/node@25.0.2': '@types/node@25.0.3':
resolution: {integrity: sha512-gWEkeiyYE4vqjON/+Obqcoeffmk0NF15WSBwSs7zwVA2bAbTaE0SJ7P0WNGoJn8uE7fiaV5a7dKYIJriEqOrmA==} resolution: {integrity: sha512-W609buLVRVmeW693xKfzHeIV6nJGGz98uCPfeXI1ELMLXVeKYZ9m15fAMSaUPBHYLGFsVRcMmSCksQOrZV9BYA==}
'@types/react-dom@19.2.3': '@types/react-dom@19.2.3':
resolution: {integrity: sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ==} resolution: {integrity: sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ==}
@@ -1389,8 +1331,8 @@ packages:
balanced-match@1.0.2: balanced-match@1.0.2:
resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==} resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==}
baseline-browser-mapping@2.9.7: baseline-browser-mapping@2.9.11:
resolution: {integrity: sha512-k9xFKplee6KIio3IDbwj+uaCLpqzOwakOgmqzPezM0sFJlFKcg30vk2wOiAJtkTSfx0SSQDSe8q+mWA/fSH5Zg==} resolution: {integrity: sha512-Sg0xJUNDU1sJNGdfGWhVHX0kkZ+HWcvmVymJbj6NSgZZmW/8S9Y2HQ5euytnIgakgxN6papOAWiwDo1ctFDcoQ==}
hasBin: true hasBin: true
brace-expansion@1.1.12: brace-expansion@1.1.12:
@@ -1408,8 +1350,8 @@ packages:
resolution: {integrity: sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==} resolution: {integrity: sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==}
engines: {node: '>=6'} engines: {node: '>=6'}
caniuse-lite@1.0.30001760: caniuse-lite@1.0.30001761:
resolution: {integrity: sha512-7AAMPcueWELt1p3mi13HR/LHH0TJLT11cnwDJEs3xA4+CK/PLKeO9Kl1oru24htkyUKtkGCvAx4ohB0Ttry8Dw==} resolution: {integrity: sha512-JF9ptu1vP2coz98+5051jZ4PwQgd2ni8A+gYSN7EA7dPKIMf0pDlSUxhdmVOaV3/fYK5uWBkgSXJaRLr4+3A6g==}
chalk@4.1.2: chalk@4.1.2:
resolution: {integrity: sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==} resolution: {integrity: sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==}
@@ -1468,8 +1410,8 @@ packages:
resolution: {integrity: sha512-LgQMM4WXU3QI+SYgEc2liRgznaD5ojbmY3sb8LxyguVkIg5FxdpTkvk72te2R38/TGKxH634oLxXRGY6d7AP+Q==} resolution: {integrity: sha512-LgQMM4WXU3QI+SYgEc2liRgznaD5ojbmY3sb8LxyguVkIg5FxdpTkvk72te2R38/TGKxH634oLxXRGY6d7AP+Q==}
engines: {node: '>=10.13.0'} engines: {node: '>=10.13.0'}
esbuild@0.27.1: esbuild@0.27.2:
resolution: {integrity: sha512-yY35KZckJJuVVPXpvjgxiCuVEJT67F6zDeVTv4rizyPrfGBUpZQsvmxnN+C371c2esD/hNMjj4tpBhuueLN7aA==} resolution: {integrity: sha512-HyNQImnsOC7X9PMNaCIeAm4ISCQXs5a5YasTXVliKv4uuBo1dKrG0A+uQS8M5eXjVMnLg3WgXaKvprHlFJQffw==}
engines: {node: '>=18'} engines: {node: '>=18'}
hasBin: true hasBin: true
@@ -1487,8 +1429,8 @@ packages:
peerDependencies: peerDependencies:
eslint: ^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0-0 || ^9.0.0 eslint: ^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0-0 || ^9.0.0
eslint-plugin-react-refresh@0.4.25: eslint-plugin-react-refresh@0.4.26:
resolution: {integrity: sha512-dRUD2LOdEqI4zXHqbQ442blQAzdSuShAaiSq5Vtyy6LT08YUf0oOjBDo4VPx0dCPgiPWh1WB4dtbLOd0kOlDPQ==} resolution: {integrity: sha512-1RETEylht2O6FM/MvgnyvT+8K21wLqDNg4qD51Zj3guhjt433XbnnkVttHMyaVyAFD03QSV4LPS5iE3VQmO7XQ==}
peerDependencies: peerDependencies:
eslint: '>=8.40' eslint: '>=8.40'
@@ -1567,6 +1509,20 @@ packages:
flatted@3.3.3: flatted@3.3.3:
resolution: {integrity: sha512-GX+ysw4PBCz0PzosHDepZGANEuFCMLrnRTiEy9McGjmkCQYwRq4A/X786G/fjM/+OjsWSU1ZrY5qyARZmO/uwg==} resolution: {integrity: sha512-GX+ysw4PBCz0PzosHDepZGANEuFCMLrnRTiEy9McGjmkCQYwRq4A/X786G/fjM/+OjsWSU1ZrY5qyARZmO/uwg==}
framer-motion@12.23.26:
resolution: {integrity: sha512-cPcIhgR42xBn1Uj+PzOyheMtZ73H927+uWPDVhUMqxy8UHt6Okavb6xIz9J/phFUHUj0OncR6UvMfJTXoc/LKA==}
peerDependencies:
'@emotion/is-prop-valid': '*'
react: ^18.0.0 || ^19.0.0
react-dom: ^18.0.0 || ^19.0.0
peerDependenciesMeta:
'@emotion/is-prop-valid':
optional: true
react:
optional: true
react-dom:
optional: true
fsevents@2.3.3: fsevents@2.3.3:
resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==}
engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0}
@@ -1749,8 +1705,8 @@ packages:
lru-cache@5.1.1: lru-cache@5.1.1:
resolution: {integrity: sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==} resolution: {integrity: sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==}
lucide-react@0.561.0: lucide-react@0.562.0:
resolution: {integrity: sha512-Y59gMY38tl4/i0qewcqohPdEbieBy7SovpBL9IFebhc2mDd8x4PZSOsiFRkpPcOq6bj1r/mjH/Rk73gSlIJP2A==} resolution: {integrity: sha512-82hOAu7y0dbVuFfmO4bYF1XEwYk/mEbM5E+b1jgci/udUBEE/R7LF5Ip0CCEmXe8AybRM8L+04eP+LGZeDvkiw==}
peerDependencies: peerDependencies:
react: ^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0 react: ^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0
@@ -1764,6 +1720,26 @@ packages:
resolution: {integrity: sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow==} resolution: {integrity: sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow==}
engines: {node: '>=16 || 14 >=14.17'} engines: {node: '>=16 || 14 >=14.17'}
motion-dom@12.23.23:
resolution: {integrity: sha512-n5yolOs0TQQBRUFImrRfs/+6X4p3Q4n1dUEqt/H58Vx7OW6RF+foWEgmTVDhIWJIMXOuNNL0apKH2S16en9eiA==}
motion-utils@12.23.6:
resolution: {integrity: sha512-eAWoPgr4eFEOFfg2WjIsMoqJTW6Z8MTUCgn/GZ3VRpClWBdnbjryiA3ZSNLyxCTmCQx4RmYX6jX1iWHbenUPNQ==}
motion@12.23.26:
resolution: {integrity: sha512-Ll8XhVxY8LXMVYTCfme27WH2GjBrCIzY4+ndr5QKxsK+YwCtOi2B/oBi5jcIbik5doXuWT/4KKDOVAZJkeY5VQ==}
peerDependencies:
'@emotion/is-prop-valid': '*'
react: ^18.0.0 || ^19.0.0
react-dom: ^18.0.0 || ^19.0.0
peerDependenciesMeta:
'@emotion/is-prop-valid':
optional: true
react:
optional: true
react-dom:
optional: true
ms@2.1.3: ms@2.1.3:
resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==} resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==}
@@ -1966,8 +1942,8 @@ packages:
undici-types@7.16.0: undici-types@7.16.0:
resolution: {integrity: sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==} resolution: {integrity: sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==}
update-browserslist-db@1.2.2: update-browserslist-db@1.2.3:
resolution: {integrity: sha512-E85pfNzMQ9jpKkA7+TJAi4TJN+tBCuWh5rUcS/sv6cFi+1q9LYDwDI5dpUL0u/73EElyQ8d3TEaeW4sPedBqYA==} resolution: {integrity: sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w==}
hasBin: true hasBin: true
peerDependencies: peerDependencies:
browserslist: '>= 4.21.0' browserslist: '>= 4.21.0'
@@ -2179,82 +2155,82 @@ snapshots:
tslib: 2.8.1 tslib: 2.8.1
optional: true optional: true
'@esbuild/aix-ppc64@0.27.1': '@esbuild/aix-ppc64@0.27.2':
optional: true optional: true
'@esbuild/android-arm64@0.27.1': '@esbuild/android-arm64@0.27.2':
optional: true optional: true
'@esbuild/android-arm@0.27.1': '@esbuild/android-arm@0.27.2':
optional: true optional: true
'@esbuild/android-x64@0.27.1': '@esbuild/android-x64@0.27.2':
optional: true optional: true
'@esbuild/darwin-arm64@0.27.1': '@esbuild/darwin-arm64@0.27.2':
optional: true optional: true
'@esbuild/darwin-x64@0.27.1': '@esbuild/darwin-x64@0.27.2':
optional: true optional: true
'@esbuild/freebsd-arm64@0.27.1': '@esbuild/freebsd-arm64@0.27.2':
optional: true optional: true
'@esbuild/freebsd-x64@0.27.1': '@esbuild/freebsd-x64@0.27.2':
optional: true optional: true
'@esbuild/linux-arm64@0.27.1': '@esbuild/linux-arm64@0.27.2':
optional: true optional: true
'@esbuild/linux-arm@0.27.1': '@esbuild/linux-arm@0.27.2':
optional: true optional: true
'@esbuild/linux-ia32@0.27.1': '@esbuild/linux-ia32@0.27.2':
optional: true optional: true
'@esbuild/linux-loong64@0.27.1': '@esbuild/linux-loong64@0.27.2':
optional: true optional: true
'@esbuild/linux-mips64el@0.27.1': '@esbuild/linux-mips64el@0.27.2':
optional: true optional: true
'@esbuild/linux-ppc64@0.27.1': '@esbuild/linux-ppc64@0.27.2':
optional: true optional: true
'@esbuild/linux-riscv64@0.27.1': '@esbuild/linux-riscv64@0.27.2':
optional: true optional: true
'@esbuild/linux-s390x@0.27.1': '@esbuild/linux-s390x@0.27.2':
optional: true optional: true
'@esbuild/linux-x64@0.27.1': '@esbuild/linux-x64@0.27.2':
optional: true optional: true
'@esbuild/netbsd-arm64@0.27.1': '@esbuild/netbsd-arm64@0.27.2':
optional: true optional: true
'@esbuild/netbsd-x64@0.27.1': '@esbuild/netbsd-x64@0.27.2':
optional: true optional: true
'@esbuild/openbsd-arm64@0.27.1': '@esbuild/openbsd-arm64@0.27.2':
optional: true optional: true
'@esbuild/openbsd-x64@0.27.1': '@esbuild/openbsd-x64@0.27.2':
optional: true optional: true
'@esbuild/openharmony-arm64@0.27.1': '@esbuild/openharmony-arm64@0.27.2':
optional: true optional: true
'@esbuild/sunos-x64@0.27.1': '@esbuild/sunos-x64@0.27.2':
optional: true optional: true
'@esbuild/win32-arm64@0.27.1': '@esbuild/win32-arm64@0.27.2':
optional: true optional: true
'@esbuild/win32-ia32@0.27.1': '@esbuild/win32-ia32@0.27.2':
optional: true optional: true
'@esbuild/win32-x64@0.27.1': '@esbuild/win32-x64@0.27.2':
optional: true optional: true
'@eslint-community/eslint-utils@4.9.0(eslint@9.39.2(jiti@2.6.1))': '@eslint-community/eslint-utils@4.9.0(eslint@9.39.2(jiti@2.6.1))':
@@ -2450,23 +2426,6 @@ snapshots:
'@radix-ui/primitive@1.1.3': {} '@radix-ui/primitive@1.1.3': {}
'@radix-ui/react-accordion@1.2.12(@types/react-dom@19.2.3(@types/react@19.2.7))(@types/react@19.2.7)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)':
dependencies:
'@radix-ui/primitive': 1.1.3
'@radix-ui/react-collapsible': 1.1.12(@types/react-dom@19.2.3(@types/react@19.2.7))(@types/react@19.2.7)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
'@radix-ui/react-collection': 1.1.7(@types/react-dom@19.2.3(@types/react@19.2.7))(@types/react@19.2.7)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
'@radix-ui/react-compose-refs': 1.1.2(@types/react@19.2.7)(react@19.2.3)
'@radix-ui/react-context': 1.1.2(@types/react@19.2.7)(react@19.2.3)
'@radix-ui/react-direction': 1.1.1(@types/react@19.2.7)(react@19.2.3)
'@radix-ui/react-id': 1.1.1(@types/react@19.2.7)(react@19.2.3)
'@radix-ui/react-primitive': 2.1.3(@types/react-dom@19.2.3(@types/react@19.2.7))(@types/react@19.2.7)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
'@radix-ui/react-use-controllable-state': 1.2.2(@types/react@19.2.7)(react@19.2.3)
react: 19.2.3
react-dom: 19.2.3(react@19.2.3)
optionalDependencies:
'@types/react': 19.2.7
'@types/react-dom': 19.2.3(@types/react@19.2.7)
'@radix-ui/react-arrow@1.1.7(@types/react-dom@19.2.3(@types/react@19.2.7))(@types/react@19.2.7)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)': '@radix-ui/react-arrow@1.1.7(@types/react-dom@19.2.3(@types/react@19.2.7))(@types/react@19.2.7)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)':
dependencies: dependencies:
'@radix-ui/react-primitive': 2.1.3(@types/react-dom@19.2.3(@types/react@19.2.7))(@types/react@19.2.7)(react-dom@19.2.3(react@19.2.3))(react@19.2.3) '@radix-ui/react-primitive': 2.1.3(@types/react-dom@19.2.3(@types/react@19.2.7))(@types/react@19.2.7)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
@@ -2492,22 +2451,6 @@ snapshots:
'@types/react': 19.2.7 '@types/react': 19.2.7
'@types/react-dom': 19.2.3(@types/react@19.2.7) '@types/react-dom': 19.2.3(@types/react@19.2.7)
'@radix-ui/react-collapsible@1.1.12(@types/react-dom@19.2.3(@types/react@19.2.7))(@types/react@19.2.7)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)':
dependencies:
'@radix-ui/primitive': 1.1.3
'@radix-ui/react-compose-refs': 1.1.2(@types/react@19.2.7)(react@19.2.3)
'@radix-ui/react-context': 1.1.2(@types/react@19.2.7)(react@19.2.3)
'@radix-ui/react-id': 1.1.1(@types/react@19.2.7)(react@19.2.3)
'@radix-ui/react-presence': 1.1.5(@types/react-dom@19.2.3(@types/react@19.2.7))(@types/react@19.2.7)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
'@radix-ui/react-primitive': 2.1.3(@types/react-dom@19.2.3(@types/react@19.2.7))(@types/react@19.2.7)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
'@radix-ui/react-use-controllable-state': 1.2.2(@types/react@19.2.7)(react@19.2.3)
'@radix-ui/react-use-layout-effect': 1.1.1(@types/react@19.2.7)(react@19.2.3)
react: 19.2.3
react-dom: 19.2.3(react@19.2.3)
optionalDependencies:
'@types/react': 19.2.7
'@types/react-dom': 19.2.3(@types/react@19.2.7)
'@radix-ui/react-collection@1.1.7(@types/react-dom@19.2.3(@types/react@19.2.7))(@types/react@19.2.7)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)': '@radix-ui/react-collection@1.1.7(@types/react-dom@19.2.3(@types/react@19.2.7))(@types/react@19.2.7)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)':
dependencies: dependencies:
'@radix-ui/react-compose-refs': 1.1.2(@types/react@19.2.7)(react@19.2.3) '@radix-ui/react-compose-refs': 1.1.2(@types/react@19.2.7)(react@19.2.3)
@@ -2733,24 +2676,6 @@ snapshots:
'@types/react': 19.2.7 '@types/react': 19.2.7
'@types/react-dom': 19.2.3(@types/react@19.2.7) '@types/react-dom': 19.2.3(@types/react@19.2.7)
'@radix-ui/react-radio-group@1.3.8(@types/react-dom@19.2.3(@types/react@19.2.7))(@types/react@19.2.7)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)':
dependencies:
'@radix-ui/primitive': 1.1.3
'@radix-ui/react-compose-refs': 1.1.2(@types/react@19.2.7)(react@19.2.3)
'@radix-ui/react-context': 1.1.2(@types/react@19.2.7)(react@19.2.3)
'@radix-ui/react-direction': 1.1.1(@types/react@19.2.7)(react@19.2.3)
'@radix-ui/react-presence': 1.1.5(@types/react-dom@19.2.3(@types/react@19.2.7))(@types/react@19.2.7)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
'@radix-ui/react-primitive': 2.1.3(@types/react-dom@19.2.3(@types/react@19.2.7))(@types/react@19.2.7)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
'@radix-ui/react-roving-focus': 1.1.11(@types/react-dom@19.2.3(@types/react@19.2.7))(@types/react@19.2.7)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
'@radix-ui/react-use-controllable-state': 1.2.2(@types/react@19.2.7)(react@19.2.3)
'@radix-ui/react-use-previous': 1.1.1(@types/react@19.2.7)(react@19.2.3)
'@radix-ui/react-use-size': 1.1.1(@types/react@19.2.7)(react@19.2.3)
react: 19.2.3
react-dom: 19.2.3(react@19.2.3)
optionalDependencies:
'@types/react': 19.2.7
'@types/react-dom': 19.2.3(@types/react@19.2.7)
'@radix-ui/react-roving-focus@1.1.11(@types/react-dom@19.2.3(@types/react@19.2.7))(@types/react@19.2.7)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)': '@radix-ui/react-roving-focus@1.1.11(@types/react-dom@19.2.3(@types/react@19.2.7))(@types/react@19.2.7)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)':
dependencies: dependencies:
'@radix-ui/primitive': 1.1.3 '@radix-ui/primitive': 1.1.3
@@ -2826,22 +2751,6 @@ snapshots:
'@types/react': 19.2.7 '@types/react': 19.2.7
'@types/react-dom': 19.2.3(@types/react@19.2.7) '@types/react-dom': 19.2.3(@types/react@19.2.7)
'@radix-ui/react-tabs@1.1.13(@types/react-dom@19.2.3(@types/react@19.2.7))(@types/react@19.2.7)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)':
dependencies:
'@radix-ui/primitive': 1.1.3
'@radix-ui/react-context': 1.1.2(@types/react@19.2.7)(react@19.2.3)
'@radix-ui/react-direction': 1.1.1(@types/react@19.2.7)(react@19.2.3)
'@radix-ui/react-id': 1.1.1(@types/react@19.2.7)(react@19.2.3)
'@radix-ui/react-presence': 1.1.5(@types/react-dom@19.2.3(@types/react@19.2.7))(@types/react@19.2.7)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
'@radix-ui/react-primitive': 2.1.3(@types/react-dom@19.2.3(@types/react@19.2.7))(@types/react@19.2.7)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
'@radix-ui/react-roving-focus': 1.1.11(@types/react-dom@19.2.3(@types/react@19.2.7))(@types/react@19.2.7)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
'@radix-ui/react-use-controllable-state': 1.2.2(@types/react@19.2.7)(react@19.2.3)
react: 19.2.3
react-dom: 19.2.3(react@19.2.3)
optionalDependencies:
'@types/react': 19.2.7
'@types/react-dom': 19.2.3(@types/react@19.2.7)
'@radix-ui/react-tooltip@1.2.8(@types/react-dom@19.2.3(@types/react@19.2.7))(@types/react@19.2.7)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)': '@radix-ui/react-tooltip@1.2.8(@types/react-dom@19.2.3(@types/react@19.2.7))(@types/react@19.2.7)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)':
dependencies: dependencies:
'@radix-ui/primitive': 1.1.3 '@radix-ui/primitive': 1.1.3
@@ -3056,12 +2965,12 @@ snapshots:
'@tailwindcss/oxide-win32-arm64-msvc': 4.1.18 '@tailwindcss/oxide-win32-arm64-msvc': 4.1.18
'@tailwindcss/oxide-win32-x64-msvc': 4.1.18 '@tailwindcss/oxide-win32-x64-msvc': 4.1.18
'@tailwindcss/vite@4.1.18(vite@7.3.0(@types/node@25.0.2)(jiti@2.6.1)(lightningcss@1.30.2))': '@tailwindcss/vite@4.1.18(vite@7.3.0(@types/node@25.0.3)(jiti@2.6.1)(lightningcss@1.30.2))':
dependencies: dependencies:
'@tailwindcss/node': 4.1.18 '@tailwindcss/node': 4.1.18
'@tailwindcss/oxide': 4.1.18 '@tailwindcss/oxide': 4.1.18
tailwindcss: 4.1.18 tailwindcss: 4.1.18
vite: 7.3.0(@types/node@25.0.2)(jiti@2.6.1)(lightningcss@1.30.2) vite: 7.3.0(@types/node@25.0.3)(jiti@2.6.1)(lightningcss@1.30.2)
'@types/babel__core@7.20.5': '@types/babel__core@7.20.5':
dependencies: dependencies:
@@ -3088,7 +2997,7 @@ snapshots:
'@types/json-schema@7.0.15': {} '@types/json-schema@7.0.15': {}
'@types/node@25.0.2': '@types/node@25.0.3':
dependencies: dependencies:
undici-types: 7.16.0 undici-types: 7.16.0
@@ -3191,7 +3100,7 @@ snapshots:
'@typescript-eslint/types': 8.50.0 '@typescript-eslint/types': 8.50.0
eslint-visitor-keys: 4.2.1 eslint-visitor-keys: 4.2.1
'@vitejs/plugin-react@5.1.2(vite@7.3.0(@types/node@25.0.2)(jiti@2.6.1)(lightningcss@1.30.2))': '@vitejs/plugin-react@5.1.2(vite@7.3.0(@types/node@25.0.3)(jiti@2.6.1)(lightningcss@1.30.2))':
dependencies: dependencies:
'@babel/core': 7.28.5 '@babel/core': 7.28.5
'@babel/plugin-transform-react-jsx-self': 7.27.1(@babel/core@7.28.5) '@babel/plugin-transform-react-jsx-self': 7.27.1(@babel/core@7.28.5)
@@ -3199,7 +3108,7 @@ snapshots:
'@rolldown/pluginutils': 1.0.0-beta.53 '@rolldown/pluginutils': 1.0.0-beta.53
'@types/babel__core': 7.20.5 '@types/babel__core': 7.20.5
react-refresh: 0.18.0 react-refresh: 0.18.0
vite: 7.3.0(@types/node@25.0.2)(jiti@2.6.1)(lightningcss@1.30.2) vite: 7.3.0(@types/node@25.0.3)(jiti@2.6.1)(lightningcss@1.30.2)
transitivePeerDependencies: transitivePeerDependencies:
- supports-color - supports-color
@@ -3228,7 +3137,7 @@ snapshots:
balanced-match@1.0.2: {} balanced-match@1.0.2: {}
baseline-browser-mapping@2.9.7: {} baseline-browser-mapping@2.9.11: {}
brace-expansion@1.1.12: brace-expansion@1.1.12:
dependencies: dependencies:
@@ -3241,15 +3150,15 @@ snapshots:
browserslist@4.28.1: browserslist@4.28.1:
dependencies: dependencies:
baseline-browser-mapping: 2.9.7 baseline-browser-mapping: 2.9.11
caniuse-lite: 1.0.30001760 caniuse-lite: 1.0.30001761
electron-to-chromium: 1.5.267 electron-to-chromium: 1.5.267
node-releases: 2.0.27 node-releases: 2.0.27
update-browserslist-db: 1.2.2(browserslist@4.28.1) update-browserslist-db: 1.2.3(browserslist@4.28.1)
callsites@3.1.0: {} callsites@3.1.0: {}
caniuse-lite@1.0.30001760: {} caniuse-lite@1.0.30001761: {}
chalk@4.1.2: chalk@4.1.2:
dependencies: dependencies:
@@ -3297,34 +3206,34 @@ snapshots:
graceful-fs: 4.2.11 graceful-fs: 4.2.11
tapable: 2.3.0 tapable: 2.3.0
esbuild@0.27.1: esbuild@0.27.2:
optionalDependencies: optionalDependencies:
'@esbuild/aix-ppc64': 0.27.1 '@esbuild/aix-ppc64': 0.27.2
'@esbuild/android-arm': 0.27.1 '@esbuild/android-arm': 0.27.2
'@esbuild/android-arm64': 0.27.1 '@esbuild/android-arm64': 0.27.2
'@esbuild/android-x64': 0.27.1 '@esbuild/android-x64': 0.27.2
'@esbuild/darwin-arm64': 0.27.1 '@esbuild/darwin-arm64': 0.27.2
'@esbuild/darwin-x64': 0.27.1 '@esbuild/darwin-x64': 0.27.2
'@esbuild/freebsd-arm64': 0.27.1 '@esbuild/freebsd-arm64': 0.27.2
'@esbuild/freebsd-x64': 0.27.1 '@esbuild/freebsd-x64': 0.27.2
'@esbuild/linux-arm': 0.27.1 '@esbuild/linux-arm': 0.27.2
'@esbuild/linux-arm64': 0.27.1 '@esbuild/linux-arm64': 0.27.2
'@esbuild/linux-ia32': 0.27.1 '@esbuild/linux-ia32': 0.27.2
'@esbuild/linux-loong64': 0.27.1 '@esbuild/linux-loong64': 0.27.2
'@esbuild/linux-mips64el': 0.27.1 '@esbuild/linux-mips64el': 0.27.2
'@esbuild/linux-ppc64': 0.27.1 '@esbuild/linux-ppc64': 0.27.2
'@esbuild/linux-riscv64': 0.27.1 '@esbuild/linux-riscv64': 0.27.2
'@esbuild/linux-s390x': 0.27.1 '@esbuild/linux-s390x': 0.27.2
'@esbuild/linux-x64': 0.27.1 '@esbuild/linux-x64': 0.27.2
'@esbuild/netbsd-arm64': 0.27.1 '@esbuild/netbsd-arm64': 0.27.2
'@esbuild/netbsd-x64': 0.27.1 '@esbuild/netbsd-x64': 0.27.2
'@esbuild/openbsd-arm64': 0.27.1 '@esbuild/openbsd-arm64': 0.27.2
'@esbuild/openbsd-x64': 0.27.1 '@esbuild/openbsd-x64': 0.27.2
'@esbuild/openharmony-arm64': 0.27.1 '@esbuild/openharmony-arm64': 0.27.2
'@esbuild/sunos-x64': 0.27.1 '@esbuild/sunos-x64': 0.27.2
'@esbuild/win32-arm64': 0.27.1 '@esbuild/win32-arm64': 0.27.2
'@esbuild/win32-ia32': 0.27.1 '@esbuild/win32-ia32': 0.27.2
'@esbuild/win32-x64': 0.27.1 '@esbuild/win32-x64': 0.27.2
escalade@3.2.0: {} escalade@3.2.0: {}
@@ -3341,7 +3250,7 @@ snapshots:
transitivePeerDependencies: transitivePeerDependencies:
- supports-color - supports-color
eslint-plugin-react-refresh@0.4.25(eslint@9.39.2(jiti@2.6.1)): eslint-plugin-react-refresh@0.4.26(eslint@9.39.2(jiti@2.6.1)):
dependencies: dependencies:
eslint: 9.39.2(jiti@2.6.1) eslint: 9.39.2(jiti@2.6.1)
@@ -3439,6 +3348,15 @@ snapshots:
flatted@3.3.3: {} flatted@3.3.3: {}
framer-motion@12.23.26(react-dom@19.2.3(react@19.2.3))(react@19.2.3):
dependencies:
motion-dom: 12.23.23
motion-utils: 12.23.6
tslib: 2.8.1
optionalDependencies:
react: 19.2.3
react-dom: 19.2.3(react@19.2.3)
fsevents@2.3.3: fsevents@2.3.3:
optional: true optional: true
@@ -3569,7 +3487,7 @@ snapshots:
dependencies: dependencies:
yallist: 3.1.1 yallist: 3.1.1
lucide-react@0.561.0(react@19.2.3): lucide-react@0.562.0(react@19.2.3):
dependencies: dependencies:
react: 19.2.3 react: 19.2.3
@@ -3585,6 +3503,20 @@ snapshots:
dependencies: dependencies:
brace-expansion: 2.0.2 brace-expansion: 2.0.2
motion-dom@12.23.23:
dependencies:
motion-utils: 12.23.6
motion-utils@12.23.6: {}
motion@12.23.26(react-dom@19.2.3(react@19.2.3))(react@19.2.3):
dependencies:
framer-motion: 12.23.26(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
tslib: 2.8.1
optionalDependencies:
react: 19.2.3
react-dom: 19.2.3(react@19.2.3)
ms@2.1.3: {} ms@2.1.3: {}
nanoid@3.3.11: {} nanoid@3.3.11: {}
@@ -3797,7 +3729,7 @@ snapshots:
undici-types@7.16.0: {} undici-types@7.16.0: {}
update-browserslist-db@1.2.2(browserslist@4.28.1): update-browserslist-db@1.2.3(browserslist@4.28.1):
dependencies: dependencies:
browserslist: 4.28.1 browserslist: 4.28.1
escalade: 3.2.0 escalade: 3.2.0
@@ -3822,16 +3754,16 @@ snapshots:
optionalDependencies: optionalDependencies:
'@types/react': 19.2.7 '@types/react': 19.2.7
vite@7.3.0(@types/node@25.0.2)(jiti@2.6.1)(lightningcss@1.30.2): vite@7.3.0(@types/node@25.0.3)(jiti@2.6.1)(lightningcss@1.30.2):
dependencies: dependencies:
esbuild: 0.27.1 esbuild: 0.27.2
fdir: 6.5.0(picomatch@4.0.3) fdir: 6.5.0(picomatch@4.0.3)
picomatch: 4.0.3 picomatch: 4.0.3
postcss: 8.5.6 postcss: 8.5.6
rollup: 4.53.5 rollup: 4.53.5
tinyglobby: 0.2.15 tinyglobby: 0.2.15
optionalDependencies: optionalDependencies:
'@types/node': 25.0.2 '@types/node': 25.0.3
fsevents: 2.3.3 fsevents: 2.3.3
jiti: 2.6.1 jiti: 2.6.1
lightningcss: 1.30.2 lightningcss: 1.30.2
+13 -22
View File
@@ -2,32 +2,23 @@ import sharp from 'sharp';
import { readFileSync, mkdirSync } from 'fs'; import { readFileSync, mkdirSync } from 'fs';
import { dirname, join } from 'path'; import { dirname, join } from 'path';
import { fileURLToPath } from 'url'; import { fileURLToPath } from 'url';
const __dirname = dirname(fileURLToPath(import.meta.url)); const __dirname = dirname(fileURLToPath(import.meta.url));
const rootDir = join(__dirname, '..', '..'); const rootDir = join(__dirname, '..', '..');
const svgPath = join(rootDir, 'frontend', 'public', 'icon.svg'); const svgPath = join(rootDir, 'frontend', 'public', 'icon.svg');
const outputPath = join(rootDir, 'build', 'appicon.png'); const outputPath = join(rootDir, 'build', 'appicon.png');
async function generateIcon() { async function generateIcon() {
try { try {
// Ensure build directory exists mkdirSync(join(rootDir, 'build'), { recursive: true });
mkdirSync(join(rootDir, 'build'), { recursive: true }); const svgBuffer = readFileSync(svgPath);
await sharp(svgBuffer)
// Read SVG .resize(1024, 1024)
const svgBuffer = readFileSync(svgPath); .png()
.toFile(outputPath);
// Convert SVG to PNG (1024x1024 for Wails) console.log('✓ Icon generated:', outputPath);
await sharp(svgBuffer) }
.resize(1024, 1024) catch (error) {
.png() console.error('✗ Failed to generate icon:', error.message);
.toFile(outputPath); process.exit(1);
}
console.log('✓ Icon generated:', outputPath);
} catch (error) {
console.error('✗ Failed to generate icon:', error.message);
process.exit(1);
}
} }
generateIcon(); generateIcon();
+1245 -1613
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+53 -83
View File
@@ -2,99 +2,72 @@ import { useState, useEffect, useRef } from "react";
import { Trash2, Copy, Check } from "lucide-react"; import { Trash2, Copy, Check } from "lucide-react";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { logger, type LogEntry } from "@/lib/logger"; import { logger, type LogEntry } from "@/lib/logger";
const levelColors: Record<string, string> = { const levelColors: Record<string, string> = {
info: "text-blue-500", info: "text-blue-500",
success: "text-green-500", success: "text-green-500",
warning: "text-yellow-500", warning: "text-yellow-500",
error: "text-red-500", error: "text-red-500",
debug: "text-gray-500", debug: "text-gray-500",
}; };
function formatTime(date: Date): string { function formatTime(date: Date): string {
return date.toLocaleTimeString("en-US", { return date.toLocaleTimeString("en-US", {
hour12: false, hour12: false,
hour: "2-digit", hour: "2-digit",
minute: "2-digit", minute: "2-digit",
second: "2-digit", second: "2-digit",
});
}
export function DebugLoggerPage() {
const [logs, setLogs] = useState<LogEntry[]>([]);
const [copied, setCopied] = useState(false);
const scrollRef = useRef<HTMLDivElement>(null);
useEffect(() => {
const unsubscribe = logger.subscribe(() => {
setLogs(logger.getLogs());
}); });
setLogs(logger.getLogs()); }
return () => { export function DebugLoggerPage() {
unsubscribe(); const [logs, setLogs] = useState<LogEntry[]>([]);
const [copied, setCopied] = useState(false);
const scrollRef = useRef<HTMLDivElement>(null);
useEffect(() => {
const unsubscribe = logger.subscribe(() => {
setLogs(logger.getLogs());
});
setLogs(logger.getLogs());
return () => {
unsubscribe();
};
}, []);
useEffect(() => {
if (scrollRef.current) {
scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
}
}, [logs]);
const handleClear = () => {
logger.clear();
}; };
}, []); const handleCopy = async () => {
const logText = logs
useEffect(() => { .map((log) => `[${formatTime(log.timestamp)}] [${log.level}] ${log.message}`)
if (scrollRef.current) { .join("\n");
scrollRef.current.scrollTop = scrollRef.current.scrollHeight; try {
} await navigator.clipboard.writeText(logText);
}, [logs]); setCopied(true);
setTimeout(() => setCopied(false), 500);
const handleClear = () => { }
logger.clear(); catch (err) {
}; console.error("Failed to copy logs:", err);
}
const handleCopy = async () => { };
const logText = logs return (<div className="space-y-6">
.map((log) => `[${formatTime(log.timestamp)}] [${log.level}] ${log.message}`)
.join("\n");
try {
await navigator.clipboard.writeText(logText);
setCopied(true);
setTimeout(() => setCopied(false), 500);
} catch (err) {
console.error("Failed to copy logs:", err);
}
};
return (
<div className="space-y-6">
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<h1 className="text-2xl font-bold">Debug Logs</h1> <h1 className="text-2xl font-bold">Debug Logs</h1>
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<Button <Button variant="outline" size="sm" onClick={handleCopy} disabled={logs.length === 0} className="gap-1.5">
variant="outline" {copied ? <Check className="h-4 w-4"/> : <Copy className="h-4 w-4"/>}
size="sm"
onClick={handleCopy}
disabled={logs.length === 0}
className="gap-1.5"
>
{copied ? <Check className="h-4 w-4" /> : <Copy className="h-4 w-4" />}
Copy Copy
</Button> </Button>
<Button <Button variant="outline" size="sm" onClick={handleClear} className="gap-1.5">
variant="outline" <Trash2 className="h-4 w-4"/>
size="sm"
onClick={handleClear}
className="gap-1.5"
>
<Trash2 className="h-4 w-4" />
Clear Clear
</Button> </Button>
</div> </div>
</div> </div>
<div <div ref={scrollRef} className="h-[calc(100vh-220px)] overflow-y-auto bg-muted/50 rounded-md p-3 font-mono text-xs">
ref={scrollRef} {logs.length === 0 ? (<p className="text-muted-foreground lowercase">no logs yet...</p>) : (logs.map((log, i) => (<div key={i} className="flex gap-2 py-0.5">
className="h-[calc(100vh-220px)] overflow-y-auto bg-muted/50 rounded-md p-3 font-mono text-xs"
>
{logs.length === 0 ? (
<p className="text-muted-foreground lowercase">no logs yet...</p>
) : (
logs.map((log, i) => (
<div key={i} className="flex gap-2 py-0.5">
<span className="text-muted-foreground shrink-0"> <span className="text-muted-foreground shrink-0">
[{formatTime(log.timestamp)}] [{formatTime(log.timestamp)}]
</span> </span>
@@ -102,10 +75,7 @@ export function DebugLoggerPage() {
[{log.level}] [{log.level}]
</span> </span>
<span className="break-all">{log.message}</span> <span className="break-all">{log.message}</span>
</div> </div>)))}
))
)}
</div> </div>
</div> </div>);
);
} }
@@ -0,0 +1,103 @@
import { useEffect, useState } from "react";
import { AlertCircle, Download, Package } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from "@/components/ui/dialog";
import { Spinner } from "@/components/ui/spinner";
import { toastWithSound as toast } from "@/lib/toast-with-sound";
import { DownloadExtractor, IsExtractorInstalled } from "../../wailsjs/go/main/App";
interface DependencySetupDialogProps {
onInstalled?: () => void;
}
export function DependencySetupDialog({ onInstalled }: DependencySetupDialogProps) {
const [open, setOpen] = useState(false);
const [checking, setChecking] = useState(true);
const [downloading, setDownloading] = useState(false);
const [errorMessage, setErrorMessage] = useState<string | null>(null);
useEffect(() => {
let cancelled = false;
const checkDependency = async () => {
try {
const installed = await IsExtractorInstalled();
if (!cancelled) {
setOpen(!installed);
setErrorMessage(null);
}
}
catch {
if (!cancelled) {
setOpen(true);
setErrorMessage("Couldn't verify the core dependency. You can install it now.");
}
}
finally {
if (!cancelled) {
setChecking(false);
}
}
};
checkDependency();
return () => {
cancelled = true;
};
}, []);
const handleDownload = async () => {
setDownloading(true);
setErrorMessage(null);
try {
await DownloadExtractor();
setOpen(false);
toast.success("Core dependency installed");
onInstalled?.();
}
catch (error) {
const message = error instanceof Error ? error.message : String(error);
setErrorMessage(message || "Failed to download dependency.");
toast.error("Failed to download dependency");
}
finally {
setDownloading(false);
}
};
if (checking && !open) {
return null;
}
return (<Dialog open={open} onOpenChange={(nextOpen) => !downloading && setOpen(nextOpen)}>
<DialogContent className="max-w-xl [&>button]:hidden" showCloseButton={false}>
<DialogHeader>
<div className="mb-2 flex h-12 w-12 items-center justify-center rounded-2xl border bg-muted/50">
<Package className="h-6 w-6"/>
</div>
<DialogTitle>Download Core Dependency</DialogTitle>
<DialogDescription>
This app now uses a prebuilt xtractor binary from GitHub releases. Download it once so fetching can work on this device.
</DialogDescription>
</DialogHeader>
<div className="space-y-3">
<div className="rounded-lg border bg-muted/40 p-3 text-sm text-muted-foreground">
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.
</div>
{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"/>
<p>{errorMessage}</p>
</div>)}
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setOpen(false)} disabled={downloading}>
Later
</Button>
<Button onClick={handleDownload} disabled={downloading}>
{downloading ? (<>
<Spinner />
Downloading...
</>) : (<>
<Download className="h-4 w-4"/>
Download Dependency
</>)}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>);
}
+19 -43
View File
@@ -1,58 +1,34 @@
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { X, User } from "lucide-react"; import { X, User } from "lucide-react";
export interface HistoryItem { export interface HistoryItem {
id: string; id: string;
username: string; username: string;
name: string; name: string;
image: string; image: string;
mediaCount: number; mediaCount: number;
timestamp: number; timestamp: number;
} }
interface FetchHistoryProps { interface FetchHistoryProps {
history: HistoryItem[]; history: HistoryItem[];
onSelect: (item: HistoryItem) => void; onSelect: (item: HistoryItem) => void;
onRemove: (id: string) => void; onRemove: (id: string) => void;
} }
export function FetchHistory({ history, onSelect, onRemove }: FetchHistoryProps) { export function FetchHistory({ history, onSelect, onRemove }: FetchHistoryProps) {
if (history.length === 0) return null; if (history.length === 0)
return null;
return ( return (<div className="space-y-2">
<div className="space-y-2">
<p className="text-sm text-muted-foreground">Recent Fetches</p> <p className="text-sm text-muted-foreground">Recent Fetches</p>
<div className="flex flex-wrap gap-2"> <div className="flex flex-wrap gap-2">
{history.map((item) => ( {history.map((item) => (<div key={item.id} className="flex items-center gap-2 px-3 py-1.5 bg-muted/50 rounded-full hover:bg-muted transition-colors group cursor-pointer" onClick={() => onSelect(item)}>
<div {item.image ? (<img src={item.image} alt={item.name} className="w-5 h-5 rounded-full"/>) : (<User className="w-5 h-5 text-muted-foreground"/>)}
key={item.id}
className="flex items-center gap-2 px-3 py-1.5 bg-muted/50 rounded-full hover:bg-muted transition-colors group cursor-pointer"
onClick={() => onSelect(item)}
>
{item.image ? (
<img
src={item.image}
alt={item.name}
className="w-5 h-5 rounded-full"
/>
) : (
<User className="w-5 h-5 text-muted-foreground" />
)}
<span className="text-sm">@{item.username}</span> <span className="text-sm">@{item.username}</span>
<Button <Button variant="ghost" size="icon" className="h-4 w-4 opacity-0 group-hover:opacity-100 transition-opacity" onClick={(e) => {
variant="ghost"
size="icon"
className="h-4 w-4 opacity-0 group-hover:opacity-100 transition-opacity"
onClick={(e) => {
e.stopPropagation(); e.stopPropagation();
onRemove(item.id); onRemove(item.id);
}} }}>
> <X className="h-3 w-3"/>
<X className="h-3 w-3" />
</Button> </Button>
</div> </div>))}
))}
</div> </div>
</div> </div>);
);
} }
+13 -37
View File
@@ -1,63 +1,39 @@
import { Badge } from "@/components/ui/badge"; import { Badge } from "@/components/ui/badge";
import { import { Tooltip, TooltipContent, TooltipTrigger, } from "@/components/ui/tooltip";
Tooltip,
TooltipContent,
TooltipTrigger,
} from "@/components/ui/tooltip";
import { openExternal } from "@/lib/utils"; import { openExternal } from "@/lib/utils";
import { formatRelativeTime } from "@/lib/relative-time"; import { formatRelativeTime } from "@/lib/relative-time";
interface HeaderProps { interface HeaderProps {
version: string; version: string;
hasUpdate: boolean; hasUpdate: boolean;
releaseDate?: string | null; releaseDate?: string | null;
} }
export function Header({ version, hasUpdate, releaseDate }: HeaderProps) { export function Header({ version, hasUpdate, releaseDate }: HeaderProps) {
return ( return (<div className="relative">
<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 <img src="/icon.svg" alt="Twitter/X Media Batch Downloader" className="w-12 h-12 cursor-pointer" onClick={() => window.location.reload()}/>
src="/icon.svg" <h1 className="text-3xl font-bold cursor-pointer" onClick={() => window.location.reload()}>
alt="Twitter/X Media Batch Downloader"
className="w-12 h-12 cursor-pointer"
onClick={() => window.location.reload()}
/>
<h1
className="text-3xl font-bold cursor-pointer"
onClick={() => window.location.reload()}
>
Twitter/X Media Batch Downloader Twitter/X Media Batch Downloader
</h1> </h1>
<div className="relative"> <div className="relative">
<Tooltip> <Tooltip>
<TooltipTrigger asChild> <TooltipTrigger asChild>
<Badge variant="default" asChild> <Badge variant="default" asChild>
<button <button type="button" onClick={() => openExternal("https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases")} className="cursor-pointer hover:opacity-80 transition-opacity">
type="button"
onClick={() => openExternal("https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases")}
className="cursor-pointer hover:opacity-80 transition-opacity"
>
v{version} v{version}
</button> </button>
</Badge> </Badge>
</TooltipTrigger> </TooltipTrigger>
{hasUpdate && releaseDate && ( {hasUpdate && releaseDate && (<TooltipContent>
<TooltipContent>
<p>{formatRelativeTime(releaseDate)}</p> <p>{formatRelativeTime(releaseDate)}</p>
</TooltipContent> </TooltipContent>)}
)}
</Tooltip> </Tooltip>
{hasUpdate && ( {hasUpdate && (<span className="absolute -top-1 -right-1 flex h-3 w-3">
<span className="absolute -top-1 -right-1 flex h-3 w-3">
<span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-green-400 opacity-75"></span> <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-green-400 opacity-75"></span>
<span className="relative inline-flex rounded-full h-3 w-3 bg-green-500"></span> <span className="relative inline-flex rounded-full h-3 w-3 bg-green-500"></span>
</span> </span>)}
)}
</div> </div>
</div> </div>
</div> </div>
</div> </div>);
);
} }
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+261 -275
View File
@@ -2,160 +2,170 @@ import { useState, useEffect } from "react";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { InputWithContext } from "@/components/ui/input-with-context"; import { InputWithContext } from "@/components/ui/input-with-context";
import { Label } from "@/components/ui/label"; import { Label } from "@/components/ui/label";
import { import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select";
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 { FolderOpen, Save, RotateCcw, Info, Download, Check } from "lucide-react"; import { FolderOpen, Save, RotateCcw, Info, Download, Check } from "lucide-react";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from "@/components/ui/dialog";
import { Spinner } from "@/components/ui/spinner"; import { Spinner } from "@/components/ui/spinner";
import { Switch } from "@/components/ui/switch"; import { Switch } from "@/components/ui/switch";
import { getSettings, getSettingsWithDefaults, saveSettings, resetToDefaultSettings, applyThemeMode, applyFont, FONT_OPTIONS, type Settings as SettingsType, type FontFamily, type GifQuality, type GifResolution } from "@/lib/settings"; import { getSettings, getSettingsWithDefaults, saveSettings, resetToDefaultSettings, applyThemeMode, applyFont, FONT_OPTIONS, type Settings as SettingsType, type FontFamily, type GifQuality, type GifResolution } from "@/lib/settings";
import { themes, applyTheme } from "@/lib/themes"; import { themes, applyTheme } from "@/lib/themes";
import { SelectFolder, IsFFmpegInstalled, DownloadFFmpeg, IsExifToolInstalled, DownloadExifTool } from "../../wailsjs/go/main/App"; import { SelectFolder, IsExtractorInstalled, DownloadExtractor, IsFFmpegInstalled, DownloadFFmpeg, IsExifToolInstalled, DownloadExifTool } from "../../wailsjs/go/main/App";
import { toastWithSound as toast } from "@/lib/toast-with-sound"; import { toastWithSound as toast } from "@/lib/toast-with-sound";
export function SettingsPage() { export function SettingsPage() {
const [savedSettings, setSavedSettings] = useState<SettingsType>(getSettings()); const [savedSettings, setSavedSettings] = useState<SettingsType>(getSettings());
const [tempSettings, setTempSettings] = useState<SettingsType>(savedSettings); const [tempSettings, setTempSettings] = useState<SettingsType>(savedSettings);
const [isDark, setIsDark] = useState(document.documentElement.classList.contains('dark')); const [isDark, setIsDark] = useState(document.documentElement.classList.contains('dark'));
const [ffmpegInstalled, setFfmpegInstalled] = useState(false); const [extractorInstalled, setExtractorInstalled] = useState(false);
const [downloadingFFmpeg, setDownloadingFFmpeg] = useState(false); const [downloadingExtractor, setDownloadingExtractor] = useState(false);
const [exiftoolInstalled, setExiftoolInstalled] = useState(false); const [ffmpegInstalled, setFfmpegInstalled] = useState(false);
const [downloadingExifTool, setDownloadingExifTool] = useState(false); const [downloadingFFmpeg, setDownloadingFFmpeg] = useState(false);
const [exiftoolInstalled, setExiftoolInstalled] = useState(false);
useEffect(() => { const [downloadingExifTool, setDownloadingExifTool] = useState(false);
applyThemeMode(savedSettings.themeMode); const [showResetConfirm, setShowResetConfirm] = useState(false);
applyTheme(savedSettings.theme); useEffect(() => {
applyThemeMode(savedSettings.themeMode);
const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");
const handleChange = () => {
if (savedSettings.themeMode === "auto") {
applyThemeMode("auto");
applyTheme(savedSettings.theme); applyTheme(savedSettings.theme);
} const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");
const handleChange = () => {
if (savedSettings.themeMode === "auto") {
applyThemeMode("auto");
applyTheme(savedSettings.theme);
}
};
mediaQuery.addEventListener("change", handleChange);
return () => mediaQuery.removeEventListener("change", handleChange);
}, [savedSettings.themeMode, savedSettings.theme]);
useEffect(() => {
applyThemeMode(tempSettings.themeMode);
applyTheme(tempSettings.theme);
applyFont(tempSettings.fontFamily);
setTimeout(() => {
setIsDark(document.documentElement.classList.contains('dark'));
}, 0);
}, [tempSettings.themeMode, tempSettings.theme, tempSettings.fontFamily]);
useEffect(() => {
const loadDependencyStatus = async () => {
try {
const [extractor, ffmpeg, exiftool] = await Promise.all([
IsExtractorInstalled(),
IsFFmpegInstalled(),
IsExifToolInstalled(),
]);
setExtractorInstalled(extractor);
setFfmpegInstalled(ffmpeg);
setExiftoolInstalled(exiftool);
}
catch (error) {
console.error("Failed to check dependency status:", error);
}
};
const loadDefaults = async () => {
if (!savedSettings.downloadPath) {
const settingsWithDefaults = await getSettingsWithDefaults();
setSavedSettings(settingsWithDefaults);
setTempSettings(settingsWithDefaults);
}
};
loadDefaults();
loadDependencyStatus();
}, []);
const handleSave = () => {
saveSettings(tempSettings);
setSavedSettings(tempSettings);
toast.success("Settings saved");
}; };
const handleReset = async () => {
mediaQuery.addEventListener("change", handleChange); const defaultSettings = await resetToDefaultSettings();
return () => mediaQuery.removeEventListener("change", handleChange); setTempSettings(defaultSettings);
}, [savedSettings.themeMode, savedSettings.theme]); setSavedSettings(defaultSettings);
applyThemeMode(defaultSettings.themeMode);
useEffect(() => { applyTheme(defaultSettings.theme);
applyThemeMode(tempSettings.themeMode); applyFont(defaultSettings.fontFamily);
applyTheme(tempSettings.theme); setShowResetConfirm(false);
applyFont(tempSettings.fontFamily); toast.success("Settings reset to default");
setTimeout(() => {
setIsDark(document.documentElement.classList.contains('dark'));
}, 0);
}, [tempSettings.themeMode, tempSettings.theme, tempSettings.fontFamily]);
useEffect(() => {
const loadDefaults = async () => {
if (!savedSettings.downloadPath) {
const settingsWithDefaults = await getSettingsWithDefaults();
setSavedSettings(settingsWithDefaults);
setTempSettings(settingsWithDefaults);
}
}; };
loadDefaults(); const handleBrowseFolder = async () => {
try {
// Check FFmpeg and ExifTool status const selectedPath = await SelectFolder(tempSettings.downloadPath || "");
IsFFmpegInstalled().then(setFfmpegInstalled); if (selectedPath && selectedPath.trim() !== "") {
IsExifToolInstalled().then(setExiftoolInstalled); setTempSettings((prev) => ({ ...prev, downloadPath: selectedPath }));
}, []); }
}
const handleSave = () => { catch (error) {
saveSettings(tempSettings); console.error("Error selecting folder:", error);
setSavedSettings(tempSettings); toast.error(`Error selecting folder: ${error}`);
toast.success("Settings saved"); }
}; };
const handleDownloadExtractor = async () => {
const handleReset = async () => { setDownloadingExtractor(true);
const defaultSettings = await resetToDefaultSettings(); try {
setTempSettings(defaultSettings); await DownloadExtractor();
setSavedSettings(defaultSettings); setExtractorInstalled(true);
applyThemeMode(defaultSettings.themeMode); toast.success(extractorInstalled ? "Xtractor reinstalled successfully" : "Xtractor downloaded successfully");
applyTheme(defaultSettings.theme); }
applyFont(defaultSettings.fontFamily); catch (error) {
toast.success("Settings reset to default"); toast.error("Failed to download xtractor");
}; console.error("Error downloading extractor:", error);
}
const handleBrowseFolder = async () => { finally {
try { setDownloadingExtractor(false);
const selectedPath = await SelectFolder(tempSettings.downloadPath || ""); }
if (selectedPath && selectedPath.trim() !== "") { };
setTempSettings((prev) => ({ ...prev, downloadPath: selectedPath })); const handleDownloadFFmpeg = async () => {
} setDownloadingFFmpeg(true);
} catch (error) { try {
console.error("Error selecting folder:", error); await DownloadFFmpeg();
toast.error(`Error selecting folder: ${error}`); setFfmpegInstalled(true);
} toast.success("FFmpeg downloaded successfully");
}; }
catch (error) {
const handleDownloadFFmpeg = async () => { toast.error("Failed to download FFmpeg");
setDownloadingFFmpeg(true); console.error("Error downloading FFmpeg:", error);
try { }
await DownloadFFmpeg(); finally {
setFfmpegInstalled(true); setDownloadingFFmpeg(false);
toast.success("FFmpeg downloaded successfully"); }
} catch (error) { };
toast.error("Failed to download FFmpeg"); const handleDownloadExifTool = async () => {
console.error("Error downloading FFmpeg:", error); setDownloadingExifTool(true);
} finally { try {
setDownloadingFFmpeg(false); await DownloadExifTool();
} setExiftoolInstalled(true);
}; toast.success("ExifTool downloaded successfully");
}
const handleDownloadExifTool = async () => { catch (error) {
setDownloadingExifTool(true); toast.error("Failed to download ExifTool");
try { console.error("Error downloading ExifTool:", error);
await DownloadExifTool(); }
setExiftoolInstalled(true); finally {
toast.success("ExifTool downloaded successfully"); setDownloadingExifTool(false);
} catch (error) { }
toast.error("Failed to download ExifTool"); };
console.error("Error downloading ExifTool:", error); return (<div className="space-y-6">
} finally {
setDownloadingExifTool(false);
}
};
return (
<div className="space-y-6">
<h1 className="text-2xl font-bold">Settings</h1> <h1 className="text-2xl font-bold">Settings</h1>
<div className="grid grid-cols-1 md:grid-cols-2 gap-6"> <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
{/* Left Column */}
<div className="space-y-4"> <div className="space-y-4">
{/* Download Path */}
<div className="space-y-2"> <div className="space-y-2">
<Label htmlFor="download-path">Download Path</Label> <Label htmlFor="download-path">Download Path</Label>
<div className="flex gap-2"> <div className="flex gap-2">
<InputWithContext <InputWithContext id="download-path" value={tempSettings.downloadPath} onChange={(e) => setTempSettings((prev) => ({ ...prev, downloadPath: e.target.value }))} placeholder="C:\Users\YourUsername\Pictures"/>
id="download-path"
value={tempSettings.downloadPath}
onChange={(e) => setTempSettings((prev) => ({ ...prev, downloadPath: e.target.value }))}
placeholder="C:\Users\YourUsername\Pictures"
/>
<Button type="button" onClick={handleBrowseFolder} className="gap-1.5"> <Button type="button" onClick={handleBrowseFolder} className="gap-1.5">
<FolderOpen className="h-4 w-4" /> <FolderOpen className="h-4 w-4"/>
Browse Browse
</Button> </Button>
</div> </div>
</div> </div>
{/* Theme Mode */}
<div className="space-y-2"> <div className="space-y-2">
<Label htmlFor="theme-mode">Mode</Label> <Label htmlFor="theme-mode">Mode</Label>
<Select <Select value={tempSettings.themeMode} onValueChange={(value: "auto" | "light" | "dark") => setTempSettings((prev) => ({ ...prev, themeMode: value }))}>
value={tempSettings.themeMode}
onValueChange={(value: "auto" | "light" | "dark") => setTempSettings((prev) => ({ ...prev, themeMode: value }))}
>
<SelectTrigger id="theme-mode"> <SelectTrigger id="theme-mode">
<SelectValue placeholder="Select theme mode" /> <SelectValue placeholder="Select theme mode"/>
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
<SelectItem value="auto">Auto</SelectItem> <SelectItem value="auto">Auto</SelectItem>
@@ -165,74 +175,87 @@ export function SettingsPage() {
</Select> </Select>
</div> </div>
{/* Accent */}
<div className="space-y-2"> <div className="space-y-2">
<Label htmlFor="theme">Accent</Label> <Label htmlFor="theme">Accent</Label>
<Select <Select value={tempSettings.theme} onValueChange={(value) => setTempSettings((prev) => ({ ...prev, theme: value }))}>
value={tempSettings.theme}
onValueChange={(value) => setTempSettings((prev) => ({ ...prev, theme: value }))}
>
<SelectTrigger id="theme"> <SelectTrigger id="theme">
<SelectValue placeholder="Select a theme" /> <SelectValue placeholder="Select a theme"/>
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
{themes.map((theme) => ( {themes.map((theme) => (<SelectItem key={theme.name} value={theme.name}>
<SelectItem key={theme.name} value={theme.name}>
<span className="flex items-center gap-2"> <span className="flex items-center gap-2">
<span <span className="w-3 h-3 rounded-full border border-border" style={{
className="w-3 h-3 rounded-full border border-border" backgroundColor: isDark ? theme.cssVars.dark.primary : theme.cssVars.light.primary
style={{ }}/>
backgroundColor: isDark ? theme.cssVars.dark.primary : theme.cssVars.light.primary
}}
/>
{theme.label} {theme.label}
</span> </span>
</SelectItem> </SelectItem>))}
))}
</SelectContent> </SelectContent>
</Select> </Select>
</div> </div>
{/* Font */}
<div className="space-y-2"> <div className="space-y-2">
<Label htmlFor="font">Font</Label> <Label htmlFor="font">Font</Label>
<Select <Select value={tempSettings.fontFamily} onValueChange={(value: FontFamily) => setTempSettings((prev) => ({ ...prev, fontFamily: value }))}>
value={tempSettings.fontFamily}
onValueChange={(value: FontFamily) => setTempSettings((prev) => ({ ...prev, fontFamily: value }))}
>
<SelectTrigger id="font"> <SelectTrigger id="font">
<SelectValue placeholder="Select a font" /> <SelectValue placeholder="Select a font"/>
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
{FONT_OPTIONS.map((font) => ( {FONT_OPTIONS.map((font) => (<SelectItem key={font.value} value={font.value}>
<SelectItem key={font.value} value={font.value}>
<span style={{ fontFamily: font.fontFamily }}>{font.label}</span> <span style={{ fontFamily: font.fontFamily }}>{font.label}</span>
</SelectItem> </SelectItem>))}
))}
</SelectContent> </SelectContent>
</Select> </Select>
</div> </div>
{/* Sound Effects */}
<div className="flex items-center gap-3 pt-2"> <div className="flex items-center gap-3 pt-2">
<Label htmlFor="sfx-enabled" className="cursor-pointer text-sm">Sound Effects</Label> <Label htmlFor="sfx-enabled" className="cursor-pointer text-sm">Sound Effects</Label>
<Switch <Switch id="sfx-enabled" checked={tempSettings.sfxEnabled} onCheckedChange={(checked) => setTempSettings(prev => ({ ...prev, sfxEnabled: checked }))}/>
id="sfx-enabled"
checked={tempSettings.sfxEnabled}
onCheckedChange={(checked) => setTempSettings(prev => ({ ...prev, sfxEnabled: checked }))}
/>
</div> </div>
</div> </div>
{/* Right Column */}
<div className="space-y-4"> <div className="space-y-4">
{/* Metadata Embedding */}
<div className="space-y-2">
<Label className="flex items-center gap-2">
Core Xtractor
<Tooltip>
<TooltipTrigger asChild>
<Info className="h-3.5 w-3.5 text-muted-foreground cursor-help"/>
</TooltipTrigger>
<TooltipContent side="top">
<p>Required to fetch media from Twitter/X. Downloaded from the xtractor-binaries GitHub releases.</p>
</TooltipContent>
</Tooltip>
</Label>
<div className="flex min-h-9 items-center gap-3">
{extractorInstalled && (<div className="flex items-center gap-2 text-sm text-green-600 dark:text-green-400">
<Check className="h-4 w-4"/>
Installed
</div>)}
<Button variant="outline" size="sm" className="h-9" onClick={handleDownloadExtractor} disabled={downloadingExtractor}>
{downloadingExtractor ? (<>
<Spinner />
Downloading...
</>) : (<>
<Download className="h-4 w-4"/>
{extractorInstalled ? "Reinstall Xtractor" : "Download Xtractor"}
</>)}
</Button>
</div>
</div>
<div className="space-y-2"> <div className="space-y-2">
<Label className="flex items-center gap-2"> <Label className="flex items-center gap-2">
Metadata Embedding Metadata Embedding
<Tooltip> <Tooltip>
<TooltipTrigger asChild> <TooltipTrigger asChild>
<Info className="h-3.5 w-3.5 text-muted-foreground cursor-help" /> <Info className="h-3.5 w-3.5 text-muted-foreground cursor-help"/>
</TooltipTrigger> </TooltipTrigger>
<TooltipContent side="top"> <TooltipContent side="top">
<p>ExifTool is required to embed tweet URL and original filename into media file metadata</p> <p>ExifTool is required to embed tweet URL and original filename into media file metadata</p>
@@ -240,42 +263,28 @@ export function SettingsPage() {
</Tooltip> </Tooltip>
</Label> </Label>
<div className="h-9 flex items-center"> <div className="h-9 flex items-center">
{exiftoolInstalled ? ( {exiftoolInstalled ? (<div className="flex items-center gap-2 text-sm text-green-600 dark:text-green-400">
<div className="flex items-center gap-2 text-sm text-green-600 dark:text-green-400"> <Check className="h-4 w-4"/>
<Check className="h-4 w-4" />
Installed Installed
</div> </div>) : (<Button variant="outline" size="sm" className="h-9" onClick={handleDownloadExifTool} disabled={downloadingExifTool}>
) : ( {downloadingExifTool ? (<>
<Button
variant="outline"
size="sm"
className="h-9"
onClick={handleDownloadExifTool}
disabled={downloadingExifTool}
>
{downloadingExifTool ? (
<>
<Spinner /> <Spinner />
Downloading... Downloading...
</> </>) : (<>
) : ( <Download className="h-4 w-4"/>
<>
<Download className="h-4 w-4" />
Download ExifTool Download ExifTool
</> </>)}
)} </Button>)}
</Button>
)}
</div> </div>
</div> </div>
{/* GIF Conversion */}
<div className="space-y-2"> <div className="space-y-2">
<Label className="flex items-center gap-2"> <Label className="flex items-center gap-2">
GIF Conversion GIF Conversion
<Tooltip> <Tooltip>
<TooltipTrigger asChild> <TooltipTrigger asChild>
<Info className="h-3.5 w-3.5 text-muted-foreground cursor-help" /> <Info className="h-3.5 w-3.5 text-muted-foreground cursor-help"/>
</TooltipTrigger> </TooltipTrigger>
<TooltipContent side="top"> <TooltipContent side="top">
<p>FFmpeg is required to convert Twitter's MP4 to actual GIF format</p> <p>FFmpeg is required to convert Twitter's MP4 to actual GIF format</p>
@@ -283,63 +292,42 @@ export function SettingsPage() {
</Tooltip> </Tooltip>
</Label> </Label>
<div className="h-9 flex items-center"> <div className="h-9 flex items-center">
{ffmpegInstalled ? ( {ffmpegInstalled ? (<div className="flex items-center gap-2 text-sm text-green-600 dark:text-green-400">
<div className="flex items-center gap-2 text-sm text-green-600 dark:text-green-400"> <Check className="h-4 w-4"/>
<Check className="h-4 w-4" />
Installed Installed
</div> </div>) : (<Button variant="outline" size="sm" className="h-9" onClick={handleDownloadFFmpeg} disabled={downloadingFFmpeg}>
) : ( {downloadingFFmpeg ? (<>
<Button
variant="outline"
size="sm"
className="h-9"
onClick={handleDownloadFFmpeg}
disabled={downloadingFFmpeg}
>
{downloadingFFmpeg ? (
<>
<Spinner /> <Spinner />
Downloading... Downloading...
</> </>) : (<>
) : ( <Download className="h-4 w-4"/>
<>
<Download className="h-4 w-4" />
Download FFmpeg Download FFmpeg
</> </>)}
)} </Button>)}
</Button>
)}
</div> </div>
</div> </div>
{/* GIF Quality - only show if FFmpeg installed */}
{ffmpegInstalled && ( {ffmpegInstalled && (<div className="space-y-2">
<div className="space-y-2">
<Label htmlFor="gif-quality">GIF Quality</Label> <Label htmlFor="gif-quality">GIF Quality</Label>
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<Select <Select value={tempSettings.gifQuality} onValueChange={(value: GifQuality) => {
value={tempSettings.gifQuality} setTempSettings((prev) => ({
onValueChange={(value: GifQuality) => { ...prev,
setTempSettings((prev) => ({ gifQuality: value,
...prev, }));
gifQuality: value, }}>
}));
}}
>
<SelectTrigger id="gif-quality" className="w-auto"> <SelectTrigger id="gif-quality" className="w-auto">
<SelectValue placeholder="Select quality" /> <SelectValue placeholder="Select quality"/>
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
<SelectItem value="fast">Fast</SelectItem> <SelectItem value="fast">Fast</SelectItem>
<SelectItem value="better">Better</SelectItem> <SelectItem value="better">Better</SelectItem>
</SelectContent> </SelectContent>
</Select> </Select>
<Select <Select value={tempSettings.gifResolution} onValueChange={(value: GifResolution) => setTempSettings((prev) => ({ ...prev, gifResolution: value }))}>
value={tempSettings.gifResolution}
onValueChange={(value: GifResolution) => setTempSettings((prev) => ({ ...prev, gifResolution: value }))}
>
<SelectTrigger id="gif-resolution" className="w-auto"> <SelectTrigger id="gif-resolution" className="w-auto">
<SelectValue placeholder="Resolution" /> <SelectValue placeholder="Resolution"/>
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
<SelectItem value="original">Original</SelectItem> <SelectItem value="original">Original</SelectItem>
@@ -349,89 +337,87 @@ export function SettingsPage() {
</SelectContent> </SelectContent>
</Select> </Select>
</div> </div>
</div> </div>)}
)}
{/* Proxy */}
<div className="space-y-2"> <div className="space-y-2">
<Label htmlFor="proxy" className="flex items-center gap-2"> <Label htmlFor="proxy" className="flex items-center gap-2">
Proxy Proxy
<Tooltip> <Tooltip>
<TooltipTrigger asChild> <TooltipTrigger asChild>
<Info className="h-3.5 w-3.5 text-muted-foreground cursor-help" /> <Info className="h-3.5 w-3.5 text-muted-foreground cursor-help"/>
</TooltipTrigger> </TooltipTrigger>
<TooltipContent side="top"> <TooltipContent side="top">
<p>If download fails, try using a proxy server</p> <p>If download fails, try using a proxy server</p>
</TooltipContent> </TooltipContent>
</Tooltip> </Tooltip>
</Label> </Label>
<InputWithContext <InputWithContext id="proxy" value={tempSettings.proxy || ""} onChange={(e) => setTempSettings((prev) => ({ ...prev, proxy: e.target.value }))} placeholder="http://proxy:port or socks5://proxy:port (optional)" className="w-[90%]"/>
id="proxy"
value={tempSettings.proxy || ""}
onChange={(e) => setTempSettings((prev) => ({ ...prev, proxy: e.target.value }))}
placeholder="http://proxy:port or socks5://proxy:port (optional)"
className="w-[90%]"
/>
</div> </div>
{/* Fetch Timeout */}
<div className="space-y-2"> <div className="space-y-2">
<Label htmlFor="fetch-timeout" className="flex items-center gap-2"> <Label htmlFor="fetch-timeout" className="flex items-center gap-2">
Fetch Timeout Fetch Timeout
<Tooltip> <Tooltip>
<TooltipTrigger asChild> <TooltipTrigger asChild>
<Info className="h-3.5 w-3.5 text-muted-foreground cursor-help" /> <Info className="h-3.5 w-3.5 text-muted-foreground cursor-help"/>
</TooltipTrigger> </TooltipTrigger>
<TooltipContent side="top"> <TooltipContent side="top">
<p>Timeout in seconds. Fetch stops automatically when reached</p> <p>Timeout in seconds. Fetch stops automatically when reached</p>
</TooltipContent> </TooltipContent>
</Tooltip> </Tooltip>
</Label> </Label>
<InputWithContext <InputWithContext id="fetch-timeout" type="number" value={tempSettings.fetchTimeout || 60} onChange={(e) => {
id="fetch-timeout" const inputValue = e.target.value;
type="number" if (inputValue === "") {
value={tempSettings.fetchTimeout || 60} setTempSettings((prev) => ({ ...prev, fetchTimeout: 60 }));
onChange={(e) => { return;
const inputValue = e.target.value; }
// Allow empty input for user to type freely const value = parseInt(inputValue, 10);
if (inputValue === "") { if (!isNaN(value)) {
setTempSettings((prev) => ({ ...prev, fetchTimeout: 60 })); setTempSettings((prev) => ({ ...prev, fetchTimeout: value }));
return; }
} }} onBlur={(e) => {
const value = parseInt(inputValue, 10); const value = parseInt(e.target.value, 10);
// Allow any number while typing (including values less than min during typing) if (isNaN(value) || value < 30) {
// Validation will happen on blur setTempSettings((prev) => ({ ...prev, fetchTimeout: 30 }));
if (!isNaN(value)) { }
setTempSettings((prev) => ({ ...prev, fetchTimeout: value })); else if (value > 900) {
} setTempSettings((prev) => ({ ...prev, fetchTimeout: 900 }));
}} }
onBlur={(e) => { }} placeholder="60" className="w-[20%]"/>
// Validate and clamp value on blur
const value = parseInt(e.target.value, 10);
if (isNaN(value) || value < 30) {
setTempSettings((prev) => ({ ...prev, fetchTimeout: 30 }));
} else if (value > 900) {
setTempSettings((prev) => ({ ...prev, fetchTimeout: 900 }));
}
}}
placeholder="60"
className="w-[20%]"
/>
</div> </div>
</div> </div>
</div> </div>
{/* Actions */}
<div className="flex gap-2 justify-between pt-4 border-t"> <div className="flex gap-2 justify-between pt-4 border-t">
<Button variant="outline" onClick={handleReset} className="gap-1.5"> <Button variant="outline" onClick={() => setShowResetConfirm(true)} className="gap-1.5">
<RotateCcw className="h-4 w-4" /> <RotateCcw className="h-4 w-4"/>
Reset to Default Reset to Default
</Button> </Button>
<Button onClick={handleSave} className="gap-1.5"> <Button onClick={handleSave} className="gap-1.5">
<Save className="h-4 w-4" /> <Save className="h-4 w-4"/>
Save Changes Save Changes
</Button> </Button>
</div> </div>
</div>
);
<Dialog open={showResetConfirm} onOpenChange={setShowResetConfirm}>
<DialogContent className="max-w-md [&>button]:hidden">
<DialogHeader>
<DialogTitle>Reset to Default?</DialogTitle>
<DialogDescription>
This will reset all settings to their default values. Your custom configurations will be lost.
</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button variant="outline" onClick={() => setShowResetConfirm(false)}>Cancel</Button>
<Button onClick={handleReset}>Reset</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>);
} }
+63 -69
View File
@@ -1,60 +1,75 @@
import { Home, Settings, Bug, Database, LayoutGrid, Coffee, Github } from "lucide-react"; import { HomeIcon } from "@/components/ui/home";
import { import { SettingsIcon } from "@/components/ui/settings";
Tooltip, import { ArchiveIcon } from "@/components/ui/archive";
TooltipContent, import { TerminalIcon } from "@/components/ui/terminal";
TooltipTrigger, import { GithubIcon } from "@/components/ui/github";
} from "@/components/ui/tooltip"; import { CoffeeIcon } from "@/components/ui/coffee";
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";
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 navItems = [ 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">
{ id: "main" as PageType, icon: Home, label: "Home" },
{ id: "settings" as PageType, icon: Settings, label: "Settings" },
{ id: "database" as PageType, icon: Database, label: "Saved Accounts" },
{ id: "debug" as PageType, icon: Bug, label: "Debug Logs" },
];
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">
{navItems.map((item) => (
<Tooltip key={item.id} delayDuration={0}> <Tooltip delayDuration={0}>
<TooltipTrigger asChild> <TooltipTrigger asChild>
<Button <Button variant={currentPage === "main" ? "secondary" : "ghost"} size="icon" className="h-10 w-10" onClick={() => onPageChange("main")}>
variant={currentPage === item.id ? "secondary" : "ghost"} <HomeIcon size={20}/>
size="icon" </Button>
className="h-10 w-10" </TooltipTrigger>
onClick={() => onPageChange(item.id)} <TooltipContent side="right">
> <p>Home</p>
<item.icon className="h-5 w-5" /> </TooltipContent>
</Button> </Tooltip>
</TooltipTrigger>
<TooltipContent side="right">
<p>{item.label}</p> <Tooltip delayDuration={0}>
</TooltipContent> <TooltipTrigger asChild>
</Tooltip> <Button variant={currentPage === "settings" ? "secondary" : "ghost"} size="icon" className="h-10 w-10" onClick={() => onPageChange("settings")}>
))} <SettingsIcon size={20}/>
</Button>
</TooltipTrigger>
<TooltipContent side="right">
<p>Settings</p>
</TooltipContent>
</Tooltip>
<Tooltip delayDuration={0}>
<TooltipTrigger asChild>
<Button variant={currentPage === "database" ? "secondary" : "ghost"} size="icon" className="h-10 w-10" onClick={() => onPageChange("database")}>
<ArchiveIcon size={20}/>
</Button>
</TooltipTrigger>
<TooltipContent side="right">
<p>Saved Accounts</p>
</TooltipContent>
</Tooltip>
<Tooltip delayDuration={0}>
<TooltipTrigger asChild>
<Button variant={currentPage === "debug" ? "secondary" : "ghost"} size="icon" className="h-10 w-10" onClick={() => onPageChange("debug")}>
<TerminalIcon size={20}/>
</Button>
</TooltipTrigger>
<TooltipContent side="right">
<p>Debug Logs</p>
</TooltipContent>
</Tooltip>
</div> </div>
{/* Bottom icons */}
<div className="mt-auto flex flex-col gap-2"> <div className="mt-auto flex flex-col gap-2">
<Tooltip delayDuration={0}> <Tooltip delayDuration={0}>
<TooltipTrigger asChild> <TooltipTrigger asChild>
<Button <Button variant="ghost" size="icon" className="h-10 w-10" onClick={() => openExternal("https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/issues")}>
variant="ghost" <GithubIcon size={20}/>
size="icon"
className="h-10 w-10"
onClick={() => openExternal("https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/issues")}
>
<Github className="h-5 w-5" />
</Button> </Button>
</TooltipTrigger> </TooltipTrigger>
<TooltipContent side="right"> <TooltipContent side="right">
@@ -63,28 +78,8 @@ export function Sidebar({ currentPage, onPageChange }: SidebarProps) {
</Tooltip> </Tooltip>
<Tooltip delayDuration={0}> <Tooltip delayDuration={0}>
<TooltipTrigger asChild> <TooltipTrigger asChild>
<Button <Button variant="ghost" size="icon" className="h-10 w-10" onClick={() => openExternal("https://ko-fi.com/afkarxyz")}>
variant="ghost" <CoffeeIcon size={20}/>
size="icon"
className="h-10 w-10"
onClick={() => openExternal("https://exyezed.cc/")}
>
<LayoutGrid className="h-5 w-5" />
</Button>
</TooltipTrigger>
<TooltipContent side="right">
<p>Other Projects</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")}
>
<Coffee className="h-5 w-5" />
</Button> </Button>
</TooltipTrigger> </TooltipTrigger>
<TooltipContent side="right"> <TooltipContent side="right">
@@ -92,6 +87,5 @@ export function Sidebar({ currentPage, onPageChange }: SidebarProps) {
</TooltipContent> </TooltipContent>
</Tooltip> </Tooltip>
</div> </div>
</div> </div>);
);
} }
+18 -43
View File
@@ -1,55 +1,30 @@
import { X, Minus, Maximize } from "lucide-react"; import { X, Minus, Maximize } from "lucide-react";
import { WindowMinimise, WindowToggleMaximise, Quit } from "../../wailsjs/runtime/runtime"; import { WindowMinimise, WindowToggleMaximise, Quit } from "../../wailsjs/runtime/runtime";
export function TitleBar() { export function TitleBar() {
const handleMinimize = () => { const handleMinimize = () => {
WindowMinimise(); WindowMinimise();
}; };
const handleMaximize = () => {
WindowToggleMaximise();
};
const handleClose = () => {
Quit();
};
return (<>
const 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}/>
WindowToggleMaximise();
};
const handleClose = () => {
Quit();
};
return (
<>
{/* Draggable area */}
<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}
/>
{/* Window control buttons - Windows style, right side */}
<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">
<button <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">
onClick={handleMinimize} <Minus className="w-3.5 h-3.5"/>
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"
>
<Minus className="w-3.5 h-3.5" />
</button> </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">
onClick={handleMaximize} <Maximize className="w-3.5 h-3.5"/>
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"
>
<Maximize className="w-3.5 h-3.5" />
</button> </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">
onClick={handleClose} <X className="w-3.5 h-3.5"/>
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"
>
<X className="w-3.5 h-3.5" />
</button> </button>
</div> </div>
</> </>);
);
} }
+77
View File
@@ -0,0 +1,77 @@
'use client';
import type { Variants } from 'motion/react';
import type { HTMLAttributes } from 'react';
import { forwardRef, useCallback, useImperativeHandle, useRef } from 'react';
import { motion, useAnimation } from 'motion/react';
import { cn } from '@/lib/utils';
export interface ArchiveIconHandle {
startAnimation: () => void;
stopAnimation: () => void;
}
interface ArchiveIconProps extends HTMLAttributes<HTMLDivElement> {
size?: number;
}
const RECT_VARIANTS: Variants = {
normal: {
translateY: 0,
transition: {
duration: 0.2,
type: 'spring',
stiffness: 200,
damping: 25,
},
},
animate: {
translateY: -1.5,
transition: {
duration: 0.2,
type: 'spring',
stiffness: 200,
damping: 25,
},
},
};
const PATH_VARIANTS: Variants = {
normal: { d: 'M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8' },
animate: { d: 'M4 11v9a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V11' },
};
const SECONDARY_PATH_VARIANTS: Variants = {
normal: { d: 'M10 12h4' },
animate: { d: 'M10 15h4' },
};
const ArchiveIcon = forwardRef<ArchiveIconHandle, ArchiveIconProps>(({ onMouseEnter, onMouseLeave, className, size = 28, ...props }, ref) => {
const controls = useAnimation();
const isControlledRef = useRef(false);
useImperativeHandle(ref, () => {
isControlledRef.current = true;
return {
startAnimation: () => controls.start('animate'),
stopAnimation: () => controls.start('normal'),
};
});
const handleMouseEnter = useCallback((e: React.MouseEvent<HTMLDivElement>) => {
if (!isControlledRef.current) {
controls.start('animate');
}
else {
onMouseEnter?.(e);
}
}, [controls, onMouseEnter]);
const handleMouseLeave = useCallback((e: React.MouseEvent<HTMLDivElement>) => {
if (!isControlledRef.current) {
controls.start('normal');
}
else {
onMouseLeave?.(e);
}
}, [controls, onMouseLeave]);
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">
<motion.rect width="20" height="5" x="2" y="3" rx="1" initial="normal" animate={controls} variants={RECT_VARIANTS}/>
<motion.path d="M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8" variants={PATH_VARIANTS} animate={controls}/>
<motion.path d="M10 12h4" variants={SECONDARY_PATH_VARIANTS} animate={controls}/>
</svg>
</div>);
});
ArchiveIcon.displayName = 'ArchiveIcon';
export { ArchiveIcon };
+19 -41
View File
@@ -1,46 +1,24 @@
import * as React from "react" import * as React from "react";
import { Slot } from "@radix-ui/react-slot" import { Slot } from "@radix-ui/react-slot";
import { cva, type VariantProps } from "class-variance-authority" import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils";
import { cn } from "@/lib/utils" const badgeVariants = cva("inline-flex items-center justify-center rounded-full border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden", {
const badgeVariants = cva(
"inline-flex items-center justify-center rounded-full border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",
{
variants: { variants: {
variant: { variant: {
default: default: "border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",
"border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90", secondary: "border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",
secondary: destructive: "border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
"border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90", outline: "text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
destructive: },
"border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
outline:
"text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
},
}, },
defaultVariants: { defaultVariants: {
variant: "default", variant: "default",
}, },
} });
) function Badge({ className, variant, asChild = false, ...props }: React.ComponentProps<"span"> & VariantProps<typeof badgeVariants> & {
asChild?: boolean;
function Badge({ }) {
className, const Comp = asChild ? Slot : "span";
variant, return (<Comp data-slot="badge" className={cn(badgeVariants({ variant }), className)} {...props}/>);
asChild = false,
...props
}: React.ComponentProps<"span"> &
VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
const Comp = asChild ? Slot : "span"
return (
<Comp
data-slot="badge"
className={cn(badgeVariants({ variant }), className)}
{...props}
/>
)
} }
export { Badge, badgeVariants };
export { Badge, badgeVariants }
+52
View File
@@ -0,0 +1,52 @@
'use client';
import type { Variants } from 'motion/react';
import type { HTMLAttributes } from 'react';
import { forwardRef, useCallback, useImperativeHandle, useRef } from 'react';
import { motion, useAnimation } from 'motion/react';
import { cn } from '@/lib/utils';
export interface BlocksIconHandle {
startAnimation: () => void;
stopAnimation: () => void;
}
interface BlocksIconProps extends HTMLAttributes<HTMLDivElement> {
size?: number;
}
const VARIANTS: Variants = {
normal: { translateX: 0, translateY: 0 },
animate: { translateX: -4, translateY: 4 },
};
const BlocksIcon = forwardRef<BlocksIconHandle, BlocksIconProps>(({ onMouseEnter, onMouseLeave, className, size = 28, ...props }, ref) => {
const controls = useAnimation();
const isControlledRef = useRef(false);
useImperativeHandle(ref, () => {
isControlledRef.current = true;
return {
startAnimation: () => controls.start('animate'),
stopAnimation: () => controls.start('normal'),
};
});
const handleMouseEnter = useCallback((e: React.MouseEvent<HTMLDivElement>) => {
if (!isControlledRef.current) {
controls.start('animate');
}
else {
onMouseEnter?.(e);
}
}, [controls, onMouseEnter]);
const handleMouseLeave = useCallback((e: React.MouseEvent<HTMLDivElement>) => {
if (!isControlledRef.current) {
controls.start('normal');
}
else {
onMouseLeave?.(e);
}
}, [controls, onMouseLeave]);
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">
<path d="M10 21V8a1 1 0 0 0-1-1H4a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-5a1 1 0 0 0-1-1H3"/>
<motion.path d="M14 3h7v7h-7z" variants={VARIANTS} animate={controls}/>
</svg>
</div>);
});
BlocksIcon.displayName = 'BlocksIcon';
export { BlocksIcon };
+30 -55
View File
@@ -1,60 +1,35 @@
import * as React from "react" import * as React from "react";
import { Slot } from "@radix-ui/react-slot" import { Slot } from "@radix-ui/react-slot";
import { cva, type VariantProps } from "class-variance-authority" import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils";
import { cn } from "@/lib/utils" const buttonVariants = cva("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all cursor-pointer disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive", {
const buttonVariants = cva(
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all cursor-pointer disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
{
variants: { variants: {
variant: { variant: {
default: "bg-primary text-primary-foreground hover:bg-primary/90", default: "bg-primary text-primary-foreground hover:bg-primary/90",
destructive: destructive: "bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60", outline: "border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",
outline: secondary: "bg-secondary text-secondary-foreground hover:bg-secondary/80",
"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50", ghost: "hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
secondary: link: "text-primary underline-offset-4 hover:underline",
"bg-secondary text-secondary-foreground hover:bg-secondary/80", },
ghost: size: {
"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50", default: "h-9 px-4 py-2 has-[>svg]:px-3",
link: "text-primary underline-offset-4 hover:underline", sm: "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",
}, lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
size: { icon: "size-9",
default: "h-9 px-4 py-2 has-[>svg]:px-3", "icon-sm": "size-8",
sm: "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5", "icon-lg": "size-10",
lg: "h-10 rounded-md px-6 has-[>svg]:px-4", },
icon: "size-9",
"icon-sm": "size-8",
"icon-lg": "size-10",
},
}, },
defaultVariants: { defaultVariants: {
variant: "default", variant: "default",
size: "default", size: "default",
}, },
} });
) function Button({ className, variant, size, asChild = false, ...props }: React.ComponentProps<"button"> & VariantProps<typeof buttonVariants> & {
asChild?: boolean;
function Button({ }) {
className, const Comp = asChild ? Slot : "button";
variant, return (<Comp data-slot="button" className={cn(buttonVariants({ variant, size, className }))} {...props}/>);
size,
asChild = false,
...props
}: React.ComponentProps<"button"> &
VariantProps<typeof buttonVariants> & {
asChild?: boolean
}) {
const Comp = asChild ? Slot : "button"
return (
<Comp
data-slot="button"
className={cn(buttonVariants({ variant, size, className }))}
{...props}
/>
)
} }
export { Button, buttonVariants };
export { Button, buttonVariants }
+11 -30
View File
@@ -1,32 +1,13 @@
"use client" "use client";
import * as React from "react";
import * as React from "react" import * as CheckboxPrimitive from "@radix-ui/react-checkbox";
import * as CheckboxPrimitive from "@radix-ui/react-checkbox" import { CheckIcon } from "lucide-react";
import { CheckIcon } from "lucide-react" import { cn } from "@/lib/utils";
function Checkbox({ className, ...props }: React.ComponentProps<typeof CheckboxPrimitive.Root>) {
import { cn } from "@/lib/utils" return (<CheckboxPrimitive.Root data-slot="checkbox" className={cn("peer border-input dark:bg-input/30 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:data-[state=checked]:bg-primary data-[state=checked]:border-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive size-4 shrink-0 rounded-[4px] border shadow-xs transition-shadow outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50", className)} {...props}>
<CheckboxPrimitive.Indicator data-slot="checkbox-indicator" className="grid place-content-center text-current transition-none">
function Checkbox({ <CheckIcon className="size-3.5"/>
className,
...props
}: React.ComponentProps<typeof CheckboxPrimitive.Root>) {
return (
<CheckboxPrimitive.Root
data-slot="checkbox"
className={cn(
"peer border-input dark:bg-input/30 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:data-[state=checked]:bg-primary data-[state=checked]:border-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive size-4 shrink-0 rounded-[4px] border shadow-xs transition-shadow outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
className
)}
{...props}
>
<CheckboxPrimitive.Indicator
data-slot="checkbox-indicator"
className="grid place-content-center text-current transition-none"
>
<CheckIcon className="size-3.5" />
</CheckboxPrimitive.Indicator> </CheckboxPrimitive.Indicator>
</CheckboxPrimitive.Root> </CheckboxPrimitive.Root>);
)
} }
export { Checkbox };
export { Checkbox }
+66
View File
@@ -0,0 +1,66 @@
'use client';
import type { Variants } from 'motion/react';
import type { HTMLAttributes } from 'react';
import { forwardRef, useCallback, useImperativeHandle, useRef } from 'react';
import { motion, useAnimation } from 'motion/react';
import { cn } from '@/lib/utils';
export interface CoffeeIconHandle {
startAnimation: () => void;
stopAnimation: () => void;
}
interface CoffeeIconProps extends HTMLAttributes<HTMLDivElement> {
size?: number;
}
const PATH_VARIANTS: Variants = {
normal: {
y: 0,
opacity: 1,
},
animate: (custom: number) => ({
y: -3,
opacity: [0, 1, 0],
transition: {
repeat: Infinity,
duration: 1.5,
ease: 'easeInOut',
delay: 0.2 * custom,
},
}),
};
const CoffeeIcon = forwardRef<CoffeeIconHandle, CoffeeIconProps>(({ onMouseEnter, onMouseLeave, className, size = 28, ...props }, ref) => {
const controls = useAnimation();
const isControlledRef = useRef(false);
useImperativeHandle(ref, () => {
isControlledRef.current = true;
return {
startAnimation: () => controls.start('animate'),
stopAnimation: () => controls.start('normal'),
};
});
const handleMouseEnter = useCallback((e: React.MouseEvent<HTMLDivElement>) => {
if (!isControlledRef.current) {
controls.start('animate');
}
else {
onMouseEnter?.(e);
}
}, [controls, onMouseEnter]);
const handleMouseLeave = useCallback((e: React.MouseEvent<HTMLDivElement>) => {
if (!isControlledRef.current) {
controls.start('normal');
}
else {
onMouseLeave?.(e);
}
}, [controls, onMouseLeave]);
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' }}>
<motion.path d="M10 2v2" animate={controls} variants={PATH_VARIANTS} custom={0.2}/>
<motion.path d="M14 2v2" animate={controls} variants={PATH_VARIANTS} custom={0.4}/>
<motion.path d="M6 2v2" 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"/>
</svg>
</div>);
});
CoffeeIcon.displayName = 'CoffeeIcon';
export { CoffeeIcon };
+48 -223
View File
@@ -1,252 +1,77 @@
"use client" "use client";
import * as React from "react";
import * as React from "react" import * as ContextMenuPrimitive from "@radix-ui/react-context-menu";
import * as ContextMenuPrimitive from "@radix-ui/react-context-menu" import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react";
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react" import { cn } from "@/lib/utils";
function ContextMenu({ ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Root>) {
import { cn } from "@/lib/utils" return <ContextMenuPrimitive.Root data-slot="context-menu" {...props}/>;
function ContextMenu({
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.Root>) {
return <ContextMenuPrimitive.Root data-slot="context-menu" {...props} />
} }
function ContextMenuTrigger({ ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Trigger>) {
function ContextMenuTrigger({ return (<ContextMenuPrimitive.Trigger data-slot="context-menu-trigger" {...props}/>);
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.Trigger>) {
return (
<ContextMenuPrimitive.Trigger data-slot="context-menu-trigger" {...props} />
)
} }
function ContextMenuGroup({ ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Group>) {
function ContextMenuGroup({ return (<ContextMenuPrimitive.Group data-slot="context-menu-group" {...props}/>);
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.Group>) {
return (
<ContextMenuPrimitive.Group data-slot="context-menu-group" {...props} />
)
} }
function ContextMenuPortal({ ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Portal>) {
function ContextMenuPortal({ return (<ContextMenuPrimitive.Portal data-slot="context-menu-portal" {...props}/>);
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.Portal>) {
return (
<ContextMenuPrimitive.Portal data-slot="context-menu-portal" {...props} />
)
} }
function ContextMenuSub({ ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Sub>) {
function ContextMenuSub({ return <ContextMenuPrimitive.Sub data-slot="context-menu-sub" {...props}/>;
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.Sub>) {
return <ContextMenuPrimitive.Sub data-slot="context-menu-sub" {...props} />
} }
function ContextMenuRadioGroup({ ...props }: React.ComponentProps<typeof ContextMenuPrimitive.RadioGroup>) {
function ContextMenuRadioGroup({ return (<ContextMenuPrimitive.RadioGroup data-slot="context-menu-radio-group" {...props}/>);
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.RadioGroup>) {
return (
<ContextMenuPrimitive.RadioGroup
data-slot="context-menu-radio-group"
{...props}
/>
)
} }
function ContextMenuSubTrigger({ className, inset, children, ...props }: React.ComponentProps<typeof ContextMenuPrimitive.SubTrigger> & {
function ContextMenuSubTrigger({ inset?: boolean;
className,
inset,
children,
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.SubTrigger> & {
inset?: boolean
}) { }) {
return ( return (<ContextMenuPrimitive.SubTrigger data-slot="context-menu-sub-trigger" data-inset={inset} className={cn("focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground flex cursor-default items-center rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-inset:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4", className)} {...props}>
<ContextMenuPrimitive.SubTrigger
data-slot="context-menu-sub-trigger"
data-inset={inset}
className={cn(
"focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground flex cursor-default items-center rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-inset:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
>
{children} {children}
<ChevronRightIcon className="ml-auto" /> <ChevronRightIcon className="ml-auto"/>
</ContextMenuPrimitive.SubTrigger> </ContextMenuPrimitive.SubTrigger>);
)
} }
function ContextMenuSubContent({ className, ...props }: React.ComponentProps<typeof ContextMenuPrimitive.SubContent>) {
function ContextMenuSubContent({ return (<ContextMenuPrimitive.SubContent data-slot="context-menu-sub-content" className={cn("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-32 origin-(--radix-context-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg", className)} {...props}/>);
className,
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.SubContent>) {
return (
<ContextMenuPrimitive.SubContent
data-slot="context-menu-sub-content"
className={cn(
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-32 origin-(--radix-context-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",
className
)}
{...props}
/>
)
} }
function ContextMenuContent({ className, ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Content>) {
function ContextMenuContent({ return (<ContextMenuPrimitive.Portal>
className, <ContextMenuPrimitive.Content data-slot="context-menu-content" className={cn("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-context-menu-content-available-height) min-w-32 origin-(--radix-context-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md", className)} {...props}/>
...props </ContextMenuPrimitive.Portal>);
}: React.ComponentProps<typeof ContextMenuPrimitive.Content>) {
return (
<ContextMenuPrimitive.Portal>
<ContextMenuPrimitive.Content
data-slot="context-menu-content"
className={cn(
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-context-menu-content-available-height) min-w-32 origin-(--radix-context-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md",
className
)}
{...props}
/>
</ContextMenuPrimitive.Portal>
)
} }
function ContextMenuItem({ className, inset, variant = "default", ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Item> & {
function ContextMenuItem({ inset?: boolean;
className, variant?: "default" | "destructive";
inset,
variant = "default",
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.Item> & {
inset?: boolean
variant?: "default" | "destructive"
}) { }) {
return ( return (<ContextMenuPrimitive.Item data-slot="context-menu-item" data-inset={inset} data-variant={variant} className={cn("focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:text-destructive! [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-disabled:pointer-events-none data-disabled:opacity-50 data-inset:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4", className)} {...props}/>);
<ContextMenuPrimitive.Item
data-slot="context-menu-item"
data-inset={inset}
data-variant={variant}
className={cn(
"focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:text-destructive! [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-disabled:pointer-events-none data-disabled:opacity-50 data-inset:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
/>
)
} }
function ContextMenuCheckboxItem({ className, children, checked, ...props }: React.ComponentProps<typeof ContextMenuPrimitive.CheckboxItem>) {
function ContextMenuCheckboxItem({ return (<ContextMenuPrimitive.CheckboxItem data-slot="context-menu-checkbox-item" className={cn("focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4", className)} checked={checked} {...props}>
className,
children,
checked,
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.CheckboxItem>) {
return (
<ContextMenuPrimitive.CheckboxItem
data-slot="context-menu-checkbox-item"
className={cn(
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
checked={checked}
{...props}
>
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center"> <span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
<ContextMenuPrimitive.ItemIndicator> <ContextMenuPrimitive.ItemIndicator>
<CheckIcon className="size-4" /> <CheckIcon className="size-4"/>
</ContextMenuPrimitive.ItemIndicator> </ContextMenuPrimitive.ItemIndicator>
</span> </span>
{children} {children}
</ContextMenuPrimitive.CheckboxItem> </ContextMenuPrimitive.CheckboxItem>);
)
} }
function ContextMenuRadioItem({ className, children, ...props }: React.ComponentProps<typeof ContextMenuPrimitive.RadioItem>) {
function ContextMenuRadioItem({ return (<ContextMenuPrimitive.RadioItem data-slot="context-menu-radio-item" className={cn("focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4", className)} {...props}>
className,
children,
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.RadioItem>) {
return (
<ContextMenuPrimitive.RadioItem
data-slot="context-menu-radio-item"
className={cn(
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
>
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center"> <span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
<ContextMenuPrimitive.ItemIndicator> <ContextMenuPrimitive.ItemIndicator>
<CircleIcon className="size-2 fill-current" /> <CircleIcon className="size-2 fill-current"/>
</ContextMenuPrimitive.ItemIndicator> </ContextMenuPrimitive.ItemIndicator>
</span> </span>
{children} {children}
</ContextMenuPrimitive.RadioItem> </ContextMenuPrimitive.RadioItem>);
)
} }
function ContextMenuLabel({ className, inset, ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Label> & {
function ContextMenuLabel({ inset?: boolean;
className,
inset,
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.Label> & {
inset?: boolean
}) { }) {
return ( return (<ContextMenuPrimitive.Label data-slot="context-menu-label" data-inset={inset} className={cn("text-foreground px-2 py-1.5 text-sm font-medium data-inset:pl-8", className)} {...props}/>);
<ContextMenuPrimitive.Label
data-slot="context-menu-label"
data-inset={inset}
className={cn(
"text-foreground px-2 py-1.5 text-sm font-medium data-inset:pl-8",
className
)}
{...props}
/>
)
} }
function ContextMenuSeparator({ className, ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Separator>) {
function ContextMenuSeparator({ return (<ContextMenuPrimitive.Separator data-slot="context-menu-separator" className={cn("bg-border -mx-1 my-1 h-px", className)} {...props}/>);
className,
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.Separator>) {
return (
<ContextMenuPrimitive.Separator
data-slot="context-menu-separator"
className={cn("bg-border -mx-1 my-1 h-px", className)}
{...props}
/>
)
} }
function ContextMenuShortcut({ className, ...props }: React.ComponentProps<"span">) {
function ContextMenuShortcut({ return (<span data-slot="context-menu-shortcut" className={cn("text-muted-foreground ml-auto text-xs tracking-widest", className)} {...props}/>);
className,
...props
}: React.ComponentProps<"span">) {
return (
<span
data-slot="context-menu-shortcut"
className={cn(
"text-muted-foreground ml-auto text-xs tracking-widest",
className
)}
{...props}
/>
)
}
export {
ContextMenu,
ContextMenuTrigger,
ContextMenuContent,
ContextMenuItem,
ContextMenuCheckboxItem,
ContextMenuRadioItem,
ContextMenuLabel,
ContextMenuSeparator,
ContextMenuShortcut,
ContextMenuGroup,
ContextMenuPortal,
ContextMenuSub,
ContextMenuSubContent,
ContextMenuSubTrigger,
ContextMenuRadioGroup,
} }
export { ContextMenu, ContextMenuTrigger, ContextMenuContent, ContextMenuItem, ContextMenuCheckboxItem, ContextMenuRadioItem, ContextMenuLabel, ContextMenuSeparator, ContextMenuShortcut, ContextMenuGroup, ContextMenuPortal, ContextMenuSub, ContextMenuSubContent, ContextMenuSubTrigger, ContextMenuRadioGroup, };
+29 -125
View File
@@ -1,143 +1,47 @@
"use client" "use client";
import * as React from "react";
import * as React from "react" import * as DialogPrimitive from "@radix-ui/react-dialog";
import * as DialogPrimitive from "@radix-ui/react-dialog" import { XIcon } from "lucide-react";
import { XIcon } from "lucide-react" import { cn } from "@/lib/utils";
function Dialog({ ...props }: React.ComponentProps<typeof DialogPrimitive.Root>) {
import { cn } from "@/lib/utils" return <DialogPrimitive.Root data-slot="dialog" {...props}/>;
function Dialog({
...props
}: React.ComponentProps<typeof DialogPrimitive.Root>) {
return <DialogPrimitive.Root data-slot="dialog" {...props} />
} }
function DialogTrigger({ ...props }: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
function DialogTrigger({ return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props}/>;
...props
}: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
} }
function DialogPortal({ ...props }: React.ComponentProps<typeof DialogPrimitive.Portal>) {
function DialogPortal({ return <DialogPrimitive.Portal data-slot="dialog-portal" {...props}/>;
...props
}: React.ComponentProps<typeof DialogPrimitive.Portal>) {
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
} }
function DialogClose({ ...props }: React.ComponentProps<typeof DialogPrimitive.Close>) {
function DialogClose({ return <DialogPrimitive.Close data-slot="dialog-close" {...props}/>;
...props
}: React.ComponentProps<typeof DialogPrimitive.Close>) {
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
} }
function DialogOverlay({ className, ...props }: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
function DialogOverlay({ return (<DialogPrimitive.Overlay data-slot="dialog-overlay" className={cn("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50", className)} {...props}/>);
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
return (
<DialogPrimitive.Overlay
data-slot="dialog-overlay"
className={cn(
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
className
)}
{...props}
/>
)
} }
function DialogContent({ className, children, showCloseButton = true, ...props }: React.ComponentProps<typeof DialogPrimitive.Content> & {
function DialogContent({ showCloseButton?: boolean;
className,
children,
showCloseButton = true,
...props
}: React.ComponentProps<typeof DialogPrimitive.Content> & {
showCloseButton?: boolean
}) { }) {
return ( return (<DialogPortal data-slot="dialog-portal">
<DialogPortal data-slot="dialog-portal">
<DialogOverlay /> <DialogOverlay />
<DialogPrimitive.Content <DialogPrimitive.Content data-slot="dialog-content" className={cn("bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg", className)} {...props}>
data-slot="dialog-content"
className={cn(
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",
className
)}
{...props}
>
{children} {children}
{showCloseButton && ( {showCloseButton && (<DialogPrimitive.Close data-slot="dialog-close" className="ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4">
<DialogPrimitive.Close
data-slot="dialog-close"
className="ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"
>
<XIcon /> <XIcon />
<span className="sr-only">Close</span> <span className="sr-only">Close</span>
</DialogPrimitive.Close> </DialogPrimitive.Close>)}
)}
</DialogPrimitive.Content> </DialogPrimitive.Content>
</DialogPortal> </DialogPortal>);
)
} }
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) { function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
return ( return (<div data-slot="dialog-header" className={cn("flex flex-col gap-2 text-center sm:text-left", className)} {...props}/>);
<div
data-slot="dialog-header"
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
{...props}
/>
)
} }
function DialogFooter({ className, ...props }: React.ComponentProps<"div">) { function DialogFooter({ className, ...props }: React.ComponentProps<"div">) {
return ( return (<div data-slot="dialog-footer" className={cn("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end", className)} {...props}/>);
<div
data-slot="dialog-footer"
className={cn(
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
className
)}
{...props}
/>
)
} }
function DialogTitle({ className, ...props }: React.ComponentProps<typeof DialogPrimitive.Title>) {
function DialogTitle({ return (<DialogPrimitive.Title data-slot="dialog-title" className={cn("text-lg leading-none font-semibold", className)} {...props}/>);
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Title>) {
return (
<DialogPrimitive.Title
data-slot="dialog-title"
className={cn("text-lg leading-none font-semibold", className)}
{...props}
/>
)
} }
function DialogDescription({ className, ...props }: React.ComponentProps<typeof DialogPrimitive.Description>) {
function DialogDescription({ return (<DialogPrimitive.Description data-slot="dialog-description" className={cn("text-muted-foreground text-sm", className)} {...props}/>);
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Description>) {
return (
<DialogPrimitive.Description
data-slot="dialog-description"
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
)
}
export {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogOverlay,
DialogPortal,
DialogTitle,
DialogTrigger,
} }
export { Dialog, DialogClose, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogOverlay, DialogPortal, DialogTitle, DialogTrigger, };
+45 -186
View File
@@ -1,200 +1,59 @@
import * as React from "react" import * as React from "react";
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu" import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu";
import { CheckIcon, ChevronRightIcon } from "lucide-react" import { CheckIcon, ChevronRightIcon } from "lucide-react";
import { cn } from "@/lib/utils";
import { cn } from "@/lib/utils" const DropdownMenu = DropdownMenuPrimitive.Root;
const DropdownMenuTrigger = DropdownMenuPrimitive.Trigger;
const DropdownMenu = DropdownMenuPrimitive.Root const DropdownMenuGroup = DropdownMenuPrimitive.Group;
const DropdownMenuPortal = DropdownMenuPrimitive.Portal;
const DropdownMenuTrigger = DropdownMenuPrimitive.Trigger const DropdownMenuSub = DropdownMenuPrimitive.Sub;
const DropdownMenuRadioGroup = DropdownMenuPrimitive.RadioGroup;
const DropdownMenuGroup = DropdownMenuPrimitive.Group const DropdownMenuSubTrigger = React.forwardRef<React.ElementRef<typeof DropdownMenuPrimitive.SubTrigger>, React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubTrigger> & {
inset?: boolean;
const DropdownMenuPortal = DropdownMenuPrimitive.Portal }>(({ className, inset, children, ...props }, ref) => (<DropdownMenuPrimitive.SubTrigger ref={ref} className={cn("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent", inset && "pl-8", className)} {...props}>
const DropdownMenuSub = DropdownMenuPrimitive.Sub
const DropdownMenuRadioGroup = DropdownMenuPrimitive.RadioGroup
const DropdownMenuSubTrigger = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.SubTrigger>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubTrigger> & {
inset?: boolean
}
>(({ className, inset, children, ...props }, ref) => (
<DropdownMenuPrimitive.SubTrigger
ref={ref}
className={cn(
"flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent",
inset && "pl-8",
className
)}
{...props}
>
{children} {children}
<ChevronRightIcon className="ml-auto h-4 w-4" /> <ChevronRightIcon className="ml-auto h-4 w-4"/>
</DropdownMenuPrimitive.SubTrigger> </DropdownMenuPrimitive.SubTrigger>));
))
DropdownMenuSubTrigger.displayName = DropdownMenuSubTrigger.displayName =
DropdownMenuPrimitive.SubTrigger.displayName DropdownMenuPrimitive.SubTrigger.displayName;
const DropdownMenuSubContent = React.forwardRef<React.ElementRef<typeof DropdownMenuPrimitive.SubContent>, React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubContent>>(({ className, ...props }, ref) => (<DropdownMenuPrimitive.SubContent ref={ref} className={cn("z-50 min-w-32 overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2", className)} {...props}/>));
const DropdownMenuSubContent = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.SubContent>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubContent>
>(({ className, ...props }, ref) => (
<DropdownMenuPrimitive.SubContent
ref={ref}
className={cn(
"z-50 min-w-32 overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
className
)}
{...props}
/>
))
DropdownMenuSubContent.displayName = DropdownMenuSubContent.displayName =
DropdownMenuPrimitive.SubContent.displayName DropdownMenuPrimitive.SubContent.displayName;
const DropdownMenuContent = React.forwardRef<React.ElementRef<typeof DropdownMenuPrimitive.Content>, React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Content>>(({ className, sideOffset = 4, ...props }, ref) => (<DropdownMenuPrimitive.Portal>
const DropdownMenuContent = React.forwardRef< <DropdownMenuPrimitive.Content ref={ref} sideOffset={sideOffset} className={cn("z-50 min-w-32 overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2", className)} {...props}/>
React.ElementRef<typeof DropdownMenuPrimitive.Content>, </DropdownMenuPrimitive.Portal>));
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Content> DropdownMenuContent.displayName = DropdownMenuPrimitive.Content.displayName;
>(({ className, sideOffset = 4, ...props }, ref) => ( const DropdownMenuItem = React.forwardRef<React.ElementRef<typeof DropdownMenuPrimitive.Item>, React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Item> & {
<DropdownMenuPrimitive.Portal> inset?: boolean;
<DropdownMenuPrimitive.Content }>(({ className, inset, ...props }, ref) => (<DropdownMenuPrimitive.Item ref={ref} className={cn("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50", inset && "pl-8", className)} {...props}/>));
ref={ref} DropdownMenuItem.displayName = DropdownMenuPrimitive.Item.displayName;
sideOffset={sideOffset} const DropdownMenuCheckboxItem = React.forwardRef<React.ElementRef<typeof DropdownMenuPrimitive.CheckboxItem>, React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.CheckboxItem>>(({ className, children, checked, ...props }, ref) => (<DropdownMenuPrimitive.CheckboxItem ref={ref} className={cn("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50", className)} checked={checked} {...props}>
className={cn(
"z-50 min-w-32 overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
className
)}
{...props}
/>
</DropdownMenuPrimitive.Portal>
))
DropdownMenuContent.displayName = DropdownMenuPrimitive.Content.displayName
const DropdownMenuItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Item> & {
inset?: boolean
}
>(({ className, inset, ...props }, ref) => (
<DropdownMenuPrimitive.Item
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50",
inset && "pl-8",
className
)}
{...props}
/>
))
DropdownMenuItem.displayName = DropdownMenuPrimitive.Item.displayName
const DropdownMenuCheckboxItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.CheckboxItem>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.CheckboxItem>
>(({ className, children, checked, ...props }, ref) => (
<DropdownMenuPrimitive.CheckboxItem
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50",
className
)}
checked={checked}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center"> <span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator> <DropdownMenuPrimitive.ItemIndicator>
<CheckIcon className="h-4 w-4" /> <CheckIcon className="h-4 w-4"/>
</DropdownMenuPrimitive.ItemIndicator> </DropdownMenuPrimitive.ItemIndicator>
</span> </span>
{children} {children}
</DropdownMenuPrimitive.CheckboxItem> </DropdownMenuPrimitive.CheckboxItem>));
))
DropdownMenuCheckboxItem.displayName = DropdownMenuCheckboxItem.displayName =
DropdownMenuPrimitive.CheckboxItem.displayName DropdownMenuPrimitive.CheckboxItem.displayName;
const DropdownMenuRadioItem = React.forwardRef<React.ElementRef<typeof DropdownMenuPrimitive.RadioItem>, React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.RadioItem>>(({ className, children, ...props }, ref) => (<DropdownMenuPrimitive.RadioItem ref={ref} className={cn("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50", className)} {...props}>
const DropdownMenuRadioItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.RadioItem>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.RadioItem>
>(({ className, children, ...props }, ref) => (
<DropdownMenuPrimitive.RadioItem
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50",
className
)}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center"> <span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator> <DropdownMenuPrimitive.ItemIndicator>
<CheckIcon className="h-4 w-4" /> <CheckIcon className="h-4 w-4"/>
</DropdownMenuPrimitive.ItemIndicator> </DropdownMenuPrimitive.ItemIndicator>
</span> </span>
{children} {children}
</DropdownMenuPrimitive.RadioItem> </DropdownMenuPrimitive.RadioItem>));
)) DropdownMenuRadioItem.displayName = DropdownMenuPrimitive.RadioItem.displayName;
DropdownMenuRadioItem.displayName = DropdownMenuPrimitive.RadioItem.displayName const DropdownMenuLabel = React.forwardRef<React.ElementRef<typeof DropdownMenuPrimitive.Label>, React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Label> & {
inset?: boolean;
const DropdownMenuLabel = React.forwardRef< }>(({ className, inset, ...props }, ref) => (<DropdownMenuPrimitive.Label ref={ref} className={cn("px-2 py-1.5 text-sm font-semibold", inset && "pl-8", className)} {...props}/>));
React.ElementRef<typeof DropdownMenuPrimitive.Label>, DropdownMenuLabel.displayName = DropdownMenuPrimitive.Label.displayName;
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Label> & { const DropdownMenuSeparator = React.forwardRef<React.ElementRef<typeof DropdownMenuPrimitive.Separator>, React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Separator>>(({ className, ...props }, ref) => (<DropdownMenuPrimitive.Separator ref={ref} className={cn("-mx-1 my-1 h-px bg-muted", className)} {...props}/>));
inset?: boolean DropdownMenuSeparator.displayName = DropdownMenuPrimitive.Separator.displayName;
} const DropdownMenuShortcut = ({ className, ...props }: React.HTMLAttributes<HTMLSpanElement>) => {
>(({ className, inset, ...props }, ref) => ( return (<span className={cn("ml-auto text-xs tracking-widest opacity-60", className)} {...props}/>);
<DropdownMenuPrimitive.Label };
ref={ref} DropdownMenuShortcut.displayName = "DropdownMenuShortcut";
className={cn( export { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem, DropdownMenuCheckboxItem, DropdownMenuRadioItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuShortcut, DropdownMenuGroup, DropdownMenuPortal, DropdownMenuSub, DropdownMenuSubContent, DropdownMenuSubTrigger, DropdownMenuRadioGroup, };
"px-2 py-1.5 text-sm font-semibold",
inset && "pl-8",
className
)}
{...props}
/>
))
DropdownMenuLabel.displayName = DropdownMenuPrimitive.Label.displayName
const DropdownMenuSeparator = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Separator>
>(({ className, ...props }, ref) => (
<DropdownMenuPrimitive.Separator
ref={ref}
className={cn("-mx-1 my-1 h-px bg-muted", className)}
{...props}
/>
))
DropdownMenuSeparator.displayName = DropdownMenuPrimitive.Separator.displayName
const DropdownMenuShortcut = ({
className,
...props
}: React.HTMLAttributes<HTMLSpanElement>) => {
return (
<span
className={cn("ml-auto text-xs tracking-widest opacity-60", className)}
{...props}
/>
)
}
DropdownMenuShortcut.displayName = "DropdownMenuShortcut"
export {
DropdownMenu,
DropdownMenuTrigger,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuCheckboxItem,
DropdownMenuRadioItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuShortcut,
DropdownMenuGroup,
DropdownMenuPortal,
DropdownMenuSub,
DropdownMenuSubContent,
DropdownMenuSubTrigger,
DropdownMenuRadioGroup,
}
+102
View File
@@ -0,0 +1,102 @@
'use client';
import type { Variants } from 'motion/react';
import type { HTMLAttributes } from 'react';
import { forwardRef, useCallback, useImperativeHandle, useRef } from 'react';
import { motion, useAnimation } from 'motion/react';
import { cn } from '@/lib/utils';
export interface GithubIconHandle {
startAnimation: () => void;
stopAnimation: () => void;
}
interface GithubIconProps extends HTMLAttributes<HTMLDivElement> {
size?: number;
}
const BODY_VARIANTS: Variants = {
normal: {
opacity: 1,
pathLength: 1,
scale: 1,
transition: {
duration: 0.3,
},
},
animate: {
opacity: [0, 1],
pathLength: [0, 1],
scale: [0.9, 1],
transition: {
duration: 0.4,
},
},
};
const TAIL_VARIANTS: Variants = {
normal: {
pathLength: 1,
rotate: 0,
transition: {
duration: 0.3,
},
},
draw: {
pathLength: [0, 1],
rotate: 0,
transition: {
duration: 0.5,
},
},
wag: {
pathLength: 1,
rotate: [0, -15, 15, -10, 10, -5, 5],
transition: {
duration: 2.5,
ease: 'easeInOut',
repeat: Infinity,
},
},
};
const GithubIcon = forwardRef<GithubIconHandle, GithubIconProps>(({ onMouseEnter, onMouseLeave, className, size = 28, ...props }, ref) => {
const bodyControls = useAnimation();
const tailControls = useAnimation();
const isControlledRef = useRef(false);
useImperativeHandle(ref, () => {
isControlledRef.current = true;
return {
startAnimation: async () => {
bodyControls.start('animate');
await tailControls.start('draw');
tailControls.start('wag');
},
stopAnimation: () => {
bodyControls.start('normal');
tailControls.start('normal');
},
};
});
const handleMouseEnter = useCallback(async (e: React.MouseEvent<HTMLDivElement>) => {
if (!isControlledRef.current) {
bodyControls.start('animate');
await tailControls.start('draw');
tailControls.start('wag');
}
else {
onMouseEnter?.(e);
}
}, [bodyControls, onMouseEnter, tailControls]);
const handleMouseLeave = useCallback((e: React.MouseEvent<HTMLDivElement>) => {
if (!isControlledRef.current) {
bodyControls.start('normal');
tailControls.start('normal');
}
else {
onMouseLeave?.(e);
}
}, [bodyControls, tailControls, onMouseLeave]);
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">
<motion.path variants={BODY_VARIANTS} initial="normal" animate={bodyControls} d="M15 22v-4a4.8 4.8 0 0 0-1-3.5c3 0 6-2 6-5.5.08-1.25-.27-2.48-1-3.5.28-1.15.28-2.35 0-3.5 0 0-1 0-3 1.5-2.64-.5-5.36-.5-8 0C6 2 5 2 5 2c-.3 1.15-.3 2.35 0 3.5A5.403 5.403 0 0 0 4 9c0 3.5 3 5.5 6 5.5-.39.49-.68 1.05-.85 1.65-.17.6-.22 1.23-.15 1.85v4"/>
<motion.path variants={TAIL_VARIANTS} initial="normal" animate={tailControls} d="M9 18c-4.51 2-5-2-7-2"/>
</svg>
</div>);
});
GithubIcon.displayName = 'GithubIcon';
export { GithubIcon };
+62
View File
@@ -0,0 +1,62 @@
'use client';
import type { Transition, Variants } from 'motion/react';
import type { HTMLAttributes } from 'react';
import { forwardRef, useCallback, useImperativeHandle, useRef } from 'react';
import { motion, useAnimation } from 'motion/react';
import { cn } from '@/lib/utils';
export interface HomeIconHandle {
startAnimation: () => void;
stopAnimation: () => void;
}
interface HomeIconProps extends HTMLAttributes<HTMLDivElement> {
size?: number;
}
const DEFAULT_TRANSITION: Transition = {
duration: 0.6,
opacity: { duration: 0.2 },
};
const PATH_VARIANTS: Variants = {
normal: {
pathLength: 1,
opacity: 1,
},
animate: {
opacity: [0, 1],
pathLength: [0, 1],
},
};
const HomeIcon = forwardRef<HomeIconHandle, HomeIconProps>(({ onMouseEnter, onMouseLeave, className, size = 28, ...props }, ref) => {
const controls = useAnimation();
const isControlledRef = useRef(false);
useImperativeHandle(ref, () => {
isControlledRef.current = true;
return {
startAnimation: () => controls.start('animate'),
stopAnimation: () => controls.start('normal'),
};
});
const handleMouseEnter = useCallback((e: React.MouseEvent<HTMLDivElement>) => {
if (!isControlledRef.current) {
controls.start('animate');
}
else {
onMouseEnter?.(e);
}
}, [controls, onMouseEnter]);
const handleMouseLeave = useCallback((e: React.MouseEvent<HTMLDivElement>) => {
if (!isControlledRef.current) {
controls.start('normal');
}
else {
onMouseLeave?.(e);
}
}, [controls, onMouseLeave]);
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">
<path d="M3 10a2 2 0 0 1 .709-1.528l7-5.999a2 2 0 0 1 2.582 0l7 5.999A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/>
<motion.path d="M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8" variants={PATH_VARIANTS} transition={DEFAULT_TRANSITION} animate={controls}/>
</svg>
</div>);
});
HomeIcon.displayName = 'HomeIcon';
export { HomeIcon };
+121 -181
View File
@@ -1,216 +1,156 @@
import * as React from "react"; import * as React from "react";
import { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
import { import { ContextMenu, ContextMenuContent, ContextMenuItem, ContextMenuSeparator, ContextMenuTrigger, } from "@/components/ui/context-menu";
ContextMenu,
ContextMenuContent,
ContextMenuItem,
ContextMenuSeparator,
ContextMenuTrigger,
} from "@/components/ui/context-menu";
import { Scissors, Copy, Clipboard, Type } from "lucide-react"; import { Scissors, Copy, Clipboard, Type } from "lucide-react";
export interface InputWithContextProps extends React.InputHTMLAttributes<HTMLInputElement> {
export interface InputWithContextProps onValueChange?: (value: string) => void;
extends React.InputHTMLAttributes<HTMLInputElement> {
onValueChange?: (value: string) => void;
} }
const InputWithContext = React.forwardRef<HTMLInputElement, InputWithContextProps>(({ className, type, onValueChange, onChange, ...props }, ref) => {
const InputWithContext = React.forwardRef<HTMLInputElement, InputWithContextProps>(
({ className, type, onValueChange, onChange, ...props }, ref) => {
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);
// Combine refs
React.useImperativeHandle(ref, () => inputRef.current as HTMLInputElement); React.useImperativeHandle(ref, () => inputRef.current as HTMLInputElement);
// Check selection state
const updateSelectionState = () => { const updateSelectionState = () => {
const input = inputRef.current; const input = inputRef.current;
if (!input) return; if (!input)
const start = input.selectionStart ?? 0; return;
const end = input.selectionEnd ?? 0;
setHasSelection(start !== end);
};
// Check clipboard permission when user explicitly opens the context menu.
const checkClipboard = async () => {
try {
const text = await navigator.clipboard.readText();
setCanPaste(text.length > 0);
} catch {
setCanPaste(false);
}
};
const handleCut = async () => {
const input = inputRef.current;
if (!input) return;
const start = input.selectionStart ?? 0;
const end = input.selectionEnd ?? 0;
const selectedText = input.value.substring(start, end);
if (selectedText) {
try {
await navigator.clipboard.writeText(selectedText);
const newValue = input.value.substring(0, start) + input.value.substring(end);
// Update value and trigger change
input.value = newValue;
input.setSelectionRange(start, start);
// Trigger React onChange
if (onChange) {
const event = {
target: input,
currentTarget: input,
} as React.ChangeEvent<HTMLInputElement>;
onChange(event);
}
if (onValueChange) {
onValueChange(newValue);
}
input.focus();
} catch (err) {
console.error("Failed to cut:", err);
}
}
};
const handleCopy = async () => {
const input = inputRef.current;
if (!input) return;
const start = input.selectionStart ?? 0;
const end = input.selectionEnd ?? 0;
const selectedText = input.value.substring(start, end);
if (selectedText) {
try {
await navigator.clipboard.writeText(selectedText);
input.focus();
} catch (err) {
console.error("Failed to copy:", err);
}
}
};
const handlePaste = async () => {
const input = inputRef.current;
if (!input) return;
try {
const text = await navigator.clipboard.readText();
const start = input.selectionStart ?? 0; const start = input.selectionStart ?? 0;
const end = input.selectionEnd ?? 0; const end = input.selectionEnd ?? 0;
setHasSelection(start !== end);
const newValue = };
input.value.substring(0, start) + text + input.value.substring(end); const checkClipboard = async () => {
try {
// Update value and trigger change const text = await navigator.clipboard.readText();
input.value = newValue; setCanPaste(text.length > 0);
const newPosition = start + text.length; }
input.setSelectionRange(newPosition, newPosition); catch {
setCanPaste(false);
// Trigger React onChange }
if (onChange) { };
const event = { const handleCut = async () => {
target: input, const input = inputRef.current;
currentTarget: input, if (!input)
} as React.ChangeEvent<HTMLInputElement>; return;
onChange(event); const start = input.selectionStart ?? 0;
} const end = input.selectionEnd ?? 0;
const selectedText = input.value.substring(start, end);
if (onValueChange) { if (selectedText) {
onValueChange(newValue); try {
} await navigator.clipboard.writeText(selectedText);
const newValue = input.value.substring(0, start) + input.value.substring(end);
input.focus(); input.value = newValue;
await checkClipboard(); input.setSelectionRange(start, start);
} catch (err) { if (onChange) {
console.error("Failed to paste:", err); const event = {
} target: input,
currentTarget: input,
} as React.ChangeEvent<HTMLInputElement>;
onChange(event);
}
if (onValueChange) {
onValueChange(newValue);
}
input.focus();
}
catch (err) {
console.error("Failed to cut:", err);
}
}
};
const handleCopy = async () => {
const input = inputRef.current;
if (!input)
return;
const start = input.selectionStart ?? 0;
const end = input.selectionEnd ?? 0;
const selectedText = input.value.substring(start, end);
if (selectedText) {
try {
await navigator.clipboard.writeText(selectedText);
input.focus();
}
catch (err) {
console.error("Failed to copy:", err);
}
}
};
const handlePaste = async () => {
const input = inputRef.current;
if (!input)
return;
try {
const text = await navigator.clipboard.readText();
const start = input.selectionStart ?? 0;
const end = input.selectionEnd ?? 0;
const newValue = input.value.substring(0, start) + text + input.value.substring(end);
input.value = newValue;
const newPosition = start + text.length;
input.setSelectionRange(newPosition, newPosition);
if (onChange) {
const event = {
target: input,
currentTarget: input,
} as React.ChangeEvent<HTMLInputElement>;
onChange(event);
}
if (onValueChange) {
onValueChange(newValue);
}
input.focus();
await checkClipboard();
}
catch (err) {
console.error("Failed to paste:", err);
}
}; };
const handleSelectAll = () => { const handleSelectAll = () => {
const input = inputRef.current; const input = inputRef.current;
if (!input) return; if (!input)
input.select(); return;
input.focus(); input.select();
updateSelectionState(); input.focus();
updateSelectionState();
}; };
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => { const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
if (onChange) { if (onChange) {
onChange(e); onChange(e);
} }
if (onValueChange) { if (onValueChange) {
onValueChange(e.target.value); onValueChange(e.target.value);
} }
}; };
return (<ContextMenu onOpenChange={(open) => {
return ( if (open) {
<ContextMenu checkClipboard();
onOpenChange={(open) => { }
if (open) { }}>
checkClipboard();
}
}}
>
<ContextMenuTrigger asChild> <ContextMenuTrigger asChild>
<Input <Input ref={inputRef} type={type} className={className} onChange={handleInputChange} onSelect={updateSelectionState} onMouseUp={updateSelectionState} onKeyUp={updateSelectionState} {...props}/>
ref={inputRef}
type={type}
className={className}
onChange={handleInputChange}
onSelect={updateSelectionState}
onMouseUp={updateSelectionState}
onKeyUp={updateSelectionState}
{...props}
/>
</ContextMenuTrigger> </ContextMenuTrigger>
<ContextMenuContent className="w-48"> <ContextMenuContent className="w-48">
<ContextMenuItem <ContextMenuItem onSelect={handleCut} disabled={!hasSelection || props.disabled || props.readOnly}>
onSelect={handleCut} <Scissors className="mr-2 h-4 w-4"/>
disabled={!hasSelection || props.disabled || props.readOnly}
>
<Scissors className="mr-2 h-4 w-4" />
Cut Cut
<span className="ml-auto text-xs text-muted-foreground">Ctrl+X</span> <span className="ml-auto text-xs text-muted-foreground">Ctrl+X</span>
</ContextMenuItem> </ContextMenuItem>
<ContextMenuItem <ContextMenuItem onSelect={handleCopy} disabled={!hasSelection || props.disabled}>
onSelect={handleCopy} <Copy className="mr-2 h-4 w-4"/>
disabled={!hasSelection || props.disabled}
>
<Copy className="mr-2 h-4 w-4" />
Copy Copy
<span className="ml-auto text-xs text-muted-foreground">Ctrl+C</span> <span className="ml-auto text-xs text-muted-foreground">Ctrl+C</span>
</ContextMenuItem> </ContextMenuItem>
<ContextMenuItem <ContextMenuItem onSelect={handlePaste} disabled={!canPaste || props.disabled || props.readOnly}>
onSelect={handlePaste} <Clipboard className="mr-2 h-4 w-4"/>
disabled={!canPaste || props.disabled || props.readOnly}
>
<Clipboard className="mr-2 h-4 w-4" />
Paste Paste
<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 <ContextMenuItem onSelect={handleSelectAll} disabled={!inputRef.current?.value || props.disabled}>
onSelect={handleSelectAll} <Type className="mr-2 h-4 w-4"/>
disabled={!inputRef.current?.value || props.disabled}
>
<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>
</ContextMenuItem> </ContextMenuItem>
</ContextMenuContent> </ContextMenuContent>
</ContextMenu> </ContextMenu>);
); });
}
);
InputWithContext.displayName = "InputWithContext"; InputWithContext.displayName = "InputWithContext";
export { InputWithContext }; export { InputWithContext };
+4 -19
View File
@@ -1,21 +1,6 @@
import * as React from "react" import * as React from "react";
import { cn } from "@/lib/utils";
import { cn } from "@/lib/utils"
function Input({ className, type, ...props }: React.ComponentProps<"input">) { function Input({ className, type, ...props }: React.ComponentProps<"input">) {
return ( return (<input type={type} data-slot="input" className={cn("file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm", "focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]", "aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive", className)} {...props}/>);
<input
type={type}
data-slot="input"
className={cn(
"file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
"focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
"aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
className
)}
{...props}
/>
)
} }
export { Input };
export { Input }
+7 -23
View File
@@ -1,24 +1,8 @@
"use client" "use client";
import * as React from "react";
import * as React from "react" import * as LabelPrimitive from "@radix-ui/react-label";
import * as LabelPrimitive from "@radix-ui/react-label" import { cn } from "@/lib/utils";
function Label({ className, ...props }: React.ComponentProps<typeof LabelPrimitive.Root>) {
import { cn } from "@/lib/utils" return (<LabelPrimitive.Root data-slot="label" className={cn("flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50", className)} {...props}/>);
function Label({
className,
...props
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
return (
<LabelPrimitive.Root
data-slot="label"
className={cn(
"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
className
)}
{...props}
/>
)
} }
export { Label };
export { Label }
+9 -30
View File
@@ -1,31 +1,10 @@
"use client" "use client";
import * as React from "react";
import * as React from "react" import * as ProgressPrimitive from "@radix-ui/react-progress";
import * as ProgressPrimitive from "@radix-ui/react-progress" import { cn } from "@/lib/utils";
function Progress({ className, value, ...props }: React.ComponentProps<typeof ProgressPrimitive.Root>) {
import { cn } from "@/lib/utils" return (<ProgressPrimitive.Root data-slot="progress" className={cn("bg-primary/20 relative h-2 w-full overflow-hidden rounded-full", className)} {...props}>
<ProgressPrimitive.Indicator data-slot="progress-indicator" className="bg-primary h-full w-full flex-1 transition-all" style={{ transform: `translateX(-${100 - (value || 0)}%)` }}/>
function Progress({ </ProgressPrimitive.Root>);
className,
value,
...props
}: React.ComponentProps<typeof ProgressPrimitive.Root>) {
return (
<ProgressPrimitive.Root
data-slot="progress"
className={cn(
"bg-primary/20 relative h-2 w-full overflow-hidden rounded-full",
className
)}
{...props}
>
<ProgressPrimitive.Indicator
data-slot="progress-indicator"
className="bg-primary h-full w-full flex-1 transition-all"
style={{ transform: `translateX(-${100 - (value || 0)}%)` }}
/>
</ProgressPrimitive.Root>
)
} }
export { Progress };
export { Progress }
+39 -161
View File
@@ -1,185 +1,63 @@
import * as React from "react" import * as React from "react";
import * as SelectPrimitive from "@radix-ui/react-select" import * as SelectPrimitive from "@radix-ui/react-select";
import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-react" import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-react";
import { cn } from "@/lib/utils";
import { cn } from "@/lib/utils" function Select({ ...props }: React.ComponentProps<typeof SelectPrimitive.Root>) {
return <SelectPrimitive.Root data-slot="select" {...props}/>;
function Select({
...props
}: React.ComponentProps<typeof SelectPrimitive.Root>) {
return <SelectPrimitive.Root data-slot="select" {...props} />
} }
function SelectGroup({ ...props }: React.ComponentProps<typeof SelectPrimitive.Group>) {
function SelectGroup({ return <SelectPrimitive.Group data-slot="select-group" {...props}/>;
...props
}: React.ComponentProps<typeof SelectPrimitive.Group>) {
return <SelectPrimitive.Group data-slot="select-group" {...props} />
} }
function SelectValue({ ...props }: React.ComponentProps<typeof SelectPrimitive.Value>) {
function SelectValue({ return <SelectPrimitive.Value data-slot="select-value" {...props}/>;
...props
}: React.ComponentProps<typeof SelectPrimitive.Value>) {
return <SelectPrimitive.Value data-slot="select-value" {...props} />
} }
function SelectTrigger({ className, size = "default", children, ...props }: React.ComponentProps<typeof SelectPrimitive.Trigger> & {
function SelectTrigger({ size?: "sm" | "default";
className,
size = "default",
children,
...props
}: React.ComponentProps<typeof SelectPrimitive.Trigger> & {
size?: "sm" | "default"
}) { }) {
return ( return (<SelectPrimitive.Trigger data-slot="select-trigger" data-size={size} className={cn("border-input data-placeholder:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-fit items-center justify-between gap-2 rounded-md border bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4", className)} {...props}>
<SelectPrimitive.Trigger
data-slot="select-trigger"
data-size={size}
className={cn(
"border-input data-placeholder:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-fit items-center justify-between gap-2 rounded-md border bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
>
{children} {children}
<SelectPrimitive.Icon asChild> <SelectPrimitive.Icon asChild>
<ChevronDownIcon className="size-4 opacity-50" /> <ChevronDownIcon className="size-4 opacity-50"/>
</SelectPrimitive.Icon> </SelectPrimitive.Icon>
</SelectPrimitive.Trigger> </SelectPrimitive.Trigger>);
)
} }
function SelectContent({ className, children, position = "popper", align = "center", ...props }: React.ComponentProps<typeof SelectPrimitive.Content>) {
function SelectContent({ return (<SelectPrimitive.Portal>
className, <SelectPrimitive.Content data-slot="select-content" className={cn("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-32 origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border shadow-md", position === "popper" &&
children, "data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1", className)} position={position} align={align} {...props}>
position = "popper",
align = "center",
...props
}: React.ComponentProps<typeof SelectPrimitive.Content>) {
return (
<SelectPrimitive.Portal>
<SelectPrimitive.Content
data-slot="select-content"
className={cn(
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-32 origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border shadow-md",
position === "popper" &&
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
className
)}
position={position}
align={align}
{...props}
>
<SelectScrollUpButton /> <SelectScrollUpButton />
<SelectPrimitive.Viewport <SelectPrimitive.Viewport className={cn("p-1", position === "popper" &&
className={cn( "h-(--radix-select-trigger-height) w-full min-w-(--radix-select-trigger-width) scroll-my-1")}>
"p-1",
position === "popper" &&
"h-(--radix-select-trigger-height) w-full min-w-(--radix-select-trigger-width) scroll-my-1"
)}
>
{children} {children}
</SelectPrimitive.Viewport> </SelectPrimitive.Viewport>
<SelectScrollDownButton /> <SelectScrollDownButton />
</SelectPrimitive.Content> </SelectPrimitive.Content>
</SelectPrimitive.Portal> </SelectPrimitive.Portal>);
)
} }
function SelectLabel({ className, ...props }: React.ComponentProps<typeof SelectPrimitive.Label>) {
function SelectLabel({ return (<SelectPrimitive.Label data-slot="select-label" className={cn("text-muted-foreground px-2 py-1.5 text-xs", className)} {...props}/>);
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.Label>) {
return (
<SelectPrimitive.Label
data-slot="select-label"
className={cn("text-muted-foreground px-2 py-1.5 text-xs", className)}
{...props}
/>
)
} }
function SelectItem({ className, children, ...props }: React.ComponentProps<typeof SelectPrimitive.Item>) {
function SelectItem({ return (<SelectPrimitive.Item data-slot="select-item" className={cn("focus:bg-accent focus:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2", className)} {...props}>
className,
children,
...props
}: React.ComponentProps<typeof SelectPrimitive.Item>) {
return (
<SelectPrimitive.Item
data-slot="select-item"
className={cn(
"focus:bg-accent focus:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",
className
)}
{...props}
>
<span className="absolute right-2 flex size-3.5 items-center justify-center"> <span className="absolute right-2 flex size-3.5 items-center justify-center">
<SelectPrimitive.ItemIndicator> <SelectPrimitive.ItemIndicator>
<CheckIcon className="size-4" /> <CheckIcon className="size-4"/>
</SelectPrimitive.ItemIndicator> </SelectPrimitive.ItemIndicator>
</span> </span>
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText> <SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
</SelectPrimitive.Item> </SelectPrimitive.Item>);
)
} }
function SelectSeparator({ className, ...props }: React.ComponentProps<typeof SelectPrimitive.Separator>) {
function SelectSeparator({ return (<SelectPrimitive.Separator data-slot="select-separator" className={cn("bg-border pointer-events-none -mx-1 my-1 h-px", className)} {...props}/>);
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.Separator>) {
return (
<SelectPrimitive.Separator
data-slot="select-separator"
className={cn("bg-border pointer-events-none -mx-1 my-1 h-px", className)}
{...props}
/>
)
} }
function SelectScrollUpButton({ className, ...props }: React.ComponentProps<typeof SelectPrimitive.ScrollUpButton>) {
function SelectScrollUpButton({ return (<SelectPrimitive.ScrollUpButton data-slot="select-scroll-up-button" className={cn("flex cursor-default items-center justify-center py-1", className)} {...props}>
className, <ChevronUpIcon className="size-4"/>
...props </SelectPrimitive.ScrollUpButton>);
}: React.ComponentProps<typeof SelectPrimitive.ScrollUpButton>) {
return (
<SelectPrimitive.ScrollUpButton
data-slot="select-scroll-up-button"
className={cn(
"flex cursor-default items-center justify-center py-1",
className
)}
{...props}
>
<ChevronUpIcon className="size-4" />
</SelectPrimitive.ScrollUpButton>
)
} }
function SelectScrollDownButton({ className, ...props }: React.ComponentProps<typeof SelectPrimitive.ScrollDownButton>) {
function SelectScrollDownButton({ return (<SelectPrimitive.ScrollDownButton data-slot="select-scroll-down-button" className={cn("flex cursor-default items-center justify-center py-1", className)} {...props}>
className, <ChevronDownIcon className="size-4"/>
...props </SelectPrimitive.ScrollDownButton>);
}: React.ComponentProps<typeof SelectPrimitive.ScrollDownButton>) {
return (
<SelectPrimitive.ScrollDownButton
data-slot="select-scroll-down-button"
className={cn(
"flex cursor-default items-center justify-center py-1",
className
)}
{...props}
>
<ChevronDownIcon className="size-4" />
</SelectPrimitive.ScrollDownButton>
)
}
export {
Select,
SelectContent,
SelectGroup,
SelectItem,
SelectLabel,
SelectScrollDownButton,
SelectScrollUpButton,
SelectSeparator,
SelectTrigger,
SelectValue,
} }
export { Select, SelectContent, SelectGroup, SelectItem, SelectLabel, SelectScrollDownButton, SelectScrollUpButton, SelectSeparator, SelectTrigger, SelectValue, };
+54
View File
@@ -0,0 +1,54 @@
'use client';
import type { HTMLAttributes } from 'react';
import { forwardRef, useCallback, useImperativeHandle, useRef } from 'react';
import { motion, useAnimation } from 'motion/react';
import { cn } from '@/lib/utils';
export interface SettingsIconHandle {
startAnimation: () => void;
stopAnimation: () => void;
}
interface SettingsIconProps extends HTMLAttributes<HTMLDivElement> {
size?: number;
}
const SettingsIcon = forwardRef<SettingsIconHandle, SettingsIconProps>(({ onMouseEnter, onMouseLeave, className, size = 28, ...props }, ref) => {
const controls = useAnimation();
const isControlledRef = useRef(false);
useImperativeHandle(ref, () => {
isControlledRef.current = true;
return {
startAnimation: () => controls.start('animate'),
stopAnimation: () => controls.start('normal'),
};
});
const handleMouseEnter = useCallback((e: React.MouseEvent<HTMLDivElement>) => {
if (!isControlledRef.current) {
controls.start('animate');
}
else {
onMouseEnter?.(e);
}
}, [controls, onMouseEnter]);
const handleMouseLeave = useCallback((e: React.MouseEvent<HTMLDivElement>) => {
if (!isControlledRef.current) {
controls.start('normal');
}
else {
onMouseLeave?.(e);
}
}, [controls, onMouseLeave]);
return (<div className={cn(className)} onMouseEnter={handleMouseEnter} onMouseLeave={handleMouseLeave} {...props}>
<motion.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" transition={{ type: 'spring', stiffness: 50, damping: 10 }} variants={{
normal: {
rotate: 0,
},
animate: {
rotate: 180,
},
}} animate={controls}>
<path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"/>
<circle cx="12" cy="12" r="3"/>
</motion.svg>
</div>);
});
SettingsIcon.displayName = 'SettingsIcon';
export { SettingsIcon };
+26 -46
View File
@@ -1,47 +1,27 @@
import { import { CircleCheckIcon, InfoIcon, Loader2Icon, OctagonXIcon, TriangleAlertIcon, } from "lucide-react";
CircleCheckIcon, import { useTheme } from "next-themes";
InfoIcon, import { Toaster as Sonner, type ToasterProps } from "sonner";
Loader2Icon,
OctagonXIcon,
TriangleAlertIcon,
} from "lucide-react"
import { useTheme } from "next-themes"
import { Toaster as Sonner, type ToasterProps } from "sonner"
const Toaster = ({ ...props }: ToasterProps) => { const Toaster = ({ ...props }: ToasterProps) => {
const { theme = "system" } = useTheme() const { theme = "system" } = useTheme();
return (<Sonner theme={theme as ToasterProps["theme"]} className="toaster group" icons={{
return ( success: <CircleCheckIcon className="size-4"/>,
<Sonner info: <InfoIcon className="size-4"/>,
theme={theme as ToasterProps["theme"]} warning: <TriangleAlertIcon className="size-4"/>,
className="toaster group" error: <OctagonXIcon className="size-4"/>,
icons={{ loading: <Loader2Icon className="size-4 animate-spin"/>,
success: <CircleCheckIcon className="size-4" />, }} toastOptions={{
info: <InfoIcon className="size-4" />, classNames: {
warning: <TriangleAlertIcon className="size-4" />, success: "border-green-500 bg-green-50 text-green-900 dark:bg-green-950 dark:text-green-100 [&>svg]:text-green-500",
error: <OctagonXIcon className="size-4" />, error: "border-red-500 bg-red-50 text-red-900 dark:bg-red-950 dark:text-red-100 [&>svg]:text-red-500",
loading: <Loader2Icon className="size-4 animate-spin" />, warning: "border-yellow-500 bg-yellow-50 text-yellow-900 dark:bg-yellow-950 dark:text-yellow-100 [&>svg]:text-yellow-500",
}} info: "border-blue-500 bg-blue-50 text-blue-900 dark:bg-blue-950 dark:text-blue-100 [&>svg]:text-blue-500",
toastOptions={{ },
classNames: { }} style={{
success: "border-green-500 bg-green-50 text-green-900 dark:bg-green-950 dark:text-green-100 [&>svg]:text-green-500", "--normal-bg": "var(--popover)",
error: "border-red-500 bg-red-50 text-red-900 dark:bg-red-950 dark:text-red-100 [&>svg]:text-red-500", "--normal-text": "var(--popover-foreground)",
warning: "border-yellow-500 bg-yellow-50 text-yellow-900 dark:bg-yellow-950 dark:text-yellow-100 [&>svg]:text-yellow-500", "--normal-border": "var(--border)",
info: "border-blue-500 bg-blue-50 text-blue-900 dark:bg-blue-950 dark:text-blue-100 [&>svg]:text-blue-500", "--border-radius": "var(--radius)",
}, left: "calc(56px + 1rem)",
}} } as React.CSSProperties} {...props}/>);
style={ };
{ export { Toaster };
"--normal-bg": "var(--popover)",
"--normal-text": "var(--popover-foreground)",
"--normal-border": "var(--border)",
"--border-radius": "var(--radius)",
left: "calc(56px + 1rem)",
} as React.CSSProperties
}
{...props}
/>
)
}
export { Toaster }
+4 -13
View File
@@ -1,15 +1,6 @@
import { Loader2 } from "lucide-react" import { Loader2 } from "lucide-react";
import { cn } from "@/lib/utils" import { cn } from "@/lib/utils";
function Spinner({ className, ...props }: React.ComponentProps<"svg">) { function Spinner({ className, ...props }: React.ComponentProps<"svg">) {
return ( return (<Loader2 role="status" aria-label="Loading" className={cn("size-4 animate-spin", className)} {...props}/>);
<Loader2
role="status"
aria-label="Loading"
className={cn("size-4 animate-spin", className)}
{...props}
/>
)
} }
export { Spinner };
export { Spinner }
+9 -30
View File
@@ -1,31 +1,10 @@
"use client" "use client";
import * as React from "react";
import * as React from "react" import * as SwitchPrimitive from "@radix-ui/react-switch";
import * as SwitchPrimitive from "@radix-ui/react-switch" import { cn } from "@/lib/utils";
function Switch({ className, ...props }: React.ComponentProps<typeof SwitchPrimitive.Root>) {
import { cn } from "@/lib/utils" return (<SwitchPrimitive.Root data-slot="switch" className={cn("peer data-[state=checked]:bg-primary data-[state=unchecked]:bg-input focus-visible:border-ring focus-visible:ring-ring/50 inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border border-transparent shadow-xs transition-all outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50", className)} {...props}>
<SwitchPrimitive.Thumb data-slot="switch-thumb" className={cn("pointer-events-none block size-4 rounded-full shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0 data-[state=checked]:bg-primary-foreground data-[state=unchecked]:bg-background")}/>
function Switch({ </SwitchPrimitive.Root>);
className,
...props
}: React.ComponentProps<typeof SwitchPrimitive.Root>) {
return (
<SwitchPrimitive.Root
data-slot="switch"
className={cn(
"peer data-[state=checked]:bg-primary data-[state=unchecked]:bg-input focus-visible:border-ring focus-visible:ring-ring/50 inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border border-transparent shadow-xs transition-all outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
className
)}
{...props}
>
<SwitchPrimitive.Thumb
data-slot="switch-thumb"
className={cn(
"pointer-events-none block size-4 rounded-full shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0 data-[state=checked]:bg-primary-foreground data-[state=unchecked]:bg-background"
)}
/>
</SwitchPrimitive.Root>
)
} }
export { Switch };
export { Switch }
+59
View File
@@ -0,0 +1,59 @@
'use client';
import type { Variants } from 'motion/react';
import type { HTMLAttributes } from 'react';
import { forwardRef, useCallback, useImperativeHandle, useRef } from 'react';
import { motion, useAnimation } from 'motion/react';
import { cn } from '@/lib/utils';
export interface TerminalIconHandle {
startAnimation: () => void;
stopAnimation: () => void;
}
interface TerminalIconProps extends HTMLAttributes<HTMLDivElement> {
size?: number;
}
const LINE_VARIANTS: Variants = {
normal: { opacity: 1 },
animate: {
opacity: [1, 0, 1],
transition: {
duration: 0.8,
repeat: Infinity,
ease: 'linear',
},
},
};
const TerminalIcon = forwardRef<TerminalIconHandle, TerminalIconProps>(({ onMouseEnter, onMouseLeave, className, size = 28, ...props }, ref) => {
const controls = useAnimation();
const isControlledRef = useRef(false);
useImperativeHandle(ref, () => {
isControlledRef.current = true;
return {
startAnimation: () => controls.start('animate'),
stopAnimation: () => controls.start('normal'),
};
});
const handleMouseEnter = useCallback((e: React.MouseEvent<HTMLDivElement>) => {
if (!isControlledRef.current) {
controls.start('animate');
}
else {
onMouseEnter?.(e);
}
}, [controls, onMouseEnter]);
const handleMouseLeave = useCallback((e: React.MouseEvent<HTMLDivElement>) => {
if (!isControlledRef.current) {
controls.start('normal');
}
else {
onMouseLeave?.(e);
}
}, [controls, onMouseLeave]);
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">
<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"/>
</svg>
</div>);
});
TerminalIcon.displayName = 'TerminalIcon';
export { TerminalIcon };
+18 -55
View File
@@ -1,61 +1,24 @@
"use client" "use client";
import * as React from "react";
import * as React from "react" import * as TooltipPrimitive from "@radix-ui/react-tooltip";
import * as TooltipPrimitive from "@radix-ui/react-tooltip" import { cn } from "@/lib/utils";
function TooltipProvider({ delayDuration = 0, ...props }: React.ComponentProps<typeof TooltipPrimitive.Provider>) {
import { cn } from "@/lib/utils" return (<TooltipPrimitive.Provider data-slot="tooltip-provider" delayDuration={delayDuration} {...props}/>);
function TooltipProvider({
delayDuration = 0,
...props
}: React.ComponentProps<typeof TooltipPrimitive.Provider>) {
return (
<TooltipPrimitive.Provider
data-slot="tooltip-provider"
delayDuration={delayDuration}
{...props}
/>
)
} }
function Tooltip({ ...props }: React.ComponentProps<typeof TooltipPrimitive.Root>) {
function Tooltip({ return (<TooltipProvider>
...props <TooltipPrimitive.Root data-slot="tooltip" {...props}/>
}: React.ComponentProps<typeof TooltipPrimitive.Root>) { </TooltipProvider>);
return (
<TooltipProvider>
<TooltipPrimitive.Root data-slot="tooltip" {...props} />
</TooltipProvider>
)
} }
function TooltipTrigger({ ...props }: React.ComponentProps<typeof TooltipPrimitive.Trigger>) {
function TooltipTrigger({ return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props}/>;
...props
}: React.ComponentProps<typeof TooltipPrimitive.Trigger>) {
return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props} />
} }
function TooltipContent({ className, sideOffset = 0, children, ...props }: React.ComponentProps<typeof TooltipPrimitive.Content>) {
function TooltipContent({ return (<TooltipPrimitive.Portal>
className, <TooltipPrimitive.Content data-slot="tooltip-content" sideOffset={sideOffset} className={cn("bg-foreground text-background animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance", className)} {...props}>
sideOffset = 0,
children,
...props
}: React.ComponentProps<typeof TooltipPrimitive.Content>) {
return (
<TooltipPrimitive.Portal>
<TooltipPrimitive.Content
data-slot="tooltip-content"
sideOffset={sideOffset}
className={cn(
"bg-foreground text-background animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",
className
)}
{...props}
>
{children} {children}
<TooltipPrimitive.Arrow className="bg-foreground fill-foreground z-50 size-2.5 translate-y-[calc(-50%-2px)] rotate-45 rounded-[2px]" /> <TooltipPrimitive.Arrow className="bg-foreground fill-foreground z-50 size-2.5 translate-y-[calc(-50%-2px)] rotate-45 rounded-[2px]"/>
</TooltipPrimitive.Content> </TooltipPrimitive.Content>
</TooltipPrimitive.Portal> </TooltipPrimitive.Portal>);
)
} }
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider };
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }
+62 -97
View File
@@ -1,106 +1,71 @@
// Audio utility for toast notifications using Web Audio API
class AudioManager { 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)();
this.audioContext = new (window.AudioContext || (window as any).webkitAudioContext)(); }
return this.audioContext;
} }
return this.audioContext; private playTone(frequency: number, duration: number, type: OscillatorType = 'sine', volume: number = 0.3) {
} try {
const ctx = this.getAudioContext();
// Generate a simple tone using oscillator const oscillator = ctx.createOscillator();
private playTone(frequency: number, duration: number, type: OscillatorType = 'sine', volume: number = 0.3) { const gainNode = ctx.createGain();
try { oscillator.connect(gainNode);
const ctx = this.getAudioContext(); gainNode.connect(ctx.destination);
const oscillator = ctx.createOscillator(); oscillator.frequency.value = frequency;
const gainNode = ctx.createGain(); oscillator.type = type;
gainNode.gain.setValueAtTime(volume, ctx.currentTime);
oscillator.connect(gainNode); gainNode.gain.exponentialRampToValueAtTime(0.01, ctx.currentTime + duration);
gainNode.connect(ctx.destination); oscillator.start(ctx.currentTime);
oscillator.stop(ctx.currentTime + duration);
oscillator.frequency.value = frequency; }
oscillator.type = type; catch (error) {
console.error('Error playing audio:', error);
gainNode.gain.setValueAtTime(volume, ctx.currentTime); }
gainNode.gain.exponentialRampToValueAtTime(0.01, ctx.currentTime + duration);
oscillator.start(ctx.currentTime);
oscillator.stop(ctx.currentTime + duration);
} catch (error) {
console.error('Error playing audio:', error);
} }
} playSuccess() {
const ctx = this.getAudioContext();
// Success sound - pleasant ascending tones const now = ctx.currentTime;
playSuccess() { this.playToneAt(523.25, 0.08, 'sine', 0.2, now);
const ctx = this.getAudioContext(); this.playToneAt(659.25, 0.08, 'sine', 0.2, now + 0.08);
const now = ctx.currentTime; this.playToneAt(783.99, 0.15, 'sine', 0.25, now + 0.16);
}
// First tone playError() {
this.playToneAt(523.25, 0.08, 'sine', 0.2, now); // C5 const ctx = this.getAudioContext();
// Second tone const now = ctx.currentTime;
this.playToneAt(659.25, 0.08, 'sine', 0.2, now + 0.08); // E5 this.playToneAt(392.00, 0.1, 'square', 0.15, now);
// Third tone this.playToneAt(329.63, 0.2, 'square', 0.2, now + 0.1);
this.playToneAt(783.99, 0.15, 'sine', 0.25, now + 0.16); // G5 }
} playWarning() {
const ctx = this.getAudioContext();
// Error sound - descending tones const now = ctx.currentTime;
playError() { this.playToneAt(440.00, 0.1, 'triangle', 0.2, now);
const ctx = this.getAudioContext(); this.playToneAt(493.88, 0.1, 'triangle', 0.2, now + 0.12);
const now = ctx.currentTime; }
playInfo() {
// First tone this.playTone(523.25, 0.15, 'sine', 0.15);
this.playToneAt(392.00, 0.1, 'square', 0.15, now); // G4 }
// Second tone private playToneAt(frequency: number, duration: number, type: OscillatorType, volume: number, startTime: number) {
this.playToneAt(329.63, 0.2, 'square', 0.2, now + 0.1); // E4 try {
} const ctx = this.getAudioContext();
const oscillator = ctx.createOscillator();
// Warning sound - alternating tones const gainNode = ctx.createGain();
playWarning() { oscillator.connect(gainNode);
const ctx = this.getAudioContext(); gainNode.connect(ctx.destination);
const now = ctx.currentTime; oscillator.frequency.value = frequency;
oscillator.type = type;
// First tone gainNode.gain.setValueAtTime(volume, startTime);
this.playToneAt(440.00, 0.1, 'triangle', 0.2, now); // A4 gainNode.gain.exponentialRampToValueAtTime(0.01, startTime + duration);
// Second tone oscillator.start(startTime);
this.playToneAt(493.88, 0.1, 'triangle', 0.2, now + 0.12); // B4 oscillator.stop(startTime + duration);
} }
catch (error) {
// Info sound - single soft tone console.error('Error playing audio:', error);
playInfo() { }
this.playTone(523.25, 0.15, 'sine', 0.15); // C5
}
// Helper method to play tone at specific time
private playToneAt(frequency: number, duration: number, type: OscillatorType, volume: number, startTime: number) {
try {
const ctx = this.getAudioContext();
const oscillator = ctx.createOscillator();
const gainNode = ctx.createGain();
oscillator.connect(gainNode);
gainNode.connect(ctx.destination);
oscillator.frequency.value = frequency;
oscillator.type = type;
gainNode.gain.setValueAtTime(volume, startTime);
gainNode.gain.exponentialRampToValueAtTime(0.01, startTime + duration);
oscillator.start(startTime);
oscillator.stop(startTime + duration);
} catch (error) {
console.error('Error playing audio:', error);
} }
}
} }
// Export singleton instance
export const audioManager = new AudioManager(); export const audioManager = new AudioManager();
// Helper functions for easy use
export const playSuccessSound = () => audioManager.playSuccess(); export const playSuccessSound = () => audioManager.playSuccess();
export const playErrorSound = () => audioManager.playError(); export const playErrorSound = () => audioManager.playError();
export const playWarningSound = () => audioManager.playWarning(); export const playWarningSound = () => audioManager.playWarning();
+160 -215
View File
@@ -1,237 +1,182 @@
/**
* Fetch State Manager
* Manages resumable fetch state for large accounts
*/
import type { TwitterResponse, TimelineEntry, AccountInfo } from "@/types/api"; import type { TwitterResponse, TimelineEntry, AccountInfo } from "@/types/api";
const FETCH_STATE_KEY = "twitter_fetch_state"; const FETCH_STATE_KEY = "twitter_fetch_state";
const CURSOR_STATE_KEY = "twitter_cursor_state"; // Lightweight cursor-only storage const CURSOR_STATE_KEY = "twitter_cursor_state";
export interface FetchState { export interface FetchState {
username: string; username: string;
cursor: string; cursor: string;
timeline: TimelineEntry[]; timeline: TimelineEntry[];
accountInfo: AccountInfo | null; accountInfo: AccountInfo | null;
totalFetched: number; totalFetched: number;
completed: boolean; completed: boolean;
lastUpdated: number; lastUpdated: number;
authToken: string; // Encrypted/hashed for security authToken: string;
mediaType: string; mediaType: string;
retweets: boolean; retweets: boolean;
timelineType: string; timelineType: string;
} }
export function saveFetchState(state: Partial<FetchState> & {
/** username: string;
* Save current fetch state for resume capability }): void {
*/ try {
export function saveFetchState(state: Partial<FetchState> & { username: string }): void { const existing = getFetchState(state.username);
try { const updated: FetchState = {
const existing = getFetchState(state.username); username: state.username,
const updated: FetchState = { cursor: state.cursor || "",
username: state.username, timeline: state.timeline || existing?.timeline || [],
cursor: state.cursor || "", accountInfo: state.accountInfo || existing?.accountInfo || null,
timeline: state.timeline || existing?.timeline || [], totalFetched: state.totalFetched ?? existing?.totalFetched ?? 0,
accountInfo: state.accountInfo || existing?.accountInfo || null, completed: state.completed ?? false,
totalFetched: state.totalFetched ?? existing?.totalFetched ?? 0, lastUpdated: Date.now(),
completed: state.completed ?? false, authToken: state.authToken || existing?.authToken || "",
lastUpdated: Date.now(), mediaType: state.mediaType || existing?.mediaType || "all",
authToken: state.authToken || existing?.authToken || "", retweets: state.retweets ?? existing?.retweets ?? false,
mediaType: state.mediaType || existing?.mediaType || "all", timelineType: state.timelineType || existing?.timelineType || "timeline",
retweets: state.retweets ?? existing?.retweets ?? false, };
timelineType: state.timelineType || existing?.timelineType || "timeline", const allStates = getAllFetchStates();
}; allStates[state.username.toLowerCase()] = updated;
localStorage.setItem(FETCH_STATE_KEY, JSON.stringify(allStates));
// Get all states }
const allStates = getAllFetchStates(); catch (error) {
allStates[state.username.toLowerCase()] = updated; console.error("Failed to save fetch state:", error);
}
localStorage.setItem(FETCH_STATE_KEY, JSON.stringify(allStates));
} catch (error) {
console.error("Failed to save fetch state:", error);
}
} }
/**
* Get fetch state for a specific username
*/
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 allStates[username.toLowerCase()] || null;
} catch (error) { }
console.error("Failed to get fetch state:", error); catch (error) {
return null; console.error("Failed to get fetch state:", error);
} return null;
}
} }
/**
* Get all fetch states
*/
export function getAllFetchStates(): Record<string, FetchState> { 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); return JSON.parse(stored);
}
} }
} catch (error) { catch (error) {
console.error("Failed to parse fetch states:", error); console.error("Failed to parse fetch states:", error);
} }
return {}; return {};
} }
/**
* Check if there's a resumable fetch for username
*/
export function hasResumableFetch(username: string): boolean { export function hasResumableFetch(username: string): boolean {
const state = getFetchState(username); const state = getFetchState(username);
if (!state) return false; if (!state)
return false;
// Has cursor and not completed return !!state.cursor && !state.completed && state.timeline.length > 0;
return !!state.cursor && !state.completed && state.timeline.length > 0;
} }
/**
* Get resumable fetch info for display
*/
export function getResumableInfo(username: string): { export function getResumableInfo(username: string): {
canResume: boolean; canResume: boolean;
mediaCount: number; mediaCount: number;
lastUpdated: Date | null; lastUpdated: Date | null;
} { } {
const state = getFetchState(username); const state = getFetchState(username);
if (!state || state.completed || !state.cursor) { if (!state || state.completed || !state.cursor) {
return { canResume: false, mediaCount: 0, lastUpdated: null }; return { canResume: false, mediaCount: 0, lastUpdated: null };
}
return {
canResume: true,
mediaCount: state.timeline.length,
lastUpdated: new Date(state.lastUpdated),
};
}
/**
* Clear fetch state for username
*/
export function clearFetchState(username: string): void {
try {
const allStates = getAllFetchStates();
delete allStates[username.toLowerCase()];
localStorage.setItem(FETCH_STATE_KEY, JSON.stringify(allStates));
} catch (error) {
console.error("Failed to clear fetch state:", error);
}
}
/**
* Clear all incomplete fetch states (cleanup)
*/
export function clearAllIncompleteFetchStates(): void {
try {
const allStates = getAllFetchStates();
const completed: Record<string, FetchState> = {};
for (const [key, state] of Object.entries(allStates)) {
if (state.completed) {
completed[key] = state;
}
} }
return {
localStorage.setItem(FETCH_STATE_KEY, JSON.stringify(completed)); canResume: true,
} catch (error) { mediaCount: state.timeline.length,
console.error("Failed to clear fetch states:", error); lastUpdated: new Date(state.lastUpdated),
}
}
/**
* Convert fetch state to TwitterResponse format
*/
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,
};
}
/**
* Save cursor only (lightweight, can be called every batch)
*/
export function saveCursor(username: string, cursor: string): void {
try {
const allCursors = getAllCursors();
allCursors[username.toLowerCase()] = {
cursor,
lastUpdated: Date.now(),
}; };
localStorage.setItem(CURSOR_STATE_KEY, JSON.stringify(allCursors));
} catch (error) {
console.error("Failed to save cursor:", error);
}
} }
export function clearFetchState(username: string): void {
/** try {
* Get cursor for username from localStorage (lightweight, synchronous) const allStates = getAllFetchStates();
*/ delete allStates[username.toLowerCase()];
export function getCursor(username: string): string | null { localStorage.setItem(FETCH_STATE_KEY, JSON.stringify(allStates));
try { }
const allCursors = getAllCursors(); catch (error) {
return allCursors[username.toLowerCase()]?.cursor || null; console.error("Failed to clear fetch state:", error);
} catch (error) {
console.error("Failed to get cursor:", error);
return null;
}
}
/**
* Get all cursors
*/
function getAllCursors(): Record<string, { cursor: string; lastUpdated: number }> {
try {
const stored = localStorage.getItem(CURSOR_STATE_KEY);
if (stored) {
return JSON.parse(stored);
} }
} catch (error) {
console.error("Failed to parse cursors:", error);
}
return {};
} }
export function clearAllIncompleteFetchStates(): void {
/** try {
* Clear cursor for username const allStates = getAllFetchStates();
*/ const completed: Record<string, FetchState> = {};
for (const [key, state] of Object.entries(allStates)) {
if (state.completed) {
completed[key] = state;
}
}
localStorage.setItem(FETCH_STATE_KEY, JSON.stringify(completed));
}
catch (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 {
try {
const allCursors = getAllCursors();
allCursors[username.toLowerCase()] = {
cursor,
lastUpdated: Date.now(),
};
localStorage.setItem(CURSOR_STATE_KEY, JSON.stringify(allCursors));
}
catch (error) {
console.error("Failed to save cursor:", error);
}
}
export function getCursor(username: string): string | null {
try {
const allCursors = getAllCursors();
return allCursors[username.toLowerCase()]?.cursor || null;
}
catch (error) {
console.error("Failed to get cursor:", error);
return null;
}
}
function getAllCursors(): Record<string, {
cursor: string;
lastUpdated: number;
}> {
try {
const stored = localStorage.getItem(CURSOR_STATE_KEY);
if (stored) {
return JSON.parse(stored);
}
}
catch (error) {
console.error("Failed to parse cursors:", error);
}
return {};
}
export function clearCursor(username: string): void { export function clearCursor(username: string): void {
try { try {
const allCursors = getAllCursors(); const allCursors = getAllCursors();
delete allCursors[username.toLowerCase()]; delete allCursors[username.toLowerCase()];
localStorage.setItem(CURSOR_STATE_KEY, JSON.stringify(allCursors)); localStorage.setItem(CURSOR_STATE_KEY, JSON.stringify(allCursors));
} catch (error) { }
console.error("Failed to clear cursor:", error); catch (error) {
} console.error("Failed to clear cursor:", error);
}
} }
export function mergeTimelines(existing: TimelineEntry[], newEntries: TimelineEntry[]): TimelineEntry[] {
/** const seenIds = new Set(existing.map((e) => e.tweet_id));
* Merge new timeline entries with existing (deduplicate by tweet_id) const unique = newEntries.filter((e) => !seenIds.has(e.tweet_id));
*/ return [...existing, ...unique];
export function mergeTimelines(
existing: TimelineEntry[],
newEntries: TimelineEntry[]
): TimelineEntry[] {
const seenIds = new Set(existing.map((e) => e.tweet_id));
const unique = newEntries.filter((e) => !seenIds.has(e.tweet_id));
return [...existing, ...unique];
} }
+46 -59
View File
@@ -1,66 +1,53 @@
export type LogLevel = "info" | "success" | "warning" | "error" | "debug"; export type LogLevel = "info" | "success" | "warning" | "error" | "debug";
export interface LogEntry { export interface LogEntry {
timestamp: Date; timestamp: Date;
level: LogLevel; level: LogLevel;
message: string; message: string;
} }
class Logger { class Logger {
private logs: LogEntry[] = []; private logs: LogEntry[] = [];
private maxLogs = 500; private maxLogs = 500;
private listeners: Set<() => void> = new Set(); private listeners: Set<() => void> = new Set();
private addLog(level: LogLevel, message: string) {
private addLog(level: LogLevel, message: string) { const entry: LogEntry = {
const entry: LogEntry = { timestamp: new Date(),
timestamp: new Date(), level,
level, message: message.toLowerCase(),
message: message.toLowerCase(), };
}; this.logs.push(entry);
this.logs.push(entry); if (this.logs.length > this.maxLogs) {
if (this.logs.length > this.maxLogs) { this.logs.shift();
this.logs.shift(); }
this.notifyListeners();
}
info(message: string) {
this.addLog("info", message);
}
success(message: string) {
this.addLog("success", message);
}
warning(message: string) {
this.addLog("warning", message);
}
error(message: string) {
this.addLog("error", message);
}
debug(message: string) {
this.addLog("debug", message);
}
getLogs(): LogEntry[] {
return [...this.logs];
}
clear() {
this.logs = [];
this.notifyListeners();
}
subscribe(listener: () => void) {
this.listeners.add(listener);
return () => this.listeners.delete(listener);
}
private notifyListeners() {
this.listeners.forEach((listener) => listener());
} }
this.notifyListeners();
}
info(message: string) {
this.addLog("info", message);
}
success(message: string) {
this.addLog("success", message);
}
warning(message: string) {
this.addLog("warning", message);
}
error(message: string) {
this.addLog("error", message);
}
debug(message: string) {
this.addLog("debug", message);
}
getLogs(): LogEntry[] {
return [...this.logs];
}
clear() {
this.logs = [];
this.notifyListeners();
}
subscribe(listener: () => void) {
this.listeners.add(listener);
return () => this.listeners.delete(listener);
}
private notifyListeners() {
this.listeners.forEach((listener) => listener());
}
} }
export const logger = new Logger(); export const logger = new Logger();
+50 -52
View File
@@ -1,59 +1,57 @@
/**
* Format a date to relative time string with max 2 units
* e.g., "23 hours 32 minutes ago", "1 day 14 hours ago"
*/
export function formatRelativeTime(date: Date | string | number): string { export function formatRelativeTime(date: Date | string | number): string {
const now = new Date(); const now = new Date();
const target = new Date(date); const target = new Date(date);
const diffMs = now.getTime() - target.getTime(); const diffMs = now.getTime() - target.getTime();
if (diffMs < 0)
if (diffMs < 0) return "just now"; return "just now";
const seconds = Math.floor(diffMs / 1000);
const seconds = Math.floor(diffMs / 1000); const minutes = Math.floor(seconds / 60);
const minutes = Math.floor(seconds / 60); const hours = Math.floor(minutes / 60);
const hours = Math.floor(minutes / 60); const days = Math.floor(hours / 24);
const days = Math.floor(hours / 24); const weeks = Math.floor(days / 7);
const weeks = Math.floor(days / 7); const months = Math.floor(days / 30);
const months = Math.floor(days / 30); const years = Math.floor(days / 365);
const years = Math.floor(days / 365); const parts: string[] = [];
if (years > 0) {
const parts: string[] = []; parts.push(`${years} ${years === 1 ? "year" : "years"}`);
const remainingMonths = Math.floor((days % 365) / 30);
if (years > 0) { if (remainingMonths > 0) {
parts.push(`${years} ${years === 1 ? "year" : "years"}`); parts.push(`${remainingMonths} ${remainingMonths === 1 ? "month" : "months"}`);
const remainingMonths = Math.floor((days % 365) / 30); }
if (remainingMonths > 0) {
parts.push(`${remainingMonths} ${remainingMonths === 1 ? "month" : "months"}`);
} }
} else if (months > 0) { else if (months > 0) {
parts.push(`${months} ${months === 1 ? "month" : "months"}`); parts.push(`${months} ${months === 1 ? "month" : "months"}`);
const remainingDays = days % 30; const remainingDays = days % 30;
if (remainingDays > 0) { if (remainingDays > 0) {
parts.push(`${remainingDays} ${remainingDays === 1 ? "day" : "days"}`); parts.push(`${remainingDays} ${remainingDays === 1 ? "day" : "days"}`);
}
} }
} else if (weeks > 0) { else if (weeks > 0) {
parts.push(`${weeks} ${weeks === 1 ? "week" : "weeks"}`); parts.push(`${weeks} ${weeks === 1 ? "week" : "weeks"}`);
const remainingDays = days % 7; const remainingDays = days % 7;
if (remainingDays > 0) { if (remainingDays > 0) {
parts.push(`${remainingDays} ${remainingDays === 1 ? "day" : "days"}`); parts.push(`${remainingDays} ${remainingDays === 1 ? "day" : "days"}`);
}
} }
} else if (days > 0) { else if (days > 0) {
parts.push(`${days} ${days === 1 ? "day" : "days"}`); parts.push(`${days} ${days === 1 ? "day" : "days"}`);
const remainingHours = hours % 24; const remainingHours = hours % 24;
if (remainingHours > 0) { if (remainingHours > 0) {
parts.push(`${remainingHours} ${remainingHours === 1 ? "hour" : "hours"}`); parts.push(`${remainingHours} ${remainingHours === 1 ? "hour" : "hours"}`);
}
} }
} else if (hours > 0) { else if (hours > 0) {
parts.push(`${hours} ${hours === 1 ? "hour" : "hours"}`); parts.push(`${hours} ${hours === 1 ? "hour" : "hours"}`);
const remainingMinutes = minutes % 60; const remainingMinutes = minutes % 60;
if (remainingMinutes > 0) { if (remainingMinutes > 0) {
parts.push(`${remainingMinutes} ${remainingMinutes === 1 ? "minute" : "minutes"}`); parts.push(`${remainingMinutes} ${remainingMinutes === 1 ? "minute" : "minutes"}`);
}
} }
} else if (minutes > 0) { else if (minutes > 0) {
parts.push(`${minutes} ${minutes === 1 ? "minute" : "minutes"}`); parts.push(`${minutes} ${minutes === 1 ? "minute" : "minutes"}`);
} else { }
return "just now"; else {
} return "just now";
}
return "Released " + parts.slice(0, 2).join(" ") + " ago"; return "Released " + parts.slice(0, 2).join(" ") + " ago";
} }
+114 -112
View File
@@ -1,132 +1,134 @@
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 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 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 MediaType = "all" | "image" | "video" | "gif" | "text";
export interface Settings { export interface Settings {
downloadPath: string; downloadPath: string;
theme: string; theme: string;
themeMode: "auto" | "light" | "dark"; themeMode: "auto" | "light" | "dark";
fontFamily: FontFamily; fontFamily: FontFamily;
sfxEnabled: boolean; sfxEnabled: boolean;
gifQuality: GifQuality; gifQuality: GifQuality;
gifResolution: GifResolution; gifResolution: GifResolution;
proxy: string; // Proxy URL (e.g., http://proxy:port or socks5://proxy:port). Empty to use system proxy or no proxy. proxy: string;
fetchTimeout: number; // Fetch timeout in seconds. Default: 60 seconds. fetchTimeout: number;
fetchMode: FetchMode;
mediaType: MediaType;
includeRetweets: boolean;
} }
export const DEFAULT_SETTINGS: Settings = { export const DEFAULT_SETTINGS: Settings = {
downloadPath: "", downloadPath: "",
theme: "yellow", theme: "yellow",
themeMode: "auto", themeMode: "auto",
fontFamily: "google-sans", fontFamily: "google-sans",
sfxEnabled: true, sfxEnabled: true,
gifQuality: "fast", gifQuality: "fast",
gifResolution: "original", gifResolution: "original",
proxy: "", proxy: "",
fetchTimeout: 60, // Default: 60 seconds fetchTimeout: 60,
fetchMode: "batch",
mediaType: "all",
includeRetweets: false,
}; };
export const FONT_OPTIONS: {
export const FONT_OPTIONS: { value: FontFamily; label: string; fontFamily: string }[] = [ value: FontFamily;
{ value: "dm-sans", label: "DM Sans", fontFamily: '"DM Sans", system-ui, sans-serif' }, label: string;
{ value: "figtree", label: "Figtree", fontFamily: '"Figtree", system-ui, sans-serif' }, fontFamily: string;
{ value: "geist-sans", label: "Geist Sans", fontFamily: '"Geist", system-ui, sans-serif' }, }[] = [
{ value: "google-sans", label: "Google Sans Flex", fontFamily: '"Google Sans Flex", system-ui, sans-serif' }, { value: "dm-sans", label: "DM Sans", fontFamily: '"DM Sans", system-ui, sans-serif' },
{ value: "inter", label: "Inter", fontFamily: '"Inter", system-ui, sans-serif' }, { value: "figtree", label: "Figtree", fontFamily: '"Figtree", system-ui, sans-serif' },
{ value: "jetbrains-mono", label: "JetBrains Mono", fontFamily: '"JetBrains Mono", ui-monospace, monospace' }, { value: "geist-sans", label: "Geist Sans", fontFamily: '"Geist", system-ui, sans-serif' },
{ value: "manrope", label: "Manrope", fontFamily: '"Manrope", system-ui, sans-serif' }, { value: "google-sans", label: "Google Sans Flex", fontFamily: '"Google Sans Flex", system-ui, sans-serif' },
{ value: "noto-sans", label: "Noto Sans", fontFamily: '"Noto Sans", system-ui, sans-serif' }, { value: "inter", label: "Inter", fontFamily: '"Inter", system-ui, sans-serif' },
{ value: "nunito-sans", label: "Nunito Sans", fontFamily: '"Nunito Sans", system-ui, sans-serif' }, { value: "jetbrains-mono", label: "JetBrains Mono", fontFamily: '"JetBrains Mono", ui-monospace, monospace' },
{ value: "outfit", label: "Outfit", fontFamily: '"Outfit", system-ui, sans-serif' }, { value: "manrope", label: "Manrope", fontFamily: '"Manrope", system-ui, sans-serif' },
{ value: "plus-jakarta-sans", label: "Plus Jakarta Sans", fontFamily: '"Plus Jakarta Sans", system-ui, sans-serif' }, { value: "noto-sans", label: "Noto Sans", fontFamily: '"Noto Sans", system-ui, sans-serif' },
{ value: "poppins", label: "Poppins", fontFamily: '"Poppins", system-ui, sans-serif' }, { value: "nunito-sans", label: "Nunito Sans", fontFamily: '"Nunito Sans", system-ui, sans-serif' },
{ value: "public-sans", label: "Public Sans", fontFamily: '"Public Sans", system-ui, sans-serif' }, { value: "outfit", label: "Outfit", fontFamily: '"Outfit", system-ui, sans-serif' },
{ value: "raleway", label: "Raleway", fontFamily: '"Raleway", system-ui, sans-serif' }, { value: "plus-jakarta-sans", label: "Plus Jakarta Sans", fontFamily: '"Plus Jakarta Sans", system-ui, sans-serif' },
{ value: "roboto", label: "Roboto", fontFamily: '"Roboto", system-ui, sans-serif' }, { value: "poppins", label: "Poppins", fontFamily: '"Poppins", system-ui, sans-serif' },
{ value: "space-grotesk", label: "Space Grotesk", fontFamily: '"Space Grotesk", 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 { export function applyFont(fontFamily: FontFamily): void {
const font = FONT_OPTIONS.find(f => f.value === fontFamily); const font = FONT_OPTIONS.find(f => f.value === 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;
} }
} }
async function fetchDefaultPath(): Promise<string> { async function fetchDefaultPath(): Promise<string> {
try { try {
const data = await GetDefaults(); const data = await GetDefaults();
return data.downloadPath || ""; return data.downloadPath || "";
} catch (error) { }
console.error("Failed to fetch default path:", error); catch (error) {
return ""; console.error("Failed to fetch default path:", error);
} return "";
}
} }
const SETTINGS_KEY = "twitter-media-downloader-settings"; const SETTINGS_KEY = "twitter-media-downloader-settings";
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); const parsed = JSON.parse(stored);
return { ...DEFAULT_SETTINGS, ...parsed }; return { ...DEFAULT_SETTINGS, ...parsed };
}
} }
} catch (error) { catch (error) {
console.error("Failed to load settings:", error); console.error("Failed to load settings:", error);
} }
return DEFAULT_SETTINGS; return DEFAULT_SETTINGS;
} }
export async function getSettingsWithDefaults(): Promise<Settings> { export async function getSettingsWithDefaults(): Promise<Settings> {
const settings = getSettings(); const settings = getSettings();
if (!settings.downloadPath) {
// If downloadPath is empty, fetch from backend settings.downloadPath = await fetchDefaultPath();
if (!settings.downloadPath) { }
settings.downloadPath = await fetchDefaultPath(); return settings;
} }
export function saveSettings(settings: Settings): void {
return settings; try {
} localStorage.setItem(SETTINGS_KEY, JSON.stringify(settings));
}
export function saveSettings(settings: Settings): void { catch (error) {
try { console.error("Failed to save settings:", error);
localStorage.setItem(SETTINGS_KEY, JSON.stringify(settings)); }
} catch (error) { }
console.error("Failed to save settings:", error); export function updateSettings(partial: Partial<Settings>): Settings {
} const current = getSettings();
} const updated = { ...current, ...partial };
saveSettings(updated);
export function updateSettings(partial: Partial<Settings>): Settings { return updated;
const current = getSettings(); }
const updated = { ...current, ...partial }; export async function resetToDefaultSettings(): Promise<Settings> {
saveSettings(updated); const defaultPath = await fetchDefaultPath();
return updated; const defaultSettings = {
} ...DEFAULT_SETTINGS,
downloadPath: defaultPath,
export async function resetToDefaultSettings(): Promise<Settings> { };
const defaultPath = await fetchDefaultPath(); saveSettings(defaultSettings);
const defaultSettings = { return defaultSettings;
...DEFAULT_SETTINGS, }
downloadPath: defaultPath, export function applyThemeMode(mode: "auto" | "light" | "dark"): void {
}; if (mode === "auto") {
saveSettings(defaultSettings); const prefersDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
return defaultSettings; if (prefersDark) {
} document.documentElement.classList.add("dark");
}
export function applyThemeMode(mode: "auto" | "light" | "dark"): void { else {
if (mode === "auto") { document.documentElement.classList.remove("dark");
const prefersDark = window.matchMedia("(prefers-color-scheme: dark)").matches; }
if (prefersDark) { }
document.documentElement.classList.add("dark"); else if (mode === "dark") {
} else { document.documentElement.classList.add("dark");
document.documentElement.classList.remove("dark"); }
else {
document.documentElement.classList.remove("dark");
} }
} else if (mode === "dark") {
document.documentElement.classList.add("dark");
} else {
document.documentElement.classList.remove("dark");
}
} }
+267 -282
View File
@@ -1,290 +1,275 @@
export interface Theme { export interface Theme {
name: string; name: string;
label: string; label: string;
cssVars: {
light: Record<string, string>;
dark: Record<string, string>;
};
}
// Base colors yang sama untuk semua tema (kecuali primary dan primary-foreground)
const baseLightColors: Record<string, string> = {
background: "oklch(1 0 0)",
foreground: "oklch(0.145 0 0)",
card: "oklch(1 0 0)",
"card-foreground": "oklch(0.145 0 0)",
popover: "oklch(1 0 0)",
"popover-foreground": "oklch(0.145 0 0)",
secondary: "oklch(0.967 0.001 286.375)",
"secondary-foreground": "oklch(0.21 0.006 285.885)",
muted: "oklch(0.97 0 0)",
"muted-foreground": "oklch(0.556 0 0)",
accent: "oklch(0.97 0 0)",
"accent-foreground": "oklch(0.205 0 0)",
destructive: "oklch(0.58 0.22 27)",
border: "oklch(0.922 0 0)",
input: "oklch(0.922 0 0)",
ring: "oklch(0.708 0 0)",
};
const baseDarkColors: Record<string, string> = {
background: "oklch(0.145 0 0)",
foreground: "oklch(0.985 0 0)",
card: "oklch(0.205 0 0)",
"card-foreground": "oklch(0.985 0 0)",
popover: "oklch(0.205 0 0)",
"popover-foreground": "oklch(0.985 0 0)",
secondary: "oklch(0.274 0.006 286.033)",
"secondary-foreground": "oklch(0.985 0 0)",
muted: "oklch(0.269 0 0)",
"muted-foreground": "oklch(0.708 0 0)",
accent: "oklch(0.371 0 0)",
"accent-foreground": "oklch(0.985 0 0)",
destructive: "oklch(0.704 0.191 22.216)",
border: "oklch(1 0 0 / 10%)",
input: "oklch(1 0 0 / 15%)",
ring: "oklch(0.556 0 0)",
};
// Primary colors yang berbeda untuk setiap tema
interface PrimaryColors {
light: {
primary: string;
"primary-foreground": string;
};
dark: {
primary: string;
"primary-foreground": string;
};
}
const primaryColors: Record<string, PrimaryColors> = {
amber: {
light: {
primary: "oklch(0.67 0.16 58)",
"primary-foreground": "oklch(0.99 0.02 95)",
},
dark: {
primary: "oklch(0.77 0.16 70)",
"primary-foreground": "oklch(0.28 0.07 46)",
},
},
blue: {
light: {
primary: "oklch(0.488 0.243 264.376)",
"primary-foreground": "oklch(0.97 0.014 254.604)",
},
dark: {
primary: "oklch(0.42 0.18 266)",
"primary-foreground": "oklch(0.97 0.014 254.604)",
},
},
cyan: {
light: {
primary: "oklch(0.61 0.11 222)",
"primary-foreground": "oklch(0.98 0.02 201)",
},
dark: {
primary: "oklch(0.71 0.13 215)",
"primary-foreground": "oklch(0.30 0.05 230)",
},
},
emerald: {
light: {
primary: "oklch(0.60 0.13 163)",
"primary-foreground": "oklch(0.98 0.02 166)",
},
dark: {
primary: "oklch(0.70 0.15 162)",
"primary-foreground": "oklch(0.26 0.05 173)",
},
},
fuchsia: {
light: {
primary: "oklch(0.59 0.26 323)",
"primary-foreground": "oklch(0.98 0.02 320)",
},
dark: {
primary: "oklch(0.67 0.26 322)",
"primary-foreground": "oklch(0.98 0.02 320)",
},
},
green: {
light: {
primary: "oklch(0.648 0.2 131.684)",
"primary-foreground": "oklch(0.986 0.031 120.757)",
},
dark: {
primary: "oklch(0.648 0.2 131.684)",
"primary-foreground": "oklch(0.986 0.031 120.757)",
},
},
indigo: {
light: {
primary: "oklch(0.51 0.23 277)",
"primary-foreground": "oklch(0.96 0.02 272)",
},
dark: {
primary: "oklch(0.59 0.20 277)",
"primary-foreground": "oklch(0.96 0.02 272)",
},
},
lime: {
light: {
primary: "oklch(0.65 0.18 132)",
"primary-foreground": "oklch(0.99 0.03 121)",
},
dark: {
primary: "oklch(0.77 0.20 131)",
"primary-foreground": "oklch(0.27 0.07 132)",
},
},
neutral: {
light: {
primary: "oklch(0.205 0 0)",
"primary-foreground": "oklch(0.985 0 0)",
},
dark: {
primary: "oklch(0.922 0 0)",
"primary-foreground": "oklch(0.205 0 0)",
},
},
orange: {
light: {
primary: "oklch(0.646 0.222 41.116)",
"primary-foreground": "oklch(0.98 0.016 73.684)",
},
dark: {
primary: "oklch(0.705 0.213 47.604)",
"primary-foreground": "oklch(0.98 0.016 73.684)",
},
},
pink: {
light: {
primary: "oklch(0.59 0.22 1)",
"primary-foreground": "oklch(0.97 0.01 343)",
},
dark: {
primary: "oklch(0.66 0.21 354)",
"primary-foreground": "oklch(0.97 0.01 343)",
},
},
purple: {
light: {
primary: "oklch(0.56 0.25 302)",
"primary-foreground": "oklch(0.98 0.01 308)",
},
dark: {
primary: "oklch(0.63 0.23 304)",
"primary-foreground": "oklch(0.98 0.01 308)",
},
},
red: {
light: {
primary: "oklch(0.577 0.245 27.325)",
"primary-foreground": "oklch(0.971 0.013 17.38)",
},
dark: {
primary: "oklch(0.637 0.237 25.331)",
"primary-foreground": "oklch(0.971 0.013 17.38)",
},
},
rose: {
light: {
primary: "oklch(0.586 0.253 17.585)",
"primary-foreground": "oklch(0.969 0.015 12.422)",
},
dark: {
primary: "oklch(0.645 0.246 16.439)",
"primary-foreground": "oklch(0.969 0.015 12.422)",
},
},
sky: {
light: {
primary: "oklch(0.59 0.14 242)",
"primary-foreground": "oklch(0.98 0.01 237)",
},
dark: {
primary: "oklch(0.68 0.15 237)",
"primary-foreground": "oklch(0.29 0.06 243)",
},
},
teal: {
light: {
primary: "oklch(0.60 0.10 185)",
"primary-foreground": "oklch(0.98 0.01 181)",
},
dark: {
primary: "oklch(0.70 0.12 183)",
"primary-foreground": "oklch(0.28 0.04 193)",
},
},
violet: {
light: {
primary: "oklch(0.541 0.281 293.009)",
"primary-foreground": "oklch(0.969 0.016 293.756)",
},
dark: {
primary: "oklch(0.606 0.25 292.717)",
"primary-foreground": "oklch(0.969 0.016 293.756)",
},
},
yellow: {
light: {
primary: "oklch(0.852 0.199 91.936)",
"primary-foreground": "oklch(0.421 0.095 57.708)",
},
dark: {
primary: "oklch(0.795 0.184 86.047)",
"primary-foreground": "oklch(0.421 0.095 57.708)",
},
},
};
// Helper function untuk menggabungkan base colors dengan primary colors
function createTheme(
name: string,
label: string,
primary: PrimaryColors
): Theme {
return {
name,
label,
cssVars: { cssVars: {
light: { ...baseLightColors, ...primary.light }, light: Record<string, string>;
dark: { ...baseDarkColors, ...primary.dark }, dark: Record<string, string>;
};
}
const baseLightColors: Record<string, string> = {
background: "oklch(1 0 0)",
foreground: "oklch(0.145 0 0)",
card: "oklch(1 0 0)",
"card-foreground": "oklch(0.145 0 0)",
popover: "oklch(1 0 0)",
"popover-foreground": "oklch(0.145 0 0)",
secondary: "oklch(0.967 0.001 286.375)",
"secondary-foreground": "oklch(0.21 0.006 285.885)",
muted: "oklch(0.97 0 0)",
"muted-foreground": "oklch(0.556 0 0)",
accent: "oklch(0.97 0 0)",
"accent-foreground": "oklch(0.205 0 0)",
destructive: "oklch(0.58 0.22 27)",
border: "oklch(0.922 0 0)",
input: "oklch(0.922 0 0)",
ring: "oklch(0.708 0 0)",
};
const baseDarkColors: Record<string, string> = {
background: "oklch(0.145 0 0)",
foreground: "oklch(0.985 0 0)",
card: "oklch(0.205 0 0)",
"card-foreground": "oklch(0.985 0 0)",
popover: "oklch(0.205 0 0)",
"popover-foreground": "oklch(0.985 0 0)",
secondary: "oklch(0.274 0.006 286.033)",
"secondary-foreground": "oklch(0.985 0 0)",
muted: "oklch(0.269 0 0)",
"muted-foreground": "oklch(0.708 0 0)",
accent: "oklch(0.371 0 0)",
"accent-foreground": "oklch(0.985 0 0)",
destructive: "oklch(0.704 0.191 22.216)",
border: "oklch(1 0 0 / 10%)",
input: "oklch(1 0 0 / 15%)",
ring: "oklch(0.556 0 0)",
};
interface PrimaryColors {
light: {
primary: string;
"primary-foreground": string;
};
dark: {
primary: string;
"primary-foreground": string;
};
}
const primaryColors: Record<string, PrimaryColors> = {
amber: {
light: {
primary: "oklch(0.67 0.16 58)",
"primary-foreground": "oklch(0.99 0.02 95)",
},
dark: {
primary: "oklch(0.77 0.16 70)",
"primary-foreground": "oklch(0.28 0.07 46)",
},
}, },
}; blue: {
light: {
primary: "oklch(0.488 0.243 264.376)",
"primary-foreground": "oklch(0.97 0.014 254.604)",
},
dark: {
primary: "oklch(0.42 0.18 266)",
"primary-foreground": "oklch(0.97 0.014 254.604)",
},
},
cyan: {
light: {
primary: "oklch(0.61 0.11 222)",
"primary-foreground": "oklch(0.98 0.02 201)",
},
dark: {
primary: "oklch(0.71 0.13 215)",
"primary-foreground": "oklch(0.30 0.05 230)",
},
},
emerald: {
light: {
primary: "oklch(0.60 0.13 163)",
"primary-foreground": "oklch(0.98 0.02 166)",
},
dark: {
primary: "oklch(0.70 0.15 162)",
"primary-foreground": "oklch(0.26 0.05 173)",
},
},
fuchsia: {
light: {
primary: "oklch(0.59 0.26 323)",
"primary-foreground": "oklch(0.98 0.02 320)",
},
dark: {
primary: "oklch(0.67 0.26 322)",
"primary-foreground": "oklch(0.98 0.02 320)",
},
},
green: {
light: {
primary: "oklch(0.648 0.2 131.684)",
"primary-foreground": "oklch(0.986 0.031 120.757)",
},
dark: {
primary: "oklch(0.648 0.2 131.684)",
"primary-foreground": "oklch(0.986 0.031 120.757)",
},
},
indigo: {
light: {
primary: "oklch(0.51 0.23 277)",
"primary-foreground": "oklch(0.96 0.02 272)",
},
dark: {
primary: "oklch(0.59 0.20 277)",
"primary-foreground": "oklch(0.96 0.02 272)",
},
},
lime: {
light: {
primary: "oklch(0.65 0.18 132)",
"primary-foreground": "oklch(0.99 0.03 121)",
},
dark: {
primary: "oklch(0.77 0.20 131)",
"primary-foreground": "oklch(0.27 0.07 132)",
},
},
neutral: {
light: {
primary: "oklch(0.205 0 0)",
"primary-foreground": "oklch(0.985 0 0)",
},
dark: {
primary: "oklch(0.922 0 0)",
"primary-foreground": "oklch(0.205 0 0)",
},
},
orange: {
light: {
primary: "oklch(0.646 0.222 41.116)",
"primary-foreground": "oklch(0.98 0.016 73.684)",
},
dark: {
primary: "oklch(0.705 0.213 47.604)",
"primary-foreground": "oklch(0.98 0.016 73.684)",
},
},
pink: {
light: {
primary: "oklch(0.59 0.22 1)",
"primary-foreground": "oklch(0.97 0.01 343)",
},
dark: {
primary: "oklch(0.66 0.21 354)",
"primary-foreground": "oklch(0.97 0.01 343)",
},
},
purple: {
light: {
primary: "oklch(0.56 0.25 302)",
"primary-foreground": "oklch(0.98 0.01 308)",
},
dark: {
primary: "oklch(0.63 0.23 304)",
"primary-foreground": "oklch(0.98 0.01 308)",
},
},
red: {
light: {
primary: "oklch(0.577 0.245 27.325)",
"primary-foreground": "oklch(0.971 0.013 17.38)",
},
dark: {
primary: "oklch(0.637 0.237 25.331)",
"primary-foreground": "oklch(0.971 0.013 17.38)",
},
},
rose: {
light: {
primary: "oklch(0.586 0.253 17.585)",
"primary-foreground": "oklch(0.969 0.015 12.422)",
},
dark: {
primary: "oklch(0.645 0.246 16.439)",
"primary-foreground": "oklch(0.969 0.015 12.422)",
},
},
sky: {
light: {
primary: "oklch(0.59 0.14 242)",
"primary-foreground": "oklch(0.98 0.01 237)",
},
dark: {
primary: "oklch(0.68 0.15 237)",
"primary-foreground": "oklch(0.29 0.06 243)",
},
},
teal: {
light: {
primary: "oklch(0.60 0.10 185)",
"primary-foreground": "oklch(0.98 0.01 181)",
},
dark: {
primary: "oklch(0.70 0.12 183)",
"primary-foreground": "oklch(0.28 0.04 193)",
},
},
violet: {
light: {
primary: "oklch(0.541 0.281 293.009)",
"primary-foreground": "oklch(0.969 0.016 293.756)",
},
dark: {
primary: "oklch(0.606 0.25 292.717)",
"primary-foreground": "oklch(0.969 0.016 293.756)",
},
},
yellow: {
light: {
primary: "oklch(0.852 0.199 91.936)",
"primary-foreground": "oklch(0.421 0.095 57.708)",
},
dark: {
primary: "oklch(0.795 0.184 86.047)",
"primary-foreground": "oklch(0.421 0.095 57.708)",
},
},
};
function createTheme(name: string, label: string, primary: PrimaryColors): Theme {
return {
name,
label,
cssVars: {
light: { ...baseLightColors, ...primary.light },
dark: { ...baseDarkColors, ...primary.dark },
},
};
} }
export const themes: Theme[] = [ export const themes: Theme[] = [
createTheme("amber", "Amber", primaryColors.amber), createTheme("amber", "Amber", primaryColors.amber),
createTheme("blue", "Blue", primaryColors.blue), createTheme("blue", "Blue", primaryColors.blue),
createTheme("cyan", "Cyan", primaryColors.cyan), createTheme("cyan", "Cyan", primaryColors.cyan),
createTheme("emerald", "Emerald", primaryColors.emerald), createTheme("emerald", "Emerald", primaryColors.emerald),
createTheme("fuchsia", "Fuchsia", primaryColors.fuchsia), createTheme("fuchsia", "Fuchsia", primaryColors.fuchsia),
createTheme("green", "Green", primaryColors.green), createTheme("green", "Green", primaryColors.green),
createTheme("indigo", "Indigo", primaryColors.indigo), createTheme("indigo", "Indigo", primaryColors.indigo),
createTheme("lime", "Lime", primaryColors.lime), createTheme("lime", "Lime", primaryColors.lime),
createTheme("neutral", "Neutral", primaryColors.neutral), createTheme("neutral", "Neutral", primaryColors.neutral),
createTheme("orange", "Orange", primaryColors.orange), createTheme("orange", "Orange", primaryColors.orange),
createTheme("pink", "Pink", primaryColors.pink), createTheme("pink", "Pink", primaryColors.pink),
createTheme("purple", "Purple", primaryColors.purple), createTheme("purple", "Purple", primaryColors.purple),
createTheme("red", "Red", primaryColors.red), createTheme("red", "Red", primaryColors.red),
createTheme("rose", "Rose", primaryColors.rose), createTheme("rose", "Rose", primaryColors.rose),
createTheme("sky", "Sky", primaryColors.sky), createTheme("sky", "Sky", primaryColors.sky),
createTheme("teal", "Teal", primaryColors.teal), createTheme("teal", "Teal", primaryColors.teal),
createTheme("violet", "Violet", primaryColors.violet), createTheme("violet", "Violet", primaryColors.violet),
createTheme("yellow", "Yellow", primaryColors.yellow), createTheme("yellow", "Yellow", primaryColors.yellow),
].sort((a, b) => a.name.localeCompare(b.name)); ].sort((a, b) => a.name.localeCompare(b.name));
export function applyTheme(themeName: string) { export function applyTheme(themeName: string) {
const theme = themes.find((t) => t.name === themeName) || themes[0]; const theme = themes.find((t) => t.name === themeName) || themes[0];
const root = document.documentElement; const root = document.documentElement;
const isDark = root.classList.contains("dark"); const isDark = root.classList.contains("dark");
const vars = isDark ? theme.cssVars.dark : theme.cssVars.light; const vars = isDark ? theme.cssVars.dark : theme.cssVars.light;
Object.entries(vars).forEach(([key, value]) => {
Object.entries(vars).forEach(([key, value]) => { root.style.setProperty(`--${key}`, value);
root.style.setProperty(`--${key}`, value); });
});
} }
+37 -47
View File
@@ -1,55 +1,45 @@
import { toast } from "sonner"; import { toast } from "sonner";
import { import { playSuccessSound, playErrorSound, playWarningSound, playInfoSound, } from "./audio";
playSuccessSound,
playErrorSound,
playWarningSound,
playInfoSound,
} from "./audio";
import { logger } from "./logger"; import { logger } from "./logger";
import { getSettings } from "./settings"; import { getSettings } from "./settings";
const toastStyle = { const toastStyle = {
className: "font-mono lowercase", className: "font-mono lowercase",
}; };
// Helper to check if SFX is enabled
const isSfxEnabled = () => getSettings().sfxEnabled; const isSfxEnabled = () => getSettings().sfxEnabled;
// Wrapper functions for toast with sound effects
export const toastWithSound = { export const toastWithSound = {
success: (message: string, data?: any) => { success: (message: string, data?: any) => {
const msg = message.toLowerCase(); const msg = message.toLowerCase();
logger.success(msg); logger.success(msg);
if (isSfxEnabled()) playSuccessSound(); if (isSfxEnabled())
return toast.success(msg, { ...toastStyle, ...data }); playSuccessSound();
}, return toast.success(msg, { ...toastStyle, ...data });
},
error: (message: string, data?: any) => { error: (message: string, data?: any) => {
const msg = message.toLowerCase(); const msg = message.toLowerCase();
logger.error(msg); logger.error(msg);
if (isSfxEnabled()) playErrorSound(); if (isSfxEnabled())
return toast.error(msg, { ...toastStyle, ...data }); playErrorSound();
}, return toast.error(msg, { ...toastStyle, ...data });
},
warning: (message: string, data?: any) => { warning: (message: string, data?: any) => {
const msg = message.toLowerCase(); const msg = message.toLowerCase();
logger.warning(msg); logger.warning(msg);
if (isSfxEnabled()) playWarningSound(); if (isSfxEnabled())
return toast.warning(msg, { ...toastStyle, ...data }); playWarningSound();
}, return toast.warning(msg, { ...toastStyle, ...data });
},
info: (message: string, data?: any) => { info: (message: string, data?: any) => {
const msg = message.toLowerCase(); const msg = message.toLowerCase();
logger.info(msg); logger.info(msg);
if (isSfxEnabled()) playInfoSound(); if (isSfxEnabled())
return toast.info(msg, { ...toastStyle, ...data }); playInfoSound();
}, return toast.info(msg, { ...toastStyle, ...data });
},
// Default toast without specific type message: (message: string, data?: any) => {
message: (message: string, data?: any) => { const msg = message.toLowerCase();
const msg = message.toLowerCase(); logger.info(msg);
logger.info(msg); if (isSfxEnabled())
if (isSfxEnabled()) playInfoSound(); playInfoSound();
return toast(msg, { ...toastStyle, ...data }); return toast(msg, { ...toastStyle, ...data });
}, },
}; };
+35 -39
View File
@@ -1,44 +1,40 @@
import { clsx, type ClassValue } from "clsx" import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge" import { twMerge } from "tailwind-merge";
import { BrowserOpenURL } from "../../wailsjs/runtime/runtime" import { BrowserOpenURL } from "../../wailsjs/runtime/runtime";
export function cn(...inputs: ClassValue[]) { export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs)) return twMerge(clsx(inputs));
} }
export function sanitizePath(input: string, os: string): string { export function sanitizePath(input: string, os: string): string {
if (os === "Windows") { if (os === "Windows") {
return input.replace(/[<>:"/\\|?*]/g, "_"); return input.replace(/[<>:"/\\|?*]/g, "_");
} }
return input.replace(/\//g, "_"); return input.replace(/\//g, "_");
} }
export function joinPath(os: string, ...parts: string[]): string {
export function joinPath(os: string, ...parts: string[]): string { const sep = os === "Windows" ? "\\" : "/";
const sep = os === "Windows" ? "\\" : "/"; const filtered = parts.filter(Boolean);
if (filtered.length === 0)
const filtered = parts.filter(Boolean); return "";
if (filtered.length === 0) return ""; const joined = filtered
.map((p, i) => {
const joined = filtered if (i === 0) {
.map((p, i) => { return p.replace(/[/\\]+$/g, "");
if (i === 0) { }
return p.replace(/[/\\]+$/g, ""); return p.replace(/^[/\\]+|[/\\]+$/g, "");
} })
return p.replace(/^[/\\]+|[/\\]+$/g, ""); .filter(Boolean)
}) .join(sep);
.filter(Boolean) return joined;
.join(sep); }
export function openExternal(url: string) {
return joined; if (!url)
} return;
try {
export function openExternal(url: string) { BrowserOpenURL(url);
if (!url) return; }
try { catch (error) {
BrowserOpenURL(url); if (typeof window !== "undefined") {
} catch (error) { window.open(url, "_blank", "noopener,noreferrer");
if (typeof window !== "undefined") { }
window.open(url, "_blank", "noopener,noreferrer");
} }
}
} }
+3 -6
View File
@@ -3,10 +3,7 @@ import { createRoot } from "react-dom/client";
import "./index.css"; import "./index.css";
import App from "./App.tsx"; import App from "./App.tsx";
import { Toaster } from "@/components/ui/sonner"; import { Toaster } from "@/components/ui/sonner";
createRoot(document.getElementById("root")!).render(<StrictMode>
createRoot(document.getElementById("root")!).render(
<StrictMode>
<App /> <App />
<Toaster position="bottom-left" duration={1000} /> <Toaster position="bottom-left" duration={1000}/>
</StrictMode> </StrictMode>);
);
+55 -64
View File
@@ -1,78 +1,69 @@
// Twitter/X Media Batch Downloader Types
export interface AccountInfo { export interface AccountInfo {
name: string; // username/handle from extractor name: string;
nick: string; // display name from extractor nick: string;
date: string; date: string;
followers_count: number; followers_count: number;
friends_count: number; friends_count: number;
profile_image: string; profile_image: string;
statuses_count: number; statuses_count: number;
} }
export interface TimelineEntry { export interface TimelineEntry {
url: string; url: string;
date: string; date: string;
tweet_id: string; tweet_id: string;
type: string; // photo, video, gif, text type: string;
is_retweet: boolean; is_retweet: boolean;
extension: string; extension: string;
width: number; width: number;
height: number; height: number;
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;
source?: string; source?: string;
verified?: boolean; verified?: boolean;
original_filename?: string; // Original filename from API original_filename?: string;
author_username?: string; // Username of tweet author (for bookmarks and likes) author_username?: string;
} }
export interface ExtractMetadata { export interface ExtractMetadata {
new_entries: number; new_entries: number;
page: number; page: number;
batch_size: number; batch_size: number;
has_more: boolean; has_more: boolean;
cursor?: string; // Cursor for resume capability cursor?: string;
completed?: boolean; // True if all media fetched completed?: boolean;
} }
export interface TwitterResponse { export interface TwitterResponse {
account_info: AccountInfo; account_info: AccountInfo;
total_urls: number; total_urls: number;
timeline: TimelineEntry[]; timeline: TimelineEntry[];
metadata: ExtractMetadata; metadata: ExtractMetadata;
cursor?: string; // Cursor for next fetch (from CLI) cursor?: string;
completed?: boolean; // True if fetch completed completed?: boolean;
} }
export interface TimelineRequest { export interface TimelineRequest {
username: string; username: string;
auth_token: string; auth_token: string;
timeline_type: string; // media, timeline, tweets, with_replies, likes timeline_type: string;
batch_size: number; batch_size: number;
page: number; page: number;
media_type: string; // all, image, video, gif media_type: string;
retweets: boolean; retweets: boolean;
cursor?: string; // Resume from this cursor position cursor?: string;
} }
export interface DateRangeRequest { export interface DateRangeRequest {
username: string; username: string;
auth_token: string; auth_token: string;
start_date: string; // YYYY-MM-DD start_date: string;
end_date: string; // YYYY-MM-DD end_date: string;
media_filter: string; media_filter: string;
retweets: boolean; retweets: boolean;
} }
// Settings types
export interface Settings { export interface Settings {
downloadPath: string; downloadPath: string;
theme: string; theme: string;
themeMode: "auto" | "light" | "dark"; themeMode: "auto" | "light" | "dark";
sfxEnabled: boolean; sfxEnabled: boolean;
} }
+2
View File
@@ -0,0 +1,2 @@
/// <reference types="vite/client" />
declare const __APP_VERSION__: string;
+17 -12
View File
@@ -1,14 +1,19 @@
import path from "path" import fs from "fs";
import tailwindcss from "@tailwindcss/vite" import path from "path";
import react from "@vitejs/plugin-react" import tailwindcss from "@tailwindcss/vite";
import { defineConfig } from "vite" import react from "@vitejs/plugin-react";
import { defineConfig } from "vite";
// https://vite.dev/config/ const wailsJsonPath = path.resolve(__dirname, "../wails.json");
const wailsJson = JSON.parse(fs.readFileSync(wailsJsonPath, "utf-8"));
const appVersion = wailsJson.info.productVersion;
export default defineConfig({ export default defineConfig({
plugins: [react(), tailwindcss()], plugins: [react(), tailwindcss()],
resolve: { resolve: {
alias: { alias: {
"@": path.resolve(__dirname, "./src"), "@": path.resolve(__dirname, "./src"),
},
}, },
}, define: {
}) __APP_VERSION__: JSON.stringify(appVersion),
},
});
+70
View File
@@ -0,0 +1,70 @@
// Cynhyrchwyd y ffeil hon yn awtomatig. PEIDIWCH Â MODIWL
// This file is automatically generated. DO NOT EDIT
import {main} from '../models';
import {backend} from '../models';
export function CheckFolderExists(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 CleanupExtractorProcesses():Promise<void>;
export function ClearAllAccountsFromDB():Promise<void>;
export function ConvertGIFs(arg1:main.ConvertGIFsRequest):Promise<main.ConvertGIFsResponse>;
export function DeleteAccountFromDB(arg1:number):Promise<void>;
export function DownloadExifTool():Promise<void>;
export function DownloadExtractor():Promise<void>;
export function DownloadFFmpeg():Promise<void>;
export function DownloadMedia(arg1:main.DownloadMediaRequest):Promise<main.DownloadMediaResponse>;
export function DownloadMediaWithMetadata(arg1:main.DownloadMediaWithMetadataRequest):Promise<main.DownloadMediaResponse>;
export function ExportAccountJSON(arg1:number,arg2:string):Promise<string>;
export function ExportAccountsTXT(arg1:Array<number>,arg2:string):Promise<string>;
export function ExtractDateRange(arg1:main.DateRangeRequest):Promise<string>;
export function ExtractTimeline(arg1:main.TimelineRequest):Promise<string>;
export function GetAccountFromDB(arg1:number):Promise<string>;
export function GetAllAccountsFromDB():Promise<Array<backend.AccountListItem>>;
export function GetAllGroups():Promise<Array<Record<string, string>>>;
export function GetDefaults():Promise<Record<string, string>>;
export function GetFolderPath(arg1:string,arg2:string):Promise<string>;
export function GetGifsFolderPath(arg1:string,arg2:string):Promise<string>;
export function ImportAccountFromJSON():Promise<main.ImportAccountResponse>;
export function IsExifToolInstalled():Promise<boolean>;
export function IsExtractorInstalled():Promise<boolean>;
export function IsFFmpegInstalled():Promise<boolean>;
export function OpenFolder(arg1:string):Promise<void>;
export function Quit():Promise<void>;
export function SaveAccountToDB(arg1:string,arg2:string,arg3:string,arg4:number,arg5:string,arg6:string):Promise<void>;
export function SaveAccountToDBWithStatus(arg1:string,arg2:string,arg3:string,arg4:number,arg5:string,arg6:string,arg7:string,arg8:boolean):Promise<void>;
export function SelectFolder(arg1:string):Promise<string>;
export function StopDownload():Promise<boolean>;
export function UpdateAccountGroup(arg1:number,arg2:string,arg3:string):Promise<void>;
+135
View File
@@ -0,0 +1,135 @@
// @ts-check
// Cynhyrchwyd y ffeil hon yn awtomatig. PEIDIWCH Â MODIWL
// This file is automatically generated. DO NOT EDIT
export function CheckFolderExists(arg1, arg2) {
return window['go']['main']['App']['CheckFolderExists'](arg1, arg2);
}
export function CheckGifsFolderExists(arg1, arg2) {
return window['go']['main']['App']['CheckGifsFolderExists'](arg1, arg2);
}
export function CheckGifsFolderHasMP4(arg1, arg2) {
return window['go']['main']['App']['CheckGifsFolderHasMP4'](arg1, arg2);
}
export function CleanupExtractorProcesses() {
return window['go']['main']['App']['CleanupExtractorProcesses']();
}
export function ClearAllAccountsFromDB() {
return window['go']['main']['App']['ClearAllAccountsFromDB']();
}
export function ConvertGIFs(arg1) {
return window['go']['main']['App']['ConvertGIFs'](arg1);
}
export function DeleteAccountFromDB(arg1) {
return window['go']['main']['App']['DeleteAccountFromDB'](arg1);
}
export function DownloadExifTool() {
return window['go']['main']['App']['DownloadExifTool']();
}
export function DownloadExtractor() {
return window['go']['main']['App']['DownloadExtractor']();
}
export function DownloadFFmpeg() {
return window['go']['main']['App']['DownloadFFmpeg']();
}
export function DownloadMedia(arg1) {
return window['go']['main']['App']['DownloadMedia'](arg1);
}
export function DownloadMediaWithMetadata(arg1) {
return window['go']['main']['App']['DownloadMediaWithMetadata'](arg1);
}
export function ExportAccountJSON(arg1, arg2) {
return window['go']['main']['App']['ExportAccountJSON'](arg1, arg2);
}
export function ExportAccountsTXT(arg1, arg2) {
return window['go']['main']['App']['ExportAccountsTXT'](arg1, arg2);
}
export function ExtractDateRange(arg1) {
return window['go']['main']['App']['ExtractDateRange'](arg1);
}
export function ExtractTimeline(arg1) {
return window['go']['main']['App']['ExtractTimeline'](arg1);
}
export function GetAccountFromDB(arg1) {
return window['go']['main']['App']['GetAccountFromDB'](arg1);
}
export function GetAllAccountsFromDB() {
return window['go']['main']['App']['GetAllAccountsFromDB']();
}
export function GetAllGroups() {
return window['go']['main']['App']['GetAllGroups']();
}
export function GetDefaults() {
return window['go']['main']['App']['GetDefaults']();
}
export function GetFolderPath(arg1, arg2) {
return window['go']['main']['App']['GetFolderPath'](arg1, arg2);
}
export function GetGifsFolderPath(arg1, arg2) {
return window['go']['main']['App']['GetGifsFolderPath'](arg1, arg2);
}
export function ImportAccountFromJSON() {
return window['go']['main']['App']['ImportAccountFromJSON']();
}
export function IsExifToolInstalled() {
return window['go']['main']['App']['IsExifToolInstalled']();
}
export function IsExtractorInstalled() {
return window['go']['main']['App']['IsExtractorInstalled']();
}
export function IsFFmpegInstalled() {
return window['go']['main']['App']['IsFFmpegInstalled']();
}
export function OpenFolder(arg1) {
return window['go']['main']['App']['OpenFolder'](arg1);
}
export function Quit() {
return window['go']['main']['App']['Quit']();
}
export function SaveAccountToDB(arg1, arg2, arg3, arg4, arg5, arg6) {
return window['go']['main']['App']['SaveAccountToDB'](arg1, arg2, arg3, arg4, arg5, arg6);
}
export function SaveAccountToDBWithStatus(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8) {
return window['go']['main']['App']['SaveAccountToDBWithStatus'](arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8);
}
export function SelectFolder(arg1) {
return window['go']['main']['App']['SelectFolder'](arg1);
}
export function StopDownload() {
return window['go']['main']['App']['StopDownload']();
}
export function UpdateAccountGroup(arg1, arg2, arg3) {
return window['go']['main']['App']['UpdateAccountGroup'](arg1, arg2, arg3);
}
+245
View File
@@ -0,0 +1,245 @@
export namespace backend {
export class AccountListItem {
id: number;
username: string;
name: string;
profile_image: string;
total_media: number;
last_fetched: string;
group_name: string;
group_color: string;
media_type: string;
cursor: string;
completed: boolean;
followers_count: number;
statuses_count: number;
static createFrom(source: any = {}) {
return new AccountListItem(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.id = source["id"];
this.username = source["username"];
this.name = source["name"];
this.profile_image = source["profile_image"];
this.total_media = source["total_media"];
this.last_fetched = source["last_fetched"];
this.group_name = source["group_name"];
this.group_color = source["group_color"];
this.media_type = source["media_type"];
this.cursor = source["cursor"];
this.completed = source["completed"];
this.followers_count = source["followers_count"];
this.statuses_count = source["statuses_count"];
}
}
}
export namespace main {
export class ConvertGIFsRequest {
folder_path: string;
quality: string;
resolution: string;
delete_original: boolean;
static createFrom(source: any = {}) {
return new ConvertGIFsRequest(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.folder_path = source["folder_path"];
this.quality = source["quality"];
this.resolution = source["resolution"];
this.delete_original = source["delete_original"];
}
}
export class ConvertGIFsResponse {
success: boolean;
converted: number;
failed: number;
message: string;
static createFrom(source: any = {}) {
return new ConvertGIFsResponse(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.success = source["success"];
this.converted = source["converted"];
this.failed = source["failed"];
this.message = source["message"];
}
}
export class DateRangeRequest {
username: string;
auth_token: string;
start_date: string;
end_date: string;
media_filter: string;
retweets: boolean;
static createFrom(source: any = {}) {
return new DateRangeRequest(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.username = source["username"];
this.auth_token = source["auth_token"];
this.start_date = source["start_date"];
this.end_date = source["end_date"];
this.media_filter = source["media_filter"];
this.retweets = source["retweets"];
}
}
export class DownloadMediaRequest {
urls: string[];
output_dir: string;
username: string;
proxy?: string;
static createFrom(source: any = {}) {
return new DownloadMediaRequest(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.urls = source["urls"];
this.output_dir = source["output_dir"];
this.username = source["username"];
this.proxy = source["proxy"];
}
}
export class DownloadMediaResponse {
success: boolean;
downloaded: number;
skipped: number;
failed: number;
message: string;
static createFrom(source: any = {}) {
return new DownloadMediaResponse(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.success = source["success"];
this.downloaded = source["downloaded"];
this.skipped = source["skipped"];
this.failed = source["failed"];
this.message = source["message"];
}
}
export class MediaItemRequest {
url: string;
date: string;
tweet_id: number;
type: string;
content?: string;
original_filename?: string;
author_username?: string;
static createFrom(source: any = {}) {
return new MediaItemRequest(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.url = source["url"];
this.date = source["date"];
this.tweet_id = source["tweet_id"];
this.type = source["type"];
this.content = source["content"];
this.original_filename = source["original_filename"];
this.author_username = source["author_username"];
}
}
export class DownloadMediaWithMetadataRequest {
items: MediaItemRequest[];
output_dir: string;
username: string;
proxy?: string;
static createFrom(source: any = {}) {
return new DownloadMediaWithMetadataRequest(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.items = this.convertValues(source["items"], MediaItemRequest);
this.output_dir = source["output_dir"];
this.username = source["username"];
this.proxy = source["proxy"];
}
convertValues(a: any, classs: any, asMap: boolean = false): any {
if (!a) {
return a;
}
if (a.slice && a.map) {
return (a as any[]).map(elem => this.convertValues(elem, classs));
} else if ("object" === typeof a) {
if (asMap) {
for (const key of Object.keys(a)) {
a[key] = new classs(a[key]);
}
return a;
}
return new classs(a);
}
return a;
}
}
export class ImportAccountResponse {
success: boolean;
username: string;
message: string;
static createFrom(source: any = {}) {
return new ImportAccountResponse(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.success = source["success"];
this.username = source["username"];
this.message = source["message"];
}
}
export class TimelineRequest {
username: string;
auth_token: string;
timeline_type: string;
batch_size: number;
page: number;
media_type: string;
retweets: boolean;
cursor?: string;
static createFrom(source: any = {}) {
return new TimelineRequest(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.username = source["username"];
this.auth_token = source["auth_token"];
this.timeline_type = source["timeline_type"];
this.batch_size = source["batch_size"];
this.page = source["page"];
this.media_type = source["media_type"];
this.retweets = source["retweets"];
this.cursor = source["cursor"];
}
}
}
+24
View File
@@ -0,0 +1,24 @@
{
"name": "@wailsapp/runtime",
"version": "2.0.0",
"description": "Wails Javascript runtime library",
"main": "runtime.js",
"types": "runtime.d.ts",
"scripts": {
},
"repository": {
"type": "git",
"url": "git+https://github.com/wailsapp/wails.git"
},
"keywords": [
"Wails",
"Javascript",
"Go"
],
"author": "Lea Anthony <lea.anthony@gmail.com>",
"license": "MIT",
"bugs": {
"url": "https://github.com/wailsapp/wails/issues"
},
"homepage": "https://github.com/wailsapp/wails#readme"
}
+330
View File
@@ -0,0 +1,330 @@
/*
_ __ _ __
| | / /___ _(_) /____
| | /| / / __ `/ / / ___/
| |/ |/ / /_/ / / (__ )
|__/|__/\__,_/_/_/____/
The electron alternative for Go
(c) Lea Anthony 2019-present
*/
export interface Position {
x: number;
y: number;
}
export interface Size {
w: number;
h: number;
}
export interface Screen {
isCurrent: boolean;
isPrimary: boolean;
width : number
height : number
}
// Environment information such as platform, buildtype, ...
export interface EnvironmentInfo {
buildType: string;
platform: string;
arch: string;
}
// [EventsEmit](https://wails.io/docs/reference/runtime/events#eventsemit)
// emits the given event. Optional data may be passed with the event.
// This will trigger any event listeners.
export function EventsEmit(eventName: string, ...data: any): void;
// [EventsOn](https://wails.io/docs/reference/runtime/events#eventson) sets up a listener for the given event name.
export function EventsOn(eventName: string, callback: (...data: any) => void): () => void;
// [EventsOnMultiple](https://wails.io/docs/reference/runtime/events#eventsonmultiple)
// sets up a listener for the given event name, but will only trigger a given number times.
export function EventsOnMultiple(eventName: string, callback: (...data: any) => void, maxCallbacks: number): () => void;
// [EventsOnce](https://wails.io/docs/reference/runtime/events#eventsonce)
// sets up a listener for the given event name, but will only trigger once.
export function EventsOnce(eventName: string, callback: (...data: any) => void): () => void;
// [EventsOff](https://wails.io/docs/reference/runtime/events#eventsoff)
// unregisters the listener for the given event name.
export function EventsOff(eventName: string, ...additionalEventNames: string[]): void;
// [EventsOffAll](https://wails.io/docs/reference/runtime/events#eventsoffall)
// unregisters all listeners.
export function EventsOffAll(): void;
// [LogPrint](https://wails.io/docs/reference/runtime/log#logprint)
// logs the given message as a raw message
export function LogPrint(message: string): void;
// [LogTrace](https://wails.io/docs/reference/runtime/log#logtrace)
// logs the given message at the `trace` log level.
export function LogTrace(message: string): void;
// [LogDebug](https://wails.io/docs/reference/runtime/log#logdebug)
// logs the given message at the `debug` log level.
export function LogDebug(message: string): void;
// [LogError](https://wails.io/docs/reference/runtime/log#logerror)
// logs the given message at the `error` log level.
export function LogError(message: string): void;
// [LogFatal](https://wails.io/docs/reference/runtime/log#logfatal)
// logs the given message at the `fatal` log level.
// The application will quit after calling this method.
export function LogFatal(message: string): void;
// [LogInfo](https://wails.io/docs/reference/runtime/log#loginfo)
// logs the given message at the `info` log level.
export function LogInfo(message: string): void;
// [LogWarning](https://wails.io/docs/reference/runtime/log#logwarning)
// logs the given message at the `warning` log level.
export function LogWarning(message: string): void;
// [WindowReload](https://wails.io/docs/reference/runtime/window#windowreload)
// Forces a reload by the main application as well as connected browsers.
export function WindowReload(): void;
// [WindowReloadApp](https://wails.io/docs/reference/runtime/window#windowreloadapp)
// Reloads the application frontend.
export function WindowReloadApp(): void;
// [WindowSetAlwaysOnTop](https://wails.io/docs/reference/runtime/window#windowsetalwaysontop)
// Sets the window AlwaysOnTop or not on top.
export function WindowSetAlwaysOnTop(b: boolean): void;
// [WindowSetSystemDefaultTheme](https://wails.io/docs/next/reference/runtime/window#windowsetsystemdefaulttheme)
// *Windows only*
// Sets window theme to system default (dark/light).
export function WindowSetSystemDefaultTheme(): void;
// [WindowSetLightTheme](https://wails.io/docs/next/reference/runtime/window#windowsetlighttheme)
// *Windows only*
// Sets window to light theme.
export function WindowSetLightTheme(): void;
// [WindowSetDarkTheme](https://wails.io/docs/next/reference/runtime/window#windowsetdarktheme)
// *Windows only*
// Sets window to dark theme.
export function WindowSetDarkTheme(): void;
// [WindowCenter](https://wails.io/docs/reference/runtime/window#windowcenter)
// Centers the window on the monitor the window is currently on.
export function WindowCenter(): void;
// [WindowSetTitle](https://wails.io/docs/reference/runtime/window#windowsettitle)
// Sets the text in the window title bar.
export function WindowSetTitle(title: string): void;
// [WindowFullscreen](https://wails.io/docs/reference/runtime/window#windowfullscreen)
// Makes the window full screen.
export function WindowFullscreen(): void;
// [WindowUnfullscreen](https://wails.io/docs/reference/runtime/window#windowunfullscreen)
// Restores the previous window dimensions and position prior to full screen.
export function WindowUnfullscreen(): void;
// [WindowIsFullscreen](https://wails.io/docs/reference/runtime/window#windowisfullscreen)
// Returns the state of the window, i.e. whether the window is in full screen mode or not.
export function WindowIsFullscreen(): Promise<boolean>;
// [WindowSetSize](https://wails.io/docs/reference/runtime/window#windowsetsize)
// Sets the width and height of the window.
export function WindowSetSize(width: number, height: number): void;
// [WindowGetSize](https://wails.io/docs/reference/runtime/window#windowgetsize)
// Gets the width and height of the window.
export function WindowGetSize(): Promise<Size>;
// [WindowSetMaxSize](https://wails.io/docs/reference/runtime/window#windowsetmaxsize)
// Sets the maximum window size. Will resize the window if the window is currently larger than the given dimensions.
// Setting a size of 0,0 will disable this constraint.
export function WindowSetMaxSize(width: number, height: number): void;
// [WindowSetMinSize](https://wails.io/docs/reference/runtime/window#windowsetminsize)
// Sets the minimum window size. Will resize the window if the window is currently smaller than the given dimensions.
// Setting a size of 0,0 will disable this constraint.
export function WindowSetMinSize(width: number, height: number): void;
// [WindowSetPosition](https://wails.io/docs/reference/runtime/window#windowsetposition)
// Sets the window position relative to the monitor the window is currently on.
export function WindowSetPosition(x: number, y: number): void;
// [WindowGetPosition](https://wails.io/docs/reference/runtime/window#windowgetposition)
// Gets the window position relative to the monitor the window is currently on.
export function WindowGetPosition(): Promise<Position>;
// [WindowHide](https://wails.io/docs/reference/runtime/window#windowhide)
// Hides the window.
export function WindowHide(): void;
// [WindowShow](https://wails.io/docs/reference/runtime/window#windowshow)
// Shows the window, if it is currently hidden.
export function WindowShow(): void;
// [WindowMaximise](https://wails.io/docs/reference/runtime/window#windowmaximise)
// Maximises the window to fill the screen.
export function WindowMaximise(): void;
// [WindowToggleMaximise](https://wails.io/docs/reference/runtime/window#windowtogglemaximise)
// Toggles between Maximised and UnMaximised.
export function WindowToggleMaximise(): void;
// [WindowUnmaximise](https://wails.io/docs/reference/runtime/window#windowunmaximise)
// Restores the window to the dimensions and position prior to maximising.
export function WindowUnmaximise(): void;
// [WindowIsMaximised](https://wails.io/docs/reference/runtime/window#windowismaximised)
// Returns the state of the window, i.e. whether the window is maximised or not.
export function WindowIsMaximised(): Promise<boolean>;
// [WindowMinimise](https://wails.io/docs/reference/runtime/window#windowminimise)
// Minimises the window.
export function WindowMinimise(): void;
// [WindowUnminimise](https://wails.io/docs/reference/runtime/window#windowunminimise)
// Restores the window to the dimensions and position prior to minimising.
export function WindowUnminimise(): void;
// [WindowIsMinimised](https://wails.io/docs/reference/runtime/window#windowisminimised)
// Returns the state of the window, i.e. whether the window is minimised or not.
export function WindowIsMinimised(): Promise<boolean>;
// [WindowIsNormal](https://wails.io/docs/reference/runtime/window#windowisnormal)
// Returns the state of the window, i.e. whether the window is normal or not.
export function WindowIsNormal(): Promise<boolean>;
// [WindowSetBackgroundColour](https://wails.io/docs/reference/runtime/window#windowsetbackgroundcolour)
// Sets the background colour of the window to the given RGBA colour definition. This colour will show through for all transparent pixels.
export function WindowSetBackgroundColour(R: number, G: number, B: number, A: number): void;
// [ScreenGetAll](https://wails.io/docs/reference/runtime/window#screengetall)
// Gets the all screens. Call this anew each time you want to refresh data from the underlying windowing system.
export function ScreenGetAll(): Promise<Screen[]>;
// [BrowserOpenURL](https://wails.io/docs/reference/runtime/browser#browseropenurl)
// Opens the given URL in the system browser.
export function BrowserOpenURL(url: string): void;
// [Environment](https://wails.io/docs/reference/runtime/intro#environment)
// Returns information about the environment
export function Environment(): Promise<EnvironmentInfo>;
// [Quit](https://wails.io/docs/reference/runtime/intro#quit)
// Quits the application.
export function Quit(): void;
// [Hide](https://wails.io/docs/reference/runtime/intro#hide)
// Hides the application.
export function Hide(): void;
// [Show](https://wails.io/docs/reference/runtime/intro#show)
// Shows the application.
export function Show(): void;
// [ClipboardGetText](https://wails.io/docs/reference/runtime/clipboard#clipboardgettext)
// Returns the current text stored on clipboard
export function ClipboardGetText(): Promise<string>;
// [ClipboardSetText](https://wails.io/docs/reference/runtime/clipboard#clipboardsettext)
// Sets a text on the clipboard
export function ClipboardSetText(text: string): Promise<boolean>;
// [OnFileDrop](https://wails.io/docs/reference/runtime/draganddrop#onfiledrop)
// OnFileDrop listens to drag and drop events and calls the callback with the coordinates of the drop and an array of path strings.
export function OnFileDrop(callback: (x: number, y: number ,paths: string[]) => void, useDropTarget: boolean) :void
// [OnFileDropOff](https://wails.io/docs/reference/runtime/draganddrop#dragandddropoff)
// OnFileDropOff removes the drag and drop listeners and handlers.
export function OnFileDropOff() :void
// Check if the file path resolver is available
export function CanResolveFilePaths(): boolean;
// Resolves file paths for an array of files
export function ResolveFilePaths(files: File[]): void
// Notification types
export interface NotificationOptions {
id: string;
title: string;
subtitle?: string; // macOS and Linux only
body?: string;
categoryId?: string;
data?: { [key: string]: any };
}
export interface NotificationAction {
id?: string;
title?: string;
destructive?: boolean; // macOS-specific
}
export interface NotificationCategory {
id?: string;
actions?: NotificationAction[];
hasReplyField?: boolean;
replyPlaceholder?: string;
replyButtonTitle?: string;
}
// [InitializeNotifications](https://wails.io/docs/reference/runtime/notification#initializenotifications)
// Initializes the notification service for the application.
// This must be called before sending any notifications.
export function InitializeNotifications(): Promise<void>;
// [CleanupNotifications](https://wails.io/docs/reference/runtime/notification#cleanupnotifications)
// Cleans up notification resources and releases any held connections.
export function CleanupNotifications(): Promise<void>;
// [IsNotificationAvailable](https://wails.io/docs/reference/runtime/notification#isnotificationavailable)
// Checks if notifications are available on the current platform.
export function IsNotificationAvailable(): Promise<boolean>;
// [RequestNotificationAuthorization](https://wails.io/docs/reference/runtime/notification#requestnotificationauthorization)
// Requests notification authorization from the user (macOS only).
export function RequestNotificationAuthorization(): Promise<boolean>;
// [CheckNotificationAuthorization](https://wails.io/docs/reference/runtime/notification#checknotificationauthorization)
// Checks the current notification authorization status (macOS only).
export function CheckNotificationAuthorization(): Promise<boolean>;
// [SendNotification](https://wails.io/docs/reference/runtime/notification#sendnotification)
// Sends a basic notification with the given options.
export function SendNotification(options: NotificationOptions): Promise<void>;
// [SendNotificationWithActions](https://wails.io/docs/reference/runtime/notification#sendnotificationwithactions)
// Sends a notification with action buttons. Requires a registered category.
export function SendNotificationWithActions(options: NotificationOptions): Promise<void>;
// [RegisterNotificationCategory](https://wails.io/docs/reference/runtime/notification#registernotificationcategory)
// Registers a notification category that can be used with SendNotificationWithActions.
export function RegisterNotificationCategory(category: NotificationCategory): Promise<void>;
// [RemoveNotificationCategory](https://wails.io/docs/reference/runtime/notification#removenotificationcategory)
// Removes a previously registered notification category.
export function RemoveNotificationCategory(categoryId: string): Promise<void>;
// [RemoveAllPendingNotifications](https://wails.io/docs/reference/runtime/notification#removeallpendingnotifications)
// Removes all pending notifications from the notification center.
export function RemoveAllPendingNotifications(): Promise<void>;
// [RemovePendingNotification](https://wails.io/docs/reference/runtime/notification#removependingnotification)
// Removes a specific pending notification by its identifier.
export function RemovePendingNotification(identifier: string): Promise<void>;
// [RemoveAllDeliveredNotifications](https://wails.io/docs/reference/runtime/notification#removealldeliverednotifications)
// Removes all delivered notifications from the notification center.
export function RemoveAllDeliveredNotifications(): Promise<void>;
// [RemoveDeliveredNotification](https://wails.io/docs/reference/runtime/notification#removedeliverednotification)
// Removes a specific delivered notification by its identifier.
export function RemoveDeliveredNotification(identifier: string): Promise<void>;
// [RemoveNotification](https://wails.io/docs/reference/runtime/notification#removenotification)
// Removes a notification by its identifier (cross-platform convenience function).
export function RemoveNotification(identifier: string): Promise<void>;
+298
View File
@@ -0,0 +1,298 @@
/*
_ __ _ __
| | / /___ _(_) /____
| | /| / / __ `/ / / ___/
| |/ |/ / /_/ / / (__ )
|__/|__/\__,_/_/_/____/
The electron alternative for Go
(c) Lea Anthony 2019-present
*/
export function LogPrint(message) {
window.runtime.LogPrint(message);
}
export function LogTrace(message) {
window.runtime.LogTrace(message);
}
export function LogDebug(message) {
window.runtime.LogDebug(message);
}
export function LogInfo(message) {
window.runtime.LogInfo(message);
}
export function LogWarning(message) {
window.runtime.LogWarning(message);
}
export function LogError(message) {
window.runtime.LogError(message);
}
export function LogFatal(message) {
window.runtime.LogFatal(message);
}
export function EventsOnMultiple(eventName, callback, maxCallbacks) {
return window.runtime.EventsOnMultiple(eventName, callback, maxCallbacks);
}
export function EventsOn(eventName, callback) {
return EventsOnMultiple(eventName, callback, -1);
}
export function EventsOff(eventName, ...additionalEventNames) {
return window.runtime.EventsOff(eventName, ...additionalEventNames);
}
export function EventsOffAll() {
return window.runtime.EventsOffAll();
}
export function EventsOnce(eventName, callback) {
return EventsOnMultiple(eventName, callback, 1);
}
export function EventsEmit(eventName) {
let args = [eventName].slice.call(arguments);
return window.runtime.EventsEmit.apply(null, args);
}
export function WindowReload() {
window.runtime.WindowReload();
}
export function WindowReloadApp() {
window.runtime.WindowReloadApp();
}
export function WindowSetAlwaysOnTop(b) {
window.runtime.WindowSetAlwaysOnTop(b);
}
export function WindowSetSystemDefaultTheme() {
window.runtime.WindowSetSystemDefaultTheme();
}
export function WindowSetLightTheme() {
window.runtime.WindowSetLightTheme();
}
export function WindowSetDarkTheme() {
window.runtime.WindowSetDarkTheme();
}
export function WindowCenter() {
window.runtime.WindowCenter();
}
export function WindowSetTitle(title) {
window.runtime.WindowSetTitle(title);
}
export function WindowFullscreen() {
window.runtime.WindowFullscreen();
}
export function WindowUnfullscreen() {
window.runtime.WindowUnfullscreen();
}
export function WindowIsFullscreen() {
return window.runtime.WindowIsFullscreen();
}
export function WindowGetSize() {
return window.runtime.WindowGetSize();
}
export function WindowSetSize(width, height) {
window.runtime.WindowSetSize(width, height);
}
export function WindowSetMaxSize(width, height) {
window.runtime.WindowSetMaxSize(width, height);
}
export function WindowSetMinSize(width, height) {
window.runtime.WindowSetMinSize(width, height);
}
export function WindowSetPosition(x, y) {
window.runtime.WindowSetPosition(x, y);
}
export function WindowGetPosition() {
return window.runtime.WindowGetPosition();
}
export function WindowHide() {
window.runtime.WindowHide();
}
export function WindowShow() {
window.runtime.WindowShow();
}
export function WindowMaximise() {
window.runtime.WindowMaximise();
}
export function WindowToggleMaximise() {
window.runtime.WindowToggleMaximise();
}
export function WindowUnmaximise() {
window.runtime.WindowUnmaximise();
}
export function WindowIsMaximised() {
return window.runtime.WindowIsMaximised();
}
export function WindowMinimise() {
window.runtime.WindowMinimise();
}
export function WindowUnminimise() {
window.runtime.WindowUnminimise();
}
export function WindowSetBackgroundColour(R, G, B, A) {
window.runtime.WindowSetBackgroundColour(R, G, B, A);
}
export function ScreenGetAll() {
return window.runtime.ScreenGetAll();
}
export function WindowIsMinimised() {
return window.runtime.WindowIsMinimised();
}
export function WindowIsNormal() {
return window.runtime.WindowIsNormal();
}
export function BrowserOpenURL(url) {
window.runtime.BrowserOpenURL(url);
}
export function Environment() {
return window.runtime.Environment();
}
export function Quit() {
window.runtime.Quit();
}
export function Hide() {
window.runtime.Hide();
}
export function Show() {
window.runtime.Show();
}
export function ClipboardGetText() {
return window.runtime.ClipboardGetText();
}
export function ClipboardSetText(text) {
return window.runtime.ClipboardSetText(text);
}
/**
* Callback for OnFileDrop returns a slice of file path strings when a drop is finished.
*
* @export
* @callback OnFileDropCallback
* @param {number} x - x coordinate of the drop
* @param {number} y - y coordinate of the drop
* @param {string[]} paths - A list of file paths.
*/
/**
* OnFileDrop listens to drag and drop events and calls the callback with the coordinates of the drop and an array of path strings.
*
* @export
* @param {OnFileDropCallback} callback - Callback for OnFileDrop returns a slice of file path strings when a drop is finished.
* @param {boolean} [useDropTarget=true] - Only call the callback when the drop finished on an element that has the drop target style. (--wails-drop-target)
*/
export function OnFileDrop(callback, useDropTarget) {
return window.runtime.OnFileDrop(callback, useDropTarget);
}
/**
* OnFileDropOff removes the drag and drop listeners and handlers.
*/
export function OnFileDropOff() {
return window.runtime.OnFileDropOff();
}
export function CanResolveFilePaths() {
return window.runtime.CanResolveFilePaths();
}
export function ResolveFilePaths(files) {
return window.runtime.ResolveFilePaths(files);
}
export function InitializeNotifications() {
return window.runtime.InitializeNotifications();
}
export function CleanupNotifications() {
return window.runtime.CleanupNotifications();
}
export function IsNotificationAvailable() {
return window.runtime.IsNotificationAvailable();
}
export function RequestNotificationAuthorization() {
return window.runtime.RequestNotificationAuthorization();
}
export function CheckNotificationAuthorization() {
return window.runtime.CheckNotificationAuthorization();
}
export function SendNotification(options) {
return window.runtime.SendNotification(options);
}
export function SendNotificationWithActions(options) {
return window.runtime.SendNotificationWithActions(options);
}
export function RegisterNotificationCategory(category) {
return window.runtime.RegisterNotificationCategory(category);
}
export function RemoveNotificationCategory(categoryId) {
return window.runtime.RemoveNotificationCategory(categoryId);
}
export function RemoveAllPendingNotifications() {
return window.runtime.RemoveAllPendingNotifications();
}
export function RemovePendingNotification(identifier) {
return window.runtime.RemovePendingNotification(identifier);
}
export function RemoveAllDeliveredNotifications() {
return window.runtime.RemoveAllDeliveredNotifications();
}
export function RemoveDeliveredNotification(identifier) {
return window.runtime.RemoveDeliveredNotification(identifier);
}
export function RemoveNotification(identifier) {
return window.runtime.RemoveNotification(identifier);
}
+10 -3
View File
@@ -3,13 +3,15 @@ module twitterxmediabatchdownloader
go 1.25.4 go 1.25.4
require ( require (
github.com/mattn/go-sqlite3 v1.14.32
github.com/ulikunitz/xz v0.5.15 github.com/ulikunitz/xz v0.5.15
github.com/wailsapp/wails/v2 v2.11.0 github.com/wailsapp/wails/v2 v2.12.0
modernc.org/sqlite v1.50.1
) )
require ( require (
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/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.0 // indirect
github.com/google/uuid v1.6.0 // indirect github.com/google/uuid v1.6.0 // indirect
@@ -23,8 +25,10 @@ require (
github.com/leaanthony/u v1.1.1 // indirect github.com/leaanthony/u v1.1.1 // indirect
github.com/mattn/go-colorable v0.1.14 // indirect github.com/mattn/go-colorable v0.1.14 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect github.com/mattn/go-isatty v0.0.20 // indirect
github.com/ncruces/go-strftime v1.0.0 // indirect
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect
github.com/pkg/errors v0.9.1 // indirect github.com/pkg/errors v0.9.1 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
github.com/rivo/uniseg v0.4.7 // indirect github.com/rivo/uniseg v0.4.7 // indirect
github.com/samber/lo v1.52.0 // indirect github.com/samber/lo v1.52.0 // indirect
github.com/tkrajina/go-reflector v0.5.8 // indirect github.com/tkrajina/go-reflector v0.5.8 // indirect
@@ -34,6 +38,9 @@ require (
github.com/wailsapp/mimetype v1.4.1 // indirect github.com/wailsapp/mimetype v1.4.1 // indirect
golang.org/x/crypto v0.45.0 // indirect golang.org/x/crypto v0.45.0 // indirect
golang.org/x/net v0.47.0 // indirect golang.org/x/net v0.47.0 // indirect
golang.org/x/sys v0.38.0 // indirect golang.org/x/sys v0.42.0 // indirect
golang.org/x/text v0.31.0 // indirect golang.org/x/text v0.31.0 // indirect
modernc.org/libc v1.72.3 // indirect
modernc.org/mathutil v1.7.1 // indirect
modernc.org/memory v1.11.0 // indirect
) )
+50 -6
View File
@@ -1,15 +1,23 @@
git.sr.ht/~jackmordaunt/go-toast/v2 v2.0.3 h1:N3IGoHHp9pb6mj1cbXbuaSXV/UMKwmbKLf53nQmtqMA=
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/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/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.0 h1:3WexO+U+yg9T70v9FdHr9kCxYlazaAXUhx2VMkbfax8=
github.com/godbus/dbus/v5 v5.2.0/go.mod h1:3AAv2+hPq5rdnr5txxxRwiGjPXamgoIHgz9FPBfOp3c= github.com/godbus/dbus/v5 v5.2.0/go.mod h1:3AAv2+hPq5rdnr5txxxRwiGjPXamgoIHgz9FPBfOp3c=
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs=
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg= github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
github.com/jchv/go-winloader v0.0.0-20250406163304-c1995be93bd1 h1:njuLRcjAuMKr7kI3D85AXWkw6/+v9PwtV6M6o11sWHQ= github.com/jchv/go-winloader v0.0.0-20250406163304-c1995be93bd1 h1:njuLRcjAuMKr7kI3D85AXWkw6/+v9PwtV6M6o11sWHQ=
github.com/jchv/go-winloader v0.0.0-20250406163304-c1995be93bd1/go.mod h1:alcuEEnZsY1WQsagKhZDsoPCRoOijYqhZvPwLG0kzVs= github.com/jchv/go-winloader v0.0.0-20250406163304-c1995be93bd1/go.mod h1:alcuEEnZsY1WQsagKhZDsoPCRoOijYqhZvPwLG0kzVs=
github.com/labstack/echo/v4 v4.13.4 h1:oTZZW+T3s9gAu5L8vmzihV7/lkXGZuITzTQkTEhcXEA= github.com/labstack/echo/v4 v4.13.4 h1:oTZZW+T3s9gAu5L8vmzihV7/lkXGZuITzTQkTEhcXEA=
@@ -33,14 +41,16 @@ github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHP
github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8= github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-sqlite3 v1.14.32 h1:JD12Ag3oLy1zQA+BNn74xRgaBbdhbNIDYvQUEuuErjs= github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
github.com/mattn/go-sqlite3 v1.14.32/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y= github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ= github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ=
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU= github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ= github.com/rivo/uniseg v0.4.7 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=
@@ -60,24 +70,58 @@ github.com/wailsapp/go-webview2 v1.0.23 h1:jmv8qhz1lHibCc79bMM/a/FqOnnzOGEisLav+
github.com/wailsapp/go-webview2 v1.0.23/go.mod h1:qJmWAmAmaniuKGZPWwne+uor3AHMB5PFhqiK0Bbj8kc= github.com/wailsapp/go-webview2 v1.0.23/go.mod h1:qJmWAmAmaniuKGZPWwne+uor3AHMB5PFhqiK0Bbj8kc=
github.com/wailsapp/mimetype v1.4.1 h1:pQN9ycO7uo4vsUUuPeHEYoUkLVkaRntMnHJxVwYhwHs= github.com/wailsapp/mimetype v1.4.1 h1:pQN9ycO7uo4vsUUuPeHEYoUkLVkaRntMnHJxVwYhwHs=
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.11.0 h1:seLacV8pqupq32IjS4Y7V8ucab0WZwtK6VvUVxSBtqQ= github.com/wailsapp/wails/v2 v2.12.0 h1:BHO/kLNWFHYjCzucxbzAYZWUjub1Tvb4cSguQozHn5c=
github.com/wailsapp/wails/v2 v2.11.0/go.mod h1:jrf0ZaM6+GBc1wRmXsM8cIvzlg0karYin3erahI4+0k= github.com/wailsapp/wails/v2 v2.12.0/go.mod h1:mo1bzK1DEJrobt7YrBjgxvb5Sihb1mhAY09hppbibQg=
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/go.mod h1:swjeQEj+6r7fODbD2cqrnje9PnziFuw4bmLbBZFrQ5w=
golang.org/x/net v0.0.0-20210505024714-0287a6fb4125/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20210505024714-0287a6fb4125/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY= golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY=
golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU= golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU=
golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.0.0-20200810151505-1b9f1253b3ed/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200810151505-1b9f1253b3ed/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc= golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=
golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.31.0 h1:aC8ghyu4JhP8VojJ2lEHBnochRno1sgL6nEi9WGFGMM= golang.org/x/text v0.31.0 h1:aC8ghyu4JhP8VojJ2lEHBnochRno1sgL6nEi9WGFGMM=
golang.org/x/text v0.31.0/go.mod h1:tKRAlv61yKIjGGHX/4tP1LTbc13YSec1pxVEWXzfoeM= golang.org/x/text v0.31.0/go.mod h1:tKRAlv61yKIjGGHX/4tP1LTbc13YSec1pxVEWXzfoeM=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.42.0 h1:uNgphsn75Tdz5Ji2q36v/nsFSfR/9BRFvqhGBaJGd5k=
golang.org/x/tools v0.42.0/go.mod h1:Ma6lCIwGZvHK6XtgbswSoWroEkhugApmsXyrUmBhfr0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
modernc.org/cc/v4 v4.28.2 h1:3tQ0lf2ADtoby2EtSP+J7IE2SHwEJdP8ioR59wx7XpY=
modernc.org/cc/v4 v4.28.2/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI=
modernc.org/ccgo/v4 v4.34.0 h1:yRLPFZieg532OT4rp4JFNIVcquwalMX26G95WQDqwCQ=
modernc.org/ccgo/v4 v4.34.0/go.mod h1:AS5WYMyBakQ+fhsHhtP8mWB82KTGPkNNJDGfGQCe0/A=
modernc.org/fileutil v1.4.0 h1:j6ZzNTftVS054gi281TyLjHPp6CPHr2KCxEXjEbD6SM=
modernc.org/fileutil v1.4.0/go.mod h1:EqdKFDxiByqxLk8ozOxObDSfcVOv/54xDs/DUHdvCUU=
modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI=
modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito=
modernc.org/gc/v3 v3.1.2 h1:ZtDCnhonXSZexk/AYsegNRV1lJGgaNZJuKjJSWKyEqo=
modernc.org/gc/v3 v3.1.2/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY=
modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks=
modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI=
modernc.org/libc v1.72.3 h1:ZnDF4tXn4NBXFutMMQC4vtbTFSXhhKzR73fv0beZEAU=
modernc.org/libc v1.72.3/go.mod h1:dn0dZNnnn1clLyvRxLxYExxiKRZIRENOfqQ8XEeg4Qs=
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI=
modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
modernc.org/opt v0.2.0 h1:tGyef5ApycA7FSEOMraay9SaTk5zmbx7Tu+cJs4QKZg=
modernc.org/opt v0.2.0/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=
modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=
modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=
modernc.org/sqlite v1.50.1 h1:l+cQvn0sd0zJJtfygGHuQJ5AjlrwXmWPw4KP3ZMwr9w=
modernc.org/sqlite v1.50.1/go.mod h1:tcNzv5p84E0skkmJn038y+hWJbLQXQqEnQfeh5r2JLM=
modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=
modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=
-54
View File
@@ -1,54 +0,0 @@
# Building Extractor Binary
This guide explains how to build the `extractor` binary from `twitter_cli.py`.
## Quick Start - Use Pre-built Binary
**You don't need to build the binary yourself!** After running the main application once, the pre-built binary is automatically extracted to:
```
Windows: C:\Users\YourUsername\.twitterxmediabatchdownloader\extractor.exe
Linux: ~/.twitterxmediabatchdownloader/extractor
macOS: ~/.twitterxmediabatchdownloader/extractor
```
You can use this binary directly for CLI operations without rebuilding.
### Using the Pre-built Binary
```powershell
# Windows
C:\Users\YourUsername\.twitterxmediabatchdownloader\extractor.exe https://x.com/username/media --limit 10 --json --guest
# Linux/macOS
~/.twitterxmediabatchdownloader/extractor https://x.com/username/media --limit 10 --json --guest
```
---
## Building from Source (Optional)
If you need to rebuild the binary (e.g., after modifying `twitter_cli.py`):
### Prerequisites
```bash
pip install pyinstaller
# or
pip install nuitka
```
### Build Commands
```bash
# PyInstaller (faster build, larger file)
pyinstaller --onefile --name extractor --collect-all gallery_dl twitter_cli.py
# Nuitka (slower build, better performance, smaller file)
python -m nuitka --onefile --output-filename=extractor.exe --include-package=gallery_dl --include-package-data=gallery_dl twitter_cli.py
```
### Output Location
- PyInstaller: `dist/extractor` or `dist/extractor.exe`
- Nuitka: `extractor` or `extractor.exe` (in current directory)
-275
View File
@@ -1,275 +0,0 @@
# Usage Guide
CLI tool for extracting media and metadata from Twitter/X using gallery-dl extractor.
## Command Line Arguments
### Required
- `url` — Twitter/X URL (timeline, media, likes, search, etc.)
- `--auth-token TOKEN` — Your auth_token cookie value (required)
### Content Options
- `--retweets {skip|include|original}` — Control retweets (default: skip)
- `--no-videos` — Skip video downloads
- `--text-tweets` — Include tweets without media
- `--type {photo|video|animated_gif|all}` — Filter by media type (default: all)
### Quality & Format
- `--size SIZE` — Image size: `orig`, `4096x4096`, `large`, `medium`, `small` (default: orig)
### Fetch Control
- `--limit N` — Maximum media items to fetch (0 = unlimited)
- `--cursor CURSOR` — Resume from specific cursor position
### Output Options
- `--json` — Output results as JSON
- `--metadata` — Include tweet metadata (author, counts, etc.)
- `--output FILE` / `-o FILE` — Save to JSON file with resume capability
- `--resume FILE` / `-r FILE` — Resume from previous JSON file
- `--progress` — Show progress during fetch
### Advanced
- `--set KEY=VALUE` — Set gallery-dl extractor options (repeatable)
- `-v` / `--verbose` — Show detailed metadata during fetch
---
## Usage Examples
### Basic Fetch
```powershell
# Fetch media with authentication
python twitter_cli.py https://x.com/username/media --limit 10 --json --auth-token YOUR_TOKEN
```
### Media Type Filtering
```powershell
# Photos only
python twitter_cli.py https://x.com/username/media --type photo --json --auth-token YOUR_TOKEN
# Videos only
python twitter_cli.py https://x.com/username/media --type video --json --auth-token YOUR_TOKEN
# Animated GIFs only
python twitter_cli.py https://x.com/username/media --type animated_gif --json --auth-token YOUR_TOKEN
```
### With Metadata
```powershell
# Include tweet metadata (author, date, counts)
python twitter_cli.py https://x.com/username/media --limit 5 --json --metadata --auth-token YOUR_TOKEN
```
### Retweets Control
```powershell
# Skip retweets (default)
python twitter_cli.py https://x.com/username/timeline --retweets skip --json --auth-token YOUR_TOKEN
# Include retweets
python twitter_cli.py https://x.com/username/timeline --retweets include --json --auth-token YOUR_TOKEN
# Get original tweet from retweets
python twitter_cli.py https://x.com/username/timeline --retweets original --json --auth-token YOUR_TOKEN
```
### Save & Resume
```powershell
# Save to file (with resume capability)
python twitter_cli.py https://x.com/username/media --limit 100 --output results.json --progress --auth-token YOUR_TOKEN
# Resume from saved file
python twitter_cli.py https://x.com/username/media --resume results.json --limit 100 --output results.json --auth-token YOUR_TOKEN
# Fetch all remaining
python twitter_cli.py https://x.com/username/media --resume results.json --limit 0 --output results.json --auth-token YOUR_TOKEN
```
### Private Content
```powershell
# Your likes
python twitter_cli.py https://x.com/username/likes --limit 20 --json --auth-token YOUR_TOKEN
# Your bookmarks
python twitter_cli.py https://x.com/i/bookmarks --limit 20 --json --auth-token YOUR_TOKEN
```
### Search
```powershell
# Search with filters
python twitter_cli.py "https://x.com/search?q=from:username filter:media" --limit 50 --json --auth-token YOUR_TOKEN
# Date range search
python twitter_cli.py "https://x.com/search?q=from:username since:2024-01-01 until:2024-12-31" --json --auth-token YOUR_TOKEN
```
### Advanced Filtering
```powershell
# Filter by date (2024 only)
python twitter_cli.py https://x.com/username/media --json --metadata --set filter="date.year == 2024" --auth-token YOUR_TOKEN
# Filter by engagement (>1000 likes)
python twitter_cli.py https://x.com/username/media --json --metadata --set filter="favorite_count > 1000" --auth-token YOUR_TOKEN
# Combine filters (photos from 2024 with >100 likes)
python twitter_cli.py https://x.com/username/media --type photo --json --metadata --set filter="date.year == 2024 and favorite_count > 100" --auth-token YOUR_TOKEN
```
### Text-Only Tweets
```powershell
# Fetch tweets without media
python twitter_cli.py https://x.com/username/tweets --text-tweets --json --metadata --auth-token YOUR_TOKEN
```
---
## Output Format
### JSON Structure
```json
{
"media": [
{
"url": "https://pbs.twimg.com/media/...",
"tweet_id": 1234567890,
"extension": "jpg",
"width": 2048,
"height": 1536,
"type": "photo"
}
],
"metadata": [
{
"tweet_id": 1234567890,
"date": "2024-01-15T10:30:00+00:00",
"author": {
"id": 123456,
"name": "username",
"nick": "Display Name"
},
"content": "Tweet text content",
"favorite_count": 150,
"retweet_count": 25,
"reply_count": 5,
"view_count": 5000
}
],
"cursor": "1/DAABCgABG7OZH1D___0KAAIW...",
"total": 100,
"completed": false
}
```
### Resume File Structure
When using `--output`, the file includes:
- `url` — Original URL
- `cursor` — Position for resume
- `total` — Total items fetched
- `completed` — Whether fetch is complete
- `media` — All media items
- `metadata` — All metadata (if requested)
---
## Pagination & Resume
### How It Works
- Twitter API returns ~100-200 items per batch
- Cursor tracks position for next fetch
- System ensures cursor availability before stopping
- Resume continues from exact position (no duplicates)
### Resume Workflow
```powershell
# Step 1: Initial fetch (saves state)
python twitter_cli.py https://x.com/user/media --limit 100 --output data.json --progress --auth-token YOUR_TOKEN
# Output: Saved 202 media to data.json [partial (can resume)]
# Step 2: Resume and fetch more
python twitter_cli.py https://x.com/user/media --resume data.json --limit 100 --output data.json --auth-token YOUR_TOKEN
# Output: Resuming from cursor, 202 media already fetched
# Added 100 new media (total: 302)
# Step 3: Fetch all remaining
python twitter_cli.py https://x.com/user/media --resume data.json --limit 0 --output data.json --auth-token YOUR_TOKEN
# Output: Added 244 new media (total: 546) [completed]
```
---
## Supported URL Patterns
### User Timelines
- `https://x.com/username/media` — Media timeline
- `https://x.com/username/timeline` — Full timeline
- `https://x.com/username/tweets` — Tweets only
- `https://x.com/username/with_replies` — With replies
- `https://x.com/username/likes` — Liked tweets
### Private Content
- `https://x.com/i/bookmarks` — Your bookmarks
### Search
- `https://x.com/search?q=QUERY` — Search tweets
- `https://x.com/hashtag/NAME` — Hashtag search
### Individual Tweet
- `https://x.com/username/status/1234567890` — Single tweet
---
## Search Operators
Use in search URLs:
| Operator | Example | Description |
|----------|---------|-------------|
| `from:USER` | `from:username` | Tweets from user |
| `to:USER` | `to:username` | Tweets mentioning user |
| `filter:media` | `cats filter:media` | Only with media |
| `filter:images` | `cats filter:images` | Only images |
| `filter:videos` | `cats filter:videos` | Only videos |
| `since:DATE` | `since:2024-01-01` | After date |
| `until:DATE` | `until:2024-12-31` | Before date |
| `-filter:retweets` | `cats -filter:retweets` | Exclude retweets |
| `min_faves:N` | `min_faves:1000` | Min likes |
| `min_retweets:N` | `min_retweets:100` | Min retweets |
---
## Tips & Tricks
### 1. Progressive Fetch with Resume
```powershell
# Fetch in batches to avoid long waits
python twitter_cli.py URL --limit 200 --output data.json --progress --auth-token YOUR_TOKEN
python twitter_cli.py URL --resume data.json --limit 200 --output data.json --auth-token YOUR_TOKEN
```
### 2. Combine Type Filter with Custom Filter
```powershell
# Photos from 2024 with high engagement
python twitter_cli.py URL --type photo --metadata --set filter="date.year == 2024 and favorite_count > 500" --json --auth-token YOUR_TOKEN
```
### 3. Use Progress Flag for Long Fetches
```powershell
python twitter_cli.py URL --limit 1000 --progress --output data.json --auth-token YOUR_TOKEN
```
### 4. Check Cursor Availability
- If `completed: false` in output → can resume
- If `completed: true` → all data fetched
- If `cursor: null` → no more data available
-309
View File
@@ -1,309 +0,0 @@
"""Command-line helper for gallery-dl's Twitter extractor.
Features:
- Cursor-based resume: Use --output to save progress, --resume to continue
- Progress tracking: See fetch progress in real-time
- Rate limit: Automatically handled by gallery-dl
"""
from __future__ import annotations
import argparse
import json
import os
import sys
from typing import Dict, List, Optional
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from twitter_common import ( # type: ignore
TwitterRequest,
coerce_literal,
load_resume_state,
merge_options,
run_request_dict,
save_state,
)
DEFAULT_AUTH_TOKEN = ""
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Light-weight CLI wrapper around gallery-dl's Twitter extractor",
)
parser.add_argument("url", help="Any supported Twitter/X URL (timeline, media, likes, ...)")
parser.add_argument(
"--auth-token",
default=DEFAULT_AUTH_TOKEN,
help="Value of the auth_token cookie (leave empty to skip)",
)
parser.add_argument(
"--guest",
action="store_true",
help="Force guest mode (do not send auth_token)",
)
parser.add_argument(
"--retweets",
choices=["skip", "include", "original"],
default="skip",
help="Control retweet handling (skip, include, or swap for originals)",
)
parser.add_argument(
"--no-videos",
action="store_true",
help="Skip video/animated GIF variants",
)
parser.add_argument(
"--size",
default="orig",
help="Image size to request (orig, 4096x4096, large, ...)",
)
parser.add_argument(
"--limit",
type=int,
default=0,
help="Stop after N media files (0 = all)",
)
parser.add_argument(
"--json",
action="store_true",
help="Emit JSON instead of plain URLs",
)
parser.add_argument(
"--metadata",
action="store_true",
help="Include tweet metadata in output",
)
parser.add_argument(
"--text-tweets",
action="store_true",
help="Include text tweets (without media)",
)
parser.add_argument(
"--type",
choices=["photo", "video", "animated_gif", "all"],
default="all",
help="Filter by media type (photo, video, animated_gif, or all)",
)
parser.add_argument(
"--verbose",
"-v",
action="store_true",
help="Echo tweet metadata to stderr while crawling",
)
parser.add_argument(
"--set",
metavar="KEY=VALUE",
action="append",
default=[],
help="Add override for extractor.twitter.* options (repeatable)",
)
parser.add_argument(
"--output",
"-o",
metavar="FILE",
help="Save results to JSON file (includes cursor for resume)",
)
parser.add_argument(
"--resume",
"-r",
metavar="FILE",
help="Resume from previous JSON file (continues from saved cursor)",
)
parser.add_argument(
"--cursor",
metavar="CURSOR",
help="Resume from specific cursor position",
)
parser.add_argument(
"--progress",
action="store_true",
help="Show progress during fetch",
)
return parser.parse_args()
def _retweets_value(mode: str):
if mode == "original":
return "original"
if mode == "include":
return True
return False
def _parse_overrides(entries: List[str]) -> Dict[str, object]:
overrides: Dict[str, object] = {}
for entry in entries:
if "=" not in entry:
raise ValueError(f"Format must be KEY=VALUE, got: {entry}")
key, raw = entry.split("=", 1)
overrides[key.strip()] = coerce_literal(raw.strip())
return overrides
def _progress_callback(count: int, cursor: Optional[str]) -> None:
"""Print progress to stderr."""
cursor_info = f" (cursor: {cursor[:20]}...)" if cursor and len(cursor) > 20 else ""
cursor_info = f" (cursor: {cursor})" if cursor and len(cursor) <= 20 else cursor_info
print(f"Fetching... {count} media{cursor_info}", file=sys.stderr)
def main() -> None:
args = parse_args()
# Handle resume from file
resume_cursor: Optional[str] = None
previous_media: List[Dict] = []
previous_metadata: List[Dict] = []
seen_urls: set = set()
url = args.url
# Convert --type to filter expression
type_filter = None
if args.type != "all":
type_filter = f"type == '{args.type}'"
if args.resume:
state = load_resume_state(args.resume)
if state:
if state.get("completed"):
print(f"Previous fetch already completed ({state.get('total', 0)} media)", file=sys.stderr)
print("Use --output to start fresh or remove the file", file=sys.stderr)
sys.exit(0)
resume_cursor = state.get("cursor")
previous_media = state.get("media", [])
previous_metadata = state.get("metadata", [])
# Track seen URLs to avoid duplicates
seen_urls = {m.get("url") for m in previous_media if m.get("url")}
url = state.get("url", args.url)
if resume_cursor:
print(f"Resuming from cursor, {len(previous_media)} media already fetched", file=sys.stderr)
else:
print(f"No cursor available, will deduplicate {len(previous_media)} existing media", file=sys.stderr)
else:
print(f"Could not load resume file: {args.resume}", file=sys.stderr)
sys.exit(1)
# Manual cursor override
if args.cursor:
resume_cursor = args.cursor
include_videos = not args.no_videos
auth_token = None if args.guest or not args.auth_token.strip() else args.auth_token
# Parse user overrides
user_overrides = _parse_overrides(args.set)
# Add type filter if specified (merge with existing filter if any)
if type_filter:
existing_filter = user_overrides.get("filter")
if existing_filter:
# Combine with AND
user_overrides["filter"] = f"({existing_filter}) and ({type_filter})"
else:
user_overrides["filter"] = type_filter
options = merge_options(
{
"auth_token": auth_token,
"retweets": _retweets_value(args.retweets),
"videos": include_videos,
"size": args.size,
"text-tweets": args.text_tweets,
},
user_overrides,
)
request = TwitterRequest(
url=url,
limit=args.limit,
metadata=(args.metadata or args.verbose),
options=options,
cursor=resume_cursor,
)
progress_cb = _progress_callback if (args.progress or args.verbose) else None
# Pass seen_urls for deduplication if no cursor available
skip_urls = seen_urls if (not resume_cursor and seen_urls) else None
try:
result = run_request_dict(request, on_progress=progress_cb, skip_urls=skip_urls)
except KeyboardInterrupt:
print("\nInterrupted by user", file=sys.stderr)
sys.exit(130)
except Exception as exc:
print(f"Error: {exc}", file=sys.stderr)
sys.exit(1)
# Merge with previous results if resuming
if previous_media:
if resume_cursor:
# With cursor: filter duplicates that might occur at boundary
new_media = [m for m in result["media"] if m.get("url") not in seen_urls]
result["media"] = previous_media + new_media
result["metadata"] = previous_metadata + result["metadata"]
else:
# Without cursor: results already deduplicated via skip_urls
result["media"] = previous_media + result["media"]
result["metadata"] = previous_metadata + result["metadata"]
result["total"] = len(result["media"])
new_count = result["total"] - len(previous_media)
if new_count > 0:
print(f"Added {new_count} new media (total: {result['total']})", file=sys.stderr)
else:
print(f"No new media found", file=sys.stderr)
media = result["media"]
metadata = result["metadata"]
# Save to file if --output specified
if args.output:
save_state(args.output, result, url)
status = "completed" if result.get("completed") else "partial (can resume)"
print(f"Saved {len(media)} media to {args.output} [{status}]", file=sys.stderr)
if not result.get("completed") and result.get("cursor"):
print(f"Resume with: --resume {args.output}", file=sys.stderr)
if args.verbose:
for entry in metadata:
author = (entry.get("author") or {}).get("name")
print(
f"Processing tweet {entry.get('tweet_id')} / {author}",
file=sys.stderr,
)
if args.json:
payload: Dict[str, object] = {
"media": media,
"total": len(media),
"completed": result.get("completed", True),
}
if result.get("cursor"):
payload["cursor"] = result["cursor"]
if args.metadata:
payload["metadata"] = metadata
print(json.dumps(payload, indent=2, default=str))
else:
for item in media:
print(item["url"])
if args.metadata:
print("\n# Metadata", file=sys.stderr)
for entry in metadata:
print(
f"{entry['tweet_id']}: {entry['content']}",
file=sys.stderr,
)
# Print summary
print(f"\nTotal: {len(media)} media", file=sys.stderr)
if not result.get("completed") and result.get("cursor"):
print(f"Cursor for resume: {result['cursor']}", file=sys.stderr)
if __name__ == "__main__":
main()
-342
View File
@@ -1,342 +0,0 @@
"""Shared abstraction for all Twitter gallery-dl examples.
This file provides utility functions that build gallery-dl configuration
based on parameters in ``twitter-parameters.md`` and execute the Twitter
extractor in a single run. All four interfaces (direct module, CLI, FastAPI, and
Flask) rely on this module to ensure consistent behavior.
Features:
- Cursor-based resume: Save progress and continue from where you left off
- Progress tracking: Monitor fetch progress in real-time
- Rate limit handling: Automatically handled by gallery-dl
"""
from __future__ import annotations
import json
import os
import sys
import threading
from dataclasses import dataclass, field
from datetime import date, datetime
from typing import Any, Callable, Dict, Iterable, List, MutableMapping, Optional
REPO_ROOT = os.path.dirname(os.path.abspath(__file__))
if REPO_ROOT not in sys.path:
sys.path.append(REPO_ROOT)
from gallery_dl import config, extractor as extractor_mod # type: ignore
from gallery_dl.extractor.common import Message # type: ignore
_CONFIG_LOCK = threading.Lock()
# Internal keys that should not be directly passed to extractor config.
_INTERNAL_KEYS = {
"url",
"limit",
"metadata",
"options",
"auth_token",
"guest",
"cookies",
"cursor",
}
@dataclass
class TwitterRequest:
"""Standard request structure for all frontends."""
url: str
options: Dict[str, Any] = field(default_factory=dict)
limit: int = 0
metadata: bool = False
cursor: Optional[str] = None # Resume from this cursor position
@dataclass
class TwitterResult:
"""Result structure with cursor for resume capability."""
media: List[Dict[str, Any]]
metadata: List[Dict[str, Any]]
cursor: Optional[str] = None # Cursor to resume from
total: int = 0
completed: bool = True # False if stopped before completion
def _serialize_value(value: Any) -> Any:
if isinstance(value, (datetime, date)):
return value.isoformat()
if isinstance(value, set):
return sorted(value)
return value
def _extract_tweet_metadata(data: MutableMapping[str, Any]) -> Dict[str, Any]:
keys = (
"tweet_id",
"retweet_id",
"quote_id",
"reply_id",
"conversation_id",
"date",
"author",
"content",
"lang",
"hashtags",
"mentions",
"sensitive",
"sensitive_flags",
"favorite_count",
"retweet_count",
"quote_count",
"reply_count",
"bookmark_count",
"view_count",
)
meta = {key: _serialize_value(data.get(key)) for key in keys}
if isinstance(meta["author"], dict):
meta["author"] = {
"id": meta["author"].get("id"),
"name": meta["author"].get("name"),
"nick": meta["author"].get("nick"),
}
elif isinstance(meta["author"], str):
# Handle case where author is just a string (username)
meta["author"] = {
"id": None,
"name": meta["author"],
"nick": meta["author"],
}
else:
# Handle None or other types
meta["author"] = {
"id": None,
"name": None,
"nick": None,
}
return meta
def _clean_file_metadata(meta: MutableMapping[str, Any]) -> Dict[str, Any]:
return {key: _serialize_value(value) for key, value in meta.items()}
def _apply_options(options: Dict[str, Any], cursor: Optional[str] = None) -> None:
"""Reset config and apply all extractor options."""
config.clear()
cookies = options.get("cookies")
auth_token = options.get("auth_token")
if auth_token:
cookies = dict(cookies or {})
cookies["auth_token"] = auth_token
if cookies:
config.set(("extractor", "twitter"), "cookies", cookies)
# Enable cursor tracking, or set specific cursor for resume
if cursor:
config.set(("extractor", "twitter"), "cursor", cursor)
else:
config.set(("extractor", "twitter"), "cursor", True)
for key, value in options.items():
if key in _INTERNAL_KEYS or value is None:
continue
config.set(("extractor", "twitter"), key, value)
def run_request(
request: TwitterRequest,
on_progress: Optional[Callable[[int, Optional[str]], None]] = None,
skip_urls: Optional[set] = None,
ensure_cursor: bool = True,
) -> TwitterResult:
"""Run Twitter extractor and return media & metadata results.
Args:
request: The TwitterRequest configuration
on_progress: Optional callback(count, cursor) called periodically during fetch
skip_urls: Optional set of URLs to skip (for resume/deduplication)
ensure_cursor: If True, continue fetching until cursor is available (for reliable resume)
Returns:
TwitterResult with media, metadata, cursor for resume, and completion status
"""
skip_urls = skip_urls or set()
with _CONFIG_LOCK:
_apply_options(request.options, request.cursor)
extractor = extractor_mod.find(request.url)
if extractor is None or extractor.category != "twitter":
raise ValueError(f"URL not recognized by Twitter extractor: {request.url}")
media: List[Dict[str, Any]] = []
metadata: List[Dict[str, Any]] = []
collected = 0
skipped = 0
last_cursor: Optional[str] = None
last_tweet_id: Optional[int] = None
completed = True
limit_reached = False
try:
for message in extractor:
mtype = message[0]
if mtype is Message.Directory and request.metadata:
# Only extract metadata if message[1] is a dict
if isinstance(message[1], dict):
metadata.append(_extract_tweet_metadata(message[1]))
elif mtype is Message.Url:
url = message[1]
# Skip if already seen
if url in skip_urls:
skipped += 1
continue
file_meta = _clean_file_metadata(message[2])
# Apply client-side filter if specified
# Note: gallery-dl's filter only works for downloads, not message iteration
filter_expr = request.options.get("filter")
if filter_expr:
try:
# Create evaluation context with file metadata
eval_context = {**file_meta}
# Add common functions that might be used in filters
eval_context['datetime'] = datetime
eval_context['date'] = date
# Evaluate filter expression
if not eval(filter_expr, {"__builtins__": {}}, eval_context):
continue # Skip this item
except Exception as e:
# If filter evaluation fails, include the item (fail-open)
pass
media.append({"url": url, **file_meta})
collected += 1
# Track last tweet_id for progress display
if "tweet_id" in file_meta:
last_tweet_id = file_meta["tweet_id"]
# Try to get cursor from extractor
if hasattr(extractor, '_cursor') and extractor._cursor:
last_cursor = extractor._cursor
# Report progress every 10 items
if on_progress and collected % 10 == 0:
on_progress(collected, last_cursor)
# Check if limit reached
if request.limit and collected >= request.limit:
if ensure_cursor and not last_cursor:
# Continue until cursor is available for reliable resume
limit_reached = True
continue
completed = False # Stopped due to limit
break
# If we were waiting for cursor and now have it, stop
if limit_reached and last_cursor:
completed = False
break
except KeyboardInterrupt:
completed = False
finally:
# Get final cursor from extractor
if hasattr(extractor, '_cursor') and extractor._cursor:
last_cursor = extractor._cursor
return TwitterResult(
media=media,
metadata=metadata,
cursor=last_cursor,
total=collected,
completed=completed,
)
def run_request_dict(
request: TwitterRequest,
on_progress: Optional[Callable[[int, Optional[str]], None]] = None,
skip_urls: Optional[set] = None,
ensure_cursor: bool = True,
) -> Dict[str, Any]:
"""Run request and return as dictionary (for JSON serialization)."""
result = run_request(request, on_progress, skip_urls, ensure_cursor)
return {
"media": result.media,
"metadata": result.metadata,
"cursor": result.cursor,
"total": result.total,
"completed": result.completed,
}
def load_resume_state(filepath: str) -> Optional[Dict[str, Any]]:
"""Load previous state from JSON file for resume."""
if not os.path.exists(filepath):
return None
try:
with open(filepath, "r", encoding="utf-8") as f:
data = json.load(f)
return data
except (json.JSONDecodeError, IOError):
return None
def save_state(filepath: str, result: Dict[str, Any], url: str) -> None:
"""Save current state to JSON file."""
state = {
"url": url,
"cursor": result.get("cursor"),
"total": result.get("total", len(result.get("media", []))),
"completed": result.get("completed", True),
"media": result.get("media", []),
"metadata": result.get("metadata", []),
}
with open(filepath, "w", encoding="utf-8") as f:
json.dump(state, f, indent=2, default=str)
def merge_options(*sources: Optional[Dict[str, Any]]) -> Dict[str, Any]:
"""Merge multiple configuration dicts (None values ignored)."""
merged: Dict[str, Any] = {}
for source in sources:
if not source:
continue
for key, value in source.items():
merged[key] = value
return merged
def coerce_literal(value: str) -> Any:
"""Infer basic type from CLI argument string."""
lowered = value.lower()
if lowered in {"true", "false"}:
return lowered == "true"
if lowered in {"null", "none"}:
return None
try:
return int(value)
except ValueError:
pass
try:
return float(value)
except ValueError:
pass
if (value.startswith("[") and value.endswith("]")) or (
value.startswith("{") and value.endswith("}")
):
try:
return json.loads(value)
except json.JSONDecodeError:
return value
return value
+1 -2
View File
@@ -14,10 +14,9 @@ import (
var assets embed.FS var assets embed.FS
func main() { func main() {
// Create an instance of the app structure
app := NewApp() app := NewApp()
// Create application with options
err := wails.Run(&options.App{ err := wails.Run(&options.App{
Title: "Twitter/X Media Batch Downloader", Title: "Twitter/X Media Batch Downloader",
Width: 1024, Width: 1024,
+1 -1
View File
@@ -11,7 +11,7 @@
}, },
"info": { "info": {
"productName": "Twitter/X Media Batch Downloader", "productName": "Twitter/X Media Batch Downloader",
"productVersion": "4.2" "productVersion": "4.4"
}, },
"wailsjsdir": "./frontend", "wailsjsdir": "./frontend",
"assetdir": "./frontend/dist", "assetdir": "./frontend/dist",