Compare commits

...
92 Commits
Author SHA1 Message Date
Alvin-Zilverstand 6964753e3e f 2026-09-21 15:37:24 +02:00
afkarxyz 9c269bc8f2 v5.0.1 2026-08-18 07:51:56 +07:00
afkarxyz 70f5088574 Update README 2026-08-18 06:28:13 +07:00
afkarxyz 1f378bb356 v5.0.0 2026-07-29 14:59:28 +07:00
afkarxyz 492a318399 Update README 2026-07-16 18:41:16 +07:00
afkarxyz 2ada5da9bf v4.9 2026-07-16 18:27:23 +07:00
afkarxyz 3fb8bda2ff Update README 2026-07-15 12:26:49 +07:00
asdfghjkkly b4dfb75f5b Fix group editing and skip existing downloads (#105) 2026-07-12 10:59:29 +07:00
afkarxyz 7e584aff2c Update README 2026-07-12 10:58:42 +07:00
afkarxyz 76acb6f5e1 v4.8 2026-07-05 19:09:54 +07:00
afkarxyz 6bd03678f8 Merge pull request #103 from asdfghjkkly/fix-windows-folder-and-reposts
Fix repost folder routing and Windows folder opening
2026-07-05 17:00:37 +07:00
asdfghjkkly e400df6ea7 Fix repost folder routing and Windows folder opening 2026-07-05 05:41:36 -04:00
afkarxyz 52ffa5ba17 Update README 2026-06-22 14:31:56 +07:00
429Enjoyer c42808431c v4.7 2026-06-22 14:08:53 +07:00
429Enjoyer e05a9379fc v4.6 2026-05-19 14:28:05 +07:00
afkarxyz 33be717065 Update README 2026-05-19 14:26:35 +07:00
429Enjoyer c3ae949a38 Update README 2026-05-13 08:56:18 +07:00
429Enjoyer e67d09a248 v4.5 2026-05-13 08:49:42 +07:00
afkarxyz 84b067ebd4 Update README 2026-05-13 08:40:23 +07:00
afkarxyz eba8288a4e Update README 2026-05-12 11:28:56 +07:00
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
afkarxyz 30bcf3db9f v4.2 2025-12-17 10:07:49 +07:00
afkarxyz ada11f086e v4.2 2025-12-17 10:05:32 +07:00
afkarxyz b4266cb7fa Ko-fi 2025-12-17 04:58:29 +07:00
afkarxyz aa87cce538 v4.1 2025-12-11 22:17:57 +07:00
afkarxyz 2d913d987f v4.1 2025-12-11 22:14:01 +07:00
afkarxyz 3abba4cc59 v4.0 2025-12-05 06:12:04 +07:00
afkarxyz 6417e73da4 v4.0 2025-12-05 05:02:00 +07:00
afkarxyz 280133649d v4.0 2025-12-05 05:00:51 +07:00
afkarxyz 8e5f18c6cc v3.9 2025-11-29 06:50:36 +07:00
afkarxyz 312b6b2c50 v3.9 2025-11-29 06:46:11 +07:00
afkarxyz 671209714b v3.8
v3.8
2025-11-18 14:17:00 +07:00
afkarxyz bc450ff204 v3.8 2025-11-18 13:55:25 +07:00
afkarxyz 1ace435160 v3.8 2025-11-18 13:43:57 +07:00
afkarxyz df0de054c8 v3.8 2025-11-18 13:38:16 +07:00
afkarxyz f2a3810c8c v3.7 2025-10-05 20:09:30 +07:00
afkarxyz 549d8fde60 Update README.md 2025-10-05 20:07:17 +07:00
afkarxyz 64bd8b4b2d v3.7 2025-10-05 19:58:57 +07:00
afkarxyz 0f2427ad2b Chrome extension 2025-09-20 07:07:17 +07:00
afkarxyz 05e8230063 Update README.md 2025-09-14 16:11:32 +07:00
afkarxyz 83672f42b6 v3.6 2025-09-14 07:52:14 +07:00
afkarxyz affd36c968 v3.6 2025-09-14 07:45:19 +07:00
afkarxyz 281ea82656 Update README.md 2025-09-14 07:32:12 +07:00
afkarxyz aa003fab4c Update README.md 2025-09-14 07:30:12 +07:00
afkarxyz 805fade0fb v3.5 2025-09-11 22:31:16 +07:00
afkarxyz dacf6f5a01 v3.5 2025-09-11 22:24:40 +07:00
afkarxyz fe095afb38 v3.4 2025-08-08 16:35:38 +07:00
afkarxyz e769ea8d20 v3.4 2025-08-08 15:51:32 +07:00
afkarxyz befe838e79 v3.4 2025-08-08 15:20:30 +07:00
afkarxyz b534bc278e Update README.md 2025-08-08 15:17:31 +07:00
afkarxyz 2e882635eb v3.3 2025-07-31 12:08:25 +07:00
afkarxyz 5d5b778c8e v3.3 2025-07-30 05:26:56 +07:00
afkarxyz 7cf134f681 v3.3 2025-07-30 05:24:47 +07:00
afkarxyz 7d90eb7cb2 v3.3 2025-07-26 21:27:45 +07:00
afkarxyz 3d1fd7d1fb v3.3 2025-07-26 21:11:53 +07:00
afkarxyz c0885b1812 v3.2 2025-07-26 12:34:42 +07:00
afkarxyz 1ca5c613ae Update latest.json 2025-07-26 12:34:32 +07:00
afkarxyz 596ba9bb3c v3.2 2025-07-26 12:33:59 +07:00
afkarxyz a1cbb04402 v3.2 2025-07-26 12:33:58 +07:00
afkarxyz ddf6439893 v3.2 2025-07-26 12:27:48 +07:00
afkarxyz fed2bf7b0c Create latest.json 2025-07-26 12:24:54 +07:00
afkarxyz 241884de89 v3.2 2025-07-26 12:20:20 +07:00
afkarxyz 77b443ace0 v3.2 2025-07-26 11:55:30 +07:00
afkarxyz cd48b6f9bc Update README.md 2025-07-26 11:44:31 +07:00
afkarxyz 6f45b48047 v3.1 2025-07-19 05:45:26 +07:00
afkarxyz 7083c56c8b v3.1 2025-07-19 05:40:26 +07:00
afkarxyz 60cb3cbabd v3.1 2025-07-19 01:06:36 +07:00
afkarxyz b38bff238a . 2025-07-19 01:06:15 +07:00
afkarxyz d4d216ed6b v3.1 2025-07-19 01:04:35 +07:00
afkarxyz 129c007f6f v3.1 2025-07-18 23:42:12 +07:00
afkarxyz d78ad32c09 v3.1 2025-07-18 23:26:33 +07:00
afkarxyz 3975e5dd0e v3.0 2025-07-17 09:54:09 +07:00
afkarxyz 37f1d910cb v3.0 2025-07-14 09:49:50 +07:00
afkarxyz 74ed38cc31 v3.0 2025-07-14 09:24:38 +07:00
afkarxyz 2e326c39a0 v3.0 2025-07-14 09:22:56 +07:00
afkarxyz 39c37d4776 v3.0 2025-07-13 22:04:17 +07:00
afkarxyz 5709d76ceb . 2025-07-13 22:04:00 +07:00
afkarxyz 75b3549653 Update README.md 2025-07-13 21:55:44 +07:00
afkarxyz ebe739e612 Add files via upload 2025-07-13 21:20:26 +07:00
afkarxyz d423f20bad Update README.md 2025-07-13 21:14:28 +07:00
afkarxyz fba8a8ac45 Update README.md 2025-07-13 00:15:58 +07:00
afkarxyz a36c7613d2 Update README.md 2025-07-13 00:07:41 +07:00
afkarxyz c7615ed2f6 Merge pull request #16 from Alvin-Zilverstand/main
feat: Add Linux executable and compilation instructions
2025-07-12 22:12:19 +07:00
afkarxyz 0c17f1b419 Update README.md 2025-07-12 22:09:34 +07:00
Alvin dd38880366 feat: Add Linux executable and compilation instructions 2025-07-11 21:12:40 +02:00
afkarxyz 306d2c3c95 v3.0 2025-07-05 06:16:21 +07:00
afkarxyz 1caa59bbcf v3.0 2025-07-04 13:47:23 +07:00
afkarxyz 4d0021092c v3.0 2025-07-04 13:44:57 +07:00
107 changed files with 22048 additions and 1737 deletions

No files matched your search

+68
View File
@@ -0,0 +1,68 @@
name: Bug Report
description: Report a bug in Twitter/X Media Batch Downloader
title: "[Bug Report] "
labels: ["bug"]
body:
- type: markdown
attributes:
value: |
> **WARNING: Issues that do not follow this template will be deleted without review.**
>
> **Please keep `[Bug Report]` in the issue title and only continue after it.**
- type: textarea
id: problem
attributes:
label: Problem
placeholder: "e.g. Fetching @username/media stops after a few items, or GIF conversion fails with no clear error."
validations:
required: true
- type: input
id: target
attributes:
label: X/Twitter URL or Username
placeholder: "e.g. https://x.com/username/media or @username"
validations:
required: true
- type: textarea
id: steps
attributes:
label: Steps to Reproduce
placeholder: |
1. Open ...
2. Enter ...
3. Click ...
4. See error ...
validations:
required: true
- type: textarea
id: logs
attributes:
label: Error Message / Logs / Screenshot
placeholder: "e.g. failed to extract timeline: parse_error ..."
validations:
required: true
- type: markdown
attributes:
value: "### Environment"
- type: input
id: version
attributes:
label: Twitter/X Media Batch Downloader Version
placeholder: "e.g. v4.4"
validations:
required: true
- type: input
id: os
attributes:
label: OS
placeholder: "e.g. Windows 11 23H2"
validations:
required: true
+1
View File
@@ -0,0 +1 @@
blank_issues_enabled: false
@@ -0,0 +1,34 @@
name: Feature Request
description: Request a feature for Twitter/X Media Batch Downloader
title: "[Feature Request] "
labels: ["enhancement"]
body:
- type: markdown
attributes:
value: |
> **WARNING: Issues that do not follow this template will be deleted without review.**
>
> **Please keep `[Feature Request]` in the issue title and only continue after it.**
- type: textarea
id: description
attributes:
label: Description
placeholder: e.g. Add an option to rotate between multiple auth tokens or export filtered results directly from Saved Accounts.
validations:
required: true
- type: textarea
id: use-case
attributes:
label: Why is this needed?
placeholder: e.g. I manage multiple accounts and want a faster way to retry only failed fetches without re-running the whole batch.
validations:
required: true
- type: textarea
id: additional-context
attributes:
label: Additional Context
placeholder: e.g. Mockup, similar app behavior, workflow notes, or screenshots if needed.
+372
View File
@@ -0,0 +1,372 @@
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 --frozen-lockfile
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 --frozen-lockfile
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 (${{ matrix.display_name }})
runs-on: ${{ matrix.runner }}
strategy:
fail-fast: false
matrix:
include:
- display_name: amd64
runner: ubuntu-24.04
wails_platform: linux/amd64
artifact_name: linux-portable
output_name: TwitterXMediaBatchDownloader.AppImage
appimage_arch: x86_64
appimagetool_arch: x86_64
pkgconfig_dir: /usr/lib/x86_64-linux-gnu/pkgconfig
- display_name: arm64
runner: ubuntu-24.04-arm
wails_platform: linux/arm64
artifact_name: linux-portable-arm
output_name: TwitterXMediaBatchDownloader-ARM.AppImage
appimage_arch: aarch64
appimagetool_arch: aarch64
pkgconfig_dir: /usr/lib/aarch64-linux-gnu/pkgconfig
steps:
- name: Checkout code
uses: actions/checkout@v4
- 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 "${{ matrix.pkgconfig_dir }}/webkit2gtk-4.1.pc" "${{ matrix.pkgconfig_dir }}/webkit2gtk-4.0.pc"
- name: Install Wails CLI
run: go install github.com/wailsapp/wails/v2/cmd/wails@latest
- name: Install frontend dependencies
working-directory: frontend
run: |
pnpm install --frozen-lockfile
pnpm run generate-icon
- name: Build application
run: wails build -platform ${{ matrix.wails_platform }}
- 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-${{ matrix.appimagetool_arch }}-v2
- name: Download appimagetool
if: steps.cache-appimagetool.outputs.cache-hit != 'true'
run: |
wget --timeout=30 --tries=5 --retry-connrefused --waitretry=5 -O appimagetool "https://github.com/AppImage/appimagetool/releases/download/continuous/appimagetool-${{ matrix.appimagetool_arch }}.AppImage" || \
wget --timeout=30 --tries=5 --retry-connrefused --waitretry=5 -O appimagetool "https://github.com/AppImage/appimagetool/releases/download/1.9.1/appimagetool-${{ matrix.appimagetool_arch }}.AppImage"
- name: Make appimagetool executable
run: chmod +x appimagetool
- 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=${{ matrix.appimage_arch }} ./appimagetool --no-appstream AppDir "dist/${{ matrix.output_name }}"
- name: Upload artifacts
uses: actions/upload-artifact@v4
with:
name: ${{ matrix.artifact_name }}
path: dist/${{ matrix.output_name }}
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 AMD64
- `TwitterXMediaBatchDownloader-ARM.AppImage` - Linux ARM64
<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
```
For ARM64:
```bash
chmod +x TwitterXMediaBatchDownloader-ARM.AppImage
./TwitterXMediaBatchDownloader-ARM.AppImage
```
</details>
files: |
artifacts/windows-portable/${{ env.APP_NAME }}.exe
artifacts/macos-portable/${{ env.APP_NAME }}.dmg
artifacts/linux-portable/${{ env.APP_NAME }}.AppImage
artifacts/linux-portable-arm/${{ env.APP_NAME }}-ARM.AppImage
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+59
View File
@@ -0,0 +1,59 @@
# Wails Build
build/
*.exe
*.dll
*.dylib
*.so
# Wails Generated Files
frontend/wailsjs/
# Go
*.test
*.out
go.work
go.work.sum
# Node / Frontend
node_modules/
frontend/node_modules/
frontend/dist/
frontend/.vite/
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
.pnpm-store/
.npm
.yarn
*.tsbuildinfo
# IDE / Editors
.vscode/
.idea/
*.swp
*.swo
*~
.DS_Store
# OS
Thumbs.db
desktop.ini
# Environment
.env
.env.local
.env.*.local
# Logs
*.log
logs/
# Temporary files
tmp/
temp/
*.tmp
*.bak
*.old
*.bat
+44 -32
View File
@@ -1,53 +1,65 @@
[![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)
![TwitterXMediaBatchDownloader](https://github.com/user-attachments/assets/354d7470-c01c-4aa6-9da1-ea6c42d27330)
<div align="center">
<b>Twitter/X Media Batch Downloader</b> is a GUI tool that allows users to download all media, including images and videos, in their original quality from Twitter/X accounts using <code>gallery-dl</code>
<div align="left">
<h1>Twitter/X Media Batch Downloader</h1>
<p>
Downloads original-quality images and videos from Twitter/X accounts.
</p>
<p>
<a href="https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/stargazers"><img
src="https://img.shields.io/github/stars/afkarxyz/Twitter-X-Media-Batch-Downloader?color=ffcb47&labelColor=black&logo=github&label=Stars" /></a><a
href="https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases"><img
src="https://img.shields.io/github/downloads/afkarxyz/Twitter-X-Media-Batch-Downloader/total?color=22c55e&labelColor=black&logo=github&label=Downloads" /></a><a
href="https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases/latest"><img
src="https://img.shields.io/github/v/release/afkarxyz/Twitter-X-Media-Batch-Downloader?color=8b5cf6&labelColor=black&logo=github&label=Latest%20Release" /></a><a href="https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases/latest"><img
src="https://img.shields.io/badge/Windows-369eff?labelColor=black&logo=data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI1MTIiIGhlaWdodD0iNTEyIiB2aWV3Qm94PSIwIDAgMjAgMjAiPjxwYXRoIGZpbGw9IiNmZmZmZmYiIGZpbGwtcnVsZT0iZXZlbm9kZCIgZD0iTTIwIDEwLjg3M1YyMEw4LjQ3OSAxOC41MzdsLjAwMS03LjY2NEgyMFptLTEzLjEyIDBsLS4wMDEgNy40NjFMMCAxNy40NjF2LTYuNTg4aDYuODhaTTIwIDkuMjczSDguNDhsLS4wMDEtNy44MUwyMCAwdjkuMjczWk02Ljg3OSAxLjY2NmwuMDAxIDcuNjA3SDBWMi41MzlsNi44NzktLjg3M1oiLz48L3N2Zz4=" /></a><a
href="https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases/latest"><img
src="https://img.shields.io/badge/macOS-FFFFFF?labelColor=black&logo=apple&logoColor=white" /></a><a
href="https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases/latest"><img
src="https://img.shields.io/badge/Linux-FCC624?labelColor=black&logo=linux&logoColor=white" /></a>
<br />
<br />
<a href="https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases/latest" target="_blank"><img
src="https://github.com/user-attachments/assets/e95586cb-35ce-4ef7-a6ce-a5a18ebf3b29" alt="Dark"
width="49%" /></a>
<a href="https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases/latest" target="_blank"><img
src="https://github.com/user-attachments/assets/7581ca58-9e15-4dd9-ae45-14c2b8f3f9d6" alt="Light"
width="49%" /></a>
</p>
</div>
## 📥 Download
### [Download](https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases)
- Download the latest version of [TwitterXMediaBatchDownloader](https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases/download/v2.9/TwitterXMediaBatchDownloader.exe)
- If you're familiar with **userscripts**, please install it [here](https://greasyfork.org/en/scripts/523157)
- If you're familiar with userscripts, install it [**here**](https://greasyfork.org/en/scripts/523157)
## ✨ Features
- To install the Chrome extension version, click [**here**](https://chromewebstore.google.com/detail/cboceolmgkoobpfjiojkigmihijfgmdo)
- Powered by `gallery-dl`, similar to `yt-dlp`
- **Bulk download**: Download multiple items at once
- Media-type selection: All (Images + GIFs + Videos) or specific (Images / GIFs / Videos)
- **MP4 → GIF conversion:** Convert downloaded MP4 videos into GIF format
- Downloads at original quality
## 🖼️ Screenshots
- Also available on the web at [**TwitterDL.app**](https://twitterdl.app)
![image](https://github.com/user-attachments/assets/7295213a-d9ba-4d75-8359-d43907b74aef)
## Fetch pacing
![image](https://github.com/user-attachments/assets/67bb51ef-0051-4470-b89b-66f653093543)
Settings includes separate **Fetch Delay** controls: a base delay and a random
extra from zero to the configured value, in seconds. Both default to zero
(disabled). A suggested starting point is 5 seconds base plus up to 5 seconds
extra; this is not a guaranteed safe rate for Twitter/X.
![image](https://github.com/user-attachments/assets/27138746-cd60-41bf-abc1-c4340d72edb5)
The delay spaces out extractor starts across batches, accounts, resumes, retries,
and date-range fetches. The first fetch starts immediately. It does not control
requests made internally by the external extractor. Stop interrupts a pending
wait, and waiting counts toward Fetch Timeout, so increase the timeout when
using longer delays.
## 🔑 How to Obtain Auth Token
## How to Obtain Auth Token
> [!Warning]
> - I suggest not using the **main account** to obtain the token.
> - You can use https://temp-mail.io to register a Twitter account.
> - Using an auth token or cookies has the potential to get the **account suspended.**
> - If too many media files are fetched, it may trigger a **rate limit**, and the media retrieval will fail, try enabling Batch mode.
### [Video Tutorial](https://www.patreon.com/posts/how-to-obtain-127206894)
> - If too many media files are fetched, it may trigger a **rate limit**, and the media retrieval will fail.
1. Go to [Twitter's website](https://www.x.com/)
2. Log into your account
3. Open the Developer Tools by pressing `F12`
3. Open the Developer Tools by pressing <kbd>F12</kbd>
4. Navigate to the **Application** tab, then select **Storage → Cookies**
5. Find and copy the `auth_token` value or use the browser extension [X.com Auth Token Grabber](https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases/download/v1.0/X.com.Auth.Token.Grabber.zip)
5. Find and copy the `auth_token` value
6. Do not log out of your account, as a new `auth_token` will be generated by Twitter
> X.com Auth Token Grabber
![image](https://github.com/user-attachments/assets/4bf5f787-d34f-4259-837c-07a6432c4360)
> Developer Tools
![image](https://github.com/user-attachments/assets/8e81dd8f-f8be-4254-9cf6-cacfa97743e9)
File diff suppressed because it is too large. Load diff
+717
View File
@@ -0,0 +1,717 @@
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"time"
"twitterxmediabatchdownloader/backend"
"github.com/wailsapp/wails/v2/pkg/runtime"
)
type App struct {
ctx context.Context
downloadMu sync.Mutex
downloadCancel context.CancelFunc
downloadActive bool
}
func NewApp() *App {
return &App{}
}
func (a *App) startup(ctx context.Context) {
a.ctx = ctx
if err := backend.InitDB(); err != nil {
runtime.LogErrorf(ctx, "failed to initialize database: %v", err)
}
backend.KillAllExtractorProcesses()
}
func (a *App) shutdown(ctx context.Context) {
backend.CloseDB()
backend.KillAllExtractorProcesses()
}
func (a *App) CleanupExtractorProcesses() {
backend.KillAllExtractorProcesses()
}
type TimelineRequest struct {
Username string `json:"username"`
AuthToken string `json:"auth_token"`
TimelineType string `json:"timeline_type"`
BatchSize int `json:"batch_size"`
Page int `json:"page"`
MediaType string `json:"media_type"`
Retweets bool `json:"retweets"`
Cursor string `json:"cursor,omitempty"`
IncludePhotos bool `json:"include_photos"`
IncludeVideos bool `json:"include_videos"`
IncludeGifs bool `json:"include_gifs"`
IncludeText bool `json:"include_text"`
VideoQuality string `json:"video_quality,omitempty"`
ImageSize string `json:"image_size,omitempty"`
}
type DateRangeRequest struct {
Username string `json:"username"`
AuthToken string `json:"auth_token"`
StartDate string `json:"start_date"`
EndDate string `json:"end_date"`
MediaFilter string `json:"media_filter"`
Retweets bool `json:"retweets"`
}
func (a *App) ExtractTimeline(req TimelineRequest) (string, error) {
if req.Username == "" && req.TimelineType != "bookmarks" {
return "", fmt.Errorf("username is required")
}
if req.AuthToken == "" {
return "", fmt.Errorf("auth token is required")
}
backendReq := backend.TimelineRequest{
Username: req.Username,
AuthToken: req.AuthToken,
TimelineType: req.TimelineType,
BatchSize: req.BatchSize,
Page: req.Page,
MediaType: req.MediaType,
Retweets: req.Retweets,
Cursor: req.Cursor,
IncludePhotos: req.IncludePhotos,
IncludeVideos: req.IncludeVideos,
IncludeGifs: req.IncludeGifs,
IncludeText: req.IncludeText,
VideoQuality: req.VideoQuality,
ImageSize: req.ImageSize,
}
response, err := backend.ExtractTimeline(backendReq)
if err != nil {
return "", fmt.Errorf("failed to extract timeline: %v", err)
}
jsonData, err := json.MarshalIndent(response, "", " ")
if err != nil {
return "", fmt.Errorf("failed to encode response: %v", err)
}
return string(jsonData), nil
}
func (a *App) ExtractDateRange(req DateRangeRequest) (string, error) {
if req.Username == "" {
return "", fmt.Errorf("username is required")
}
if req.AuthToken == "" {
return "", fmt.Errorf("auth token is required")
}
if req.StartDate == "" {
return "", fmt.Errorf("start date is required")
}
if req.EndDate == "" {
return "", fmt.Errorf("end date is required")
}
backendReq := backend.DateRangeRequest{
Username: req.Username,
AuthToken: req.AuthToken,
StartDate: req.StartDate,
EndDate: req.EndDate,
MediaFilter: req.MediaFilter,
Retweets: req.Retweets,
}
response, err := backend.ExtractDateRange(backendReq)
if err != nil {
return "", fmt.Errorf("failed to extract date range: %v", err)
}
jsonData, err := json.MarshalIndent(response, "", " ")
if err != nil {
return "", fmt.Errorf("failed to encode response: %v", err)
}
return string(jsonData), nil
}
func (a *App) OpenFolder(path string) error {
if path == "" {
return fmt.Errorf("path is required")
}
cleanPath := filepath.Clean(path)
err := backend.OpenFolderInExplorer(cleanPath)
if err != nil {
return fmt.Errorf("failed to open folder: %v", err)
}
return nil
}
type DownloadProfileImageRequest struct {
URL string `json:"url"`
OutputDir string `json:"output_dir"`
Username string `json:"username"`
Kind string `json:"kind"`
Proxy string `json:"proxy,omitempty"`
}
func (a *App) DownloadProfileImage(req DownloadProfileImageRequest) (string, error) {
if req.URL == "" {
return "", fmt.Errorf("image url is required")
}
outputDir := req.OutputDir
if outputDir == "" {
outputDir = backend.GetDefaultDownloadPath()
}
path, err := backend.DownloadProfileImage(req.URL, outputDir, req.Username, req.Kind, req.Proxy)
if err != nil {
return "", err
}
return path, nil
}
func (a *App) SelectFolder(defaultPath string) (string, error) {
return backend.SelectFolderDialog(a.ctx, defaultPath)
}
func (a *App) GetDefaults() map[string]string {
return map[string]string{
"downloadPath": backend.GetDefaultDownloadPath(),
}
}
func (a *App) GetStoredAuthToken(slot string) (string, error) {
return backend.GetStoredAuthToken(slot)
}
func (a *App) SetStoredAuthToken(slot, token string) error {
return backend.SetStoredAuthToken(slot, token)
}
func (a *App) ClearStoredAuthToken(slot string) error {
return backend.ClearStoredAuthToken(slot)
}
func (a *App) IsExtractorInstalled() bool {
return backend.IsExtractorInstalled()
}
func (a *App) DownloadExtractor() error {
return backend.DownloadExtractor(nil)
}
func (a *App) GetExtractorVersionStatus() backend.ExtractorVersionStatus {
return backend.GetExtractorVersionStatus()
}
func (a *App) Quit() {
if a.ctx != nil {
runtime.Quit(a.ctx)
return
}
panic("quit")
}
func (a *App) ExportFailedLogs(content string) (string, error) {
if strings.TrimSpace(content) == "" {
return "", fmt.Errorf("no failed logs to export")
}
if a.ctx == nil {
return "", fmt.Errorf("application is not ready")
}
path, err := runtime.SaveFileDialog(a.ctx, runtime.SaveDialogOptions{
DefaultFilename: fmt.Sprintf("TwitterXMediaBatchDownloader_%s_Failed.txt", time.Now().Format("20060102_150405")),
Title: "Export Failed Logs",
Filters: []runtime.FileFilter{
{
DisplayName: "Text Files (*.txt)",
Pattern: "*.txt",
},
},
})
if err != nil {
return "", fmt.Errorf("failed to open save dialog: %v", err)
}
if path == "" {
return "", nil
}
if err := os.WriteFile(path, []byte(content), 0644); err != nil {
return "", fmt.Errorf("failed to write log file: %v", err)
}
return path, nil
}
type DownloadMediaRequest struct {
URLs []string `json:"urls"`
OutputDir string `json:"output_dir"`
Username string `json:"username"`
ConcurrentDownloads int `json:"concurrent_downloads,omitempty"`
SkipExisting bool `json:"skip_existing"`
DeleteIncompleteFiles bool `json:"delete_incomplete_files"`
RetryAttempts int `json:"retry_attempts,omitempty"`
DownloadSpeedLimitKBps int `json:"download_speed_limit_kbps,omitempty"`
DownloadDelayMillis int `json:"download_delay_ms,omitempty"`
DownloadDelayJitterMillis int `json:"download_delay_jitter_ms,omitempty"`
Proxy string `json:"proxy,omitempty"`
}
type MediaItemRequest struct {
URL string `json:"url"`
Date string `json:"date"`
TweetID backend.TweetIDString `json:"tweet_id"`
Type string `json:"type"`
Content string `json:"content,omitempty"`
OriginalFilename string `json:"original_filename,omitempty"`
AuthorUsername string `json:"author_username,omitempty"`
AccountName string `json:"account_name,omitempty"`
}
type DownloadMediaWithMetadataRequest struct {
Items []MediaItemRequest `json:"items"`
OutputDir string `json:"output_dir"`
Username string `json:"username"`
ConcurrentDownloads int `json:"concurrent_downloads,omitempty"`
SkipExisting bool `json:"skip_existing"`
DeleteIncompleteFiles bool `json:"delete_incomplete_files"`
RetryAttempts int `json:"retry_attempts,omitempty"`
DownloadSpeedLimitKBps int `json:"download_speed_limit_kbps,omitempty"`
DownloadDelayMillis int `json:"download_delay_ms,omitempty"`
DownloadDelayJitterMillis int `json:"download_delay_jitter_ms,omitempty"`
Proxy string `json:"proxy,omitempty"`
FilenameTemplate string `json:"filename_template,omitempty"`
FolderTemplate string `json:"folder_template,omitempty"`
AutoConvertGIFs bool `json:"auto_convert_gifs,omitempty"`
GIFQuality string `json:"gif_quality,omitempty"`
GIFResolution string `json:"gif_resolution,omitempty"`
}
type DownloadMediaResponse struct {
Success bool `json:"success"`
Cancelled bool `json:"cancelled"`
Downloaded int `json:"downloaded"`
Skipped int `json:"skipped"`
Failed int `json:"failed"`
Message string `json:"message"`
}
func (a *App) DownloadMedia(req DownloadMediaRequest) (DownloadMediaResponse, error) {
if len(req.URLs) == 0 {
return DownloadMediaResponse{
Success: false,
Cancelled: false,
Message: "No URLs provided",
}, fmt.Errorf("no URLs provided")
}
outputDir := req.OutputDir
if outputDir == "" {
outputDir = backend.GetDefaultDownloadPath()
}
if req.Username != "" {
outputDir = filepath.Join(outputDir, req.Username)
}
options := backend.DownloadOptions{
ConcurrentDownloads: req.ConcurrentDownloads,
SkipExistingFiles: req.SkipExisting,
DeleteIncompleteFiles: req.DeleteIncompleteFiles,
RetryAttempts: req.RetryAttempts,
DownloadSpeedLimitKBps: req.DownloadSpeedLimitKBps,
DownloadDelayMillis: req.DownloadDelayMillis,
DownloadDelayJitterMillis: req.DownloadDelayJitterMillis,
}
downloaded, failed, err := backend.DownloadMediaFiles(req.URLs, outputDir, options, req.Proxy)
if err != nil {
return DownloadMediaResponse{
Success: false,
Cancelled: false,
Downloaded: downloaded,
Skipped: 0,
Failed: failed,
Message: err.Error(),
}, err
}
return DownloadMediaResponse{
Success: true,
Cancelled: false,
Downloaded: downloaded,
Skipped: 0,
Failed: failed,
Message: fmt.Sprintf("Downloaded %d files, %d failed", downloaded, failed),
}, nil
}
type DownloadProgress struct {
Current int `json:"current"`
Total int `json:"total"`
Percent int `json:"percent"`
}
type DownloadItemStatus struct {
TweetID int64 `json:"tweet_id"`
Index int `json:"index"`
Status string `json:"status"`
}
func (a *App) DownloadMediaWithMetadata(req DownloadMediaWithMetadataRequest) (DownloadMediaResponse, error) {
if len(req.Items) == 0 {
return DownloadMediaResponse{
Success: false,
Cancelled: false,
Message: "No items provided",
}, fmt.Errorf("no items provided")
}
outputDir := req.OutputDir
if outputDir == "" {
outputDir = backend.GetDefaultDownloadPath()
}
items := make([]backend.MediaItem, len(req.Items))
for i, item := range req.Items {
originalFilename := item.OriginalFilename
if originalFilename == "" {
originalFilename = backend.ExtractOriginalFilename(item.URL)
}
username := req.Username
if (req.Username == "bookmarks" || req.Username == "likes") && item.AuthorUsername != "" {
username = item.AuthorUsername
}
items[i] = backend.MediaItem{
URL: item.URL,
Date: item.Date,
TweetID: int64(item.TweetID),
Type: item.Type,
Username: username,
AccountName: item.AccountName,
Content: item.Content,
OriginalFilename: originalFilename,
}
}
downloadCtx, err := a.startDownloadOperation()
if err != nil {
return DownloadMediaResponse{
Success: false,
Cancelled: false,
Message: err.Error(),
}, err
}
defer a.finishDownloadOperation()
progressCallback := func(current, total int) {
percent := 0
if total > 0 {
percent = (current * 100) / total
}
runtime.EventsEmit(a.ctx, "download-progress", DownloadProgress{
Current: current,
Total: total,
Percent: percent,
})
}
itemStatusCallback := func(tweetID int64, index int, status string) {
runtime.EventsEmit(a.ctx, "download-item-status", DownloadItemStatus{
TweetID: tweetID,
Index: index,
Status: status,
})
}
options := backend.DownloadOptions{
ConcurrentDownloads: req.ConcurrentDownloads,
SkipExistingFiles: req.SkipExisting,
DeleteIncompleteFiles: req.DeleteIncompleteFiles,
RetryAttempts: req.RetryAttempts,
DownloadSpeedLimitKBps: req.DownloadSpeedLimitKBps,
DownloadDelayMillis: req.DownloadDelayMillis,
DownloadDelayJitterMillis: req.DownloadDelayJitterMillis,
FilenameTemplate: req.FilenameTemplate,
FolderTemplate: req.FolderTemplate,
AutoConvertGIFs: req.AutoConvertGIFs,
GIFQuality: req.GIFQuality,
GIFResolution: req.GIFResolution,
}
downloaded, skipped, failed, err := backend.DownloadMediaWithMetadataProgressAndStatus(
items,
outputDir,
req.Username,
progressCallback,
itemStatusCallback,
downloadCtx,
options,
req.Proxy,
)
if err != nil {
if errors.Is(err, context.Canceled) {
return DownloadMediaResponse{
Success: false,
Cancelled: true,
Downloaded: downloaded,
Skipped: skipped,
Failed: failed,
Message: "Download stopped",
}, nil
}
return DownloadMediaResponse{
Success: false,
Cancelled: false,
Downloaded: downloaded,
Skipped: skipped,
Failed: failed,
Message: err.Error(),
}, err
}
return DownloadMediaResponse{
Success: true,
Cancelled: false,
Downloaded: downloaded,
Skipped: skipped,
Failed: failed,
Message: fmt.Sprintf("Downloaded %d files, %d skipped, %d failed", downloaded, skipped, failed),
}, nil
}
func (a *App) startDownloadOperation() (context.Context, error) {
a.downloadMu.Lock()
defer a.downloadMu.Unlock()
if a.downloadActive {
return nil, fmt.Errorf("another download is already in progress")
}
ctx, cancel := context.WithCancel(context.Background())
a.downloadCancel = cancel
a.downloadActive = true
return ctx, nil
}
func (a *App) finishDownloadOperation() {
a.downloadMu.Lock()
defer a.downloadMu.Unlock()
a.downloadCancel = nil
a.downloadActive = false
}
func (a *App) StopDownload() bool {
a.downloadMu.Lock()
defer a.downloadMu.Unlock()
if !a.downloadActive || a.downloadCancel == nil {
return false
}
a.downloadCancel()
return true
}
func (a *App) SaveAccountToDB(username, name, profileImage string, totalMedia int, responseJSON string, mediaType string) error {
return backend.SaveAccount(username, name, profileImage, totalMedia, responseJSON, mediaType)
}
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)
}
func (a *App) GetAllAccountsFromDB() ([]backend.AccountListItem, error) {
return backend.GetAllAccounts()
}
func (a *App) GetAccountFromDB(id int64) (string, error) {
acc, err := backend.GetAccountByID(id)
if err != nil {
return "", err
}
return acc.ResponseJSON, nil
}
func (a *App) GetSavedAccountFromDB(username, mediaType string) (string, error) {
acc, err := backend.GetAccountByUsernameAndMediaType(username, mediaType)
if err != nil {
return "", err
}
return acc.ResponseJSON, nil
}
func (a *App) DeleteAccountFromDB(id int64) error {
return backend.DeleteAccount(id)
}
func (a *App) ClearAllAccountsFromDB() error {
return backend.ClearAllAccounts()
}
func (a *App) ExportAccountJSON(id int64, outputDir string) (string, error) {
return backend.ExportAccountToFile(id, outputDir)
}
func (a *App) ExportAccountsTXT(ids []int64, outputDir string) (string, error) {
return backend.ExportAccountsToTXT(ids, outputDir)
}
func (a *App) UpdateAccountGroup(id int64, groupName, groupColor string) error {
return backend.UpdateAccountGroup(id, groupName, groupColor)
}
func (a *App) GetAllGroups() ([]map[string]string, error) {
return backend.GetAllGroups()
}
func (a *App) CheckFoldersExist(basePath string, usernames []string) map[string]bool {
return backend.CheckFoldersExist(basePath, usernames)
}
func (a *App) IsFFmpegInstalled() bool {
return backend.IsFFmpegInstalled()
}
func (a *App) DownloadFFmpeg() error {
return backend.DownloadFFmpeg(nil)
}
func (a *App) GetFFmpegVersionStatus() backend.DependencyVersionStatus {
return backend.GetFFmpegVersionStatus()
}
func (a *App) IsExifToolInstalled() bool {
return backend.IsExifToolInstalled()
}
func (a *App) DownloadExifTool() error {
return backend.DownloadExifTool(nil)
}
func (a *App) GetExifToolVersionStatus() backend.DependencyVersionStatus {
return backend.GetExifToolVersionStatus()
}
type ConvertGIFsRequest struct {
FolderPath string `json:"folder_path"`
Quality string `json:"quality"`
Resolution string `json:"resolution"`
DeleteOriginal bool `json:"delete_original"`
}
type ConvertGIFsResponse struct {
Success bool `json:"success"`
Converted int `json:"converted"`
Failed int `json:"failed"`
Message string `json:"message"`
}
func (a *App) ConvertGIFs(req ConvertGIFsRequest) (ConvertGIFsResponse, error) {
if !backend.IsFFmpegInstalled() {
return ConvertGIFsResponse{
Success: false,
Message: "FFmpeg not installed. Please download it first.",
}, nil
}
quality := req.Quality
if quality == "" {
quality = "fast"
}
resolution := req.Resolution
if resolution == "" {
resolution = "high"
}
converted, failed, err := backend.ConvertGIFsInFolder(req.FolderPath, quality, resolution, req.DeleteOriginal)
if err != nil {
return ConvertGIFsResponse{
Success: false,
Message: err.Error(),
}, err
}
return ConvertGIFsResponse{
Success: true,
Converted: converted,
Failed: failed,
Message: fmt.Sprintf("Converted %d GIFs, %d failed", converted, failed),
}, nil
}
type ImportAccountResponse struct {
Success bool `json:"success"`
Username string `json:"username"`
Message string `json:"message"`
}
func (a *App) CheckFolderExists(basePath, username string) bool {
return backend.CheckFolderExists(basePath, username)
}
func (a *App) CheckGifsFolderExists(basePath, username string) bool {
return backend.CheckGifsFolderExists(basePath, username)
}
func (a *App) CheckGifsFolderHasMP4(basePath, username string) bool {
return backend.CheckGifsFolderHasMP4(basePath, username)
}
func (a *App) GetFolderPath(basePath, username string) string {
return backend.GetFolderPath(basePath, username)
}
func (a *App) GetGifsFolderPath(basePath, username string) string {
return backend.GetGifsFolderPath(basePath, username)
}
func (a *App) ImportAccountFromJSON() (ImportAccountResponse, error) {
filePath, err := runtime.OpenFileDialog(a.ctx, runtime.OpenDialogOptions{
Title: "Import Account JSON",
Filters: []runtime.FileFilter{
{DisplayName: "JSON Files", Pattern: "*.json"},
},
})
if err != nil {
return ImportAccountResponse{Success: false, Message: err.Error()}, err
}
if filePath == "" {
return ImportAccountResponse{Success: false, Message: "Cancelled"}, nil
}
username, err := backend.ImportAccountFromFile(filePath)
if err != nil {
return ImportAccountResponse{Success: false, Message: err.Error()}, err
}
return ImportAccountResponse{
Success: true,
Username: username,
Message: fmt.Sprintf("Successfully imported @%s", username),
}, nil
}
+70
View File
@@ -0,0 +1,70 @@
package backend
import (
"errors"
"fmt"
"strings"
"github.com/zalando/go-keyring"
)
const authTokenKeyringService = "TwitterXMediaBatchDownloader"
func normalizeAuthTokenSlot(slot string) (string, error) {
switch strings.ToLower(strings.TrimSpace(slot)) {
case "public":
return "public", nil
case "private":
return "private", nil
default:
return "", fmt.Errorf("invalid auth token slot: %q", slot)
}
}
func authTokenKeyringUser(slot string) string {
return "auth-token-" + slot
}
func GetStoredAuthToken(slot string) (string, error) {
normalizedSlot, err := normalizeAuthTokenSlot(slot)
if err != nil {
return "", err
}
token, err := keyring.Get(authTokenKeyringService, authTokenKeyringUser(normalizedSlot))
if errors.Is(err, keyring.ErrNotFound) {
return "", nil
}
if err != nil {
return "", err
}
return token, nil
}
func SetStoredAuthToken(slot, token string) error {
normalizedSlot, err := normalizeAuthTokenSlot(slot)
if err != nil {
return err
}
if strings.TrimSpace(token) == "" {
return ClearStoredAuthToken(normalizedSlot)
}
return keyring.Set(authTokenKeyringService, authTokenKeyringUser(normalizedSlot), token)
}
func ClearStoredAuthToken(slot string) error {
normalizedSlot, err := normalizeAuthTokenSlot(slot)
if err != nil {
return err
}
err = keyring.Delete(authTokenKeyringService, authTokenKeyringUser(normalizedSlot))
if errors.Is(err, keyring.ErrNotFound) {
return nil
}
return err
}
+27
View File
@@ -0,0 +1,27 @@
//go:build !windows
package backend
import (
"errors"
"os/exec"
"syscall"
)
func hideWindow(cmd *exec.Cmd) {
cmd.SysProcAttr = &syscall.SysProcAttr{
Setpgid: true,
}
}
func terminateCommandProcess(cmd *exec.Cmd) error {
if cmd == nil || cmd.Process == nil {
return nil
}
if err := syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL); err != nil && !errors.Is(err, syscall.ESRCH) {
return err
}
return nil
}
+30
View File
@@ -0,0 +1,30 @@
//go:build windows
package backend
import (
"os/exec"
"strconv"
"syscall"
)
func hideWindow(cmd *exec.Cmd) {
cmd.SysProcAttr = &syscall.SysProcAttr{
HideWindow: true,
CreationFlags: 0x08000000,
}
}
func terminateCommandProcess(cmd *exec.Cmd) error {
if cmd == nil || cmd.Process == nil {
return nil
}
taskkill := exec.Command("taskkill", "/T", "/F", "/PID", strconv.Itoa(cmd.Process.Pid))
hideWindow(taskkill)
if err := taskkill.Run(); err == nil {
return nil
}
return cmd.Process.Kill()
}
+120
View File
@@ -0,0 +1,120 @@
package backend
import (
"fmt"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"sync/atomic"
"time"
)
func GetDefaultDownloadPath() string {
homeDir, err := os.UserHomeDir()
if err != nil {
return "C:\\Users\\Public\\Pictures"
}
return filepath.Join(homeDir, "Pictures")
}
func parseProxyURLs(rawValue string, sourceName string) ([]*url.URL, error) {
if strings.TrimSpace(rawValue) == "" {
return nil, nil
}
parts := strings.Split(rawValue, ",")
proxyURLs := make([]*url.URL, 0, len(parts))
for _, part := range parts {
trimmed := strings.TrimSpace(part)
if trimmed == "" {
continue
}
proxyURL, err := url.Parse(trimmed)
if err != nil {
return nil, fmt.Errorf("invalid proxy URL in %s: %v", sourceName, err)
}
if proxyURL.Scheme == "" || proxyURL.Host == "" {
return nil, fmt.Errorf("invalid proxy URL in %s: %q", sourceName, trimmed)
}
proxyURLs = append(proxyURLs, proxyURL)
}
if len(proxyURLs) == 0 {
return nil, nil
}
return proxyURLs, nil
}
func GetProxyURLs(customProxy string) ([]*url.URL, error) {
if customProxy != "" {
return parseProxyURLs(customProxy, "custom proxy setting")
}
proxyEnv := os.Getenv("HTTPS_PROXY")
if proxyEnv == "" {
proxyEnv = os.Getenv("https_proxy")
}
if proxyEnv == "" {
proxyEnv = os.Getenv("HTTP_PROXY")
}
if proxyEnv == "" {
proxyEnv = os.Getenv("http_proxy")
}
if proxyEnv != "" {
return parseProxyURLs(proxyEnv, "proxy environment variable")
}
return nil, nil
}
func GetProxyURL(customProxy string) (*url.URL, error) {
proxyURLs, err := GetProxyURLs(customProxy)
if err != nil || len(proxyURLs) == 0 {
return nil, err
}
return proxyURLs[0], nil
}
func buildProxySelector(proxyURLs []*url.URL) func(*http.Request) (*url.URL, error) {
if len(proxyURLs) == 0 {
return nil
}
if len(proxyURLs) == 1 {
return http.ProxyURL(proxyURLs[0])
}
var requestCount uint64
return func(*http.Request) (*url.URL, error) {
index := atomic.AddUint64(&requestCount, 1) - 1
return proxyURLs[index%uint64(len(proxyURLs))], nil
}
}
func CreateHTTPClient(customProxy string, timeout time.Duration) (*http.Client, error) {
proxyURLs, err := GetProxyURLs(customProxy)
if err != nil {
return nil, err
}
transport := &http.Transport{
Proxy: buildProxySelector(proxyURLs),
}
client := &http.Client{
Transport: transport,
Timeout: timeout,
}
return client, nil
}
+635
View File
@@ -0,0 +1,635 @@
package backend
import (
"database/sql"
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"time"
_ "modernc.org/sqlite"
)
type AccountDB struct {
ID int64 `json:"id"`
Username string `json:"username"`
Name string `json:"name"`
ProfileImage string `json:"profile_image"`
TotalMedia int `json:"total_media"`
LastFetched time.Time `json:"last_fetched"`
ResponseJSON string `json:"response_json"`
MediaType string `json:"media_type"`
Cursor string `json:"cursor"`
Completed bool `json:"completed"`
}
type AccountListItem struct {
ID int64 `json:"id"`
Username string `json:"username"`
Name string `json:"name"`
ProfileImage string `json:"profile_image"`
TotalMedia int `json:"total_media"`
LastFetched string `json:"last_fetched"`
GroupName string `json:"group_name"`
GroupColor string `json:"group_color"`
MediaType string `json:"media_type"`
Cursor string `json:"cursor"`
Completed bool `json:"completed"`
FollowersCount int `json:"followers_count"`
StatusesCount int `json:"statuses_count"`
}
var db *sql.DB
var dbInitMu sync.Mutex
var dbInitialized bool
func ensureDB() error {
dbInitMu.Lock()
defer dbInitMu.Unlock()
if dbInitialized && db != nil {
return nil
}
if err := initDBInternal(); err != nil {
return err
}
dbInitialized = true
return nil
}
type accountMetricsPayload struct {
AccountInfo struct {
FollowersCount int `json:"followers_count"`
StatusesCount int `json:"statuses_count"`
} `json:"account_info"`
Followers int `json:"followers"`
Posts int `json:"posts"`
}
func GetDBPath() string {
homeDir, err := os.UserHomeDir()
if err != nil {
homeDir = "."
}
return filepath.Join(homeDir, ".twitterxmediabatchdownloader", "accounts.db")
}
func InitDB() error {
return ensureDB()
}
func initDBInternal() error {
dbPath := GetDBPath()
dir := filepath.Dir(dbPath)
if err := os.MkdirAll(dir, 0755); err != nil {
return err
}
var err error
db, err = sql.Open("sqlite", dbPath)
if err != nil {
return err
}
if err := db.Ping(); err != nil {
return err
}
_, err = db.Exec(`
CREATE TABLE IF NOT EXISTS accounts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL,
name TEXT,
profile_image TEXT,
total_media INTEGER DEFAULT 0,
last_fetched DATETIME,
response_json TEXT,
group_name TEXT DEFAULT '',
group_color TEXT DEFAULT '',
media_type TEXT DEFAULT 'all',
cursor TEXT DEFAULT '',
completed INTEGER DEFAULT 1,
followers_count INTEGER DEFAULT 0,
statuses_count INTEGER DEFAULT 0,
UNIQUE(username, media_type)
)
`)
if err != nil {
return err
}
db.Exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_username_media_type ON accounts(username, media_type)")
if err := runMigrations(); err != nil {
return err
}
if err := backfillAccountMetrics(); err != nil {
return err
}
return nil
}
func runMigrations() error {
var version int
if err := db.QueryRow("PRAGMA user_version").Scan(&version); err != nil {
return err
}
migrations := []string{
"ALTER TABLE accounts ADD COLUMN group_name TEXT DEFAULT ''",
"ALTER TABLE accounts ADD COLUMN group_color TEXT DEFAULT ''",
"ALTER TABLE accounts ADD COLUMN media_type TEXT DEFAULT 'all'",
"ALTER TABLE accounts ADD COLUMN cursor TEXT DEFAULT ''",
"ALTER TABLE accounts ADD COLUMN completed INTEGER DEFAULT 1",
"ALTER TABLE accounts ADD COLUMN followers_count INTEGER DEFAULT 0",
"ALTER TABLE accounts ADD COLUMN statuses_count INTEGER DEFAULT 0",
}
for i := version; i < len(migrations); i++ {
if _, err := db.Exec(migrations[i]); err != nil {
if !strings.Contains(err.Error(), "duplicate column name") {
return fmt.Errorf("migration %d failed: %w", i, err)
}
}
}
if _, err := db.Exec(fmt.Sprintf("PRAGMA user_version = %d", len(migrations))); err != nil {
return err
}
return nil
}
func CloseDB() {
if db != nil {
db.Close()
}
}
func SaveAccount(username, name, profileImage string, totalMedia int, responseJSON string, mediaType string) error {
return SaveAccountWithStatus(username, name, profileImage, totalMedia, responseJSON, mediaType, "", true)
}
func SaveAccountWithStatus(username, name, profileImage string, totalMedia int, responseJSON string, mediaType string, cursor string, completed bool) error {
if err := ensureDB(); err != nil {
return err
}
if mediaType == "" {
mediaType = "all"
}
completedInt := 0
if completed {
completedInt = 1
}
followersCount, statusesCount := extractAccountMetrics(responseJSON)
_, err := db.Exec(`
INSERT INTO accounts (username, name, profile_image, total_media, last_fetched, response_json, media_type, cursor, completed, followers_count, statuses_count)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(username, media_type) DO UPDATE SET
name = excluded.name,
profile_image = excluded.profile_image,
total_media = excluded.total_media,
last_fetched = excluded.last_fetched,
response_json = excluded.response_json,
cursor = excluded.cursor,
completed = excluded.completed,
followers_count = excluded.followers_count,
statuses_count = excluded.statuses_count
`, username, name, profileImage, totalMedia, time.Now(), responseJSON, mediaType, cursor, completedInt, followersCount, statusesCount)
return err
}
func GetAllAccounts() ([]AccountListItem, error) {
if err := ensureDB(); err != nil {
return nil, err
}
rows, err := db.Query(`
SELECT id, username, name, profile_image, total_media, last_fetched,
COALESCE(group_name, '') as group_name, COALESCE(group_color, '') as group_color,
COALESCE(media_type, 'all') as media_type,
COALESCE(cursor, '') as cursor, COALESCE(completed, 1) as completed,
COALESCE(followers_count, 0) as followers_count,
COALESCE(statuses_count, 0) as statuses_count
FROM accounts
ORDER BY group_name ASC, last_fetched DESC
`)
if err != nil {
return nil, err
}
defer rows.Close()
var accounts []AccountListItem
for rows.Next() {
var acc AccountListItem
var lastFetched time.Time
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, &acc.FollowersCount, &acc.StatusesCount); err != nil {
continue
}
acc.LastFetched = lastFetched.Format("2006-01-02 15:04")
acc.Completed = completedInt == 1
accounts = append(accounts, acc)
}
return accounts, nil
}
func extractAccountMetrics(responseJSON string) (followersCount int, statusesCount int) {
if responseJSON == "" {
return 0, 0
}
var payload accountMetricsPayload
if err := json.Unmarshal([]byte(responseJSON), &payload); err != nil {
return 0, 0
}
followersCount = payload.AccountInfo.FollowersCount
statusesCount = payload.AccountInfo.StatusesCount
if followersCount == 0 {
followersCount = payload.Followers
}
if statusesCount == 0 {
statusesCount = payload.Posts
}
return followersCount, statusesCount
}
func backfillAccountMetrics() error {
rows, err := db.Query(`
SELECT id, COALESCE(response_json, '') as response_json
FROM accounts
WHERE COALESCE(response_json, '') != ''
AND (COALESCE(followers_count, 0) = 0 OR COALESCE(statuses_count, 0) = 0)
`)
if err != nil {
return err
}
type metricUpdate struct {
id int64
followersCount int
statusesCount int
}
var updates []metricUpdate
for rows.Next() {
var id int64
var responseJSON string
if err := rows.Scan(&id, &responseJSON); err != nil {
continue
}
followersCount, statusesCount := extractAccountMetrics(responseJSON)
updates = append(updates, metricUpdate{id, followersCount, statusesCount})
}
if err := rows.Err(); err != nil {
rows.Close()
return err
}
rows.Close()
if len(updates) == 0 {
return nil
}
stmt, err := db.Prepare(`
UPDATE accounts
SET followers_count = ?, statuses_count = ?
WHERE id = ?
`)
if err != nil {
return err
}
defer stmt.Close()
for _, u := range updates {
if _, err := stmt.Exec(u.followersCount, u.statusesCount, u.id); err != nil {
return err
}
}
return nil
}
func UpdateAccountGroup(id int64, groupName, groupColor string) error {
if err := ensureDB(); err != nil {
return err
}
_, err := db.Exec("UPDATE accounts SET group_name = ?, group_color = ? WHERE id = ?", groupName, groupColor, id)
return err
}
func GetAllGroups() ([]map[string]string, error) {
if err := ensureDB(); err != nil {
return nil, err
}
rows, err := db.Query(`
SELECT DISTINCT group_name, group_color
FROM accounts
WHERE group_name != ''
ORDER BY group_name
`)
if err != nil {
return nil, err
}
defer rows.Close()
var groups []map[string]string
for rows.Next() {
var name, color string
if err := rows.Scan(&name, &color); err != nil {
continue
}
groups = append(groups, map[string]string{"name": name, "color": color})
}
return groups, nil
}
func ClearAllAccounts() error {
if err := ensureDB(); err != nil {
return err
}
_, err := db.Exec("DELETE FROM accounts")
return err
}
func GetAccountByID(id int64) (*AccountDB, error) {
if err := ensureDB(); err != nil {
return nil, err
}
var acc AccountDB
var lastFetched time.Time
var completedInt int
err := db.QueryRow(`
SELECT id, username, name, profile_image, total_media, last_fetched, response_json,
COALESCE(cursor, '') as cursor, COALESCE(completed, 1) as completed
FROM accounts WHERE id = ?
`, id).Scan(&acc.ID, &acc.Username, &acc.Name, &acc.ProfileImage, &acc.TotalMedia, &lastFetched, &acc.ResponseJSON, &acc.Cursor, &completedInt)
if err != nil {
return nil, err
}
acc.LastFetched = lastFetched
acc.Completed = completedInt == 1
if converted, err := ConvertLegacyToNewFormat(acc.ResponseJSON); err == nil {
acc.ResponseJSON = converted
}
return &acc, nil
}
func GetAccountByUsernameAndMediaType(username, mediaType string) (*AccountDB, error) {
if err := ensureDB(); err != nil {
return nil, err
}
if mediaType == "" {
mediaType = "all"
}
var acc AccountDB
var lastFetched time.Time
var completedInt int
err := db.QueryRow(`
SELECT id, username, name, profile_image, total_media, last_fetched, response_json,
COALESCE(media_type, 'all') as media_type,
COALESCE(cursor, '') as cursor, COALESCE(completed, 1) as completed
FROM accounts
WHERE LOWER(username) = LOWER(?) AND COALESCE(media_type, 'all') = ?
`, username, mediaType).Scan(&acc.ID, &acc.Username, &acc.Name, &acc.ProfileImage, &acc.TotalMedia, &lastFetched, &acc.ResponseJSON, &acc.MediaType, &acc.Cursor, &completedInt)
if err != nil {
return nil, err
}
acc.LastFetched = lastFetched
acc.Completed = completedInt == 1
if converted, err := ConvertLegacyToNewFormat(acc.ResponseJSON); err == nil {
acc.ResponseJSON = converted
}
return &acc, nil
}
func DeleteAccount(id int64) error {
if err := ensureDB(); err != nil {
return err
}
_, err := db.Exec("DELETE FROM accounts WHERE id = ?", id)
return err
}
type LegacyMediaEntry struct {
TweetID string `json:"tweet_id"`
URL string `json:"url"`
Date string `json:"date"`
Type string `json:"type"`
}
type LegacyAccountFormat struct {
Username string `json:"username"`
Nick string `json:"nick"`
Followers int `json:"followers"`
Following int `json:"following"`
Posts int `json:"posts"`
MediaType string `json:"media_type"`
ProfileImage string `json:"profile_image"`
FetchMode string `json:"fetch_mode"`
FetchTimestamp string `json:"fetch_timestamp"`
GroupID interface{} `json:"group_id"`
MediaList []LegacyMediaEntry `json:"media_list"`
}
func ConvertLegacyToNewFormat(jsonStr string) (string, error) {
var check map[string]interface{}
if err := json.Unmarshal([]byte(jsonStr), &check); err != nil {
return jsonStr, err
}
if _, hasAccountInfo := check["account_info"]; hasAccountInfo {
return jsonStr, nil
}
if _, hasUsername := check["username"]; !hasUsername {
return jsonStr, nil
}
if _, hasMediaList := check["media_list"]; !hasMediaList {
return jsonStr, nil
}
var legacy LegacyAccountFormat
if err := json.Unmarshal([]byte(jsonStr), &legacy); err != nil {
return jsonStr, err
}
timeline := make([]map[string]interface{}, len(legacy.MediaList))
for i, media := range legacy.MediaList {
timeline[i] = map[string]interface{}{
"url": media.URL,
"date": media.Date,
"tweet_id": media.TweetID,
"type": media.Type,
"is_retweet": false,
}
}
newFormat := map[string]interface{}{
"account_info": map[string]interface{}{
"name": legacy.Username,
"nick": legacy.Nick,
"date": "",
"followers_count": legacy.Followers,
"friends_count": legacy.Following,
"profile_image": legacy.ProfileImage,
"statuses_count": legacy.Posts,
},
"total_urls": len(legacy.MediaList),
"timeline": timeline,
"metadata": map[string]interface{}{
"new_entries": len(legacy.MediaList),
"page": 0,
"batch_size": 0,
"has_more": false,
},
}
newJSON, err := json.Marshal(newFormat)
if err != nil {
return jsonStr, err
}
return string(newJSON), nil
}
func ExportAccountToFile(id int64, outputDir string) (string, error) {
acc, err := GetAccountByID(id)
if err != nil {
return "", err
}
exportDir := filepath.Join(outputDir, "twitterxmediabatchdownloader_backups")
if err := os.MkdirAll(exportDir, 0755); err != nil {
return "", err
}
filename := acc.Username
if filename == "" {
filename = acc.Name
}
filePath := filepath.Join(exportDir, filename+".json")
if err := os.WriteFile(filePath, []byte(acc.ResponseJSON), 0644); err != nil {
return "", err
}
return filePath, nil
}
func ExportAccountsToTXT(ids []int64, outputDir string) (string, error) {
if len(ids) == 0 {
return "", fmt.Errorf("no accounts to export")
}
exportDir := filepath.Join(outputDir, "twitterxmediabatchdownloader_backups")
if err := os.MkdirAll(exportDir, 0755); err != nil {
return "", err
}
var usernames []string
for _, id := range ids {
acc, err := GetAccountByID(id)
if err != nil {
continue
}
if acc.Username != "" {
usernames = append(usernames, acc.Username)
}
}
if len(usernames) == 0 {
return "", fmt.Errorf("no valid usernames found")
}
txtContent := strings.Join(usernames, "\n")
filePath := filepath.Join(exportDir, "twitterxmediabatchdownloader_multiple.txt")
if err := os.WriteFile(filePath, []byte(txtContent), 0644); err != nil {
return "", err
}
return filePath, nil
}
func ImportAccountFromFile(filePath string) (string, error) {
if err := ensureDB(); err != nil {
return "", err
}
data, err := os.ReadFile(filePath)
if err != nil {
return "", err
}
jsonStr := string(data)
convertedJSON, err := ConvertLegacyToNewFormat(jsonStr)
if err != nil {
return "", err
}
var parsed map[string]interface{}
if err := json.Unmarshal([]byte(convertedJSON), &parsed); err != nil {
return "", err
}
accountInfo, ok := parsed["account_info"].(map[string]interface{})
if !ok {
return "", fmt.Errorf("invalid JSON format: missing account_info")
}
username, _ := accountInfo["name"].(string)
name, _ := accountInfo["nick"].(string)
profileImage, _ := accountInfo["profile_image"].(string)
totalURLs := 0
if total, ok := parsed["total_urls"].(float64); ok {
totalURLs = int(total)
}
if username == "" {
return "", fmt.Errorf("invalid JSON format: missing username")
}
err = SaveAccount(username, name, profileImage, totalURLs, convertedJSON, "all")
if err != nil {
return "", err
}
return username, nil
}
+7
View File
@@ -0,0 +1,7 @@
package backend
type DependencyVersionStatus struct {
Installed bool `json:"installed"`
InstalledVersion string `json:"installed_version,omitempty"`
LatestVersion string `json:"latest_version,omitempty"`
}
+943
View File
@@ -0,0 +1,943 @@
package backend
import (
"context"
"errors"
"fmt"
"io"
"math/rand/v2"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"time"
)
const (
DefaultConcurrentDownloads = 10
MaxConcurrentDownloads = 50
DefaultRetryAttempts = 2
MaxRetryAttempts = 5
MaxDownloadSpeedLimitKBps = 10 * 1024 * 1024
MaxDownloadDelayMillis = 60 * 60 * 1000
)
func NormalizeConcurrentDownloads(requested int) int {
if requested <= 0 {
return DefaultConcurrentDownloads
}
if requested > MaxConcurrentDownloads {
return MaxConcurrentDownloads
}
return requested
}
func NormalizeRetryAttempts(requested int) int {
if requested < 0 {
return 0
}
if requested > MaxRetryAttempts {
return MaxRetryAttempts
}
return requested
}
func normalizeDownloadSpeedLimit(requested int) int {
if requested < 0 {
return 0
}
if requested > MaxDownloadSpeedLimitKBps {
return MaxDownloadSpeedLimitKBps
}
return requested
}
func normalizeDownloadDelay(requested int) int {
if requested < 0 {
return 0
}
if requested > MaxDownloadDelayMillis {
return MaxDownloadDelayMillis
}
return requested
}
type DownloadOptions struct {
ConcurrentDownloads int
SkipExistingFiles bool
DeleteIncompleteFiles bool
RetryAttempts int
DownloadSpeedLimitKBps int
DownloadDelayMillis int
DownloadDelayJitterMillis int
FilenameTemplate string
FolderTemplate string
AutoConvertGIFs bool
GIFQuality string
GIFResolution string
}
func NormalizeDownloadOptions(options DownloadOptions) DownloadOptions {
options.ConcurrentDownloads = NormalizeConcurrentDownloads(options.ConcurrentDownloads)
options.RetryAttempts = NormalizeRetryAttempts(options.RetryAttempts)
options.DownloadSpeedLimitKBps = normalizeDownloadSpeedLimit(options.DownloadSpeedLimitKBps)
options.DownloadDelayMillis = normalizeDownloadDelay(options.DownloadDelayMillis)
options.DownloadDelayJitterMillis = normalizeDownloadDelay(options.DownloadDelayJitterMillis)
return options
}
type downloadThrottle struct {
speedBytesPerSecond int64
delay time.Duration
delayJitter time.Duration
requestMu sync.Mutex
nextRequestStart time.Time
requestStarted bool
bandwidthMu sync.Mutex
nextByteWriteTime time.Time
}
func newDownloadThrottle(options DownloadOptions) *downloadThrottle {
options = NormalizeDownloadOptions(options)
if options.DownloadSpeedLimitKBps == 0 && options.DownloadDelayMillis == 0 && options.DownloadDelayJitterMillis == 0 {
return nil
}
return &downloadThrottle{
speedBytesPerSecond: int64(options.DownloadSpeedLimitKBps) * 1024,
delay: time.Duration(options.DownloadDelayMillis) * time.Millisecond,
delayJitter: time.Duration(options.DownloadDelayJitterMillis) * time.Millisecond,
}
}
func waitUntil(ctx context.Context, deadline time.Time) error {
wait := time.Until(deadline)
if wait <= 0 {
return nil
}
timer := time.NewTimer(wait)
defer timer.Stop()
select {
case <-ctx.Done():
return ctx.Err()
case <-timer.C:
return nil
}
}
func (t *downloadThrottle) waitForRequest(ctx context.Context) error {
if t == nil || (t.delay == 0 && t.delayJitter == 0) {
return nil
}
t.requestMu.Lock()
now := time.Now()
startAt := now
if t.requestStarted && t.nextRequestStart.After(startAt) {
startAt = t.nextRequestStart
}
jitter := time.Duration(0)
if t.delayJitter > 0 {
jitter = time.Duration(rand.Int64N(int64(t.delayJitter) + 1))
}
t.nextRequestStart = startAt.Add(t.delay + jitter)
t.requestStarted = true
t.requestMu.Unlock()
return waitUntil(ctx, startAt)
}
func (t *downloadThrottle) waitForBytes(ctx context.Context, byteCount int) error {
if t == nil || t.speedBytesPerSecond <= 0 || byteCount <= 0 {
return nil
}
nanoseconds := (int64(byteCount)*int64(time.Second) + t.speedBytesPerSecond - 1) / t.speedBytesPerSecond
duration := time.Duration(nanoseconds)
t.bandwidthMu.Lock()
now := time.Now()
if t.nextByteWriteTime.Before(now) {
t.nextByteWriteTime = now
}
t.nextByteWriteTime = t.nextByteWriteTime.Add(duration)
writeAt := t.nextByteWriteTime
t.bandwidthMu.Unlock()
return waitUntil(ctx, writeAt)
}
type throttledWriter struct {
ctx context.Context
writer io.Writer
throttle *downloadThrottle
}
func (w throttledWriter) Write(p []byte) (int, error) {
if err := w.throttle.waitForBytes(w.ctx, len(p)); err != nil {
return 0, err
}
return w.writer.Write(p)
}
func createMediaDownloadClient(customProxy string, options DownloadOptions) *http.Client {
client, err := CreateHTTPClient(customProxy, 60*time.Second)
if err != nil {
client = &http.Client{Timeout: 60 * time.Second}
}
if options.DownloadSpeedLimitKBps > 0 {
client.Timeout = 0
if transport, ok := client.Transport.(*http.Transport); ok {
transport.ResponseHeaderTimeout = 60 * time.Second
} else if client.Transport == nil {
transport := http.DefaultTransport.(*http.Transport).Clone()
transport.ResponseHeaderTimeout = 60 * time.Second
client.Transport = transport
}
}
return client
}
type MediaItem struct {
URL string `json:"url"`
Date string `json:"date"`
TweetID int64 `json:"tweet_id"`
Type string `json:"type"`
Username string `json:"username"`
AccountName string `json:"account_name,omitempty"`
Content string `json:"content,omitempty"`
OriginalFilename string `json:"original_filename,omitempty"`
}
func DownloadMediaFiles(urls []string, outputDir string, options DownloadOptions, customProxy string) (downloaded int, failed int, err error) {
options = NormalizeDownloadOptions(options)
if err := os.MkdirAll(outputDir, 0755); err != nil {
return 0, len(urls), fmt.Errorf("failed to create output directory: %v", err)
}
client := createMediaDownloadClient(customProxy, options)
throttle := newDownloadThrottle(options)
for _, mediaURL := range urls {
filename := extractFilename(mediaURL)
outputPath := filepath.Join(outputDir, filename)
if options.SkipExistingFiles {
if _, err := os.Stat(outputPath); err == nil {
downloaded++
continue
}
}
if err := downloadFileWithRetry(context.Background(), client, mediaURL, outputPath, options, throttle); err != nil {
failed++
continue
}
downloaded++
}
return downloaded, failed, nil
}
func fileExists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
}
if errors.Is(err, os.ErrNotExist) {
return false, nil
}
return false, err
}
func cleanupIncompleteDownload(outputPath string) {
_ = os.Remove(outputPath)
}
func replaceFile(tempPath, outputPath string, allowOverwrite bool) error {
if !allowOverwrite {
return os.Rename(tempPath, outputPath)
}
exists, err := fileExists(outputPath)
if err != nil {
return err
}
if !exists {
return os.Rename(tempPath, outputPath)
}
backupPath := fmt.Sprintf("%s.bak.%d", outputPath, time.Now().UnixNano())
if err := os.Rename(outputPath, backupPath); err != nil {
return err
}
if err := os.Rename(tempPath, outputPath); err != nil {
restoreErr := os.Rename(backupPath, outputPath)
if restoreErr != nil {
return fmt.Errorf("failed to replace existing file: %v (restore failed: %v)", err, restoreErr)
}
return err
}
_ = os.Remove(backupPath)
return nil
}
func writeFileAtomically(outputPath string, data []byte, allowOverwrite bool, keepPartialOnFailure bool) error {
out, err := os.CreateTemp(filepath.Dir(outputPath), filepath.Base(outputPath)+".*.part")
if err != nil {
return err
}
tempPath := out.Name()
cleanupTemp := !keepPartialOnFailure
defer func() {
if out != nil {
_ = out.Close()
}
if cleanupTemp {
_ = os.Remove(tempPath)
}
}()
if _, err := out.Write(data); err != nil {
return err
}
if err := out.Close(); err != nil {
return err
}
out = nil
if err := replaceFile(tempPath, outputPath, allowOverwrite); err != nil {
return err
}
cleanupTemp = false
return nil
}
func waitForRetry(ctx context.Context, attempt int) error {
timer := time.NewTimer(time.Duration(attempt) * 500 * time.Millisecond)
defer timer.Stop()
select {
case <-ctx.Done():
return ctx.Err()
case <-timer.C:
return nil
}
}
func downloadFileWithRetry(ctx context.Context, client *http.Client, mediaURL, outputPath string, options DownloadOptions, throttle *downloadThrottle) error {
options = NormalizeDownloadOptions(options)
var lastErr error
totalAttempts := options.RetryAttempts + 1
for attempt := 1; attempt <= totalAttempts; attempt++ {
keepPartialOnFailure := !options.DeleteIncompleteFiles && attempt == totalAttempts
lastErr = downloadFileWithContext(ctx, client, mediaURL, outputPath, !options.SkipExistingFiles, keepPartialOnFailure, throttle)
if lastErr == nil {
return nil
}
if ctx.Err() != nil || errors.Is(lastErr, context.Canceled) {
if options.DeleteIncompleteFiles {
cleanupIncompleteDownload(outputPath)
}
return lastErr
}
if options.DeleteIncompleteFiles {
cleanupIncompleteDownload(outputPath)
}
if attempt < totalAttempts {
if err := waitForRetry(ctx, attempt); err != nil {
if options.DeleteIncompleteFiles {
cleanupIncompleteDownload(outputPath)
}
return err
}
}
}
return lastErr
}
func writeTextFileWithOptions(outputPath string, content string, options DownloadOptions) error {
keepPartialOnFailure := !options.DeleteIncompleteFiles
if err := writeFileAtomically(outputPath, []byte(content), !options.SkipExistingFiles, keepPartialOnFailure); err != nil {
if options.DeleteIncompleteFiles {
cleanupIncompleteDownload(outputPath)
}
return err
}
return nil
}
type ProgressCallback func(current, total int)
type ItemStatusCallback func(tweetID int64, index int, status string) // status: "success", "failed", "skipped"
type downloadTask struct {
item MediaItem
outputPath string
index int
}
type pendingDownloadTask struct {
task downloadTask
typeDir string
baseName string
ext string
}
func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir string, username string, progress ProgressCallback, itemStatus ItemStatusCallback, ctx context.Context, options DownloadOptions, customProxy string) (downloaded int, skipped int, failed int, err error) {
if ctx == nil {
ctx = context.Background()
}
options = NormalizeDownloadOptions(options)
total := len(items)
if total == 0 {
return 0, 0, 0, nil
}
tweetMediaCount := make(map[string]map[int64]int)
pendingTasks := make([]pendingDownloadTask, 0, total)
filenameCounts := make(map[string]int)
downloadDate := time.Now().Format("20060102")
for i, item := range items {
itemUsername := item.Username
if itemUsername == "" {
itemUsername = username
}
itemAccountName := item.AccountName
if itemAccountName == "" {
itemAccountName = itemUsername
}
if tweetMediaCount[itemUsername] == nil {
tweetMediaCount[itemUsername] = make(map[int64]int)
}
var subfolder string
switch item.Type {
case "photo":
subfolder = "images"
case "video":
subfolder = "videos"
case "gif", "animated_gif":
subfolder = "gifs"
case "text":
subfolder = "texts"
default:
subfolder = "other"
}
baseDir := filepath.Join(outputDir, renderFolder(options.FolderTemplate, itemUsername, itemAccountName, downloadDate))
if err := os.MkdirAll(baseDir, 0755); err != nil {
continue
}
typeDir := filepath.Join(baseDir, subfolder)
if err := os.MkdirAll(typeDir, 0755); err != nil {
continue
}
timestamp := formatTimestamp(item.Date)
ext := getExtension(item.URL, item.Type)
tweetMediaCount[itemUsername][item.TweetID]++
mediaIndex := tweetMediaCount[itemUsername][item.TweetID]
mediaID := item.OriginalFilename
if mediaID == "" {
mediaID = ExtractOriginalFilename(item.URL)
}
baseName := renderFilename(options.FilenameTemplate, itemUsername, itemAccountName, timestamp, item.TweetID, item.Type, mediaIndex, mediaID)
filenameCounts[filenameCollisionKey(typeDir, baseName, ext)]++
pendingTasks = append(pendingTasks, pendingDownloadTask{
task: downloadTask{
item: item,
index: i,
},
typeDir: typeDir,
baseName: baseName,
ext: ext,
})
}
filenameIndexes := make(map[string]int, len(filenameCounts))
tasks := make([]downloadTask, 0, len(pendingTasks))
for _, pending := range pendingTasks {
key := filenameCollisionKey(pending.typeDir, pending.baseName, pending.ext)
filenameIndexes[key]++
filename := formatDownloadFilename(
pending.baseName,
pending.ext,
filenameCounts[key],
filenameIndexes[key],
)
if options.SkipExistingFiles {
canonicalPath := filepath.Join(pending.typeDir, formatDownloadFilename(pending.baseName, pending.ext, 1, 1))
if exists, err := fileExists(canonicalPath); err == nil && exists {
pending.task.outputPath = canonicalPath
tasks = append(tasks, pending.task)
continue
}
}
pending.task.outputPath = filepath.Join(pending.typeDir, filename)
tasks = append(tasks, pending.task)
}
var downloadedCount int64
var skippedCount int64
var failedCount int64
var completedCount int64
var conversionWG sync.WaitGroup
taskChan := make(chan downloadTask, len(tasks))
var wg sync.WaitGroup
numWorkers := options.ConcurrentDownloads
if numWorkers > len(tasks) {
numWorkers = len(tasks)
}
sharedClient := createMediaDownloadClient(customProxy, options)
throttle := newDownloadThrottle(options)
for i := 0; i < numWorkers; i++ {
wg.Add(1)
go func() {
defer wg.Done()
client := sharedClient
for task := range taskChan {
markCompleted := func() {
completed := atomic.AddInt64(&completedCount, 1)
if progress != nil {
progress(int(completed), total)
}
}
if ctx.Err() != nil {
if itemStatus != nil {
itemStatus(task.item.TweetID, task.index, "cancelled")
}
markCompleted()
continue
}
var status string
if options.SkipExistingFiles {
exists, err := fileExists(task.outputPath)
if err == nil && exists {
status = "skipped"
if itemStatus != nil {
itemStatus(task.item.TweetID, task.index, status)
}
atomic.AddInt64(&skippedCount, 1)
markCompleted()
continue
}
}
if task.item.Type == "text" {
if ctx.Err() != nil {
if itemStatus != nil {
itemStatus(task.item.TweetID, task.index, "cancelled")
}
markCompleted()
continue
}
if err := writeTextFileWithOptions(task.outputPath, task.item.Content, options); err != nil {
atomic.AddInt64(&failedCount, 1)
status = "failed"
} else {
atomic.AddInt64(&downloadedCount, 1)
status = "success"
}
} else if err := downloadFileWithRetry(ctx, client, task.item.URL, task.outputPath, options, throttle); err != nil {
if ctx.Err() != nil || errors.Is(err, context.Canceled) {
if itemStatus != nil {
itemStatus(task.item.TweetID, task.index, "cancelled")
}
markCompleted()
continue
}
atomic.AddInt64(&failedCount, 1)
status = "failed"
} else {
tweetURL := fmt.Sprintf("https://x.com/i/status/%d", task.item.TweetID)
originalFilename := ExtractOriginalFilename(task.item.URL)
if ctx.Err() == nil {
if err := EmbedMetadata(ctx, task.outputPath, task.item.Content, tweetURL, originalFilename); err != nil && !errors.Is(err, context.Canceled) {
}
}
atomic.AddInt64(&downloadedCount, 1)
status = "success"
if shouldAutoConvertGIF(task.item.Type, options) && ctx.Err() == nil {
conversionWG.Add(1)
go func(inputPath string) {
defer conversionWG.Done()
outputPath := strings.TrimSuffix(inputPath, filepath.Ext(inputPath)) + ".gif"
_ = ConvertMP4ToGIFWithContext(ctx, inputPath, outputPath, normalizeGIFQuality(options.GIFQuality), normalizeGIFResolution(options.GIFResolution))
}(task.outputPath)
}
}
if itemStatus != nil {
itemStatus(task.item.TweetID, task.index, status)
}
markCompleted()
}
}()
}
for _, task := range tasks {
select {
case <-ctx.Done():
close(taskChan)
wg.Wait()
return int(downloadedCount), int(skippedCount), int(failedCount), ctx.Err()
case taskChan <- task:
}
}
close(taskChan)
wg.Wait()
conversionWG.Wait()
if err := ctx.Err(); err != nil {
return int(downloadedCount), int(skippedCount), int(failedCount), err
}
return int(downloadedCount), int(skippedCount), int(failedCount), nil
}
func shouldAutoConvertGIF(mediaType string, options DownloadOptions) bool {
if !options.AutoConvertGIFs || !IsFFmpegInstalled() {
return false
}
switch mediaType {
case "gif", "animated_gif":
return true
default:
return false
}
}
func normalizeGIFQuality(quality string) string {
if quality == "better" {
return quality
}
return "fast"
}
func normalizeGIFResolution(resolution string) string {
switch resolution {
case "original", "high", "medium", "low":
return resolution
default:
return "original"
}
}
func downloadFileWithContext(ctx context.Context, client *http.Client, url, outputPath string, allowOverwrite bool, keepPartialOnFailure bool, throttle *downloadThrottle) error {
if err := throttle.waitForRequest(ctx); err != nil {
return err
}
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
if err != nil {
return err
}
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("bad status: %s", resp.Status)
}
out, err := os.CreateTemp(filepath.Dir(outputPath), filepath.Base(outputPath)+".*.part")
if err != nil {
return err
}
tempPath := out.Name()
cleanupTemp := !keepPartialOnFailure
defer func() {
if out != nil {
_ = out.Close()
}
if cleanupTemp {
_ = os.Remove(tempPath)
}
}()
writer := io.Writer(out)
if throttle != nil && throttle.speedBytesPerSecond > 0 {
writer = throttledWriter{ctx: ctx, writer: out, throttle: throttle}
}
_, err = io.Copy(writer, resp.Body)
if err != nil {
return err
}
if err := out.Close(); err != nil {
return err
}
out = nil
if ctx.Err() != nil {
return ctx.Err()
}
if err := replaceFile(tempPath, outputPath, allowOverwrite); err != nil {
return err
}
cleanupTemp = false
return nil
}
func formatTimestamp(dateStr string) string {
formats := []string{
"2006-01-02T15:04:05",
"2006-01-02T15:04:05+00:00",
"2006-01-02T15:04:05-07:00",
time.RFC3339,
"2006-01-02T15:04:05.000Z",
"2006-01-02T15:04:05Z",
"2006-01-02 15:04:05",
"Mon Jan 02 15:04:05 -0700 2006",
}
for _, format := range formats {
if t, err := time.Parse(format, dateStr); err == nil {
return t.Format("20060102_150405")
}
}
return "00000000_000000"
}
func renderFilename(template, username, accountName, timestamp string, tweetID int64, mediaType string, index int, mediaID string) string {
if strings.TrimSpace(template) == "" {
template = "{handle}_{date}_{tweet_id}"
}
replacer := strings.NewReplacer(
"{handle}", sanitizeFilenamePart(username),
"{name}", sanitizeFilenamePart(accountName),
"{username}", sanitizeFilenamePart(username),
"{account_name}", sanitizeFilenamePart(accountName),
"{date}", timestamp,
"{tweet_id}", fmt.Sprintf("%d", tweetID),
"{index}", fmt.Sprintf("%02d", index),
"{media_id}", sanitizeFilenamePart(mediaID),
"{type}", sanitizeFilenamePart(mediaType),
)
name := strings.TrimSpace(replacer.Replace(template))
name = sanitizeFilenamePart(name)
if name == "" {
name = sanitizeFilenamePart(fmt.Sprintf("%s_%s_%d", username, timestamp, tweetID))
}
return name
}
func filenameCollisionKey(dir, baseName, ext string) string {
return dir + "\x00" + baseName + ext
}
func formatDownloadFilename(baseName, ext string, duplicateCount, duplicateIndex int) string {
if duplicateCount > 1 {
return fmt.Sprintf("%s_%02d%s", baseName, duplicateIndex, ext)
}
return baseName + ext
}
func renderFolder(template, username, accountName, date string) string {
if strings.TrimSpace(template) == "" {
template = "{handle}"
}
replacer := strings.NewReplacer(
"{handle}", sanitizeFilenamePart(username),
"{name}", sanitizeFilenamePart(accountName),
"{username}", sanitizeFilenamePart(username),
"{account_name}", sanitizeFilenamePart(accountName),
"{date}", date,
)
name := strings.TrimSpace(replacer.Replace(template))
name = sanitizeFilenamePart(name)
if name == "" {
name = sanitizeFilenamePart(username)
}
return name
}
func sanitizeFilenamePart(s string) string {
cleaned := strings.TrimSpace(strings.Map(func(r rune) rune {
switch r {
case '\\', '/', ':', '*', '?', '"', '<', '>', '|':
return -1
}
if r >= 0 && r < 32 {
return -1
}
return r
}, s))
cleaned = strings.TrimRight(cleaned, ". ")
if isWindowsReservedName(cleaned) {
return cleaned + "_"
}
return cleaned
}
func isWindowsReservedName(name string) bool {
base := name
if dotIndex := strings.IndexByte(base, '.'); dotIndex >= 0 {
base = base[:dotIndex]
}
base = strings.ToUpper(strings.TrimSpace(base))
switch base {
case "CON", "PRN", "AUX", "NUL":
return true
}
return len(base) == 4 &&
((strings.HasPrefix(base, "COM") && base[3] >= '1' && base[3] <= '9') ||
(strings.HasPrefix(base, "LPT") && base[3] >= '1' && base[3] <= '9'))
}
func getExtension(mediaURL string, mediaType string) string {
parsedURL, err := url.Parse(mediaURL)
if err != nil {
return ".jpg"
}
if format := parsedURL.Query().Get("format"); format != "" {
return "." + format
}
path := parsedURL.Path
ext := filepath.Ext(path)
if ext != "" {
return ext
}
switch mediaType {
case "video":
return ".mp4"
case "gif", "animated_gif":
return ".mp4"
case "text":
return ".txt"
default:
return ".jpg"
}
}
func extractFilename(mediaURL string) string {
parsedURL, err := url.Parse(mediaURL)
if err != nil {
return fmt.Sprintf("media_%d", time.Now().UnixNano())
}
path := parsedURL.Path
base := filepath.Base(path)
if strings.Contains(mediaURL, "pbs.twimg.com/media/") {
format := parsedURL.Query().Get("format")
if format == "" {
format = "jpg"
}
if idx := strings.LastIndex(base, "."); idx > 0 {
base = base[:idx]
}
return base + "." + format
}
if strings.Contains(mediaURL, "video.twimg.com") {
return base
}
if base == "" || base == "." {
return fmt.Sprintf("media_%d", time.Now().UnixNano())
}
return base
}
func downloadFile(client *http.Client, url, outputPath string) error {
return downloadFileWithRetry(context.Background(), client, url, outputPath, DownloadOptions{
SkipExistingFiles: false,
DeleteIncompleteFiles: true,
RetryAttempts: 0,
}, nil)
}
func DownloadProfileImage(imageURL, outputDir, username, kind, customProxy string) (string, error) {
if strings.TrimSpace(imageURL) == "" {
return "", fmt.Errorf("no %s url available", kind)
}
baseDir := outputDir
if username != "" {
baseDir = filepath.Join(outputDir, username)
}
if err := os.MkdirAll(baseDir, 0755); err != nil {
return "", fmt.Errorf("failed to create output directory: %v", err)
}
ext := getExtension(imageURL, "photo")
filename := fmt.Sprintf("%s_%s%s", sanitizeFilenamePart(username), kind, ext)
outputPath := filepath.Join(baseDir, filename)
client, err := CreateHTTPClient(customProxy, 60*time.Second)
if err != nil {
client = &http.Client{Timeout: 60 * time.Second}
}
if err := downloadFile(client, imageURL, outputPath); err != nil {
return "", fmt.Errorf("failed to download %s: %v", kind, err)
}
return outputPath, nil
}
+558
View File
@@ -0,0 +1,558 @@
package backend
import (
"archive/zip"
"encoding/json"
"encoding/xml"
"fmt"
"html"
"io"
"net/http"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"strings"
"time"
)
const (
exiftoolBestReleaseAPIURL = "https://sourceforge.net/projects/exiftool/best_release.json"
exiftoolRSSURL = "https://sourceforge.net/projects/exiftool/rss?path=/"
exiftoolFilesBaseURL = "https://sourceforge.net/projects/exiftool/files"
sourceForgeUserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36"
)
var (
exiftoolVersionPattern = regexp.MustCompile(`(?i)(?:exiftool|image-exiftool)-([0-9]+(?:\.[0-9]+)+)`)
sourceForgeMirrorMetaPattern = regexp.MustCompile(`(?i)url=(https?://downloads\.sourceforge\.net/project/[^"'<> ]+)`)
sourceForgeMirrorURLPattern = regexp.MustCompile(`https?://downloads\.sourceforge\.net/project/[^"'<> ]+`)
)
type sourceForgeBestRelease struct {
Release sourceForgeBestReleaseFile `json:"release"`
}
type sourceForgeBestReleaseFile struct {
Filename string `json:"filename"`
URL string `json:"url"`
}
type sourceForgeRSS struct {
Channel sourceForgeRSSChannel `xml:"channel"`
}
type sourceForgeRSSChannel struct {
Items []sourceForgeRSSItem `xml:"item"`
}
type sourceForgeRSSItem struct {
Title string `xml:"title"`
Link string `xml:"link"`
}
func GetExifToolPath() string {
homeDir, _ := os.UserHomeDir()
baseDir := filepath.Join(homeDir, ".twitterxmediabatchdownloader")
switch runtime.GOOS {
case "windows":
return filepath.Join(baseDir, "exiftool.exe")
default:
pattern := filepath.Join(baseDir, "Image-ExifTool-*")
matches, err := filepath.Glob(pattern)
if err == nil && len(matches) > 0 {
exiftoolPath := filepath.Join(matches[0], "exiftool")
if _, err := os.Stat(exiftoolPath); err == nil {
return exiftoolPath
}
}
return filepath.Join(baseDir, "exiftool")
}
}
func IsExifToolInstalled() bool {
_, err := getInstalledExifToolVersion()
return err == nil
}
func GetExifToolVersionStatus() DependencyVersionStatus {
status := DependencyVersionStatus{
Installed: IsExifToolInstalled(),
}
if status.Installed {
if installedVersion, err := getInstalledExifToolVersion(); err == nil {
status.InstalledVersion = installedVersion
}
}
if latestVersion, err := fetchLatestExifToolVersion(); err == nil {
status.LatestVersion = latestVersion
}
return status
}
func getInstalledExifToolVersion() (string, error) {
exiftoolPath := GetExifToolPath()
if _, err := os.Stat(exiftoolPath); err != nil {
return "", fmt.Errorf("exiftool not installed")
}
cmd := exec.Command(exiftoolPath, "-ver")
hideWindow(cmd)
output, err := cmd.Output()
if err != nil {
return "", fmt.Errorf("failed to determine exiftool version: %v", err)
}
version := normalizeExifToolVersion(string(output))
if version == "" {
return "", fmt.Errorf("failed to determine exiftool version")
}
return version, nil
}
func normalizeExifToolVersion(version string) string {
version = strings.TrimSpace(version)
if version == "" {
return ""
}
fields := strings.Fields(version)
if len(fields) > 0 {
version = fields[0]
}
if strings.HasPrefix(strings.ToLower(version), "v") {
version = strings.TrimPrefix(strings.TrimPrefix(version, "v"), "V")
}
if version == "" {
return ""
}
first := version[0]
if first >= '0' && first <= '9' {
return "v" + version
}
return version
}
func is64Bit() bool {
return runtime.GOARCH == "amd64" || runtime.GOARCH == "arm64"
}
func DownloadExifTool(progressCallback func(downloaded, total int64)) error {
latestVersion, err := fetchLatestExifToolVersion()
if err != nil {
return err
}
downloadURL, err := buildLatestExifToolDownloadURL(latestVersion)
if err != nil {
return err
}
tempFile, err := os.CreateTemp("", "exiftool-*")
if err != nil {
return fmt.Errorf("failed to create temp file: %v", err)
}
tempPath := tempFile.Name()
defer os.Remove(tempPath)
if err := tempFile.Close(); err != nil {
return fmt.Errorf("failed to prepare temp file: %v", err)
}
if err := downloadSourceForgeFile(downloadURL, tempPath, progressCallback); err != nil {
return err
}
exiftoolPath := GetExifToolPath()
baseDir := filepath.Dir(exiftoolPath)
if err := os.MkdirAll(baseDir, 0755); err != nil {
return fmt.Errorf("failed to create directory: %v", err)
}
switch runtime.GOOS {
case "windows":
return extractExifToolFromZip(tempPath, exiftoolPath)
case "linux", "darwin":
return extractExifToolFromTarGz(tempPath, exiftoolPath)
}
return nil
}
func fetchLatestExifToolVersion() (string, error) {
version, err := fetchLatestExifToolVersionFromBestRelease()
if err == nil {
return version, nil
}
fallbackVersion, fallbackErr := fetchLatestExifToolVersionFromRSS()
if fallbackErr == nil {
return fallbackVersion, nil
}
return "", fmt.Errorf("failed to fetch latest exiftool version: %v; fallback failed: %v", err, fallbackErr)
}
func fetchLatestExifToolVersionFromBestRelease() (string, error) {
client, err := CreateHTTPClient("", 30*time.Second)
if err != nil {
return "", fmt.Errorf("failed to configure exiftool release client: %v", err)
}
req, err := http.NewRequest(http.MethodGet, exiftoolBestReleaseAPIURL, nil)
if err != nil {
return "", fmt.Errorf("failed to create exiftool release request: %v", err)
}
req.Header.Set("Accept", "application/json")
req.Header.Set("User-Agent", sourceForgeUserAgent)
resp, err := client.Do(req)
if err != nil {
return "", fmt.Errorf("failed to fetch exiftool release info: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("failed to fetch exiftool release info: status %d", resp.StatusCode)
}
var bestRelease sourceForgeBestRelease
if err := json.NewDecoder(resp.Body).Decode(&bestRelease); err != nil {
return "", fmt.Errorf("failed to decode exiftool release info: %v", err)
}
version := parseExifToolVersion(bestRelease.Release.Filename)
if version == "" {
version = parseExifToolVersion(bestRelease.Release.URL)
}
if version == "" {
return "", fmt.Errorf("failed to parse exiftool version from best_release.json")
}
return version, nil
}
func fetchLatestExifToolVersionFromRSS() (string, error) {
client, err := CreateHTTPClient("", 30*time.Second)
if err != nil {
return "", fmt.Errorf("failed to configure exiftool RSS client: %v", err)
}
req, err := http.NewRequest(http.MethodGet, exiftoolRSSURL, nil)
if err != nil {
return "", fmt.Errorf("failed to create exiftool RSS request: %v", err)
}
req.Header.Set("Accept", "application/rss+xml, application/xml, text/xml")
req.Header.Set("User-Agent", sourceForgeUserAgent)
resp, err := client.Do(req)
if err != nil {
return "", fmt.Errorf("failed to fetch exiftool RSS: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("failed to fetch exiftool RSS: status %d", resp.StatusCode)
}
var feed sourceForgeRSS
if err := xml.NewDecoder(resp.Body).Decode(&feed); err != nil {
return "", fmt.Errorf("failed to decode exiftool RSS: %v", err)
}
for _, item := range feed.Channel.Items {
version := parseExifToolVersion(item.Title)
if version == "" {
version = parseExifToolVersion(item.Link)
}
if version != "" {
return version, nil
}
}
return "", fmt.Errorf("failed to find exiftool version in RSS feed")
}
func parseExifToolVersion(value string) string {
matches := exiftoolVersionPattern.FindStringSubmatch(value)
if len(matches) < 2 {
return ""
}
return normalizeExifToolVersion(matches[1])
}
func buildLatestExifToolDownloadURL(version string) (string, error) {
version = normalizeExifToolVersion(version)
if version == "" {
return "", fmt.Errorf("missing exiftool version")
}
version = strings.TrimPrefix(strings.TrimPrefix(version, "v"), "V")
switch runtime.GOOS {
case "windows":
if is64Bit() {
return fmt.Sprintf("%s/exiftool-%s_64.zip/download", exiftoolFilesBaseURL, version), nil
}
return fmt.Sprintf("%s/exiftool-%s_32.zip/download", exiftoolFilesBaseURL, version), nil
case "linux", "darwin":
return fmt.Sprintf("%s/Image-ExifTool-%s.tar.gz/download", exiftoolFilesBaseURL, version), nil
default:
return "", fmt.Errorf("unsupported platform: %s", runtime.GOOS)
}
}
func downloadSourceForgeFile(downloadURL, destinationPath string, progressCallback func(downloaded, total int64)) error {
client, err := CreateHTTPClient("", 10*time.Minute)
if err != nil {
return fmt.Errorf("failed to configure SourceForge download client: %v", err)
}
err = downloadSourceForgeURL(client, downloadURL, destinationPath, progressCallback, 0)
if err == nil {
return nil
}
if runtime.GOOS == "windows" {
if fallbackErr := downloadSourceForgeFileWithCurl(downloadURL, destinationPath); fallbackErr == nil {
return nil
} else {
return fmt.Errorf("%v; curl fallback failed: %v", err, fallbackErr)
}
}
return err
}
func downloadSourceForgeURL(client *http.Client, downloadURL, destinationPath string, progressCallback func(downloaded, total int64), depth int) error {
if depth > 4 {
return fmt.Errorf("failed to resolve SourceForge mirror URL")
}
req, err := http.NewRequest(http.MethodGet, downloadURL, nil)
if err != nil {
return fmt.Errorf("failed to create SourceForge download request: %v", err)
}
req.Header.Set("User-Agent", sourceForgeUserAgent)
resp, err := client.Do(req)
if err != nil {
return fmt.Errorf("failed to download exiftool: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("failed to download exiftool: status %d", resp.StatusCode)
}
contentType := strings.ToLower(resp.Header.Get("Content-Type"))
if strings.Contains(contentType, "text/html") {
body, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("failed to read SourceForge download page: %v", err)
}
resolvedURL := extractSourceForgeMirrorURL(string(body))
if resolvedURL == "" {
return fmt.Errorf("failed to resolve SourceForge mirror URL from download page")
}
return downloadSourceForgeURL(client, resolvedURL, destinationPath, progressCallback, depth+1)
}
destination, err := os.OpenFile(destinationPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)
if err != nil {
return fmt.Errorf("failed to create exiftool archive: %v", err)
}
defer destination.Close()
total := resp.ContentLength
var downloaded int64
buf := make([]byte, 32*1024)
for {
n, err := resp.Body.Read(buf)
if n > 0 {
if _, writeErr := destination.Write(buf[:n]); writeErr != nil {
return fmt.Errorf("failed to write exiftool archive: %v", writeErr)
}
downloaded += int64(n)
if progressCallback != nil {
progressCallback(downloaded, total)
}
}
if err == io.EOF {
break
}
if err != nil {
return fmt.Errorf("failed to download exiftool: %v", err)
}
}
return nil
}
func downloadSourceForgeFileWithCurl(downloadURL, destinationPath string) error {
curlPath, err := exec.LookPath("curl.exe")
if err != nil {
curlPath, err = exec.LookPath("curl")
if err != nil {
return fmt.Errorf("curl executable not found")
}
}
cmd := exec.Command(curlPath, "-L", "-o", destinationPath, downloadURL)
hideWindow(cmd)
output, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("failed to download via curl: %v, output: %s", err, string(output))
}
return nil
}
func extractSourceForgeMirrorURL(page string) string {
page = html.UnescapeString(page)
if matches := sourceForgeMirrorMetaPattern.FindStringSubmatch(page); len(matches) > 1 {
return strings.TrimSpace(matches[1])
}
return strings.TrimSpace(sourceForgeMirrorURLPattern.FindString(page))
}
func extractExifToolFromZip(zipPath, destPath string) error {
r, err := zip.OpenReader(zipPath)
if err != nil {
return fmt.Errorf("failed to open zip: %v", err)
}
defer r.Close()
var exiftoolFile *zip.File
for _, f := range r.File {
name := filepath.Base(f.Name)
if name == "exiftool(-k).exe" || name == "exiftool.exe" {
exiftoolFile = f
break
}
}
if exiftoolFile == nil {
return fmt.Errorf("exiftool.exe not found in archive")
}
rc, err := exiftoolFile.Open()
if err != nil {
return fmt.Errorf("failed to open file in zip: %v", err)
}
defer rc.Close()
out, err := os.Create(destPath)
if err != nil {
return fmt.Errorf("failed to create output file: %v", err)
}
defer out.Close()
if _, err := io.Copy(out, rc); err != nil {
return fmt.Errorf("failed to extract file: %v", err)
}
libDir := filepath.Join(filepath.Dir(destPath), "exiftool_files")
libDirAbs, err := filepath.Abs(libDir)
if err != nil {
return fmt.Errorf("failed to resolve libDir: %v", err)
}
for _, f := range r.File {
if strings.Contains(f.Name, "exiftool_files") && !strings.HasSuffix(f.Name, "/") {
parts := strings.Split(f.Name, "exiftool_files/")
if len(parts) < 2 {
continue
}
relPath := parts[1]
if relPath == "" {
continue
}
targetPath := filepath.Join(libDir, relPath)
targetAbs, err := filepath.Abs(targetPath)
if err != nil {
continue
}
if !strings.HasPrefix(targetAbs+string(os.PathSeparator), libDirAbs+string(os.PathSeparator)) && targetAbs != libDirAbs {
continue
}
if err := os.MkdirAll(filepath.Dir(targetPath), 0755); err != nil {
continue
}
if f.FileInfo().IsDir() {
os.MkdirAll(targetPath, 0755)
continue
}
rc, err := f.Open()
if err != nil {
continue
}
outFile, err := os.Create(targetPath)
if err != nil {
rc.Close()
continue
}
io.Copy(outFile, rc)
outFile.Close()
rc.Close()
}
}
return nil
}
func extractExifToolFromTarGz(tarGzPath, destPath string) error {
baseDir := filepath.Dir(destPath)
cmd := exec.Command("tar", "-xzf", tarGzPath, "-C", baseDir)
hideWindow(cmd)
output, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("failed to extract tar.gz: %v, output: %s", err, string(output))
}
var extractedDir string
var exiftoolScript string
pattern := filepath.Join(baseDir, "Image-ExifTool-*")
matches, err := filepath.Glob(pattern)
if err == nil && len(matches) > 0 {
extractedDir = matches[0]
exiftoolScript = filepath.Join(extractedDir, "exiftool")
} else {
extractedDir = filepath.Join(baseDir, "exiftool")
exiftoolScript = filepath.Join(extractedDir, "exiftool")
}
if _, err := os.Stat(exiftoolScript); err != nil {
return fmt.Errorf("exiftool script not found in extracted archive (searched in: %s and %s)", pattern, extractedDir)
}
if err := os.Chmod(exiftoolScript, 0755); err != nil {
return fmt.Errorf("failed to make exiftool executable: %v", err)
}
return nil
}
+618
View File
@@ -0,0 +1,618 @@
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"
const extractorReleasesAPIURL = "https://api.github.com/repos/afkarxyz/xtractor-binaries/releases"
const extractorReleasePageSize = 20
type ExtractorVersionStatus struct {
Installed bool `json:"installed"`
InstalledVersion string `json:"installed_version,omitempty"`
LatestVersion string `json:"latest_version,omitempty"`
}
type extractorVersionMetadata struct {
Version string `json:"version"`
AssetName string `json:"asset_name,omitempty"`
}
type githubRelease struct {
TagName string `json:"tag_name"`
Draft bool `json:"draft"`
Prerelease bool `json:"prerelease"`
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 GetExtractorVersionStatus() ExtractorVersionStatus {
status := ExtractorVersionStatus{
Installed: IsExtractorInstalled(),
}
assetName, assetErr := getExtractorAssetName()
if status.Installed && assetErr == nil {
if installedVersion, err := getInstalledExtractorVersion(assetName); err == nil {
status.InstalledVersion = installedVersion
}
}
if latestRelease, err := fetchLatestExtractorRelease(); err == nil {
status.LatestVersion = normalizeExtractorVersion(latestRelease.TagName)
}
return status
}
func DownloadExtractor(progressCallback func(downloaded, total int64)) error {
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()
_ = writeExtractorVersionMetadata(extractorVersionMetadata{
Version: normalizeExtractorVersion(release.TagName),
AssetName: asset.Name,
})
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":
switch runtime.GOARCH {
case "amd64":
return "linux-amd64.zip", nil
case "arm64":
return "linux-arm64.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 ""
}
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 := newExtractorGitHubRequest(extractorReleaseAPIURL)
if err != nil {
return nil, err
}
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 fetchExtractorReleases(limit int) ([]githubRelease, error) {
client, err := CreateHTTPClient("", 60*time.Second)
if err != nil {
return nil, fmt.Errorf("failed to configure xtractor release client: %v", err)
}
req, err := newExtractorGitHubRequest(fmt.Sprintf("%s?per_page=%d", extractorReleasesAPIURL, limit))
if err != nil {
return nil, err
}
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to fetch xtractor releases: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("failed to fetch xtractor releases: status %d", resp.StatusCode)
}
var releases []githubRelease
if err := json.NewDecoder(resp.Body).Decode(&releases); err != nil {
return nil, fmt.Errorf("failed to decode xtractor releases: %v", err)
}
return releases, nil
}
func newExtractorGitHubRequest(url string) (*http.Request, error) {
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return nil, fmt.Errorf("failed to create xtractor GitHub request: %v", err)
}
req.Header.Set("Accept", "application/vnd.github+json")
req.Header.Set("User-Agent", "Twitter-X-Media-Batch-Downloader")
return req, nil
}
func findExtractorAsset(assets []githubReleaseAsset, assetName string) (*githubReleaseAsset, error) {
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 getInstalledExtractorVersion(assetName string) (string, error) {
metadata, err := readExtractorVersionMetadata()
if err == nil {
version := normalizeExtractorVersion(metadata.Version)
if version != "" && (metadata.AssetName == "" || strings.EqualFold(metadata.AssetName, assetName)) {
return version, nil
}
}
version, err := resolveInstalledExtractorVersionByHash(assetName)
if err != nil {
return "", err
}
version = normalizeExtractorVersion(version)
if version != "" {
_ = writeExtractorVersionMetadata(extractorVersionMetadata{
Version: version,
AssetName: assetName,
})
}
return version, nil
}
func resolveInstalledExtractorVersionByHash(assetName string) (string, error) {
exePath, err := requireExtractorPath()
if err != nil {
return "", err
}
installedHash, err := hashFileSHA256(exePath)
if err != nil {
return "", fmt.Errorf("failed to hash installed xtractor: %v", err)
}
releases, err := fetchExtractorReleases(extractorReleasePageSize)
if err != nil {
return "", err
}
for _, release := range releases {
asset, err := findExtractorAsset(release.Assets, assetName)
if err != nil {
continue
}
matches, err := archiveMatchesExtractorHash(asset.BrowserDownloadURL, installedHash)
if err != nil {
continue
}
if matches {
return release.TagName, nil
}
}
return "", nil
}
func archiveMatchesExtractorHash(downloadURL, installedHash string) (bool, error) {
tempFile, err := os.CreateTemp("", "xtractor-version-*.zip")
if err != nil {
return false, fmt.Errorf("failed to create temp archive for version check: %v", err)
}
tempPath := tempFile.Name()
defer os.Remove(tempPath)
defer tempFile.Close()
if err := downloadExtractorArchive(downloadURL, tempFile, nil); err != nil {
return false, err
}
if err := tempFile.Close(); err != nil {
return false, fmt.Errorf("failed to finalize version archive: %v", err)
}
archiveHash, err := hashExtractorBinaryInArchive(tempPath)
if err != nil {
return false, err
}
return archiveHash == installedHash, nil
}
func hashExtractorBinaryInArchive(zipPath string) (string, error) {
reader, err := zip.OpenReader(zipPath)
if err != nil {
return "", fmt.Errorf("failed to open xtractor archive for version check: %v", err)
}
defer reader.Close()
entry, err := findExtractorBinaryEntry(reader.File)
if err != nil {
return "", err
}
in, err := entry.Open()
if err != nil {
return "", fmt.Errorf("failed to open xtractor binary from archive for version check: %v", err)
}
defer in.Close()
return hashReaderSHA256(in)
}
func hashFileSHA256(filePath string) (string, error) {
file, err := os.Open(filePath)
if err != nil {
return "", fmt.Errorf("failed to open xtractor binary: %v", err)
}
defer file.Close()
return hashReaderSHA256(file)
}
func hashReaderSHA256(reader io.Reader) (string, error) {
hash := sha256.New()
if _, err := io.Copy(hash, reader); err != nil {
return "", err
}
return hex.EncodeToString(hash.Sum(nil)), nil
}
func getExtractorVersionMetadataPath() string {
return filepath.Join(filepath.Dir(getExtractorPath()), "xtractor-version.json")
}
func readExtractorVersionMetadata() (extractorVersionMetadata, error) {
data, err := os.ReadFile(getExtractorVersionMetadataPath())
if err != nil {
return extractorVersionMetadata{}, err
}
var metadata extractorVersionMetadata
if err := json.Unmarshal(data, &metadata); err != nil {
return extractorVersionMetadata{}, err
}
return metadata, nil
}
func writeExtractorVersionMetadata(metadata extractorVersionMetadata) error {
metadata.Version = normalizeExtractorVersion(metadata.Version)
if metadata.Version == "" {
return nil
}
path := getExtractorVersionMetadataPath()
if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
return fmt.Errorf("failed to create xtractor metadata directory: %v", err)
}
data, err := json.Marshal(metadata)
if err != nil {
return fmt.Errorf("failed to encode xtractor metadata: %v", err)
}
if err := os.WriteFile(path, data, 0644); err != nil {
return fmt.Errorf("failed to write xtractor metadata: %v", err)
}
return nil
}
func normalizeExtractorVersion(version string) string {
return strings.TrimSpace(version)
}
func getLegacyExtractorPath() string {
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
}
+683
View File
@@ -0,0 +1,683 @@
package backend
import (
"archive/zip"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
neturl "net/url"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"strings"
"time"
)
const (
ffmpegReleasesAPIURL = "https://api.github.com/repos/spotbye/Dependencies/releases?per_page=100"
ffmpegReleaseTagPrefix = "FFmpeg-"
ffmpegFallbackReleaseTag = "FFmpeg-9.0"
ffmpegFallbackReleaseURL = "https://github.com/spotbye/Dependencies/releases/tag/" + ffmpegFallbackReleaseTag
ffmpegFallbackDownloadBaseURL = "https://github.com/spotbye/Dependencies/releases/download/" + ffmpegFallbackReleaseTag
)
var ffmpegVersionPattern = regexp.MustCompile(`^[0-9]+(?:\.[0-9]+)+`)
type ffmpegVersionMetadata struct {
Version string `json:"version"`
AssetName string `json:"asset_name,omitempty"`
}
type ffmpegResolvedRelease struct {
Version string
AssetURL string
AssetName string
Digest string
}
func GetFFmpegPath() string {
homeDir, _ := os.UserHomeDir()
baseDir := filepath.Join(homeDir, ".twitterxmediabatchdownloader")
switch runtime.GOOS {
case "windows":
return filepath.Join(baseDir, "ffmpeg.exe")
default:
return filepath.Join(baseDir, "ffmpeg")
}
}
func IsFFmpegInstalled() bool {
ffmpegPath := GetFFmpegPath()
if _, err := os.Stat(ffmpegPath); err != nil {
return false
}
cmd := exec.Command(ffmpegPath, "-version")
hideWindow(cmd)
return cmd.Run() == nil
}
func GetFFmpegVersionStatus() DependencyVersionStatus {
status := DependencyVersionStatus{
Installed: IsFFmpegInstalled(),
}
if status.Installed {
if installedVersion, err := getInstalledFFmpegVersion(); err == nil {
status.InstalledVersion = installedVersion
}
}
if latestVersion, err := fetchLatestFFmpegVersion(); err == nil {
status.LatestVersion = latestVersion
}
return status
}
func DownloadFFmpeg(progressCallback func(downloaded, total int64)) error {
assetName, err := getFFmpegAssetName()
if err != nil {
return err
}
releaseInfo, err := resolveLatestFFmpegRelease(assetName)
if err != nil {
return err
}
tempFile, err := os.CreateTemp("", "ffmpeg-*.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 := downloadFFmpegArchive(releaseInfo.AssetURL, tempFile, progressCallback); err != nil {
return err
}
if err := tempFile.Close(); err != nil {
return fmt.Errorf("failed to finalize ffmpeg archive: %v", err)
}
if releaseInfo.Digest != "" {
if err := verifyDownloadedDigest(tempPath, releaseInfo.Digest); err != nil {
return err
}
}
ffmpegPath := GetFFmpegPath()
baseDir := filepath.Dir(ffmpegPath)
if err := os.MkdirAll(baseDir, 0755); err != nil {
return fmt.Errorf("failed to create ffmpeg directory: %v", err)
}
if err := extractFFmpegFromZip(tempPath, ffmpegPath); err != nil {
return err
}
_ = writeFFmpegVersionMetadata(ffmpegVersionMetadata{
Version: releaseInfo.Version,
AssetName: releaseInfo.AssetName,
})
return nil
}
func getFFmpegAssetName() (string, error) {
switch runtime.GOOS {
case "windows":
return "ffmpeg-windows.zip", nil
case "linux":
switch runtime.GOARCH {
case "amd64":
return "ffmpeg-linux-amd64.zip", nil
case "arm64":
return "ffmpeg-linux-arm64v8.zip", nil
}
case "darwin":
switch runtime.GOARCH {
case "amd64":
return "ffmpeg-macos-amd64.zip", nil
case "arm64":
return "ffmpeg-macos-arm64.zip", nil
}
}
return "", fmt.Errorf("unsupported platform for ffmpeg binary: %s/%s", runtime.GOOS, runtime.GOARCH)
}
func resolveLatestFFmpegRelease(assetName string) (ffmpegResolvedRelease, error) {
release, apiErr := fetchLatestFFmpegRelease()
if apiErr == nil {
asset, assetErr := findFFmpegAsset(release.Assets, assetName)
if assetErr == nil {
return ffmpegResolvedRelease{
Version: normalizeFFmpegVersion(release.TagName),
AssetURL: asset.BrowserDownloadURL,
AssetName: asset.Name,
Digest: asset.Digest,
}, nil
}
apiErr = assetErr
}
fallbackVersion, fallbackErr := fetchLatestFFmpegVersionFromRedirect()
if fallbackErr != nil {
return ffmpegResolvedRelease{}, fmt.Errorf("failed to resolve latest ffmpeg release: %v; fallback failed: %v", apiErr, fallbackErr)
}
return ffmpegResolvedRelease{
Version: fallbackVersion,
AssetURL: buildLatestFFmpegDownloadURL(assetName),
AssetName: assetName,
}, nil
}
func fetchLatestFFmpegVersion() (string, error) {
release, err := fetchLatestFFmpegRelease()
if err == nil {
version := normalizeFFmpegVersion(release.TagName)
if version != "" {
return version, nil
}
}
fallbackVersion, fallbackErr := fetchLatestFFmpegVersionFromRedirect()
if fallbackErr == nil {
return fallbackVersion, nil
}
if err != nil {
return "", fmt.Errorf("failed to fetch latest ffmpeg version: %v; fallback failed: %v", err, fallbackErr)
}
return "", fmt.Errorf("failed to determine latest ffmpeg version")
}
func fetchLatestFFmpegRelease() (*githubRelease, error) {
client, err := CreateHTTPClient("", 30*time.Second)
if err != nil {
return nil, fmt.Errorf("failed to configure ffmpeg network client: %v", err)
}
req, err := newFFmpegGitHubRequest(ffmpegReleasesAPIURL)
if err != nil {
return nil, err
}
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to fetch ffmpeg release info: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("failed to fetch ffmpeg release info: status %d", resp.StatusCode)
}
var releases []githubRelease
if err := json.NewDecoder(resp.Body).Decode(&releases); err != nil {
return nil, fmt.Errorf("failed to decode ffmpeg release info: %v", err)
}
return findLatestStableFFmpegRelease(releases)
}
func findLatestStableFFmpegRelease(releases []githubRelease) (*githubRelease, error) {
for index := range releases {
release := &releases[index]
if release.Draft || release.Prerelease || !strings.HasPrefix(strings.ToLower(release.TagName), strings.ToLower(ffmpegReleaseTagPrefix)) {
continue
}
if normalizeFFmpegVersion(release.TagName) != "" {
return release, nil
}
}
return nil, fmt.Errorf("no stable ffmpeg release found")
}
func newFFmpegGitHubRequest(url string) (*http.Request, error) {
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return nil, fmt.Errorf("failed to create ffmpeg GitHub request: %v", err)
}
req.Header.Set("Accept", "application/vnd.github+json")
req.Header.Set("User-Agent", "Twitter-X-Media-Batch-Downloader")
return req, nil
}
func findFFmpegAsset(assets []githubReleaseAsset, assetName string) (*githubReleaseAsset, error) {
for i := range assets {
if assets[i].Name == assetName {
return &assets[i], nil
}
}
return nil, fmt.Errorf("ffmpeg asset %q not found in latest release", assetName)
}
func fetchLatestFFmpegVersionFromRedirect() (string, error) {
client, err := CreateHTTPClient("", 30*time.Second)
if err != nil {
return "", fmt.Errorf("failed to configure ffmpeg redirect client: %v", err)
}
client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
}
req, err := http.NewRequest(http.MethodGet, ffmpegFallbackReleaseURL, nil)
if err != nil {
return "", fmt.Errorf("failed to create ffmpeg redirect request: %v", err)
}
req.Header.Set("User-Agent", "Twitter-X-Media-Batch-Downloader")
resp, err := client.Do(req)
if err != nil {
return "", fmt.Errorf("failed to resolve latest ffmpeg redirect: %v", err)
}
defer resp.Body.Close()
location := resp.Header.Get("Location")
if location == "" && resp.Request != nil && resp.Request.URL != nil {
location = resp.Request.URL.String()
}
version := parseFFmpegVersionFromReleaseURL(location)
if version == "" {
return "", fmt.Errorf("failed to parse ffmpeg version from redirect URL")
}
return version, nil
}
func parseFFmpegVersionFromReleaseURL(releaseURL string) string {
parsed, err := neturl.Parse(strings.TrimSpace(releaseURL))
if err != nil {
return ""
}
segments := strings.Split(strings.Trim(parsed.Path, "/"), "/")
for index, segment := range segments {
if (segment == "tag" || segment == "download") && index+1 < len(segments) {
return normalizeFFmpegVersion(segments[index+1])
}
}
return ""
}
func buildLatestFFmpegDownloadURL(assetName string) string {
return ffmpegFallbackDownloadBaseURL + "/" + assetName
}
func downloadFFmpegArchive(downloadURL string, destination *os.File, progressCallback func(downloaded, total int64)) error {
client, err := CreateHTTPClient("", 10*time.Minute)
if err != nil {
return fmt.Errorf("failed to configure ffmpeg download client: %v", err)
}
req, err := http.NewRequest(http.MethodGet, downloadURL, nil)
if err != nil {
return fmt.Errorf("failed to create ffmpeg download request: %v", err)
}
req.Header.Set("User-Agent", "Twitter-X-Media-Batch-Downloader")
resp, err := client.Do(req)
if err != nil {
return fmt.Errorf("failed to download ffmpeg: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("failed to download ffmpeg: 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 ffmpeg 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 ffmpeg: %v", err)
}
}
return nil
}
func extractFFmpegFromZip(zipPath, destPath string) error {
r, err := zip.OpenReader(zipPath)
if err != nil {
return fmt.Errorf("failed to open zip: %v", err)
}
defer r.Close()
for _, f := range r.File {
name := filepath.Base(f.Name)
if name != "ffmpeg" && name != "ffmpeg.exe" {
continue
}
rc, err := f.Open()
if err != nil {
return fmt.Errorf("failed to open file in zip: %v", err)
}
defer rc.Close()
out, err := os.Create(destPath)
if err != nil {
return fmt.Errorf("failed to create output file: %v", err)
}
defer out.Close()
if _, err := io.Copy(out, rc); err != nil {
return fmt.Errorf("failed to extract file: %v", err)
}
if runtime.GOOS != "windows" {
if err := os.Chmod(destPath, 0755); err != nil {
return fmt.Errorf("failed to make ffmpeg executable: %v", err)
}
}
return nil
}
return fmt.Errorf("ffmpeg binary not found in archive")
}
func getInstalledFFmpegVersion() (string, error) {
ffmpegPath := GetFFmpegPath()
if _, err := os.Stat(ffmpegPath); err != nil {
return "", fmt.Errorf("ffmpeg not installed")
}
cmd := exec.Command(ffmpegPath, "-version")
hideWindow(cmd)
output, err := cmd.Output()
if err == nil {
version := normalizeFFmpegVersionOutput(string(output))
if version != "" {
return version, nil
}
}
metadata, metadataErr := readFFmpegVersionMetadata()
if metadataErr == nil {
version := normalizeFFmpegVersion(metadata.Version)
if version != "" {
return version, nil
}
}
if err != nil {
return "", fmt.Errorf("failed to determine ffmpeg version: %v", err)
}
return "", fmt.Errorf("failed to determine ffmpeg version")
}
func normalizeFFmpegVersionOutput(output string) string {
line := strings.TrimSpace(output)
if line == "" {
return ""
}
line = strings.Split(line, "\n")[0]
line = strings.TrimSpace(line)
lowerLine := strings.ToLower(line)
const prefix = "ffmpeg version "
if strings.HasPrefix(lowerLine, prefix) {
line = strings.TrimSpace(line[len(prefix):])
}
fields := strings.Fields(line)
if len(fields) > 0 {
line = fields[0]
}
return normalizeFFmpegVersion(line)
}
func getFFmpegVersionMetadataPath() string {
return filepath.Join(filepath.Dir(GetFFmpegPath()), "ffmpeg-version.json")
}
func readFFmpegVersionMetadata() (ffmpegVersionMetadata, error) {
data, err := os.ReadFile(getFFmpegVersionMetadataPath())
if err != nil {
return ffmpegVersionMetadata{}, err
}
var metadata ffmpegVersionMetadata
if err := json.Unmarshal(data, &metadata); err != nil {
return ffmpegVersionMetadata{}, err
}
return metadata, nil
}
func writeFFmpegVersionMetadata(metadata ffmpegVersionMetadata) error {
metadata.Version = normalizeFFmpegVersion(metadata.Version)
if metadata.Version == "" {
return nil
}
path := getFFmpegVersionMetadataPath()
if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
return fmt.Errorf("failed to create ffmpeg metadata directory: %v", err)
}
data, err := json.Marshal(metadata)
if err != nil {
return fmt.Errorf("failed to encode ffmpeg metadata: %v", err)
}
if err := os.WriteFile(path, data, 0644); err != nil {
return fmt.Errorf("failed to write ffmpeg metadata: %v", err)
}
return nil
}
func normalizeFFmpegVersion(version string) string {
version = strings.TrimSpace(version)
if version == "" {
return ""
}
lowerVersion := strings.ToLower(version)
if strings.HasPrefix(lowerVersion, "ffmpeg version ") {
version = strings.TrimSpace(version[len("ffmpeg version "):])
}
if strings.HasPrefix(strings.ToLower(version), strings.ToLower(ffmpegReleaseTagPrefix)) {
version = version[len(ffmpegReleaseTagPrefix):]
}
fields := strings.Fields(version)
if len(fields) > 0 {
version = fields[0]
}
if strings.HasPrefix(strings.ToLower(version), "n") && len(version) > 1 {
next := version[1]
if next >= '0' && next <= '9' {
version = version[1:]
}
}
if strings.HasPrefix(strings.ToLower(version), "v") {
version = strings.TrimPrefix(strings.TrimPrefix(version, "v"), "V")
}
if version == "" {
return ""
}
if numericVersion := ffmpegVersionPattern.FindString(version); numericVersion != "" {
version = numericVersion
}
first := version[0]
if first >= '0' && first <= '9' {
return "v" + version
}
return version
}
func ConvertMP4ToGIF(inputPath, outputPath, quality, resolution string) error {
return ConvertMP4ToGIFWithContext(context.Background(), inputPath, outputPath, quality, resolution)
}
func ConvertMP4ToGIFWithContext(ctx context.Context, inputPath, outputPath, quality, resolution string) error {
ffmpegPath := GetFFmpegPath()
if !IsFFmpegInstalled() {
return fmt.Errorf("ffmpeg not installed")
}
if ctx == nil {
ctx = context.Background()
}
var args []string
if quality == "fast" {
var scaleFilter string
switch resolution {
case "high":
scaleFilter = "scale=800:-1"
case "medium":
scaleFilter = "scale=600:-1"
case "low":
scaleFilter = "scale=400:-1"
default:
scaleFilter = ""
}
if scaleFilter != "" {
args = []string{
"-i", inputPath,
"-vf", scaleFilter,
"-loop", "0",
"-y",
outputPath,
}
} else {
args = []string{
"-i", inputPath,
"-loop", "0",
"-y",
outputPath,
}
}
} else {
var filter string
switch resolution {
case "high":
filter = "scale=800:-1:flags=lanczos,palettegen=stats_mode=full[palette];[0:v]scale=800:-1:flags=lanczos[scaled];[scaled][palette]paletteuse=dither=sierra2_4a"
case "medium":
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":
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:
filter = "palettegen=stats_mode=full[palette];[0:v][palette]paletteuse=dither=sierra2_4a"
}
fps := "15"
if resolution == "medium" {
fps = "10"
} else if resolution == "low" {
fps = "8"
}
args = []string{
"-i", inputPath,
"-lavfi", filter,
"-r", fps,
"-y",
outputPath,
}
}
cmd := exec.CommandContext(ctx, ffmpegPath, args...)
hideWindow(cmd)
output, err := cmd.CombinedOutput()
if err != nil {
if ctx.Err() != nil {
return ctx.Err()
}
return fmt.Errorf("ffmpeg error: %v, output: %s", err, string(output))
}
return nil
}
func ConvertGIFsInFolder(folderPath, quality, resolution string, deleteOriginal bool) (converted int, failed int, err error) {
if !IsFFmpegInstalled() {
return 0, 0, fmt.Errorf("ffmpeg not installed")
}
cleanPath := filepath.Clean(folderPath)
gifsFolder := filepath.Join(cleanPath, "gifs")
if _, err := os.Stat(gifsFolder); os.IsNotExist(err) {
return 0, 0, fmt.Errorf("gifs folder not found: %s", gifsFolder)
}
files, err := os.ReadDir(gifsFolder)
if err != nil {
return 0, 0, fmt.Errorf("failed to read gifs folder: %v", err)
}
for _, file := range files {
if file.IsDir() {
continue
}
name := file.Name()
if !strings.HasSuffix(strings.ToLower(name), ".mp4") {
continue
}
inputPath := filepath.Join(gifsFolder, name)
outputPath := filepath.Join(gifsFolder, strings.TrimSuffix(name, filepath.Ext(name))+".gif")
if err := ConvertMP4ToGIF(inputPath, outputPath, quality, resolution); err != nil {
failed++
continue
}
if deleteOriginal {
os.Remove(inputPath)
}
converted++
}
return converted, failed, nil
}
+125
View File
@@ -0,0 +1,125 @@
package backend
import (
"context"
"os"
"os/exec"
"path/filepath"
"runtime"
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
)
func OpenFolderInExplorer(path string) error {
os.WriteFile(filepath.Join(os.TempDir(), "openfolder.txt"), []byte(path), 0644)
info, err := os.Stat(path)
if err != nil {
return err
}
if !info.IsDir() {
return os.ErrInvalid
}
var cmd *exec.Cmd
switch runtime.GOOS {
case "windows":
cmd = exec.Command("cmd", "/C", "start", "", path)
case "darwin":
cmd = exec.Command("open", path)
case "linux":
cmd = exec.Command("xdg-open", path)
default:
cmd = exec.Command("xdg-open", path)
}
hideWindow(cmd)
return cmd.Run()
}
func SelectFolderDialog(ctx context.Context, defaultPath string) (string, error) {
if defaultPath == "" {
defaultPath = GetDefaultDownloadPath()
}
options := wailsRuntime.OpenDialogOptions{
Title: "Select Download Folder",
DefaultDirectory: defaultPath,
}
selectedPath, err := wailsRuntime.OpenDirectoryDialog(ctx, options)
if err != nil {
return "", err
}
if selectedPath == "" {
return "", nil
}
return selectedPath, nil
}
func CheckFolderExists(basePath, username string) bool {
folderPath := filepath.Join(basePath, username)
info, err := os.Stat(folderPath)
if err != nil {
return false
}
return info.IsDir()
}
func CheckFoldersExist(basePath string, usernames []string) map[string]bool {
results := make(map[string]bool, len(usernames))
if basePath == "" {
return results
}
checked := make(map[string]bool, len(usernames))
for _, username := range usernames {
if _, alreadyChecked := checked[username]; alreadyChecked {
continue
}
exists := CheckFolderExists(basePath, username)
checked[username] = exists
results[username] = exists
}
return results
}
func CheckGifsFolderExists(basePath, username string) bool {
gifsPath := filepath.Join(basePath, username, "gifs")
info, err := os.Stat(gifsPath)
if err != nil {
return false
}
return info.IsDir()
}
func CheckGifsFolderHasMP4(basePath, username string) bool {
gifsPath := filepath.Join(basePath, username, "gifs")
entries, err := os.ReadDir(gifsPath)
if err != nil {
return false
}
for _, entry := range entries {
if !entry.IsDir() {
ext := filepath.Ext(entry.Name())
if ext == ".mp4" || ext == ".MP4" {
return true
}
}
}
return false
}
func GetFolderPath(basePath, username string) string {
return filepath.Join(basePath, username)
}
func GetGifsFolderPath(basePath, username string) string {
return filepath.Join(basePath, username, "gifs")
}
+218
View File
@@ -0,0 +1,218 @@
package backend
import (
"context"
"fmt"
"net/url"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"strings"
)
var (
filenameSafeRegex = regexp.MustCompile(`^[A-Za-z0-9_]+$`)
filenameLetterRegex = regexp.MustCompile(`[A-Za-z]`)
)
func ExtractOriginalFilename(mediaURL string) string {
parsedURL, err := url.Parse(mediaURL)
if err != nil {
return ""
}
path := parsedURL.Path
parts := strings.Split(path, "/")
if strings.Contains(mediaURL, "/tweet_video/") {
for i, part := range parts {
if part == "tweet_video" && i+1 < len(parts) {
filename := parts[i+1]
if idx := strings.LastIndex(filename, "."); idx > 0 {
filename = filename[:idx]
}
if filenameSafeRegex.MatchString(filename) && len(filename) > 0 {
return filename
}
}
}
}
if strings.Contains(mediaURL, "pbs.twimg.com/media/") {
if len(parts) > 0 {
filename := parts[len(parts)-1]
if idx := strings.LastIndex(filename, "."); idx > 0 {
filename = filename[:idx]
}
if filenameSafeRegex.MatchString(filename) && len(filename) > 0 {
return filename
}
}
}
if strings.Contains(mediaURL, "video.twimg.com") && !strings.Contains(mediaURL, "/tweet_video/") {
if len(parts) > 0 {
filename := parts[len(parts)-1]
if idx := strings.LastIndex(filename, "."); idx > 0 {
filename = filename[:idx]
}
if filenameSafeRegex.MatchString(filename) {
if filenameLetterRegex.MatchString(filename) && len(filename) >= 8 {
return filename
}
}
}
}
return ""
}
func EmbedMetadata(ctx context.Context, filePath string, tweetContent string, tweetURL string, originalFilename string) error {
ext := strings.ToLower(filepath.Ext(filePath))
switch ext {
case ".jpg", ".jpeg":
return embedImageMetadata(ctx, filePath, tweetContent, tweetURL, originalFilename)
case ".mp4":
return embedVideoMetadata(ctx, filePath, tweetContent, tweetURL, originalFilename)
default:
return nil
}
}
func embedImageMetadata(ctx context.Context, filePath string, tweetContent string, tweetURL string, originalFilename string) error {
if ctx == nil {
ctx = context.Background()
}
exiftoolPath := findExifTool()
if exiftoolPath == "" {
return nil
}
metadataComment := buildMetadataComment(tweetContent, tweetURL, originalFilename)
args := []string{
"-overwrite_original",
"-Comment=" + metadataComment,
filePath,
}
cmd := exec.CommandContext(ctx, exiftoolPath, args...)
hideWindow(cmd)
output, err := cmd.CombinedOutput()
if err != nil {
if ctx.Err() != nil {
return ctx.Err()
}
return fmt.Errorf("exiftool error (non-fatal): %v, output: %s", err, string(output))
}
_ = output
return nil
}
func embedVideoMetadata(ctx context.Context, filePath string, tweetContent string, tweetURL string, originalFilename string) error {
if ctx == nil {
ctx = context.Background()
}
exiftoolPath := findExifTool()
if exiftoolPath == "" {
return nil
}
return embedVideoMetadataWithExifTool(ctx, exiftoolPath, filePath, tweetContent, tweetURL, originalFilename)
}
func embedVideoMetadataWithExifTool(ctx context.Context, exiftoolPath string, filePath string, tweetContent string, tweetURL string, originalFilename string) error {
if ctx == nil {
ctx = context.Background()
}
metadataComment := buildMetadataComment(tweetContent, tweetURL, originalFilename)
args := []string{
"-overwrite_original",
"-Comment=" + metadataComment,
filePath,
}
cmd := exec.CommandContext(ctx, exiftoolPath, args...)
hideWindow(cmd)
output, err := cmd.CombinedOutput()
if err != nil {
if ctx.Err() != nil {
return ctx.Err()
}
return fmt.Errorf("exiftool error (non-fatal): %v, output: %s", err, string(output))
}
_ = output
return nil
}
func buildMetadataComment(tweetContent string, tweetURL string, originalFilename string) string {
var parts []string
if tweetURL != "" {
parts = append(parts, tweetURL)
}
if originalFilename != "" {
parts = append(parts, originalFilename)
}
if len(parts) == 0 {
return ""
}
return strings.Join(parts, " | ")
}
func findExifTool() string {
if IsExifToolInstalled() {
return GetExifToolPath()
}
commonPaths := []string{
"exiftool",
"/usr/bin/exiftool",
"/usr/local/bin/exiftool",
"C:\\Program Files\\exiftool\\exiftool.exe",
"C:\\exiftool\\exiftool.exe",
}
for _, path := range commonPaths {
if runtime.GOOS == "windows" {
if _, err := exec.LookPath(path); err == nil {
return path
}
} else {
if _, err := os.Stat(path); err == nil {
return path
}
}
}
if path, err := exec.LookPath("exiftool"); err == nil {
return path
}
return ""
}
+917
View File
@@ -0,0 +1,917 @@
package backend
import (
"bytes"
"encoding/json"
"fmt"
"net/url"
"os"
"os/exec"
"path/filepath"
"runtime"
"sort"
"strings"
"sync"
)
var activeExtractorCommands = struct {
sync.Mutex
byPID map[int]*exec.Cmd
}{
byPID: make(map[int]*exec.Cmd),
}
func registerExtractorCommand(cmd *exec.Cmd) {
if cmd == nil || cmd.Process == nil {
return
}
activeExtractorCommands.Lock()
activeExtractorCommands.byPID[cmd.Process.Pid] = cmd
activeExtractorCommands.Unlock()
}
func unregisterExtractorCommand(cmd *exec.Cmd) {
if cmd == nil || cmd.Process == nil {
return
}
activeExtractorCommands.Lock()
delete(activeExtractorCommands.byPID, cmd.Process.Pid)
activeExtractorCommands.Unlock()
}
func runTrackedExtractorCommand(cmd *exec.Cmd) (stdout, stderr []byte, err error) {
var stdoutBuffer bytes.Buffer
var stderrBuffer bytes.Buffer
cmd.Stdout = &stdoutBuffer
cmd.Stderr = &stderrBuffer
hideWindow(cmd)
if err := cmd.Start(); err != nil {
return nil, nil, err
}
registerExtractorCommand(cmd)
defer unregisterExtractorCommand(cmd)
err = cmd.Wait()
return stdoutBuffer.Bytes(), stderrBuffer.Bytes(), err
}
func extractorErrorOutput(stdout, stderr []byte) string {
parts := make([]string, 0, 2)
if text := strings.TrimSpace(string(stderr)); text != "" {
parts = append(parts, text)
}
if text := strings.TrimSpace(string(stdout)); text != "" {
parts = append(parts, text)
}
return strings.Join(parts, "\n")
}
func getExecutableName() string {
if runtime.GOOS == "windows" {
return "xtractor.exe"
}
return "xtractor"
}
func getLegacyExecutableName() string {
if runtime.GOOS == "windows" {
return "extractor.exe"
}
return "extractor"
}
func KillAllExtractorProcesses() {
activeExtractorCommands.Lock()
commands := make([]*exec.Cmd, 0, len(activeExtractorCommands.byPID))
for _, cmd := range activeExtractorCommands.byPID {
commands = append(commands, cmd)
}
activeExtractorCommands.byPID = make(map[int]*exec.Cmd)
activeExtractorCommands.Unlock()
for _, cmd := range commands {
if cmd != nil && cmd.Process != nil {
_ = terminateCommandProcess(cmd)
}
}
}
func parseExtractorError(output string, username string) string {
outputLower := strings.ToLower(output)
lines := strings.Split(output, "\n")
var errorLine string
for _, line := range lines {
lineLower := strings.ToLower(line)
if strings.Contains(lineLower, "error:") || strings.Contains(lineLower, "exception") {
errorLine = strings.TrimSpace(line)
break
}
}
if errorLine == "" {
errorLine = strings.TrimSpace(output)
}
if len(errorLine) > 300 {
errorLine = errorLine[:300] + "..."
}
var hint string
if strings.Contains(outputLower, "unable to retrieve tweets from this timeline") {
hint = " [Hint: End of timeline reached or rate limited - data already fetched has been saved]"
} else if strings.Contains(outputLower, "rate limit") || strings.Contains(outputLower, "rate_limited") || strings.Contains(output, "429") {
hint = " [Hint: Wait 5-15 minutes before retrying]"
} else if strings.Contains(output, "401") || strings.Contains(outputLower, "unauthorized") || strings.Contains(outputLower, "auth_invalid") {
hint = " [Hint: Auth token may be invalid or expired]"
} else if strings.Contains(output, "404") || strings.Contains(outputLower, "user_not_found") {
hint = fmt.Sprintf(" [Hint: @%s may not exist or is suspended]", username)
} else if strings.Contains(outputLower, "protected") || strings.Contains(output, "403") {
hint = " [Hint: Protected account - need to follow and use auth token]"
}
return errorLine + hint
}
type TweetIDString int64
func (t TweetIDString) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%d"`, t)), nil
}
func (t *TweetIDString) UnmarshalJSON(data []byte) error {
var num int64
if err := json.Unmarshal(data, &num); err == nil {
*t = TweetIDString(num)
return nil
}
var str string
if err := json.Unmarshal(data, &str); err == nil {
parsed, err := fmt.Sscanf(str, "%d", &num)
if err != nil || parsed != 1 {
return fmt.Errorf("invalid tweet_id string: %s", str)
}
*t = TweetIDString(num)
return nil
}
return fmt.Errorf("tweet_id must be number or string")
}
type richThumb struct {
Name string `json:"name"`
URL string `json:"url"`
}
type richSize struct {
W int `json:"w"`
H int `json:"h"`
Resize string `json:"resize"`
URL string `json:"url"`
}
type richVariant struct {
ContentType string `json:"content_type"`
URL string `json:"url"`
Bitrate int `json:"bitrate"`
Resolution string `json:"resolution"`
}
type richMedia struct {
Type string `json:"type"`
MediaID string `json:"media_id"`
MediaKey string `json:"media_key"`
Thumbnail string `json:"thumbnail"`
ExpandedURL string `json:"expanded_url"`
Width int `json:"width"`
Height int `json:"height"`
AspectRatio []int `json:"aspect_ratio"`
DurationMS int `json:"duration_ms"`
AltText string `json:"alt_text"`
Sizes map[string]richSize `json:"sizes"`
Thumbs []richThumb `json:"thumbs"`
Variants []richVariant `json:"variants"`
}
type richMiniUser struct {
UserID string `json:"user_id"`
Username string `json:"username"`
Name string `json:"name"`
Avatar string `json:"avatar"`
Verified bool `json:"verified"`
BlueVerified bool `json:"blue_verified"`
}
type richStats struct {
Likes int `json:"likes"`
Retweets int `json:"retweets"`
Replies int `json:"replies"`
Quotes int `json:"quotes"`
Bookmarks int `json:"bookmarks"`
Views int `json:"views"`
}
type richTweet struct {
TweetID string `json:"tweet_id"`
URL string `json:"url"`
Text string `json:"text"`
Lang string `json:"lang"`
CreatedAt string `json:"created_at"`
Source string `json:"source"`
Sensitive bool `json:"sensitive"`
IsRepost bool `json:"is_repost"`
IsReply bool `json:"is_reply"`
IsQuote bool `json:"is_quote"`
RepostedBy *richMiniUser `json:"reposted_by"`
Author richMiniUser `json:"author"`
Stats richStats `json:"stats"`
Media []richMedia `json:"media"`
Hashtags []string `json:"hashtags"`
}
type richAccount struct {
ID string `json:"id"`
Username string `json:"username"`
Name string `json:"name"`
Bio string `json:"bio"`
Avatar string `json:"avatar"`
AvatarVariants []richThumb `json:"avatar_variants"`
Banner string `json:"banner"`
BannerVariants []richThumb `json:"banner_variants"`
Location string `json:"location"`
URL string `json:"url"`
CreatedAt string `json:"created_at"`
Followers int `json:"followers"`
Following int `json:"following"`
Tweets int `json:"tweets"`
MediaCount int `json:"media_count"`
Protected bool `json:"protected"`
Verified bool `json:"verified"`
BlueVerified bool `json:"blue_verified"`
}
type richResponse struct {
Account richAccount `json:"account"`
Tweets []richTweet `json:"tweets"`
NextCursor string `json:"next_cursor"`
HasMore bool `json:"has_more"`
}
type TimelineEntry struct {
URL string `json:"url"`
Date string `json:"date"`
TweetID TweetIDString `json:"tweet_id"`
Type string `json:"type"`
IsRetweet bool `json:"is_retweet"`
Extension string `json:"extension"`
Width int `json:"width"`
Height int `json:"height"`
Thumbnail string `json:"thumbnail,omitempty"`
DurationMS int `json:"duration_ms,omitempty"`
AltText string `json:"alt_text,omitempty"`
Content string `json:"content,omitempty"`
ViewCount int `json:"view_count,omitempty"`
BookmarkCount int `json:"bookmark_count,omitempty"`
FavoriteCount int `json:"favorite_count,omitempty"`
RetweetCount int `json:"retweet_count,omitempty"`
ReplyCount int `json:"reply_count,omitempty"`
QuoteCount int `json:"quote_count,omitempty"`
Source string `json:"source,omitempty"`
Verified bool `json:"verified,omitempty"`
OriginalFilename string `json:"original_filename,omitempty"`
AuthorUsername string `json:"author_username,omitempty"`
AuthorName string `json:"author_name,omitempty"`
}
type AccountInfo struct {
Name string `json:"name"`
Nick string `json:"nick"`
Date string `json:"date"`
FollowersCount int `json:"followers_count"`
FriendsCount int `json:"friends_count"`
ProfileImage string `json:"profile_image"`
StatusesCount int `json:"statuses_count"`
Bio string `json:"bio,omitempty"`
Banner string `json:"banner,omitempty"`
Location string `json:"location,omitempty"`
URL string `json:"url,omitempty"`
MediaCount int `json:"media_count,omitempty"`
Verified bool `json:"verified,omitempty"`
BlueVerified bool `json:"blue_verified,omitempty"`
Protected bool `json:"protected,omitempty"`
AvatarVariants []richThumb `json:"avatar_variants,omitempty"`
BannerVariants []richThumb `json:"banner_variants,omitempty"`
}
type ExtractMetadata struct {
NewEntries int `json:"new_entries"`
Page int `json:"page"`
BatchSize int `json:"batch_size"`
HasMore bool `json:"has_more"`
Cursor string `json:"cursor,omitempty"`
Completed bool `json:"completed,omitempty"`
}
type TwitterResponse struct {
AccountInfo AccountInfo `json:"account_info"`
TotalURLs int `json:"total_urls"`
Timeline []TimelineEntry `json:"timeline"`
Metadata ExtractMetadata `json:"metadata"`
Cursor string `json:"cursor,omitempty"`
Completed bool `json:"completed,omitempty"`
}
type TimelineRequest struct {
Username string `json:"username"`
AuthToken string `json:"auth_token"`
TimelineType string `json:"timeline_type"`
BatchSize int `json:"batch_size"`
Page int `json:"page"`
MediaType string `json:"media_type"`
Retweets bool `json:"retweets"`
Cursor string `json:"cursor,omitempty"`
IncludePhotos bool `json:"include_photos"`
IncludeVideos bool `json:"include_videos"`
IncludeGifs bool `json:"include_gifs"`
IncludeText bool `json:"include_text"`
VideoQuality string `json:"video_quality,omitempty"`
ImageSize string `json:"image_size,omitempty"`
}
type DateRangeRequest struct {
Username string `json:"username"`
AuthToken string `json:"auth_token"`
StartDate string `json:"start_date"`
EndDate string `json:"end_date"`
MediaFilter string `json:"media_filter"`
Retweets bool `json:"retweets"`
}
func buildTwitterURL(username, timelineType string) string {
if timelineType == "bookmarks" {
return "https://x.com/i/bookmarks"
}
username = cleanUsername(username)
baseURL := "https://x.com/" + username
switch timelineType {
case "media":
return baseURL + "/media"
case "timeline":
return baseURL + "/timeline"
case "tweets":
return baseURL + "/tweets"
case "with_replies":
return baseURL + "/with_replies"
case "likes":
return baseURL + "/likes"
default:
return baseURL + "/timeline"
}
}
func cleanUsername(username string) string {
username = strings.TrimSpace(username)
username = strings.TrimPrefix(username, "@")
if strings.Contains(username, "x.com/") || strings.Contains(username, "twitter.com/") {
parsed := username
if !strings.HasPrefix(parsed, "http://") && !strings.HasPrefix(parsed, "https://") {
parsed = "https://" + strings.TrimPrefix(parsed, "//")
}
if u, err := url.Parse(parsed); err == nil {
segments := strings.Split(strings.Trim(u.Path, "/"), "/")
if len(segments) > 0 && segments[0] != "" {
firstSegment := strings.ToLower(segments[0])
if firstSegment == "i" || firstSegment == "search" || firstSegment == "home" || firstSegment == "explore" || firstSegment == "settings" || firstSegment == "messages" || firstSegment == "notifications" {
return username
}
return segments[0]
}
}
}
return username
}
func ensureURLScheme(raw string) string {
raw = strings.TrimSpace(raw)
if raw == "" {
return raw
}
if strings.HasPrefix(raw, "http://") || strings.HasPrefix(raw, "https://") {
return raw
}
if strings.HasPrefix(raw, "//") {
return "https:" + raw
}
return "https://" + strings.TrimPrefix(raw, "//")
}
func buildSearchURL(username, startDate, endDate, mediaFilter string, includeRetweets bool) string {
trimmed := strings.TrimSpace(username)
lower := strings.ToLower(trimmed)
if strings.Contains(lower, "search?q=") {
return ensureURLScheme(trimmed)
}
handle := cleanUsername(trimmed)
var parts []string
if handle != "" {
parts = append(parts, fmt.Sprintf("from:%s", handle))
}
if startDate != "" {
parts = append(parts, fmt.Sprintf("since:%s", startDate))
}
if endDate != "" {
parts = append(parts, fmt.Sprintf("until:%s", endDate))
}
switch strings.ToLower(strings.TrimSpace(mediaFilter)) {
case "image", "images", "photo", "photos":
parts = append(parts, "filter:images")
case "video", "videos", "gif", "gifs":
parts = append(parts, "filter:videos")
case "text":
parts = append(parts, "-filter:media")
default:
parts = append(parts, "filter:media")
}
if !includeRetweets {
parts = append(parts, "-filter:retweets")
}
query := url.QueryEscape(strings.Join(parts, " "))
return fmt.Sprintf("https://x.com/search?q=%s&src=typed_query&f=live", query)
}
func parseTweetID(s string) TweetIDString {
var n int64
_, _ = fmt.Sscanf(strings.TrimSpace(s), "%d", &n)
return TweetIDString(n)
}
func bestPhotoURL(m richMedia, size string) string {
if size == "" {
size = "orig"
}
if size == "orig" {
for _, t := range m.Thumbs {
if t.Name == "orig" {
return t.URL
}
}
} else if s, ok := m.Sizes[size]; ok && s.URL != "" {
return s.URL
}
if s, ok := m.Sizes["large"]; ok && s.URL != "" {
return s.URL
}
if s, ok := m.Sizes["medium"]; ok && s.URL != "" {
return s.URL
}
if s, ok := m.Sizes["small"]; ok && s.URL != "" {
return s.URL
}
return m.Thumbnail
}
func bestVideoURL(m richMedia, quality string) string {
mp4s := make([]richVariant, 0, len(m.Variants))
for _, v := range m.Variants {
if v.ContentType == "video/mp4" && v.URL != "" {
mp4s = append(mp4s, v)
}
}
if len(mp4s) == 0 {
if len(m.Variants) > 0 {
return m.Variants[len(m.Variants)-1].URL
}
return m.Thumbnail
}
sort.Slice(mp4s, func(i, j int) bool { return mp4s[i].Bitrate < mp4s[j].Bitrate })
switch quality {
case "lowest":
return mp4s[0].URL
case "", "highest":
return mp4s[len(mp4s)-1].URL
}
target := 0
_, _ = fmt.Sscanf(quality, "%d", &target)
if target == 0 {
return mp4s[len(mp4s)-1].URL
}
best := mp4s[0]
bestDelta := 1 << 30
for _, v := range mp4s {
h := resolutionHeight(v.Resolution)
delta := h - target
if delta < 0 {
delta = -delta
}
if delta < bestDelta {
bestDelta = delta
best = v
}
}
return best.URL
}
func resolutionHeight(resolution string) int {
if i := strings.Index(resolution, "x"); i >= 0 {
h := 0
_, _ = fmt.Sscanf(resolution[i+1:], "%d", &h)
return h
}
return 0
}
func previewURL(m richMedia) string {
for _, t := range m.Thumbs {
if t.Name == "360x360" {
return t.URL
}
}
if s, ok := m.Sizes["small"]; ok && s.URL != "" {
return s.URL
}
return m.Thumbnail
}
func extensionFor(downloadURL, mediaType string) string {
switch mediaType {
case "video", "gif", "animated_gif":
return "mp4"
}
if i := strings.Index(downloadURL, "format="); i >= 0 {
rest := downloadURL[i+len("format="):]
if amp := strings.IndexByte(rest, '&'); amp >= 0 {
rest = rest[:amp]
}
if rest != "" {
return rest
}
}
return "jpg"
}
func isVerified(u richMiniUser) bool {
return u.Verified || u.BlueVerified
}
func textEntry(t richTweet) TimelineEntry {
return TimelineEntry{
URL: "",
Date: t.CreatedAt,
TweetID: parseTweetID(t.TweetID),
Type: "text",
IsRetweet: t.IsRepost,
Extension: "txt",
Content: t.Text,
ViewCount: t.Stats.Views,
BookmarkCount: t.Stats.Bookmarks,
FavoriteCount: t.Stats.Likes,
RetweetCount: t.Stats.Retweets,
ReplyCount: t.Stats.Replies,
QuoteCount: t.Stats.Quotes,
Source: t.Source,
Verified: isVerified(t.Author),
AuthorUsername: t.Author.Username,
AuthorName: t.Author.Name,
}
}
func mediaEntry(t richTweet, m richMedia, videoQuality, imageSize string) TimelineEntry {
var downloadURL string
switch m.Type {
case "video", "animated_gif", "gif":
downloadURL = bestVideoURL(m, videoQuality)
default:
downloadURL = bestPhotoURL(m, imageSize)
}
return TimelineEntry{
URL: downloadURL,
Date: t.CreatedAt,
TweetID: parseTweetID(t.TweetID),
Type: m.Type,
IsRetweet: t.IsRepost,
Extension: extensionFor(downloadURL, m.Type),
Width: m.Width,
Height: m.Height,
Thumbnail: previewURL(m),
DurationMS: m.DurationMS,
AltText: m.AltText,
Content: t.Text,
ViewCount: t.Stats.Views,
BookmarkCount: t.Stats.Bookmarks,
FavoriteCount: t.Stats.Likes,
RetweetCount: t.Stats.Retweets,
ReplyCount: t.Stats.Replies,
QuoteCount: t.Stats.Quotes,
Source: t.Source,
Verified: isVerified(t.Author),
AuthorUsername: t.Author.Username,
AuthorName: t.Author.Name,
}
}
type FlattenOptions struct {
IncludePhotos bool
IncludeVideos bool
IncludeGifs bool
IncludeText bool
VideoQuality string
ImageSize string
}
func flattenTweets(tweets []richTweet, opts FlattenOptions) []TimelineEntry {
out := make([]TimelineEntry, 0, len(tweets))
for _, t := range tweets {
if len(t.Media) == 0 {
if opts.IncludeText && strings.TrimSpace(t.Text) != "" {
out = append(out, textEntry(t))
}
continue
}
for _, m := range t.Media {
switch m.Type {
case "photo":
if !opts.IncludePhotos {
continue
}
case "video":
if !opts.IncludeVideos {
continue
}
case "animated_gif", "gif":
if !opts.IncludeGifs {
continue
}
}
out = append(out, mediaEntry(t, m, opts.VideoQuality, opts.ImageSize))
}
}
return out
}
func buildAccountInfo(acc richAccount, fallbackUsername string) AccountInfo {
info := AccountInfo{
Name: fallbackUsername,
Nick: fallbackUsername,
}
if acc.Username != "" {
info.Name = acc.Username
}
if acc.Name != "" {
info.Nick = acc.Name
}
info.Date = acc.CreatedAt
info.FollowersCount = acc.Followers
info.FriendsCount = acc.Following
info.ProfileImage = acc.Avatar
info.StatusesCount = acc.Tweets
info.Bio = acc.Bio
info.Banner = acc.Banner
info.Location = acc.Location
info.URL = acc.URL
info.MediaCount = acc.MediaCount
info.Verified = acc.Verified
info.BlueVerified = acc.BlueVerified
info.Protected = acc.Protected
info.AvatarVariants = acc.AvatarVariants
info.BannerVariants = acc.BannerVariants
return info
}
func parseRichResponse(jsonStr string) (*richResponse, error) {
var resp richResponse
if err := json.Unmarshal([]byte(jsonStr), &resp); err != nil {
return nil, fmt.Errorf("json_error: Failed to parse JSON response: %v", err)
}
return &resp, nil
}
func ExtractTimeline(req TimelineRequest) (*TwitterResponse, error) {
exePath, err := requireExtractorPath()
if err != nil {
return nil, err
}
includeText := req.IncludeText
timelineType := req.TimelineType
if timelineType == "" {
if includeText {
timelineType = "tweets"
} else {
timelineType = "media"
}
}
targetURL := buildTwitterURL(req.Username, timelineType)
args := []string{targetURL}
if req.AuthToken != "" {
args = append(args, "--auth-token", req.AuthToken)
} else {
args = append(args, "--guest")
}
args = append(args, "--json", "--metadata", "--no-discord")
if req.BatchSize > 0 {
args = append(args, "--limit", fmt.Sprintf("%d", req.BatchSize))
}
if timelineType == "tweets" || timelineType == "timeline" || timelineType == "media" {
if req.Retweets {
args = append(args, "--retweets", "include")
} else {
args = append(args, "--retweets", "skip")
}
}
if includeText {
args = append(args, "--text-tweets")
}
if req.Cursor != "" {
args = append(args, "--cursor", req.Cursor)
}
cmd := exec.Command(exePath, args...)
cmd.Env = append(os.Environ(),
"PYTHONIOENCODING=utf-8",
"PYTHONUTF8=1",
)
stdout, stderr, err := runTrackedExtractorCommand(cmd)
if err != nil {
outputStr := extractorErrorOutput(stdout, stderr)
if strings.TrimSpace(outputStr) == "" {
return nil, fmt.Errorf("xtractor process terminated before returning data")
}
errorMsg := parseExtractorError(outputStr, req.Username)
return nil, fmt.Errorf("%s", errorMsg)
}
jsonStr := strings.TrimSpace(string(stdout))
if jsonStr == "" {
if strings.TrimSpace(string(stderr)) == "" {
return nil, fmt.Errorf("empty_response: Xtractor returned no data. The timeline may be empty or inaccessible")
}
return nil, fmt.Errorf("empty_response: Xtractor returned no JSON. Logs: %s", strings.TrimSpace(string(stderr)))
}
resp, err := parseRichResponse(jsonStr)
if err != nil {
return nil, err
}
accountInfo := buildAccountInfo(resp.Account, req.Username)
isBookmarks := req.TimelineType == "bookmarks"
isLikes := req.TimelineType == "likes"
if isBookmarks {
accountInfo.Name = "bookmarks"
accountInfo.Nick = "My Bookmarks"
} else if isLikes {
accountInfo.Name = "likes"
accountInfo.Nick = "My Likes"
}
timeline := flattenTweets(resp.Tweets, FlattenOptions{
IncludePhotos: req.IncludePhotos,
IncludeVideos: req.IncludeVideos,
IncludeGifs: req.IncludeGifs,
IncludeText: req.IncludeText,
VideoQuality: req.VideoQuality,
ImageSize: req.ImageSize,
})
completed := !resp.HasMore
response := &TwitterResponse{
AccountInfo: accountInfo,
TotalURLs: len(timeline),
Timeline: timeline,
Metadata: ExtractMetadata{
NewEntries: len(timeline),
Page: req.Page,
BatchSize: req.BatchSize,
HasMore: resp.HasMore,
Cursor: resp.NextCursor,
Completed: completed,
},
Cursor: resp.NextCursor,
Completed: completed,
}
return response, nil
}
func ExtractDateRange(req DateRangeRequest) (*TwitterResponse, error) {
exePath, err := requireExtractorPath()
if err != nil {
return nil, err
}
mediaFilter := strings.ToLower(strings.TrimSpace(req.MediaFilter))
targetURL := buildSearchURL(req.Username, req.StartDate, req.EndDate, mediaFilter, req.Retweets)
args := []string{targetURL}
if req.AuthToken != "" {
args = append(args, "--auth-token", req.AuthToken)
} else {
args = append(args, "--guest")
}
args = append(args, "--json", "--metadata", "--no-discord")
if req.Retweets {
args = append(args, "--retweets", "include")
} else {
args = append(args, "--retweets", "skip")
}
isTextOnly := mediaFilter == "text"
if isTextOnly {
args = append(args, "--text-tweets")
}
cmd := exec.Command(exePath, args...)
cmd.Env = append(os.Environ(),
"PYTHONIOENCODING=utf-8",
"PYTHONUTF8=1",
)
stdout, stderr, err := runTrackedExtractorCommand(cmd)
if err != nil {
outputStr := extractorErrorOutput(stdout, stderr)
if strings.TrimSpace(outputStr) == "" {
return nil, fmt.Errorf("xtractor process terminated before returning data")
}
errorMsg := parseExtractorError(outputStr, req.Username)
return nil, fmt.Errorf("%s", errorMsg)
}
jsonStr := strings.TrimSpace(string(stdout))
if jsonStr == "" {
if strings.TrimSpace(string(stderr)) == "" {
return nil, fmt.Errorf("empty_response: Xtractor returned no data. The timeline may be empty or inaccessible")
}
return nil, fmt.Errorf("empty_response: Xtractor returned no JSON. Logs: %s", strings.TrimSpace(string(stderr)))
}
resp, err := parseRichResponse(jsonStr)
if err != nil {
return nil, err
}
timeline := flattenTweets(resp.Tweets, FlattenOptions{
IncludePhotos: true,
IncludeVideos: true,
IncludeGifs: true,
IncludeText: isTextOnly,
})
accountInfo := buildAccountInfo(resp.Account, req.Username)
completed := !resp.HasMore
response := &TwitterResponse{
AccountInfo: accountInfo,
TotalURLs: len(timeline),
Timeline: timeline,
Metadata: ExtractMetadata{
NewEntries: len(timeline),
Page: 0,
BatchSize: 0,
HasMore: resp.HasMore,
Cursor: resp.NextCursor,
Completed: completed,
},
Cursor: resp.NextCursor,
Completed: completed,
}
return response, nil
}
func getExtractorPath() string {
homeDir, _ := os.UserHomeDir()
baseDir := filepath.Join(homeDir, ".twitterxmediabatchdownloader")
return filepath.Join(baseDir, getExecutableName())
}
+24
View File
@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
+24
View File
@@ -0,0 +1,24 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "new-york",
"rsc": false,
"tsx": true,
"tailwind": {
"config": "",
"css": "src/index.css",
"baseColor": "neutral",
"cssVariables": true,
"prefix": ""
},
"iconLibrary": "lucide",
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
"ui": "@/components/ui",
"lib": "@/lib",
"hooks": "@/hooks"
},
"registries": {
"@lucide-animated": "https://lucide-animated.com/r/{name}.json"
}
}
+28
View File
@@ -0,0 +1,28 @@
import js from '@eslint/js';
import globals from 'globals';
import reactHooks from 'eslint-plugin-react-hooks';
import reactRefresh from 'eslint-plugin-react-refresh';
import tseslint from 'typescript-eslint';
import { defineConfig, globalIgnores } from 'eslint/config';
export default defineConfig([
globalIgnores(['dist', 'wailsjs']),
{
files: ['**/*.{ts,tsx}'],
extends: [
js.configs.recommended,
tseslint.configs.recommended,
reactHooks.configs.flat.recommended,
reactRefresh.configs.vite,
],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
},
},
{
files: ['src/components/ui/badge.tsx', 'src/components/ui/button.tsx'],
rules: {
'react-refresh/only-export-components': 'off',
},
},
]);
+16
View File
@@ -0,0 +1,16 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/icon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,200..800&family=DM+Sans:wght@300..800&family=Figtree:wght@300..900&family=Geist:wght@100..900&family=Google+Sans+Code:ital,wght@0,300..800;1,300..800&family=Google+Sans+Flex:opsz,wght@6..144,1..1000&family=Inter:wght@300..800&family=JetBrains+Mono:ital,wght@0,100..800;1,100..800&family=Manrope:wght@300..800&family=Noto+Sans:wght@100..900&family=Nunito+Sans:opsz,wght@6..12,200..1000&family=Outfit:wght@100..900&family=Plus+Jakarta+Sans:wght@300..800&family=Poppins:wght@300;400;500;600;700;800&family=Public+Sans:ital,wght@0,100..900;1,100..900&family=Raleway:wght@100..900&family=Roboto:wght@300;400;500;700;900&family=Space+Grotesk:wght@300..700&display=swap" rel="stylesheet">
<title>Twitter/X Media Batch Downloader</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+54
View File
@@ -0,0 +1,54 @@
{
"name": "frontend",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"test": "node --experimental-strip-types --test scripts/*.test.mjs",
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "eslint .",
"preview": "vite preview",
"generate-icon": "node scripts/generate-icon.js",
"postinstall": "node scripts/generate-icon.js"
},
"dependencies": {
"@radix-ui/react-checkbox": "^1.3.11",
"@radix-ui/react-context-menu": "^2.3.7",
"@radix-ui/react-dialog": "^1.1.23",
"@radix-ui/react-dropdown-menu": "^2.1.24",
"@radix-ui/react-label": "^2.1.15",
"@radix-ui/react-progress": "^1.1.16",
"@radix-ui/react-select": "^2.3.7",
"@radix-ui/react-slot": "^1.3.3",
"@radix-ui/react-switch": "^1.3.7",
"@radix-ui/react-tooltip": "^1.2.16",
"@tailwindcss/vite": "^4.3.3",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"lucide-react": "^0.562.0",
"motion": "^12.43.0",
"next-themes": "^0.4.6",
"react": "^19.2.8",
"react-dom": "^19.2.8",
"sonner": "^2.0.8",
"tailwind-merge": "^3.6.0",
"tailwindcss": "^4.3.3"
},
"devDependencies": {
"@eslint/js": "^10.0.1",
"@types/node": "^26.2.0",
"@types/react": "^19.2.18",
"@types/react-dom": "^19.2.4",
"@vitejs/plugin-react": "^6.0.5",
"eslint": "^10.8.1",
"eslint-plugin-react-hooks": "^7.1.1",
"eslint-plugin-react-refresh": "^0.5.4",
"globals": "^17.11.0",
"sharp": "^0.35.3",
"tw-animate-css": "^1.4.0",
"typescript": "~6.0.3",
"typescript-eslint": "^8.67.0",
"vite": "^8.2.1"
}
}
+1
View File
@@ -0,0 +1 @@
11d903f252aa57269b096713a9fa71fe
+3683
View File
File diff suppressed because it is too large. Load diff
+3
View File
@@ -0,0 +1,3 @@
allowBuilds:
esbuild: true
sharp: true
+11
View File
@@ -0,0 +1,11 @@
<?xml version="1.0" ?>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1"
id="Layer_1" width="512px" height="512px" viewBox="0 0 24 24" style="enable-background:new 0 0 24 24;"
xml:space="preserve">
<g fill="#1da0f1">
<polygon
points="12.153992,10.729553 8.088684,5.041199 5.92041,5.041199 10.956299,12.087097 11.59021,12.97345 15.900635,19.009583 18.068909,19.009583 12.785217,11.615906 " />
<path
d="M21.15979,1H2.84021C1.823853,1,1,1.823853,1,2.84021v18.31958C1,22.176147,1.823853,23,2.84021,23h18.31958 C22.176147,23,23,22.176147,23,21.15979V2.84021C23,1.823853,22.176147,1,21.15979,1z M15.235352,20l-4.362549-6.213013 L5.411438,20H4l6.246887-7.104675L4,4h4.764648l4.130127,5.881958L18.06958,4h1.411377l-5.95697,6.775635L20,20H15.235352z" />
</g>
</svg>

After

Width:  |  Height:  |  Size: 865 B

+84
View File
@@ -0,0 +1,84 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { createFetchDelayGate, normalizeFetchDelay } from "../src/lib/fetch-delay.ts";
function clock(random = 0.5) {
let time = 0;
const waits = [];
const gate = createFetchDelayGate({
now: () => time,
random: () => random,
sleep: async (ms) => { waits.push(ms); time += ms; },
});
return { gate, waits, now: () => time, advance: (ms) => { time += ms; } };
}
test("old or invalid settings disable delay; valid settings are bounded", () => {
for (const value of [undefined, null, "5", NaN, Infinity, -1]) {
assert.equal(normalizeFetchDelay(value), 0);
}
assert.equal(normalizeFetchDelay(4000), 3600);
assert.equal(normalizeFetchDelay(1.2345), 1.235);
});
test("first fetch starts immediately; later batches/accounts share pacing", async () => {
const c = clock();
assert.equal(await c.gate(5, 5, () => false), true);
assert.equal(c.now(), 0);
c.advance(2000); // Time spent fetching the previous batch.
assert.equal(await c.gate(5, 5, () => false), true);
assert.equal(c.now(), 7500);
await c.gate(5, 5, () => false);
assert.equal(c.now(), 15000);
assert.ok(c.waits.every((ms) => ms <= 100));
});
test("disabled pacing and a long fetch do not introduce unnecessary waits", async () => {
const c = clock();
await c.gate(0, 0, () => false);
await c.gate(0, 0, () => false);
c.advance(10000);
await c.gate(5, 0, () => false);
assert.deepEqual(c.waits, []);
});
test("random-only pacing supports both ends of the random range", async () => {
for (const random of [0, 0.999]) {
const c = clock(random);
await c.gate(0, 5, () => false);
await c.gate(0, 5, () => false);
assert.equal(c.now(), random * 5000);
}
});
test("stop or timeout during a wait prevents the next fetch from starting", async () => {
const c = clock();
await c.gate(5, 0, () => false);
assert.equal(await c.gate(5, 0, () => c.now() >= 200), false);
assert.equal(c.now(), 200);
assert.equal(await c.gate(0, 0, () => true), false);
await c.gate(5, 0, () => false);
assert.equal(c.now(), 5000); // Cancellation did not reserve a future slot.
});
test("concurrent callers recheck the shared start time after waking", async () => {
let time = 0;
const sleepers = [];
const gate = createFetchDelayGate({
now: () => time,
random: () => 0,
sleep: () => new Promise((resolve) => sleepers.push(resolve)),
});
await gate(1, 0, () => false);
const starts = [];
const a = gate(1, 0, () => false).then(() => starts.push(time));
const b = gate(1, 0, () => false).then(() => starts.push(time));
time = 1000;
sleepers.splice(0).forEach((resolve) => resolve());
await a;
assert.deepEqual(starts, [1000]);
time = 2000;
sleepers.splice(0).forEach((resolve) => resolve());
await b;
assert.deepEqual(starts, [1000, 2000]);
});
+24
View File
@@ -0,0 +1,24 @@
import sharp from 'sharp';
import { readFileSync, mkdirSync } from 'fs';
import { dirname, join } from 'path';
import { fileURLToPath } from 'url';
const __dirname = dirname(fileURLToPath(import.meta.url));
const rootDir = join(__dirname, '..', '..');
const svgPath = join(rootDir, 'frontend', 'public', 'icon.svg');
const outputPath = join(rootDir, 'build', 'appicon.png');
async function generateIcon() {
try {
mkdirSync(join(rootDir, 'build'), { recursive: true });
const svgBuffer = readFileSync(svgPath);
await sharp(svgBuffer)
.resize(1024, 1024)
.png()
.toFile(outputPath);
console.log('✓ Icon generated:', outputPath);
}
catch (error) {
console.error('✗ Failed to generate icon:', error.message);
process.exit(1);
}
}
generateIcon();
+1614
View File
File diff suppressed because it is too large. Load diff
Binary file not shown.

After

Width:  |  Height:  |  Size: 903 KiB

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

After

Width:  |  Height:  |  Size: 3.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

File diff suppressed because it is too large. Load diff
+110
View File
@@ -0,0 +1,110 @@
import { useState, useEffect, useRef } from "react";
import { Trash2, Copy, CircleCheck, FileDown } from "lucide-react";
import { Button } from "@/components/ui/button";
import { logger, type LogEntry } from "@/lib/logger";
import { ExportFailedLogs } from "../../wailsjs/go/main/App";
import { toastWithSound as toast } from "@/lib/toast-with-sound";
const levelColors: Record<string, string> = {
info: "text-blue-500",
success: "text-green-500",
warning: "text-yellow-500",
error: "text-red-500",
debug: "text-gray-500",
};
function formatTime(date: Date): string {
return date.toLocaleTimeString("en-US", {
hour12: false,
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
});
}
export function DebugLoggerPage() {
const [logs, setLogs] = useState<LogEntry[]>(() => logger.getLogs());
const [copied, setCopied] = useState(false);
const scrollRef = useRef<HTMLDivElement>(null);
const failedLogs = logs.filter((log) => log.level === "error");
useEffect(() => {
const unsubscribe = logger.subscribe(() => {
setLogs(logger.getLogs());
});
return () => {
unsubscribe();
};
}, []);
useEffect(() => {
if (scrollRef.current) {
scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
}
}, [logs]);
const handleClear = () => {
logger.clear();
};
const handleCopy = async () => {
const logText = logs
.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);
}
};
const handleExportFailed = async () => {
if (failedLogs.length === 0) {
toast.info("No failed logs to export");
return;
}
const lines = [
`Failed Logs Report - ${new Date().toLocaleString()}`,
"-".repeat(50),
"",
...failedLogs.map((log) => `[${formatTime(log.timestamp)}] [${log.level}] ${log.message}`),
"",
];
try {
const path = await ExportFailedLogs(lines.join("\n"));
if (path) {
toast.success(`Exported ${failedLogs.length} failed log${failedLogs.length === 1 ? "" : "s"}`);
}
}
catch (error) {
console.error("Failed to export logs:", error);
toast.error(`Failed to export logs: ${error}`);
}
};
return (<div className="space-y-6">
<div className="flex items-center justify-between">
<h1 className="text-2xl font-bold">Debug Logs</h1>
<div className="flex items-center gap-2">
<Button variant="outline" size="sm" onClick={handleExportFailed} className="gap-1.5">
<FileDown className="h-4 w-4"/>
Export Failed
</Button>
<Button variant="outline" size="sm" onClick={handleCopy} disabled={logs.length === 0} className="gap-1.5">
{copied ? <CircleCheck className="h-4 w-4"/> : <Copy className="h-4 w-4"/>}
Copy
</Button>
<Button variant="destructive" size="sm" onClick={handleClear} disabled={logs.length === 0} className="gap-1.5">
<Trash2 className="h-4 w-4"/>
Clear
</Button>
</div>
</div>
<div ref={scrollRef} className="h-[calc(100vh-220px)] overflow-y-auto rounded-lg bg-muted/50 p-4 font-mono text-xs">
{logs.length === 0 ? (<p className="text-muted-foreground lowercase">no logs yet...</p>) : (logs.map((log, i) => (<div key={i} className="flex gap-2 py-0.5">
<span className="text-muted-foreground shrink-0">
[{formatTime(log.timestamp)}]
</span>
<span className={`shrink-0 w-16 ${levelColors[log.level]}`}>
[{log.level}]
</span>
<span className="break-all">{log.message}</span>
</div>)))}
</div>
</div>);
}
@@ -0,0 +1,131 @@
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 { compareVersionNumbers } from "@/lib/version";
import { Quit } from "../../wailsjs/runtime/runtime";
import { DownloadExtractor, GetExtractorVersionStatus } from "../../wailsjs/go/main/App";
interface DependencySetupDialogProps {
onInstalled?: () => void;
}
interface ExtractorVersionStatus {
installed: boolean;
installed_version?: string;
latest_version?: string;
}
export function DependencySetupDialog({ onInstalled }: DependencySetupDialogProps) {
const [open, setOpen] = useState(false);
const [checking, setChecking] = useState(true);
const [downloading, setDownloading] = useState(false);
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const [updateRequired, setUpdateRequired] = useState(false);
const [installedVersion, setInstalledVersion] = useState<string | null>(null);
const [releaseVersion, setReleaseVersion] = useState<string | null>(null);
const [releaseStatusMessage, setReleaseStatusMessage] = useState("Checking latest GitHub release...");
useEffect(() => {
let cancelled = false;
const checkDependency = async () => {
try {
const status = await GetExtractorVersionStatus() as ExtractorVersionStatus;
const nextInstalledVersion = status.installed_version?.trim() || null;
const nextLatestVersion = status.latest_version?.trim() || null;
const nextUpdateRequired = !!(status.installed && nextLatestVersion && (!nextInstalledVersion || compareVersionNumbers(nextLatestVersion, nextInstalledVersion) > 0));
if (!cancelled) {
setUpdateRequired(nextUpdateRequired);
setInstalledVersion(nextInstalledVersion);
setReleaseVersion(nextLatestVersion);
setReleaseStatusMessage(nextLatestVersion ? `Latest GitHub release: ${nextLatestVersion}` : "Latest GitHub release unavailable.");
setOpen(!status.installed || nextUpdateRequired);
setErrorMessage(null);
}
}
catch {
if (!cancelled) {
setOpen(true);
setErrorMessage("Couldn't verify Xtractor. Download it to continue.");
}
}
finally {
if (!cancelled) {
setChecking(false);
}
}
};
void checkDependency();
return () => {
cancelled = true;
};
}, []);
const handleDownload = async () => {
setDownloading(true);
setErrorMessage(null);
try {
await DownloadExtractor();
setOpen(false);
toast.success(updateRequired ? "Xtractor updated" : "Xtractor installed");
onInstalled?.();
}
catch (error) {
const message = error instanceof Error ? error.message : String(error);
setErrorMessage(message || "Failed to download Xtractor.");
toast.error("Failed to download Xtractor");
}
finally {
setDownloading(false);
}
};
const handleExit = () => {
if (!downloading) {
void Quit();
}
};
if (checking && !open) {
return null;
}
return (<Dialog open={open} onOpenChange={(nextOpen) => {
if (nextOpen) {
setOpen(true);
}
}}>
<DialogContent className="max-w-xl [&>button]:hidden" showCloseButton={false} onEscapeKeyDown={(event) => event.preventDefault()} onInteractOutside={(event) => event.preventDefault()}>
<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>{updateRequired ? "Update Xtractor" : "Download Xtractor"}</DialogTitle>
<DialogDescription>
{updateRequired ? "A newer Xtractor binary is available or the installed version could not be verified." : "Xtractor is required before you can use this app."}
</DialogDescription>
</DialogHeader>
<div className="space-y-3">
{updateRequired && releaseVersion && (<p className="text-sm text-amber-600 dark:text-amber-400">
Installed: {installedVersion || "unknown"} - Latest: {releaseVersion}
</p>)}
<p className="text-sm text-muted-foreground">{releaseVersion ? `Latest GitHub release: ${releaseVersion}` : releaseStatusMessage}</p>
{errorMessage && (<div className="flex items-start gap-2 rounded-lg border border-destructive/40 bg-destructive/10 p-3 text-sm text-destructive">
<AlertCircle className="mt-0.5 h-4 w-4 shrink-0"/>
<p>{errorMessage}</p>
</div>)}
</div>
<DialogFooter>
<Button variant="outline" onClick={handleExit} disabled={downloading}>
Exit App
</Button>
<Button onClick={handleDownload} disabled={downloading}>
{downloading ? (<>
<Spinner />
{updateRequired ? "Updating Xtractor..." : "Downloading Xtractor..."}
</>) : (<>
<Download className="h-4 w-4"/>
{updateRequired ? "Update Xtractor" : "Download Xtractor"}
</>)}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>);
}
+34
View File
@@ -0,0 +1,34 @@
import { Button } from "@/components/ui/button";
import { X, User } from "lucide-react";
export interface HistoryItem {
id: string;
username: string;
name: string;
image: string;
mediaCount: number;
timestamp: number;
}
interface FetchHistoryProps {
history: HistoryItem[];
onSelect: (item: HistoryItem) => void;
onRemove: (id: string) => void;
}
export function FetchHistory({ history, onSelect, onRemove }: FetchHistoryProps) {
if (history.length === 0)
return null;
return (<div className="space-y-2">
<p className="text-sm text-muted-foreground">Recent Fetches</p>
<div className="flex flex-wrap gap-2">
{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)}>
{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>
<Button variant="ghost" size="icon" className="h-4 w-4 opacity-0 group-hover:opacity-100 transition-opacity" onClick={(e) => {
e.stopPropagation();
onRemove(item.id);
}}>
<X className="h-3 w-3"/>
</Button>
</div>))}
</div>
</div>);
}
+66
View File
@@ -0,0 +1,66 @@
import { useRef } from "react";
import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
import { RefreshCw } from "lucide-react";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { type TemplateToken } from "@/lib/settings";
export function FormatEditor({ title, value, defaultValue, tokens, suffix, placeholder, render, onChange }: {
title: string;
value: string;
defaultValue: string;
tokens: TemplateToken[];
suffix?: string;
placeholder?: string;
render: (template: string) => string;
onChange: (next: string) => void;
}) {
const inputRef = useRef<HTMLInputElement | null>(null);
const insertToken = (token: string) => {
const input = inputRef.current;
let next: string;
let caret: number;
if (input && input.selectionStart !== null && input.selectionEnd !== null) {
const start = input.selectionStart;
const end = input.selectionEnd;
next = value.slice(0, start) + token + value.slice(end);
caret = start + token.length;
}
else {
next = value + token;
caret = next.length;
}
onChange(next);
requestAnimationFrame(() => {
if (input) {
input.focus();
input.setSelectionRange(caret, caret);
}
});
};
const preview = render(value) + (suffix ?? "");
return (<div className="space-y-3">
<Label className="text-sm font-semibold">{title}</Label>
<div className="relative">
<Input ref={inputRef} value={value} placeholder={placeholder} onChange={(e) => onChange(e.target.value)} className="font-mono text-sm pr-9"/>
<button type="button" onClick={() => onChange(defaultValue)} className="absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground transition-colors">
<RefreshCw className="h-4 w-4"/>
</button>
</div>
<div className="rounded-lg border bg-muted/40 px-3 py-2">
<div className="text-[10px] font-semibold uppercase tracking-wide text-muted-foreground">Preview</div>
<div className="font-mono text-sm break-all">{preview || <span className="text-muted-foreground italic">empty</span>}</div>
</div>
<div className="flex flex-wrap gap-2">
{tokens.map((token) => (<Tooltip key={token.key}>
<TooltipTrigger asChild>
<button type="button" onMouseDown={(e) => e.preventDefault()} onClick={() => insertToken(token.key)} className="rounded-md border bg-background px-2.5 py-1 text-xs font-mono text-muted-foreground transition-colors hover:text-foreground hover:border-primary/50">
{token.key}
</button>
</TooltipTrigger>
<TooltipContent side="top">
<span className="font-mono">{token.example || "—"}</span>
</TooltipContent>
</Tooltip>))}
</div>
</div>);
}
+39
View File
@@ -0,0 +1,39 @@
import { Badge } from "@/components/ui/badge";
import { Tooltip, TooltipContent, TooltipTrigger, } from "@/components/ui/tooltip";
import { openExternal } from "@/lib/utils";
import { formatRelativeTime } from "@/lib/relative-time";
interface HeaderProps {
version: string;
hasUpdate: boolean;
releaseDate?: string | null;
}
export function Header({ version, hasUpdate, releaseDate }: HeaderProps) {
return (<div className="relative">
<div className="text-center space-y-2">
<div className="flex items-center justify-center gap-3">
<img src="/icon.svg" alt="Twitter/X Media Batch Downloader" className="w-12 h-12"/>
<h1 className="text-3xl font-bold">
Twitter/X Media Batch Downloader
</h1>
<div className="relative">
<Tooltip>
<TooltipTrigger asChild>
<Badge variant="default" asChild>
<button type="button" onClick={() => openExternal("https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases")} className="cursor-pointer hover:opacity-80 transition-opacity">
v{version}
</button>
</Badge>
</TooltipTrigger>
{hasUpdate && releaseDate && (<TooltipContent>
<p>{formatRelativeTime(releaseDate)}</p>
</TooltipContent>)}
</Tooltip>
{hasUpdate && (<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="relative inline-flex rounded-full h-3 w-3 bg-green-500"></span>
</span>)}
</div>
</div>
</div>
</div>);
}
+75
View File
@@ -0,0 +1,75 @@
import { Fragment, type ReactNode } from "react";
import { openExternal } from "@/lib/utils";
function renderInline(text: string, keyPrefix: string): ReactNode[] {
const nodes: ReactNode[] = [];
const pattern = /\[([^\]]+)\]\(([^)]+)\)|\*\*([^*]+)\*\*|\*([^*]+)\*|`([^`]+)`/g;
let lastIndex = 0;
let match: RegExpExecArray | null;
let index = 0;
while ((match = pattern.exec(text)) !== null) {
if (match.index > lastIndex) {
nodes.push(<Fragment key={`${keyPrefix}-t${index}`}>{text.slice(lastIndex, match.index)}</Fragment>);
}
if (match[1] !== undefined && match[2] !== undefined) {
const label = match[1];
const url = match[2];
nodes.push(<button key={`${keyPrefix}-l${index}`} type="button" onClick={() => openExternal(url)} className="cursor-pointer border-none bg-transparent p-0 text-primary underline hover:opacity-80">
{label}
</button>);
}
else if (match[3] !== undefined) {
nodes.push(<strong key={`${keyPrefix}-b${index}`} className="font-semibold text-foreground">{match[3]}</strong>);
}
else if (match[4] !== undefined) {
nodes.push(<em key={`${keyPrefix}-i${index}`}>{match[4]}</em>);
}
else if (match[5] !== undefined) {
nodes.push(<code key={`${keyPrefix}-c${index}`} className="rounded bg-muted px-1 py-0.5 font-mono text-xs">{match[5]}</code>);
}
lastIndex = pattern.lastIndex;
index++;
}
if (lastIndex < text.length) {
nodes.push(<Fragment key={`${keyPrefix}-t${index}`}>{text.slice(lastIndex)}</Fragment>);
}
return nodes;
}
export function MarkdownLite({ content }: {
content: string;
}) {
const lines = (content || "").replace(/\r\n/g, "\n").split("\n");
const blocks: ReactNode[] = [];
let listItems: string[] = [];
let key = 0;
const flushList = () => {
if (listItems.length === 0)
return;
const items = listItems;
listItems = [];
blocks.push(<ul key={`ul-${key++}`} className="list-disc space-y-1 pl-5">
{items.map((item, index) => (<li key={index}>{renderInline(item, `li-${key}-${index}`)}</li>))}
</ul>);
};
for (const raw of lines) {
const line = raw.trimEnd();
const bullet = line.match(/^\s*[-*]\s+(.*)$/);
if (bullet) {
listItems.push(bullet[1]);
continue;
}
flushList();
const heading = line.match(/^(#{1,6})\s+(.*)$/);
if (heading) {
blocks.push(<p key={`h-${key++}`} className="font-semibold text-foreground">
{renderInline(heading[2], `h-${key}`)}
</p>);
continue;
}
if (line.trim() === "") {
continue;
}
blocks.push(<p key={`p-${key++}`}>{renderInline(line, `p-${key}`)}</p>);
}
flushList();
return <div className="space-y-2 text-sm text-muted-foreground">{blocks}</div>;
}
File diff suppressed because it is too large. Load diff
+772
View File
@@ -0,0 +1,772 @@
import { useEffect, useRef, useState } from "react";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { InputWithContext } from "@/components/ui/input-with-context";
import { Label } from "@/components/ui/label";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { FetchHistory } from "@/components/FetchHistory";
import type { HistoryItem } from "@/components/FetchHistory";
import { toastWithSound as toast } from "@/lib/toast-with-sound";
import { cn } from "@/lib/utils";
import { getSettings, updateSettings, VIDEO_QUALITIES, IMAGE_SIZES, AVATAR_SIZES, BANNER_SIZES, type VideoQuality, type ImageSize, type AvatarSize, type BannerSize } from "@/lib/settings";
import { GetStoredAuthToken, SetStoredAuthToken } from "../../wailsjs/go/main/App";
import { AlertCircle, Bookmark, CheckCircle, CircleQuestionMark, Clipboard, CloudDownload, Clock, Database, Eye, EyeOff, Globe, Heart, Hourglass, Lock, RotateCcw, SlidersHorizontal, StopCircle, Trash2, User, Users, XCircle } from "lucide-react";
import { Spinner } from "@/components/ui/spinner";
function formatNumberWithComma(num: number): string {
return num.toLocaleString();
}
function pillClass(active: boolean): string {
return cn("rounded-md px-3 py-1.5 text-sm font-medium transition-colors cursor-pointer", active
? "bg-primary text-primary-foreground"
: "bg-muted text-muted-foreground hover:text-foreground");
}
export type FetchMode = "public" | "private";
export type PrivateType = "bookmarks" | "likes";
export type FetchType = "single" | "multiple";
const LEGACY_PUBLIC_AUTH_TOKEN_KEY = "twitter_public_auth_token";
const LEGACY_PRIVATE_AUTH_TOKEN_KEY = "twitter_private_auth_token";
let sessionAuthToken = "";
export interface MultipleAccount {
id: string;
username: string;
status: "pending" | "fetching" | "completed" | "incomplete" | "failed";
accountInfo?: {
name: string;
nick: string;
profile_image: string;
};
mediaCount: number;
previousMediaCount: number;
elapsedTime: number;
remainingTime: number | null;
error?: string;
showDiff?: boolean;
cursor?: string;
}
interface SearchBarProps {
username: string;
loading: boolean;
onUsernameChange: (username: string) => void;
onFetch: (useDateRange: boolean, startDate?: string, endDate?: string, mediaType?: string, retweets?: boolean, mode?: FetchMode, privateType?: PrivateType, authToken?: string, isResume?: boolean) => void;
onStopFetch: () => void;
onResume?: (authToken: string, mediaType?: string, retweets?: boolean) => void;
onClearResume?: () => void;
resumeInfo?: {
canResume: boolean;
mediaCount: number;
} | null;
history: HistoryItem[];
onHistorySelect: (item: HistoryItem) => void;
onHistoryRemove: (id: string) => void;
hasResult: boolean;
elapsedTime?: number;
remainingTime?: number | null;
fetchType?: FetchType;
onFetchTypeChange?: (type: FetchType) => void;
multipleAccounts?: MultipleAccount[];
onImportAccounts?: (accounts: string[]) => void;
onFetchAll?: (authToken: string) => void;
onStopAll?: () => void;
onStopAccount?: (accountId: string) => void;
onRetryAccount?: (accountId: string, authToken: string) => void;
onClearMultipleAccounts?: () => void;
onRemoveMultipleAccount?: (accountId: string) => void;
onOpenSavedAccounts?: () => void;
isFetchingAll?: boolean;
mode?: FetchMode;
privateType?: PrivateType;
onModeChange?: (mode: FetchMode, privateType?: PrivateType) => void;
}
export function SearchBar({ username, loading, onUsernameChange, onFetch, onStopFetch, onResume, onClearResume, resumeInfo, history, onHistorySelect, onHistoryRemove, hasResult, elapsedTime = 0, remainingTime = null, fetchType = "single", onFetchTypeChange, multipleAccounts = [], onImportAccounts, onFetchAll, onStopAll, onStopAccount, onRetryAccount, onClearMultipleAccounts, onRemoveMultipleAccount, onOpenSavedAccounts, isFetchingAll = false, mode: externalMode, privateType: externalPrivateType, onModeChange, }: SearchBarProps) {
const [includePhotos, setIncludePhotos] = useState(getSettings().includePhotos);
const [includeVideos, setIncludeVideos] = useState(getSettings().includeVideos);
const [includeGifs, setIncludeGifs] = useState(getSettings().includeGifs);
const [includeText, setIncludeText] = useState(getSettings().includeText);
const [retweets, setRetweets] = useState(getSettings().includeRetweets);
const [videoQuality, setVideoQuality] = useState<VideoQuality>(getSettings().videoQuality);
const [imageSize, setImageSize] = useState<ImageSize>(getSettings().imageSize);
const [avatarSize, setAvatarSize] = useState<AvatarSize>(getSettings().avatarSize);
const [bannerSize, setBannerSize] = useState<BannerSize>(getSettings().bannerSize);
const [sharedAuthToken, setSharedAuthToken] = useState(() => sessionAuthToken || localStorage.getItem(LEGACY_PUBLIC_AUTH_TOKEN_KEY) || localStorage.getItem(LEGACY_PRIVATE_AUTH_TOKEN_KEY) || "");
const [showAuthToken, setShowAuthToken] = useState(false);
const [showAuthRequiredDialog, setShowAuthRequiredDialog] = useState(false);
const [showSettingsDialog, setShowSettingsDialog] = useState(false);
useEffect(() => {
if (showSettingsDialog) {
const fresh = getSettings();
setIncludePhotos(fresh.includePhotos);
setIncludeVideos(fresh.includeVideos);
setIncludeGifs(fresh.includeGifs);
setIncludeText(fresh.includeText);
setRetweets(fresh.includeRetweets);
setVideoQuality(fresh.videoQuality);
setImageSize(fresh.imageSize);
setAvatarSize(fresh.avatarSize);
setBannerSize(fresh.bannerSize);
}
}, [showSettingsDialog]);
const [showImportDialog, setShowImportDialog] = useState(false);
const [importAccountsText, setImportAccountsText] = useState("");
const [authPromptToken, setAuthPromptToken] = useState("");
const mode = externalMode || "public";
const privateType = externalPrivateType || "bookmarks";
const isLikesMode = mode === "private" && privateType === "likes";
const isBookmarksMode = mode === "private" && privateType === "bookmarks";
const isAnyMultipleAccountFetching = multipleAccounts.some((account) => account.status === "fetching");
useEffect(() => {
let active = true;
const syncStoredTokens = async () => {
const legacyPublicToken = localStorage.getItem(LEGACY_PUBLIC_AUTH_TOKEN_KEY) || "";
const legacyPrivateToken = localStorage.getItem(LEGACY_PRIVATE_AUTH_TOKEN_KEY) || "";
const legacyUnifiedToken = legacyPublicToken || legacyPrivateToken;
try {
if (legacyUnifiedToken) {
await Promise.all([
SetStoredAuthToken("public", legacyUnifiedToken),
SetStoredAuthToken("private", legacyUnifiedToken),
]);
}
}
catch (error) {
console.error("Failed to migrate legacy auth token:", error);
}
finally {
localStorage.removeItem(LEGACY_PUBLIC_AUTH_TOKEN_KEY);
localStorage.removeItem(LEGACY_PRIVATE_AUTH_TOKEN_KEY);
}
try {
const [storedPublicToken, storedPrivateToken] = await Promise.all([
GetStoredAuthToken("public"),
GetStoredAuthToken("private"),
]);
if (!active) {
return;
}
const unifiedToken = storedPublicToken || storedPrivateToken || "";
sessionAuthToken = unifiedToken;
setSharedAuthToken(unifiedToken);
if (unifiedToken && (storedPublicToken !== unifiedToken || storedPrivateToken !== unifiedToken)) {
await Promise.all([
SetStoredAuthToken("public", unifiedToken),
SetStoredAuthToken("private", unifiedToken),
]);
}
}
catch (error) {
console.error("Failed to load auth token from secure storage:", error);
}
};
void syncStoredTokens();
return () => {
active = false;
};
}, []);
const tokenWriteTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const pendingAuthActionRef = useRef<((authToken: string) => void) | null>(null);
useEffect(() => {
return () => {
if (tokenWriteTimerRef.current) {
clearTimeout(tokenWriteTimerRef.current);
}
};
}, []);
const handleSharedTokenChange = (value: string) => {
sessionAuthToken = value;
setSharedAuthToken(value);
if (tokenWriteTimerRef.current) {
clearTimeout(tokenWriteTimerRef.current);
}
tokenWriteTimerRef.current = setTimeout(() => {
void Promise.all([
SetStoredAuthToken("public", value),
SetStoredAuthToken("private", value),
]).catch((error) => {
console.error("Failed to store auth token securely:", error);
});
}, 400);
};
const closeAuthRequiredDialog = (open: boolean) => {
setShowAuthRequiredDialog(open);
if (!open) {
pendingAuthActionRef.current = null;
}
};
const requireAuthToken = (onAuthorized: (authToken: string) => void) => {
const token = sharedAuthToken.trim();
if (token) {
onAuthorized(token);
return;
}
pendingAuthActionRef.current = onAuthorized;
setAuthPromptToken(sharedAuthToken);
setShowAuthRequiredDialog(true);
};
const handleFetch = () => {
requireAuthToken((authToken) => {
onFetch(false, undefined, undefined, undefined, retweets, mode, privateType, authToken, false);
});
};
const handleClipboardPaste = async () => {
try {
const clipboardText = (await navigator.clipboard.readText()).trim();
if (clipboardText) {
onUsernameChange(clipboardText);
}
}
catch (error) {
console.error("Failed to read clipboard:", error);
}
};
const handleResume = () => {
if (onResume) {
requireAuthToken((authToken) => {
onResume(authToken, undefined, retweets);
});
}
};
const handleFetchAll = () => {
requireAuthToken((authToken) => {
onFetchAll?.(authToken);
});
};
const handleRetry = (accountId: string) => {
requireAuthToken((authToken) => {
onRetryAccount?.(accountId, authToken);
});
};
const handleAuthPromptSubmit = () => {
const token = authPromptToken.trim();
if (!token) {
toast.error("Please enter your auth token");
return;
}
handleSharedTokenChange(token);
const pendingAction = pendingAuthActionRef.current;
pendingAuthActionRef.current = null;
setShowAuthRequiredDialog(false);
pendingAction?.(token);
};
const handleOpenFetchSettings = () => {
pendingAuthActionRef.current = null;
setShowAuthRequiredDialog(false);
setShowSettingsDialog(true);
};
const openImportDialog = () => {
setImportAccountsText(multipleAccounts.map((account) => account.username).join("\n"));
setShowImportDialog(true);
};
const handleImportSubmit = () => {
const accounts = importAccountsText
.split(/[\n,;]+/)
.map((entry) => entry.trim())
.filter((entry) => entry.length > 0);
if (accounts.length === 0) {
toast.error("Please enter at least one account");
return;
}
onImportAccounts?.(accounts);
setShowImportDialog(false);
};
const formatTime = (seconds: number): string => {
const mins = Math.floor(seconds / 60);
const secs = seconds % 60;
return `${mins}:${String(secs).padStart(2, "0")}`;
};
const activeCountdown = remainingTime !== null && remainingTime >= 0
? formatTime(remainingTime)
: elapsedTime > 0
? formatTime(elapsedTime)
: null;
const fetchingLabel = activeCountdown ? `Fetching... (${activeCountdown})` : "Fetching...";
const authTokenHelpText = mode === "private"
? "Use auth token from the account whose bookmarks or likes you want to fetch."
: "Recommended to use a dummy account, not your main account. Excessive usage may cause suspension.";
return (<div className="space-y-3">
<div className="flex justify-center gap-2">
<div className="flex w-fit gap-0.5 rounded-lg bg-muted p-0.5">
<button type="button" onClick={() => onFetchTypeChange?.("single")} className={cn("flex cursor-pointer items-center gap-1 rounded-md px-2 py-1 text-xs font-medium transition-all", fetchType === "single"
? "bg-background text-foreground shadow-sm"
: "text-muted-foreground hover:text-foreground")}>
<User className="h-3 w-3"/>
Single
</button>
<button type="button" onClick={() => onFetchTypeChange?.("multiple")} className={cn("flex cursor-pointer items-center gap-1 rounded-md px-2 py-1 text-xs font-medium transition-all", fetchType === "multiple"
? "bg-background text-foreground shadow-sm"
: "text-muted-foreground hover:text-foreground")}>
<Users className="h-3 w-3"/>
Multiple
</button>
</div>
{fetchType === "single" && (<div className="flex w-fit gap-0.5 rounded-lg bg-muted p-0.5">
<button type="button" onClick={() => {
onModeChange?.("public");
}} className={cn("flex cursor-pointer items-center gap-1 rounded-md px-2 py-1 text-xs font-medium transition-all", mode === "public"
? "bg-background text-foreground shadow-sm"
: "text-muted-foreground hover:text-foreground")}>
<Globe className="h-3 w-3"/>
Public
</button>
<button type="button" onClick={() => {
onModeChange?.("private");
}} className={cn("flex cursor-pointer items-center gap-1 rounded-md px-2 py-1 text-xs font-medium transition-all", mode === "private"
? "bg-background text-foreground shadow-sm"
: "text-muted-foreground hover:text-foreground")}>
<Lock className="h-3 w-3"/>
Private
</button>
</div>)}
</div>
{fetchType === "multiple" && (<div className="space-y-2">
<div className="flex items-center gap-2">
<Label className="text-sm">Account List</Label>
<Tooltip>
<TooltipTrigger asChild>
<CircleQuestionMark className="h-4 w-4 cursor-help text-muted-foreground"/>
</TooltipTrigger>
<TooltipContent className="max-w-xs">
<p className="text-sm">
One username or URL per line. Commas and semicolons are supported too.
</p>
</TooltipContent>
</Tooltip>
</div>
<div className="flex flex-wrap items-center justify-between gap-2">
<Button variant="outline" onClick={openImportDialog} disabled={isFetchingAll} className="flex w-64 items-center justify-center gap-2">
<Users className="h-4 w-4"/>
Input Account List
</Button>
<div className="ml-auto flex items-center gap-2">
{isFetchingAll && (<Button variant="destructive" onClick={onStopAll} className="w-28">
<StopCircle className="h-4 w-4"/>
Stop All
</Button>)}
<Tooltip>
<TooltipTrigger asChild>
<Button variant="outline" size="icon" onClick={() => setShowSettingsDialog(true)} disabled={loading || isFetchingAll} aria-label="Fetch settings">
<SlidersHorizontal className="h-4 w-4"/>
</Button>
</TooltipTrigger>
<TooltipContent>Fetch Settings</TooltipContent>
</Tooltip>
<Button variant="default" onClick={handleFetchAll} disabled={multipleAccounts.length === 0 || isFetchingAll} className="flex w-36 items-center justify-center gap-2">
{isFetchingAll ? (<>
<Spinner />
Fetching All...
</>) : (<>
<CloudDownload className="h-4 w-4"/>
Fetch All
</>)}
</Button>
</div>
</div>
</div>)}
{fetchType === "single" && (mode === "public" || isLikesMode) && (<div className="space-y-2">
<Label htmlFor="username">X/Twitter URL or Username</Label>
<div className="flex gap-2">
<div className="relative flex-1">
<InputWithContext id="username" placeholder={isLikesMode
? "your_username or @your_username or https://x.com/your_username"
: "masteraoko or @masteraoko or https://x.com/masteraoko"} value={username} onChange={(e) => onUsernameChange(e.target.value)} onKeyDown={(e) => e.key === "Enter" && handleFetch()} className="pr-8"/>
{username && (<button type="button" className="absolute top-1/2 right-2 -translate-y-1/2 cursor-pointer text-muted-foreground transition-colors hover:text-foreground" onClick={() => onUsernameChange("")}>
<XCircle className="h-4 w-4"/>
</button>)}
</div>
<Button variant="outline" size="icon" className="shrink-0" aria-label="Paste from clipboard" onClick={() => void handleClipboardPaste()}>
<Clipboard className="h-4 w-4"/>
</Button>
<div className="flex items-center gap-2">
{loading && (<Button variant="destructive" onClick={onStopFetch}>
<StopCircle className="h-4 w-4"/>
Stop
</Button>)}
{!loading && resumeInfo?.canResume && mode === "public" && (<>
<Tooltip>
<TooltipTrigger asChild>
<Button variant="outline" size="icon" onClick={onClearResume}>
<Trash2 className="h-4 w-4"/>
</Button>
</TooltipTrigger>
<TooltipContent>Clear Resume</TooltipContent>
</Tooltip>
<Button variant="secondary" onClick={handleResume}>
<RotateCcw className="h-4 w-4"/>
Resume ({resumeInfo.mediaCount.toLocaleString()})
</Button>
</>)}
<Tooltip>
<TooltipTrigger asChild>
<Button variant="outline" size="icon" onClick={() => setShowSettingsDialog(true)} disabled={loading} aria-label="Fetch settings">
<SlidersHorizontal className="h-4 w-4"/>
</Button>
</TooltipTrigger>
<TooltipContent>Fetch Settings</TooltipContent>
</Tooltip>
<Button onClick={handleFetch} disabled={loading}>
{loading ? (<>
<Spinner />
{fetchingLabel}
</>) : (<>
{isLikesMode ? <Heart className="h-4 w-4"/> : <CloudDownload className="h-4 w-4"/>}
{isLikesMode ? "Fetch Likes" : "Fetch"}
</>)}
</Button>
</div>
</div>
</div>)}
<div className="flex items-center gap-2">
{mode === "private" && fetchType === "single" && (<>
<button type="button" onClick={() => {
onModeChange?.("private", "bookmarks");
}} className={cn("flex cursor-pointer items-center gap-2 rounded-lg border px-4 py-2 text-sm font-medium transition-all", privateType === "bookmarks"
? "border-primary bg-primary/10 text-primary"
: "border-border hover:border-primary/50")}>
<Bookmark className="h-4 w-4"/>
My Bookmarks
</button>
<button type="button" onClick={() => {
onModeChange?.("private", "likes");
}} className={cn("flex cursor-pointer items-center gap-2 rounded-lg border px-4 py-2 text-sm font-medium transition-all", privateType === "likes"
? "border-primary bg-primary/10 text-primary"
: "border-border hover:border-primary/50")}>
<Heart className="h-4 w-4"/>
My Likes
</button>
</>)}
{fetchType === "single" && isBookmarksMode && (<div className="ml-auto flex items-center gap-2">
{loading && (<Button variant="destructive" onClick={onStopFetch}>
<StopCircle className="h-4 w-4"/>
Stop
</Button>)}
<Tooltip>
<TooltipTrigger asChild>
<Button variant="outline" size="icon" onClick={() => setShowSettingsDialog(true)} disabled={loading} aria-label="Fetch settings">
<SlidersHorizontal className="h-4 w-4"/>
</Button>
</TooltipTrigger>
<TooltipContent>Fetch Settings</TooltipContent>
</Tooltip>
<Button onClick={handleFetch} disabled={loading}>
{loading ? (<>
<Spinner />
{fetchingLabel}
</>) : (<>
<Bookmark className="h-4 w-4"/>
Fetch Bookmarks
</>)}
</Button>
</div>)}
</div>
{fetchType === "multiple" && multipleAccounts.length > 0 && (<div className="rounded-lg border bg-muted/30 p-3">
<div className="flex items-center gap-6 text-sm">
<div className="flex items-center gap-2">
<CheckCircle className="h-4 w-4 text-green-600 dark:text-green-400"/>
<span className="text-muted-foreground">Completed:</span>
<span className="font-medium">
{formatNumberWithComma(multipleAccounts.filter((acc) => acc.status === "completed").length)}
</span>
</div>
<div className="flex items-center gap-2">
<AlertCircle className="h-4 w-4 text-yellow-600 dark:text-yellow-400"/>
<span className="text-muted-foreground">Incomplete:</span>
<span className="font-medium">
{formatNumberWithComma(multipleAccounts.filter((acc) => acc.status === "incomplete").length)}
</span>
</div>
<div className="flex items-center gap-2">
<XCircle className="h-4 w-4 text-red-600 dark:text-red-400"/>
<span className="text-muted-foreground">Failed:</span>
<span className="font-medium">
{formatNumberWithComma(multipleAccounts.filter((acc) => acc.status === "failed").length)}
</span>
</div>
<div className="ml-auto flex items-center gap-3">
<div className="flex items-center gap-2">
<span className="text-muted-foreground">Total:</span>
<span className="font-medium">
{formatNumberWithComma(multipleAccounts.filter((acc) => acc.status === "completed" || acc.status === "incomplete" || acc.status === "failed").length)}/{formatNumberWithComma(multipleAccounts.length)}
</span>
</div>
{!isFetchingAll && onOpenSavedAccounts && multipleAccounts.some((acc) => acc.status === "completed" || acc.status === "incomplete") && (<Button variant="secondary" size="sm" onClick={onOpenSavedAccounts} className="flex items-center gap-2">
<Database className="h-3.5 w-3.5"/>
Open Saved Accounts to Download
</Button>)}
</div>
</div>
</div>)}
{fetchType === "multiple" && multipleAccounts.length > 0 && (<div className="space-y-2">
<div className="flex items-center justify-between gap-2">
<p className="text-sm text-muted-foreground">Accounts to Fetch ({formatNumberWithComma(multipleAccounts.length)})</p>
<Button variant="outline" size="sm" onClick={onClearMultipleAccounts} disabled={isFetchingAll || isAnyMultipleAccountFetching} className="flex items-center gap-2">
<Trash2 className="h-4 w-4"/>
Clear List
</Button>
</div>
<div className="max-h-100 space-y-2 overflow-y-auto">
{multipleAccounts.map((account) => (<div key={account.id} className="rounded-lg border bg-card p-3">
<div className="flex items-center gap-3">
{account.accountInfo ? (<img src={account.accountInfo.profile_image} alt={account.accountInfo.nick} className="h-10 w-10 rounded-full"/>) : (<div className="flex h-10 w-10 items-center justify-center rounded-full bg-muted">
<User className="h-5 w-5 text-muted-foreground"/>
</div>)}
<div className="min-w-0 flex-1">
{account.accountInfo ? (<>
<div className="flex items-center gap-2">
<span className="font-medium">{account.accountInfo.nick}</span>
<span className="text-sm text-muted-foreground">@{account.accountInfo.name}</span>
</div>
<div className="mt-1 flex items-center gap-2">
<span className="text-sm text-muted-foreground">
<span className="text-primary">{account.mediaCount.toLocaleString()}</span> items found
</span>
{account.showDiff && account.previousMediaCount > 0 && account.mediaCount > account.previousMediaCount && (<span className="text-sm font-medium text-green-600 dark:text-green-400">
+{account.mediaCount - account.previousMediaCount}
</span>)}
</div>
</>) : (<div className="flex items-center gap-2">
<span className="font-medium">@{account.username}</span>
</div>)}
</div>
<div className="flex items-center gap-2">
{account.status === "fetching" && (<>
<div className="flex w-21.25 items-center gap-1.5 rounded-md border bg-muted/50 px-3 py-1.5 text-sm">
<Clock className="h-3.5 w-3.5 shrink-0 text-muted-foreground"/>
<span className="font-mono">
{account.remainingTime !== null && account.remainingTime >= 0
? formatTime(account.remainingTime)
: formatTime(account.elapsedTime)}
</span>
</div>
<Button variant="destructive" onClick={() => onStopAccount?.(account.id)} className="flex items-center gap-2">
<StopCircle className="h-4 w-4"/>
Stop
</Button>
</>)}
{account.status === "pending" && (<span className="flex items-center gap-1.5 rounded bg-gray-500/20 px-2 py-1 text-xs text-gray-600 dark:text-gray-400">
<Hourglass className="h-3 w-3"/>
Pending
</span>)}
{account.status === "completed" && (<span className="flex items-center gap-1.5 rounded bg-green-500/20 px-2 py-1 text-xs text-green-600 dark:text-green-400">
<CheckCircle className="h-3 w-3"/>
Completed
</span>)}
{account.status === "incomplete" && (<>
<span className="flex items-center gap-1.5 rounded bg-yellow-500/20 px-2 py-1 text-xs text-yellow-600 dark:text-yellow-400">
<AlertCircle className="h-3 w-3"/>
Incomplete
</span>
<Button variant="outline" size="sm" onClick={() => handleRetry(account.id)} disabled={isFetchingAll} className="flex items-center gap-2">
<RotateCcw className="h-3.5 w-3.5"/>
Retry
</Button>
</>)}
{account.status === "failed" && (<>
<span className="flex items-center gap-1.5 rounded bg-red-500/20 px-2 py-1 text-xs text-red-600 dark:text-red-400">
<XCircle className="h-3 w-3"/>
Failed
</span>
<Button variant="outline" size="sm" onClick={() => handleRetry(account.id)} disabled={isFetchingAll} className="flex items-center gap-2">
<RotateCcw className="h-3.5 w-3.5"/>
Retry
</Button>
</>)}
<Button variant="outline" size="sm" onClick={() => onRemoveMultipleAccount?.(account.id)} disabled={isFetchingAll || account.status === "fetching"} className="flex items-center gap-2">
<Trash2 className="h-3.5 w-3.5"/>
Delete
</Button>
</div>
</div>
</div>))}
</div>
</div>)}
{!hasResult && mode === "public" && fetchType === "single" && (<FetchHistory history={history} onSelect={onHistorySelect} onRemove={onHistoryRemove}/>)}
<Dialog open={showImportDialog} onOpenChange={setShowImportDialog}>
<DialogContent className="sm:max-w-xl">
<DialogHeader>
<DialogTitle>Input Account List</DialogTitle>
<DialogDescription>
Enter one username or URL per line. Commas and semicolons also work.
</DialogDescription>
</DialogHeader>
<textarea value={importAccountsText} onChange={(e) => setImportAccountsText(e.target.value)} placeholder={"masteraoko\nxbatchdemo\nhttps://x.com/takomayuyi"} className="border-input placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 min-h-64 w-full rounded-md border bg-transparent px-3 py-2 text-sm shadow-xs outline-none focus-visible:ring-[3px]"/>
<DialogFooter>
<Button variant="outline" onClick={() => setShowImportDialog(false)}>Cancel</Button>
<Button onClick={handleImportSubmit}>Import Accounts</Button>
</DialogFooter>
</DialogContent>
</Dialog>
<Dialog open={showAuthRequiredDialog} onOpenChange={closeAuthRequiredDialog}>
<DialogContent className="sm:max-w-xl">
<DialogHeader>
<DialogTitle>Cookie Required</DialogTitle>
</DialogHeader>
<div className="space-y-4">
<div className="space-y-2">
<Label htmlFor="required-auth-token">Auth Token</Label>
<div className="relative">
<InputWithContext id="required-auth-token" type={showAuthToken ? "text" : "password"} placeholder="Enter your auth_token cookie value" value={authPromptToken} onChange={(e) => setAuthPromptToken(e.target.value)} onKeyDown={(e) => {
if (e.key === "Enter") {
handleAuthPromptSubmit();
}
}} className="pr-10"/>
<button type="button" aria-label={showAuthToken ? "Hide auth token" : "Show auth token"} className="absolute top-1/2 right-2 -translate-y-1/2 text-muted-foreground transition-colors hover:text-foreground" onClick={() => setShowAuthToken((prev) => !prev)}>
{showAuthToken ? <EyeOff className="h-4 w-4"/> : <Eye className="h-4 w-4"/>}
</button>
</div>
</div>
<div className="space-y-3 rounded-lg border bg-muted/30 p-4 text-sm">
<p>
Tutorial:
{" "}
<a href="https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader#how-to-obtain-auth-token" target="_blank" rel="noreferrer" className="font-medium underline underline-offset-4">
afkarxyz/Twitter-X-Media-Batch-Downloader
</a>
</p>
<ol className="list-decimal space-y-1 pl-5 text-muted-foreground">
<li>
Go to
{" "}
<a href="https://www.x.com/" target="_blank" rel="noreferrer" className="underline underline-offset-4">
Twitter&apos;s website
</a>
</li>
<li>Log into your account</li>
<li>
Open the Developer Tools by pressing
{" "}
<kbd className="rounded border bg-background px-1.5 py-0.5 font-mono text-xs">F12</kbd>
</li>
<li>
Navigate to the Application tab, then select Storage {"->"} Cookies
</li>
<li>Find and copy the <code>auth_token</code> value</li>
<li>Do not log out of your account, as a new <code>auth_token</code> will be generated by Twitter</li>
</ol>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={handleOpenFetchSettings}>Open Fetch Settings</Button>
<Button variant="outline" onClick={() => closeAuthRequiredDialog(false)}>Cancel</Button>
<Button onClick={handleAuthPromptSubmit}>Save and Continue</Button>
</DialogFooter>
</DialogContent>
</Dialog>
<Dialog open={showSettingsDialog} onOpenChange={setShowSettingsDialog}>
<DialogContent className="sm:max-w-xl max-h-[85vh] flex flex-col overflow-hidden">
<DialogHeader>
<DialogTitle>Fetch Settings</DialogTitle>
</DialogHeader>
<div className="space-y-4 overflow-y-auto flex-1 min-h-0 -mx-2 px-2">
<div className="space-y-2">
<div className="flex items-center gap-2">
<Label htmlFor="shared-auth-token" className="text-sm">Auth Token</Label>
<Tooltip>
<TooltipTrigger asChild>
<CircleQuestionMark className="h-4 w-4 cursor-help text-muted-foreground"/>
</TooltipTrigger>
<TooltipContent className="max-w-sm">
<p className="text-sm">{authTokenHelpText}</p>
</TooltipContent>
</Tooltip>
</div>
<InputWithContext id="shared-auth-token" type="text" placeholder="Enter your auth_token cookie value" value={sharedAuthToken} onChange={(e) => void handleSharedTokenChange(e.target.value)}/>
</div>
{fetchType === "single" && (<div className="flex items-center justify-between gap-4">
<Label htmlFor="retweets" className="cursor-pointer text-sm">Include Reposts</Label>
<Checkbox id="retweets" checked={retweets} onCheckedChange={(checked) => {
const value = checked as boolean;
updateSettings({ includeRetweets: value });
setRetweets(value);
}}/>
</div>)}
<div className="space-y-2">
<Label className="text-sm">Include Media</Label>
<div className="grid grid-cols-4 gap-2">
<button type="button" className={pillClass(includePhotos)} onClick={() => { updateSettings({ includePhotos: !includePhotos }); setIncludePhotos((v) => !v); }}>Photos</button>
<button type="button" className={pillClass(includeVideos)} onClick={() => { updateSettings({ includeVideos: !includeVideos }); setIncludeVideos((v) => !v); }}>Videos</button>
<button type="button" className={pillClass(includeGifs)} onClick={() => { updateSettings({ includeGifs: !includeGifs }); setIncludeGifs((v) => !v); }}>GIFs</button>
<button type="button" className={pillClass(includeText)} onClick={() => { updateSettings({ includeText: !includeText }); setIncludeText((v) => !v); }}>Text</button>
</div>
</div>
<div className="space-y-2">
<Label className="text-sm">Video Quality</Label>
<div className="grid grid-cols-5 gap-2">
{VIDEO_QUALITIES.map((q) => (<button key={q.value} type="button" className={pillClass(videoQuality === q.value)} onClick={() => { updateSettings({ videoQuality: q.value }); setVideoQuality(q.value); }}>{q.label}</button>))}
</div>
</div>
<div className="space-y-2">
<Label className="text-sm">Image Size</Label>
<div className="grid grid-cols-4 gap-2">
{IMAGE_SIZES.map((s) => (<button key={s.value} type="button" className={pillClass(imageSize === s.value)} onClick={() => { updateSettings({ imageSize: s.value }); setImageSize(s.value); }}>{s.label}</button>))}
</div>
</div>
<div className="space-y-2">
<Label className="text-sm">Avatar Size</Label>
<div className="grid grid-cols-5 gap-2">
{AVATAR_SIZES.map((s) => (<button key={s.value} type="button" className={pillClass(avatarSize === s.value)} onClick={() => { updateSettings({ avatarSize: s.value }); setAvatarSize(s.value); }}>{s.label}</button>))}
</div>
</div>
<div className="space-y-2">
<Label className="text-sm">Banner Size</Label>
<div className="grid grid-cols-4 gap-2">
{BANNER_SIZES.map((s) => (<button key={s.value} type="button" className={pillClass(bannerSize === s.value)} onClick={() => { updateSettings({ bannerSize: s.value }); setBannerSize(s.value); }}>{s.label}</button>))}
</div>
</div>
</div>
<DialogFooter>
<Button onClick={() => setShowSettingsDialog(false)}>Done</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>);
}
+984
View File
@@ -0,0 +1,984 @@
import { useEffect, useState, useCallback, useRef } from "react";
import { flushSync } from "react-dom";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { InputWithContext } from "@/components/ui/input-with-context";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { Check, CircleQuestionMark, Download, ExternalLink, FolderOpen, MonitorCog, PackageSearch, Plus, RotateCcw, Save, Trash2, FileSignature } from "lucide-react";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from "@/components/ui/dialog";
import { Spinner } from "@/components/ui/spinner";
import { Switch } from "@/components/ui/switch";
import { getSettings, getSettingsWithDefaults, saveSettings, resetToDefaultSettings, applyThemeMode, applyFont, getFontOptions, parseGoogleFontUrl, loadGoogleFontUrl, loadCustomFonts, saveCustomFonts, DEFAULT_FILENAME_TEMPLATE, FILENAME_TEMPLATE_VARIABLES, renderFilenameTemplate, SAMPLE_FILENAME_DATA, DEFAULT_FOLDER_TEMPLATE, FOLDER_TEMPLATE_VARIABLES, renderFolderTemplate, SAMPLE_FOLDER_DATA, type Settings as SettingsType, type FontFamily, type GifQuality, type GifResolution, type CustomFontFamily } from "@/lib/settings";
import { FormatEditor } from "@/components/FormatEditor";
import { getCachedDependencyStatus, setCachedDependencyStatus } from "@/lib/runtime-cache";
import { baseColors, getThemesForBaseColor, normalizeThemeName, applyTheme, type BaseColorName } from "@/lib/themes";
import { compareVersionNumbers } from "@/lib/version";
import { SelectFolder, IsExtractorInstalled, DownloadExtractor, IsFFmpegInstalled, DownloadFFmpeg, IsExifToolInstalled, DownloadExifTool } from "../../wailsjs/go/main/App";
import { toastWithSound as toast } from "@/lib/toast-with-sound";
interface DependencyVersionStatus {
installed: boolean;
installed_version?: string;
latest_version?: string;
}
type DependencyVersionMethod = "GetExtractorVersionStatus" | "GetFFmpegVersionStatus" | "GetExifToolVersionStatus";
type SettingsTab = "general" | "downloads" | "naming" | "dependencies";
const THEME_PREVIEW_DEBOUNCE_MS = 50;
interface SettingsPageProps {
onUnsavedChangesChange?: (hasUnsavedChanges: boolean) => void;
onResetRequest?: (resetFn: () => void) => void;
}
function getDependencyVersionStatus(methodName: DependencyVersionMethod) {
const app = (window as Window & {
go?: {
main?: {
App?: Partial<Record<DependencyVersionMethod, () => Promise<DependencyVersionStatus>>>;
};
};
}).go?.main?.App;
const method = app?.[methodName];
return method ? method() : Promise.resolve(null);
}
function hasNewDependencyVersion(installedVersion: string | null, latestVersion: string | null) {
if (!installedVersion || !latestVersion) {
return false;
}
return compareVersionNumbers(latestVersion, installedVersion) > 0;
}
function buildDependencyVersionText(name: string, installed: boolean, installedVersion: string | null, latestVersion: string | null, updateAvailable: boolean) {
if (installed) {
if (!installedVersion) {
return `${name} installed`;
}
return updateAvailable && latestVersion
? `${name} ${installedVersion} (New Version Available: ${latestVersion})`
: `${name} ${installedVersion}`;
}
return latestVersion ? `Latest ${name}: ${latestVersion}` : null;
}
export function SettingsPage({ onUnsavedChangesChange, onResetRequest }: SettingsPageProps) {
const cachedExtractorStatus = getCachedDependencyStatus("extractor");
const cachedFfmpegStatus = getCachedDependencyStatus("ffmpeg");
const cachedExiftoolStatus = getCachedDependencyStatus("exiftool");
const [savedSettings, setSavedSettings] = useState<SettingsType>(getSettings());
const [tempSettings, setTempSettings] = useState<SettingsType>(savedSettings);
const [isDark, setIsDark] = useState(document.documentElement.classList.contains("dark"));
const [activeTab, setActiveTab] = useState<SettingsTab>("general");
const [showAddFontDialog, setShowAddFontDialog] = useState(false);
const [addFontUrl, setAddFontUrl] = useState("");
const [extractorInstalled, setExtractorInstalled] = useState(cachedExtractorStatus.installed ?? false);
const [extractorInstalledVersion, setExtractorInstalledVersion] = useState<string | null>(cachedExtractorStatus.installedVersion);
const [extractorLatestVersion, setExtractorLatestVersion] = useState<string | null>(cachedExtractorStatus.latestVersion);
const [downloadingExtractor, setDownloadingExtractor] = useState(false);
const [ffmpegInstalled, setFfmpegInstalled] = useState(cachedFfmpegStatus.installed ?? false);
const [ffmpegInstalledVersion, setFfmpegInstalledVersion] = useState<string | null>(cachedFfmpegStatus.installedVersion);
const [ffmpegLatestVersion, setFfmpegLatestVersion] = useState<string | null>(cachedFfmpegStatus.latestVersion);
const [downloadingFFmpeg, setDownloadingFFmpeg] = useState(false);
const [exiftoolInstalled, setExiftoolInstalled] = useState(cachedExiftoolStatus.installed ?? false);
const [exiftoolInstalledVersion, setExiftoolInstalledVersion] = useState<string | null>(cachedExiftoolStatus.installedVersion);
const [exiftoolLatestVersion, setExiftoolLatestVersion] = useState<string | null>(cachedExiftoolStatus.latestVersion);
const [downloadingExifTool, setDownloadingExifTool] = useState(false);
const [showResetConfirm, setShowResetConfirm] = useState(false);
const extractorUpdateAvailable = hasNewDependencyVersion(extractorInstalledVersion, extractorLatestVersion);
const ffmpegUpdateAvailable = hasNewDependencyVersion(ffmpegInstalledVersion, ffmpegLatestVersion);
const exiftoolUpdateAvailable = hasNewDependencyVersion(exiftoolInstalledVersion, exiftoolLatestVersion);
const parsedAddFont = parseGoogleFontUrl(addFontUrl);
const fontOptions = getFontOptions(tempSettings.customFonts);
const availableThemes = getThemesForBaseColor(tempSettings.baseColor);
const hasUnsavedChanges = JSON.stringify(savedSettings) !== JSON.stringify(tempSettings);
const themePreviewTimerRef = useRef<number | null>(null);
const selectedThemeConfigRef = useRef({
baseColor: tempSettings.baseColor,
theme: tempSettings.theme,
});
const cancelThemePreview = useCallback(() => {
if (themePreviewTimerRef.current !== null) {
window.clearTimeout(themePreviewTimerRef.current);
themePreviewTimerRef.current = null;
}
}, []);
const previewThemeConfig = useCallback((themeName: SettingsType["theme"], baseColorName: BaseColorName) => {
cancelThemePreview();
themePreviewTimerRef.current = window.setTimeout(() => {
themePreviewTimerRef.current = null;
applyTheme(themeName, baseColorName);
}, THEME_PREVIEW_DEBOUNCE_MS);
}, [cancelThemePreview]);
const previewTheme = useCallback((themeName: SettingsType["theme"]) => {
previewThemeConfig(themeName, selectedThemeConfigRef.current.baseColor);
}, [previewThemeConfig]);
const previewBaseColor = useCallback((baseColorName: BaseColorName) => {
const themeName = normalizeThemeName(selectedThemeConfigRef.current.theme, baseColorName);
previewThemeConfig(themeName, baseColorName);
}, [previewThemeConfig]);
const restoreSelectedTheme = useCallback(() => {
cancelThemePreview();
const selectedTheme = selectedThemeConfigRef.current;
applyTheme(selectedTheme.theme, selectedTheme.baseColor);
}, [cancelThemePreview]);
const handleThemeChange = useCallback((themeName: SettingsType["theme"]) => {
cancelThemePreview();
const baseColorName = selectedThemeConfigRef.current.baseColor;
selectedThemeConfigRef.current = { baseColor: baseColorName, theme: themeName };
applyTheme(themeName, baseColorName);
setTempSettings((prev) => ({ ...prev, theme: themeName }));
}, [cancelThemePreview]);
const handleBaseColorChange = useCallback((baseColorName: BaseColorName) => {
cancelThemePreview();
const themeName = normalizeThemeName(selectedThemeConfigRef.current.theme, baseColorName);
selectedThemeConfigRef.current = { baseColor: baseColorName, theme: themeName };
applyTheme(themeName, baseColorName);
setTempSettings((prev) => ({ ...prev, baseColor: baseColorName, theme: themeName }));
}, [cancelThemePreview]);
const resetToSaved = useCallback(() => {
cancelThemePreview();
const freshSavedSettings = getSettings();
selectedThemeConfigRef.current = {
baseColor: freshSavedSettings.baseColor,
theme: freshSavedSettings.theme,
};
flushSync(() => {
setTempSettings(freshSavedSettings);
setIsDark(document.documentElement.classList.contains("dark"));
});
}, [cancelThemePreview]);
useEffect(() => {
selectedThemeConfigRef.current = {
baseColor: tempSettings.baseColor,
theme: tempSettings.theme,
};
}, [tempSettings.baseColor, tempSettings.theme]);
useEffect(() => () => {
cancelThemePreview();
const persistedSettings = getSettings();
applyTheme(persistedSettings.theme, persistedSettings.baseColor);
}, [cancelThemePreview]);
useEffect(() => {
if (onResetRequest) {
onResetRequest(resetToSaved);
}
}, [onResetRequest, resetToSaved]);
useEffect(() => {
onUnsavedChangesChange?.(hasUnsavedChanges);
}, [hasUnsavedChanges, onUnsavedChangesChange]);
const extractorVersionText = extractorInstalled
? extractorInstalledVersion
? extractorUpdateAvailable && extractorLatestVersion
? `${extractorInstalledVersion} (New Version Available: ${extractorLatestVersion})`
: extractorInstalledVersion
: "Installed (version unavailable)"
: extractorLatestVersion
? `Latest: ${extractorLatestVersion}`
: null;
const ffmpegVersionText = buildDependencyVersionText("FFmpeg", ffmpegInstalled, ffmpegInstalledVersion, ffmpegLatestVersion, ffmpegUpdateAvailable);
const exiftoolVersionText = buildDependencyVersionText("ExifTool", exiftoolInstalled, exiftoolInstalledVersion, exiftoolLatestVersion, exiftoolUpdateAvailable);
const loadDependencyStatus = async () => {
try {
const [extractorVersionStatus, ffmpegVersionStatus, exiftoolVersionStatus, extractor, ffmpeg, exiftool] = await Promise.all([
getDependencyVersionStatus("GetExtractorVersionStatus"),
getDependencyVersionStatus("GetFFmpegVersionStatus"),
getDependencyVersionStatus("GetExifToolVersionStatus"),
IsExtractorInstalled(),
IsFFmpegInstalled(),
IsExifToolInstalled(),
]);
const nextExtractorInstalled = extractorVersionStatus?.installed ?? extractor;
const nextExtractorInstalledVersion = extractorVersionStatus?.installed_version?.trim() || null;
const nextExtractorLatestVersion = extractorVersionStatus?.latest_version?.trim() || null;
const nextFfmpegInstalled = ffmpegVersionStatus?.installed ?? ffmpeg;
const nextFfmpegInstalledVersion = ffmpegVersionStatus?.installed_version?.trim() || null;
const nextFfmpegLatestVersion = ffmpegVersionStatus?.latest_version?.trim() || null;
const nextExiftoolInstalled = exiftoolVersionStatus?.installed ?? exiftool;
const nextExiftoolInstalledVersion = exiftoolVersionStatus?.installed_version?.trim() || null;
const nextExiftoolLatestVersion = exiftoolVersionStatus?.latest_version?.trim() || null;
setCachedDependencyStatus("extractor", {
installed: nextExtractorInstalled,
installedVersion: nextExtractorInstalledVersion,
latestVersion: nextExtractorLatestVersion,
});
setCachedDependencyStatus("ffmpeg", {
installed: nextFfmpegInstalled,
installedVersion: nextFfmpegInstalledVersion,
latestVersion: nextFfmpegLatestVersion,
});
setCachedDependencyStatus("exiftool", {
installed: nextExiftoolInstalled,
installedVersion: nextExiftoolInstalledVersion,
latestVersion: nextExiftoolLatestVersion,
});
setExtractorInstalled(nextExtractorInstalled);
setExtractorInstalledVersion(nextExtractorInstalledVersion);
setExtractorLatestVersion(nextExtractorLatestVersion);
setFfmpegInstalled(nextFfmpegInstalled);
setFfmpegInstalledVersion(nextFfmpegInstalledVersion);
setFfmpegLatestVersion(nextFfmpegLatestVersion);
setExiftoolInstalled(nextExiftoolInstalled);
setExiftoolInstalledVersion(nextExiftoolInstalledVersion);
setExiftoolLatestVersion(nextExiftoolLatestVersion);
}
catch (error) {
console.error("Failed to check dependency status:", error);
}
};
useEffect(() => {
applyThemeMode(savedSettings.themeMode);
applyTheme(savedSettings.theme, savedSettings.baseColor);
const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");
const handleChange = () => {
if (savedSettings.themeMode === "auto") {
applyThemeMode("auto");
applyTheme(savedSettings.theme, savedSettings.baseColor);
}
};
mediaQuery.addEventListener("change", handleChange);
return () => mediaQuery.removeEventListener("change", handleChange);
}, [savedSettings.themeMode, savedSettings.baseColor, savedSettings.theme]);
useEffect(() => {
applyThemeMode(tempSettings.themeMode);
applyTheme(tempSettings.theme, tempSettings.baseColor);
applyFont(tempSettings.fontFamily, tempSettings.customFonts);
setTimeout(() => {
setIsDark(document.documentElement.classList.contains("dark"));
}, 0);
}, [tempSettings.themeMode, tempSettings.baseColor, tempSettings.theme, tempSettings.fontFamily, tempSettings.customFonts]);
useEffect(() => {
if (showAddFontDialog && parsedAddFont) {
loadGoogleFontUrl(parsedAddFont.url, "twitter-media-add-font-preview");
}
}, [showAddFontDialog, parsedAddFont]);
useEffect(() => {
const loadDefaults = async () => {
if (!savedSettings.downloadPath) {
const settingsWithDefaults = await getSettingsWithDefaults();
setSavedSettings(settingsWithDefaults);
setTempSettings(settingsWithDefaults);
}
};
void loadDefaults();
void loadDependencyStatus();
}, []);
useEffect(() => {
const syncCustomFonts = async () => {
const customFonts = await loadCustomFonts();
setSavedSettings((prev) => ({ ...prev, customFonts }));
setTempSettings((prev) => ({ ...prev, customFonts }));
};
void syncCustomFonts();
}, []);
const handleSave = () => {
saveSettings(tempSettings);
setSavedSettings(tempSettings);
toast.success("Settings saved");
onUnsavedChangesChange?.(false);
};
const handleReset = async () => {
const defaultSettings = await resetToDefaultSettings();
setTempSettings(defaultSettings);
setSavedSettings(defaultSettings);
applyThemeMode(defaultSettings.themeMode);
applyTheme(defaultSettings.theme, defaultSettings.baseColor);
applyFont(defaultSettings.fontFamily, defaultSettings.customFonts);
setShowResetConfirm(false);
toast.success("Settings reset to default");
};
const handleBrowseFolder = async () => {
try {
const selectedPath = await SelectFolder(tempSettings.downloadPath || "");
if (selectedPath && selectedPath.trim() !== "") {
setTempSettings((prev) => ({ ...prev, downloadPath: selectedPath }));
}
}
catch (error) {
console.error("Error selecting folder:", error);
toast.error(`Error selecting folder: ${error}`);
}
};
const closeAddFontDialog = () => {
setShowAddFontDialog(false);
setAddFontUrl("");
};
const handleAddFont = async () => {
if (!parsedAddFont) {
toast.error("Enter a valid Google Fonts URL");
return;
}
const existingFonts = tempSettings.customFonts || [];
const existingIndex = existingFonts.findIndex((font) => font.value === parsedAddFont.value || font.url === parsedAddFont.url);
const customFonts = existingIndex >= 0
? existingFonts.map((font, index) => index === existingIndex ? parsedAddFont : font)
: [...existingFonts, parsedAddFont];
const savedCustomFonts = await saveCustomFonts(customFonts);
setSavedSettings((prev) => ({ ...prev, customFonts: savedCustomFonts }));
setTempSettings((prev) => ({
...prev,
customFonts: savedCustomFonts,
fontFamily: parsedAddFont.value,
}));
closeAddFontDialog();
toast.success(`${parsedAddFont.label} added`);
};
const handleDeleteCustomFont = async (fontValue: CustomFontFamily) => {
const customFonts = (tempSettings.customFonts || []).filter((font) => font.value !== fontValue);
const savedCustomFonts = await saveCustomFonts(customFonts);
const shouldResetSavedFont = savedSettings.fontFamily === fontValue;
const shouldResetTempFont = tempSettings.fontFamily === fontValue;
const nextSavedSettings: SettingsType = {
...savedSettings,
customFonts: savedCustomFonts,
fontFamily: shouldResetSavedFont ? "google-sans" : savedSettings.fontFamily,
};
setSavedSettings(nextSavedSettings);
setTempSettings((prev) => ({
...prev,
customFonts: savedCustomFonts,
fontFamily: shouldResetTempFont ? "google-sans" : prev.fontFamily,
}));
if (shouldResetSavedFont) {
saveSettings(nextSavedSettings);
}
toast.success("Font deleted");
};
const handleDownloadExtractor = async () => {
setDownloadingExtractor(true);
try {
const successMessage = extractorInstalled
? extractorUpdateAvailable
? "Xtractor updated successfully"
: "Xtractor reinstalled successfully"
: "Xtractor downloaded successfully";
await DownloadExtractor();
await loadDependencyStatus();
toast.success(successMessage);
}
catch (error) {
toast.error("Failed to download xtractor");
console.error("Error downloading extractor:", error);
}
finally {
setDownloadingExtractor(false);
}
};
const handleDownloadFFmpeg = async () => {
setDownloadingFFmpeg(true);
try {
const successMessage = ffmpegInstalled
? ffmpegUpdateAvailable
? "FFmpeg updated successfully"
: "FFmpeg reinstalled successfully"
: "FFmpeg downloaded successfully";
await DownloadFFmpeg();
await loadDependencyStatus();
toast.success(successMessage);
}
catch (error) {
toast.error("Failed to download FFmpeg");
console.error("Error downloading FFmpeg:", error);
}
finally {
setDownloadingFFmpeg(false);
}
};
const handleDownloadExifTool = async () => {
setDownloadingExifTool(true);
try {
const successMessage = exiftoolInstalled
? exiftoolUpdateAvailable
? "ExifTool updated successfully"
: "ExifTool reinstalled successfully"
: "ExifTool downloaded successfully";
await DownloadExifTool();
await loadDependencyStatus();
toast.success(successMessage);
}
catch (error) {
toast.error("Failed to download ExifTool");
console.error("Error downloading ExifTool:", error);
}
finally {
setDownloadingExifTool(false);
}
};
return (<div className="space-y-4">
<div className="flex items-center justify-between">
<h1 className="text-2xl font-bold">Settings</h1>
<div className="flex gap-2">
<Button variant="outline" onClick={() => setShowResetConfirm(true)} className="gap-1.5">
<RotateCcw className="h-4 w-4"/>
Reset to Default
</Button>
<Button onClick={handleSave} className="gap-1.5">
<Save className="h-4 w-4"/>
Save Changes
</Button>
</div>
</div>
<div className="flex gap-2 border-b">
<Button variant={activeTab === "general" ? "default" : "ghost"} size="sm" onClick={() => setActiveTab("general")} className="rounded-b-none gap-2">
<MonitorCog className="h-4 w-4"/>
General
</Button>
<Button variant={activeTab === "downloads" ? "default" : "ghost"} size="sm" onClick={() => setActiveTab("downloads")} className="rounded-b-none gap-2">
<Download className="h-4 w-4"/>
Downloads
</Button>
<Button variant={activeTab === "naming" ? "default" : "ghost"} size="sm" onClick={() => setActiveTab("naming")} className="rounded-b-none gap-2">
<FileSignature className="h-4 w-4"/>
Naming
</Button>
<Button variant={activeTab === "dependencies" ? "default" : "ghost"} size="sm" onClick={() => setActiveTab("dependencies")} className="rounded-b-none gap-2">
<PackageSearch className="h-4 w-4"/>
Dependencies
</Button>
</div>
<div className="pt-4">
{activeTab === "general" && (<div className="grid grid-cols-1 gap-4 md:grid-cols-[minmax(0,1fr)_1px_minmax(0,1fr)] md:gap-6">
<div className="space-y-4">
<div className="grid grid-cols-[8rem_8rem] gap-4">
<div className="min-w-0 space-y-2">
<Label htmlFor="theme-mode">Mode</Label>
<Select value={tempSettings.themeMode} onValueChange={(value: "auto" | "light" | "dark") => setTempSettings((prev) => ({ ...prev, themeMode: value }))}>
<SelectTrigger id="theme-mode" className="w-full">
<SelectValue placeholder="Select theme mode"/>
</SelectTrigger>
<SelectContent>
<SelectItem value="auto">Auto</SelectItem>
<SelectItem value="light">Light</SelectItem>
<SelectItem value="dark">Dark</SelectItem>
</SelectContent>
</Select>
</div>
<div className="min-w-0 space-y-2">
<Label htmlFor="base-color">Base Color</Label>
<Select value={tempSettings.baseColor} onValueChange={(value) => handleBaseColorChange(value as BaseColorName)} onOpenChange={(open) => {
if (!open) {
restoreSelectedTheme();
}
}}>
<SelectTrigger id="base-color" className="w-full">
<SelectValue placeholder="Select a base color"/>
</SelectTrigger>
<SelectContent onMouseLeave={restoreSelectedTheme}>
{baseColors.map((baseColor) => (<SelectItem key={baseColor.name} value={baseColor.name} onMouseMove={() => previewBaseColor(baseColor.name)} onFocus={() => previewBaseColor(baseColor.name)}>
<span className="flex items-center gap-2">
<span className="h-3 w-3 rounded-full border border-border" style={{
backgroundColor: isDark
? baseColor.cssVars.dark["muted-foreground"]
: baseColor.cssVars.light["muted-foreground"],
}}/>
{baseColor.label}
</span>
</SelectItem>))}
</SelectContent>
</Select>
</div>
</div>
<div className="space-y-2">
<Label htmlFor="theme">Theme</Label>
<Select value={tempSettings.theme} onValueChange={(value) => handleThemeChange(value as SettingsType["theme"])} onOpenChange={(open) => {
if (!open) {
restoreSelectedTheme();
}
}}>
<SelectTrigger id="theme" className="w-32">
<SelectValue placeholder="Select a theme"/>
</SelectTrigger>
<SelectContent onMouseLeave={restoreSelectedTheme}>
{availableThemes.map((theme) => (<SelectItem key={theme.name} value={theme.name} onMouseMove={() => previewTheme(theme.name)} onFocus={() => previewTheme(theme.name)}>
<span className="flex items-center gap-2">
<span className="h-3 w-3 rounded-full border border-border" style={{
backgroundColor: isDark
? theme.cssVars.dark[theme.name === tempSettings.baseColor ? "muted-foreground" : "primary"]
: theme.cssVars.light[theme.name === tempSettings.baseColor ? "muted-foreground" : "primary"],
}}/>
{theme.label}
</span>
</SelectItem>))}
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label htmlFor="font">Font</Label>
<div className="flex flex-wrap items-center gap-2">
<Select value={tempSettings.fontFamily} onValueChange={(value: FontFamily) => setTempSettings((prev) => ({ ...prev, fontFamily: value }))}>
<SelectTrigger id="font" className="max-w-full min-w-40">
<SelectValue placeholder="Select a font"/>
</SelectTrigger>
<SelectContent>
{fontOptions.map((font) => (<SelectItem key={font.value} value={font.value}>
<span style={{ fontFamily: font.fontFamily }}>{font.label}</span>
</SelectItem>))}
</SelectContent>
</Select>
<Button type="button" variant="outline" onClick={() => setShowAddFontDialog(true)} className="shrink-0 gap-1.5">
<Plus className="h-4 w-4"/>
Add Font
</Button>
</div>
{tempSettings.customFonts.length > 0 && (<div className="space-y-2 rounded-lg border bg-muted/20 p-3">
<p className="text-xs font-medium text-muted-foreground">Custom Fonts</p>
<div className="space-y-2">
{tempSettings.customFonts.map((font) => (<div key={font.value} className="flex items-center justify-between gap-3 rounded-md border bg-background/70 px-3 py-2">
<div className="min-w-0">
<p className="truncate text-sm font-medium" style={{ fontFamily: font.fontFamily }}>
{font.label}
</p>
<p className="truncate text-xs text-muted-foreground">{font.url}</p>
</div>
<Button type="button" variant="ghost" size="icon" className="h-8 w-8 shrink-0 text-muted-foreground hover:text-destructive" onClick={() => void handleDeleteCustomFont(font.value as CustomFontFamily)}>
<Trash2 className="h-4 w-4"/>
</Button>
</div>))}
</div>
</div>)}
</div>
<div className="flex items-center gap-3 pt-2">
<Switch id="sfx-enabled" checked={tempSettings.sfxEnabled} onCheckedChange={(checked) => setTempSettings((prev) => ({ ...prev, sfxEnabled: checked }))}/>
<Label htmlFor="sfx-enabled" className="cursor-pointer text-sm">Sound Effects</Label>
</div>
<div className="flex items-center gap-3 pt-1">
<Switch id="show-update-notifications" checked={tempSettings.showUpdateNotifications} onCheckedChange={(checked) => setTempSettings((prev) => ({ ...prev, showUpdateNotifications: checked }))}/>
<Label htmlFor="show-update-notifications" className="cursor-pointer text-sm">Update Notifications</Label>
</div>
</div>
<div aria-hidden="true" className="hidden bg-border md:block"/>
<div className="space-y-6">
<div className="space-y-2">
<Label htmlFor="download-path">Download Path</Label>
<div className="flex gap-2">
<InputWithContext 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">
<FolderOpen className="h-4 w-4"/>
Browse
</Button>
</div>
</div>
<div className="space-y-4">
<Label>File Handling</Label>
<div className="flex items-center gap-3">
<Switch id="skip-existing-files" checked={tempSettings.skipExistingFiles} onCheckedChange={(checked) => setTempSettings((prev) => ({ ...prev, skipExistingFiles: checked }))}/>
<Label htmlFor="skip-existing-files" className="cursor-pointer font-normal">Skip Existing Files</Label>
</div>
<div className="flex items-center gap-3">
<Switch id="delete-incomplete-files" checked={tempSettings.deleteIncompleteFiles} onCheckedChange={(checked) => setTempSettings((prev) => ({ ...prev, deleteIncompleteFiles: checked }))}/>
<Label htmlFor="delete-incomplete-files" className="cursor-pointer font-normal">Delete Incomplete Files</Label>
</div>
</div>
<div className="space-y-3">
<Label className="flex items-center gap-2">
GIF Conversion
<Tooltip>
<TooltipTrigger asChild>
<CircleQuestionMark className="h-3.5 w-3.5 cursor-help text-muted-foreground"/>
</TooltipTrigger>
<TooltipContent side="top">
<p>Quality settings for converting Twitter's MP4 into actual GIF files.</p>
</TooltipContent>
</Tooltip>
</Label>
<div className="flex items-center gap-3">
<Switch id="auto-convert-gifs" checked={tempSettings.autoConvertGifs} onCheckedChange={(checked) => setTempSettings((prev) => ({ ...prev, autoConvertGifs: checked }))} disabled={!ffmpegInstalled}/>
<Label htmlFor="auto-convert-gifs" className={!ffmpegInstalled ? "text-muted-foreground" : "cursor-pointer"}>Auto Convert GIFs</Label>
</div>
<div className="flex items-center justify-between gap-4">
<Label htmlFor="gif-quality" className={!ffmpegInstalled || !tempSettings.autoConvertGifs ? "text-muted-foreground" : undefined}>GIF Quality</Label>
<div className="flex items-center gap-2">
<Select value={tempSettings.gifQuality} onValueChange={(value: GifQuality) => {
setTempSettings((prev) => ({
...prev,
gifQuality: value,
}));
}} disabled={!ffmpegInstalled || !tempSettings.autoConvertGifs}>
<SelectTrigger id="gif-quality" className="w-fit">
<SelectValue placeholder="Select quality"/>
</SelectTrigger>
<SelectContent>
<SelectItem value="fast">Fast</SelectItem>
<SelectItem value="better">Better</SelectItem>
</SelectContent>
</Select>
<Select value={tempSettings.gifResolution} onValueChange={(value: GifResolution) => setTempSettings((prev) => ({ ...prev, gifResolution: value }))} disabled={!ffmpegInstalled || !tempSettings.autoConvertGifs}>
<SelectTrigger id="gif-resolution" className="w-fit">
<SelectValue placeholder="Resolution"/>
</SelectTrigger>
<SelectContent>
<SelectItem value="original">Original</SelectItem>
<SelectItem value="high">High (800px)</SelectItem>
<SelectItem value="medium">Medium (600px)</SelectItem>
<SelectItem value="low">Low (400px)</SelectItem>
</SelectContent>
</Select>
</div>
</div>
</div>
</div>
</div>)}
{activeTab === "downloads" && (<div className="grid grid-cols-1 gap-4 md:grid-cols-[minmax(0,1fr)_1px_minmax(0,1fr)] md:gap-6">
<div className="space-y-4">
<div className="flex items-center gap-2">
<Label>Download Controls</Label>
<Tooltip>
<TooltipTrigger asChild>
<CircleQuestionMark className="h-3.5 w-3.5 cursor-help text-muted-foreground"/>
</TooltipTrigger>
<TooltipContent side="top" className="max-w-xs">
<p>The speed limit is shared by all concurrent downloads. Delay spaces out media requests and adds an optional random variation.</p>
</TooltipContent>
</Tooltip>
</div>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-1.5">
<Label htmlFor="concurrent-downloads" className="flex items-center gap-2 text-xs">
Concurrent Downloads
<Tooltip>
<TooltipTrigger asChild>
<CircleQuestionMark className="h-3.5 w-3.5 cursor-help text-muted-foreground"/>
</TooltipTrigger>
<TooltipContent side="top">
<p>How many media files can download at the same time.</p>
</TooltipContent>
</Tooltip>
</Label>
<Select value={String(tempSettings.concurrentDownloads || 10)} onValueChange={(value) => setTempSettings((prev) => ({ ...prev, concurrentDownloads: parseInt(value, 10) }))}>
<SelectTrigger id="concurrent-downloads" className="w-24">
<SelectValue placeholder="10"/>
</SelectTrigger>
<SelectContent>
{[1, 2, 3, 5, 8, 10, 15, 20, 25, 30, 40, 50].map((value) => (<SelectItem key={value} value={String(value)}>
{value}
</SelectItem>))}
</SelectContent>
</Select>
</div>
<div className="space-y-1.5">
<Label htmlFor="retry-attempts" className="flex items-center gap-2 text-xs">
Retry Attempts
<Tooltip>
<TooltipTrigger asChild>
<CircleQuestionMark className="h-3.5 w-3.5 cursor-help text-muted-foreground"/>
</TooltipTrigger>
<TooltipContent side="top">
<p>How many times to retry a failed download before giving up.</p>
</TooltipContent>
</Tooltip>
</Label>
<Select value={String(tempSettings.retryAttempts)} onValueChange={(value) => setTempSettings((prev) => ({ ...prev, retryAttempts: parseInt(value, 10) }))}>
<SelectTrigger id="retry-attempts" className="w-24">
<SelectValue placeholder="1"/>
</SelectTrigger>
<SelectContent>
{[1, 2, 3, 4, 5].map((value) => (<SelectItem key={value} value={String(value)}>
{value}
</SelectItem>))}
</SelectContent>
</Select>
</div>
</div>
<div className="grid grid-cols-1 gap-3 sm:grid-cols-3">
<div className="space-y-1.5">
<Label htmlFor="download-speed-limit" className="text-xs">Speed Limit</Label>
<div className="flex items-center gap-2">
<InputWithContext id="download-speed-limit" type="number" min="0" max="10485760" step="1" value={tempSettings.downloadSpeedLimitKBps} onChange={(e) => {
const value = Number(e.target.value);
setTempSettings((prev) => ({ ...prev, downloadSpeedLimitKBps: Number.isFinite(value) ? Math.min(10485760, Math.max(0, Math.round(value))) : 0 }));
}} className="w-24"/>
<span className="text-xs text-muted-foreground">KB/s</span>
</div>
</div>
<div className="space-y-1.5">
<Label htmlFor="download-delay" className="text-xs">Base Delay</Label>
<div className="flex items-center gap-2">
<InputWithContext id="download-delay" type="number" min="0" max="3600" step="0.1" value={tempSettings.downloadDelaySeconds} onChange={(e) => {
const value = Number(e.target.value);
setTempSettings((prev) => ({ ...prev, downloadDelaySeconds: Number.isFinite(value) ? Math.min(3600, Math.max(0, value)) : 0 }));
}} className="w-24"/>
<span className="text-xs text-muted-foreground">sec</span>
</div>
</div>
<div className="space-y-1.5">
<Label htmlFor="download-delay-jitter" className="text-xs">Random Extra</Label>
<div className="flex items-center gap-2">
<InputWithContext id="download-delay-jitter" type="number" min="0" max="3600" step="0.1" value={tempSettings.downloadDelayJitterSeconds} onChange={(e) => {
const value = Number(e.target.value);
setTempSettings((prev) => ({ ...prev, downloadDelayJitterSeconds: Number.isFinite(value) ? Math.min(3600, Math.max(0, value)) : 0 }));
}} className="w-24"/>
<span className="text-xs text-muted-foreground">sec</span>
</div>
</div>
</div>
</div>
<div aria-hidden="true" className="hidden bg-border md:block"/>
<div className="space-y-4">
<div className="space-y-2">
<Label htmlFor="proxy" className="flex items-center gap-2">
Proxy
<Tooltip>
<TooltipTrigger asChild>
<CircleQuestionMark className="h-3.5 w-3.5 cursor-help text-muted-foreground"/>
</TooltipTrigger>
<TooltipContent side="top">
<p>Supports one proxy or multiple proxies separated by commas. Requests will rotate through them.</p>
</TooltipContent>
</Tooltip>
</Label>
<InputWithContext id="proxy" value={tempSettings.proxy || ""} onChange={(e) => setTempSettings((prev) => ({ ...prev, proxy: e.target.value }))} placeholder="http://proxy1:port, socks5://proxy2:port (optional)" className="max-w-md"/>
</div>
<div className="space-y-2">
<Label>Fetch Delay</Label>
<div className="flex flex-wrap gap-4">
{([
["fetchDelaySeconds", "Base Delay"],
["fetchDelayJitterSeconds", "Random Extra"],
] as const).map(([key, label]) => (
<div key={key} className="space-y-1.5">
<Label htmlFor={key} className="text-xs">{label}</Label>
<div className="flex items-center gap-2">
<InputWithContext id={key} type="number" min="0" max="3600" step="0.1" value={tempSettings[key]} onChange={(e) => {
const value = Number(e.target.value);
setTempSettings((prev) => ({ ...prev, [key]: Number.isFinite(value) ? Math.min(3600, Math.max(0, value)) : 0 }));
}} className="w-24"/>
<span className="text-xs text-muted-foreground">sec</span>
</div>
</div>
))}
</div>
<p className="text-xs text-muted-foreground">Spaces out fetch batch starts, including account switches and retries. Random Extra adds between 0 and the chosen number of seconds. Set both to 0 to disable.</p>
<p className="text-xs text-muted-foreground">Suggested starting point: 5 sec base + 5 sec random extra. No delay guarantees avoidance of rate limits. Waiting counts toward Fetch Timeout; increase it for longer delays.</p>
<p className="text-xs text-muted-foreground">Applies between extractor runs, including date-range fetches, rather than individual requests inside the extractor.</p>
</div>
<div className="space-y-2">
<Label htmlFor="fetch-timeout" className="flex items-center gap-2">
Fetch Timeout
<Tooltip>
<TooltipTrigger asChild>
<CircleQuestionMark className="h-3.5 w-3.5 cursor-help text-muted-foreground"/>
</TooltipTrigger>
<TooltipContent side="top">
<p>Timeout in seconds. Fetch stops automatically when reached</p>
</TooltipContent>
</Tooltip>
</Label>
<InputWithContext id="fetch-timeout" type="number" value={tempSettings.fetchTimeout || 60} onChange={(e) => {
const inputValue = e.target.value;
if (inputValue === "") {
setTempSettings((prev) => ({ ...prev, fetchTimeout: 60 }));
return;
}
const value = parseInt(inputValue, 10);
if (!isNaN(value)) {
setTempSettings((prev) => ({ ...prev, fetchTimeout: value }));
}
}} onBlur={(e) => {
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-24"/>
</div>
</div>
</div>)}
{activeTab === "naming" && (<div className="grid grid-cols-1 gap-6 md:grid-cols-2 md:gap-8 items-start">
<div className="md:pr-8 md:border-r border-border">
<FormatEditor title="Folder" value={tempSettings.folderTemplate} defaultValue={DEFAULT_FOLDER_TEMPLATE} tokens={FOLDER_TEMPLATE_VARIABLES} placeholder={DEFAULT_FOLDER_TEMPLATE} render={(t) => renderFolderTemplate(t, SAMPLE_FOLDER_DATA)} onChange={(next) => setTempSettings((prev) => ({ ...prev, folderTemplate: next }))}/>
</div>
<div>
<FormatEditor title="Filename" value={tempSettings.filenameTemplate} defaultValue={DEFAULT_FILENAME_TEMPLATE} tokens={FILENAME_TEMPLATE_VARIABLES} placeholder={DEFAULT_FILENAME_TEMPLATE} suffix=".jpg" render={(t) => renderFilenameTemplate(t, SAMPLE_FILENAME_DATA)} onChange={(next) => setTempSettings((prev) => ({ ...prev, filenameTemplate: next }))}/>
</div>
</div>)}
{activeTab === "dependencies" && (<div className="grid grid-cols-1 gap-4 md:grid-cols-2">
<div className="space-y-4">
<div className="space-y-2">
<Label className="flex flex-wrap items-center gap-2">
<span>Core Xtractor</span>
{extractorVersionText && (<span className={extractorUpdateAvailable
? "text-xs font-normal text-amber-600 dark:text-amber-400"
: "text-xs font-normal text-muted-foreground"}>
{extractorVersionText}
</span>)}
<Tooltip>
<TooltipTrigger asChild>
<CircleQuestionMark className="h-3.5 w-3.5 cursor-help text-muted-foreground"/>
</TooltipTrigger>
<TooltipContent side="top">
<p>Required to fetch media from Twitter/X. Downloaded from the xtractor-binaries GitHub releases.</p>
</TooltipContent>
</Tooltip>
</Label>
<div className="flex min-h-9 items-center gap-3">
<Button variant="outline" size="sm" className="h-9" onClick={handleDownloadExtractor} disabled={downloadingExtractor}>
{downloadingExtractor ? (<>
<Spinner />
Downloading...
</>) : (<>
<Download className="h-4 w-4"/>
{extractorInstalled ? extractorUpdateAvailable ? "Update Xtractor" : "Reinstall Xtractor" : "Download Xtractor"}
</>)}
</Button>
{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>)}
</div>
</div>
<div className="space-y-2">
<Label className="flex flex-wrap items-center gap-2">
<span>GIF Conversion</span>
{ffmpegVersionText && (<span className={ffmpegUpdateAvailable
? "text-xs font-normal text-amber-600 dark:text-amber-400"
: "text-xs font-normal text-muted-foreground"}>
{ffmpegVersionText}
</span>)}
<Tooltip>
<TooltipTrigger asChild>
<CircleQuestionMark className="h-3.5 w-3.5 cursor-help text-muted-foreground"/>
</TooltipTrigger>
<TooltipContent side="top">
<p>FFmpeg is required to convert Twitter's MP4 to actual GIF format</p>
</TooltipContent>
</Tooltip>
</Label>
<div className="flex h-9 items-center">
<Button variant="outline" size="sm" className="h-9" onClick={handleDownloadFFmpeg} disabled={downloadingFFmpeg}>
{downloadingFFmpeg ? (<>
<Spinner />
Downloading...
</>) : (<>
<Download className="h-4 w-4"/>
{ffmpegInstalled ? ffmpegUpdateAvailable ? "Update FFmpeg" : "Reinstall FFmpeg" : "Download FFmpeg"}
</>)}
</Button>
{ffmpegInstalled && (<div className="ml-3 flex items-center gap-2 text-sm text-green-600 dark:text-green-400">
<Check className="h-4 w-4"/>
Installed
</div>)}
</div>
</div>
<div className="space-y-2">
<Label className="flex flex-wrap items-center gap-2">
<span>Metadata Embedding</span>
{exiftoolVersionText && (<span className={exiftoolUpdateAvailable
? "text-xs font-normal text-amber-600 dark:text-amber-400"
: "text-xs font-normal text-muted-foreground"}>
{exiftoolVersionText}
</span>)}
<Tooltip>
<TooltipTrigger asChild>
<CircleQuestionMark className="h-3.5 w-3.5 cursor-help text-muted-foreground"/>
</TooltipTrigger>
<TooltipContent side="top">
<p>ExifTool is required to embed tweet URL and original filename into media file metadata</p>
</TooltipContent>
</Tooltip>
</Label>
<div className="flex h-9 items-center">
<Button variant="outline" size="sm" className="h-9" onClick={handleDownloadExifTool} disabled={downloadingExifTool}>
{downloadingExifTool ? (<>
<Spinner />
Downloading...
</>) : (<>
<Download className="h-4 w-4"/>
{exiftoolInstalled ? exiftoolUpdateAvailable ? "Update ExifTool" : "Reinstall ExifTool" : "Download ExifTool"}
</>)}
</Button>
{exiftoolInstalled && (<div className="ml-3 flex items-center gap-2 text-sm text-green-600 dark:text-green-400">
<Check className="h-4 w-4"/>
Installed
</div>)}
</div>
</div>
</div>
<div />
</div>)}
</div>
<Dialog open={showAddFontDialog} onOpenChange={(open) => open ? setShowAddFontDialog(true) : closeAddFontDialog()}>
<DialogContent className="sm:max-w-115 [&>button]:hidden">
<DialogHeader>
<div className="flex items-center justify-between gap-3">
<DialogTitle>Add Font</DialogTitle>
<a href="https://fonts.google.com" target="_blank" rel="noreferrer" className="inline-flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground hover:underline">
Open Google Fonts
<ExternalLink className="h-3 w-3"/>
</a>
</div>
<DialogDescription />
</DialogHeader>
<div className="space-y-4">
<div className="space-y-2">
<Label htmlFor="google-font-url">Google Font URL</Label>
<Input id="google-font-url" value={addFontUrl} onChange={(event) => setAddFontUrl(event.target.value)} onKeyDown={(event) => {
if (event.key === "Enter" && parsedAddFont) {
void handleAddFont();
}
}} placeholder="https://fonts.google.com/specimen/Ubuntu" autoFocus/>
{addFontUrl.trim() && !parsedAddFont && (<p className="text-xs text-destructive">
Enter a valid Google Fonts URL.
</p>)}
</div>
<div className="rounded-md border bg-muted/20 p-4">
<p className="mb-2 text-xs font-medium text-muted-foreground">Preview</p>
<p className="text-2xl font-semibold leading-tight" style={{ fontFamily: parsedAddFont?.fontFamily }}>
Aa The quick brown fox
</p>
<p className="mt-2 text-sm text-muted-foreground" style={{ fontFamily: parsedAddFont?.fontFamily }}>
Twitter/X Media Batch Downloader
</p>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={closeAddFontDialog}>
Cancel
</Button>
<Button onClick={() => void handleAddFont()} disabled={!parsedAddFont}>
Add
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
<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>);
}
+139
View File
@@ -0,0 +1,139 @@
import { useState } from "react";
import { HomeIcon } from "@/components/ui/home";
import { SettingsIcon } from "@/components/ui/settings";
import { ArchiveIcon } from "@/components/ui/archive";
import { TerminalIcon } from "@/components/ui/terminal";
import { BugReportIcon } from "@/components/ui/bug-report-icon";
import { CoffeeIcon } from "@/components/ui/coffee";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Checkbox } from "@/components/ui/checkbox";
import { Tooltip, TooltipContent, TooltipTrigger, } from "@/components/ui/tooltip";
import { Button } from "@/components/ui/button";
import { openExternal } from "@/lib/utils";
export type PageType = "main" | "settings" | "debug" | "database" | "support";
interface SidebarProps {
currentPage: PageType;
onPageChange: (page: PageType) => void;
}
export function Sidebar({ currentPage, onPageChange }: SidebarProps) {
const [isIssuesDialogOpen, setIsIssuesDialogOpen] = useState(false);
const [hasIssueAgreement, setHasIssueAgreement] = useState(false);
const handleIssuesDialogChange = (open: boolean) => {
setIsIssuesDialogOpen(open);
if (!open) {
setHasIssueAgreement(false);
}
};
const handleOpenIssues = () => {
openExternal("https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/issues");
handleIssuesDialogChange(false);
};
return (<div className="fixed left-0 top-0 h-full w-14 bg-card border-r border-border flex flex-col items-center py-14 z-30">
<div className="flex flex-col gap-2 flex-1">
<Tooltip delayDuration={0}>
<TooltipTrigger asChild>
<Button variant={currentPage === "main" ? "secondary" : "ghost"} size="icon" className="h-10 w-10" onClick={() => onPageChange("main")}>
<HomeIcon size={20}/>
</Button>
</TooltipTrigger>
<TooltipContent side="right">
<p>Home</p>
</TooltipContent>
</Tooltip>
<Tooltip delayDuration={0}>
<TooltipTrigger asChild>
<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} loop={true}/>
</Button>
</TooltipTrigger>
<TooltipContent side="right">
<p>Debug Logs</p>
</TooltipContent>
</Tooltip>
</div>
<div className="mt-auto flex flex-col gap-2">
<Dialog open={isIssuesDialogOpen} onOpenChange={handleIssuesDialogChange}>
<Tooltip delayDuration={0}>
<TooltipTrigger asChild>
<Button variant="ghost" size="icon" className="h-10 w-10 hover:bg-primary/10 hover:text-primary" onClick={() => setIsIssuesDialogOpen(true)}>
<BugReportIcon size={20} loop={true}/>
</Button>
</TooltipTrigger>
<TooltipContent side="right">
<p>Report Bugs or Request Features</p>
</TooltipContent>
</Tooltip>
<DialogContent className="max-w-xl">
<DialogHeader>
<DialogTitle>Before Opening GitHub Issues</DialogTitle>
<DialogDescription />
</DialogHeader>
<div className="space-y-4 text-sm">
<div className="rounded-lg border border-amber-500/40 bg-amber-500/10 p-4">
<p className="font-semibold text-amber-900 dark:text-amber-200">Important</p>
<p className="mt-1 text-amber-950/90 dark:text-amber-100/90">
Search existing issues first and use the issue template when opening a new bug report or feature request.
</p>
</div>
<label className="flex cursor-pointer items-center gap-3 rounded-lg border p-4">
<Checkbox className="shrink-0" checked={hasIssueAgreement} onCheckedChange={(checked) => setHasIssueAgreement(checked === true)}/>
<span className="leading-5 text-foreground/90">
I understand that I should use the issue template and avoid duplicate issues.
</span>
</label>
</div>
<DialogFooter className="sm:justify-between gap-2">
<Button variant="outline" onClick={() => handleIssuesDialogChange(false)}>
Cancel
</Button>
<Button disabled={!hasIssueAgreement} onClick={handleOpenIssues}>
Open Issues
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
<Tooltip delayDuration={0}>
<TooltipTrigger asChild>
<Button variant={currentPage === "support" ? "secondary" : "ghost"} size="icon" className="h-10 w-10" onClick={() => onPageChange("support")}>
<CoffeeIcon size={20} loop={true}/>
</Button>
</TooltipTrigger>
<TooltipContent side="right">
<p>Support Me</p>
</TooltipContent>
</Tooltip>
</div>
</div>);
}
+98
View File
@@ -0,0 +1,98 @@
import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { CircleCheck, Copy } from "lucide-react";
import UsdtTronQr from "@/assets/usdt.jpg";
import UsdtEvmQr from "@/assets/usdt_evm.jpg";
import UsdcEvmQr from "@/assets/usdc.jpg";
type CryptoCoin = "usdt" | "usdc";
type CryptoNetwork = "ethereum" | "bsc" | "polygon" | "base" | "tron";
const EVM_ADDRESS = "0xB563a7F39770C151e2FacE26926081a00c5EF349";
const TRON_ADDRESS = "THnzAAwZgp2Sq5CAXLP2njQDhTvgZG9EWs";
const EVM_NETWORKS: Array<{
value: CryptoNetwork;
label: string;
shortLabel: string;
}> = [
{ value: "bsc", label: "BNB Smart Chain (BEP20)", shortLabel: "BEP20" },
{ value: "polygon", label: "Polygon", shortLabel: "Polygon" },
{ value: "ethereum", label: "Ethereum (ERC20)", shortLabel: "ERC20" },
{ value: "base", label: "Base", shortLabel: "Base" },
];
const USDT_NETWORKS: Array<{
value: CryptoNetwork;
label: string;
shortLabel: string;
}> = [
{ value: "ethereum", label: "Ethereum (ERC20)", shortLabel: "ERC20" },
{ value: "bsc", label: "BNB Smart Chain (BEP20)", shortLabel: "BEP20" },
{ value: "tron", label: "Tron (TRC20)", shortLabel: "TRC20" },
{ value: "polygon", label: "Polygon", shortLabel: "Polygon" },
];
export function SupportPage() {
const [selectedCoin, setSelectedCoin] = useState<CryptoCoin>("usdt");
const [selectedNetwork, setSelectedNetwork] = useState<CryptoNetwork>("tron");
const [copiedAddress, setCopiedAddress] = useState(false);
const networkOptions = selectedCoin === "usdt" ? USDT_NETWORKS : EVM_NETWORKS;
const activeNetwork = networkOptions.find((network) => network.value === selectedNetwork) || EVM_NETWORKS[0];
const isTron = selectedNetwork === "tron";
const cryptoAddress = isTron ? TRON_ADDRESS : EVM_ADDRESS;
const cryptoQr = isTron ? UsdtTronQr : selectedCoin === "usdt" ? UsdtEvmQr : UsdcEvmQr;
const handleCoinChange = (coin: CryptoCoin) => {
setSelectedCoin(coin);
setCopiedAddress(false);
const nextNetworks = coin === "usdt" ? USDT_NETWORKS : EVM_NETWORKS;
if (!nextNetworks.some((network) => network.value === selectedNetwork)) {
setSelectedNetwork("ethereum");
}
};
return (<div className="mx-auto flex min-h-[70vh] w-full max-w-lg flex-col items-center justify-center space-y-4 p-6">
<div className="flex w-full flex-col items-center space-y-3">
<div className="flex h-40 items-center justify-center">
<div className="rounded-xl border bg-white p-2 shadow-sm">
<img src={cryptoQr} className="h-32 w-32 object-contain" alt={`${selectedCoin.toUpperCase()} ${activeNetwork.label} QR code`}/>
</div>
</div>
<h4 className="font-semibold text-foreground">Support via Crypto</h4>
<p className="px-4 text-center text-sm text-muted-foreground">
Scan the QR code or copy the address to support the project.
</p>
</div>
<div className="w-full space-y-2">
<div className="grid grid-cols-2 gap-2">
<Select value={selectedCoin} onValueChange={(value: CryptoCoin) => handleCoinChange(value)}>
<SelectTrigger size="sm" className="w-full" aria-label="Coin">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="usdt">USDT</SelectItem>
<SelectItem value="usdc">USDC</SelectItem>
</SelectContent>
</Select>
<Select value={selectedNetwork} onValueChange={(value: CryptoNetwork) => {
setSelectedNetwork(value);
setCopiedAddress(false);
}}>
<SelectTrigger size="sm" className="w-full" aria-label="Network">
<SelectValue>{activeNetwork.shortLabel}</SelectValue>
</SelectTrigger>
<SelectContent>
{networkOptions.map((network) => (<SelectItem key={network.value} value={network.value}>{network.label}</SelectItem>))}
</SelectContent>
</Select>
</div>
<div className="flex h-10 w-full items-center justify-between gap-2 rounded-lg border bg-muted/50 py-1.5 pr-1.5 pl-3">
<code className="min-w-0 flex-1 truncate text-xs font-mono text-muted-foreground" title={cryptoAddress}>
{cryptoAddress}
</code>
<Button variant="ghost" size="icon" className="h-7 w-7 shrink-0 hover:bg-background" aria-label="Copy wallet address" onClick={() => {
navigator.clipboard.writeText(cryptoAddress);
setCopiedAddress(true);
setTimeout(() => setCopiedAddress(false), 500);
}}>
{copiedAddress ? <CircleCheck className="h-3.5 w-3.5 text-green-500"/> : <Copy className="h-3.5 w-3.5"/>}
</Button>
</div>
</div>
</div>);
}
+63
View File
@@ -0,0 +1,63 @@
import { X, Minus, Maximize, Sparkles, Puzzle, FileCode2, Globe, ArrowLeft, ArrowRight, RotateCw } from "lucide-react";
import { WindowMinimise, WindowToggleMaximise, Quit } from "../../wailsjs/runtime/runtime";
import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem } from "@/components/ui/dropdown-menu";
import { openExternal } from "@/lib/utils";
const INFO_LINKS = [
{ label: "Chrome Extension", icon: Puzzle, url: "https://chromewebstore.google.com/detail/cboceolmgkoobpfjiojkigmihijfgmdo" },
{ label: "Userscript", icon: FileCode2, url: "https://greasyfork.org/en/scripts/523157" },
{ label: "Website", icon: Globe, url: "https://twitterdl.app" },
];
interface TitleBarProps {
canGoBack?: boolean;
canGoForward?: boolean;
navigationDisabled?: boolean;
onBack?: () => void;
onForward?: () => void;
}
export function TitleBar({ canGoBack = false, canGoForward = false, navigationDisabled = false, onBack, onForward }: TitleBarProps) {
const handleMinimize = () => {
WindowMinimise();
};
const handleMaximize = () => {
WindowToggleMaximise();
};
const handleClose = () => {
Quit();
};
return (<>
<div className="fixed top-0 left-14 right-0 h-10 z-40 bg-background/80 backdrop-blur-sm" style={{ "--wails-draggable": "drag" } as React.CSSProperties} onDoubleClick={handleMaximize}/>
<div className="fixed top-1.5 left-16 z-50 flex h-7 items-center gap-0.5" style={{ "--wails-draggable": "no-drag" } as React.CSSProperties}>
<button type="button" onClick={onBack} disabled={!canGoBack || navigationDisabled} className="flex size-7 items-center justify-center rounded transition-colors hover:bg-muted disabled:cursor-default disabled:opacity-35 disabled:hover:bg-transparent" aria-label="Go back"><ArrowLeft className="h-3.5 w-3.5"/></button>
<button type="button" onClick={onForward} disabled={!canGoForward || navigationDisabled} className="flex size-7 items-center justify-center rounded transition-colors hover:bg-muted disabled:cursor-default disabled:opacity-35 disabled:hover:bg-transparent" aria-label="Go forward"><ArrowRight className="h-3.5 w-3.5"/></button>
<button type="button" onClick={() => window.location.reload()} className="flex size-7 items-center justify-center rounded transition-colors hover:bg-muted" aria-label="Reload"><RotateCw className="h-3.5 w-3.5"/></button>
</div>
<div className="fixed top-1.5 right-2 z-50 flex h-7 gap-0.5" style={{ "--wails-draggable": "no-drag" } as React.CSSProperties}>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button className="size-7 flex items-center justify-center hover:bg-muted transition-colors rounded" aria-label="Info">
<Sparkles className="h-3.5 w-3.5 text-primary"/>
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
{INFO_LINKS.map(({ label, icon: Icon, url }) => (<DropdownMenuItem key={label} onClick={() => openExternal(url)} className="gap-2 cursor-pointer">
<Icon className="w-4 h-4 text-muted-foreground"/>
{label}
</DropdownMenuItem>))}
</DropdownMenuContent>
</DropdownMenu>
<button onClick={handleMinimize} className="size-7 flex items-center justify-center hover:bg-muted transition-colors rounded" aria-label="Minimize">
<Minus className="w-3.5 h-3.5"/>
</button>
<button onClick={handleMaximize} className="size-7 flex items-center justify-center hover:bg-muted transition-colors rounded" aria-label="Maximize">
<Maximize className="w-3.5 h-3.5"/>
</button>
<button onClick={handleClose} className="size-7 flex items-center justify-center hover:bg-destructive hover:text-white transition-colors rounded" aria-label="Close">
<X className="w-3.5 h-3.5"/>
</button>
</div>
</>);
}
+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 };
+24
View File
@@ -0,0 +1,24 @@
import * as React from "react";
import { Slot } from "@radix-ui/react-slot";
import { cva, type VariantProps } from "class-variance-authority";
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", {
variants: {
variant: {
default: "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",
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: {
variant: "default",
},
});
function Badge({ className, variant, 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 };
+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 };
@@ -0,0 +1,116 @@
"use client";
import type { Transition, Variants } from "motion/react";
import { AnimatePresence, motion } from "motion/react";
import { useEffect, useState, type HTMLAttributes } from "react";
import { cn } from "@/lib/utils";
type ReportIconMode = "bug" | "bulb";
interface BugReportIconProps extends HTMLAttributes<HTMLDivElement> {
size?: number;
loop?: boolean;
}
const LOOP_INTERVAL_MS = 2200;
const GROUP_VARIANTS: Variants = {
hidden: {
opacity: 0,
},
visible: {
opacity: 1,
transition: {
duration: 0.2,
ease: [0, 0, 0.2, 1],
},
},
exit: {
opacity: 0,
transition: {
duration: 0.18,
ease: [0.4, 0, 1, 1],
},
},
};
const DRAW_VARIANTS: Variants = {
hidden: {
pathLength: 0,
opacity: 0,
},
visible: {
pathLength: 1,
opacity: 1,
},
exit: {
pathLength: 1,
opacity: 0,
},
};
function createDrawTransition(delay = 0, duration = 0.36): Transition {
return {
duration,
delay,
ease: [0.4, 0, 0.2, 1],
opacity: { delay },
};
}
function BugPaths() {
return (<>
<motion.path d="m8 2 1.88 1.88" transition={createDrawTransition(0)} variants={DRAW_VARIANTS}/>
<motion.path d="M14.12 3.88 16 2" transition={createDrawTransition(0.04)} variants={DRAW_VARIANTS}/>
<motion.path d="M9 7.13V6a3 3 0 1 1 6 0v1.13" transition={createDrawTransition(0.08)} variants={DRAW_VARIANTS}/>
<motion.path d="M6.53 9A4 4 0 0 1 3 5" transition={createDrawTransition(0.14)} variants={DRAW_VARIANTS}/>
<motion.path d="M17.47 9A4 4 0 0 0 21 5" transition={createDrawTransition(0.18)} variants={DRAW_VARIANTS}/>
<motion.path d="M12 20v-9" transition={createDrawTransition(0.24)} variants={DRAW_VARIANTS}/>
<motion.path d="M14 7a4 4 0 0 1 4 4v3a6 6 0 0 1-12 0v-3a4 4 0 0 1 4-4z" transition={createDrawTransition(0.3, 0.42)} variants={DRAW_VARIANTS}/>
<motion.path d="M22 13h-4" transition={createDrawTransition(0.42)} variants={DRAW_VARIANTS}/>
<motion.path d="M6 13H2" transition={createDrawTransition(0.46)} variants={DRAW_VARIANTS}/>
<motion.path d="M21 21a4 4 0 0 0-3.81-4" transition={createDrawTransition(0.52)} variants={DRAW_VARIANTS}/>
<motion.path d="M3 21a4 4 0 0 1 3.81-4" transition={createDrawTransition(0.56)} variants={DRAW_VARIANTS}/>
</>);
}
function BulbPaths() {
return (<>
<motion.path d="M15 14c.2-1 .7-1.7 1.5-2.5 1-.9 1.5-2.2 1.5-3.5A6 6 0 0 0 6 8c0 1 .2 2.2 1.5 3.5.7.7 1.3 1.5 1.5 2.5" transition={createDrawTransition(0, 0.46)} variants={DRAW_VARIANTS}/>
<motion.path d="M9 18h6" transition={createDrawTransition(0.16)} variants={DRAW_VARIANTS}/>
<motion.path d="M10 22h4" transition={createDrawTransition(0.24)} variants={DRAW_VARIANTS}/>
</>);
}
function ReportIconGroup({ mode }: {
mode: ReportIconMode;
}) {
return (<motion.g animate="visible" exit="exit" initial="hidden" variants={GROUP_VARIANTS}>
{mode === "bug" ? <BugPaths /> : <BulbPaths />}
</motion.g>);
}
function StaticBugIcon() {
return (<g>
<path d="m8 2 1.88 1.88"/>
<path d="M14.12 3.88 16 2"/>
<path d="M9 7.13V6a3 3 0 1 1 6 0v1.13"/>
<path d="M6.53 9A4 4 0 0 1 3 5"/>
<path d="M17.47 9A4 4 0 0 0 21 5"/>
<path d="M12 20v-9"/>
<path d="M14 7a4 4 0 0 1 4 4v3a6 6 0 0 1-12 0v-3a4 4 0 0 1 4-4z"/>
<path d="M22 13h-4"/>
<path d="M6 13H2"/>
<path d="M21 21a4 4 0 0 0-3.81-4"/>
<path d="M3 21a4 4 0 0 1 3.81-4"/>
</g>);
}
function BugReportIcon({ className, size = 28, loop = false, ...props }: BugReportIconProps) {
const [mode, setMode] = useState<ReportIconMode>("bug");
useEffect(() => {
if (!loop) {
return;
}
const intervalId = window.setInterval(() => {
setMode((currentMode) => currentMode === "bug" ? "bulb" : "bug");
}, LOOP_INTERVAL_MS);
return () => window.clearInterval(intervalId);
}, [loop]);
return (<div className={cn("flex items-center justify-center", className)} {...props}>
<svg fill="none" height={size} stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" viewBox="0 0 24 24" width={size} xmlns="http://www.w3.org/2000/svg">
{loop ? (<AnimatePresence>
<ReportIconGroup key={mode} mode={mode}/>
</AnimatePresence>) : (<StaticBugIcon />)}
</svg>
</div>);
}
export { BugReportIcon };
+35
View File
@@ -0,0 +1,35 @@
import * as React from "react";
import { Slot } from "@radix-ui/react-slot";
import { cva, type VariantProps } from "class-variance-authority";
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", {
variants: {
variant: {
default: "bg-primary text-primary-foreground hover:bg-primary/90",
destructive: "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",
secondary: "bg-secondary text-secondary-foreground hover:bg-secondary/80",
ghost: "hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-9 px-4 py-2 has-[>svg]:px-3",
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",
icon: "size-9",
"icon-sm": "size-8",
"icon-lg": "size-10",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
});
function Button({ className, variant, 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 };
+13
View File
@@ -0,0 +1,13 @@
"use client";
import * as React from "react";
import * as CheckboxPrimitive from "@radix-ui/react-checkbox";
import { CheckIcon } from "lucide-react";
import { cn } from "@/lib/utils";
function Checkbox({ 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.Root>);
}
export { Checkbox };
+67
View File
@@ -0,0 +1,67 @@
'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;
loop?: boolean;
}
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, loop = false, ...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={loop ? 'animate' : controls} variants={PATH_VARIANTS} custom={0.2}/>
<motion.path d="M14 2v2" animate={loop ? 'animate' : controls} variants={PATH_VARIANTS} custom={0.4}/>
<motion.path d="M6 2v2" animate={loop ? 'animate' : controls} variants={PATH_VARIANTS} custom={0}/>
<path d="M16 8a1 1 0 0 1 1 1v8a4 4 0 0 1-4 4H7a4 4 0 0 1-4-4V9a1 1 0 0 1 1-1h14a4 4 0 1 1 0 8h-1"/>
</svg>
</div>);
});
CoffeeIcon.displayName = 'CoffeeIcon';
export { CoffeeIcon };
@@ -0,0 +1,77 @@
"use client";
import * as React from "react";
import * as ContextMenuPrimitive from "@radix-ui/react-context-menu";
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react";
import { cn } from "@/lib/utils";
function ContextMenu({ ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Root>) {
return <ContextMenuPrimitive.Root data-slot="context-menu" {...props}/>;
}
function ContextMenuTrigger({ ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Trigger>) {
return (<ContextMenuPrimitive.Trigger data-slot="context-menu-trigger" {...props}/>);
}
function ContextMenuGroup({ ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Group>) {
return (<ContextMenuPrimitive.Group data-slot="context-menu-group" {...props}/>);
}
function ContextMenuPortal({ ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Portal>) {
return (<ContextMenuPrimitive.Portal data-slot="context-menu-portal" {...props}/>);
}
function ContextMenuSub({ ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Sub>) {
return <ContextMenuPrimitive.Sub data-slot="context-menu-sub" {...props}/>;
}
function ContextMenuRadioGroup({ ...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> & {
inset?: boolean;
}) {
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}>
{children}
<ChevronRightIcon className="ml-auto"/>
</ContextMenuPrimitive.SubTrigger>);
}
function ContextMenuSubContent({ 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>) {
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> & {
inset?: boolean;
variant?: "default" | "destructive";
}) {
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}/>);
}
function ContextMenuCheckboxItem({ 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">
<ContextMenuPrimitive.ItemIndicator>
<CheckIcon className="size-4"/>
</ContextMenuPrimitive.ItemIndicator>
</span>
{children}
</ContextMenuPrimitive.CheckboxItem>);
}
function ContextMenuRadioItem({ 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">
<ContextMenuPrimitive.ItemIndicator>
<CircleIcon className="size-2 fill-current"/>
</ContextMenuPrimitive.ItemIndicator>
</span>
{children}
</ContextMenuPrimitive.RadioItem>);
}
function ContextMenuLabel({ className, inset, ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Label> & {
inset?: boolean;
}) {
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}/>);
}
function ContextMenuSeparator({ 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">) {
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, };
+47
View File
@@ -0,0 +1,47 @@
"use client";
import * as React from "react";
import * as DialogPrimitive from "@radix-ui/react-dialog";
import { XIcon } from "lucide-react";
import { cn } from "@/lib/utils";
function Dialog({ ...props }: React.ComponentProps<typeof DialogPrimitive.Root>) {
return <DialogPrimitive.Root data-slot="dialog" {...props}/>;
}
function DialogTrigger({ ...props }: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props}/>;
}
function DialogPortal({ ...props }: React.ComponentProps<typeof DialogPrimitive.Portal>) {
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props}/>;
}
function DialogClose({ ...props }: React.ComponentProps<typeof DialogPrimitive.Close>) {
return <DialogPrimitive.Close data-slot="dialog-close" {...props}/>;
}
function DialogOverlay({ 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> & {
showCloseButton?: boolean;
}) {
return (<DialogPortal data-slot="dialog-portal">
<DialogOverlay />
<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}>
{children}
{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">
<XIcon />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>)}
</DialogPrimitive.Content>
</DialogPortal>);
}
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
return (<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">) {
return (<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>) {
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>) {
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, };
@@ -0,0 +1,59 @@
import * as React from "react";
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu";
import { CheckIcon, ChevronRightIcon } from "lucide-react";
import { cn } from "@/lib/utils";
const DropdownMenu = DropdownMenuPrimitive.Root;
const DropdownMenuTrigger = DropdownMenuPrimitive.Trigger;
const DropdownMenuGroup = DropdownMenuPrimitive.Group;
const DropdownMenuPortal = DropdownMenuPrimitive.Portal;
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}
<ChevronRightIcon className="ml-auto h-4 w-4"/>
</DropdownMenuPrimitive.SubTrigger>));
DropdownMenuSubTrigger.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}/>));
DropdownMenuSubContent.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>
<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}/>
</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">
<DropdownMenuPrimitive.ItemIndicator>
<CheckIcon className="h-4 w-4"/>
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.CheckboxItem>));
DropdownMenuCheckboxItem.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}>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<CheckIcon className="h-4 w-4"/>
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.RadioItem>));
DropdownMenuRadioItem.displayName = DropdownMenuPrimitive.RadioItem.displayName;
const DropdownMenuLabel = React.forwardRef<React.ElementRef<typeof DropdownMenuPrimitive.Label>, React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Label> & {
inset?: boolean;
}>(({ className, inset, ...props }, ref) => (<DropdownMenuPrimitive.Label ref={ref} className={cn("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 };
@@ -0,0 +1,172 @@
import * as React from "react";
import { Input } from "@/components/ui/input";
import { ContextMenu, ContextMenuContent, ContextMenuItem, ContextMenuSeparator, ContextMenuTrigger, } from "@/components/ui/context-menu";
import { Scissors, Copy, Clipboard, Type } from "lucide-react";
export interface InputWithContextProps extends React.InputHTMLAttributes<HTMLInputElement> {
onValueChange?: (value: string) => void;
}
const InputWithContext = React.forwardRef<HTMLInputElement, InputWithContextProps>(({ className, type, onValueChange, onChange, ...props }, ref) => {
const inputRef = React.useRef<HTMLInputElement>(null);
const [hasSelection, setHasSelection] = React.useState(false);
const [canPaste, setCanPaste] = React.useState(false);
const [uncontrolledHasValue, setUncontrolledHasValue] = React.useState(() => {
const defaultValue = props.defaultValue;
return defaultValue !== undefined && defaultValue !== null && String(defaultValue).length > 0;
});
const hasValue = props.value !== undefined && props.value !== null
? String(props.value).length > 0
: uncontrolledHasValue;
React.useImperativeHandle(ref, () => inputRef.current as HTMLInputElement);
const updateSelectionState = () => {
const input = inputRef.current;
if (!input)
return;
const start = input.selectionStart ?? 0;
const end = input.selectionEnd ?? 0;
setHasSelection(start !== end);
};
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);
input.value = newValue;
input.setSelectionRange(start, start);
if (onChange) {
const event = {
target: input,
currentTarget: input,
} as React.ChangeEvent<HTMLInputElement>;
onChange(event);
}
if (onValueChange) {
onValueChange(newValue);
}
if (props.value === undefined) {
setUncontrolledHasValue(newValue.length > 0);
}
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);
}
if (props.value === undefined) {
setUncontrolledHasValue(newValue.length > 0);
}
input.focus();
await checkClipboard();
}
catch (err) {
console.error("Failed to paste:", err);
}
};
const handleSelectAll = () => {
const input = inputRef.current;
if (!input)
return;
input.select();
input.focus();
updateSelectionState();
};
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
if (onChange) {
onChange(e);
}
if (onValueChange) {
onValueChange(e.target.value);
}
if (props.value === undefined) {
setUncontrolledHasValue(e.target.value.length > 0);
}
};
return (<ContextMenu onOpenChange={(open) => {
if (open) {
checkClipboard();
}
}}>
<ContextMenuTrigger asChild>
<Input ref={inputRef} type={type} className={className} onChange={handleInputChange} onSelect={updateSelectionState} onMouseUp={updateSelectionState} onKeyUp={updateSelectionState} {...props}/>
</ContextMenuTrigger>
<ContextMenuContent className="w-48">
<ContextMenuItem onSelect={handleCut} disabled={!hasSelection || props.disabled || props.readOnly}>
<Scissors className="mr-2 h-4 w-4"/>
Cut
<span className="ml-auto text-xs text-muted-foreground">Ctrl+X</span>
</ContextMenuItem>
<ContextMenuItem onSelect={handleCopy} disabled={!hasSelection || props.disabled}>
<Copy className="mr-2 h-4 w-4"/>
Copy
<span className="ml-auto text-xs text-muted-foreground">Ctrl+C</span>
</ContextMenuItem>
<ContextMenuItem onSelect={handlePaste} disabled={!canPaste || props.disabled || props.readOnly}>
<Clipboard className="mr-2 h-4 w-4"/>
Paste
<span className="ml-auto text-xs text-muted-foreground">Ctrl+V</span>
</ContextMenuItem>
<ContextMenuSeparator />
<ContextMenuItem onSelect={handleSelectAll} disabled={!hasValue || props.disabled}>
<Type className="mr-2 h-4 w-4"/>
Select All
<span className="ml-auto text-xs text-muted-foreground">Ctrl+A</span>
</ContextMenuItem>
</ContextMenuContent>
</ContextMenu>);
});
InputWithContext.displayName = "InputWithContext";
export { InputWithContext };
+6
View File
@@ -0,0 +1,6 @@
import * as React from "react";
import { cn } from "@/lib/utils";
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
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}/>);
}
export { Input };
+8
View File
@@ -0,0 +1,8 @@
"use client";
import * as React from "react";
import * as LabelPrimitive from "@radix-ui/react-label";
import { cn } from "@/lib/utils";
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 };
+10
View File
@@ -0,0 +1,10 @@
"use client";
import * as React from "react";
import * as ProgressPrimitive from "@radix-ui/react-progress";
import { cn } from "@/lib/utils";
function Progress({ 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 };
+63
View File
@@ -0,0 +1,63 @@
import * as React from "react";
import * as SelectPrimitive from "@radix-ui/react-select";
import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-react";
import { cn } from "@/lib/utils";
function Select({ ...props }: React.ComponentProps<typeof SelectPrimitive.Root>) {
return <SelectPrimitive.Root data-slot="select" {...props}/>;
}
function SelectGroup({ ...props }: React.ComponentProps<typeof SelectPrimitive.Group>) {
return <SelectPrimitive.Group data-slot="select-group" {...props}/>;
}
function SelectValue({ ...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> & {
size?: "sm" | "default";
}) {
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}>
{children}
<SelectPrimitive.Icon asChild>
<ChevronDownIcon className="size-4 opacity-50"/>
</SelectPrimitive.Icon>
</SelectPrimitive.Trigger>);
}
function SelectContent({ className, children, 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 />
<SelectPrimitive.Viewport className={cn("p-1", position === "popper" &&
"h-(--radix-select-trigger-height) w-full min-w-(--radix-select-trigger-width) scroll-my-1")}>
{children}
</SelectPrimitive.Viewport>
<SelectScrollDownButton />
</SelectPrimitive.Content>
</SelectPrimitive.Portal>);
}
function SelectLabel({ 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>) {
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">
<SelectPrimitive.ItemIndicator>
<CheckIcon className="size-4"/>
</SelectPrimitive.ItemIndicator>
</span>
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
</SelectPrimitive.Item>);
}
function SelectSeparator({ 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>) {
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>) {
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, };
+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 };
+27
View File
@@ -0,0 +1,27 @@
import { CircleCheckIcon, InfoIcon, Loader2Icon, OctagonXIcon, TriangleAlertIcon, } from "lucide-react";
import { useTheme } from "next-themes";
import { Toaster as Sonner, type ToasterProps } from "sonner";
const Toaster = ({ ...props }: ToasterProps) => {
const { theme = "system" } = useTheme();
return (<Sonner theme={theme as ToasterProps["theme"]} className="toaster group" icons={{
success: <CircleCheckIcon className="size-4"/>,
info: <InfoIcon className="size-4"/>,
warning: <TriangleAlertIcon className="size-4"/>,
error: <OctagonXIcon className="size-4"/>,
loading: <Loader2Icon className="size-4 animate-spin"/>,
}} toastOptions={{
classNames: {
success: "border-green-500 bg-green-50 text-green-900 dark:bg-green-950 dark:text-green-100 [&>svg]:text-green-500",
error: "border-red-500 bg-red-50 text-red-900 dark:bg-red-950 dark:text-red-100 [&>svg]:text-red-500",
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",
},
}} style={{
"--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 };
+6
View File
@@ -0,0 +1,6 @@
import { Loader2 } from "lucide-react";
import { cn } from "@/lib/utils";
function Spinner({ className, ...props }: React.ComponentProps<"svg">) {
return (<Loader2 role="status" aria-label="Loading" className={cn("size-4 animate-spin", className)} {...props}/>);
}
export { Spinner };
+10
View File
@@ -0,0 +1,10 @@
"use client";
import * as React from "react";
import * as SwitchPrimitive from "@radix-ui/react-switch";
import { cn } from "@/lib/utils";
function Switch({ 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 };
+60
View File
@@ -0,0 +1,60 @@
'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;
loop?: boolean;
}
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, loop = false, ...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={loop ? 'animate' : controls} initial="normal"/>
</svg>
</div>);
});
TerminalIcon.displayName = 'TerminalIcon';
export { TerminalIcon };
+24
View File
@@ -0,0 +1,24 @@
"use client";
import * as React from "react";
import * as TooltipPrimitive from "@radix-ui/react-tooltip";
import { cn } from "@/lib/utils";
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>) {
return (<TooltipProvider>
<TooltipPrimitive.Root data-slot="tooltip" {...props}/>
</TooltipProvider>);
}
function TooltipTrigger({ ...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>) {
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}
<TooltipPrimitive.Arrow className="bg-foreground fill-foreground z-50 size-2.5 translate-y-[calc(-50%-2px)] rotate-45 rounded-[2px]"/>
</TooltipPrimitive.Content>
</TooltipPrimitive.Portal>);
}
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider };
+294
View File
@@ -0,0 +1,294 @@
@import "tailwindcss";
@import "tw-animate-css";
@custom-variant dark (&:is(.dark *));
@theme inline {
--radius-sm: calc(var(--radius) - 4px);
--radius-md: calc(var(--radius) - 2px);
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) + 4px);
--color-background: var(--background);
--color-foreground: var(--foreground);
--color-card: var(--card);
--color-card-foreground: var(--card-foreground);
--color-popover: var(--popover);
--color-popover-foreground: var(--popover-foreground);
--color-primary: var(--primary);
--color-primary-foreground: var(--primary-foreground);
--color-secondary: var(--secondary);
--color-secondary-foreground: var(--secondary-foreground);
--color-muted: var(--muted);
--color-muted-foreground: var(--muted-foreground);
--color-accent: var(--accent);
--color-accent-foreground: var(--accent-foreground);
--color-destructive: var(--destructive);
--color-border: var(--border);
--color-input: var(--input);
--color-ring: var(--ring);
}
:root {
--radius: 0.625rem;
--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);
--primary: oklch(0.205 0 0);
--primary-foreground: oklch(0.985 0 0);
--secondary: oklch(0.97 0 0);
--secondary-foreground: oklch(0.205 0 0);
--muted: oklch(0.97 0 0);
--muted-foreground: oklch(0.556 0 0);
--accent: oklch(0.97 0 0);
--accent-foreground: oklch(0.205 0 0);
--destructive: oklch(0.577 0.245 27.325);
--border: oklch(0.922 0 0);
--input: oklch(0.922 0 0);
--ring: oklch(0.708 0 0);
}
.dark {
--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);
--primary: oklch(0.922 0 0);
--primary-foreground: oklch(0.205 0 0);
--secondary: oklch(0.269 0 0);
--secondary-foreground: oklch(0.985 0 0);
--muted: oklch(0.269 0 0);
--muted-foreground: oklch(0.708 0 0);
--accent: oklch(0.269 0 0);
--accent-foreground: oklch(0.985 0 0);
--destructive: oklch(0.704 0.191 22.216);
--border: oklch(1 0 0 / 10%);
--input: oklch(1 0 0 / 15%);
--ring: oklch(0.556 0 0);
}
@layer base {
html,
body,
#root {
height: 100%;
overflow: hidden;
}
* {
@apply border-border outline-ring/50;
}
body {
@apply bg-background text-foreground;
font-family: "Google Sans Flex", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
}
code, pre, .font-mono {
font-family: "Google Sans Code", ui-monospace, SFMono-Regular, "SF Mono", Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace !important;
}
}
@theme inline {
--font-mono: "Google Sans Code", ui-monospace, SFMono-Regular, "SF Mono", Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
}
/* Sonner Toast Styling */
[data-sonner-toast] {
@apply rounded-lg shadow-lg border;
}
[data-sonner-toast][data-type="success"] {
@apply bg-green-50 border-green-200 text-green-900;
}
[data-sonner-toast][data-type="success"] [data-icon] {
@apply text-green-600;
}
[data-sonner-toast][data-type="error"] {
@apply bg-red-50 border-red-200 text-red-900;
}
[data-sonner-toast][data-type="error"] [data-icon] {
@apply text-red-600;
}
[data-sonner-toast][data-type="warning"] {
@apply bg-yellow-50 border-yellow-200 text-yellow-900;
}
[data-sonner-toast][data-type="warning"] [data-icon] {
@apply text-yellow-600;
}
[data-sonner-toast][data-type="info"] {
@apply bg-blue-50 border-blue-200 text-blue-900;
}
[data-sonner-toast][data-type="info"] [data-icon] {
@apply text-blue-600;
}
/* Ensure description text uses same color as title */
[data-sonner-toast] [data-description],
[data-sonner-toast] [data-description] * {
opacity: 1 !important;
}
/* Specific color for each toast type - match icon color */
[data-sonner-toast][data-type="success"] [data-description],
[data-sonner-toast][data-type="success"] [data-description] * {
color: rgb(22 163 74) !important; /* green-600 - same as icon */
}
[data-sonner-toast][data-type="error"] [data-description],
[data-sonner-toast][data-type="error"] [data-description] * {
color: rgb(220 38 38) !important; /* red-600 - same as icon */
}
[data-sonner-toast][data-type="warning"] [data-description],
[data-sonner-toast][data-type="warning"] [data-description] * {
color: rgb(202 138 4) !important; /* yellow-600 - same as icon */
}
[data-sonner-toast][data-type="info"] [data-description],
[data-sonner-toast][data-type="info"] [data-description] * {
color: rgb(37 99 235) !important; /* blue-600 - same as icon */
}
/* Dark mode - use same icon colors */
.dark [data-sonner-toast][data-type="success"] [data-description],
.dark [data-sonner-toast][data-type="success"] [data-description] * {
color: rgb(22 163 74) !important; /* green-600 */
}
.dark [data-sonner-toast][data-type="error"] [data-description],
.dark [data-sonner-toast][data-type="error"] [data-description] * {
color: rgb(220 38 38) !important; /* red-600 */
}
.dark [data-sonner-toast][data-type="warning"] [data-description],
.dark [data-sonner-toast][data-type="warning"] [data-description] * {
color: rgb(202 138 4) !important; /* yellow-600 */
}
.dark [data-sonner-toast][data-type="info"] [data-description],
.dark [data-sonner-toast][data-type="info"] [data-description] * {
color: rgb(37 99 235) !important; /* blue-600 */
}
/* Dark mode toast styling */
.dark [data-sonner-toast][data-type="success"] {
@apply bg-green-950 border-green-800 text-green-100;
}
.dark [data-sonner-toast][data-type="success"] [data-icon] {
@apply text-green-400;
}
.dark [data-sonner-toast][data-type="error"] {
@apply bg-red-950 border-red-800 text-red-100;
}
.dark [data-sonner-toast][data-type="error"] [data-icon] {
@apply text-red-400;
}
.dark [data-sonner-toast][data-type="warning"] {
@apply bg-yellow-950 border-yellow-800 text-yellow-100;
}
.dark [data-sonner-toast][data-type="warning"] [data-icon] {
@apply text-yellow-400;
}
.dark [data-sonner-toast][data-type="info"] {
@apply bg-blue-950 border-blue-800 text-blue-100;
}
.dark [data-sonner-toast][data-type="info"] [data-icon] {
@apply text-blue-400;
}
/* Custom Scrollbar - mengikuti primary color theme */
::-webkit-scrollbar {
width: 8px;
height: 8px;
}
::-webkit-scrollbar-track {
background: var(--secondary);
border-radius: 4px;
}
::-webkit-scrollbar-thumb {
background: var(--primary);
border-radius: 4px;
opacity: 0.7;
}
::-webkit-scrollbar-thumb:hover {
background: var(--primary);
filter: brightness(1.2);
}
/* Firefox scrollbar support */
* {
scrollbar-width: thin;
scrollbar-color: var(--primary) var(--secondary);
}
input::-ms-reveal,
input::-ms-clear {
display: none;
}
input[type="number"],
input[type="date"],
input[type="datetime-local"],
input[type="time"],
input[type="month"],
input[type="week"] {
color-scheme: light;
}
.dark input[type="number"],
.dark input[type="date"],
.dark input[type="datetime-local"],
.dark input[type="time"],
.dark input[type="month"],
.dark input[type="week"] {
color-scheme: dark;
}
input[type="number"]::-webkit-outer-spin-button,
input[type="number"]::-webkit-inner-spin-button {
margin: 0;
background: transparent;
border: 0;
box-shadow: none;
opacity: 1;
}
/* Custom scrollbar class untuk komponen tertentu */
.custom-scrollbar::-webkit-scrollbar {
width: 6px;
height: 6px;
}
.custom-scrollbar::-webkit-scrollbar-track {
background: var(--muted);
border-radius: 3px;
}
.custom-scrollbar::-webkit-scrollbar-thumb {
background: var(--primary);
border-radius: 3px;
}
.custom-scrollbar::-webkit-scrollbar-thumb:hover {
filter: brightness(1.2);
}
+80
View File
@@ -0,0 +1,80 @@
class AudioManager {
private audioContext: AudioContext | null = null;
private getAudioContext(): AudioContext {
if (!this.audioContext) {
const AudioContextConstructor = window.AudioContext || (window as Window & {
webkitAudioContext?: typeof AudioContext;
}).webkitAudioContext;
if (!AudioContextConstructor) {
throw new Error("Web Audio API is not supported in this browser");
}
const context = new AudioContextConstructor();
this.audioContext = context;
return context;
}
return this.audioContext;
}
private playTone(frequency: number, duration: number, type: OscillatorType = 'sine', volume: number = 0.3) {
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, 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();
const now = ctx.currentTime;
this.playToneAt(523.25, 0.08, 'sine', 0.2, now);
this.playToneAt(659.25, 0.08, 'sine', 0.2, now + 0.08);
this.playToneAt(783.99, 0.15, 'sine', 0.25, now + 0.16);
}
playError() {
const ctx = this.getAudioContext();
const now = ctx.currentTime;
this.playToneAt(392.00, 0.1, 'square', 0.15, now);
this.playToneAt(329.63, 0.2, 'square', 0.2, now + 0.1);
}
playWarning() {
const ctx = this.getAudioContext();
const now = ctx.currentTime;
this.playToneAt(440.00, 0.1, 'triangle', 0.2, now);
this.playToneAt(493.88, 0.1, 'triangle', 0.2, now + 0.12);
}
playInfo() {
this.playTone(523.25, 0.15, 'sine', 0.15);
}
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 const audioManager = new AudioManager();
export const playSuccessSound = () => audioManager.playSuccess();
export const playErrorSound = () => audioManager.playError();
export const playWarningSound = () => audioManager.playWarning();
export const playInfoSound = () => audioManager.playInfo();
+112
View File
@@ -0,0 +1,112 @@
import { useSyncExternalStore } from "react";
import { EventsOn } from "../../wailsjs/runtime/runtime";
export interface DownloadProgress {
current: number;
total: number;
percent: number;
}
export interface DownloadItemStatus {
tweet_id: number;
index: number;
status: "success" | "failed" | "skipped" | "cancelled";
}
export type DownloadScope = "media" | "database" | "database-bulk";
export type DownloadItemResult = "success" | "failed" | "skipped";
export interface DownloadState {
active: boolean;
scope: DownloadScope | null;
accountId: number | null;
progress: DownloadProgress | null;
currentItemKey: string | null;
itemKeyByIndex: Record<number, string>;
itemStatusByKey: Record<string, DownloadItemResult>;
}
const listeners = new Set<() => void>();
let state: DownloadState = {
active: false,
scope: null,
accountId: null,
progress: null,
currentItemKey: null,
itemKeyByIndex: {},
itemStatusByKey: {},
};
let unsubscribeEvents: (() => void) | null = null;
function emit() {
for (const listener of listeners) {
listener();
}
}
function setState(next: Partial<DownloadState>) {
state = { ...state, ...next };
emit();
}
export function initDownloadProgressEvents() {
if (unsubscribeEvents) {
return unsubscribeEvents;
}
const unsubscribeProgress = EventsOn("download-progress", (progress: DownloadProgress) => {
if (!state.scope) {
return;
}
setState({ progress });
});
const unsubscribeItemStatus = EventsOn("download-item-status", (status: DownloadItemStatus) => {
if (status.status === "cancelled") {
return;
}
const itemKey = state.currentItemKey || state.itemKeyByIndex[status.index] || `${String(status.tweet_id)}-${status.index}`;
setState({
itemStatusByKey: {
...state.itemStatusByKey,
[itemKey]: status.status,
},
});
});
unsubscribeEvents = () => {
unsubscribeProgress();
unsubscribeItemStatus();
unsubscribeEvents = null;
};
return unsubscribeEvents;
}
export function beginDownload(progress: DownloadProgress, meta: Pick<DownloadState, "scope"> & Partial<Pick<DownloadState, "accountId" | "currentItemKey" | "itemKeyByIndex">>) {
setState({
active: true,
scope: meta.scope,
accountId: meta.accountId ?? null,
progress,
currentItemKey: meta.currentItemKey ?? null,
itemKeyByIndex: meta.itemKeyByIndex ?? {},
});
}
export function finishDownload() {
setState({
active: false,
scope: null,
accountId: null,
progress: null,
currentItemKey: null,
itemKeyByIndex: {},
});
}
export function setDownloadItemStatus(itemKey: string, status: DownloadItemResult) {
setState({
itemStatusByKey: {
...state.itemStatusByKey,
[itemKey]: status,
},
});
}
export function subscribeDownloadState(listener: () => void) {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
}
export function getDownloadState() {
return state;
}
export function useDownloadState() {
return useSyncExternalStore(subscribeDownloadState, getDownloadState, getDownloadState);
}
+27
View File
@@ -0,0 +1,27 @@
export function normalizeFetchDelay(value: unknown): number {
return typeof value === "number" && Number.isFinite(value)
? Math.round(Math.min(3600, Math.max(0, value)) * 1000) / 1000
: 0;
}
// One gate shared by all fetch paths, so switching accounts also respects pacing.
export function createFetchDelayGate({
now = () => performance.now(),
random = Math.random,
sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)),
} = {}) {
let lastStarted: number | null = null;
return async (baseSeconds: number, extraSeconds: number, stopped: () => boolean): Promise<boolean> => {
const delay = (normalizeFetchDelay(baseSeconds) + random() * normalizeFetchDelay(extraSeconds)) * 1000;
while (!stopped()) {
const remaining = lastStarted === null ? 0 : lastStarted + delay - now();
if (remaining <= 0) {
lastStarted = now();
return true;
}
// Recheck the shared timestamp after each wait to space concurrent callers too.
await sleep(Math.min(remaining, 100));
}
return false;
};
}
+182
View File
@@ -0,0 +1,182 @@
import type { TimelineEntry } from "@/types/api";
const FETCH_STATE_KEY = "twitter_fetch_state";
const CURSOR_STATE_KEY = "twitter_cursor_state";
export interface FetchState {
username: string;
cursor: string;
totalFetched: number;
completed: boolean;
lastUpdated: number;
mediaType: string;
retweets: boolean;
timelineType: string;
}
function normalizeFetchState(state: FetchState | null | undefined): FetchState | null {
if (!state) {
return null;
}
return {
...state,
cursor: state.cursor || "",
totalFetched: state.totalFetched ?? 0,
mediaType: state.mediaType || "all",
retweets: state.retweets ?? false,
timelineType: state.timelineType || "timeline",
};
}
export function saveFetchState(state: Partial<FetchState> & {
username: string;
}): void {
try {
const existing = getFetchState(state.username);
const updated: FetchState = {
username: state.username,
cursor: state.cursor || "",
totalFetched: state.totalFetched ?? existing?.totalFetched ?? 0,
completed: state.completed ?? false,
lastUpdated: Date.now(),
mediaType: state.mediaType || existing?.mediaType || "all",
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));
}
catch (error) {
console.error("Failed to save fetch state:", error);
}
}
export function getFetchState(username: string): FetchState | null {
try {
const allStates = getAllFetchStates();
return normalizeFetchState(allStates[username.toLowerCase()]);
}
catch (error) {
console.error("Failed to get fetch state:", error);
return null;
}
}
export function getAllFetchStates(): Record<string, FetchState> {
try {
const stored = localStorage.getItem(FETCH_STATE_KEY);
if (stored) {
const parsed = JSON.parse(stored);
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
const normalized: Record<string, FetchState> = {};
for (const [key, value] of Object.entries(parsed as Record<string, FetchState | null | undefined>)) {
const state = normalizeFetchState(value);
if (state) {
normalized[key] = state;
}
}
return normalized;
}
}
}
catch (error) {
console.error("Failed to parse fetch states:", error);
}
return {};
}
export function hasResumableFetch(username: string): boolean {
const state = getFetchState(username);
if (!state)
return false;
return !!state.cursor && !state.completed && state.totalFetched > 0;
}
export function getResumableInfo(username: string): {
canResume: boolean;
mediaCount: number;
lastUpdated: Date | null;
} {
const state = getFetchState(username);
if (!state || state.completed || !state.cursor) {
return { canResume: false, mediaCount: 0, lastUpdated: null };
}
return {
canResume: true,
mediaCount: state.totalFetched,
lastUpdated: new Date(state.lastUpdated),
};
}
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);
}
}
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;
}
}
localStorage.setItem(FETCH_STATE_KEY, JSON.stringify(completed));
}
catch (error) {
console.error("Failed to clear fetch states:", error);
}
}
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 {
try {
const allCursors = getAllCursors();
delete allCursors[username.toLowerCase()];
localStorage.setItem(CURSOR_STATE_KEY, JSON.stringify(allCursors));
}
catch (error) {
console.error("Failed to clear cursor:", error);
}
}
export function mergeTimelines(existing: TimelineEntry[], newEntries: TimelineEntry[]): TimelineEntry[] {
const existingTimeline = Array.isArray(existing) ? existing : [];
const incomingTimeline = Array.isArray(newEntries) ? newEntries : [];
const seenIds = new Set(existingTimeline.map((e) => e.tweet_id));
const unique = incomingTimeline.filter((e) => !seenIds.has(e.tweet_id));
return [...existingTimeline, ...unique];
}
+53
View File
@@ -0,0 +1,53 @@
export type LogLevel = "info" | "success" | "warning" | "error" | "debug";
export interface LogEntry {
timestamp: Date;
level: LogLevel;
message: string;
}
class Logger {
private logs: LogEntry[] = [];
private maxLogs = 500;
private listeners: Set<() => void> = new Set();
private addLog(level: LogLevel, message: string) {
const entry: LogEntry = {
timestamp: new Date(),
level,
message: message.toLowerCase(),
};
this.logs.push(entry);
if (this.logs.length > this.maxLogs) {
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());
}
}
export const logger = new Logger();
+24
View File
@@ -0,0 +1,24 @@
export function extractMarkdownSection(body: string, heading: string): string {
const text = (body || "").replace(/\r\n/g, "\n");
const lines = text.split("\n");
const target = heading.trim().toLowerCase();
let start = -1;
for (let i = 0; i < lines.length; i++) {
const match = lines[i].match(/^#{1,6}\s+(.*)$/);
if (match && match[1].trim().toLowerCase() === target) {
start = i + 1;
break;
}
}
if (start === -1) {
return text.trim();
}
const collected: string[] = [];
for (let i = start; i < lines.length; i++) {
if (/^#{1,6}\s+/.test(lines[i])) {
break;
}
collected.push(lines[i]);
}
return collected.join("\n").trim();
}
+57
View File
@@ -0,0 +1,57 @@
export function formatRelativeTime(date: Date | string | number): string {
const now = new Date();
const target = new Date(date);
const diffMs = now.getTime() - target.getTime();
if (diffMs < 0)
return "just now";
const seconds = Math.floor(diffMs / 1000);
const minutes = Math.floor(seconds / 60);
const hours = Math.floor(minutes / 60);
const days = Math.floor(hours / 24);
const weeks = Math.floor(days / 7);
const months = Math.floor(days / 30);
const years = Math.floor(days / 365);
const parts: string[] = [];
if (years > 0) {
parts.push(`${years} ${years === 1 ? "year" : "years"}`);
const remainingMonths = Math.floor((days % 365) / 30);
if (remainingMonths > 0) {
parts.push(`${remainingMonths} ${remainingMonths === 1 ? "month" : "months"}`);
}
}
else if (months > 0) {
parts.push(`${months} ${months === 1 ? "month" : "months"}`);
const remainingDays = days % 30;
if (remainingDays > 0) {
parts.push(`${remainingDays} ${remainingDays === 1 ? "day" : "days"}`);
}
}
else if (weeks > 0) {
parts.push(`${weeks} ${weeks === 1 ? "week" : "weeks"}`);
const remainingDays = days % 7;
if (remainingDays > 0) {
parts.push(`${remainingDays} ${remainingDays === 1 ? "day" : "days"}`);
}
}
else if (days > 0) {
parts.push(`${days} ${days === 1 ? "day" : "days"}`);
const remainingHours = hours % 24;
if (remainingHours > 0) {
parts.push(`${remainingHours} ${remainingHours === 1 ? "hour" : "hours"}`);
}
}
else if (hours > 0) {
parts.push(`${hours} ${hours === 1 ? "hour" : "hours"}`);
const remainingMinutes = minutes % 60;
if (remainingMinutes > 0) {
parts.push(`${remainingMinutes} ${remainingMinutes === 1 ? "minute" : "minutes"}`);
}
}
else if (minutes > 0) {
parts.push(`${minutes} ${minutes === 1 ? "minute" : "minutes"}`);
}
else {
return "just now";
}
return "Released " + parts.slice(0, 2).join(" ") + " ago";
}
+46
View File
@@ -0,0 +1,46 @@
export type DependencyName = "extractor" | "ffmpeg" | "exiftool";
export interface CachedDependencyStatus {
installed: boolean | null;
installedVersion: string | null;
latestVersion: string | null;
}
export interface CachedMediaFolderStatus {
folderExists: boolean;
gifsFolderHasMP4: boolean;
}
const dependencyStatusCache: Record<DependencyName, CachedDependencyStatus> = {
extractor: {
installed: null,
installedVersion: null,
latestVersion: null,
},
ffmpeg: {
installed: null,
installedVersion: null,
latestVersion: null,
},
exiftool: {
installed: null,
installedVersion: null,
latestVersion: null,
},
};
const mediaFolderStatusCache = new Map<string, CachedMediaFolderStatus>();
function getMediaFolderStatusKey(downloadPath: string, folderName: string): string {
return `${downloadPath}::${folderName}`;
}
export function getCachedDependencyStatus(name: DependencyName): CachedDependencyStatus {
return { ...dependencyStatusCache[name] };
}
export function setCachedDependencyStatus(name: DependencyName, status: Partial<CachedDependencyStatus>): void {
dependencyStatusCache[name] = {
...dependencyStatusCache[name],
...status,
};
}
export function getCachedMediaFolderStatus(downloadPath: string, folderName: string): CachedMediaFolderStatus | null {
return mediaFolderStatusCache.get(getMediaFolderStatusKey(downloadPath, folderName)) ?? null;
}
export function setCachedMediaFolderStatus(downloadPath: string, folderName: string, status: CachedMediaFolderStatus): void {
mediaFolderStatusCache.set(getMediaFolderStatusKey(downloadPath, folderName), status);
}
+640
View File
@@ -0,0 +1,640 @@
import { GetDefaults } from "../../wailsjs/go/main/App";
import { normalizeFetchDelay } from "./fetch-delay";
import { normalizeBaseColorName, normalizeThemeName, type BaseColorName, type ThemeName } from "./themes";
export type BuiltInFontFamily = "google-sans" | "inter" | "poppins" | "roboto" | "dm-sans" | "plus-jakarta-sans" | "manrope" | "space-grotesk" | "noto-sans" | "nunito-sans" | "figtree" | "raleway" | "public-sans" | "outfit" | "jetbrains-mono" | "geist-sans" | "bricolage-grotesque";
export type CustomFontFamily = `custom-${string}`;
export type FontFamily = BuiltInFontFamily | CustomFontFamily;
export interface CustomFontOption {
value: CustomFontFamily;
label: string;
fontFamily: string;
url: string;
}
export interface FontOption {
value: FontFamily;
label: string;
fontFamily: string;
url?: string;
}
export type GifQuality = "fast" | "better";
export type GifResolution = "original" | "high" | "medium" | "low";
export type VideoQuality = "highest" | "720" | "480" | "360" | "lowest";
export type ImageSize = "orig" | "large" | "medium" | "small";
export type AvatarSize = "orig" | "400x400" | "200x200" | "bigger" | "normal";
export type BannerSize = "orig" | "1500x500" | "600x200" | "300x100";
export const VIDEO_QUALITIES: {
value: VideoQuality;
label: string;
}[] = [
{ value: "highest", label: "Highest" },
{ value: "720", label: "720p" },
{ value: "480", label: "480p" },
{ value: "360", label: "360p" },
{ value: "lowest", label: "Lowest" },
];
export const IMAGE_SIZES: {
value: ImageSize;
label: string;
}[] = [
{ value: "orig", label: "Original" },
{ value: "large", label: "Large" },
{ value: "medium", label: "Medium" },
{ value: "small", label: "Small" },
];
export const AVATAR_SIZES: {
value: AvatarSize;
label: string;
}[] = [
{ value: "orig", label: "Original" },
{ value: "400x400", label: "400px" },
{ value: "200x200", label: "200px" },
{ value: "bigger", label: "Bigger" },
{ value: "normal", label: "Normal" },
];
export const BANNER_SIZES: {
value: BannerSize;
label: string;
}[] = [
{ value: "orig", label: "Original" },
{ value: "1500x500", label: "1500×500" },
{ value: "600x200", label: "600×200" },
{ value: "300x100", label: "300×100" },
];
export const DEFAULT_FILENAME_TEMPLATE = "{handle}_{date}_{tweet_id}";
export interface TemplateToken {
key: string;
description: string;
example: string;
}
export const FILENAME_TEMPLATE_VARIABLES: TemplateToken[] = [
{ key: "{handle}", description: "Author handle", example: "elonmusk" },
{ key: "{name}", description: "Author display name", example: "Elon Musk" },
{ key: "{date}", description: "Tweet date & time", example: "20250620_104556" },
{ key: "{tweet_id}", description: "Tweet ID", example: "1989033613824815258" },
{ key: "{media_id}", description: "Unique media ID (prevents overwrites)", example: "Gx1aB2cXkAA7Yz9" },
{ key: "{type}", description: "Media type", example: "photo" },
];
export interface FilenameTemplateData {
username?: string;
accountName?: string;
date?: string;
tweetId?: string;
index?: number;
mediaID?: string;
type?: string;
}
export const SAMPLE_FILENAME_DATA: FilenameTemplateData = {
username: "elonmusk",
accountName: "Elon Musk",
date: "20250620_104556",
tweetId: "1989033613824815258",
index: 1,
mediaID: "Gx1aB2cXkAA7Yz9",
type: "photo",
};
function sanitizeTemplatePart(input: string): string {
const cleaned = input
.replace(/[\u0000-\u001f\\/:*?"<>|]/g, "")
.trim()
.replace(/[. ]+$/g, "");
return /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i.test(cleaned) ? `${cleaned}_` : cleaned;
}
export function renderFilenameTemplate(template: string, data: FilenameTemplateData): string {
if (!template)
return "";
return sanitizeTemplatePart(template
.replace(/\{handle\}/g, sanitizeTemplatePart(data.username ?? ""))
.replace(/\{name\}/g, sanitizeTemplatePart(data.accountName ?? ""))
.replace(/\{username\}/g, sanitizeTemplatePart(data.username ?? ""))
.replace(/\{account_name\}/g, sanitizeTemplatePart(data.accountName ?? ""))
.replace(/\{date\}/g, sanitizeTemplatePart(data.date ?? ""))
.replace(/\{tweet_id\}/g, sanitizeTemplatePart(data.tweetId ?? ""))
.replace(/\{index\}/g, String(data.index ?? 1).padStart(2, "0"))
.replace(/\{media_id\}/g, sanitizeTemplatePart(data.mediaID ?? ""))
.replace(/\{type\}/g, sanitizeTemplatePart(data.type ?? ""))
.trim());
}
export const DEFAULT_FOLDER_TEMPLATE = "{handle}";
export const FOLDER_TEMPLATE_VARIABLES: TemplateToken[] = [
{ key: "{handle}", description: "Author handle", example: "elonmusk" },
{ key: "{name}", description: "Author display name", example: "Elon Musk" },
{ key: "{date}", description: "Download date", example: "20250620" },
];
export interface FolderTemplateData {
username?: string;
accountName?: string;
date?: string;
}
export const SAMPLE_FOLDER_DATA: FolderTemplateData = {
username: "elonmusk",
accountName: "Elon Musk",
date: "20250620",
};
export function renderFolderTemplate(template: string, data: FolderTemplateData): string {
if (!template)
return "";
return sanitizeTemplatePart(template
.replace(/\{handle\}/g, sanitizeTemplatePart(data.username ?? ""))
.replace(/\{name\}/g, sanitizeTemplatePart(data.accountName ?? ""))
.replace(/\{username\}/g, sanitizeTemplatePart(data.username ?? ""))
.replace(/\{account_name\}/g, sanitizeTemplatePart(data.accountName ?? ""))
.replace(/\{date\}/g, sanitizeTemplatePart(data.date ?? ""))
.trim());
}
const DEFAULT_CONCURRENT_DOWNLOADS = 10;
const MIN_CONCURRENT_DOWNLOADS = 1;
const MAX_CONCURRENT_DOWNLOADS = 50;
const DEFAULT_RETRY_ATTEMPTS = 1;
const MIN_RETRY_ATTEMPTS = 1;
const MAX_RETRY_ATTEMPTS = 5;
const DEFAULT_DOWNLOAD_SPEED_LIMIT_KBPS = 0;
const MAX_DOWNLOAD_SPEED_LIMIT_KBPS = 10 * 1024 * 1024;
const DEFAULT_DOWNLOAD_DELAY_SECONDS = 0;
const MAX_DOWNLOAD_DELAY_SECONDS = 60 * 60;
export interface Settings {
downloadPath: string;
concurrentDownloads: number;
skipExistingFiles: boolean;
deleteIncompleteFiles: boolean;
retryAttempts: number;
downloadSpeedLimitKBps: number;
downloadDelaySeconds: number;
downloadDelayJitterSeconds: number;
baseColor: BaseColorName;
theme: ThemeName;
themeMode: "auto" | "light" | "dark";
fontFamily: FontFamily;
customFonts: CustomFontOption[];
sfxEnabled: boolean;
showUpdateNotifications: boolean;
autoConvertGifs: boolean;
gifQuality: GifQuality;
gifResolution: GifResolution;
proxy: string;
fetchTimeout: number;
fetchDelaySeconds: number;
fetchDelayJitterSeconds: number;
includePhotos: boolean;
includeVideos: boolean;
includeGifs: boolean;
includeText: boolean;
includeRetweets: boolean;
videoQuality: VideoQuality;
imageSize: ImageSize;
avatarSize: AvatarSize;
bannerSize: BannerSize;
filenameTemplate: string;
folderTemplate: string;
}
export const DEFAULT_SETTINGS: Settings = {
downloadPath: "",
concurrentDownloads: DEFAULT_CONCURRENT_DOWNLOADS,
skipExistingFiles: true,
deleteIncompleteFiles: true,
retryAttempts: DEFAULT_RETRY_ATTEMPTS,
downloadSpeedLimitKBps: DEFAULT_DOWNLOAD_SPEED_LIMIT_KBPS,
downloadDelaySeconds: DEFAULT_DOWNLOAD_DELAY_SECONDS,
downloadDelayJitterSeconds: DEFAULT_DOWNLOAD_DELAY_SECONDS,
baseColor: "neutral",
theme: "yellow",
themeMode: "auto",
fontFamily: "google-sans",
customFonts: [],
sfxEnabled: true,
showUpdateNotifications: true,
autoConvertGifs: false,
gifQuality: "fast",
gifResolution: "original",
proxy: "",
fetchTimeout: 60,
fetchDelaySeconds: 0,
fetchDelayJitterSeconds: 0,
includePhotos: true,
includeVideos: true,
includeGifs: true,
includeText: false,
includeRetweets: false,
videoQuality: "highest",
imageSize: "orig",
avatarSize: "orig",
bannerSize: "orig",
filenameTemplate: DEFAULT_FILENAME_TEMPLATE,
folderTemplate: DEFAULT_FOLDER_TEMPLATE,
};
export const FONT_OPTIONS: FontOption[] = [
{
value: "bricolage-grotesque",
label: "Bricolage Grotesque",
fontFamily: '"Bricolage Grotesque", system-ui, sans-serif',
},
{
value: "dm-sans",
label: "DM Sans",
fontFamily: '"DM Sans", system-ui, sans-serif',
},
{
value: "figtree",
label: "Figtree",
fontFamily: '"Figtree", system-ui, sans-serif',
},
{
value: "geist-sans",
label: "Geist Sans",
fontFamily: '"Geist", system-ui, sans-serif',
},
{
value: "google-sans",
label: "Google Sans",
fontFamily: '"Google Sans Flex", system-ui, sans-serif',
},
{
value: "inter",
label: "Inter",
fontFamily: '"Inter", system-ui, sans-serif',
},
{
value: "jetbrains-mono",
label: "JetBrains Mono",
fontFamily: '"JetBrains Mono", ui-monospace, monospace',
},
{
value: "manrope",
label: "Manrope",
fontFamily: '"Manrope", system-ui, sans-serif',
},
{
value: "noto-sans",
label: "Noto Sans",
fontFamily: '"Noto Sans", system-ui, sans-serif',
},
{
value: "nunito-sans",
label: "Nunito Sans",
fontFamily: '"Nunito Sans", system-ui, sans-serif',
},
{
value: "outfit",
label: "Outfit",
fontFamily: '"Outfit", system-ui, sans-serif',
},
{
value: "plus-jakarta-sans",
label: "Plus Jakarta Sans",
fontFamily: '"Plus Jakarta Sans", system-ui, sans-serif',
},
{
value: "poppins",
label: "Poppins",
fontFamily: '"Poppins", system-ui, sans-serif',
},
{
value: "public-sans",
label: "Public Sans",
fontFamily: '"Public Sans", system-ui, sans-serif',
},
{
value: "raleway",
label: "Raleway",
fontFamily: '"Raleway", system-ui, sans-serif',
},
{
value: "roboto",
label: "Roboto",
fontFamily: '"Roboto", system-ui, sans-serif',
},
{
value: "space-grotesk",
label: "Space Grotesk",
fontFamily: '"Space Grotesk", system-ui, sans-serif',
},
];
const BUILT_IN_FONT_VALUES = new Set(FONT_OPTIONS.map((font) => font.value));
const SETTINGS_KEY = "twitter-media-downloader-settings";
const GOOGLE_FONT_LINK_ID_PREFIX = "twitter-media-custom-font-";
const GOOGLE_FONTS_CSS_HOST = "fonts.googleapis.com";
const GOOGLE_FONTS_SPECIMEN_HOST = "fonts.google.com";
function extractGoogleFontInputUrl(input: string): string {
const trimmed = input.trim();
const hrefMatch = trimmed.match(/\bhref=["']([^"']+)["']/i);
if (hrefMatch?.[1]) {
return hrefMatch[1];
}
const importMatch = trimmed.match(/@import\s+url\(["']?([^"')]+)["']?\)/i);
if (importMatch?.[1]) {
return importMatch[1];
}
return trimmed;
}
function coerceGoogleFontUrl(rawUrl: string): string {
const trimmed = rawUrl.trim();
if (/^https?:\/\//i.test(trimmed)) {
return trimmed;
}
if (/^(fonts\.googleapis\.com|fonts\.google\.com)\//i.test(trimmed)) {
return `https://${trimmed}`;
}
return trimmed;
}
function normalizeFontLabel(label: string): string {
return label.replace(/\+/g, " ").replace(/\s+/g, " ").trim();
}
function slugifyFontLabel(label: string): string {
return label.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "font";
}
function toFontFamilyCss(label: string): string {
const escapedLabel = label.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
return `"${escapedLabel}", system-ui, sans-serif`;
}
function buildGoogleFontsCssUrl(label: string): string {
const url = new URL("https://fonts.googleapis.com/css2");
url.searchParams.set("family", label);
url.searchParams.set("display", "swap");
return url.toString();
}
function extractSpecimenFontLabel(parsed: URL): string {
const segments = parsed.pathname.split("/").filter(Boolean);
const specimenIndex = segments.findIndex((segment) => segment.toLowerCase() === "specimen");
const specimenName = specimenIndex >= 0 ? segments[specimenIndex + 1] : "";
return normalizeFontLabel(decodeURIComponent(specimenName || ""));
}
function normalizeGoogleFontCssUrl(rawUrl: string): string | null {
try {
const parsed = new URL(coerceGoogleFontUrl(extractGoogleFontInputUrl(rawUrl)));
if (parsed.protocol !== "https:") {
return null;
}
if (parsed.hostname === GOOGLE_FONTS_SPECIMEN_HOST) {
const label = extractSpecimenFontLabel(parsed);
return label ? buildGoogleFontsCssUrl(label) : null;
}
if (parsed.hostname !== GOOGLE_FONTS_CSS_HOST || (parsed.pathname !== "/css" && parsed.pathname !== "/css2")) {
return null;
}
if (parsed.searchParams.getAll("family").length === 0) {
return null;
}
if (!parsed.searchParams.has("display")) {
parsed.searchParams.set("display", "swap");
}
return parsed.toString();
}
catch {
return null;
}
}
export function parseGoogleFontUrl(rawUrl: string): CustomFontOption | null {
const normalizedUrl = normalizeGoogleFontCssUrl(rawUrl);
if (!normalizedUrl) {
return null;
}
const parsed = new URL(normalizedUrl);
const family = parsed.searchParams.getAll("family")[0];
const label = normalizeFontLabel((family || "").split(":")[0] || "");
if (!label) {
return null;
}
return {
value: `custom-${slugifyFontLabel(label)}` as CustomFontFamily,
label,
fontFamily: toFontFamilyCss(label),
url: normalizedUrl,
};
}
function normalizeCustomFonts(customFonts: unknown): CustomFontOption[] {
if (!Array.isArray(customFonts)) {
return [];
}
const normalizedFonts: CustomFontOption[] = [];
const seenValues = new Set<string>();
const seenUrls = new Set<string>();
for (const item of customFonts) {
if (!item || typeof item !== "object") {
continue;
}
const rawUrl = (item as {
url?: unknown;
}).url;
if (typeof rawUrl !== "string") {
continue;
}
const parsed = parseGoogleFontUrl(rawUrl);
if (!parsed || seenValues.has(parsed.value) || seenUrls.has(parsed.url)) {
continue;
}
seenValues.add(parsed.value);
seenUrls.add(parsed.url);
normalizedFonts.push(parsed);
}
return normalizedFonts;
}
function normalizeFontFamily(fontFamily: unknown, customFonts: CustomFontOption[]): FontFamily {
if (typeof fontFamily !== "string") {
return DEFAULT_SETTINGS.fontFamily;
}
if (BUILT_IN_FONT_VALUES.has(fontFamily as BuiltInFontFamily)) {
return fontFamily as BuiltInFontFamily;
}
const customFont = customFonts.find((font) => font.value === fontFamily);
return customFont ? customFont.value : DEFAULT_SETTINGS.fontFamily;
}
function normalizeConcurrentDownloads(value: unknown): number {
if (typeof value !== "number" || !Number.isFinite(value)) {
return DEFAULT_CONCURRENT_DOWNLOADS;
}
const rounded = Math.round(value);
if (rounded < MIN_CONCURRENT_DOWNLOADS) {
return MIN_CONCURRENT_DOWNLOADS;
}
if (rounded > MAX_CONCURRENT_DOWNLOADS) {
return MAX_CONCURRENT_DOWNLOADS;
}
return rounded;
}
function normalizeBoolean(value: unknown, fallback: boolean): boolean {
if (typeof value === "boolean") {
return value;
}
return fallback;
}
function normalizeRetryAttempts(value: unknown): number {
if (typeof value !== "number" || !Number.isFinite(value)) {
return DEFAULT_RETRY_ATTEMPTS;
}
const rounded = Math.round(value);
if (rounded < MIN_RETRY_ATTEMPTS) {
return MIN_RETRY_ATTEMPTS;
}
if (rounded > MAX_RETRY_ATTEMPTS) {
return MAX_RETRY_ATTEMPTS;
}
return rounded;
}
function normalizeDownloadSpeedLimit(value: unknown): number {
if (typeof value !== "number" || !Number.isFinite(value)) {
return DEFAULT_DOWNLOAD_SPEED_LIMIT_KBPS;
}
return Math.min(MAX_DOWNLOAD_SPEED_LIMIT_KBPS, Math.max(0, Math.round(value)));
}
function normalizeDownloadDelay(value: unknown): number {
if (typeof value !== "number" || !Number.isFinite(value)) {
return DEFAULT_DOWNLOAD_DELAY_SECONDS;
}
const milliseconds = Math.round(Math.min(MAX_DOWNLOAD_DELAY_SECONDS, Math.max(0, value)) * 1000);
return milliseconds / 1000;
}
function normalizeTemplateTokens(value: unknown, fallback: string): string {
if (typeof value !== "string") {
return fallback;
}
return value
.replace(/\{username\}/g, "{handle}")
.replace(/\{account_name\}/g, "{name}");
}
function normalizeFilenameTemplate(value: unknown): string {
const template = normalizeTemplateTokens(value, DEFAULT_FILENAME_TEMPLATE);
return template === "{handle}_{date}_{tweet_id}_{index}" ? DEFAULT_FILENAME_TEMPLATE : template;
}
function normalizeFolderTemplate(value: unknown): string {
return normalizeTemplateTokens(value, DEFAULT_FOLDER_TEMPLATE);
}
export function getFontOptions(customFonts: CustomFontOption[] = []): FontOption[] {
return [...FONT_OPTIONS, ...normalizeCustomFonts(customFonts)];
}
export function loadGoogleFontUrl(url: string, id = `${GOOGLE_FONT_LINK_ID_PREFIX}preview`): void {
const normalizedUrl = normalizeGoogleFontCssUrl(url);
if (!normalizedUrl) {
return;
}
let link = document.getElementById(id) as HTMLLinkElement | null;
if (!link) {
link = document.createElement("link");
link.id = id;
link.rel = "stylesheet";
document.head.appendChild(link);
}
if (link.href !== normalizedUrl) {
link.href = normalizedUrl;
}
}
function loadCustomFontStylesheets(customFonts: CustomFontOption[]): void {
for (const font of normalizeCustomFonts(customFonts)) {
loadGoogleFontUrl(font.url, `${GOOGLE_FONT_LINK_ID_PREFIX}${font.value}`);
}
}
export function applyFont(fontFamily: FontFamily, customFonts: CustomFontOption[] = []): void {
const fontOptions = getFontOptions(customFonts);
loadCustomFontStylesheets(customFonts);
const font = fontOptions.find((option) => option.value === fontFamily) || FONT_OPTIONS.find((option) => option.value === DEFAULT_SETTINGS.fontFamily);
if (font) {
document.documentElement.style.setProperty("--font-sans", font.fontFamily);
document.body.style.fontFamily = font.fontFamily;
}
}
async function fetchDefaultPath(): Promise<string> {
try {
const data = await GetDefaults();
return data.downloadPath || "";
}
catch (error) {
console.error("Failed to fetch default path:", error);
return "";
}
}
function toNormalizedSettings(settings: Partial<Settings>): Settings {
const customFonts = normalizeCustomFonts(settings.customFonts);
const baseColor = normalizeBaseColorName(settings.baseColor);
return {
...DEFAULT_SETTINGS,
...settings,
baseColor,
theme: normalizeThemeName(settings.theme, baseColor),
concurrentDownloads: normalizeConcurrentDownloads(settings.concurrentDownloads),
skipExistingFiles: normalizeBoolean(settings.skipExistingFiles, DEFAULT_SETTINGS.skipExistingFiles),
deleteIncompleteFiles: normalizeBoolean(settings.deleteIncompleteFiles, DEFAULT_SETTINGS.deleteIncompleteFiles),
retryAttempts: normalizeRetryAttempts(settings.retryAttempts),
downloadSpeedLimitKBps: normalizeDownloadSpeedLimit(settings.downloadSpeedLimitKBps),
downloadDelaySeconds: normalizeDownloadDelay(settings.downloadDelaySeconds),
downloadDelayJitterSeconds: normalizeDownloadDelay(settings.downloadDelayJitterSeconds),
fetchDelaySeconds: normalizeFetchDelay(settings.fetchDelaySeconds),
fetchDelayJitterSeconds: normalizeFetchDelay(settings.fetchDelayJitterSeconds),
showUpdateNotifications: normalizeBoolean(settings.showUpdateNotifications, DEFAULT_SETTINGS.showUpdateNotifications),
autoConvertGifs: normalizeBoolean(settings.autoConvertGifs, DEFAULT_SETTINGS.autoConvertGifs),
filenameTemplate: normalizeFilenameTemplate(settings.filenameTemplate),
folderTemplate: normalizeFolderTemplate(settings.folderTemplate),
customFonts,
fontFamily: normalizeFontFamily(settings.fontFamily, customFonts),
};
}
export function getSettings(): Settings {
try {
const stored = localStorage.getItem(SETTINGS_KEY);
if (stored) {
return toNormalizedSettings(JSON.parse(stored) as Partial<Settings>);
}
}
catch (error) {
console.error("Failed to load settings:", error);
}
return DEFAULT_SETTINGS;
}
export async function getSettingsWithDefaults(): Promise<Settings> {
const settings = getSettings();
if (!settings.downloadPath) {
settings.downloadPath = await fetchDefaultPath();
}
return toNormalizedSettings(settings);
}
export function saveSettings(settings: Settings): void {
try {
const normalizedSettings = toNormalizedSettings(settings);
localStorage.setItem(SETTINGS_KEY, JSON.stringify(normalizedSettings));
}
catch (error) {
console.error("Failed to save settings:", error);
}
}
export function updateSettings(partial: Partial<Settings>): Settings {
const current = getSettings();
const updated = toNormalizedSettings({ ...current, ...partial });
saveSettings(updated);
return updated;
}
export async function resetToDefaultSettings(): Promise<Settings> {
const defaultPath = await fetchDefaultPath();
const defaultSettings = toNormalizedSettings({
...DEFAULT_SETTINGS,
downloadPath: defaultPath,
});
saveSettings(defaultSettings);
return defaultSettings;
}
export async function loadCustomFonts(): Promise<CustomFontOption[]> {
return normalizeCustomFonts(getSettings().customFonts);
}
export async function saveCustomFonts(customFonts: CustomFontOption[]): Promise<CustomFontOption[]> {
const normalizedFonts = normalizeCustomFonts(customFonts);
const settings = getSettings();
saveSettings({
...settings,
customFonts: normalizedFonts,
fontFamily: normalizeFontFamily(settings.fontFamily, normalizedFonts),
});
return normalizedFonts;
}
export function applyThemeMode(mode: "auto" | "light" | "dark"): void {
if (mode === "auto") {
const prefersDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
if (prefersDark) {
document.documentElement.classList.add("dark");
}
else {
document.documentElement.classList.remove("dark");
}
}
else if (mode === "dark") {
document.documentElement.classList.add("dark");
}
else {
document.documentElement.classList.remove("dark");
}
}
+577
View File
@@ -0,0 +1,577 @@
export const BASE_COLOR_NAMES = ["neutral", "stone", "zinc", "mauve", "olive", "mist", "taupe"] as const;
export const ACCENT_COLOR_NAMES = ["amber", "blue", "cyan", "emerald", "fuchsia", "green", "indigo", "lime", "orange", "pink", "purple", "red", "rose", "sky", "teal", "violet", "yellow"] as const;
export type BaseColorName = (typeof BASE_COLOR_NAMES)[number];
export type AccentColorName = (typeof ACCENT_COLOR_NAMES)[number];
export type ThemeName = BaseColorName | AccentColorName;
export interface Theme {
name: ThemeName;
label: string;
cssVars: {
light: Record<string, string>;
dark: Record<string, string>;
};
}
export interface BaseColor extends Theme {
name: BaseColorName;
}
const baseLightColors: Record<string, string> = {
background: "oklch(1 0 0)",
foreground: "oklch(0.145 0 0)",
card: "oklch(1 0 0)",
"card-foreground": "oklch(0.145 0 0)",
popover: "oklch(1 0 0)",
"popover-foreground": "oklch(0.145 0 0)",
primary: "oklch(0.205 0 0)",
"primary-foreground": "oklch(0.985 0 0)",
secondary: "oklch(0.97 0 0)",
"secondary-foreground": "oklch(0.205 0 0)",
muted: "oklch(0.97 0 0)",
"muted-foreground": "oklch(0.556 0 0)",
accent: "oklch(0.97 0 0)",
"accent-foreground": "oklch(0.205 0 0)",
destructive: "oklch(0.577 0.245 27.325)",
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)",
primary: "oklch(0.922 0 0)",
"primary-foreground": "oklch(0.205 0 0)",
secondary: "oklch(0.269 0 0)",
"secondary-foreground": "oklch(0.985 0 0)",
muted: "oklch(0.269 0 0)",
"muted-foreground": "oklch(0.708 0 0)",
accent: "oklch(0.269 0 0)",
"accent-foreground": "oklch(0.985 0 0)",
destructive: "oklch(0.704 0.191 22.216)",
border: "oklch(1 0 0 / 10%)",
input: "oklch(1 0 0 / 15%)",
ring: "oklch(0.556 0 0)",
};
function createBaseColor(name: BaseColorName, label: string, cssVars: Theme["cssVars"]): BaseColor {
return { name, label, cssVars };
}
export const baseColors: BaseColor[] = [
createBaseColor("neutral", "Neutral", {
light: baseLightColors,
dark: baseDarkColors,
}),
createBaseColor("stone", "Stone", {
light: {
background: "oklch(1 0 0)",
foreground: "oklch(0.147 0.004 49.25)",
card: "oklch(1 0 0)",
"card-foreground": "oklch(0.147 0.004 49.25)",
popover: "oklch(1 0 0)",
"popover-foreground": "oklch(0.147 0.004 49.25)",
primary: "oklch(0.216 0.006 56.043)",
"primary-foreground": "oklch(0.985 0.001 106.423)",
secondary: "oklch(0.97 0.001 106.424)",
"secondary-foreground": "oklch(0.216 0.006 56.043)",
muted: "oklch(0.97 0.001 106.424)",
"muted-foreground": "oklch(0.553 0.013 58.071)",
accent: "oklch(0.97 0.001 106.424)",
"accent-foreground": "oklch(0.216 0.006 56.043)",
destructive: "oklch(0.577 0.245 27.325)",
border: "oklch(0.923 0.003 48.717)",
input: "oklch(0.923 0.003 48.717)",
ring: "oklch(0.709 0.01 56.259)",
},
dark: {
background: "oklch(0.147 0.004 49.25)",
foreground: "oklch(0.985 0.001 106.423)",
card: "oklch(0.216 0.006 56.043)",
"card-foreground": "oklch(0.985 0.001 106.423)",
popover: "oklch(0.216 0.006 56.043)",
"popover-foreground": "oklch(0.985 0.001 106.423)",
primary: "oklch(0.923 0.003 48.717)",
"primary-foreground": "oklch(0.216 0.006 56.043)",
secondary: "oklch(0.268 0.007 34.298)",
"secondary-foreground": "oklch(0.985 0.001 106.423)",
muted: "oklch(0.268 0.007 34.298)",
"muted-foreground": "oklch(0.709 0.01 56.259)",
accent: "oklch(0.268 0.007 34.298)",
"accent-foreground": "oklch(0.985 0.001 106.423)",
destructive: "oklch(0.704 0.191 22.216)",
border: "oklch(1 0 0 / 10%)",
input: "oklch(1 0 0 / 15%)",
ring: "oklch(0.553 0.013 58.071)",
},
}),
createBaseColor("zinc", "Zinc", {
light: {
background: "oklch(1 0 0)",
foreground: "oklch(0.141 0.005 285.823)",
card: "oklch(1 0 0)",
"card-foreground": "oklch(0.141 0.005 285.823)",
popover: "oklch(1 0 0)",
"popover-foreground": "oklch(0.141 0.005 285.823)",
primary: "oklch(0.21 0.006 285.885)",
"primary-foreground": "oklch(0.985 0 0)",
secondary: "oklch(0.967 0.001 286.375)",
"secondary-foreground": "oklch(0.21 0.006 285.885)",
muted: "oklch(0.967 0.001 286.375)",
"muted-foreground": "oklch(0.552 0.016 285.938)",
accent: "oklch(0.967 0.001 286.375)",
"accent-foreground": "oklch(0.21 0.006 285.885)",
destructive: "oklch(0.577 0.245 27.325)",
border: "oklch(0.92 0.004 286.32)",
input: "oklch(0.92 0.004 286.32)",
ring: "oklch(0.705 0.015 286.067)",
},
dark: {
background: "oklch(0.141 0.005 285.823)",
foreground: "oklch(0.985 0 0)",
card: "oklch(0.21 0.006 285.885)",
"card-foreground": "oklch(0.985 0 0)",
popover: "oklch(0.21 0.006 285.885)",
"popover-foreground": "oklch(0.985 0 0)",
primary: "oklch(0.92 0.004 286.32)",
"primary-foreground": "oklch(0.21 0.006 285.885)",
secondary: "oklch(0.274 0.006 286.033)",
"secondary-foreground": "oklch(0.985 0 0)",
muted: "oklch(0.274 0.006 286.033)",
"muted-foreground": "oklch(0.705 0.015 286.067)",
accent: "oklch(0.274 0.006 286.033)",
"accent-foreground": "oklch(0.985 0 0)",
destructive: "oklch(0.704 0.191 22.216)",
border: "oklch(1 0 0 / 10%)",
input: "oklch(1 0 0 / 15%)",
ring: "oklch(0.552 0.016 285.938)",
},
}),
createBaseColor("mauve", "Mauve", {
light: {
background: "oklch(1 0 0)",
foreground: "oklch(0.145 0.008 326)",
card: "oklch(1 0 0)",
"card-foreground": "oklch(0.145 0.008 326)",
popover: "oklch(1 0 0)",
"popover-foreground": "oklch(0.145 0.008 326)",
primary: "oklch(0.212 0.019 322.12)",
"primary-foreground": "oklch(0.985 0 0)",
secondary: "oklch(0.96 0.003 325.6)",
"secondary-foreground": "oklch(0.212 0.019 322.12)",
muted: "oklch(0.96 0.003 325.6)",
"muted-foreground": "oklch(0.542 0.034 322.5)",
accent: "oklch(0.96 0.003 325.6)",
"accent-foreground": "oklch(0.212 0.019 322.12)",
destructive: "oklch(0.577 0.245 27.325)",
border: "oklch(0.922 0.005 325.62)",
input: "oklch(0.922 0.005 325.62)",
ring: "oklch(0.711 0.019 323.02)",
},
dark: {
background: "oklch(0.145 0.008 326)",
foreground: "oklch(0.985 0 0)",
card: "oklch(0.212 0.019 322.12)",
"card-foreground": "oklch(0.985 0 0)",
popover: "oklch(0.212 0.019 322.12)",
"popover-foreground": "oklch(0.985 0 0)",
primary: "oklch(0.922 0.005 325.62)",
"primary-foreground": "oklch(0.212 0.019 322.12)",
secondary: "oklch(0.263 0.024 320.12)",
"secondary-foreground": "oklch(0.985 0 0)",
muted: "oklch(0.263 0.024 320.12)",
"muted-foreground": "oklch(0.711 0.019 323.02)",
accent: "oklch(0.263 0.024 320.12)",
"accent-foreground": "oklch(0.985 0 0)",
destructive: "oklch(0.704 0.191 22.216)",
border: "oklch(1 0 0 / 10%)",
input: "oklch(1 0 0 / 15%)",
ring: "oklch(0.542 0.034 322.5)",
},
}),
createBaseColor("olive", "Olive", {
light: {
background: "oklch(1 0 0)",
foreground: "oklch(0.153 0.006 107.1)",
card: "oklch(1 0 0)",
"card-foreground": "oklch(0.153 0.006 107.1)",
popover: "oklch(1 0 0)",
"popover-foreground": "oklch(0.153 0.006 107.1)",
primary: "oklch(0.228 0.013 107.4)",
"primary-foreground": "oklch(0.988 0.003 106.5)",
secondary: "oklch(0.966 0.005 106.5)",
"secondary-foreground": "oklch(0.228 0.013 107.4)",
muted: "oklch(0.966 0.005 106.5)",
"muted-foreground": "oklch(0.58 0.031 107.3)",
accent: "oklch(0.966 0.005 106.5)",
"accent-foreground": "oklch(0.228 0.013 107.4)",
destructive: "oklch(0.577 0.245 27.325)",
border: "oklch(0.93 0.007 106.5)",
input: "oklch(0.93 0.007 106.5)",
ring: "oklch(0.737 0.021 106.9)",
},
dark: {
background: "oklch(0.153 0.006 107.1)",
foreground: "oklch(0.988 0.003 106.5)",
card: "oklch(0.228 0.013 107.4)",
"card-foreground": "oklch(0.988 0.003 106.5)",
popover: "oklch(0.228 0.013 107.4)",
"popover-foreground": "oklch(0.988 0.003 106.5)",
primary: "oklch(0.93 0.007 106.5)",
"primary-foreground": "oklch(0.228 0.013 107.4)",
secondary: "oklch(0.286 0.016 107.4)",
"secondary-foreground": "oklch(0.988 0.003 106.5)",
muted: "oklch(0.286 0.016 107.4)",
"muted-foreground": "oklch(0.737 0.021 106.9)",
accent: "oklch(0.286 0.016 107.4)",
"accent-foreground": "oklch(0.988 0.003 106.5)",
destructive: "oklch(0.704 0.191 22.216)",
border: "oklch(1 0 0 / 10%)",
input: "oklch(1 0 0 / 15%)",
ring: "oklch(0.58 0.031 107.3)",
},
}),
createBaseColor("mist", "Mist", {
light: {
background: "oklch(1 0 0)",
foreground: "oklch(0.148 0.004 228.8)",
card: "oklch(1 0 0)",
"card-foreground": "oklch(0.148 0.004 228.8)",
popover: "oklch(1 0 0)",
"popover-foreground": "oklch(0.148 0.004 228.8)",
primary: "oklch(0.218 0.008 223.9)",
"primary-foreground": "oklch(0.987 0.002 197.1)",
secondary: "oklch(0.963 0.002 197.1)",
"secondary-foreground": "oklch(0.218 0.008 223.9)",
muted: "oklch(0.963 0.002 197.1)",
"muted-foreground": "oklch(0.56 0.021 213.5)",
accent: "oklch(0.963 0.002 197.1)",
"accent-foreground": "oklch(0.218 0.008 223.9)",
destructive: "oklch(0.577 0.245 27.325)",
border: "oklch(0.925 0.005 214.3)",
input: "oklch(0.925 0.005 214.3)",
ring: "oklch(0.723 0.014 214.4)",
},
dark: {
background: "oklch(0.148 0.004 228.8)",
foreground: "oklch(0.987 0.002 197.1)",
card: "oklch(0.218 0.008 223.9)",
"card-foreground": "oklch(0.987 0.002 197.1)",
popover: "oklch(0.218 0.008 223.9)",
"popover-foreground": "oklch(0.987 0.002 197.1)",
primary: "oklch(0.925 0.005 214.3)",
"primary-foreground": "oklch(0.218 0.008 223.9)",
secondary: "oklch(0.275 0.011 216.9)",
"secondary-foreground": "oklch(0.987 0.002 197.1)",
muted: "oklch(0.275 0.011 216.9)",
"muted-foreground": "oklch(0.723 0.014 214.4)",
accent: "oklch(0.275 0.011 216.9)",
"accent-foreground": "oklch(0.987 0.002 197.1)",
destructive: "oklch(0.704 0.191 22.216)",
border: "oklch(1 0 0 / 10%)",
input: "oklch(1 0 0 / 15%)",
ring: "oklch(0.56 0.021 213.5)",
},
}),
createBaseColor("taupe", "Taupe", {
light: {
background: "oklch(1 0 0)",
foreground: "oklch(0.147 0.004 49.3)",
card: "oklch(1 0 0)",
"card-foreground": "oklch(0.147 0.004 49.3)",
popover: "oklch(1 0 0)",
"popover-foreground": "oklch(0.147 0.004 49.3)",
primary: "oklch(0.214 0.009 43.1)",
"primary-foreground": "oklch(0.986 0.002 67.8)",
secondary: "oklch(0.96 0.002 17.2)",
"secondary-foreground": "oklch(0.214 0.009 43.1)",
muted: "oklch(0.96 0.002 17.2)",
"muted-foreground": "oklch(0.547 0.021 43.1)",
accent: "oklch(0.96 0.002 17.2)",
"accent-foreground": "oklch(0.214 0.009 43.1)",
destructive: "oklch(0.577 0.245 27.325)",
border: "oklch(0.922 0.005 34.3)",
input: "oklch(0.922 0.005 34.3)",
ring: "oklch(0.714 0.014 41.2)",
},
dark: {
background: "oklch(0.147 0.004 49.3)",
foreground: "oklch(0.986 0.002 67.8)",
card: "oklch(0.214 0.009 43.1)",
"card-foreground": "oklch(0.986 0.002 67.8)",
popover: "oklch(0.214 0.009 43.1)",
"popover-foreground": "oklch(0.986 0.002 67.8)",
primary: "oklch(0.922 0.005 34.3)",
"primary-foreground": "oklch(0.214 0.009 43.1)",
secondary: "oklch(0.268 0.011 36.5)",
"secondary-foreground": "oklch(0.986 0.002 67.8)",
muted: "oklch(0.268 0.011 36.5)",
"muted-foreground": "oklch(0.714 0.014 41.2)",
accent: "oklch(0.268 0.011 36.5)",
"accent-foreground": "oklch(0.986 0.002 67.8)",
destructive: "oklch(0.704 0.191 22.216)",
border: "oklch(1 0 0 / 10%)",
input: "oklch(1 0 0 / 15%)",
ring: "oklch(0.547 0.021 43.1)",
},
}),
];
interface PrimaryColors {
light: {
primary: string;
"primary-foreground": string;
};
dark: {
primary: string;
"primary-foreground": string;
};
}
const primaryColors: Record<AccentColorName, PrimaryColors> = {
amber: {
light: {
primary: "oklch(0.555 0.163 48.998)",
"primary-foreground": "oklch(0.987 0.022 95.277)",
},
dark: {
primary: "oklch(0.473 0.137 46.201)",
"primary-foreground": "oklch(0.987 0.022 95.277)",
},
},
blue: {
light: {
primary: "oklch(0.488 0.243 264.376)",
"primary-foreground": "oklch(0.97 0.014 254.604)",
},
dark: {
primary: "oklch(0.424 0.199 265.638)",
"primary-foreground": "oklch(0.97 0.014 254.604)",
},
},
cyan: {
light: {
primary: "oklch(0.52 0.105 223.128)",
"primary-foreground": "oklch(0.984 0.019 200.873)",
},
dark: {
primary: "oklch(0.45 0.085 224.283)",
"primary-foreground": "oklch(0.984 0.019 200.873)",
},
},
emerald: {
light: {
primary: "oklch(0.508 0.118 165.612)",
"primary-foreground": "oklch(0.979 0.021 166.113)",
},
dark: {
primary: "oklch(0.432 0.095 166.913)",
"primary-foreground": "oklch(0.979 0.021 166.113)",
},
},
fuchsia: {
light: {
primary: "oklch(0.518 0.253 323.949)",
"primary-foreground": "oklch(0.977 0.017 320.058)",
},
dark: {
primary: "oklch(0.452 0.211 324.591)",
"primary-foreground": "oklch(0.977 0.017 320.058)",
},
},
green: {
light: {
primary: "oklch(0.527 0.154 150.069)",
"primary-foreground": "oklch(0.982 0.018 155.826)",
},
dark: {
primary: "oklch(0.448 0.119 151.328)",
"primary-foreground": "oklch(0.982 0.018 155.826)",
},
},
indigo: {
light: {
primary: "oklch(0.457 0.24 277.023)",
"primary-foreground": "oklch(0.962 0.018 272.314)",
},
dark: {
primary: "oklch(0.398 0.195 277.366)",
"primary-foreground": "oklch(0.962 0.018 272.314)",
},
},
lime: {
light: {
primary: "oklch(0.841 0.238 128.85)",
"primary-foreground": "oklch(0.405 0.101 131.063)",
},
dark: {
primary: "oklch(0.768 0.233 130.85)",
"primary-foreground": "oklch(0.405 0.101 131.063)",
},
},
orange: {
light: {
primary: "oklch(0.553 0.195 38.402)",
"primary-foreground": "oklch(0.98 0.016 73.684)",
},
dark: {
primary: "oklch(0.47 0.157 37.304)",
"primary-foreground": "oklch(0.98 0.016 73.684)",
},
},
pink: {
light: {
primary: "oklch(0.525 0.223 3.958)",
"primary-foreground": "oklch(0.971 0.014 343.198)",
},
dark: {
primary: "oklch(0.459 0.187 3.815)",
"primary-foreground": "oklch(0.971 0.014 343.198)",
},
},
purple: {
light: {
primary: "oklch(0.496 0.265 301.924)",
"primary-foreground": "oklch(0.977 0.014 308.299)",
},
dark: {
primary: "oklch(0.438 0.218 303.724)",
"primary-foreground": "oklch(0.977 0.014 308.299)",
},
},
red: {
light: {
primary: "oklch(0.505 0.213 27.518)",
"primary-foreground": "oklch(0.971 0.013 17.38)",
},
dark: {
primary: "oklch(0.444 0.177 26.899)",
"primary-foreground": "oklch(0.971 0.013 17.38)",
},
},
rose: {
light: {
primary: "oklch(0.514 0.222 16.935)",
"primary-foreground": "oklch(0.969 0.015 12.422)",
},
dark: {
primary: "oklch(0.455 0.188 13.697)",
"primary-foreground": "oklch(0.969 0.015 12.422)",
},
},
sky: {
light: {
primary: "oklch(0.5 0.134 242.749)",
"primary-foreground": "oklch(0.977 0.013 236.62)",
},
dark: {
primary: "oklch(0.443 0.11 240.79)",
"primary-foreground": "oklch(0.977 0.013 236.62)",
},
},
teal: {
light: {
primary: "oklch(0.511 0.096 186.391)",
"primary-foreground": "oklch(0.984 0.014 180.72)",
},
dark: {
primary: "oklch(0.437 0.078 188.216)",
"primary-foreground": "oklch(0.984 0.014 180.72)",
},
},
violet: {
light: {
primary: "oklch(0.491 0.27 292.581)",
"primary-foreground": "oklch(0.969 0.016 293.756)",
},
dark: {
primary: "oklch(0.432 0.232 292.759)",
"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)",
},
},
};
const coloredThemeLightColors: Record<string, string> = {
secondary: "oklch(0.967 0.001 286.375)",
"secondary-foreground": "oklch(0.21 0.006 285.885)",
};
const coloredThemeDarkColors: Record<string, string> = {
secondary: "oklch(0.274 0.006 286.033)",
"secondary-foreground": "oklch(0.985 0 0)",
};
function createAccentTheme(name: AccentColorName, label: string, primary: PrimaryColors): Theme {
return {
name,
label,
cssVars: {
light: { ...coloredThemeLightColors, ...primary.light },
dark: { ...coloredThemeDarkColors, ...primary.dark },
},
};
}
const accentThemes: Theme[] = [
createAccentTheme("amber", "Amber", primaryColors.amber),
createAccentTheme("blue", "Blue", primaryColors.blue),
createAccentTheme("cyan", "Cyan", primaryColors.cyan),
createAccentTheme("emerald", "Emerald", primaryColors.emerald),
createAccentTheme("fuchsia", "Fuchsia", primaryColors.fuchsia),
createAccentTheme("green", "Green", primaryColors.green),
createAccentTheme("indigo", "Indigo", primaryColors.indigo),
createAccentTheme("lime", "Lime", primaryColors.lime),
createAccentTheme("orange", "Orange", primaryColors.orange),
createAccentTheme("pink", "Pink", primaryColors.pink),
createAccentTheme("purple", "Purple", primaryColors.purple),
createAccentTheme("red", "Red", primaryColors.red),
createAccentTheme("rose", "Rose", primaryColors.rose),
createAccentTheme("sky", "Sky", primaryColors.sky),
createAccentTheme("teal", "Teal", primaryColors.teal),
createAccentTheme("violet", "Violet", primaryColors.violet),
createAccentTheme("yellow", "Yellow", primaryColors.yellow),
];
export function normalizeBaseColorName(baseColorName: unknown): BaseColorName {
return typeof baseColorName === "string" && BASE_COLOR_NAMES.includes(baseColorName as BaseColorName)
? baseColorName as BaseColorName
: "neutral";
}
const themesByBaseColor = Object.fromEntries(baseColors.map((baseColor) => [
baseColor.name,
[
baseColor,
...accentThemes.map((accentTheme) => ({
...accentTheme,
cssVars: {
light: { ...baseColor.cssVars.light, ...accentTheme.cssVars.light },
dark: { ...baseColor.cssVars.dark, ...accentTheme.cssVars.dark },
},
})),
],
])) as Record<BaseColorName, Theme[]>;
export function getThemesForBaseColor(baseColorName: unknown): Theme[] {
return themesByBaseColor[normalizeBaseColorName(baseColorName)];
}
export function normalizeThemeName(themeName: unknown, baseColorName: unknown): ThemeName {
const normalizedBaseColor = normalizeBaseColorName(baseColorName);
const availableThemes = getThemesForBaseColor(normalizedBaseColor);
return typeof themeName === "string" && availableThemes.some((theme) => theme.name === themeName)
? themeName as ThemeName
: normalizedBaseColor;
}
export const themes = getThemesForBaseColor("neutral");
export function applyTheme(themeName: unknown, baseColorName: unknown = "neutral") {
const normalizedBaseColor = normalizeBaseColorName(baseColorName);
const availableThemes = getThemesForBaseColor(normalizedBaseColor);
const normalizedTheme = normalizeThemeName(themeName, normalizedBaseColor);
const theme = availableThemes.find((candidate) => candidate.name === normalizedTheme) || availableThemes[0];
const root = document.documentElement;
const isDark = root.classList.contains("dark");
const vars = isDark ? theme.cssVars.dark : theme.cssVars.light;
Object.entries(vars).forEach(([key, value]) => {
root.style.setProperty(`--${key}`, value);
});
}
+45
View File
@@ -0,0 +1,45 @@
import { toast, type ExternalToast } from "sonner";
import { playSuccessSound, playErrorSound, playWarningSound, playInfoSound, } from "./audio";
import { logger } from "./logger";
import { getSettings } from "./settings";
const toastStyle = {
className: "font-mono lowercase",
};
const isSfxEnabled = () => getSettings().sfxEnabled;
export const toastWithSound = {
success: (message: string, data?: ExternalToast) => {
const msg = message.toLowerCase();
logger.success(msg);
if (isSfxEnabled())
playSuccessSound();
return toast.success(msg, { ...toastStyle, ...data });
},
error: (message: string, data?: ExternalToast) => {
const msg = message.toLowerCase();
logger.error(msg);
if (isSfxEnabled())
playErrorSound();
return toast.error(msg, { ...toastStyle, ...data });
},
warning: (message: string, data?: ExternalToast) => {
const msg = message.toLowerCase();
logger.warning(msg);
if (isSfxEnabled())
playWarningSound();
return toast.warning(msg, { ...toastStyle, ...data });
},
info: (message: string, data?: ExternalToast) => {
const msg = message.toLowerCase();
logger.info(msg);
if (isSfxEnabled())
playInfoSound();
return toast.info(msg, { ...toastStyle, ...data });
},
message: (message: string, data?: ExternalToast) => {
const msg = message.toLowerCase();
logger.info(msg);
if (isSfxEnabled())
playInfoSound();
return toast(msg, { ...toastStyle, ...data });
},
};
+40
View File
@@ -0,0 +1,40 @@
import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";
import { BrowserOpenURL } from "../../wailsjs/runtime/runtime";
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
export function sanitizePath(input: string, os: string): string {
if (os === "Windows") {
return input.replace(/[<>:"/\\|?*]/g, "_");
}
return input.replace(/\//g, "_");
}
export function joinPath(os: string, ...parts: string[]): string {
const sep = os === "Windows" ? "\\" : "/";
const filtered = parts.filter(Boolean);
if (filtered.length === 0)
return "";
const joined = filtered
.map((p, i) => {
if (i === 0) {
return p.replace(/[/\\]+$/g, "");
}
return p.replace(/^[/\\]+|[/\\]+$/g, "");
})
.filter(Boolean)
.join(sep);
return joined;
}
export function openExternal(url: string) {
if (!url)
return;
try {
BrowserOpenURL(url);
}
catch {
if (typeof window !== "undefined") {
window.open(url, "_blank", "noopener,noreferrer");
}
}
}
+86
View File
@@ -0,0 +1,86 @@
export function compareVersionNumbers(left: string, right: string) {
const toParts = (value: string) => value
.trim()
.replace(/^[^\d]*/, "")
.split(/[^0-9]+/)
.filter(Boolean)
.map((part) => Number.parseInt(part, 10));
const leftParts = toParts(left);
const rightParts = toParts(right);
const maxLength = Math.max(leftParts.length, rightParts.length);
for (let index = 0; index < maxLength; index += 1) {
const leftPart = leftParts[index] ?? 0;
const rightPart = rightParts[index] ?? 0;
if (leftPart > rightPart) {
return 1;
}
if (leftPart < rightPart) {
return -1;
}
}
return 0;
}
interface ParsedVersion {
core: number[];
prerelease: Array<number | string>;
}
const VERSION_IDENTIFIER_PATTERN = /^[0-9A-Za-z-]+$/;
function parseVersion(value: string): ParsedVersion | null {
let normalized = value.trim().replace(/^v/i, "");
if (!normalized)
return null;
const buildIndex = normalized.indexOf("+");
if (buildIndex >= 0) {
const build = normalized.slice(buildIndex + 1);
if (!build || build.split(".").some((identifier) => !VERSION_IDENTIFIER_PATTERN.test(identifier)))
return null;
normalized = normalized.slice(0, buildIndex);
}
const prereleaseIndex = normalized.indexOf("-");
const corePart = prereleaseIndex >= 0 ? normalized.slice(0, prereleaseIndex) : normalized;
const prereleasePart = prereleaseIndex >= 0 ? normalized.slice(prereleaseIndex + 1) : "";
const coreIdentifiers = corePart.split(".");
if (coreIdentifiers.length === 0 || coreIdentifiers.some((identifier) => !/^\d+$/.test(identifier)))
return null;
const core = coreIdentifiers.map(Number);
if (core.some((identifier) => !Number.isSafeInteger(identifier)))
return null;
if (prereleaseIndex >= 0 && (!prereleasePart || prereleasePart.split(".").some((identifier) => !VERSION_IDENTIFIER_PATTERN.test(identifier))))
return null;
const prerelease = prereleasePart
? prereleasePart.split(".").map((identifier) => /^\d+$/.test(identifier) ? Number(identifier) : identifier)
: [];
return { core, prerelease };
}
export function isNewerVersion(latestValue: string, currentValue: string): boolean {
const latest = parseVersion(latestValue);
const current = parseVersion(currentValue);
if (!latest || !current)
return false;
for (let i = 0; i < Math.max(latest.core.length, current.core.length); i++) {
const latestIdentifier = latest.core[i] ?? 0;
const currentIdentifier = current.core[i] ?? 0;
if (latestIdentifier !== currentIdentifier)
return latestIdentifier > currentIdentifier;
}
if (latest.prerelease.length === 0 || current.prerelease.length === 0)
return latest.prerelease.length === 0 && current.prerelease.length > 0;
for (let i = 0; i < Math.max(latest.prerelease.length, current.prerelease.length); i++) {
const latestIdentifier = latest.prerelease[i];
const currentIdentifier = current.prerelease[i];
if (latestIdentifier === undefined)
return false;
if (currentIdentifier === undefined)
return true;
if (latestIdentifier === currentIdentifier)
continue;
const latestIsNumber = typeof latestIdentifier === "number";
const currentIsNumber = typeof currentIdentifier === "number";
if (latestIsNumber && currentIsNumber)
return latestIdentifier > currentIdentifier;
if (latestIsNumber !== currentIsNumber)
return !latestIsNumber;
return latestIdentifier > currentIdentifier;
}
return false;
}
+9
View File
@@ -0,0 +1,9 @@
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import "./index.css";
import App from "./App.tsx";
import { Toaster } from "@/components/ui/sonner";
createRoot(document.getElementById("root")!).render(<StrictMode>
<App />
<Toaster position="bottom-left" duration={1000}/>
</StrictMode>);
+90
View File
@@ -0,0 +1,90 @@
export interface Thumb {
name: string;
url: string;
}
export interface AccountInfo {
name: string;
nick: string;
date: string;
followers_count: number;
friends_count: number;
profile_image: string;
statuses_count: number;
bio?: string;
banner?: string;
location?: string;
url?: string;
media_count?: number;
verified?: boolean;
blue_verified?: boolean;
protected?: boolean;
avatar_variants?: Thumb[];
banner_variants?: Thumb[];
}
export interface TimelineEntry {
url: string;
date: string;
tweet_id: string;
type: string;
is_retweet: boolean;
extension: string;
width: number;
height: number;
thumbnail?: string;
duration_ms?: number;
alt_text?: string;
content?: string;
view_count?: number;
bookmark_count?: number;
favorite_count?: number;
retweet_count?: number;
reply_count?: number;
quote_count?: number;
source?: string;
verified?: boolean;
original_filename?: string;
author_username?: string;
author_name?: string;
}
export interface ExtractMetadata {
new_entries: number;
page: number;
batch_size: number;
has_more: boolean;
cursor?: string;
completed?: boolean;
}
export interface TwitterResponse {
account_info: AccountInfo;
total_urls: number;
timeline: TimelineEntry[];
metadata: ExtractMetadata;
cursor?: string;
completed?: boolean;
}
export interface TimelineRequest {
username: string;
auth_token: string;
timeline_type: string;
batch_size: number;
page: number;
media_type: string;
retweets: boolean;
cursor?: string;
}
export interface DateRangeRequest {
username: string;
auth_token: string;
start_date: string;
end_date: string;
media_filter: string;
retweets: boolean;
}
export interface Settings {
downloadPath: string;
baseColor: string;
theme: string;
themeMode: "auto" | "light" | "dark";
sfxEnabled: boolean;
showUpdateNotifications: boolean;
}
+2
View File
@@ -0,0 +1,2 @@
/// <reference types="vite/client" />
declare const __APP_VERSION__: string;
+37
View File
@@ -0,0 +1,37 @@
{
"compilerOptions": {
"ignoreDeprecations": "6.0",
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "ES2022",
"useDefineForClassFields": true,
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"module": "ESNext",
"types": ["vite/client"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": false,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true,
/* Path Mapping */
"baseUrl": ".",
"paths": {
"@/*": [
"./src/*"
]
}
},
"include": ["src"]
}
+13
View File
@@ -0,0 +1,13 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
],
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
}
}
}
+26
View File
@@ -0,0 +1,26 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "ES2023",
"lib": ["ES2023"],
"module": "ESNext",
"types": ["node"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["vite.config.ts"]
}
+22
View File
@@ -0,0 +1,22 @@
import fs from "fs";
import path from "path";
import tailwindcss from "@tailwindcss/vite";
import react from "@vitejs/plugin-react";
import { defineConfig } from "vite";
const wailsJsonPath = path.resolve(__dirname, "../wails.json");
const wailsJson = JSON.parse(fs.readFileSync(wailsJsonPath, "utf-8"));
const appVersion = wailsJson.info.productVersion;
export default defineConfig({
plugins: [react(), tailwindcss()],
build: {
target: "safari15",
},
resolve: {
alias: {
"@": path.resolve(__dirname, "./src"),
},
},
define: {
__APP_VERSION__: JSON.stringify(appVersion),
},
});
+90
View File
@@ -0,0 +1,90 @@
// 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 CheckFoldersExist(arg1:string,arg2:Array<string>):Promise<Record<string, 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 ClearStoredAuthToken(arg1:string):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 DownloadProfileImage(arg1:main.DownloadProfileImageRequest):Promise<string>;
export function ExportAccountJSON(arg1:number,arg2:string):Promise<string>;
export function ExportAccountsTXT(arg1:Array<number>,arg2:string):Promise<string>;
export function ExportFailedLogs(arg1:string):Promise<string>;
export function ExtractDateRange(arg1:main.DateRangeRequest):Promise<string>;
export function ExtractTimeline(arg1:main.TimelineRequest):Promise<string>;
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 GetExifToolVersionStatus():Promise<backend.DependencyVersionStatus>;
export function GetExtractorVersionStatus():Promise<backend.ExtractorVersionStatus>;
export function GetFFmpegVersionStatus():Promise<backend.DependencyVersionStatus>;
export function GetFolderPath(arg1:string,arg2:string):Promise<string>;
export function GetGifsFolderPath(arg1:string,arg2:string):Promise<string>;
export function GetSavedAccountFromDB(arg1:string,arg2:string):Promise<string>;
export function GetStoredAuthToken(arg1:string):Promise<string>;
export function ImportAccountFromJSON():Promise<main.ImportAccountResponse>;
export function 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 SetStoredAuthToken(arg1:string,arg2:string):Promise<void>;
export function StopDownload():Promise<boolean>;
export function UpdateAccountGroup(arg1:number,arg2:string,arg3:string):Promise<void>;
+175
View File
@@ -0,0 +1,175 @@
// @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 CheckFoldersExist(arg1, arg2) {
return window['go']['main']['App']['CheckFoldersExist'](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 ClearStoredAuthToken(arg1) {
return window['go']['main']['App']['ClearStoredAuthToken'](arg1);
}
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 DownloadProfileImage(arg1) {
return window['go']['main']['App']['DownloadProfileImage'](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 ExportFailedLogs(arg1) {
return window['go']['main']['App']['ExportFailedLogs'](arg1);
}
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 GetExifToolVersionStatus() {
return window['go']['main']['App']['GetExifToolVersionStatus']();
}
export function GetExtractorVersionStatus() {
return window['go']['main']['App']['GetExtractorVersionStatus']();
}
export function GetFFmpegVersionStatus() {
return window['go']['main']['App']['GetFFmpegVersionStatus']();
}
export function GetFolderPath(arg1, arg2) {
return window['go']['main']['App']['GetFolderPath'](arg1, arg2);
}
export function GetGifsFolderPath(arg1, arg2) {
return window['go']['main']['App']['GetGifsFolderPath'](arg1, arg2);
}
export function GetSavedAccountFromDB(arg1, arg2) {
return window['go']['main']['App']['GetSavedAccountFromDB'](arg1, arg2);
}
export function GetStoredAuthToken(arg1) {
return window['go']['main']['App']['GetStoredAuthToken'](arg1);
}
export function ImportAccountFromJSON() {
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 SetStoredAuthToken(arg1, arg2) {
return window['go']['main']['App']['SetStoredAuthToken'](arg1, arg2);
}
export function StopDownload() {
return window['go']['main']['App']['StopDownload']();
}
export function UpdateAccountGroup(arg1, arg2, arg3) {
return window['go']['main']['App']['UpdateAccountGroup'](arg1, arg2, arg3);
}
+351
View File
@@ -0,0 +1,351 @@
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 class DependencyVersionStatus {
installed: boolean;
installed_version?: string;
latest_version?: string;
static createFrom(source: any = {}) {
return new DependencyVersionStatus(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.installed = source["installed"];
this.installed_version = source["installed_version"];
this.latest_version = source["latest_version"];
}
}
export class ExtractorVersionStatus {
installed: boolean;
installed_version?: string;
latest_version?: string;
static createFrom(source: any = {}) {
return new ExtractorVersionStatus(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.installed = source["installed"];
this.installed_version = source["installed_version"];
this.latest_version = source["latest_version"];
}
}
}
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;
concurrent_downloads?: number;
skip_existing: boolean;
delete_incomplete_files: boolean;
retry_attempts?: number;
download_speed_limit_kbps?: number;
download_delay_ms?: number;
download_delay_jitter_ms?: number;
proxy?: string;
static createFrom(source: any = {}) {
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.concurrent_downloads = source["concurrent_downloads"];
this.skip_existing = source["skip_existing"];
this.delete_incomplete_files = source["delete_incomplete_files"];
this.retry_attempts = source["retry_attempts"];
this.download_speed_limit_kbps = source["download_speed_limit_kbps"];
this.download_delay_ms = source["download_delay_ms"];
this.download_delay_jitter_ms = source["download_delay_jitter_ms"];
this.proxy = source["proxy"];
}
}
export class DownloadMediaResponse {
success: boolean;
cancelled: 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.cancelled = source["cancelled"];
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;
account_name?: 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"];
this.account_name = source["account_name"];
}
}
export class DownloadMediaWithMetadataRequest {
items: MediaItemRequest[];
output_dir: string;
username: string;
concurrent_downloads?: number;
skip_existing: boolean;
delete_incomplete_files: boolean;
retry_attempts?: number;
download_speed_limit_kbps?: number;
download_delay_ms?: number;
download_delay_jitter_ms?: number;
proxy?: string;
filename_template?: string;
folder_template?: string;
auto_convert_gifs?: boolean;
gif_quality?: string;
gif_resolution?: string;
static createFrom(source: any = {}) {
return new DownloadMediaWithMetadataRequest(source);
}
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.concurrent_downloads = source["concurrent_downloads"];
this.skip_existing = source["skip_existing"];
this.delete_incomplete_files = source["delete_incomplete_files"];
this.retry_attempts = source["retry_attempts"];
this.download_speed_limit_kbps = source["download_speed_limit_kbps"];
this.download_delay_ms = source["download_delay_ms"];
this.download_delay_jitter_ms = source["download_delay_jitter_ms"];
this.proxy = source["proxy"];
this.filename_template = source["filename_template"];
this.folder_template = source["folder_template"];
this.auto_convert_gifs = source["auto_convert_gifs"];
this.gif_quality = source["gif_quality"];
this.gif_resolution = source["gif_resolution"];
}
convertValues(a: any, classs: any, asMap: boolean = false): any {
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 DownloadProfileImageRequest {
url: string;
output_dir: string;
username: string;
kind: string;
proxy?: string;
static createFrom(source: any = {}) {
return new DownloadProfileImageRequest(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.url = source["url"];
this.output_dir = source["output_dir"];
this.username = source["username"];
this.kind = source["kind"];
this.proxy = source["proxy"];
}
}
export class ImportAccountResponse {
success: boolean;
username: string;
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;
include_photos: boolean;
include_videos: boolean;
include_gifs: boolean;
include_text: boolean;
video_quality?: string;
image_size?: string;
static createFrom(source: any = {}) {
return new TimelineRequest(source);
}
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"];
this.include_photos = source["include_photos"];
this.include_videos = source["include_videos"];
this.include_gifs = source["include_gifs"];
this.include_text = source["include_text"];
this.video_quality = source["video_quality"];
this.image_size = source["image_size"];
}
}
}
+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>;
Loaded 100 of 107 files, more files were not shown because too many files have changed in this diff. Show more