mirror of
https://github.com/Alvin-Zilverstand/Twitter-X-Media-Batch-Downloader.git
synced 2026-11-24 15:23:11 +01:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e67d09a248 | ||
|
|
84b067ebd4 | ||
|
|
eba8288a4e | ||
|
|
4794fac099 | ||
|
|
8cbf7c979b | ||
|
|
de402efe6b | ||
|
|
2f51a118e4 | ||
|
|
b611632c30 | ||
|
|
30bcf3db9f | ||
|
|
ada11f086e | ||
|
|
b4266cb7fa | ||
|
|
aa87cce538 | ||
|
|
2d913d987f | ||
|
|
3abba4cc59 |
No files matched your search
@@ -0,0 +1 @@
|
|||||||
|
ko_fi: afkarxyz
|
||||||
@@ -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
|
||||||
@@ -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.
|
||||||
@@ -0,0 +1,344 @@
|
|||||||
|
name: Build Multi-Platform
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
tags:
|
||||||
|
- 'v*'
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
env:
|
||||||
|
NODE_VERSION: '24'
|
||||||
|
PNPM_VERSION: '10'
|
||||||
|
APP_NAME: TwitterXMediaBatchDownloader
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build-windows:
|
||||||
|
name: Build Windows
|
||||||
|
runs-on: windows-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout code
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Setup Go
|
||||||
|
uses: actions/setup-go@v5
|
||||||
|
with:
|
||||||
|
go-version-file: go.mod
|
||||||
|
|
||||||
|
- name: Setup Node.js
|
||||||
|
uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: ${{ env.NODE_VERSION }}
|
||||||
|
|
||||||
|
- name: Install pnpm
|
||||||
|
uses: pnpm/action-setup@v4
|
||||||
|
with:
|
||||||
|
version: ${{ env.PNPM_VERSION }}
|
||||||
|
|
||||||
|
- name: Get pnpm store directory
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
echo "STORE_PATH=$(pnpm store path --silent)" >> $GITHUB_ENV
|
||||||
|
|
||||||
|
- name: Setup pnpm cache
|
||||||
|
continue-on-error: true
|
||||||
|
uses: actions/cache@v4
|
||||||
|
with:
|
||||||
|
path: ${{ env.STORE_PATH }}
|
||||||
|
key: ${{ runner.os }}-pnpm-store-${{ hashFiles('frontend/pnpm-lock.yaml') }}
|
||||||
|
restore-keys: |
|
||||||
|
${{ runner.os }}-pnpm-store-
|
||||||
|
|
||||||
|
- name: Install Wails CLI
|
||||||
|
run: go install github.com/wailsapp/wails/v2/cmd/wails@latest
|
||||||
|
|
||||||
|
- name: Install frontend dependencies
|
||||||
|
working-directory: frontend
|
||||||
|
run: |
|
||||||
|
pnpm install
|
||||||
|
pnpm run generate-icon
|
||||||
|
|
||||||
|
- name: Install UPX
|
||||||
|
run: choco install upx -y
|
||||||
|
|
||||||
|
- name: Build application
|
||||||
|
run: wails build -platform windows/amd64
|
||||||
|
|
||||||
|
- name: Compress with UPX
|
||||||
|
run: upx --best --lzma "build\bin\${{ env.APP_NAME }}.exe"
|
||||||
|
|
||||||
|
- name: Prepare artifacts
|
||||||
|
shell: pwsh
|
||||||
|
run: |
|
||||||
|
New-Item -ItemType Directory -Force -Path dist | Out-Null
|
||||||
|
Copy-Item -Path "build\bin\${{ env.APP_NAME }}.exe" -Destination "dist\${{ env.APP_NAME }}.exe"
|
||||||
|
|
||||||
|
- name: Upload artifacts
|
||||||
|
uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: windows-portable
|
||||||
|
path: dist/${{ env.APP_NAME }}.exe
|
||||||
|
retention-days: 7
|
||||||
|
|
||||||
|
build-macos:
|
||||||
|
name: Build macOS
|
||||||
|
runs-on: macos-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout code
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Setup Go
|
||||||
|
uses: actions/setup-go@v5
|
||||||
|
with:
|
||||||
|
go-version-file: go.mod
|
||||||
|
|
||||||
|
- name: Setup Node.js
|
||||||
|
uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: ${{ env.NODE_VERSION }}
|
||||||
|
|
||||||
|
- name: Install pnpm
|
||||||
|
uses: pnpm/action-setup@v4
|
||||||
|
with:
|
||||||
|
version: ${{ env.PNPM_VERSION }}
|
||||||
|
|
||||||
|
- name: Get pnpm store directory
|
||||||
|
run: |
|
||||||
|
echo "STORE_PATH=$(pnpm store path --silent)" >> $GITHUB_ENV
|
||||||
|
|
||||||
|
- name: Setup pnpm cache
|
||||||
|
continue-on-error: true
|
||||||
|
uses: actions/cache@v4
|
||||||
|
with:
|
||||||
|
path: ${{ env.STORE_PATH }}
|
||||||
|
key: ${{ runner.os }}-pnpm-store-${{ hashFiles('frontend/pnpm-lock.yaml') }}
|
||||||
|
restore-keys: |
|
||||||
|
${{ runner.os }}-pnpm-store-
|
||||||
|
|
||||||
|
- name: Install Wails CLI
|
||||||
|
run: go install github.com/wailsapp/wails/v2/cmd/wails@latest
|
||||||
|
|
||||||
|
- name: Install frontend dependencies
|
||||||
|
working-directory: frontend
|
||||||
|
run: |
|
||||||
|
pnpm install
|
||||||
|
pnpm run generate-icon
|
||||||
|
|
||||||
|
- name: Build application
|
||||||
|
run: wails build -platform darwin/universal
|
||||||
|
|
||||||
|
- name: Create DMG
|
||||||
|
run: |
|
||||||
|
mkdir -p dist
|
||||||
|
brew install create-dmg || true
|
||||||
|
|
||||||
|
create-dmg \
|
||||||
|
--volname "${{ env.APP_NAME }}" \
|
||||||
|
--window-pos 200 120 \
|
||||||
|
--window-size 600 400 \
|
||||||
|
--icon-size 100 \
|
||||||
|
--icon "${{ env.APP_NAME }}.app" 175 120 \
|
||||||
|
--hide-extension "${{ env.APP_NAME }}.app" \
|
||||||
|
--app-drop-link 425 120 \
|
||||||
|
"dist/${{ env.APP_NAME }}.dmg" \
|
||||||
|
"build/bin/${{ env.APP_NAME }}.app" || \
|
||||||
|
hdiutil create -volname "${{ env.APP_NAME }}" -srcfolder "build/bin/${{ env.APP_NAME }}.app" -ov -format UDZO "dist/${{ env.APP_NAME }}.dmg"
|
||||||
|
|
||||||
|
- name: Upload artifacts
|
||||||
|
uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: macos-portable
|
||||||
|
path: dist/${{ env.APP_NAME }}.dmg
|
||||||
|
retention-days: 7
|
||||||
|
|
||||||
|
build-linux:
|
||||||
|
name: Build Linux
|
||||||
|
runs-on: ubuntu-24.04
|
||||||
|
steps:
|
||||||
|
- name: Checkout code
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Setup Go
|
||||||
|
uses: actions/setup-go@v5
|
||||||
|
with:
|
||||||
|
go-version-file: go.mod
|
||||||
|
|
||||||
|
- name: Setup Node.js
|
||||||
|
uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: ${{ env.NODE_VERSION }}
|
||||||
|
|
||||||
|
- name: Install pnpm
|
||||||
|
uses: pnpm/action-setup@v4
|
||||||
|
with:
|
||||||
|
version: ${{ env.PNPM_VERSION }}
|
||||||
|
|
||||||
|
- name: Get pnpm store directory
|
||||||
|
run: |
|
||||||
|
echo "STORE_PATH=$(pnpm store path --silent)" >> $GITHUB_ENV
|
||||||
|
|
||||||
|
- name: Setup pnpm cache
|
||||||
|
continue-on-error: true
|
||||||
|
uses: actions/cache@v4
|
||||||
|
with:
|
||||||
|
path: ${{ env.STORE_PATH }}
|
||||||
|
key: ${{ runner.os }}-pnpm-store-${{ hashFiles('frontend/pnpm-lock.yaml') }}
|
||||||
|
restore-keys: |
|
||||||
|
${{ runner.os }}-pnpm-store-
|
||||||
|
|
||||||
|
- name: Install dependencies
|
||||||
|
run: |
|
||||||
|
sudo apt-get update
|
||||||
|
sudo apt-get install -y libgtk-3-dev libwebkit2gtk-4.1-dev libfuse2 imagemagick upx-ucl
|
||||||
|
sudo ln -sf /usr/lib/x86_64-linux-gnu/pkgconfig/webkit2gtk-4.1.pc /usr/lib/x86_64-linux-gnu/pkgconfig/webkit2gtk-4.0.pc
|
||||||
|
|
||||||
|
- name: Install Wails CLI
|
||||||
|
run: go install github.com/wailsapp/wails/v2/cmd/wails@latest
|
||||||
|
|
||||||
|
- name: Install frontend dependencies
|
||||||
|
working-directory: frontend
|
||||||
|
run: |
|
||||||
|
pnpm install
|
||||||
|
pnpm run generate-icon
|
||||||
|
|
||||||
|
- name: Build application
|
||||||
|
run: wails build -platform linux/amd64
|
||||||
|
|
||||||
|
- name: Compress with UPX
|
||||||
|
run: upx --best --lzma "build/bin/${{ env.APP_NAME }}"
|
||||||
|
|
||||||
|
- name: Cache appimagetool
|
||||||
|
id: cache-appimagetool
|
||||||
|
uses: actions/cache@v4
|
||||||
|
with:
|
||||||
|
path: appimagetool
|
||||||
|
key: appimagetool-x86_64-v2
|
||||||
|
|
||||||
|
- name: Download appimagetool
|
||||||
|
if: steps.cache-appimagetool.outputs.cache-hit != 'true'
|
||||||
|
run: |
|
||||||
|
wget --timeout=30 --tries=5 --retry-connrefused --waitretry=5 -O appimagetool "https://github.com/AppImage/appimagetool/releases/download/continuous/appimagetool-x86_64.AppImage" || \
|
||||||
|
wget --timeout=30 --tries=5 --retry-connrefused --waitretry=5 -O appimagetool "https://github.com/AppImage/appimagetool/releases/download/1.9.1/appimagetool-x86_64.AppImage"
|
||||||
|
|
||||||
|
- name: Make appimagetool executable
|
||||||
|
run: chmod +x appimagetool
|
||||||
|
|
||||||
|
- name: Create AppImage
|
||||||
|
run: |
|
||||||
|
mkdir -p AppDir/usr/bin
|
||||||
|
mkdir -p AppDir/usr/share/applications
|
||||||
|
mkdir -p AppDir/usr/share/icons/hicolor/256x256/apps
|
||||||
|
|
||||||
|
cp "build/bin/${{ env.APP_NAME }}" AppDir/usr/bin/
|
||||||
|
|
||||||
|
cat > AppDir/twitterxmediabatchdownloader.desktop << 'EOF'
|
||||||
|
[Desktop Entry]
|
||||||
|
Name=Twitter/X Media Batch Downloader
|
||||||
|
Exec=TwitterXMediaBatchDownloader
|
||||||
|
Icon=twitterxmediabatchdownloader
|
||||||
|
Type=Application
|
||||||
|
Categories=Network;Utility;
|
||||||
|
Comment=Download Twitter/X media in batches
|
||||||
|
EOF
|
||||||
|
|
||||||
|
cp AppDir/twitterxmediabatchdownloader.desktop AppDir/usr/share/applications/
|
||||||
|
|
||||||
|
if [ -f "build/appicon.png" ]; then
|
||||||
|
convert build/appicon.png -resize 256x256 AppDir/twitterxmediabatchdownloader.png
|
||||||
|
elif [ -f "frontend/public/icon.svg" ]; then
|
||||||
|
convert -background none -size 256x256 frontend/public/icon.svg AppDir/twitterxmediabatchdownloader.png
|
||||||
|
else
|
||||||
|
echo "Warning: No icon found, building without icon"
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ -f "AppDir/twitterxmediabatchdownloader.png" ]; then
|
||||||
|
cp AppDir/twitterxmediabatchdownloader.png AppDir/usr/share/icons/hicolor/256x256/apps/
|
||||||
|
cp AppDir/twitterxmediabatchdownloader.png AppDir/.DirIcon
|
||||||
|
fi
|
||||||
|
|
||||||
|
cat > AppDir/AppRun << 'EOF'
|
||||||
|
#!/bin/sh
|
||||||
|
SELF=$(readlink -f "$0")
|
||||||
|
HERE=${SELF%/*}
|
||||||
|
export PATH="${HERE}/usr/bin/:${PATH}"
|
||||||
|
export LD_LIBRARY_PATH="${HERE}/usr/lib/:${LD_LIBRARY_PATH}"
|
||||||
|
exec "${HERE}/usr/bin/TwitterXMediaBatchDownloader" "$@"
|
||||||
|
EOF
|
||||||
|
chmod +x AppDir/AppRun
|
||||||
|
|
||||||
|
mkdir -p dist
|
||||||
|
ARCH=x86_64 ./appimagetool --no-appstream AppDir "dist/${{ env.APP_NAME }}.AppImage"
|
||||||
|
|
||||||
|
- name: Upload artifacts
|
||||||
|
uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: linux-portable
|
||||||
|
path: dist/${{ env.APP_NAME }}.AppImage
|
||||||
|
retention-days: 7
|
||||||
|
|
||||||
|
create-release:
|
||||||
|
name: Create Release
|
||||||
|
needs: [build-windows, build-macos, build-linux]
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
if: startsWith(github.ref, 'refs/tags/v')
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
|
steps:
|
||||||
|
- name: Checkout code
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Download all artifacts
|
||||||
|
uses: actions/download-artifact@v4
|
||||||
|
with:
|
||||||
|
path: artifacts
|
||||||
|
|
||||||
|
- name: Display structure of downloaded files
|
||||||
|
run: ls -R artifacts
|
||||||
|
|
||||||
|
- name: Create Release
|
||||||
|
uses: softprops/action-gh-release@v2
|
||||||
|
with:
|
||||||
|
draft: true
|
||||||
|
prerelease: false
|
||||||
|
generate_release_notes: false
|
||||||
|
body: |
|
||||||
|
## Changelog
|
||||||
|
|
||||||
|
## Downloads
|
||||||
|
|
||||||
|
- `TwitterXMediaBatchDownloader.exe` - Windows
|
||||||
|
- `TwitterXMediaBatchDownloader.dmg` - macOS
|
||||||
|
- `TwitterXMediaBatchDownloader.AppImage` - Linux
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary><b>Linux Requirements</b></summary>
|
||||||
|
|
||||||
|
The AppImage requires `webkit2gtk-4.1` to be installed on your system:
|
||||||
|
|
||||||
|
**Ubuntu/Debian:**
|
||||||
|
```bash
|
||||||
|
sudo apt install libwebkit2gtk-4.1-0
|
||||||
|
```
|
||||||
|
|
||||||
|
**Arch Linux:**
|
||||||
|
```bash
|
||||||
|
sudo pacman -S webkit2gtk-4.1
|
||||||
|
```
|
||||||
|
|
||||||
|
**Fedora:**
|
||||||
|
```bash
|
||||||
|
sudo dnf install webkit2gtk4.1
|
||||||
|
```
|
||||||
|
|
||||||
|
After installing the dependency, make the AppImage executable:
|
||||||
|
```bash
|
||||||
|
chmod +x TwitterXMediaBatchDownloader.AppImage
|
||||||
|
./TwitterXMediaBatchDownloader.AppImage
|
||||||
|
```
|
||||||
|
|
||||||
|
</details>
|
||||||
|
files: |
|
||||||
|
artifacts/windows-portable/${{ env.APP_NAME }}.exe
|
||||||
|
artifacts/macos-portable/${{ env.APP_NAME }}.dmg
|
||||||
|
artifacts/linux-portable/${{ env.APP_NAME }}.AppImage
|
||||||
|
env:
|
||||||
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
+1
-4
@@ -1,6 +1,5 @@
|
|||||||
# Wails Build
|
# Wails Build
|
||||||
build/
|
build/
|
||||||
backend/bin/
|
|
||||||
*.exe
|
*.exe
|
||||||
*.dll
|
*.dll
|
||||||
*.dylib
|
*.dylib
|
||||||
@@ -57,6 +56,4 @@ temp/
|
|||||||
*.bak
|
*.bak
|
||||||
*.old
|
*.old
|
||||||
|
|
||||||
# Build notes (optional - uncomment if you don't want to commit)
|
*.bat
|
||||||
# BUILD_NOTES.md
|
|
||||||
build.txt
|
|
||||||
@@ -1,25 +1,18 @@
|
|||||||
[](https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases)
|
# Twitter/X Media Batch Downloader
|
||||||
|
|
||||||

|
A GUI tool to download original-quality images and videos from Twitter/X accounts.
|
||||||
|
|
||||||
<div align="center">
|
|
||||||
|
|
||||||
A GUI tool to download original-quality images and videos from Twitter/X accounts, powered by gallery-dl by @mikf
|
|
||||||
|
|
||||||

|

|
||||||

|

|
||||||

|

|
||||||
|
|
||||||
</div>
|
### [Download](https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases)
|
||||||
|
|
||||||
### [Download](https://github.com/afkarxyz/SpotiFLAC/releases)
|

|
||||||
|
|
||||||
- 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)
|
||||||
- The **Chrome extension** version is now available, please install it [**here**](https://www.patreon.com/posts/chrome-extension-139296789)
|
|
||||||
|
|
||||||
## Screenshot
|
|
||||||
|
|
||||||

|
- To install the Chrome extension version, click [**here**](https://chromewebstore.google.com/detail/cboceolmgkoobpfjiojkigmihijfgmdo)
|
||||||
|
|
||||||
## How to Obtain Auth Token
|
## How to Obtain Auth Token
|
||||||
|
|
||||||
@@ -27,7 +20,7 @@ A GUI tool to download original-quality images and videos from Twitter/X account
|
|||||||
> - I suggest not using the **main account** to obtain the token.
|
> - I suggest not using the **main account** to obtain the token.
|
||||||
> - You can use https://temp-mail.io to register a Twitter account.
|
> - 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.**
|
> - 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.
|
> - If too many media files are fetched, it may trigger a **rate limit**, and the media retrieval will fail.
|
||||||
|
|
||||||
### [Video Tutorial](https://www.patreon.com/posts/how-to-obtain-127206894)
|
### [Video Tutorial](https://www.patreon.com/posts/how-to-obtain-127206894)
|
||||||
|
|
||||||
@@ -35,13 +28,7 @@ A GUI tool to download original-quality images and videos from Twitter/X account
|
|||||||
2. Log into your account
|
2. Log into your account
|
||||||
3. Open the Developer Tools by pressing <kbd>F12</kbd>
|
3. Open the Developer Tools by pressing <kbd>F12</kbd>
|
||||||
4. Navigate to the **Application** tab, then select **Storage → Cookies**
|
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
|
6. Do not log out of your account, as a new `auth_token` will be generated by Twitter
|
||||||
|
|
||||||
> X.com Auth Token Grabber
|
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||
> Developer Tools
|
|
||||||
|
|
||||||

|

|
||||||
@@ -3,6 +3,7 @@ package main
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"twitterxmediabatchdownloader/backend"
|
"twitterxmediabatchdownloader/backend"
|
||||||
@@ -10,42 +11,36 @@ import (
|
|||||||
"github.com/wailsapp/wails/v2/pkg/runtime"
|
"github.com/wailsapp/wails/v2/pkg/runtime"
|
||||||
)
|
)
|
||||||
|
|
||||||
// App struct
|
|
||||||
type App struct {
|
type App struct {
|
||||||
ctx context.Context
|
ctx context.Context
|
||||||
downloadCtx context.Context
|
downloadCtx context.Context
|
||||||
downloadCancel context.CancelFunc
|
downloadCancel context.CancelFunc
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewApp creates a new App application struct
|
|
||||||
func NewApp() *App {
|
func NewApp() *App {
|
||||||
return &App{}
|
return &App{}
|
||||||
}
|
}
|
||||||
|
|
||||||
// startup is called when the app starts. The context is saved
|
|
||||||
// so we can call the runtime methods
|
|
||||||
func (a *App) startup(ctx context.Context) {
|
func (a *App) startup(ctx context.Context) {
|
||||||
a.ctx = ctx
|
a.ctx = ctx
|
||||||
// Initialize database
|
|
||||||
backend.InitDB()
|
if err := backend.InitDB(); err != nil {
|
||||||
// Kill any leftover extractor processes from previous session
|
runtime.LogErrorf(ctx, "failed to initialize database: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
backend.KillAllExtractorProcesses()
|
backend.KillAllExtractorProcesses()
|
||||||
}
|
}
|
||||||
|
|
||||||
// shutdown is called when the app is closing
|
|
||||||
func (a *App) shutdown(ctx context.Context) {
|
func (a *App) shutdown(ctx context.Context) {
|
||||||
backend.CloseDB()
|
backend.CloseDB()
|
||||||
// Kill any running extractor processes
|
|
||||||
backend.KillAllExtractorProcesses()
|
backend.KillAllExtractorProcesses()
|
||||||
}
|
}
|
||||||
|
|
||||||
// CleanupExtractorProcesses kills all running extractor processes
|
|
||||||
// Can be called from frontend when user wants to stop/reset
|
|
||||||
func (a *App) CleanupExtractorProcesses() {
|
func (a *App) CleanupExtractorProcesses() {
|
||||||
backend.KillAllExtractorProcesses()
|
backend.KillAllExtractorProcesses()
|
||||||
}
|
}
|
||||||
|
|
||||||
// TimelineRequest represents the request structure for timeline extraction
|
|
||||||
type TimelineRequest struct {
|
type TimelineRequest struct {
|
||||||
Username string `json:"username"`
|
Username string `json:"username"`
|
||||||
AuthToken string `json:"auth_token"`
|
AuthToken string `json:"auth_token"`
|
||||||
@@ -54,10 +49,9 @@ type TimelineRequest struct {
|
|||||||
Page int `json:"page"`
|
Page int `json:"page"`
|
||||||
MediaType string `json:"media_type"`
|
MediaType string `json:"media_type"`
|
||||||
Retweets bool `json:"retweets"`
|
Retweets bool `json:"retweets"`
|
||||||
Cursor string `json:"cursor,omitempty"` // Resume from this cursor position
|
Cursor string `json:"cursor,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// DateRangeRequest represents the request structure for date range extraction
|
|
||||||
type DateRangeRequest struct {
|
type DateRangeRequest struct {
|
||||||
Username string `json:"username"`
|
Username string `json:"username"`
|
||||||
AuthToken string `json:"auth_token"`
|
AuthToken string `json:"auth_token"`
|
||||||
@@ -67,9 +61,8 @@ type DateRangeRequest struct {
|
|||||||
Retweets bool `json:"retweets"`
|
Retweets bool `json:"retweets"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// ExtractTimeline extracts media from user timeline
|
|
||||||
func (a *App) ExtractTimeline(req TimelineRequest) (string, error) {
|
func (a *App) ExtractTimeline(req TimelineRequest) (string, error) {
|
||||||
// Username not required for bookmarks only
|
|
||||||
if req.Username == "" && req.TimelineType != "bookmarks" {
|
if req.Username == "" && req.TimelineType != "bookmarks" {
|
||||||
return "", fmt.Errorf("username is required")
|
return "", fmt.Errorf("username is required")
|
||||||
}
|
}
|
||||||
@@ -101,7 +94,6 @@ func (a *App) ExtractTimeline(req TimelineRequest) (string, error) {
|
|||||||
return string(jsonData), nil
|
return string(jsonData), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ExtractDateRange extracts media based on date range
|
|
||||||
func (a *App) ExtractDateRange(req DateRangeRequest) (string, error) {
|
func (a *App) ExtractDateRange(req DateRangeRequest) (string, error) {
|
||||||
if req.Username == "" {
|
if req.Username == "" {
|
||||||
return "", fmt.Errorf("username is required")
|
return "", fmt.Errorf("username is required")
|
||||||
@@ -138,13 +130,11 @@ func (a *App) ExtractDateRange(req DateRangeRequest) (string, error) {
|
|||||||
return string(jsonData), nil
|
return string(jsonData), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// OpenFolder opens a folder in the file explorer
|
|
||||||
func (a *App) OpenFolder(path string) error {
|
func (a *App) OpenFolder(path string) error {
|
||||||
if path == "" {
|
if path == "" {
|
||||||
return fmt.Errorf("path is required")
|
return fmt.Errorf("path is required")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Clean the path to use correct separators for the OS
|
|
||||||
cleanPath := filepath.Clean(path)
|
cleanPath := filepath.Clean(path)
|
||||||
|
|
||||||
err := backend.OpenFolderInExplorer(cleanPath)
|
err := backend.OpenFolderInExplorer(cleanPath)
|
||||||
@@ -155,60 +145,83 @@ func (a *App) OpenFolder(path string) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// SelectFolder opens a folder selection dialog and returns the selected path
|
|
||||||
func (a *App) SelectFolder(defaultPath string) (string, error) {
|
func (a *App) SelectFolder(defaultPath string) (string, error) {
|
||||||
return backend.SelectFolderDialog(a.ctx, defaultPath)
|
return backend.SelectFolderDialog(a.ctx, defaultPath)
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetDefaults returns the default configuration
|
|
||||||
func (a *App) GetDefaults() map[string]string {
|
func (a *App) GetDefaults() map[string]string {
|
||||||
return map[string]string{
|
return map[string]string{
|
||||||
"downloadPath": backend.GetDefaultDownloadPath(),
|
"downloadPath": backend.GetDefaultDownloadPath(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Quit closes the application
|
func (a *App) 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() {
|
func (a *App) Quit() {
|
||||||
panic("quit")
|
panic("quit")
|
||||||
}
|
}
|
||||||
|
|
||||||
// DownloadMediaRequest represents the request for downloading media (legacy)
|
|
||||||
type DownloadMediaRequest struct {
|
type DownloadMediaRequest struct {
|
||||||
URLs []string `json:"urls"`
|
URLs []string `json:"urls"`
|
||||||
OutputDir string `json:"output_dir"`
|
OutputDir string `json:"output_dir"`
|
||||||
Username string `json:"username"`
|
Username string `json:"username"`
|
||||||
|
Proxy string `json:"proxy,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// MediaItemRequest represents a media item with metadata
|
|
||||||
type MediaItemRequest struct {
|
type MediaItemRequest struct {
|
||||||
URL string `json:"url"`
|
URL string `json:"url"`
|
||||||
Date string `json:"date"`
|
Date string `json:"date"`
|
||||||
TweetID backend.TweetIDString `json:"tweet_id"`
|
TweetID backend.TweetIDString `json:"tweet_id"`
|
||||||
Type string `json:"type"`
|
Type string `json:"type"`
|
||||||
Content string `json:"content,omitempty"` // Tweet text content (for text-only tweets)
|
Content string `json:"content,omitempty"`
|
||||||
|
OriginalFilename string `json:"original_filename,omitempty"`
|
||||||
|
AuthorUsername string `json:"author_username,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// DownloadMediaWithMetadataRequest represents the request for downloading media with metadata
|
|
||||||
type DownloadMediaWithMetadataRequest struct {
|
type DownloadMediaWithMetadataRequest struct {
|
||||||
Items []MediaItemRequest `json:"items"`
|
Items []MediaItemRequest `json:"items"`
|
||||||
OutputDir string `json:"output_dir"`
|
OutputDir string `json:"output_dir"`
|
||||||
Username string `json:"username"`
|
Username string `json:"username"`
|
||||||
|
Proxy string `json:"proxy,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// DownloadMediaResponse represents the response for download operation
|
|
||||||
type DownloadMediaResponse struct {
|
type DownloadMediaResponse struct {
|
||||||
Success bool `json:"success"`
|
Success bool `json:"success"`
|
||||||
|
Cancelled bool `json:"cancelled"`
|
||||||
Downloaded int `json:"downloaded"`
|
Downloaded int `json:"downloaded"`
|
||||||
|
Skipped int `json:"skipped"`
|
||||||
Failed int `json:"failed"`
|
Failed int `json:"failed"`
|
||||||
Message string `json:"message"`
|
Message string `json:"message"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// DownloadMedia downloads media files from URLs (legacy)
|
|
||||||
func (a *App) DownloadMedia(req DownloadMediaRequest) (DownloadMediaResponse, error) {
|
func (a *App) DownloadMedia(req DownloadMediaRequest) (DownloadMediaResponse, error) {
|
||||||
if len(req.URLs) == 0 {
|
if len(req.URLs) == 0 {
|
||||||
return DownloadMediaResponse{
|
return DownloadMediaResponse{
|
||||||
Success: false,
|
Success: false,
|
||||||
Message: "No URLs provided",
|
Cancelled: false,
|
||||||
|
Message: "No URLs provided",
|
||||||
}, fmt.Errorf("no URLs provided")
|
}, fmt.Errorf("no URLs provided")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -217,16 +230,17 @@ func (a *App) DownloadMedia(req DownloadMediaRequest) (DownloadMediaResponse, er
|
|||||||
outputDir = backend.GetDefaultDownloadPath()
|
outputDir = backend.GetDefaultDownloadPath()
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create subfolder for username if provided
|
|
||||||
if req.Username != "" {
|
if req.Username != "" {
|
||||||
outputDir = filepath.Join(outputDir, req.Username)
|
outputDir = filepath.Join(outputDir, req.Username)
|
||||||
}
|
}
|
||||||
|
|
||||||
downloaded, failed, err := backend.DownloadMediaFiles(req.URLs, outputDir)
|
downloaded, failed, err := backend.DownloadMediaFiles(req.URLs, outputDir, req.Proxy)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return DownloadMediaResponse{
|
return DownloadMediaResponse{
|
||||||
Success: false,
|
Success: false,
|
||||||
|
Cancelled: false,
|
||||||
Downloaded: downloaded,
|
Downloaded: downloaded,
|
||||||
|
Skipped: 0,
|
||||||
Failed: failed,
|
Failed: failed,
|
||||||
Message: err.Error(),
|
Message: err.Error(),
|
||||||
}, err
|
}, err
|
||||||
@@ -234,32 +248,32 @@ func (a *App) DownloadMedia(req DownloadMediaRequest) (DownloadMediaResponse, er
|
|||||||
|
|
||||||
return DownloadMediaResponse{
|
return DownloadMediaResponse{
|
||||||
Success: true,
|
Success: true,
|
||||||
|
Cancelled: false,
|
||||||
Downloaded: downloaded,
|
Downloaded: downloaded,
|
||||||
|
Skipped: 0,
|
||||||
Failed: failed,
|
Failed: failed,
|
||||||
Message: fmt.Sprintf("Downloaded %d files, %d failed", downloaded, failed),
|
Message: fmt.Sprintf("Downloaded %d files, %d failed", downloaded, failed),
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// DownloadProgress represents download progress event data
|
|
||||||
type DownloadProgress struct {
|
type DownloadProgress struct {
|
||||||
Current int `json:"current"`
|
Current int `json:"current"`
|
||||||
Total int `json:"total"`
|
Total int `json:"total"`
|
||||||
Percent int `json:"percent"`
|
Percent int `json:"percent"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// DownloadItemStatus represents per-item download status event data
|
|
||||||
type DownloadItemStatus struct {
|
type DownloadItemStatus struct {
|
||||||
TweetID int64 `json:"tweet_id"`
|
TweetID int64 `json:"tweet_id"`
|
||||||
Index int `json:"index"`
|
Index int `json:"index"`
|
||||||
Status string `json:"status"` // "success", "failed", "skipped"
|
Status string `json:"status"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// DownloadMediaWithMetadata downloads media files with proper naming and categorization
|
|
||||||
func (a *App) DownloadMediaWithMetadata(req DownloadMediaWithMetadataRequest) (DownloadMediaResponse, error) {
|
func (a *App) DownloadMediaWithMetadata(req DownloadMediaWithMetadataRequest) (DownloadMediaResponse, error) {
|
||||||
if len(req.Items) == 0 {
|
if len(req.Items) == 0 {
|
||||||
return DownloadMediaResponse{
|
return DownloadMediaResponse{
|
||||||
Success: false,
|
Success: false,
|
||||||
Message: "No items provided",
|
Cancelled: false,
|
||||||
|
Message: "No items provided",
|
||||||
}, fmt.Errorf("no items provided")
|
}, fmt.Errorf("no items provided")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -268,23 +282,37 @@ func (a *App) DownloadMediaWithMetadata(req DownloadMediaWithMetadataRequest) (D
|
|||||||
outputDir = backend.GetDefaultDownloadPath()
|
outputDir = backend.GetDefaultDownloadPath()
|
||||||
}
|
}
|
||||||
|
|
||||||
// Convert request items to backend items
|
|
||||||
items := make([]backend.MediaItem, len(req.Items))
|
items := make([]backend.MediaItem, len(req.Items))
|
||||||
for i, item := range req.Items {
|
for i, item := range req.Items {
|
||||||
|
|
||||||
|
originalFilename := item.OriginalFilename
|
||||||
|
if originalFilename == "" {
|
||||||
|
|
||||||
|
originalFilename = backend.ExtractOriginalFilename(item.URL)
|
||||||
|
}
|
||||||
|
|
||||||
|
username := req.Username
|
||||||
|
if item.AuthorUsername != "" {
|
||||||
|
username = item.AuthorUsername
|
||||||
|
}
|
||||||
|
|
||||||
items[i] = backend.MediaItem{
|
items[i] = backend.MediaItem{
|
||||||
URL: item.URL,
|
URL: item.URL,
|
||||||
Date: item.Date,
|
Date: item.Date,
|
||||||
TweetID: int64(item.TweetID),
|
TweetID: int64(item.TweetID),
|
||||||
Type: item.Type,
|
Type: item.Type,
|
||||||
Username: req.Username,
|
Username: username,
|
||||||
Content: item.Content,
|
Content: item.Content,
|
||||||
|
OriginalFilename: originalFilename,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create cancellable context
|
|
||||||
a.downloadCtx, a.downloadCancel = context.WithCancel(context.Background())
|
a.downloadCtx, a.downloadCancel = context.WithCancel(context.Background())
|
||||||
|
defer func() {
|
||||||
|
a.downloadCtx = nil
|
||||||
|
a.downloadCancel = nil
|
||||||
|
}()
|
||||||
|
|
||||||
// Progress callback
|
|
||||||
progressCallback := func(current, total int) {
|
progressCallback := func(current, total int) {
|
||||||
percent := 0
|
percent := 0
|
||||||
if total > 0 {
|
if total > 0 {
|
||||||
@@ -297,7 +325,6 @@ func (a *App) DownloadMediaWithMetadata(req DownloadMediaWithMetadataRequest) (D
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// Per-item status callback
|
|
||||||
itemStatusCallback := func(tweetID int64, index int, status string) {
|
itemStatusCallback := func(tweetID int64, index int, status string) {
|
||||||
runtime.EventsEmit(a.ctx, "download-item-status", DownloadItemStatus{
|
runtime.EventsEmit(a.ctx, "download-item-status", DownloadItemStatus{
|
||||||
TweetID: tweetID,
|
TweetID: tweetID,
|
||||||
@@ -306,28 +333,39 @@ func (a *App) DownloadMediaWithMetadata(req DownloadMediaWithMetadataRequest) (D
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
downloaded, failed, err := backend.DownloadMediaWithMetadataProgressAndStatus(items, outputDir, req.Username, progressCallback, itemStatusCallback, a.downloadCtx)
|
downloaded, skipped, failed, err := backend.DownloadMediaWithMetadataProgressAndStatus(items, outputDir, req.Username, progressCallback, itemStatusCallback, a.downloadCtx, req.Proxy)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
if errors.Is(err, context.Canceled) {
|
||||||
|
return DownloadMediaResponse{
|
||||||
|
Success: false,
|
||||||
|
Cancelled: true,
|
||||||
|
Downloaded: downloaded,
|
||||||
|
Skipped: skipped,
|
||||||
|
Failed: failed,
|
||||||
|
Message: "Download stopped",
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
return DownloadMediaResponse{
|
return DownloadMediaResponse{
|
||||||
Success: false,
|
Success: false,
|
||||||
|
Cancelled: false,
|
||||||
Downloaded: downloaded,
|
Downloaded: downloaded,
|
||||||
|
Skipped: skipped,
|
||||||
Failed: failed,
|
Failed: failed,
|
||||||
Message: err.Error(),
|
Message: err.Error(),
|
||||||
}, err
|
}, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Clear cancel function
|
|
||||||
a.downloadCancel = nil
|
|
||||||
|
|
||||||
return DownloadMediaResponse{
|
return DownloadMediaResponse{
|
||||||
Success: true,
|
Success: true,
|
||||||
|
Cancelled: false,
|
||||||
Downloaded: downloaded,
|
Downloaded: downloaded,
|
||||||
|
Skipped: skipped,
|
||||||
Failed: failed,
|
Failed: failed,
|
||||||
Message: fmt.Sprintf("Downloaded %d files, %d failed", downloaded, failed),
|
Message: fmt.Sprintf("Downloaded %d files, %d skipped, %d failed", downloaded, skipped, failed),
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// StopDownload cancels the current download operation
|
|
||||||
func (a *App) StopDownload() bool {
|
func (a *App) StopDownload() bool {
|
||||||
if a.downloadCancel != nil {
|
if a.downloadCancel != nil {
|
||||||
a.downloadCancel()
|
a.downloadCancel()
|
||||||
@@ -337,24 +375,18 @@ func (a *App) StopDownload() bool {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
// Database functions
|
|
||||||
|
|
||||||
// SaveAccountToDB saves account data to database
|
|
||||||
func (a *App) SaveAccountToDB(username, name, profileImage string, totalMedia int, responseJSON string, mediaType string) error {
|
func (a *App) SaveAccountToDB(username, name, profileImage string, totalMedia int, responseJSON string, mediaType string) error {
|
||||||
return backend.SaveAccount(username, name, profileImage, totalMedia, responseJSON, mediaType)
|
return backend.SaveAccount(username, name, profileImage, totalMedia, responseJSON, mediaType)
|
||||||
}
|
}
|
||||||
|
|
||||||
// SaveAccountToDBWithStatus saves account data with cursor and completion status for resume capability
|
|
||||||
func (a *App) SaveAccountToDBWithStatus(username, name, profileImage string, totalMedia int, responseJSON string, mediaType string, cursor string, completed bool) error {
|
func (a *App) SaveAccountToDBWithStatus(username, name, profileImage string, totalMedia int, responseJSON string, mediaType string, cursor string, completed bool) error {
|
||||||
return backend.SaveAccountWithStatus(username, name, profileImage, totalMedia, responseJSON, mediaType, cursor, completed)
|
return backend.SaveAccountWithStatus(username, name, profileImage, totalMedia, responseJSON, mediaType, cursor, completed)
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetAllAccountsFromDB returns all saved accounts
|
|
||||||
func (a *App) GetAllAccountsFromDB() ([]backend.AccountListItem, error) {
|
func (a *App) GetAllAccountsFromDB() ([]backend.AccountListItem, error) {
|
||||||
return backend.GetAllAccounts()
|
return backend.GetAllAccounts()
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetAccountFromDB returns account data by ID
|
|
||||||
func (a *App) GetAccountFromDB(id int64) (string, error) {
|
func (a *App) GetAccountFromDB(id int64) (string, error) {
|
||||||
acc, err := backend.GetAccountByID(id)
|
acc, err := backend.GetAccountByID(id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -363,52 +395,73 @@ func (a *App) GetAccountFromDB(id int64) (string, error) {
|
|||||||
return acc.ResponseJSON, nil
|
return acc.ResponseJSON, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// DeleteAccountFromDB deletes an account from database
|
func (a *App) GetSavedAccountFromDB(username, mediaType string) (string, error) {
|
||||||
|
acc, err := backend.GetAccountByUsernameAndMediaType(username, mediaType)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return acc.ResponseJSON, nil
|
||||||
|
}
|
||||||
|
|
||||||
func (a *App) DeleteAccountFromDB(id int64) error {
|
func (a *App) DeleteAccountFromDB(id int64) error {
|
||||||
return backend.DeleteAccount(id)
|
return backend.DeleteAccount(id)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ClearAllAccountsFromDB deletes all accounts from database
|
|
||||||
func (a *App) ClearAllAccountsFromDB() error {
|
func (a *App) ClearAllAccountsFromDB() error {
|
||||||
return backend.ClearAllAccounts()
|
return backend.ClearAllAccounts()
|
||||||
}
|
}
|
||||||
|
|
||||||
// ExportAccountJSON exports account to JSON file in specified directory
|
|
||||||
func (a *App) ExportAccountJSON(id int64, outputDir string) (string, error) {
|
func (a *App) ExportAccountJSON(id int64, outputDir string) (string, error) {
|
||||||
return backend.ExportAccountToFile(id, outputDir)
|
return backend.ExportAccountToFile(id, outputDir)
|
||||||
}
|
}
|
||||||
|
|
||||||
// UpdateAccountGroup updates the group for an account
|
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 {
|
func (a *App) UpdateAccountGroup(id int64, groupName, groupColor string) error {
|
||||||
return backend.UpdateAccountGroup(id, groupName, groupColor)
|
return backend.UpdateAccountGroup(id, groupName, groupColor)
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetAllGroups returns all unique groups
|
|
||||||
func (a *App) GetAllGroups() ([]map[string]string, error) {
|
func (a *App) GetAllGroups() ([]map[string]string, error) {
|
||||||
return backend.GetAllGroups()
|
return backend.GetAllGroups()
|
||||||
}
|
}
|
||||||
|
|
||||||
// FFmpeg functions
|
func (a *App) CheckFoldersExist(basePath string, usernames []string) map[string]bool {
|
||||||
|
return backend.CheckFoldersExist(basePath, usernames)
|
||||||
|
}
|
||||||
|
|
||||||
// IsFFmpegInstalled checks if ffmpeg is available
|
|
||||||
func (a *App) IsFFmpegInstalled() bool {
|
func (a *App) IsFFmpegInstalled() bool {
|
||||||
return backend.IsFFmpegInstalled()
|
return backend.IsFFmpegInstalled()
|
||||||
}
|
}
|
||||||
|
|
||||||
// DownloadFFmpeg downloads ffmpeg binary
|
|
||||||
func (a *App) DownloadFFmpeg() error {
|
func (a *App) DownloadFFmpeg() error {
|
||||||
return backend.DownloadFFmpeg(nil)
|
return backend.DownloadFFmpeg(nil)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ConvertGIFsRequest represents request for converting GIFs
|
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 {
|
type ConvertGIFsRequest struct {
|
||||||
FolderPath string `json:"folder_path"`
|
FolderPath string `json:"folder_path"`
|
||||||
Quality string `json:"quality"` // "fast" or "better"
|
Quality string `json:"quality"`
|
||||||
Resolution string `json:"resolution"` // "original", "high", "medium", "low"
|
Resolution string `json:"resolution"`
|
||||||
DeleteOriginal bool `json:"delete_original"`
|
DeleteOriginal bool `json:"delete_original"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// ConvertGIFsResponse represents response for GIF conversion
|
|
||||||
type ConvertGIFsResponse struct {
|
type ConvertGIFsResponse struct {
|
||||||
Success bool `json:"success"`
|
Success bool `json:"success"`
|
||||||
Converted int `json:"converted"`
|
Converted int `json:"converted"`
|
||||||
@@ -416,7 +469,6 @@ type ConvertGIFsResponse struct {
|
|||||||
Message string `json:"message"`
|
Message string `json:"message"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// ConvertGIFs converts MP4 files in gifs folder to actual GIF format
|
|
||||||
func (a *App) ConvertGIFs(req ConvertGIFsRequest) (ConvertGIFsResponse, error) {
|
func (a *App) ConvertGIFs(req ConvertGIFsRequest) (ConvertGIFsResponse, error) {
|
||||||
if !backend.IsFFmpegInstalled() {
|
if !backend.IsFFmpegInstalled() {
|
||||||
return ConvertGIFsResponse{
|
return ConvertGIFsResponse{
|
||||||
@@ -425,7 +477,6 @@ func (a *App) ConvertGIFs(req ConvertGIFsRequest) (ConvertGIFsResponse, error) {
|
|||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Default values if not provided
|
|
||||||
quality := req.Quality
|
quality := req.Quality
|
||||||
if quality == "" {
|
if quality == "" {
|
||||||
quality = "fast"
|
quality = "fast"
|
||||||
@@ -451,16 +502,34 @@ func (a *App) ConvertGIFs(req ConvertGIFsRequest) (ConvertGIFsResponse, error) {
|
|||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ImportAccountResponse represents the response for import operation
|
|
||||||
type ImportAccountResponse struct {
|
type ImportAccountResponse struct {
|
||||||
Success bool `json:"success"`
|
Success bool `json:"success"`
|
||||||
Username string `json:"username"`
|
Username string `json:"username"`
|
||||||
Message string `json:"message"`
|
Message string `json:"message"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// ImportAccountFromJSON imports account from JSON file (supports both old and new format)
|
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) {
|
func (a *App) ImportAccountFromJSON() (ImportAccountResponse, error) {
|
||||||
// Open file dialog
|
|
||||||
filePath, err := runtime.OpenFileDialog(a.ctx, runtime.OpenDialogOptions{
|
filePath, err := runtime.OpenFileDialog(a.ctx, runtime.OpenDialogOptions{
|
||||||
Title: "Import Account JSON",
|
Title: "Import Account JSON",
|
||||||
Filters: []runtime.FileFilter{
|
Filters: []runtime.FileFilter{
|
||||||
@@ -471,12 +540,10 @@ func (a *App) ImportAccountFromJSON() (ImportAccountResponse, error) {
|
|||||||
return ImportAccountResponse{Success: false, Message: err.Error()}, err
|
return ImportAccountResponse{Success: false, Message: err.Error()}, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// User cancelled
|
|
||||||
if filePath == "" {
|
if filePath == "" {
|
||||||
return ImportAccountResponse{Success: false, Message: "Cancelled"}, nil
|
return ImportAccountResponse{Success: false, Message: "Cancelled"}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Import the file
|
|
||||||
username, err := backend.ImportAccountFromFile(filePath)
|
username, err := backend.ImportAccountFromFile(filePath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return ImportAccountResponse{Success: false, Message: err.Error()}, err
|
return ImportAccountResponse{Success: false, Message: err.Error()}, err
|
||||||
|
|||||||
@@ -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
|
||||||
|
}
|
||||||
+1
-2
@@ -4,7 +4,6 @@ package backend
|
|||||||
|
|
||||||
import "os/exec"
|
import "os/exec"
|
||||||
|
|
||||||
// hideWindow is a no-op on non-Windows platforms
|
|
||||||
func hideWindow(cmd *exec.Cmd) {
|
func hideWindow(cmd *exec.Cmd) {
|
||||||
// No action needed on Unix-like systems
|
|
||||||
}
|
}
|
||||||
@@ -7,10 +7,9 @@ import (
|
|||||||
"syscall"
|
"syscall"
|
||||||
)
|
)
|
||||||
|
|
||||||
// hideWindow sets the command to run without showing a console window on Windows
|
|
||||||
func hideWindow(cmd *exec.Cmd) {
|
func hideWindow(cmd *exec.Cmd) {
|
||||||
cmd.SysProcAttr = &syscall.SysProcAttr{
|
cmd.SysProcAttr = &syscall.SysProcAttr{
|
||||||
HideWindow: true,
|
HideWindow: true,
|
||||||
CreationFlags: 0x08000000, // CREATE_NO_WINDOW
|
CreationFlags: 0x08000000,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+105
-3
@@ -1,18 +1,120 @@
|
|||||||
package backend
|
package backend
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"sync/atomic"
|
||||||
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
func GetDefaultDownloadPath() string {
|
func GetDefaultDownloadPath() string {
|
||||||
// Get user's home directory
|
|
||||||
homeDir, err := os.UserHomeDir()
|
homeDir, err := os.UserHomeDir()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
// Fallback to Public Pictures if can't get home dir
|
|
||||||
return "C:\\Users\\Public\\Pictures"
|
return "C:\\Users\\Public\\Pictures"
|
||||||
}
|
}
|
||||||
|
|
||||||
// Return path to user's Pictures folder
|
|
||||||
return filepath.Join(homeDir, "Pictures")
|
return filepath.Join(homeDir, "Pictures")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
+188
-96
@@ -8,10 +8,9 @@ import (
|
|||||||
"path/filepath"
|
"path/filepath"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
_ "github.com/mattn/go-sqlite3"
|
_ "modernc.org/sqlite"
|
||||||
)
|
)
|
||||||
|
|
||||||
// AccountDB represents a saved account in the database
|
|
||||||
type AccountDB struct {
|
type AccountDB struct {
|
||||||
ID int64 `json:"id"`
|
ID int64 `json:"id"`
|
||||||
Username string `json:"username"`
|
Username string `json:"username"`
|
||||||
@@ -25,24 +24,33 @@ type AccountDB struct {
|
|||||||
Completed bool `json:"completed"`
|
Completed bool `json:"completed"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// AccountListItem represents a simplified account for listing
|
|
||||||
type AccountListItem struct {
|
type AccountListItem struct {
|
||||||
ID int64 `json:"id"`
|
ID int64 `json:"id"`
|
||||||
Username string `json:"username"`
|
Username string `json:"username"`
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
ProfileImage string `json:"profile_image"`
|
ProfileImage string `json:"profile_image"`
|
||||||
TotalMedia int `json:"total_media"`
|
TotalMedia int `json:"total_media"`
|
||||||
LastFetched string `json:"last_fetched"`
|
LastFetched string `json:"last_fetched"`
|
||||||
GroupName string `json:"group_name"`
|
GroupName string `json:"group_name"`
|
||||||
GroupColor string `json:"group_color"`
|
GroupColor string `json:"group_color"`
|
||||||
MediaType string `json:"media_type"`
|
MediaType string `json:"media_type"`
|
||||||
Cursor string `json:"cursor"`
|
Cursor string `json:"cursor"`
|
||||||
Completed bool `json:"completed"`
|
Completed bool `json:"completed"`
|
||||||
|
FollowersCount int `json:"followers_count"`
|
||||||
|
StatusesCount int `json:"statuses_count"`
|
||||||
}
|
}
|
||||||
|
|
||||||
var db *sql.DB
|
var db *sql.DB
|
||||||
|
|
||||||
// GetDBPath returns the database file path
|
type accountMetricsPayload struct {
|
||||||
|
AccountInfo struct {
|
||||||
|
FollowersCount int `json:"followers_count"`
|
||||||
|
StatusesCount int `json:"statuses_count"`
|
||||||
|
} `json:"account_info"`
|
||||||
|
Followers int `json:"followers"`
|
||||||
|
Posts int `json:"posts"`
|
||||||
|
}
|
||||||
|
|
||||||
func GetDBPath() string {
|
func GetDBPath() string {
|
||||||
homeDir, err := os.UserHomeDir()
|
homeDir, err := os.UserHomeDir()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -51,23 +59,24 @@ func GetDBPath() string {
|
|||||||
return filepath.Join(homeDir, ".twitterxmediabatchdownloader", "accounts.db")
|
return filepath.Join(homeDir, ".twitterxmediabatchdownloader", "accounts.db")
|
||||||
}
|
}
|
||||||
|
|
||||||
// InitDB initializes the database connection
|
|
||||||
func InitDB() error {
|
func InitDB() error {
|
||||||
dbPath := GetDBPath()
|
dbPath := GetDBPath()
|
||||||
|
|
||||||
// Create directory if not exists
|
|
||||||
dir := filepath.Dir(dbPath)
|
dir := filepath.Dir(dbPath)
|
||||||
if err := os.MkdirAll(dir, 0755); err != nil {
|
if err := os.MkdirAll(dir, 0755); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
var err error
|
var err error
|
||||||
db, err = sql.Open("sqlite3", dbPath)
|
db, err = sql.Open("sqlite", dbPath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create tables
|
if err := db.Ping(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
_, err = db.Exec(`
|
_, err = db.Exec(`
|
||||||
CREATE TABLE IF NOT EXISTS accounts (
|
CREATE TABLE IF NOT EXISTS accounts (
|
||||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
@@ -82,6 +91,8 @@ func InitDB() error {
|
|||||||
media_type TEXT DEFAULT 'all',
|
media_type TEXT DEFAULT 'all',
|
||||||
cursor TEXT DEFAULT '',
|
cursor TEXT DEFAULT '',
|
||||||
completed INTEGER DEFAULT 1,
|
completed INTEGER DEFAULT 1,
|
||||||
|
followers_count INTEGER DEFAULT 0,
|
||||||
|
statuses_count INTEGER DEFAULT 0,
|
||||||
UNIQUE(username, media_type)
|
UNIQUE(username, media_type)
|
||||||
)
|
)
|
||||||
`)
|
`)
|
||||||
@@ -89,33 +100,33 @@ func InitDB() error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add group columns if they don't exist (migration for existing databases)
|
|
||||||
db.Exec("ALTER TABLE accounts ADD COLUMN group_name TEXT DEFAULT ''")
|
db.Exec("ALTER TABLE accounts ADD COLUMN group_name TEXT DEFAULT ''")
|
||||||
db.Exec("ALTER TABLE accounts ADD COLUMN group_color TEXT DEFAULT ''")
|
db.Exec("ALTER TABLE accounts ADD COLUMN group_color TEXT DEFAULT ''")
|
||||||
db.Exec("ALTER TABLE accounts ADD COLUMN media_type TEXT DEFAULT 'all'")
|
db.Exec("ALTER TABLE accounts ADD COLUMN media_type TEXT DEFAULT 'all'")
|
||||||
db.Exec("ALTER TABLE accounts ADD COLUMN cursor TEXT DEFAULT ''")
|
db.Exec("ALTER TABLE accounts ADD COLUMN cursor TEXT DEFAULT ''")
|
||||||
db.Exec("ALTER TABLE accounts ADD COLUMN completed INTEGER DEFAULT 1")
|
db.Exec("ALTER TABLE accounts ADD COLUMN completed INTEGER DEFAULT 1")
|
||||||
|
db.Exec("ALTER TABLE accounts ADD COLUMN followers_count INTEGER DEFAULT 0")
|
||||||
|
db.Exec("ALTER TABLE accounts ADD COLUMN statuses_count INTEGER DEFAULT 0")
|
||||||
|
|
||||||
// Migration: Update unique constraint for existing databases
|
|
||||||
// This allows same username with different media types
|
|
||||||
db.Exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_username_media_type ON accounts(username, media_type)")
|
db.Exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_username_media_type ON accounts(username, media_type)")
|
||||||
|
|
||||||
|
if err := backfillAccountMetrics(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// CloseDB closes the database connection
|
|
||||||
func CloseDB() {
|
func CloseDB() {
|
||||||
if db != nil {
|
if db != nil {
|
||||||
db.Close()
|
db.Close()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// SaveAccount saves or updates an account in the database
|
|
||||||
func SaveAccount(username, name, profileImage string, totalMedia int, responseJSON string, mediaType string) error {
|
func SaveAccount(username, name, profileImage string, totalMedia int, responseJSON string, mediaType string) error {
|
||||||
return SaveAccountWithStatus(username, name, profileImage, totalMedia, responseJSON, mediaType, "", true)
|
return SaveAccountWithStatus(username, name, profileImage, totalMedia, responseJSON, mediaType, "", true)
|
||||||
}
|
}
|
||||||
|
|
||||||
// SaveAccountWithStatus saves or updates an account with cursor and completion status
|
|
||||||
func SaveAccountWithStatus(username, name, profileImage string, totalMedia int, responseJSON string, mediaType string, cursor string, completed bool) error {
|
func SaveAccountWithStatus(username, name, profileImage string, totalMedia int, responseJSON string, mediaType string, cursor string, completed bool) error {
|
||||||
if db == nil {
|
if db == nil {
|
||||||
if err := InitDB(); err != nil {
|
if err := InitDB(); err != nil {
|
||||||
@@ -123,7 +134,6 @@ func SaveAccountWithStatus(username, name, profileImage string, totalMedia int,
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Default to "all" if not specified
|
|
||||||
if mediaType == "" {
|
if mediaType == "" {
|
||||||
mediaType = "all"
|
mediaType = "all"
|
||||||
}
|
}
|
||||||
@@ -133,9 +143,11 @@ func SaveAccountWithStatus(username, name, profileImage string, totalMedia int,
|
|||||||
completedInt = 1
|
completedInt = 1
|
||||||
}
|
}
|
||||||
|
|
||||||
|
followersCount, statusesCount := extractAccountMetrics(responseJSON)
|
||||||
|
|
||||||
_, err := db.Exec(`
|
_, err := db.Exec(`
|
||||||
INSERT INTO accounts (username, name, profile_image, total_media, last_fetched, response_json, media_type, cursor, completed)
|
INSERT INTO accounts (username, name, profile_image, total_media, last_fetched, response_json, media_type, cursor, completed, followers_count, statuses_count)
|
||||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
ON CONFLICT(username, media_type) DO UPDATE SET
|
ON CONFLICT(username, media_type) DO UPDATE SET
|
||||||
name = excluded.name,
|
name = excluded.name,
|
||||||
profile_image = excluded.profile_image,
|
profile_image = excluded.profile_image,
|
||||||
@@ -143,13 +155,14 @@ func SaveAccountWithStatus(username, name, profileImage string, totalMedia int,
|
|||||||
last_fetched = excluded.last_fetched,
|
last_fetched = excluded.last_fetched,
|
||||||
response_json = excluded.response_json,
|
response_json = excluded.response_json,
|
||||||
cursor = excluded.cursor,
|
cursor = excluded.cursor,
|
||||||
completed = excluded.completed
|
completed = excluded.completed,
|
||||||
`, username, name, profileImage, totalMedia, time.Now(), responseJSON, mediaType, cursor, completedInt)
|
followers_count = excluded.followers_count,
|
||||||
|
statuses_count = excluded.statuses_count
|
||||||
|
`, username, name, profileImage, totalMedia, time.Now(), responseJSON, mediaType, cursor, completedInt, followersCount, statusesCount)
|
||||||
|
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetAllAccounts returns all saved accounts
|
|
||||||
func GetAllAccounts() ([]AccountListItem, error) {
|
func GetAllAccounts() ([]AccountListItem, error) {
|
||||||
if db == nil {
|
if db == nil {
|
||||||
if err := InitDB(); err != nil {
|
if err := InitDB(); err != nil {
|
||||||
@@ -161,7 +174,9 @@ func GetAllAccounts() ([]AccountListItem, error) {
|
|||||||
SELECT id, username, name, profile_image, total_media, last_fetched,
|
SELECT id, username, name, profile_image, total_media, last_fetched,
|
||||||
COALESCE(group_name, '') as group_name, COALESCE(group_color, '') as group_color,
|
COALESCE(group_name, '') as group_name, COALESCE(group_color, '') as group_color,
|
||||||
COALESCE(media_type, 'all') as media_type,
|
COALESCE(media_type, 'all') as media_type,
|
||||||
COALESCE(cursor, '') as cursor, COALESCE(completed, 1) as completed
|
COALESCE(cursor, '') as cursor, COALESCE(completed, 1) as completed,
|
||||||
|
COALESCE(followers_count, 0) as followers_count,
|
||||||
|
COALESCE(statuses_count, 0) as statuses_count
|
||||||
FROM accounts
|
FROM accounts
|
||||||
ORDER BY group_name ASC, last_fetched DESC
|
ORDER BY group_name ASC, last_fetched DESC
|
||||||
`)
|
`)
|
||||||
@@ -175,18 +190,79 @@ func GetAllAccounts() ([]AccountListItem, error) {
|
|||||||
var acc AccountListItem
|
var acc AccountListItem
|
||||||
var lastFetched time.Time
|
var lastFetched time.Time
|
||||||
var completedInt int
|
var completedInt int
|
||||||
if err := rows.Scan(&acc.ID, &acc.Username, &acc.Name, &acc.ProfileImage, &acc.TotalMedia, &lastFetched, &acc.GroupName, &acc.GroupColor, &acc.MediaType, &acc.Cursor, &completedInt); err != nil {
|
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
|
continue
|
||||||
}
|
}
|
||||||
acc.LastFetched = lastFetched.Format("2006-01-02 15:04")
|
acc.LastFetched = lastFetched.Format("2006-01-02 15:04")
|
||||||
acc.Completed = completedInt == 1
|
acc.Completed = completedInt == 1
|
||||||
|
|
||||||
accounts = append(accounts, acc)
|
accounts = append(accounts, acc)
|
||||||
}
|
}
|
||||||
|
|
||||||
return accounts, nil
|
return accounts, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// UpdateAccountGroup updates the group for an account
|
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
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
|
||||||
|
stmt, err := db.Prepare(`
|
||||||
|
UPDATE accounts
|
||||||
|
SET followers_count = ?, statuses_count = ?
|
||||||
|
WHERE id = ?
|
||||||
|
`)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer stmt.Close()
|
||||||
|
|
||||||
|
for rows.Next() {
|
||||||
|
var id int64
|
||||||
|
var responseJSON string
|
||||||
|
if err := rows.Scan(&id, &responseJSON); err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
followersCount, statusesCount := extractAccountMetrics(responseJSON)
|
||||||
|
if _, err := stmt.Exec(followersCount, statusesCount, id); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return rows.Err()
|
||||||
|
}
|
||||||
|
|
||||||
func UpdateAccountGroup(id int64, groupName, groupColor string) error {
|
func UpdateAccountGroup(id int64, groupName, groupColor string) error {
|
||||||
if db == nil {
|
if db == nil {
|
||||||
if err := InitDB(); err != nil {
|
if err := InitDB(); err != nil {
|
||||||
@@ -198,7 +274,6 @@ func UpdateAccountGroup(id int64, groupName, groupColor string) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetAllGroups returns all unique groups
|
|
||||||
func GetAllGroups() ([]map[string]string, error) {
|
func GetAllGroups() ([]map[string]string, error) {
|
||||||
if db == nil {
|
if db == nil {
|
||||||
if err := InitDB(); err != nil {
|
if err := InitDB(); err != nil {
|
||||||
@@ -229,7 +304,6 @@ func GetAllGroups() ([]map[string]string, error) {
|
|||||||
return groups, nil
|
return groups, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ClearAllAccounts deletes all accounts from the database
|
|
||||||
func ClearAllAccounts() error {
|
func ClearAllAccounts() error {
|
||||||
if db == nil {
|
if db == nil {
|
||||||
if err := InitDB(); err != nil {
|
if err := InitDB(); err != nil {
|
||||||
@@ -241,38 +315,6 @@ func ClearAllAccounts() error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetAccountByUsername returns a specific account by username
|
|
||||||
func GetAccountByUsername(username string) (*AccountDB, error) {
|
|
||||||
if db == nil {
|
|
||||||
if err := InitDB(); 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 username = ?
|
|
||||||
`, username).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
|
|
||||||
|
|
||||||
// Convert legacy format if needed
|
|
||||||
if converted, err := ConvertLegacyToNewFormat(acc.ResponseJSON); err == nil {
|
|
||||||
acc.ResponseJSON = converted
|
|
||||||
}
|
|
||||||
|
|
||||||
return &acc, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetAccountByID returns a specific account by ID
|
|
||||||
func GetAccountByID(id int64) (*AccountDB, error) {
|
func GetAccountByID(id int64) (*AccountDB, error) {
|
||||||
if db == nil {
|
if db == nil {
|
||||||
if err := InitDB(); err != nil {
|
if err := InitDB(); err != nil {
|
||||||
@@ -295,7 +337,6 @@ func GetAccountByID(id int64) (*AccountDB, error) {
|
|||||||
acc.LastFetched = lastFetched
|
acc.LastFetched = lastFetched
|
||||||
acc.Completed = completedInt == 1
|
acc.Completed = completedInt == 1
|
||||||
|
|
||||||
// Convert legacy format if needed
|
|
||||||
if converted, err := ConvertLegacyToNewFormat(acc.ResponseJSON); err == nil {
|
if converted, err := ConvertLegacyToNewFormat(acc.ResponseJSON); err == nil {
|
||||||
acc.ResponseJSON = converted
|
acc.ResponseJSON = converted
|
||||||
}
|
}
|
||||||
@@ -303,7 +344,41 @@ func GetAccountByID(id int64) (*AccountDB, error) {
|
|||||||
return &acc, nil
|
return &acc, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// DeleteAccount deletes an account from the database
|
func GetAccountByUsernameAndMediaType(username, mediaType string) (*AccountDB, error) {
|
||||||
|
if db == nil {
|
||||||
|
if err := InitDB(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if mediaType == "" {
|
||||||
|
mediaType = "all"
|
||||||
|
}
|
||||||
|
|
||||||
|
var acc AccountDB
|
||||||
|
var lastFetched time.Time
|
||||||
|
var completedInt int
|
||||||
|
err := db.QueryRow(`
|
||||||
|
SELECT id, username, name, profile_image, total_media, last_fetched, response_json,
|
||||||
|
COALESCE(media_type, 'all') as media_type,
|
||||||
|
COALESCE(cursor, '') as cursor, COALESCE(completed, 1) as completed
|
||||||
|
FROM accounts
|
||||||
|
WHERE LOWER(username) = LOWER(?) AND COALESCE(media_type, 'all') = ?
|
||||||
|
`, username, mediaType).Scan(&acc.ID, &acc.Username, &acc.Name, &acc.ProfileImage, &acc.TotalMedia, &lastFetched, &acc.ResponseJSON, &acc.MediaType, &acc.Cursor, &completedInt)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
acc.LastFetched = lastFetched
|
||||||
|
acc.Completed = completedInt == 1
|
||||||
|
|
||||||
|
if converted, err := ConvertLegacyToNewFormat(acc.ResponseJSON); err == nil {
|
||||||
|
acc.ResponseJSON = converted
|
||||||
|
}
|
||||||
|
|
||||||
|
return &acc, nil
|
||||||
|
}
|
||||||
|
|
||||||
func DeleteAccount(id int64) error {
|
func DeleteAccount(id int64) error {
|
||||||
if db == nil {
|
if db == nil {
|
||||||
if err := InitDB(); err != nil {
|
if err := InitDB(); err != nil {
|
||||||
@@ -315,14 +390,6 @@ func DeleteAccount(id int64) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// ParseResponseJSON parses the stored JSON response
|
|
||||||
func ParseResponseJSON(jsonStr string) (map[string]interface{}, error) {
|
|
||||||
var result map[string]interface{}
|
|
||||||
err := json.Unmarshal([]byte(jsonStr), &result)
|
|
||||||
return result, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// LegacyMediaEntry represents media entry in old format
|
|
||||||
type LegacyMediaEntry struct {
|
type LegacyMediaEntry struct {
|
||||||
TweetID string `json:"tweet_id"`
|
TweetID string `json:"tweet_id"`
|
||||||
URL string `json:"url"`
|
URL string `json:"url"`
|
||||||
@@ -330,7 +397,6 @@ type LegacyMediaEntry struct {
|
|||||||
Type string `json:"type"`
|
Type string `json:"type"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// LegacyAccountFormat represents the old saved account format
|
|
||||||
type LegacyAccountFormat struct {
|
type LegacyAccountFormat struct {
|
||||||
Username string `json:"username"`
|
Username string `json:"username"`
|
||||||
Nick string `json:"nick"`
|
Nick string `json:"nick"`
|
||||||
@@ -345,20 +411,17 @@ type LegacyAccountFormat struct {
|
|||||||
MediaList []LegacyMediaEntry `json:"media_list"`
|
MediaList []LegacyMediaEntry `json:"media_list"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// ConvertLegacyToNewFormat converts old format to new TwitterResponse format
|
|
||||||
func ConvertLegacyToNewFormat(jsonStr string) (string, error) {
|
func ConvertLegacyToNewFormat(jsonStr string) (string, error) {
|
||||||
// First check if it's already in new format (has account_info key)
|
|
||||||
var check map[string]interface{}
|
var check map[string]interface{}
|
||||||
if err := json.Unmarshal([]byte(jsonStr), &check); err != nil {
|
if err := json.Unmarshal([]byte(jsonStr), &check); err != nil {
|
||||||
return jsonStr, err
|
return jsonStr, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// If already has account_info, it's new format - return as is
|
|
||||||
if _, hasAccountInfo := check["account_info"]; hasAccountInfo {
|
if _, hasAccountInfo := check["account_info"]; hasAccountInfo {
|
||||||
return jsonStr, nil
|
return jsonStr, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check if it's legacy format (has username and media_list)
|
|
||||||
if _, hasUsername := check["username"]; !hasUsername {
|
if _, hasUsername := check["username"]; !hasUsername {
|
||||||
return jsonStr, nil
|
return jsonStr, nil
|
||||||
}
|
}
|
||||||
@@ -366,13 +429,11 @@ func ConvertLegacyToNewFormat(jsonStr string) (string, error) {
|
|||||||
return jsonStr, nil
|
return jsonStr, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Parse as legacy format
|
|
||||||
var legacy LegacyAccountFormat
|
var legacy LegacyAccountFormat
|
||||||
if err := json.Unmarshal([]byte(jsonStr), &legacy); err != nil {
|
if err := json.Unmarshal([]byte(jsonStr), &legacy); err != nil {
|
||||||
return jsonStr, err
|
return jsonStr, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Convert timeline entries
|
|
||||||
timeline := make([]map[string]interface{}, len(legacy.MediaList))
|
timeline := make([]map[string]interface{}, len(legacy.MediaList))
|
||||||
for i, media := range legacy.MediaList {
|
for i, media := range legacy.MediaList {
|
||||||
timeline[i] = map[string]interface{}{
|
timeline[i] = map[string]interface{}{
|
||||||
@@ -384,7 +445,6 @@ func ConvertLegacyToNewFormat(jsonStr string) (string, error) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Build new format
|
|
||||||
newFormat := map[string]interface{}{
|
newFormat := map[string]interface{}{
|
||||||
"account_info": map[string]interface{}{
|
"account_info": map[string]interface{}{
|
||||||
"name": legacy.Username,
|
"name": legacy.Username,
|
||||||
@@ -405,7 +465,6 @@ func ConvertLegacyToNewFormat(jsonStr string) (string, error) {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
// Convert back to JSON
|
|
||||||
newJSON, err := json.Marshal(newFormat)
|
newJSON, err := json.Marshal(newFormat)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return jsonStr, err
|
return jsonStr, err
|
||||||
@@ -414,20 +473,17 @@ func ConvertLegacyToNewFormat(jsonStr string) (string, error) {
|
|||||||
return string(newJSON), nil
|
return string(newJSON), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ExportAccountToFile exports account JSON to a file
|
|
||||||
func ExportAccountToFile(id int64, outputDir string) (string, error) {
|
func ExportAccountToFile(id int64, outputDir string) (string, error) {
|
||||||
acc, err := GetAccountByID(id)
|
acc, err := GetAccountByID(id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create export directory if not exists
|
|
||||||
exportDir := filepath.Join(outputDir, "twitterxmediabatchdownloader_backups")
|
exportDir := filepath.Join(outputDir, "twitterxmediabatchdownloader_backups")
|
||||||
if err := os.MkdirAll(exportDir, 0755); err != nil {
|
if err := os.MkdirAll(exportDir, 0755); err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Use username (nick) for filename
|
|
||||||
filename := acc.Username
|
filename := acc.Username
|
||||||
if filename == "" {
|
if filename == "" {
|
||||||
filename = acc.Name
|
filename = acc.Name
|
||||||
@@ -442,7 +498,48 @@ func ExportAccountToFile(id int64, outputDir string) (string, error) {
|
|||||||
return filePath, nil
|
return filePath, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ImportAccountFromFile imports account from JSON file (supports both old and new format)
|
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 := ""
|
||||||
|
for i, username := range usernames {
|
||||||
|
if i > 0 {
|
||||||
|
txtContent += "\n"
|
||||||
|
}
|
||||||
|
txtContent += username
|
||||||
|
}
|
||||||
|
|
||||||
|
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) {
|
func ImportAccountFromFile(filePath string) (string, error) {
|
||||||
if db == nil {
|
if db == nil {
|
||||||
if err := InitDB(); err != nil {
|
if err := InitDB(); err != nil {
|
||||||
@@ -450,7 +547,6 @@ func ImportAccountFromFile(filePath string) (string, error) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Read file
|
|
||||||
data, err := os.ReadFile(filePath)
|
data, err := os.ReadFile(filePath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
@@ -458,19 +554,16 @@ func ImportAccountFromFile(filePath string) (string, error) {
|
|||||||
|
|
||||||
jsonStr := string(data)
|
jsonStr := string(data)
|
||||||
|
|
||||||
// Convert legacy format if needed
|
|
||||||
convertedJSON, err := ConvertLegacyToNewFormat(jsonStr)
|
convertedJSON, err := ConvertLegacyToNewFormat(jsonStr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Parse the converted JSON to extract account info
|
|
||||||
var parsed map[string]interface{}
|
var parsed map[string]interface{}
|
||||||
if err := json.Unmarshal([]byte(convertedJSON), &parsed); err != nil {
|
if err := json.Unmarshal([]byte(convertedJSON), &parsed); err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Extract account info
|
|
||||||
accountInfo, ok := parsed["account_info"].(map[string]interface{})
|
accountInfo, ok := parsed["account_info"].(map[string]interface{})
|
||||||
if !ok {
|
if !ok {
|
||||||
return "", fmt.Errorf("invalid JSON format: missing account_info")
|
return "", fmt.Errorf("invalid JSON format: missing account_info")
|
||||||
@@ -489,7 +582,6 @@ func ImportAccountFromFile(filePath string) (string, error) {
|
|||||||
return "", fmt.Errorf("invalid JSON format: missing username")
|
return "", fmt.Errorf("invalid JSON format: missing username")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Save to database with default media type "all" for imported files
|
|
||||||
err = SaveAccount(username, name, profileImage, totalURLs, convertedJSON, "all")
|
err = SaveAccount(username, name, profileImage, totalURLs, convertedJSON, "all")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
|
|||||||
@@ -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"`
|
||||||
|
}
|
||||||
+84
-89
@@ -15,36 +15,37 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
// MaxConcurrentDownloads is the number of parallel downloads
|
|
||||||
MaxConcurrentDownloads = 10
|
MaxConcurrentDownloads = 10
|
||||||
)
|
)
|
||||||
|
|
||||||
// MediaItem represents a media item with metadata for download
|
|
||||||
type MediaItem struct {
|
type MediaItem struct {
|
||||||
URL string `json:"url"`
|
URL string `json:"url"`
|
||||||
Date string `json:"date"`
|
Date string `json:"date"`
|
||||||
TweetID int64 `json:"tweet_id"`
|
TweetID int64 `json:"tweet_id"`
|
||||||
Type string `json:"type"`
|
Type string `json:"type"`
|
||||||
Username string `json:"username"`
|
Username string `json:"username"`
|
||||||
Content string `json:"content,omitempty"` // Tweet text content (for text-only tweets)
|
Content string `json:"content,omitempty"`
|
||||||
|
OriginalFilename string `json:"original_filename,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// DownloadMediaFiles downloads media files from URLs to the output directory (legacy)
|
func DownloadMediaFiles(urls []string, outputDir string, customProxy string) (downloaded int, failed int, err error) {
|
||||||
func DownloadMediaFiles(urls []string, outputDir string) (downloaded int, failed int, err error) {
|
|
||||||
// Create output directory if it doesn't exist
|
|
||||||
if err := os.MkdirAll(outputDir, 0755); err != nil {
|
if err := os.MkdirAll(outputDir, 0755); err != nil {
|
||||||
return 0, len(urls), fmt.Errorf("failed to create output directory: %v", err)
|
return 0, len(urls), fmt.Errorf("failed to create output directory: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
client := &http.Client{
|
client, err := CreateHTTPClient(customProxy, 60*time.Second)
|
||||||
Timeout: 60 * time.Second,
|
if err != nil {
|
||||||
|
|
||||||
|
client = &http.Client{
|
||||||
|
Timeout: 60 * time.Second,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, mediaURL := range urls {
|
for _, mediaURL := range urls {
|
||||||
filename := extractFilename(mediaURL)
|
filename := extractFilename(mediaURL)
|
||||||
outputPath := filepath.Join(outputDir, filename)
|
outputPath := filepath.Join(outputDir, filename)
|
||||||
|
|
||||||
// Skip if file already exists
|
|
||||||
if _, err := os.Stat(outputPath); err == nil {
|
if _, err := os.Stat(outputPath); err == nil {
|
||||||
downloaded++
|
downloaded++
|
||||||
continue
|
continue
|
||||||
@@ -60,52 +61,40 @@ func DownloadMediaFiles(urls []string, outputDir string) (downloaded int, failed
|
|||||||
return downloaded, failed, nil
|
return downloaded, failed, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ProgressCallback is a function type for progress updates
|
|
||||||
type ProgressCallback func(current, total int)
|
type ProgressCallback func(current, total int)
|
||||||
|
|
||||||
// ItemStatusCallback is a function type for per-item status updates
|
|
||||||
type ItemStatusCallback func(tweetID int64, index int, status string) // status: "success", "failed", "skipped"
|
type ItemStatusCallback func(tweetID int64, index int, status string) // status: "success", "failed", "skipped"
|
||||||
|
|
||||||
// downloadTask represents a single download task
|
|
||||||
type downloadTask struct {
|
type downloadTask struct {
|
||||||
item MediaItem
|
item MediaItem
|
||||||
outputPath string
|
outputPath string
|
||||||
index int
|
index int
|
||||||
}
|
}
|
||||||
|
|
||||||
// DownloadMediaWithMetadata downloads media files with proper naming and categorization
|
func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir string, username string, progress ProgressCallback, itemStatus ItemStatusCallback, ctx context.Context, customProxy string) (downloaded int, skipped int, failed int, err error) {
|
||||||
func DownloadMediaWithMetadata(items []MediaItem, outputDir string, username string) (downloaded int, failed int, err error) {
|
|
||||||
return DownloadMediaWithMetadataProgressAndStatus(items, outputDir, username, nil, nil, nil)
|
|
||||||
}
|
|
||||||
|
|
||||||
// DownloadMediaWithMetadataProgress downloads media files with progress callback and cancellation support
|
|
||||||
func DownloadMediaWithMetadataProgress(items []MediaItem, outputDir string, username string, progress ProgressCallback, ctx context.Context) (downloaded int, failed int, err error) {
|
|
||||||
return DownloadMediaWithMetadataProgressAndStatus(items, outputDir, username, progress, nil, ctx)
|
|
||||||
}
|
|
||||||
|
|
||||||
// DownloadMediaWithMetadataProgressAndStatus downloads media files with progress and per-item status callbacks
|
|
||||||
func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir string, username string, progress ProgressCallback, itemStatus ItemStatusCallback, ctx context.Context) (downloaded int, failed int, err error) {
|
|
||||||
if ctx == nil {
|
if ctx == nil {
|
||||||
ctx = context.Background()
|
ctx = context.Background()
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create base output directory
|
|
||||||
baseDir := filepath.Join(outputDir, username)
|
|
||||||
if err := os.MkdirAll(baseDir, 0755); err != nil {
|
|
||||||
return 0, len(items), fmt.Errorf("failed to create output directory: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
total := len(items)
|
total := len(items)
|
||||||
if total == 0 {
|
if total == 0 {
|
||||||
return 0, 0, nil
|
return 0, 0, 0, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Prepare all tasks first (sequential to handle tweet media count)
|
tweetMediaCount := make(map[string]map[int64]int)
|
||||||
tweetMediaCount := make(map[int64]int)
|
|
||||||
tasks := make([]downloadTask, 0, total)
|
tasks := make([]downloadTask, 0, total)
|
||||||
|
|
||||||
for i, item := range items {
|
for i, item := range items {
|
||||||
// Determine subfolder based on type
|
|
||||||
|
itemUsername := item.Username
|
||||||
|
if itemUsername == "" {
|
||||||
|
itemUsername = username
|
||||||
|
}
|
||||||
|
|
||||||
|
if tweetMediaCount[itemUsername] == nil {
|
||||||
|
tweetMediaCount[itemUsername] = make(map[int64]int)
|
||||||
|
}
|
||||||
|
|
||||||
var subfolder string
|
var subfolder string
|
||||||
switch item.Type {
|
switch item.Type {
|
||||||
case "photo":
|
case "photo":
|
||||||
@@ -120,24 +109,24 @@ func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir str
|
|||||||
subfolder = "other"
|
subfolder = "other"
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create type subfolder
|
baseDir := filepath.Join(outputDir, itemUsername)
|
||||||
|
if err := os.MkdirAll(baseDir, 0755); err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
typeDir := filepath.Join(baseDir, subfolder)
|
typeDir := filepath.Join(baseDir, subfolder)
|
||||||
if err := os.MkdirAll(typeDir, 0755); err != nil {
|
if err := os.MkdirAll(typeDir, 0755); err != nil {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
// Format timestamp from date
|
|
||||||
timestamp := formatTimestamp(item.Date)
|
timestamp := formatTimestamp(item.Date)
|
||||||
|
|
||||||
// Get file extension
|
|
||||||
ext := getExtension(item.URL, item.Type)
|
ext := getExtension(item.URL, item.Type)
|
||||||
|
|
||||||
// Increment counter for this tweet_id
|
tweetMediaCount[itemUsername][item.TweetID]++
|
||||||
tweetMediaCount[item.TweetID]++
|
mediaIndex := tweetMediaCount[itemUsername][item.TweetID]
|
||||||
mediaIndex := tweetMediaCount[item.TweetID]
|
|
||||||
|
|
||||||
// Create filename: {username}_{timestamp}_{tweet_id}_{index}.{ext}
|
filename := fmt.Sprintf("%s_%s_%d_%02d%s", itemUsername, timestamp, item.TweetID, mediaIndex, ext)
|
||||||
filename := fmt.Sprintf("%s_%s_%d_%02d%s", username, timestamp, item.TweetID, mediaIndex, ext)
|
|
||||||
outputPath := filepath.Join(typeDir, filename)
|
outputPath := filepath.Join(typeDir, filename)
|
||||||
|
|
||||||
tasks = append(tasks, downloadTask{
|
tasks = append(tasks, downloadTask{
|
||||||
@@ -147,31 +136,38 @@ func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir str
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// Counters for parallel downloads
|
|
||||||
var downloadedCount int64
|
var downloadedCount int64
|
||||||
|
var skippedCount int64
|
||||||
var failedCount int64
|
var failedCount int64
|
||||||
var completedCount int64
|
var completedCount int64
|
||||||
|
|
||||||
// Create worker pool
|
|
||||||
taskChan := make(chan downloadTask, len(tasks))
|
taskChan := make(chan downloadTask, len(tasks))
|
||||||
var wg sync.WaitGroup
|
var wg sync.WaitGroup
|
||||||
|
|
||||||
// Start workers
|
|
||||||
numWorkers := MaxConcurrentDownloads
|
numWorkers := MaxConcurrentDownloads
|
||||||
if numWorkers > len(tasks) {
|
if numWorkers > len(tasks) {
|
||||||
numWorkers = len(tasks)
|
numWorkers = len(tasks)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var sharedClient *http.Client
|
||||||
|
client, err := CreateHTTPClient(customProxy, 60*time.Second)
|
||||||
|
if err != nil {
|
||||||
|
|
||||||
|
sharedClient = &http.Client{
|
||||||
|
Timeout: 60 * time.Second,
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
sharedClient = client
|
||||||
|
}
|
||||||
|
|
||||||
for i := 0; i < numWorkers; i++ {
|
for i := 0; i < numWorkers; i++ {
|
||||||
wg.Add(1)
|
wg.Add(1)
|
||||||
go func() {
|
go func() {
|
||||||
defer wg.Done()
|
defer wg.Done()
|
||||||
client := &http.Client{
|
client := sharedClient
|
||||||
Timeout: 60 * time.Second,
|
|
||||||
}
|
|
||||||
|
|
||||||
for task := range taskChan {
|
for task := range taskChan {
|
||||||
// Check for cancellation
|
|
||||||
select {
|
select {
|
||||||
case <-ctx.Done():
|
case <-ctx.Done():
|
||||||
return
|
return
|
||||||
@@ -179,12 +175,24 @@ func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir str
|
|||||||
}
|
}
|
||||||
|
|
||||||
var status string
|
var status string
|
||||||
// Skip if file already exists
|
markCompleted := func() {
|
||||||
|
completed := atomic.AddInt64(&completedCount, 1)
|
||||||
|
if progress != nil {
|
||||||
|
progress(int(completed), total)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if _, err := os.Stat(task.outputPath); err == nil {
|
if _, err := os.Stat(task.outputPath); err == nil {
|
||||||
atomic.AddInt64(&downloadedCount, 1)
|
|
||||||
status = "skipped"
|
status = "skipped"
|
||||||
|
|
||||||
|
if itemStatus != nil {
|
||||||
|
itemStatus(task.item.TweetID, task.index, status)
|
||||||
|
}
|
||||||
|
atomic.AddInt64(&skippedCount, 1)
|
||||||
|
markCompleted()
|
||||||
|
continue
|
||||||
} else if task.item.Type == "text" {
|
} else if task.item.Type == "text" {
|
||||||
// For text tweets, write content to file
|
|
||||||
if err := os.WriteFile(task.outputPath, []byte(task.item.Content), 0644); err != nil {
|
if err := os.WriteFile(task.outputPath, []byte(task.item.Content), 0644); err != nil {
|
||||||
atomic.AddInt64(&failedCount, 1)
|
atomic.AddInt64(&failedCount, 1)
|
||||||
status = "failed"
|
status = "failed"
|
||||||
@@ -196,43 +204,44 @@ func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir str
|
|||||||
atomic.AddInt64(&failedCount, 1)
|
atomic.AddInt64(&failedCount, 1)
|
||||||
status = "failed"
|
status = "failed"
|
||||||
} else {
|
} else {
|
||||||
|
|
||||||
|
tweetURL := fmt.Sprintf("https://x.com/i/status/%d", task.item.TweetID)
|
||||||
|
|
||||||
|
originalFilename := ExtractOriginalFilename(task.item.URL)
|
||||||
|
|
||||||
|
if err := EmbedMetadata(task.outputPath, task.item.Content, tweetURL, originalFilename); err != nil {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
atomic.AddInt64(&downloadedCount, 1)
|
atomic.AddInt64(&downloadedCount, 1)
|
||||||
status = "success"
|
status = "success"
|
||||||
}
|
}
|
||||||
|
|
||||||
// Emit per-item status
|
|
||||||
if itemStatus != nil {
|
if itemStatus != nil {
|
||||||
itemStatus(task.item.TweetID, task.index, status)
|
itemStatus(task.item.TweetID, task.index, status)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Update progress
|
markCompleted()
|
||||||
completed := atomic.AddInt64(&completedCount, 1)
|
|
||||||
if progress != nil {
|
|
||||||
progress(int(completed), total)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
}
|
}
|
||||||
|
|
||||||
// Send tasks to workers
|
|
||||||
for _, task := range tasks {
|
for _, task := range tasks {
|
||||||
select {
|
select {
|
||||||
case <-ctx.Done():
|
case <-ctx.Done():
|
||||||
close(taskChan)
|
close(taskChan)
|
||||||
wg.Wait()
|
wg.Wait()
|
||||||
return int(downloadedCount), int(failedCount) + (total - int(completedCount)), ctx.Err()
|
return int(downloadedCount), int(skippedCount), int(failedCount) + (total - int(completedCount)), ctx.Err()
|
||||||
case taskChan <- task:
|
case taskChan <- task:
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
close(taskChan)
|
close(taskChan)
|
||||||
|
|
||||||
// Wait for all workers to finish
|
|
||||||
wg.Wait()
|
wg.Wait()
|
||||||
|
|
||||||
return int(downloadedCount), int(failedCount), nil
|
return int(downloadedCount), int(skippedCount), int(failedCount), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// downloadFileWithContext downloads a single file with context support for cancellation
|
|
||||||
func downloadFileWithContext(ctx context.Context, client *http.Client, url, outputPath string) error {
|
func downloadFileWithContext(ctx context.Context, client *http.Client, url, outputPath string) error {
|
||||||
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
|
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -259,14 +268,13 @@ func downloadFileWithContext(ctx context.Context, client *http.Client, url, outp
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// formatTimestamp converts date string to timestamp format
|
|
||||||
func formatTimestamp(dateStr string) string {
|
func formatTimestamp(dateStr string) string {
|
||||||
// Try parsing various date formats
|
|
||||||
formats := []string{
|
formats := []string{
|
||||||
"2006-01-02T15:04:05", // ISO 8601 without timezone (from extractor)
|
"2006-01-02T15:04:05",
|
||||||
"2006-01-02T15:04:05+00:00", // ISO 8601 with timezone
|
"2006-01-02T15:04:05+00:00",
|
||||||
"2006-01-02T15:04:05-07:00", // ISO 8601 with timezone offset
|
"2006-01-02T15:04:05-07:00",
|
||||||
time.RFC3339, // Standard RFC3339
|
time.RFC3339,
|
||||||
"2006-01-02T15:04:05.000Z",
|
"2006-01-02T15:04:05.000Z",
|
||||||
"2006-01-02T15:04:05Z",
|
"2006-01-02T15:04:05Z",
|
||||||
"2006-01-02 15:04:05",
|
"2006-01-02 15:04:05",
|
||||||
@@ -279,35 +287,30 @@ func formatTimestamp(dateStr string) string {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fallback: use empty string to indicate parsing failed
|
|
||||||
return "00000000_000000"
|
return "00000000_000000"
|
||||||
}
|
}
|
||||||
|
|
||||||
// getExtension determines file extension from URL and type
|
|
||||||
func getExtension(mediaURL string, mediaType string) string {
|
func getExtension(mediaURL string, mediaType string) string {
|
||||||
parsedURL, err := url.Parse(mediaURL)
|
parsedURL, err := url.Parse(mediaURL)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return ".jpg"
|
return ".jpg"
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check format query param for Twitter images
|
|
||||||
if format := parsedURL.Query().Get("format"); format != "" {
|
if format := parsedURL.Query().Get("format"); format != "" {
|
||||||
return "." + format
|
return "." + format
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get extension from path
|
|
||||||
path := parsedURL.Path
|
path := parsedURL.Path
|
||||||
ext := filepath.Ext(path)
|
ext := filepath.Ext(path)
|
||||||
if ext != "" {
|
if ext != "" {
|
||||||
return ext
|
return ext
|
||||||
}
|
}
|
||||||
|
|
||||||
// Default based on type
|
|
||||||
switch mediaType {
|
switch mediaType {
|
||||||
case "video":
|
case "video":
|
||||||
return ".mp4"
|
return ".mp4"
|
||||||
case "gif", "animated_gif":
|
case "gif", "animated_gif":
|
||||||
return ".mp4" // Twitter GIFs are actually MP4
|
return ".mp4"
|
||||||
case "text":
|
case "text":
|
||||||
return ".txt"
|
return ".txt"
|
||||||
default:
|
default:
|
||||||
@@ -315,28 +318,23 @@ func getExtension(mediaURL string, mediaType string) string {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// extractFilename extracts filename from URL (legacy)
|
|
||||||
func extractFilename(mediaURL string) string {
|
func extractFilename(mediaURL string) string {
|
||||||
parsedURL, err := url.Parse(mediaURL)
|
parsedURL, err := url.Parse(mediaURL)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Sprintf("media_%d", time.Now().UnixNano())
|
return fmt.Sprintf("media_%d", time.Now().UnixNano())
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get the path part
|
|
||||||
path := parsedURL.Path
|
path := parsedURL.Path
|
||||||
|
|
||||||
// Extract base filename
|
|
||||||
base := filepath.Base(path)
|
base := filepath.Base(path)
|
||||||
|
|
||||||
// Handle Twitter image URLs: /media/XXX -> XXX.jpg
|
|
||||||
if strings.Contains(mediaURL, "pbs.twimg.com/media/") {
|
if strings.Contains(mediaURL, "pbs.twimg.com/media/") {
|
||||||
// Get format from query params
|
|
||||||
format := parsedURL.Query().Get("format")
|
format := parsedURL.Query().Get("format")
|
||||||
if format == "" {
|
if format == "" {
|
||||||
format = "jpg"
|
format = "jpg"
|
||||||
}
|
}
|
||||||
|
|
||||||
// Remove any existing extension
|
|
||||||
if idx := strings.LastIndex(base, "."); idx > 0 {
|
if idx := strings.LastIndex(base, "."); idx > 0 {
|
||||||
base = base[:idx]
|
base = base[:idx]
|
||||||
}
|
}
|
||||||
@@ -344,12 +342,10 @@ func extractFilename(mediaURL string) string {
|
|||||||
return base + "." + format
|
return base + "." + format
|
||||||
}
|
}
|
||||||
|
|
||||||
// Handle Twitter video URLs
|
|
||||||
if strings.Contains(mediaURL, "video.twimg.com") {
|
if strings.Contains(mediaURL, "video.twimg.com") {
|
||||||
return base
|
return base
|
||||||
}
|
}
|
||||||
|
|
||||||
// Default: use base name or generate one
|
|
||||||
if base == "" || base == "." {
|
if base == "" || base == "." {
|
||||||
return fmt.Sprintf("media_%d", time.Now().UnixNano())
|
return fmt.Sprintf("media_%d", time.Now().UnixNano())
|
||||||
}
|
}
|
||||||
@@ -357,7 +353,6 @@ func extractFilename(mediaURL string) string {
|
|||||||
return base
|
return base
|
||||||
}
|
}
|
||||||
|
|
||||||
// downloadFile downloads a single file from URL
|
|
||||||
func downloadFile(client *http.Client, url, outputPath string) error {
|
func downloadFile(client *http.Client, url, outputPath string) error {
|
||||||
resp, err := client.Get(url)
|
resp, err := client.Get(url)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -1,8 +0,0 @@
|
|||||||
//go:build linux || darwin
|
|
||||||
|
|
||||||
package backend
|
|
||||||
|
|
||||||
import _ "embed"
|
|
||||||
|
|
||||||
//go:embed bin/extractor
|
|
||||||
var extractorBin []byte
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
//go:build windows
|
|
||||||
|
|
||||||
package backend
|
|
||||||
|
|
||||||
import _ "embed"
|
|
||||||
|
|
||||||
//go:embed bin/extractor.exe
|
|
||||||
var extractorBin []byte
|
|
||||||
@@ -0,0 +1,546 @@
|
|||||||
|
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")
|
||||||
|
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)
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
@@ -0,0 +1,614 @@
|
|||||||
|
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"`
|
||||||
|
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":
|
||||||
|
if runtime.GOARCH == "amd64" {
|
||||||
|
return "linux-amd64.zip", nil
|
||||||
|
}
|
||||||
|
case "darwin":
|
||||||
|
switch resolveMacOSExtractorArch(runtime.GOARCH, detectMacOSHardwareArch()) {
|
||||||
|
case "amd64":
|
||||||
|
return "macos-amd64.zip", nil
|
||||||
|
case "arm64":
|
||||||
|
return "macos-arm64.zip", nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return "", fmt.Errorf("unsupported platform for prebuilt xtractor: %s/%s", runtime.GOOS, runtime.GOARCH)
|
||||||
|
}
|
||||||
|
|
||||||
|
func resolveMacOSExtractorArch(processArch, hardwareArch string) string {
|
||||||
|
if hardwareArch == "arm64" {
|
||||||
|
return "arm64"
|
||||||
|
}
|
||||||
|
|
||||||
|
return processArch
|
||||||
|
}
|
||||||
|
|
||||||
|
func detectMacOSHardwareArch() string {
|
||||||
|
if runtime.GOOS != "darwin" {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// On Apple Silicon, this stays "1" even if the app itself runs under Rosetta.
|
||||||
|
cmd := exec.Command("sysctl", "-in", "hw.optional.arm64")
|
||||||
|
hideWindow(cmd)
|
||||||
|
output, err := cmd.Output()
|
||||||
|
if err != nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
if strings.TrimSpace(string(output)) == "1" {
|
||||||
|
return "arm64"
|
||||||
|
}
|
||||||
|
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func fetchLatestExtractorRelease() (*githubRelease, error) {
|
||||||
|
client, err := CreateHTTPClient("", 30*time.Second)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to configure xtractor network client: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
req, err := 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
|
||||||
|
}
|
||||||
+466
-129
@@ -1,28 +1,41 @@
|
|||||||
package backend
|
package backend
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"archive/tar"
|
|
||||||
"archive/zip"
|
"archive/zip"
|
||||||
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
neturl "net/url"
|
||||||
"os"
|
"os"
|
||||||
"os/exec"
|
"os/exec"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
"regexp"
|
||||||
"runtime"
|
"runtime"
|
||||||
"strings"
|
"strings"
|
||||||
|
"time"
|
||||||
"github.com/ulikunitz/xz"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// FFmpeg download URLs
|
|
||||||
const (
|
const (
|
||||||
ffmpegWindowsURL = "https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/ffmpeg-master-latest-win64-gpl.zip"
|
ffmpegReleaseAPIURL = "https://api.github.com/repos/afkarxyz/ffmpeg-binaries/releases/latest"
|
||||||
ffmpegLinuxURL = "https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/ffmpeg-master-latest-linux64-gpl.tar.xz"
|
ffmpegLatestReleaseURL = "https://github.com/afkarxyz/ffmpeg-binaries/releases/latest"
|
||||||
ffmpegMacOSURL = "https://evermeet.cx/ffmpeg/getrelease/ffmpeg/zip"
|
ffmpegLatestDownloadBaseURL = "https://github.com/afkarxyz/ffmpeg-binaries/releases/latest/download"
|
||||||
)
|
)
|
||||||
|
|
||||||
// GetFFmpegPath returns the path to ffmpeg binary
|
var ffmpegVersionPattern = regexp.MustCompile(`^[0-9]+(?:\.[0-9]+)+`)
|
||||||
|
|
||||||
|
type ffmpegVersionMetadata struct {
|
||||||
|
Version string `json:"version"`
|
||||||
|
AssetName string `json:"asset_name,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type ffmpegResolvedRelease struct {
|
||||||
|
Version string
|
||||||
|
AssetURL string
|
||||||
|
AssetName string
|
||||||
|
Digest string
|
||||||
|
}
|
||||||
|
|
||||||
func GetFFmpegPath() string {
|
func GetFFmpegPath() string {
|
||||||
homeDir, _ := os.UserHomeDir()
|
homeDir, _ := os.UserHomeDir()
|
||||||
baseDir := filepath.Join(homeDir, ".twitterxmediabatchdownloader")
|
baseDir := filepath.Join(homeDir, ".twitterxmediabatchdownloader")
|
||||||
@@ -35,32 +48,47 @@ func GetFFmpegPath() string {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// IsFFmpegInstalled checks if ffmpeg is available
|
|
||||||
func IsFFmpegInstalled() bool {
|
func IsFFmpegInstalled() bool {
|
||||||
ffmpegPath := GetFFmpegPath()
|
ffmpegPath := GetFFmpegPath()
|
||||||
if _, err := os.Stat(ffmpegPath); err == nil {
|
if _, err := os.Stat(ffmpegPath); err != nil {
|
||||||
return true
|
return false
|
||||||
}
|
}
|
||||||
return false
|
|
||||||
|
cmd := exec.Command(ffmpegPath, "-version")
|
||||||
|
hideWindow(cmd)
|
||||||
|
return cmd.Run() == nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// DownloadFFmpeg downloads ffmpeg binary for current platform
|
func GetFFmpegVersionStatus() DependencyVersionStatus {
|
||||||
func DownloadFFmpeg(progressCallback func(downloaded, total int64)) error {
|
status := DependencyVersionStatus{
|
||||||
var downloadURL string
|
Installed: IsFFmpegInstalled(),
|
||||||
|
|
||||||
switch runtime.GOOS {
|
|
||||||
case "windows":
|
|
||||||
downloadURL = ffmpegWindowsURL
|
|
||||||
case "linux":
|
|
||||||
downloadURL = ffmpegLinuxURL
|
|
||||||
case "darwin":
|
|
||||||
downloadURL = ffmpegMacOSURL
|
|
||||||
default:
|
|
||||||
return fmt.Errorf("unsupported platform: %s", runtime.GOOS)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create temp file for download
|
if status.Installed {
|
||||||
tempFile, err := os.CreateTemp("", "ffmpeg-*")
|
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 {
|
if err != nil {
|
||||||
return fmt.Errorf("failed to create temp file: %v", err)
|
return fmt.Errorf("failed to create temp file: %v", err)
|
||||||
}
|
}
|
||||||
@@ -68,8 +96,227 @@ func DownloadFFmpeg(progressCallback func(downloaded, total int64)) error {
|
|||||||
defer os.Remove(tempPath)
|
defer os.Remove(tempPath)
|
||||||
defer tempFile.Close()
|
defer tempFile.Close()
|
||||||
|
|
||||||
// Download file
|
if err := downloadFFmpegArchive(releaseInfo.AssetURL, tempFile, progressCallback); err != nil {
|
||||||
resp, err := http.Get(downloadURL)
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := tempFile.Close(); err != nil {
|
||||||
|
return fmt.Errorf("failed to finalize ffmpeg archive: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if releaseInfo.Digest != "" {
|
||||||
|
if err := verifyDownloadedDigest(tempPath, releaseInfo.Digest); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ffmpegPath := GetFFmpegPath()
|
||||||
|
baseDir := filepath.Dir(ffmpegPath)
|
||||||
|
if err := os.MkdirAll(baseDir, 0755); err != nil {
|
||||||
|
return fmt.Errorf("failed to create ffmpeg directory: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := extractFFmpegFromZip(tempPath, ffmpegPath); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
_ = writeFFmpegVersionMetadata(ffmpegVersionMetadata{
|
||||||
|
Version: releaseInfo.Version,
|
||||||
|
AssetName: releaseInfo.AssetName,
|
||||||
|
})
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func getFFmpegAssetName() (string, error) {
|
||||||
|
switch runtime.GOOS {
|
||||||
|
case "windows":
|
||||||
|
return "ffmpeg-windows.zip", nil
|
||||||
|
case "linux":
|
||||||
|
switch runtime.GOARCH {
|
||||||
|
case "amd64":
|
||||||
|
return "ffmpeg-linux-amd64.zip", nil
|
||||||
|
case "arm64":
|
||||||
|
return "ffmpeg-linux-arm64v8.zip", nil
|
||||||
|
}
|
||||||
|
case "darwin":
|
||||||
|
switch runtime.GOARCH {
|
||||||
|
case "amd64":
|
||||||
|
return "ffmpeg-macos-amd64.zip", nil
|
||||||
|
case "arm64":
|
||||||
|
return "ffmpeg-macos-arm64.zip", nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return "", fmt.Errorf("unsupported platform for ffmpeg binary: %s/%s", runtime.GOOS, runtime.GOARCH)
|
||||||
|
}
|
||||||
|
|
||||||
|
func resolveLatestFFmpegRelease(assetName string) (ffmpegResolvedRelease, error) {
|
||||||
|
release, apiErr := fetchLatestFFmpegRelease()
|
||||||
|
if apiErr == nil {
|
||||||
|
asset, assetErr := findFFmpegAsset(release.Assets, assetName)
|
||||||
|
if assetErr == nil {
|
||||||
|
return ffmpegResolvedRelease{
|
||||||
|
Version: normalizeFFmpegVersion(release.TagName),
|
||||||
|
AssetURL: asset.BrowserDownloadURL,
|
||||||
|
AssetName: asset.Name,
|
||||||
|
Digest: asset.Digest,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
apiErr = assetErr
|
||||||
|
}
|
||||||
|
|
||||||
|
fallbackVersion, fallbackErr := fetchLatestFFmpegVersionFromRedirect()
|
||||||
|
if fallbackErr != nil {
|
||||||
|
return ffmpegResolvedRelease{}, fmt.Errorf("failed to resolve latest ffmpeg release: %v; fallback failed: %v", apiErr, fallbackErr)
|
||||||
|
}
|
||||||
|
|
||||||
|
return ffmpegResolvedRelease{
|
||||||
|
Version: fallbackVersion,
|
||||||
|
AssetURL: buildLatestFFmpegDownloadURL(assetName),
|
||||||
|
AssetName: assetName,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func fetchLatestFFmpegVersion() (string, error) {
|
||||||
|
release, err := fetchLatestFFmpegRelease()
|
||||||
|
if err == nil {
|
||||||
|
version := normalizeFFmpegVersion(release.TagName)
|
||||||
|
if version != "" {
|
||||||
|
return version, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fallbackVersion, fallbackErr := fetchLatestFFmpegVersionFromRedirect()
|
||||||
|
if fallbackErr == nil {
|
||||||
|
return fallbackVersion, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("failed to fetch latest ffmpeg version: %v; fallback failed: %v", err, fallbackErr)
|
||||||
|
}
|
||||||
|
|
||||||
|
return "", fmt.Errorf("failed to determine latest ffmpeg version")
|
||||||
|
}
|
||||||
|
|
||||||
|
func fetchLatestFFmpegRelease() (*githubRelease, error) {
|
||||||
|
client, err := CreateHTTPClient("", 30*time.Second)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to configure ffmpeg network client: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
req, err := newFFmpegGitHubRequest(ffmpegReleaseAPIURL)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
resp, err := client.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to fetch ffmpeg release info: %v", err)
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
if resp.StatusCode != http.StatusOK {
|
||||||
|
return nil, fmt.Errorf("failed to fetch ffmpeg release info: status %d", resp.StatusCode)
|
||||||
|
}
|
||||||
|
|
||||||
|
var release githubRelease
|
||||||
|
if err := json.NewDecoder(resp.Body).Decode(&release); err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to decode ffmpeg release info: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &release, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func newFFmpegGitHubRequest(url string) (*http.Request, error) {
|
||||||
|
req, err := http.NewRequest(http.MethodGet, url, nil)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to create ffmpeg GitHub request: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
req.Header.Set("Accept", "application/vnd.github+json")
|
||||||
|
req.Header.Set("User-Agent", "Twitter-X-Media-Batch-Downloader")
|
||||||
|
return req, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func findFFmpegAsset(assets []githubReleaseAsset, assetName string) (*githubReleaseAsset, error) {
|
||||||
|
for i := range assets {
|
||||||
|
if assets[i].Name == assetName {
|
||||||
|
return &assets[i], nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil, fmt.Errorf("ffmpeg asset %q not found in latest release", assetName)
|
||||||
|
}
|
||||||
|
|
||||||
|
func fetchLatestFFmpegVersionFromRedirect() (string, error) {
|
||||||
|
client, err := CreateHTTPClient("", 30*time.Second)
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("failed to configure ffmpeg redirect client: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
|
||||||
|
return http.ErrUseLastResponse
|
||||||
|
}
|
||||||
|
|
||||||
|
req, err := http.NewRequest(http.MethodGet, ffmpegLatestReleaseURL, nil)
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("failed to create ffmpeg redirect request: %v", err)
|
||||||
|
}
|
||||||
|
req.Header.Set("User-Agent", "Twitter-X-Media-Batch-Downloader")
|
||||||
|
|
||||||
|
resp, err := client.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("failed to resolve latest ffmpeg redirect: %v", err)
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
location := resp.Header.Get("Location")
|
||||||
|
if location == "" && resp.Request != nil && resp.Request.URL != nil {
|
||||||
|
location = resp.Request.URL.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
version := parseFFmpegVersionFromReleaseURL(location)
|
||||||
|
if version == "" {
|
||||||
|
return "", fmt.Errorf("failed to parse ffmpeg version from redirect URL")
|
||||||
|
}
|
||||||
|
|
||||||
|
return version, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseFFmpegVersionFromReleaseURL(releaseURL string) string {
|
||||||
|
parsed, err := neturl.Parse(strings.TrimSpace(releaseURL))
|
||||||
|
if err != nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
segments := strings.Split(strings.Trim(parsed.Path, "/"), "/")
|
||||||
|
for index, segment := range segments {
|
||||||
|
if (segment == "tag" || segment == "download") && index+1 < len(segments) {
|
||||||
|
return normalizeFFmpegVersion(segments[index+1])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func buildLatestFFmpegDownloadURL(assetName string) string {
|
||||||
|
return ffmpegLatestDownloadBaseURL + "/" + assetName
|
||||||
|
}
|
||||||
|
|
||||||
|
func downloadFFmpegArchive(downloadURL string, destination *os.File, progressCallback func(downloaded, total int64)) error {
|
||||||
|
client, err := CreateHTTPClient("", 10*time.Minute)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to configure ffmpeg download client: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
req, err := http.NewRequest(http.MethodGet, downloadURL, nil)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to create ffmpeg download request: %v", err)
|
||||||
|
}
|
||||||
|
req.Header.Set("User-Agent", "Twitter-X-Media-Batch-Downloader")
|
||||||
|
|
||||||
|
resp, err := client.Do(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("failed to download ffmpeg: %v", err)
|
return fmt.Errorf("failed to download ffmpeg: %v", err)
|
||||||
}
|
}
|
||||||
@@ -79,7 +326,6 @@ func DownloadFFmpeg(progressCallback func(downloaded, total int64)) error {
|
|||||||
return fmt.Errorf("failed to download ffmpeg: status %d", resp.StatusCode)
|
return fmt.Errorf("failed to download ffmpeg: status %d", resp.StatusCode)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Copy with progress
|
|
||||||
total := resp.ContentLength
|
total := resp.ContentLength
|
||||||
var downloaded int64
|
var downloaded int64
|
||||||
buf := make([]byte, 32*1024)
|
buf := make([]byte, 32*1024)
|
||||||
@@ -87,9 +333,8 @@ func DownloadFFmpeg(progressCallback func(downloaded, total int64)) error {
|
|||||||
for {
|
for {
|
||||||
n, err := resp.Body.Read(buf)
|
n, err := resp.Body.Read(buf)
|
||||||
if n > 0 {
|
if n > 0 {
|
||||||
_, writeErr := tempFile.Write(buf[:n])
|
if _, writeErr := destination.Write(buf[:n]); writeErr != nil {
|
||||||
if writeErr != nil {
|
return fmt.Errorf("failed to write ffmpeg archive: %v", writeErr)
|
||||||
return fmt.Errorf("failed to write temp file: %v", writeErr)
|
|
||||||
}
|
}
|
||||||
downloaded += int64(n)
|
downloaded += int64(n)
|
||||||
if progressCallback != nil {
|
if progressCallback != nil {
|
||||||
@@ -100,30 +345,14 @@ func DownloadFFmpeg(progressCallback func(downloaded, total int64)) error {
|
|||||||
break
|
break
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("failed to download: %v", err)
|
return fmt.Errorf("failed to download ffmpeg: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
tempFile.Close()
|
|
||||||
|
|
||||||
// Extract ffmpeg binary
|
|
||||||
ffmpegPath := GetFFmpegPath()
|
|
||||||
baseDir := filepath.Dir(ffmpegPath)
|
|
||||||
if err := os.MkdirAll(baseDir, 0755); err != nil {
|
|
||||||
return fmt.Errorf("failed to create directory: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
switch runtime.GOOS {
|
|
||||||
case "windows", "darwin":
|
|
||||||
return extractFromZip(tempPath, ffmpegPath)
|
|
||||||
case "linux":
|
|
||||||
return extractFromTarXz(tempPath, ffmpegPath)
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// extractFromZip extracts ffmpeg from zip archive
|
func extractFFmpegFromZip(zipPath, destPath string) error {
|
||||||
func extractFromZip(zipPath, destPath string) error {
|
|
||||||
r, err := zip.OpenReader(zipPath)
|
r, err := zip.OpenReader(zipPath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("failed to open zip: %v", err)
|
return fmt.Errorf("failed to open zip: %v", err)
|
||||||
@@ -131,85 +360,176 @@ func extractFromZip(zipPath, destPath string) error {
|
|||||||
defer r.Close()
|
defer r.Close()
|
||||||
|
|
||||||
for _, f := range r.File {
|
for _, f := range r.File {
|
||||||
// Look for ffmpeg binary
|
|
||||||
name := filepath.Base(f.Name)
|
name := filepath.Base(f.Name)
|
||||||
if name == "ffmpeg" || name == "ffmpeg.exe" {
|
if name != "ffmpeg" && name != "ffmpeg.exe" {
|
||||||
rc, err := f.Open()
|
continue
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("failed to open file in zip: %v", err)
|
|
||||||
}
|
|
||||||
defer rc.Close()
|
|
||||||
|
|
||||||
out, err := os.Create(destPath)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("failed to create output file: %v", err)
|
|
||||||
}
|
|
||||||
defer out.Close()
|
|
||||||
|
|
||||||
if _, err := io.Copy(out, rc); err != nil {
|
|
||||||
return fmt.Errorf("failed to extract file: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Make executable on Unix
|
|
||||||
if runtime.GOOS != "windows" {
|
|
||||||
os.Chmod(destPath, 0755)
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
return fmt.Errorf("ffmpeg binary not found in archive")
|
rc, err := f.Open()
|
||||||
}
|
|
||||||
|
|
||||||
// extractFromTarXz extracts ffmpeg from tar.xz archive
|
|
||||||
func extractFromTarXz(tarXzPath, destPath string) error {
|
|
||||||
file, err := os.Open(tarXzPath)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("failed to open tar.xz: %v", err)
|
|
||||||
}
|
|
||||||
defer file.Close()
|
|
||||||
|
|
||||||
xzReader, err := xz.NewReader(file)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("failed to create xz reader: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
tarReader := tar.NewReader(xzReader)
|
|
||||||
|
|
||||||
for {
|
|
||||||
header, err := tarReader.Next()
|
|
||||||
if err == io.EOF {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("failed to read tar: %v", err)
|
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)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Look for ffmpeg binary
|
if runtime.GOOS != "windows" {
|
||||||
name := filepath.Base(header.Name)
|
if err := os.Chmod(destPath, 0755); err != nil {
|
||||||
if name == "ffmpeg" && header.Typeflag == tar.TypeReg {
|
return fmt.Errorf("failed to make ffmpeg executable: %v", err)
|
||||||
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, tarReader); err != nil {
|
|
||||||
return fmt.Errorf("failed to extract file: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
os.Chmod(destPath, 0755)
|
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
return fmt.Errorf("ffmpeg binary not found in archive")
|
return fmt.Errorf("ffmpeg binary not found in archive")
|
||||||
}
|
}
|
||||||
|
|
||||||
// ConvertMP4ToGIF converts an MP4 file to GIF using ffmpeg
|
func getInstalledFFmpegVersion() (string, error) {
|
||||||
// quality: "fast" for simple conversion, "better" for optimized palette
|
ffmpegPath := GetFFmpegPath()
|
||||||
// resolution: "original", "high" (800px), "medium" (600px), "low" (400px)
|
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 "):])
|
||||||
|
}
|
||||||
|
|
||||||
|
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 {
|
func ConvertMP4ToGIF(inputPath, outputPath, quality, resolution string) error {
|
||||||
ffmpegPath := GetFFmpegPath()
|
ffmpegPath := GetFFmpegPath()
|
||||||
|
|
||||||
@@ -220,15 +540,35 @@ func ConvertMP4ToGIF(inputPath, outputPath, quality, resolution string) error {
|
|||||||
var args []string
|
var args []string
|
||||||
|
|
||||||
if quality == "fast" {
|
if quality == "fast" {
|
||||||
// Fast mode: simple conversion
|
var scaleFilter string
|
||||||
args = []string{
|
switch resolution {
|
||||||
"-i", inputPath,
|
case "high":
|
||||||
"-loop", "0",
|
scaleFilter = "scale=800:-1"
|
||||||
"-y",
|
case "medium":
|
||||||
outputPath,
|
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 {
|
} else {
|
||||||
// Better mode: optimized palette with dithering
|
|
||||||
var filter string
|
var filter string
|
||||||
|
|
||||||
switch resolution {
|
switch resolution {
|
||||||
@@ -238,11 +578,10 @@ func ConvertMP4ToGIF(inputPath, outputPath, quality, resolution string) error {
|
|||||||
filter = "scale=600:-1:flags=lanczos,palettegen=stats_mode=full[palette];[0:v]scale=600:-1:flags=lanczos[scaled];[scaled][palette]paletteuse=dither=sierra2_4a"
|
filter = "scale=600:-1:flags=lanczos,palettegen=stats_mode=full[palette];[0:v]scale=600:-1:flags=lanczos[scaled];[scaled][palette]paletteuse=dither=sierra2_4a"
|
||||||
case "low":
|
case "low":
|
||||||
filter = "scale=400:-1:flags=lanczos,palettegen=stats_mode=full[palette];[0:v]scale=400:-1:flags=lanczos[scaled];[scaled][palette]paletteuse=dither=sierra2_4a"
|
filter = "scale=400:-1:flags=lanczos,palettegen=stats_mode=full[palette];[0:v]scale=400:-1:flags=lanczos[scaled];[scaled][palette]paletteuse=dither=sierra2_4a"
|
||||||
default: // original
|
default:
|
||||||
filter = "palettegen=stats_mode=full[palette];[0:v][palette]paletteuse=dither=sierra2_4a"
|
filter = "palettegen=stats_mode=full[palette];[0:v][palette]paletteuse=dither=sierra2_4a"
|
||||||
}
|
}
|
||||||
|
|
||||||
// Set FPS based on resolution
|
|
||||||
fps := "15"
|
fps := "15"
|
||||||
if resolution == "medium" {
|
if resolution == "medium" {
|
||||||
fps = "10"
|
fps = "10"
|
||||||
@@ -260,7 +599,7 @@ func ConvertMP4ToGIF(inputPath, outputPath, quality, resolution string) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
cmd := exec.Command(ffmpegPath, args...)
|
cmd := exec.Command(ffmpegPath, args...)
|
||||||
hideWindow(cmd) // Hide console window on Windows
|
hideWindow(cmd)
|
||||||
output, err := cmd.CombinedOutput()
|
output, err := cmd.CombinedOutput()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("ffmpeg error: %v, output: %s", err, string(output))
|
return fmt.Errorf("ffmpeg error: %v, output: %s", err, string(output))
|
||||||
@@ -269,13 +608,11 @@ func ConvertMP4ToGIF(inputPath, outputPath, quality, resolution string) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ConvertGIFsInFolder converts all MP4 files in gifs folder to actual GIF format
|
|
||||||
func ConvertGIFsInFolder(folderPath, quality, resolution string, deleteOriginal bool) (converted int, failed int, err error) {
|
func ConvertGIFsInFolder(folderPath, quality, resolution string, deleteOriginal bool) (converted int, failed int, err error) {
|
||||||
if !IsFFmpegInstalled() {
|
if !IsFFmpegInstalled() {
|
||||||
return 0, 0, fmt.Errorf("ffmpeg not installed")
|
return 0, 0, fmt.Errorf("ffmpeg not installed")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Clean the path to handle cross-platform path separators
|
|
||||||
cleanPath := filepath.Clean(folderPath)
|
cleanPath := filepath.Clean(folderPath)
|
||||||
gifsFolder := filepath.Join(cleanPath, "gifs")
|
gifsFolder := filepath.Join(cleanPath, "gifs")
|
||||||
if _, err := os.Stat(gifsFolder); os.IsNotExist(err) {
|
if _, err := os.Stat(gifsFolder); os.IsNotExist(err) {
|
||||||
|
|||||||
+70
-5
@@ -2,7 +2,9 @@ package backend
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"os"
|
||||||
"os/exec"
|
"os/exec"
|
||||||
|
"path/filepath"
|
||||||
"runtime"
|
"runtime"
|
||||||
|
|
||||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||||
@@ -13,9 +15,9 @@ func OpenFolderInExplorer(path string) error {
|
|||||||
|
|
||||||
switch runtime.GOOS {
|
switch runtime.GOOS {
|
||||||
case "windows":
|
case "windows":
|
||||||
// Use cmd /c start to open explorer - more reliable
|
|
||||||
cmd = exec.Command("cmd", "/c", "start", "", path)
|
cmd = exec.Command("cmd", "/c", "start", "", path)
|
||||||
case "darwin": // macOS
|
case "darwin":
|
||||||
cmd = exec.Command("open", path)
|
cmd = exec.Command("open", path)
|
||||||
case "linux":
|
case "linux":
|
||||||
cmd = exec.Command("xdg-open", path)
|
cmd = exec.Command("xdg-open", path)
|
||||||
@@ -23,12 +25,12 @@ func OpenFolderInExplorer(path string) error {
|
|||||||
cmd = exec.Command("xdg-open", path)
|
cmd = exec.Command("xdg-open", path)
|
||||||
}
|
}
|
||||||
|
|
||||||
hideWindow(cmd) // Hide console window on Windows
|
hideWindow(cmd)
|
||||||
return cmd.Run()
|
return cmd.Run()
|
||||||
}
|
}
|
||||||
|
|
||||||
func SelectFolderDialog(ctx context.Context, defaultPath string) (string, error) {
|
func SelectFolderDialog(ctx context.Context, defaultPath string) (string, error) {
|
||||||
// If defaultPath is empty, use default download path
|
|
||||||
if defaultPath == "" {
|
if defaultPath == "" {
|
||||||
defaultPath = GetDefaultDownloadPath()
|
defaultPath = GetDefaultDownloadPath()
|
||||||
}
|
}
|
||||||
@@ -43,10 +45,73 @@ func SelectFolderDialog(ctx context.Context, defaultPath string) (string, error)
|
|||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
// If user cancelled, selectedPath will be empty
|
|
||||||
if selectedPath == "" {
|
if selectedPath == "" {
|
||||||
return "", nil
|
return "", nil
|
||||||
}
|
}
|
||||||
|
|
||||||
return selectedPath, 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")
|
||||||
|
}
|
||||||
@@ -0,0 +1,198 @@
|
|||||||
|
package backend
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"net/url"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"path/filepath"
|
||||||
|
"regexp"
|
||||||
|
"runtime"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
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 matched, _ := regexp.MatchString(`^[A-Za-z0-9_]+$`, filename); matched && 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 matched, _ := regexp.MatchString(`^[A-Za-z0-9_]+$`, filename); matched && 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 matched, _ := regexp.MatchString(`^[A-Za-z0-9_]+$`, filename); matched {
|
||||||
|
hasLetter, _ := regexp.MatchString(`[A-Za-z]`, filename)
|
||||||
|
if hasLetter && len(filename) >= 8 {
|
||||||
|
return filename
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func EmbedMetadata(filePath string, tweetContent string, tweetURL string, originalFilename string) error {
|
||||||
|
ext := strings.ToLower(filepath.Ext(filePath))
|
||||||
|
|
||||||
|
switch ext {
|
||||||
|
case ".jpg", ".jpeg":
|
||||||
|
return embedImageMetadata(filePath, tweetContent, tweetURL, originalFilename)
|
||||||
|
case ".mp4":
|
||||||
|
return embedVideoMetadata(filePath, tweetContent, tweetURL, originalFilename)
|
||||||
|
default:
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func embedImageMetadata(filePath string, tweetContent string, tweetURL string, originalFilename string) error {
|
||||||
|
|
||||||
|
exiftoolPath := findExifTool()
|
||||||
|
if exiftoolPath == "" {
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
metadataComment := buildMetadataComment(tweetContent, tweetURL, originalFilename)
|
||||||
|
|
||||||
|
args := []string{
|
||||||
|
"-overwrite_original",
|
||||||
|
"-Comment=" + metadataComment,
|
||||||
|
filePath,
|
||||||
|
}
|
||||||
|
|
||||||
|
cmd := exec.Command(exiftoolPath, args...)
|
||||||
|
hideWindow(cmd)
|
||||||
|
output, err := cmd.CombinedOutput()
|
||||||
|
if err != nil {
|
||||||
|
|
||||||
|
return fmt.Errorf("exiftool error (non-fatal): %v, output: %s", err, string(output))
|
||||||
|
}
|
||||||
|
|
||||||
|
_ = output
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func embedVideoMetadata(filePath string, tweetContent string, tweetURL string, originalFilename string) error {
|
||||||
|
|
||||||
|
exiftoolPath := findExifTool()
|
||||||
|
if exiftoolPath == "" {
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
return embedVideoMetadataWithExifTool(exiftoolPath, filePath, tweetContent, tweetURL, originalFilename)
|
||||||
|
}
|
||||||
|
|
||||||
|
func embedVideoMetadataWithExifTool(exiftoolPath string, filePath string, tweetContent string, tweetURL string, originalFilename string) error {
|
||||||
|
|
||||||
|
metadataComment := buildMetadataComment(tweetContent, tweetURL, originalFilename)
|
||||||
|
|
||||||
|
args := []string{
|
||||||
|
"-overwrite_original",
|
||||||
|
"-Comment=" + metadataComment,
|
||||||
|
filePath,
|
||||||
|
}
|
||||||
|
|
||||||
|
cmd := exec.Command(exiftoolPath, args...)
|
||||||
|
hideWindow(cmd)
|
||||||
|
output, err := cmd.CombinedOutput()
|
||||||
|
if err != nil {
|
||||||
|
|
||||||
|
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 ""
|
||||||
|
}
|
||||||
+221
-289
@@ -1,8 +1,7 @@
|
|||||||
package backend
|
package backend
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"crypto/sha256"
|
"bytes"
|
||||||
"encoding/hex"
|
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/url"
|
"net/url"
|
||||||
@@ -11,40 +10,86 @@ import (
|
|||||||
"path/filepath"
|
"path/filepath"
|
||||||
"runtime"
|
"runtime"
|
||||||
"strings"
|
"strings"
|
||||||
|
"sync"
|
||||||
)
|
)
|
||||||
|
|
||||||
// getExecutableName returns the appropriate executable name for the current OS
|
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) ([]byte, error) {
|
||||||
|
var output bytes.Buffer
|
||||||
|
cmd.Stdout = &output
|
||||||
|
cmd.Stderr = &output
|
||||||
|
|
||||||
|
hideWindow(cmd)
|
||||||
|
if err := cmd.Start(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
registerExtractorCommand(cmd)
|
||||||
|
defer unregisterExtractorCommand(cmd)
|
||||||
|
|
||||||
|
err := cmd.Wait()
|
||||||
|
return output.Bytes(), err
|
||||||
|
}
|
||||||
|
|
||||||
func getExecutableName() string {
|
func getExecutableName() string {
|
||||||
|
if runtime.GOOS == "windows" {
|
||||||
|
return "xtractor.exe"
|
||||||
|
}
|
||||||
|
return "xtractor"
|
||||||
|
}
|
||||||
|
|
||||||
|
func getLegacyExecutableName() string {
|
||||||
if runtime.GOOS == "windows" {
|
if runtime.GOOS == "windows" {
|
||||||
return "extractor.exe"
|
return "extractor.exe"
|
||||||
}
|
}
|
||||||
return "extractor"
|
return "extractor"
|
||||||
}
|
}
|
||||||
|
|
||||||
// KillAllExtractorProcesses kills all running extractor processes
|
|
||||||
// This is useful for cleanup when starting fresh or when user stops fetch
|
|
||||||
func KillAllExtractorProcesses() {
|
func KillAllExtractorProcesses() {
|
||||||
exeName := getExecutableName()
|
activeExtractorCommands.Lock()
|
||||||
|
commands := make([]*exec.Cmd, 0, len(activeExtractorCommands.byPID))
|
||||||
var cmd *exec.Cmd
|
for _, cmd := range activeExtractorCommands.byPID {
|
||||||
if runtime.GOOS == "windows" {
|
commands = append(commands, cmd)
|
||||||
// Use taskkill on Windows
|
|
||||||
cmd = exec.Command("taskkill", "/F", "/IM", exeName)
|
|
||||||
} else {
|
|
||||||
// Use pkill on Unix
|
|
||||||
cmd = exec.Command("pkill", "-f", exeName)
|
|
||||||
}
|
}
|
||||||
|
activeExtractorCommands.byPID = make(map[int]*exec.Cmd)
|
||||||
|
activeExtractorCommands.Unlock()
|
||||||
|
|
||||||
hideWindow(cmd)
|
for _, cmd := range commands {
|
||||||
cmd.CombinedOutput() // Ignore errors - it's okay if no processes found
|
if cmd != nil && cmd.Process != nil {
|
||||||
|
_ = cmd.Process.Kill()
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// parseExtractorError parses the extractor output and returns a user-friendly error message
|
|
||||||
// while preserving the original error from gallery-dl
|
|
||||||
func parseExtractorError(output string, username string) string {
|
func parseExtractorError(output string, username string) string {
|
||||||
outputLower := strings.ToLower(output)
|
outputLower := strings.ToLower(output)
|
||||||
|
|
||||||
// Extract the actual error line from gallery-dl output
|
|
||||||
lines := strings.Split(output, "\n")
|
lines := strings.Split(output, "\n")
|
||||||
var errorLine string
|
var errorLine string
|
||||||
for _, line := range lines {
|
for _, line := range lines {
|
||||||
@@ -58,12 +103,10 @@ func parseExtractorError(output string, username string) string {
|
|||||||
errorLine = strings.TrimSpace(output)
|
errorLine = strings.TrimSpace(output)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Truncate if too long
|
|
||||||
if len(errorLine) > 300 {
|
if len(errorLine) > 300 {
|
||||||
errorLine = errorLine[:300] + "..."
|
errorLine = errorLine[:300] + "..."
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add context hint based on error type, but keep original message
|
|
||||||
var hint string
|
var hint string
|
||||||
if strings.Contains(outputLower, "unable to retrieve tweets from this timeline") {
|
if strings.Contains(outputLower, "unable to retrieve tweets from this timeline") {
|
||||||
hint = " [Hint: End of timeline reached or rate limited - data already fetched has been saved]"
|
hint = " [Hint: End of timeline reached or rate limited - data already fetched has been saved]"
|
||||||
@@ -80,23 +123,20 @@ func parseExtractorError(output string, username string) string {
|
|||||||
return errorLine + hint
|
return errorLine + hint
|
||||||
}
|
}
|
||||||
|
|
||||||
// TweetIDString is a custom type that unmarshals int64 but marshals as string
|
|
||||||
type TweetIDString int64
|
type TweetIDString int64
|
||||||
|
|
||||||
// MarshalJSON converts TweetIDString to JSON string to preserve precision in JavaScript
|
|
||||||
func (t TweetIDString) MarshalJSON() ([]byte, error) {
|
func (t TweetIDString) MarshalJSON() ([]byte, error) {
|
||||||
return []byte(fmt.Sprintf(`"%d"`, t)), nil
|
return []byte(fmt.Sprintf(`"%d"`, t)), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// UnmarshalJSON accepts both number and string from JSON
|
|
||||||
func (t *TweetIDString) UnmarshalJSON(data []byte) error {
|
func (t *TweetIDString) UnmarshalJSON(data []byte) error {
|
||||||
// Try to unmarshal as number first (from extractor)
|
|
||||||
var num int64
|
var num int64
|
||||||
if err := json.Unmarshal(data, &num); err == nil {
|
if err := json.Unmarshal(data, &num); err == nil {
|
||||||
*t = TweetIDString(num)
|
*t = TweetIDString(num)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
// Try as string (for future compatibility)
|
|
||||||
var str string
|
var str string
|
||||||
if err := json.Unmarshal(data, &str); err == nil {
|
if err := json.Unmarshal(data, &str); err == nil {
|
||||||
parsed, err := fmt.Sscanf(str, "%d", &num)
|
parsed, err := fmt.Sscanf(str, "%d", &num)
|
||||||
@@ -109,14 +149,12 @@ func (t *TweetIDString) UnmarshalJSON(data []byte) error {
|
|||||||
return fmt.Errorf("tweet_id must be number or string")
|
return fmt.Errorf("tweet_id must be number or string")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Author represents tweet author information from extractor
|
|
||||||
type Author struct {
|
type Author struct {
|
||||||
ID int64 `json:"id"`
|
ID int64 `json:"id"`
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
Nick string `json:"nick"`
|
Nick string `json:"nick"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// UserInfo represents full user information from extractor
|
|
||||||
type UserInfo struct {
|
type UserInfo struct {
|
||||||
ID int64 `json:"id"`
|
ID int64 `json:"id"`
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
@@ -137,7 +175,6 @@ type UserInfo struct {
|
|||||||
URL string `json:"url"`
|
URL string `json:"url"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// CLIMediaItem represents a single media entry from extractor CLI
|
|
||||||
type CLIMediaItem struct {
|
type CLIMediaItem struct {
|
||||||
URL string `json:"url"`
|
URL string `json:"url"`
|
||||||
TweetID TweetIDString `json:"tweet_id"`
|
TweetID TweetIDString `json:"tweet_id"`
|
||||||
@@ -165,7 +202,6 @@ type CLIMediaItem struct {
|
|||||||
Sensitive bool `json:"sensitive"`
|
Sensitive bool `json:"sensitive"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// TweetMetadata represents tweet metadata from extractor
|
|
||||||
type TweetMetadata struct {
|
type TweetMetadata struct {
|
||||||
TweetID TweetIDString `json:"tweet_id"`
|
TweetID TweetIDString `json:"tweet_id"`
|
||||||
RetweetID TweetIDString `json:"retweet_id,omitempty"`
|
RetweetID TweetIDString `json:"retweet_id,omitempty"`
|
||||||
@@ -186,36 +222,35 @@ type TweetMetadata struct {
|
|||||||
Sensitive bool `json:"sensitive,omitempty"`
|
Sensitive bool `json:"sensitive,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// CLIResponse represents the raw response from extractor CLI
|
|
||||||
type CLIResponse struct {
|
type CLIResponse struct {
|
||||||
Media []CLIMediaItem `json:"media"`
|
Media []CLIMediaItem `json:"media"`
|
||||||
Metadata []TweetMetadata `json:"metadata"`
|
Metadata []TweetMetadata `json:"metadata"`
|
||||||
Cursor string `json:"cursor,omitempty"` // Cursor for resume
|
Cursor string `json:"cursor,omitempty"`
|
||||||
Total int `json:"total,omitempty"` // Total items fetched
|
Total int `json:"total,omitempty"`
|
||||||
Completed bool `json:"completed,omitempty"` // True if all fetched
|
Completed bool `json:"completed,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// TimelineEntry represents a single media entry for frontend (converted from MediaItem)
|
|
||||||
type TimelineEntry struct {
|
type TimelineEntry struct {
|
||||||
URL string `json:"url"`
|
URL string `json:"url"`
|
||||||
Date string `json:"date"`
|
Date string `json:"date"`
|
||||||
TweetID TweetIDString `json:"tweet_id"`
|
TweetID TweetIDString `json:"tweet_id"`
|
||||||
Type string `json:"type"`
|
Type string `json:"type"`
|
||||||
IsRetweet bool `json:"is_retweet"`
|
IsRetweet bool `json:"is_retweet"`
|
||||||
Extension string `json:"extension"`
|
Extension string `json:"extension"`
|
||||||
Width int `json:"width"`
|
Width int `json:"width"`
|
||||||
Height int `json:"height"`
|
Height int `json:"height"`
|
||||||
Content string `json:"content,omitempty"`
|
Content string `json:"content,omitempty"`
|
||||||
ViewCount int `json:"view_count,omitempty"`
|
ViewCount int `json:"view_count,omitempty"`
|
||||||
BookmarkCount int `json:"bookmark_count,omitempty"`
|
BookmarkCount int `json:"bookmark_count,omitempty"`
|
||||||
FavoriteCount int `json:"favorite_count,omitempty"`
|
FavoriteCount int `json:"favorite_count,omitempty"`
|
||||||
RetweetCount int `json:"retweet_count,omitempty"`
|
RetweetCount int `json:"retweet_count,omitempty"`
|
||||||
ReplyCount int `json:"reply_count,omitempty"`
|
ReplyCount int `json:"reply_count,omitempty"`
|
||||||
Source string `json:"source,omitempty"`
|
Source string `json:"source,omitempty"`
|
||||||
Verified bool `json:"verified,omitempty"`
|
Verified bool `json:"verified,omitempty"`
|
||||||
|
OriginalFilename string `json:"original_filename,omitempty"`
|
||||||
|
AuthorUsername string `json:"author_username,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// AccountInfo represents Twitter account information (derived from metadata)
|
|
||||||
type AccountInfo struct {
|
type AccountInfo struct {
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
Nick string `json:"nick"`
|
Nick string `json:"nick"`
|
||||||
@@ -226,65 +261,58 @@ type AccountInfo struct {
|
|||||||
StatusesCount int `json:"statuses_count"`
|
StatusesCount int `json:"statuses_count"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// ExtractMetadata represents extraction metadata
|
|
||||||
type ExtractMetadata struct {
|
type ExtractMetadata struct {
|
||||||
NewEntries int `json:"new_entries"`
|
NewEntries int `json:"new_entries"`
|
||||||
Page int `json:"page"`
|
Page int `json:"page"`
|
||||||
BatchSize int `json:"batch_size"`
|
BatchSize int `json:"batch_size"`
|
||||||
HasMore bool `json:"has_more"`
|
HasMore bool `json:"has_more"`
|
||||||
Cursor string `json:"cursor,omitempty"` // Cursor for resume capability
|
Cursor string `json:"cursor,omitempty"`
|
||||||
Completed bool `json:"completed,omitempty"` // True if all media fetched
|
Completed bool `json:"completed,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// TwitterResponse represents the full response for frontend
|
|
||||||
type TwitterResponse struct {
|
type TwitterResponse struct {
|
||||||
AccountInfo AccountInfo `json:"account_info"`
|
AccountInfo AccountInfo `json:"account_info"`
|
||||||
TotalURLs int `json:"total_urls"`
|
TotalURLs int `json:"total_urls"`
|
||||||
Timeline []TimelineEntry `json:"timeline"`
|
Timeline []TimelineEntry `json:"timeline"`
|
||||||
Metadata ExtractMetadata `json:"metadata"`
|
Metadata ExtractMetadata `json:"metadata"`
|
||||||
Cursor string `json:"cursor,omitempty"` // Cursor for next fetch
|
Cursor string `json:"cursor,omitempty"`
|
||||||
Completed bool `json:"completed,omitempty"` // True if fetch completed
|
Completed bool `json:"completed,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// TimelineRequest represents request parameters for timeline extraction
|
|
||||||
type TimelineRequest struct {
|
type TimelineRequest struct {
|
||||||
Username string `json:"username"`
|
Username string `json:"username"`
|
||||||
AuthToken string `json:"auth_token"`
|
AuthToken string `json:"auth_token"`
|
||||||
TimelineType string `json:"timeline_type"` // media, timeline, tweets, with_replies, likes, bookmarks
|
TimelineType string `json:"timeline_type"`
|
||||||
BatchSize int `json:"batch_size"` // 0 = all
|
BatchSize int `json:"batch_size"`
|
||||||
Page int `json:"page"`
|
Page int `json:"page"`
|
||||||
MediaType string `json:"media_type"` // all, image, video, gif
|
MediaType string `json:"media_type"`
|
||||||
Retweets bool `json:"retweets"`
|
Retweets bool `json:"retweets"`
|
||||||
Cursor string `json:"cursor,omitempty"` // Resume from this cursor position
|
Cursor string `json:"cursor,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// DateRangeRequest represents request parameters for date range extraction
|
|
||||||
type DateRangeRequest struct {
|
type DateRangeRequest struct {
|
||||||
Username string `json:"username"`
|
Username string `json:"username"`
|
||||||
AuthToken string `json:"auth_token"`
|
AuthToken string `json:"auth_token"`
|
||||||
StartDate string `json:"start_date"` // YYYY-MM-DD
|
StartDate string `json:"start_date"`
|
||||||
EndDate string `json:"end_date"` // YYYY-MM-DD
|
EndDate string `json:"end_date"`
|
||||||
MediaFilter string `json:"media_filter"`
|
MediaFilter string `json:"media_filter"`
|
||||||
Retweets bool `json:"retweets"`
|
Retweets bool `json:"retweets"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// buildTwitterURL constructs the Twitter URL based on username and timeline type
|
|
||||||
func buildTwitterURL(username, timelineType string) string {
|
func buildTwitterURL(username, timelineType string) string {
|
||||||
// Special case: bookmarks don't need username
|
|
||||||
if timelineType == "bookmarks" {
|
if timelineType == "bookmarks" {
|
||||||
return "https://x.com/i/bookmarks"
|
return "https://x.com/i/bookmarks"
|
||||||
}
|
}
|
||||||
|
|
||||||
// Clean username - extract handle from URL if needed
|
|
||||||
username = cleanUsername(username)
|
username = cleanUsername(username)
|
||||||
|
|
||||||
// Build URL based on timeline type
|
|
||||||
baseURL := "https://x.com/" + username
|
baseURL := "https://x.com/" + username
|
||||||
switch timelineType {
|
switch timelineType {
|
||||||
case "media":
|
case "media":
|
||||||
return baseURL + "/media"
|
return baseURL + "/media"
|
||||||
case "timeline":
|
case "timeline":
|
||||||
return baseURL + "/timeline" // Best for cursor support
|
return baseURL + "/timeline"
|
||||||
case "tweets":
|
case "tweets":
|
||||||
return baseURL + "/tweets"
|
return baseURL + "/tweets"
|
||||||
case "with_replies":
|
case "with_replies":
|
||||||
@@ -292,12 +320,10 @@ func buildTwitterURL(username, timelineType string) string {
|
|||||||
case "likes":
|
case "likes":
|
||||||
return baseURL + "/likes"
|
return baseURL + "/likes"
|
||||||
default:
|
default:
|
||||||
return baseURL + "/timeline" // Default to timeline for reliable cursor
|
return baseURL + "/timeline"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// cleanUsername extracts the handle from different input formats
|
|
||||||
// Handles: @username, username, https://x.com/username, https://x.com/username/media, etc.
|
|
||||||
func cleanUsername(username string) string {
|
func cleanUsername(username string) string {
|
||||||
username = strings.TrimSpace(username)
|
username = strings.TrimSpace(username)
|
||||||
username = strings.TrimPrefix(username, "@")
|
username = strings.TrimPrefix(username, "@")
|
||||||
@@ -309,12 +335,12 @@ func cleanUsername(username string) string {
|
|||||||
}
|
}
|
||||||
if u, err := url.Parse(parsed); err == nil {
|
if u, err := url.Parse(parsed); err == nil {
|
||||||
segments := strings.Split(strings.Trim(u.Path, "/"), "/")
|
segments := strings.Split(strings.Trim(u.Path, "/"), "/")
|
||||||
// Skip special paths like /i/bookmarks, /search, /home, /explore
|
|
||||||
if len(segments) > 0 && segments[0] != "" {
|
if len(segments) > 0 && segments[0] != "" {
|
||||||
firstSegment := strings.ToLower(segments[0])
|
firstSegment := strings.ToLower(segments[0])
|
||||||
// These are not usernames
|
|
||||||
if firstSegment == "i" || firstSegment == "search" || firstSegment == "home" || firstSegment == "explore" || firstSegment == "settings" || firstSegment == "messages" || firstSegment == "notifications" {
|
if firstSegment == "i" || firstSegment == "search" || firstSegment == "home" || firstSegment == "explore" || firstSegment == "settings" || firstSegment == "messages" || firstSegment == "notifications" {
|
||||||
return username // Return as-is, let caller handle
|
return username
|
||||||
}
|
}
|
||||||
return segments[0]
|
return segments[0]
|
||||||
}
|
}
|
||||||
@@ -324,7 +350,6 @@ func cleanUsername(username string) string {
|
|||||||
return username
|
return username
|
||||||
}
|
}
|
||||||
|
|
||||||
// ensureURLScheme normalises URLs so the CLI accepts them
|
|
||||||
func ensureURLScheme(raw string) string {
|
func ensureURLScheme(raw string) string {
|
||||||
raw = strings.TrimSpace(raw)
|
raw = strings.TrimSpace(raw)
|
||||||
if raw == "" {
|
if raw == "" {
|
||||||
@@ -339,7 +364,6 @@ func ensureURLScheme(raw string) string {
|
|||||||
return "https://" + strings.TrimPrefix(raw, "//")
|
return "https://" + strings.TrimPrefix(raw, "//")
|
||||||
}
|
}
|
||||||
|
|
||||||
// buildSearchURL assembles an X.com search URL for date range queries
|
|
||||||
func buildSearchURL(username, startDate, endDate, mediaFilter string, includeRetweets bool) string {
|
func buildSearchURL(username, startDate, endDate, mediaFilter string, includeRetweets bool) string {
|
||||||
trimmed := strings.TrimSpace(username)
|
trimmed := strings.TrimSpace(username)
|
||||||
lower := strings.ToLower(trimmed)
|
lower := strings.ToLower(trimmed)
|
||||||
@@ -378,47 +402,54 @@ func buildSearchURL(username, startDate, endDate, mediaFilter string, includeRet
|
|||||||
return fmt.Sprintf("https://x.com/search?q=%s&src=typed_query&f=live", query)
|
return fmt.Sprintf("https://x.com/search?q=%s&src=typed_query&f=live", query)
|
||||||
}
|
}
|
||||||
|
|
||||||
// convertMetadataToTimelineEntry converts metadata-only tweets to timeline entries
|
|
||||||
func convertMetadataToTimelineEntry(meta TweetMetadata) TimelineEntry {
|
func convertMetadataToTimelineEntry(meta TweetMetadata) TimelineEntry {
|
||||||
return TimelineEntry{
|
return TimelineEntry{
|
||||||
URL: "",
|
URL: "",
|
||||||
Date: meta.Date,
|
Date: meta.Date,
|
||||||
TweetID: meta.TweetID,
|
TweetID: meta.TweetID,
|
||||||
Type: "text",
|
Type: "text",
|
||||||
IsRetweet: meta.RetweetID != 0,
|
IsRetweet: meta.RetweetID != 0,
|
||||||
Extension: "txt",
|
Extension: "txt",
|
||||||
Width: 0,
|
Width: 0,
|
||||||
Height: 0,
|
Height: 0,
|
||||||
Content: meta.Content,
|
Content: meta.Content,
|
||||||
ViewCount: meta.ViewCount,
|
ViewCount: meta.ViewCount,
|
||||||
BookmarkCount: meta.BookmarkCount,
|
BookmarkCount: meta.BookmarkCount,
|
||||||
FavoriteCount: meta.FavoriteCount,
|
FavoriteCount: meta.FavoriteCount,
|
||||||
RetweetCount: meta.RetweetCount,
|
RetweetCount: meta.RetweetCount,
|
||||||
ReplyCount: meta.ReplyCount,
|
ReplyCount: meta.ReplyCount,
|
||||||
|
AuthorUsername: meta.Author.Name,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// convertToTimelineEntry converts CLIMediaItem to TimelineEntry
|
|
||||||
func convertToTimelineEntry(media CLIMediaItem) TimelineEntry {
|
func convertToTimelineEntry(media CLIMediaItem) TimelineEntry {
|
||||||
entry := TimelineEntry{
|
|
||||||
URL: media.URL,
|
authorUsername := ""
|
||||||
TweetID: media.TweetID,
|
if media.Author.Name != "" {
|
||||||
Date: media.Date,
|
authorUsername = media.Author.Name
|
||||||
Extension: media.Extension,
|
} else if media.User.Name != "" {
|
||||||
Width: media.Width,
|
authorUsername = media.User.Name
|
||||||
Height: media.Height,
|
}
|
||||||
IsRetweet: media.RetweetID != 0,
|
|
||||||
Content: media.Content,
|
entry := TimelineEntry{
|
||||||
ViewCount: media.ViewCount,
|
URL: media.URL,
|
||||||
BookmarkCount: media.BookmarkCount,
|
TweetID: media.TweetID,
|
||||||
FavoriteCount: media.FavoriteCount,
|
Date: media.Date,
|
||||||
RetweetCount: media.RetweetCount,
|
Extension: media.Extension,
|
||||||
ReplyCount: media.ReplyCount,
|
Width: media.Width,
|
||||||
Source: media.Source,
|
Height: media.Height,
|
||||||
Verified: media.Author.Verified,
|
IsRetweet: media.RetweetID != 0,
|
||||||
|
Content: media.Content,
|
||||||
|
ViewCount: media.ViewCount,
|
||||||
|
BookmarkCount: media.BookmarkCount,
|
||||||
|
FavoriteCount: media.FavoriteCount,
|
||||||
|
RetweetCount: media.RetweetCount,
|
||||||
|
ReplyCount: media.ReplyCount,
|
||||||
|
Source: media.Source,
|
||||||
|
Verified: media.Author.Verified,
|
||||||
|
AuthorUsername: authorUsername,
|
||||||
}
|
}
|
||||||
|
|
||||||
// Determine type - media item already has type from CLI
|
|
||||||
if media.Type != "" {
|
if media.Type != "" {
|
||||||
entry.Type = media.Type
|
entry.Type = media.Type
|
||||||
} else {
|
} else {
|
||||||
@@ -435,119 +466,52 @@ func convertToTimelineEntry(media CLIMediaItem) TimelineEntry {
|
|||||||
return entry
|
return entry
|
||||||
}
|
}
|
||||||
|
|
||||||
// getExtractorPath returns the path to extractor binary
|
|
||||||
// Binary is stored in ~/.twitterxmediabatchdownloader/ (same as ffmpeg and database)
|
|
||||||
func getExtractorPath() string {
|
func getExtractorPath() string {
|
||||||
homeDir, _ := os.UserHomeDir()
|
homeDir, _ := os.UserHomeDir()
|
||||||
baseDir := filepath.Join(homeDir, ".twitterxmediabatchdownloader")
|
baseDir := filepath.Join(homeDir, ".twitterxmediabatchdownloader")
|
||||||
return filepath.Join(baseDir, getExecutableName())
|
return filepath.Join(baseDir, getExecutableName())
|
||||||
}
|
}
|
||||||
|
|
||||||
// getHashFilePath returns the path to the hash file for version checking
|
|
||||||
func getHashFilePath() string {
|
|
||||||
homeDir, _ := os.UserHomeDir()
|
|
||||||
baseDir := filepath.Join(homeDir, ".twitterxmediabatchdownloader")
|
|
||||||
return filepath.Join(baseDir, "extractor.sha256")
|
|
||||||
}
|
|
||||||
|
|
||||||
// calculateHash calculates SHA256 hash of data
|
|
||||||
func calculateHash(data []byte) string {
|
|
||||||
hash := sha256.Sum256(data)
|
|
||||||
return hex.EncodeToString(hash[:])
|
|
||||||
}
|
|
||||||
|
|
||||||
// ensureExtractor ensures the extractor binary exists
|
|
||||||
// Extracts from embedded binary if not present or if hash differs (update)
|
|
||||||
func ensureExtractor() (string, error) {
|
|
||||||
exePath := getExtractorPath()
|
|
||||||
hashPath := getHashFilePath()
|
|
||||||
baseDir := filepath.Dir(exePath)
|
|
||||||
|
|
||||||
// Create directory if not exists
|
|
||||||
if err := os.MkdirAll(baseDir, 0755); err != nil {
|
|
||||||
return "", fmt.Errorf("failed to create directory: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Calculate hash of embedded binary
|
|
||||||
embeddedHash := calculateHash(extractorBin)
|
|
||||||
|
|
||||||
// Check if binary and hash file exist
|
|
||||||
if _, err := os.Stat(exePath); err == nil {
|
|
||||||
// Binary exists - check hash
|
|
||||||
if storedHash, err := os.ReadFile(hashPath); err == nil {
|
|
||||||
if string(storedHash) == embeddedHash {
|
|
||||||
return exePath, nil // Already extracted and up to date
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Hash differs or missing - need to update
|
|
||||||
os.Remove(exePath)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Extract binary
|
|
||||||
if err := os.WriteFile(exePath, extractorBin, 0755); err != nil {
|
|
||||||
return "", fmt.Errorf("failed to write extractor: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Save hash for future comparison
|
|
||||||
if err := os.WriteFile(hashPath, []byte(embeddedHash), 0644); err != nil {
|
|
||||||
// Non-fatal - binary still works, just won't skip next time
|
|
||||||
fmt.Printf("Warning: failed to save hash file: %v\n", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return exePath, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// ExtractTimeline extracts media from user timeline using the new CLI
|
|
||||||
func ExtractTimeline(req TimelineRequest) (*TwitterResponse, error) {
|
func ExtractTimeline(req TimelineRequest) (*TwitterResponse, error) {
|
||||||
// Get or extract extractor binary (persistent, not temp)
|
|
||||||
exePath, err := ensureExtractor()
|
exePath, err := requireExtractorPath()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Determine the right endpoint based on what user wants:
|
|
||||||
// - Media (all/image/video/gif): Use /media endpoint - fastest and most reliable
|
|
||||||
// - Text tweets: Use /tweets endpoint with --text-tweets
|
|
||||||
// - With retweets: Use /tweets endpoint (retweets not available on /media)
|
|
||||||
isTextOnly := req.MediaType == "text"
|
isTextOnly := req.MediaType == "text"
|
||||||
wantsRetweets := req.Retweets
|
wantsRetweets := req.Retweets
|
||||||
|
|
||||||
timelineType := req.TimelineType
|
timelineType := req.TimelineType
|
||||||
if timelineType == "" {
|
if timelineType == "" {
|
||||||
if isTextOnly {
|
if isTextOnly {
|
||||||
// Text-only tweets need /tweets endpoint
|
|
||||||
timelineType = "tweets"
|
timelineType = "tweets"
|
||||||
} else if wantsRetweets {
|
} else if wantsRetweets {
|
||||||
// Retweets need /tweets endpoint (not available on /media)
|
|
||||||
timelineType = "tweets"
|
timelineType = "tweets"
|
||||||
} else {
|
} else {
|
||||||
// Default: /media endpoint - fastest for media-only fetch
|
|
||||||
timelineType = "media"
|
timelineType = "media"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := buildTwitterURL(req.Username, timelineType)
|
url := buildTwitterURL(req.Username, timelineType)
|
||||||
|
|
||||||
// Build command arguments for new CLI format
|
|
||||||
// Format: extractor.exe URL --auth-token TOKEN --json [options]
|
|
||||||
args := []string{url}
|
args := []string{url}
|
||||||
|
|
||||||
// Add auth token
|
|
||||||
if req.AuthToken != "" {
|
if req.AuthToken != "" {
|
||||||
args = append(args, "--auth-token", req.AuthToken)
|
args = append(args, "--auth-token", req.AuthToken)
|
||||||
} else {
|
} else {
|
||||||
args = append(args, "--guest")
|
args = append(args, "--guest")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Always request JSON output with metadata
|
|
||||||
args = append(args, "--json", "--metadata")
|
args = append(args, "--json", "--metadata")
|
||||||
|
|
||||||
// Add limit if specified
|
|
||||||
if req.BatchSize > 0 {
|
if req.BatchSize > 0 {
|
||||||
args = append(args, "--limit", fmt.Sprintf("%d", req.BatchSize))
|
args = append(args, "--limit", fmt.Sprintf("%d", req.BatchSize))
|
||||||
}
|
}
|
||||||
|
|
||||||
// Handle retweets - only relevant when using /tweets endpoint
|
|
||||||
if timelineType == "tweets" || timelineType == "timeline" {
|
if timelineType == "tweets" || timelineType == "timeline" {
|
||||||
if req.Retweets {
|
if req.Retweets {
|
||||||
args = append(args, "--retweets", "include")
|
args = append(args, "--retweets", "include")
|
||||||
@@ -556,12 +520,10 @@ func ExtractTimeline(req TimelineRequest) (*TwitterResponse, error) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Only add --text-tweets when explicitly requesting text content
|
|
||||||
if isTextOnly {
|
if isTextOnly {
|
||||||
args = append(args, "--text-tweets")
|
args = append(args, "--text-tweets")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Handle media type filter using --type parameter
|
|
||||||
if req.MediaType != "" && req.MediaType != "all" && !isTextOnly {
|
if req.MediaType != "" && req.MediaType != "all" && !isTextOnly {
|
||||||
switch req.MediaType {
|
switch req.MediaType {
|
||||||
case "image":
|
case "image":
|
||||||
@@ -573,24 +535,16 @@ func ExtractTimeline(req TimelineRequest) (*TwitterResponse, error) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add cursor for resume capability
|
|
||||||
if req.Cursor != "" {
|
if req.Cursor != "" {
|
||||||
args = append(args, "--cursor", req.Cursor)
|
args = append(args, "--cursor", req.Cursor)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Execute command with UTF-8 encoding
|
|
||||||
cmd := exec.Command(exePath, args...)
|
cmd := exec.Command(exePath, args...)
|
||||||
cmd.Env = append(os.Environ(),
|
cmd.Env = append(os.Environ(),
|
||||||
"PYTHONIOENCODING=utf-8",
|
"PYTHONIOENCODING=utf-8",
|
||||||
"PYTHONUTF8=1",
|
"PYTHONUTF8=1",
|
||||||
)
|
)
|
||||||
hideWindow(cmd) // Hide console window on Windows
|
output, err := runTrackedExtractorCommand(cmd)
|
||||||
output, err := cmd.CombinedOutput()
|
|
||||||
|
|
||||||
// Ensure process is killed after completion
|
|
||||||
if cmd.Process != nil {
|
|
||||||
cmd.Process.Kill()
|
|
||||||
}
|
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
outputStr := string(output)
|
outputStr := string(output)
|
||||||
@@ -598,106 +552,124 @@ func ExtractTimeline(req TimelineRequest) (*TwitterResponse, error) {
|
|||||||
return nil, fmt.Errorf("%s", errorMsg)
|
return nil, fmt.Errorf("%s", errorMsg)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Find JSON in output (skip any info messages)
|
|
||||||
jsonStr := extractJSON(string(output))
|
jsonStr := extractJSON(string(output))
|
||||||
if jsonStr == "" {
|
if jsonStr == "" {
|
||||||
outputStr := string(output)
|
outputStr := string(output)
|
||||||
if strings.TrimSpace(outputStr) == "" {
|
if strings.TrimSpace(outputStr) == "" {
|
||||||
return nil, fmt.Errorf("empty_response: Extractor returned no data. The timeline may be empty or inaccessible")
|
return nil, fmt.Errorf("empty_response: Xtractor returned no data. The timeline may be empty or inaccessible")
|
||||||
}
|
}
|
||||||
return nil, fmt.Errorf("parse_error: Could not parse extractor output. Raw output: %s", outputStr)
|
return nil, fmt.Errorf("parse_error: Could not parse xtractor output. Raw output: %s", outputStr)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Parse CLI response
|
|
||||||
var cliResponse CLIResponse
|
var cliResponse CLIResponse
|
||||||
if err := json.Unmarshal([]byte(jsonStr), &cliResponse); err != nil {
|
if err := json.Unmarshal([]byte(jsonStr), &cliResponse); err != nil {
|
||||||
return nil, fmt.Errorf("json_error: Failed to parse JSON response: %v", err)
|
return nil, fmt.Errorf("json_error: Failed to parse JSON response: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Convert to frontend format
|
timeline := make([]TimelineEntry, 0)
|
||||||
var timeline []TimelineEntry
|
|
||||||
accountInfo := AccountInfo{
|
accountInfo := AccountInfo{
|
||||||
Name: req.Username,
|
Name: req.Username,
|
||||||
Nick: req.Username,
|
Nick: req.Username,
|
||||||
}
|
}
|
||||||
|
|
||||||
// Build a set of tweet IDs that have media
|
|
||||||
mediaTweetIDs := make(map[int64]bool)
|
mediaTweetIDs := make(map[int64]bool)
|
||||||
for _, media := range cliResponse.Media {
|
for _, media := range cliResponse.Media {
|
||||||
mediaTweetIDs[int64(media.TweetID)] = true
|
mediaTweetIDs[int64(media.TweetID)] = true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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"
|
||||||
|
}
|
||||||
|
|
||||||
if isTextOnly {
|
if isTextOnly {
|
||||||
// Text-only mode: get tweets from metadata that don't have media
|
|
||||||
timeline = make([]TimelineEntry, 0)
|
|
||||||
for _, meta := range cliResponse.Metadata {
|
for _, meta := range cliResponse.Metadata {
|
||||||
if !mediaTweetIDs[int64(meta.TweetID)] {
|
if !mediaTweetIDs[int64(meta.TweetID)] {
|
||||||
timeline = append(timeline, convertMetadataToTimelineEntry(meta))
|
timeline = append(timeline, convertMetadataToTimelineEntry(meta))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get account info from first media item if available, otherwise from metadata
|
if !isBookmarks && !isLikes {
|
||||||
if len(cliResponse.Media) > 0 {
|
if len(cliResponse.Media) > 0 {
|
||||||
user := cliResponse.Media[0].User
|
user := cliResponse.Media[0].User
|
||||||
accountInfo.Name = user.Name
|
accountInfo.Name = user.Name
|
||||||
accountInfo.Nick = user.Nick
|
accountInfo.Nick = user.Nick
|
||||||
accountInfo.Date = user.Date
|
accountInfo.Date = user.Date
|
||||||
accountInfo.FollowersCount = user.FollowersCount
|
accountInfo.FollowersCount = user.FollowersCount
|
||||||
accountInfo.FriendsCount = user.FriendsCount
|
accountInfo.FriendsCount = user.FriendsCount
|
||||||
accountInfo.ProfileImage = user.ProfileImage
|
accountInfo.ProfileImage = user.ProfileImage
|
||||||
accountInfo.StatusesCount = user.StatusesCount
|
accountInfo.StatusesCount = user.StatusesCount
|
||||||
} else if len(cliResponse.Metadata) > 0 {
|
} else if len(cliResponse.Metadata) > 0 {
|
||||||
firstMeta := cliResponse.Metadata[0]
|
firstMeta := cliResponse.Metadata[0]
|
||||||
accountInfo.Name = firstMeta.Author.Name
|
accountInfo.Name = firstMeta.Author.Name
|
||||||
accountInfo.Nick = firstMeta.Author.Nick
|
accountInfo.Nick = firstMeta.Author.Nick
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
|
||||||
|
if len(cliResponse.Media) > 0 {
|
||||||
|
user := cliResponse.Media[0].User
|
||||||
|
accountInfo.Date = user.Date
|
||||||
|
accountInfo.FollowersCount = user.FollowersCount
|
||||||
|
accountInfo.FriendsCount = user.FriendsCount
|
||||||
|
accountInfo.ProfileImage = user.ProfileImage
|
||||||
|
accountInfo.StatusesCount = user.StatusesCount
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} else if len(cliResponse.Media) > 0 {
|
} else if len(cliResponse.Media) > 0 {
|
||||||
// Normal media items only (text tweets handled separately with "text" media type)
|
|
||||||
timeline = make([]TimelineEntry, 0, len(cliResponse.Media))
|
timeline = make([]TimelineEntry, 0, len(cliResponse.Media))
|
||||||
|
|
||||||
// Add media items
|
|
||||||
for _, media := range cliResponse.Media {
|
for _, media := range cliResponse.Media {
|
||||||
timeline = append(timeline, convertToTimelineEntry(media))
|
timeline = append(timeline, convertToTimelineEntry(media))
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get account info from first media item
|
|
||||||
user := cliResponse.Media[0].User
|
user := cliResponse.Media[0].User
|
||||||
accountInfo.Name = user.Name
|
if !isBookmarks && !isLikes {
|
||||||
accountInfo.Nick = user.Nick
|
accountInfo.Name = user.Name
|
||||||
|
accountInfo.Nick = user.Nick
|
||||||
|
}
|
||||||
accountInfo.Date = user.Date
|
accountInfo.Date = user.Date
|
||||||
accountInfo.FollowersCount = user.FollowersCount
|
accountInfo.FollowersCount = user.FollowersCount
|
||||||
accountInfo.FriendsCount = user.FriendsCount
|
accountInfo.FriendsCount = user.FriendsCount
|
||||||
accountInfo.ProfileImage = user.ProfileImage
|
accountInfo.ProfileImage = user.ProfileImage
|
||||||
accountInfo.StatusesCount = user.StatusesCount
|
accountInfo.StatusesCount = user.StatusesCount
|
||||||
} else if len(cliResponse.Metadata) > 0 {
|
} else if len(cliResponse.Metadata) > 0 {
|
||||||
// Fallback: Text-only tweets (no media) - convert metadata to timeline entries
|
|
||||||
timeline = make([]TimelineEntry, 0, len(cliResponse.Metadata))
|
timeline = make([]TimelineEntry, 0, len(cliResponse.Metadata))
|
||||||
for _, meta := range cliResponse.Metadata {
|
for _, meta := range cliResponse.Metadata {
|
||||||
entry := TimelineEntry{
|
entry := TimelineEntry{
|
||||||
URL: "", // No media URL for text tweets
|
URL: "",
|
||||||
TweetID: meta.TweetID,
|
TweetID: meta.TweetID,
|
||||||
Date: meta.Date,
|
Date: meta.Date,
|
||||||
Type: "text",
|
Type: "text",
|
||||||
IsRetweet: meta.RetweetID != 0,
|
IsRetweet: meta.RetweetID != 0,
|
||||||
Extension: "txt",
|
Extension: "txt",
|
||||||
Width: 0,
|
Width: 0,
|
||||||
Height: 0,
|
Height: 0,
|
||||||
Content: meta.Content,
|
Content: meta.Content,
|
||||||
ViewCount: meta.ViewCount,
|
ViewCount: meta.ViewCount,
|
||||||
BookmarkCount: meta.BookmarkCount,
|
BookmarkCount: meta.BookmarkCount,
|
||||||
FavoriteCount: meta.FavoriteCount,
|
FavoriteCount: meta.FavoriteCount,
|
||||||
RetweetCount: meta.RetweetCount,
|
RetweetCount: meta.RetweetCount,
|
||||||
ReplyCount: meta.ReplyCount,
|
ReplyCount: meta.ReplyCount,
|
||||||
|
AuthorUsername: meta.Author.Name,
|
||||||
}
|
}
|
||||||
timeline = append(timeline, entry)
|
timeline = append(timeline, entry)
|
||||||
}
|
}
|
||||||
// Get account info from first metadata
|
|
||||||
firstMeta := cliResponse.Metadata[0]
|
if !isBookmarks && !isLikes {
|
||||||
accountInfo.Name = firstMeta.Author.Name
|
firstMeta := cliResponse.Metadata[0]
|
||||||
accountInfo.Nick = firstMeta.Author.Nick
|
accountInfo.Name = firstMeta.Author.Name
|
||||||
|
accountInfo.Nick = firstMeta.Author.Nick
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Determine if there's more data to fetch
|
|
||||||
hasMore := cliResponse.Cursor != "" && !cliResponse.Completed
|
hasMore := cliResponse.Cursor != "" && !cliResponse.Completed
|
||||||
|
|
||||||
response := &TwitterResponse{
|
response := &TwitterResponse{
|
||||||
@@ -719,10 +691,9 @@ func ExtractTimeline(req TimelineRequest) (*TwitterResponse, error) {
|
|||||||
return response, nil
|
return response, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ExtractDateRange extracts media based on date range using the new CLI
|
|
||||||
func ExtractDateRange(req DateRangeRequest) (*TwitterResponse, error) {
|
func ExtractDateRange(req DateRangeRequest) (*TwitterResponse, error) {
|
||||||
// Get or extract extractor binary (persistent, not temp)
|
|
||||||
exePath, err := ensureExtractor()
|
exePath, err := requireExtractorPath()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -730,17 +701,14 @@ func ExtractDateRange(req DateRangeRequest) (*TwitterResponse, error) {
|
|||||||
mediaFilter := strings.ToLower(strings.TrimSpace(req.MediaFilter))
|
mediaFilter := strings.ToLower(strings.TrimSpace(req.MediaFilter))
|
||||||
url := buildSearchURL(req.Username, req.StartDate, req.EndDate, mediaFilter, req.Retweets)
|
url := buildSearchURL(req.Username, req.StartDate, req.EndDate, mediaFilter, req.Retweets)
|
||||||
|
|
||||||
// Build command arguments
|
|
||||||
args := []string{url}
|
args := []string{url}
|
||||||
|
|
||||||
// Add auth token
|
|
||||||
if req.AuthToken != "" {
|
if req.AuthToken != "" {
|
||||||
args = append(args, "--auth-token", req.AuthToken)
|
args = append(args, "--auth-token", req.AuthToken)
|
||||||
} else {
|
} else {
|
||||||
args = append(args, "--guest")
|
args = append(args, "--guest")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Always request JSON output with metadata
|
|
||||||
args = append(args, "--json", "--metadata")
|
args = append(args, "--json", "--metadata")
|
||||||
|
|
||||||
if req.Retweets {
|
if req.Retweets {
|
||||||
@@ -754,19 +722,12 @@ func ExtractDateRange(req DateRangeRequest) (*TwitterResponse, error) {
|
|||||||
args = append(args, "--text-tweets")
|
args = append(args, "--text-tweets")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Execute command with UTF-8 encoding
|
|
||||||
cmd := exec.Command(exePath, args...)
|
cmd := exec.Command(exePath, args...)
|
||||||
cmd.Env = append(os.Environ(),
|
cmd.Env = append(os.Environ(),
|
||||||
"PYTHONIOENCODING=utf-8",
|
"PYTHONIOENCODING=utf-8",
|
||||||
"PYTHONUTF8=1",
|
"PYTHONUTF8=1",
|
||||||
)
|
)
|
||||||
hideWindow(cmd)
|
output, err := runTrackedExtractorCommand(cmd)
|
||||||
output, err := cmd.CombinedOutput()
|
|
||||||
|
|
||||||
// Ensure process is killed after completion
|
|
||||||
if cmd.Process != nil {
|
|
||||||
cmd.Process.Kill()
|
|
||||||
}
|
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
outputStr := string(output)
|
outputStr := string(output)
|
||||||
@@ -774,23 +735,20 @@ func ExtractDateRange(req DateRangeRequest) (*TwitterResponse, error) {
|
|||||||
return nil, fmt.Errorf("%s", errorMsg)
|
return nil, fmt.Errorf("%s", errorMsg)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Find JSON in output (skip any info messages)
|
|
||||||
jsonStr := extractJSON(string(output))
|
jsonStr := extractJSON(string(output))
|
||||||
if jsonStr == "" {
|
if jsonStr == "" {
|
||||||
outputStr := string(output)
|
outputStr := string(output)
|
||||||
if strings.TrimSpace(outputStr) == "" {
|
if strings.TrimSpace(outputStr) == "" {
|
||||||
return nil, fmt.Errorf("empty_response: Extractor returned no data. The timeline may be empty or inaccessible")
|
return nil, fmt.Errorf("empty_response: Xtractor returned no data. The timeline may be empty or inaccessible")
|
||||||
}
|
}
|
||||||
return nil, fmt.Errorf("parse_error: Could not parse extractor output. Raw output: %s", outputStr)
|
return nil, fmt.Errorf("parse_error: Could not parse xtractor output. Raw output: %s", outputStr)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Parse CLI response
|
|
||||||
var cliResponse CLIResponse
|
var cliResponse CLIResponse
|
||||||
if err := json.Unmarshal([]byte(jsonStr), &cliResponse); err != nil {
|
if err := json.Unmarshal([]byte(jsonStr), &cliResponse); err != nil {
|
||||||
return nil, fmt.Errorf("json_error: Failed to parse JSON response: %v", err)
|
return nil, fmt.Errorf("json_error: Failed to parse JSON response: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Convert to frontend format
|
|
||||||
mediaTweetIDs := make(map[int64]bool)
|
mediaTweetIDs := make(map[int64]bool)
|
||||||
for _, media := range cliResponse.Media {
|
for _, media := range cliResponse.Media {
|
||||||
mediaTweetIDs[int64(media.TweetID)] = true
|
mediaTweetIDs[int64(media.TweetID)] = true
|
||||||
@@ -809,7 +767,6 @@ func ExtractDateRange(req DateRangeRequest) (*TwitterResponse, error) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Build account info from first media item (has full user info)
|
|
||||||
accountInfo := AccountInfo{
|
accountInfo := AccountInfo{
|
||||||
Name: req.Username,
|
Name: req.Username,
|
||||||
Nick: req.Username,
|
Nick: req.Username,
|
||||||
@@ -829,7 +786,6 @@ func ExtractDateRange(req DateRangeRequest) (*TwitterResponse, error) {
|
|||||||
accountInfo.Nick = firstMeta.Author.Nick
|
accountInfo.Nick = firstMeta.Author.Nick
|
||||||
}
|
}
|
||||||
|
|
||||||
// Determine if there's more data to fetch
|
|
||||||
hasMore := cliResponse.Cursor != "" && !cliResponse.Completed
|
hasMore := cliResponse.Cursor != "" && !cliResponse.Completed
|
||||||
|
|
||||||
response := &TwitterResponse{
|
response := &TwitterResponse{
|
||||||
@@ -851,15 +807,13 @@ func ExtractDateRange(req DateRangeRequest) (*TwitterResponse, error) {
|
|||||||
return response, nil
|
return response, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// extractJSON finds and extracts JSON object from output string
|
|
||||||
func extractJSON(output string) string {
|
func extractJSON(output string) string {
|
||||||
// Find the start of JSON object
|
|
||||||
start := strings.Index(output, "{")
|
start := strings.Index(output, "{")
|
||||||
if start == -1 {
|
if start == -1 {
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
// Find the matching closing brace
|
|
||||||
depth := 0
|
depth := 0
|
||||||
for i := start; i < len(output); i++ {
|
for i := start; i < len(output); i++ {
|
||||||
if output[i] == '{' {
|
if output[i] == '{' {
|
||||||
@@ -874,25 +828,3 @@ func extractJSON(output string) string {
|
|||||||
|
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetThumbnailURL converts a Twitter media URL to thumbnail size
|
|
||||||
func GetThumbnailURL(url string) string {
|
|
||||||
// For images: https://pbs.twimg.com/media/XXX?format=jpg&name=thumb
|
|
||||||
if strings.Contains(url, "pbs.twimg.com/media/") {
|
|
||||||
// Check if it already has format parameter
|
|
||||||
if strings.Contains(url, "?format=") {
|
|
||||||
// Replace name parameter with thumb
|
|
||||||
if strings.Contains(url, "&name=") {
|
|
||||||
parts := strings.Split(url, "&name=")
|
|
||||||
return parts[0] + "&name=thumb"
|
|
||||||
}
|
|
||||||
return url + "&name=thumb"
|
|
||||||
}
|
|
||||||
// Add format and name parameters
|
|
||||||
if strings.Contains(url, "?") {
|
|
||||||
return url + "&name=thumb"
|
|
||||||
}
|
|
||||||
return url + "?format=jpg&name=thumb"
|
|
||||||
}
|
|
||||||
return url
|
|
||||||
}
|
|
||||||
@@ -18,5 +18,7 @@
|
|||||||
"lib": "@/lib",
|
"lib": "@/lib",
|
||||||
"hooks": "@/hooks"
|
"hooks": "@/hooks"
|
||||||
},
|
},
|
||||||
"registries": {}
|
"registries": {
|
||||||
|
"@lucide-animated": "https://lucide-animated.com/r/{name}.json"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+26
-21
@@ -1,23 +1,28 @@
|
|||||||
import js from '@eslint/js'
|
import js from '@eslint/js';
|
||||||
import globals from 'globals'
|
import globals from 'globals';
|
||||||
import reactHooks from 'eslint-plugin-react-hooks'
|
import reactHooks from 'eslint-plugin-react-hooks';
|
||||||
import reactRefresh from 'eslint-plugin-react-refresh'
|
import reactRefresh from 'eslint-plugin-react-refresh';
|
||||||
import tseslint from 'typescript-eslint'
|
import tseslint from 'typescript-eslint';
|
||||||
import { defineConfig, globalIgnores } from 'eslint/config'
|
import { defineConfig, globalIgnores } from 'eslint/config';
|
||||||
|
|
||||||
export default defineConfig([
|
export default defineConfig([
|
||||||
globalIgnores(['dist']),
|
globalIgnores(['dist', 'wailsjs']),
|
||||||
{
|
{
|
||||||
files: ['**/*.{ts,tsx}'],
|
files: ['**/*.{ts,tsx}'],
|
||||||
extends: [
|
extends: [
|
||||||
js.configs.recommended,
|
js.configs.recommended,
|
||||||
tseslint.configs.recommended,
|
tseslint.configs.recommended,
|
||||||
reactHooks.configs.flat.recommended,
|
reactHooks.configs.flat.recommended,
|
||||||
reactRefresh.configs.vite,
|
reactRefresh.configs.vite,
|
||||||
],
|
],
|
||||||
languageOptions: {
|
languageOptions: {
|
||||||
ecmaVersion: 2020,
|
ecmaVersion: 2020,
|
||||||
globals: globals.browser,
|
globals: globals.browser,
|
||||||
|
},
|
||||||
},
|
},
|
||||||
},
|
{
|
||||||
])
|
files: ['src/components/ui/badge.tsx', 'src/components/ui/button.tsx'],
|
||||||
|
rules: {
|
||||||
|
'react-refresh/only-export-components': 'off',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
]);
|
||||||
+1
-1
@@ -6,7 +6,7 @@
|
|||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||||
<link href="https://fonts.googleapis.com/css2?family=DM+Sans:ital,opsz,wght@0,9..40,100..1000;1,9..40,100..1000&family=Google+Sans+Code:ital,wght@0,300..800;1,300..800&family=Google+Sans+Flex:opsz,wght@6..144,1..1000&family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&family=Manrope:wght@200..800&family=Plus+Jakarta+Sans:ital,wght@0,200..800;1,200..800&family=Poppins:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&family=Roboto:ital,wght@0,100..900;1,100..900&family=Space+Grotesk:wght@300..700&display=swap" rel="stylesheet">
|
<link href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,200..800&family=DM+Sans:wght@300..800&family=Figtree:wght@300..900&family=Geist:wght@100..900&family=Google+Sans+Code:ital,wght@0,300..800;1,300..800&family=Google+Sans+Flex:opsz,wght@6..144,1..1000&family=Inter:wght@300..800&family=JetBrains+Mono:ital,wght@0,100..800;1,100..800&family=Manrope:wght@300..800&family=Noto+Sans:wght@100..900&family=Nunito+Sans:opsz,wght@6..12,200..1000&family=Outfit:wght@100..900&family=Plus+Jakarta+Sans:wght@300..800&family=Poppins:wght@300;400;500;600;700;800&family=Public+Sans:ital,wght@0,100..900;1,100..900&family=Raleway:wght@100..900&family=Roboto:wght@300;400;500;700;900&family=Space+Grotesk:wght@300..700&display=swap" rel="stylesheet">
|
||||||
<title>Twitter/X Media Batch Downloader</title>
|
<title>Twitter/X Media Batch Downloader</title>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
|
|||||||
+16
-17
@@ -12,43 +12,42 @@
|
|||||||
"postinstall": "node scripts/generate-icon.js"
|
"postinstall": "node scripts/generate-icon.js"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@radix-ui/react-accordion": "^1.2.12",
|
|
||||||
"@radix-ui/react-checkbox": "^1.3.3",
|
"@radix-ui/react-checkbox": "^1.3.3",
|
||||||
"@radix-ui/react-context-menu": "^2.2.16",
|
"@radix-ui/react-context-menu": "^2.2.16",
|
||||||
"@radix-ui/react-dialog": "^1.1.15",
|
"@radix-ui/react-dialog": "^1.1.15",
|
||||||
|
"@radix-ui/react-dropdown-menu": "^2.1.16",
|
||||||
"@radix-ui/react-label": "^2.1.8",
|
"@radix-ui/react-label": "^2.1.8",
|
||||||
"@radix-ui/react-progress": "^1.1.8",
|
"@radix-ui/react-progress": "^1.1.8",
|
||||||
"@radix-ui/react-radio-group": "^1.3.8",
|
|
||||||
"@radix-ui/react-select": "^2.2.6",
|
"@radix-ui/react-select": "^2.2.6",
|
||||||
"@radix-ui/react-slot": "^1.2.4",
|
"@radix-ui/react-slot": "^1.2.4",
|
||||||
"@radix-ui/react-switch": "^1.1.4",
|
"@radix-ui/react-switch": "^1.2.6",
|
||||||
"@radix-ui/react-tabs": "^1.1.13",
|
|
||||||
"@radix-ui/react-tooltip": "^1.2.8",
|
"@radix-ui/react-tooltip": "^1.2.8",
|
||||||
"@tailwindcss/vite": "^4.1.17",
|
"@tailwindcss/vite": "^4.1.18",
|
||||||
"class-variance-authority": "^0.7.1",
|
"class-variance-authority": "^0.7.1",
|
||||||
"clsx": "^2.1.1",
|
"clsx": "^2.1.1",
|
||||||
"lucide-react": "^0.554.0",
|
"lucide-react": "^0.562.0",
|
||||||
|
"motion": "^12.23.26",
|
||||||
"next-themes": "^0.4.6",
|
"next-themes": "^0.4.6",
|
||||||
"react": "^19.2.0",
|
"react": "^19.2.3",
|
||||||
"react-dom": "^19.2.0",
|
"react-dom": "^19.2.3",
|
||||||
"sonner": "^2.0.7",
|
"sonner": "^2.0.7",
|
||||||
"tailwind-merge": "^3.4.0",
|
"tailwind-merge": "^3.4.0",
|
||||||
"tailwindcss": "^4.1.17"
|
"tailwindcss": "^4.1.18"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@eslint/js": "^9.39.1",
|
"@eslint/js": "^9.39.2",
|
||||||
"@types/node": "^24.10.1",
|
"@types/node": "^25.0.3",
|
||||||
"@types/react": "^19.2.6",
|
"@types/react": "^19.2.7",
|
||||||
"@types/react-dom": "^19.2.3",
|
"@types/react-dom": "^19.2.3",
|
||||||
"@vitejs/plugin-react": "^5.1.1",
|
"@vitejs/plugin-react": "^5.1.2",
|
||||||
"eslint": "^9.39.1",
|
"eslint": "^9.39.2",
|
||||||
"eslint-plugin-react-hooks": "^7.0.1",
|
"eslint-plugin-react-hooks": "^7.0.1",
|
||||||
"eslint-plugin-react-refresh": "^0.4.24",
|
"eslint-plugin-react-refresh": "^0.4.26",
|
||||||
"globals": "^16.5.0",
|
"globals": "^16.5.0",
|
||||||
"sharp": "^0.34.5",
|
"sharp": "^0.34.5",
|
||||||
"tw-animate-css": "^1.4.0",
|
"tw-animate-css": "^1.4.0",
|
||||||
"typescript": "~5.9.3",
|
"typescript": "~5.9.3",
|
||||||
"typescript-eslint": "^8.47.0",
|
"typescript-eslint": "^8.50.0",
|
||||||
"vite": "^7.2.4"
|
"vite": "^7.3.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1 +1 @@
|
|||||||
6d6b26a2fed70996ef14dbc3e325f141
|
cb4545ab700ecc9d641ab1be76b622f1
|
||||||
Generated
+874
-1038
File diff suppressed because it is too large.
Load diff
@@ -2,32 +2,23 @@ import sharp from 'sharp';
|
|||||||
import { readFileSync, mkdirSync } from 'fs';
|
import { readFileSync, mkdirSync } from 'fs';
|
||||||
import { dirname, join } from 'path';
|
import { dirname, join } from 'path';
|
||||||
import { fileURLToPath } from 'url';
|
import { fileURLToPath } from 'url';
|
||||||
|
|
||||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||||
const rootDir = join(__dirname, '..', '..');
|
const rootDir = join(__dirname, '..', '..');
|
||||||
|
|
||||||
const svgPath = join(rootDir, 'frontend', 'public', 'icon.svg');
|
const svgPath = join(rootDir, 'frontend', 'public', 'icon.svg');
|
||||||
const outputPath = join(rootDir, 'build', 'appicon.png');
|
const outputPath = join(rootDir, 'build', 'appicon.png');
|
||||||
|
|
||||||
async function generateIcon() {
|
async function generateIcon() {
|
||||||
try {
|
try {
|
||||||
// Ensure build directory exists
|
mkdirSync(join(rootDir, 'build'), { recursive: true });
|
||||||
mkdirSync(join(rootDir, 'build'), { recursive: true });
|
const svgBuffer = readFileSync(svgPath);
|
||||||
|
await sharp(svgBuffer)
|
||||||
// Read SVG
|
.resize(1024, 1024)
|
||||||
const svgBuffer = readFileSync(svgPath);
|
.png()
|
||||||
|
.toFile(outputPath);
|
||||||
// Convert SVG to PNG (1024x1024 for Wails)
|
console.log('✓ Icon generated:', outputPath);
|
||||||
await sharp(svgBuffer)
|
}
|
||||||
.resize(1024, 1024)
|
catch (error) {
|
||||||
.png()
|
console.error('✗ Failed to generate icon:', error.message);
|
||||||
.toFile(outputPath);
|
process.exit(1);
|
||||||
|
}
|
||||||
console.log('✓ Icon generated:', outputPath);
|
|
||||||
} catch (error) {
|
|
||||||
console.error('✗ Failed to generate icon:', error.message);
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
generateIcon();
|
generateIcon();
|
||||||
+1370
-572
File diff suppressed because it is too large.
Load diff
Binary file not shown.
|
After Width: | Height: | Size: 903 KiB |
@@ -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: 34 KiB |
File diff suppressed because it is too large.
Load diff
@@ -1,132 +0,0 @@
|
|||||||
import { useState, useEffect, useRef } from "react";
|
|
||||||
import { Bug, Trash2, X, Copy, Check } from "lucide-react";
|
|
||||||
import { Button } from "@/components/ui/button";
|
|
||||||
import {
|
|
||||||
Dialog,
|
|
||||||
DialogContent,
|
|
||||||
DialogTitle,
|
|
||||||
DialogTrigger,
|
|
||||||
} from "@/components/ui/dialog";
|
|
||||||
import { logger, type LogEntry } from "@/lib/logger";
|
|
||||||
|
|
||||||
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 DebugLogger() {
|
|
||||||
const [open, setOpen] = useState(false);
|
|
||||||
const [logs, setLogs] = useState<LogEntry[]>([]);
|
|
||||||
const [copied, setCopied] = useState(false);
|
|
||||||
const scrollRef = useRef<HTMLDivElement>(null);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const unsubscribe = logger.subscribe(() => {
|
|
||||||
setLogs(logger.getLogs());
|
|
||||||
});
|
|
||||||
setLogs(logger.getLogs());
|
|
||||||
return () => {
|
|
||||||
unsubscribe();
|
|
||||||
};
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (scrollRef.current) {
|
|
||||||
scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
|
|
||||||
}
|
|
||||||
}, [logs]);
|
|
||||||
|
|
||||||
const handleClear = () => {
|
|
||||||
logger.clear();
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleCopy = async () => {
|
|
||||||
const logText = logs
|
|
||||||
.map((log) => `[${formatTime(log.timestamp)}] [${log.level}] ${log.message}`)
|
|
||||||
.join("\n");
|
|
||||||
|
|
||||||
try {
|
|
||||||
await navigator.clipboard.writeText(logText);
|
|
||||||
setCopied(true);
|
|
||||||
setTimeout(() => setCopied(false), 500);
|
|
||||||
} catch (err) {
|
|
||||||
console.error("Failed to copy logs:", err);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Dialog open={open} onOpenChange={setOpen}>
|
|
||||||
<DialogTrigger asChild>
|
|
||||||
<Button
|
|
||||||
variant="ghost"
|
|
||||||
size="icon"
|
|
||||||
className="h-6 w-6 opacity-50 hover:opacity-100"
|
|
||||||
>
|
|
||||||
<Bug className="h-3.5 w-3.5" />
|
|
||||||
</Button>
|
|
||||||
</DialogTrigger>
|
|
||||||
<DialogContent className="sm:max-w-[600px] max-h-[80vh] p-6 [&>button]:hidden">
|
|
||||||
<DialogTitle className="text-sm font-medium">Debug Logs</DialogTitle>
|
|
||||||
<div className="absolute right-4 top-4 flex items-center gap-1">
|
|
||||||
<Button
|
|
||||||
variant="ghost"
|
|
||||||
size="icon"
|
|
||||||
className="h-6 w-6 opacity-70 hover:opacity-100"
|
|
||||||
onClick={handleCopy}
|
|
||||||
disabled={logs.length === 0}
|
|
||||||
>
|
|
||||||
{copied ? <Check className="h-4 w-4" /> : <Copy className="h-4 w-4" />}
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
variant="ghost"
|
|
||||||
size="icon"
|
|
||||||
className="h-6 w-6 opacity-70 hover:opacity-100"
|
|
||||||
onClick={handleClear}
|
|
||||||
>
|
|
||||||
<Trash2 className="h-4 w-4" />
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
variant="ghost"
|
|
||||||
size="icon"
|
|
||||||
className="h-6 w-6 opacity-70 hover:opacity-100"
|
|
||||||
onClick={() => setOpen(false)}
|
|
||||||
>
|
|
||||||
<X className="h-4 w-4" />
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
<div
|
|
||||||
ref={scrollRef}
|
|
||||||
className="h-[400px] overflow-y-auto bg-muted/50 rounded-md p-3 font-mono text-xs"
|
|
||||||
>
|
|
||||||
{logs.length === 0 ? (
|
|
||||||
<p className="text-muted-foreground lowercase">no logs yet...</p>
|
|
||||||
) : (
|
|
||||||
logs.map((log, i) => (
|
|
||||||
<div key={i} className="flex gap-2 py-0.5">
|
|
||||||
<span className="text-muted-foreground shrink-0">
|
|
||||||
[{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>
|
|
||||||
</DialogContent>
|
|
||||||
</Dialog>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -2,99 +2,71 @@ import { useState, useEffect, useRef } from "react";
|
|||||||
import { Trash2, Copy, Check } from "lucide-react";
|
import { Trash2, Copy, Check } from "lucide-react";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { logger, type LogEntry } from "@/lib/logger";
|
import { logger, type LogEntry } from "@/lib/logger";
|
||||||
|
|
||||||
const levelColors: Record<string, string> = {
|
const levelColors: Record<string, string> = {
|
||||||
info: "text-blue-500",
|
info: "text-blue-500",
|
||||||
success: "text-green-500",
|
success: "text-green-500",
|
||||||
warning: "text-yellow-500",
|
warning: "text-yellow-500",
|
||||||
error: "text-red-500",
|
error: "text-red-500",
|
||||||
debug: "text-gray-500",
|
debug: "text-gray-500",
|
||||||
};
|
};
|
||||||
|
|
||||||
function formatTime(date: Date): string {
|
function formatTime(date: Date): string {
|
||||||
return date.toLocaleTimeString("en-US", {
|
return date.toLocaleTimeString("en-US", {
|
||||||
hour12: false,
|
hour12: false,
|
||||||
hour: "2-digit",
|
hour: "2-digit",
|
||||||
minute: "2-digit",
|
minute: "2-digit",
|
||||||
second: "2-digit",
|
second: "2-digit",
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export function DebugLoggerPage() {
|
|
||||||
const [logs, setLogs] = useState<LogEntry[]>([]);
|
|
||||||
const [copied, setCopied] = useState(false);
|
|
||||||
const scrollRef = useRef<HTMLDivElement>(null);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const unsubscribe = logger.subscribe(() => {
|
|
||||||
setLogs(logger.getLogs());
|
|
||||||
});
|
});
|
||||||
setLogs(logger.getLogs());
|
}
|
||||||
return () => {
|
export function DebugLoggerPage() {
|
||||||
unsubscribe();
|
const [logs, setLogs] = useState<LogEntry[]>(() => logger.getLogs());
|
||||||
|
const [copied, setCopied] = useState(false);
|
||||||
|
const scrollRef = useRef<HTMLDivElement>(null);
|
||||||
|
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
|
||||||
useEffect(() => {
|
.map((log) => `[${formatTime(log.timestamp)}] [${log.level}] ${log.message}`)
|
||||||
if (scrollRef.current) {
|
.join("\n");
|
||||||
scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
|
try {
|
||||||
}
|
await navigator.clipboard.writeText(logText);
|
||||||
}, [logs]);
|
setCopied(true);
|
||||||
|
setTimeout(() => setCopied(false), 500);
|
||||||
const handleClear = () => {
|
}
|
||||||
logger.clear();
|
catch (err) {
|
||||||
};
|
console.error("Failed to copy logs:", err);
|
||||||
|
}
|
||||||
const handleCopy = async () => {
|
};
|
||||||
const logText = logs
|
return (<div className="space-y-6">
|
||||||
.map((log) => `[${formatTime(log.timestamp)}] [${log.level}] ${log.message}`)
|
|
||||||
.join("\n");
|
|
||||||
|
|
||||||
try {
|
|
||||||
await navigator.clipboard.writeText(logText);
|
|
||||||
setCopied(true);
|
|
||||||
setTimeout(() => setCopied(false), 500);
|
|
||||||
} catch (err) {
|
|
||||||
console.error("Failed to copy logs:", err);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="space-y-6">
|
|
||||||
<div className="flex items-center justify-between">
|
<div className="flex items-center justify-between">
|
||||||
<h1 className="text-2xl font-bold">Debug Logs</h1>
|
<h1 className="text-2xl font-bold">Debug Logs</h1>
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<Button
|
<Button variant="outline" size="sm" onClick={handleCopy} disabled={logs.length === 0} className="gap-1.5">
|
||||||
variant="outline"
|
{copied ? <Check className="h-4 w-4"/> : <Copy className="h-4 w-4"/>}
|
||||||
size="sm"
|
|
||||||
onClick={handleCopy}
|
|
||||||
disabled={logs.length === 0}
|
|
||||||
className="gap-1.5"
|
|
||||||
>
|
|
||||||
{copied ? <Check className="h-4 w-4" /> : <Copy className="h-4 w-4" />}
|
|
||||||
Copy
|
Copy
|
||||||
</Button>
|
</Button>
|
||||||
<Button
|
<Button variant="outline" size="sm" onClick={handleClear} className="gap-1.5">
|
||||||
variant="outline"
|
<Trash2 className="h-4 w-4"/>
|
||||||
size="sm"
|
|
||||||
onClick={handleClear}
|
|
||||||
className="gap-1.5"
|
|
||||||
>
|
|
||||||
<Trash2 className="h-4 w-4" />
|
|
||||||
Clear
|
Clear
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div
|
<div ref={scrollRef} className="h-[calc(100vh-220px)] overflow-y-auto bg-muted/50 rounded-md p-3 font-mono text-xs">
|
||||||
ref={scrollRef}
|
{logs.length === 0 ? (<p className="text-muted-foreground lowercase">no logs yet...</p>) : (logs.map((log, i) => (<div key={i} className="flex gap-2 py-0.5">
|
||||||
className="h-[calc(100vh-220px)] overflow-y-auto bg-muted/50 rounded-md p-3 font-mono text-xs"
|
|
||||||
>
|
|
||||||
{logs.length === 0 ? (
|
|
||||||
<p className="text-muted-foreground lowercase">no logs yet...</p>
|
|
||||||
) : (
|
|
||||||
logs.map((log, i) => (
|
|
||||||
<div key={i} className="flex gap-2 py-0.5">
|
|
||||||
<span className="text-muted-foreground shrink-0">
|
<span className="text-muted-foreground shrink-0">
|
||||||
[{formatTime(log.timestamp)}]
|
[{formatTime(log.timestamp)}]
|
||||||
</span>
|
</span>
|
||||||
@@ -102,10 +74,7 @@ export function DebugLoggerPage() {
|
|||||||
[{log.level}]
|
[{log.level}]
|
||||||
</span>
|
</span>
|
||||||
<span className="break-all">{log.message}</span>
|
<span className="break-all">{log.message}</span>
|
||||||
</div>
|
</div>)))}
|
||||||
))
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>);
|
||||||
);
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,163 @@
|
|||||||
|
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 { Quit } from "../../wailsjs/runtime/runtime";
|
||||||
|
import { DownloadExtractor, IsExtractorInstalled } from "../../wailsjs/go/main/App";
|
||||||
|
|
||||||
|
interface DependencySetupDialogProps {
|
||||||
|
onInstalled?: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface GithubReleaseResponse {
|
||||||
|
tag_name?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const extractorReleaseAPIURL = "https://api.github.com/repos/afkarxyz/xtractor-binaries/releases/latest";
|
||||||
|
|
||||||
|
export function DependencySetupDialog({ onInstalled }: DependencySetupDialogProps) {
|
||||||
|
const [open, setOpen] = useState(false);
|
||||||
|
const [checking, setChecking] = useState(true);
|
||||||
|
const [downloading, setDownloading] = useState(false);
|
||||||
|
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
||||||
|
const [releaseVersion, setReleaseVersion] = useState<string | null>(null);
|
||||||
|
const [releaseStatusMessage, setReleaseStatusMessage] = useState("Checking latest GitHub release...");
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let cancelled = false;
|
||||||
|
const abortController = new AbortController();
|
||||||
|
|
||||||
|
const checkDependency = async () => {
|
||||||
|
try {
|
||||||
|
const installed = await IsExtractorInstalled();
|
||||||
|
if (!cancelled) {
|
||||||
|
setOpen(!installed);
|
||||||
|
setErrorMessage(null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch {
|
||||||
|
if (!cancelled) {
|
||||||
|
setOpen(true);
|
||||||
|
setErrorMessage("Couldn't verify Xtractor. Download it to continue.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finally {
|
||||||
|
if (!cancelled) {
|
||||||
|
setChecking(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const loadReleaseInfo = async () => {
|
||||||
|
try {
|
||||||
|
const response = await fetch(extractorReleaseAPIURL, {
|
||||||
|
headers: {
|
||||||
|
Accept: "application/vnd.github+json",
|
||||||
|
},
|
||||||
|
signal: abortController.signal,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(`GitHub release status ${response.status}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const release = (await response.json()) as GithubReleaseResponse;
|
||||||
|
const version = release.tag_name?.trim();
|
||||||
|
|
||||||
|
if (!version) {
|
||||||
|
throw new Error("Missing GitHub release tag");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!cancelled) {
|
||||||
|
setReleaseVersion(version);
|
||||||
|
setReleaseStatusMessage(`Latest GitHub release: ${version}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch {
|
||||||
|
if (!cancelled && !abortController.signal.aborted) {
|
||||||
|
setReleaseVersion(null);
|
||||||
|
setReleaseStatusMessage("Latest GitHub release unavailable.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
void checkDependency();
|
||||||
|
void loadReleaseInfo();
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
cancelled = true;
|
||||||
|
abortController.abort();
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleDownload = async () => {
|
||||||
|
setDownloading(true);
|
||||||
|
setErrorMessage(null);
|
||||||
|
try {
|
||||||
|
await DownloadExtractor();
|
||||||
|
setOpen(false);
|
||||||
|
toast.success("Xtractor installed");
|
||||||
|
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>Download Xtractor</DialogTitle>
|
||||||
|
<DialogDescription>Xtractor is required before you can use this app.</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
|
||||||
|
<div className="space-y-3">
|
||||||
|
<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 />
|
||||||
|
Downloading Xtractor...
|
||||||
|
</>) : (<>
|
||||||
|
<Download className="h-4 w-4"/>
|
||||||
|
Download Xtractor
|
||||||
|
</>)}
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>);
|
||||||
|
}
|
||||||
@@ -1,58 +1,34 @@
|
|||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { X, User } from "lucide-react";
|
import { X, User } from "lucide-react";
|
||||||
|
|
||||||
export interface HistoryItem {
|
export interface HistoryItem {
|
||||||
id: string;
|
id: string;
|
||||||
username: string;
|
username: string;
|
||||||
name: string;
|
name: string;
|
||||||
image: string;
|
image: string;
|
||||||
mediaCount: number;
|
mediaCount: number;
|
||||||
timestamp: number;
|
timestamp: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface FetchHistoryProps {
|
interface FetchHistoryProps {
|
||||||
history: HistoryItem[];
|
history: HistoryItem[];
|
||||||
onSelect: (item: HistoryItem) => void;
|
onSelect: (item: HistoryItem) => void;
|
||||||
onRemove: (id: string) => void;
|
onRemove: (id: string) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function FetchHistory({ history, onSelect, onRemove }: FetchHistoryProps) {
|
export function FetchHistory({ history, onSelect, onRemove }: FetchHistoryProps) {
|
||||||
if (history.length === 0) return null;
|
if (history.length === 0)
|
||||||
|
return null;
|
||||||
return (
|
return (<div className="space-y-2">
|
||||||
<div className="space-y-2">
|
|
||||||
<p className="text-sm text-muted-foreground">Recent Fetches</p>
|
<p className="text-sm text-muted-foreground">Recent Fetches</p>
|
||||||
<div className="flex flex-wrap gap-2">
|
<div className="flex flex-wrap gap-2">
|
||||||
{history.map((item) => (
|
{history.map((item) => (<div key={item.id} className="flex items-center gap-2 px-3 py-1.5 bg-muted/50 rounded-full hover:bg-muted transition-colors group cursor-pointer" onClick={() => onSelect(item)}>
|
||||||
<div
|
{item.image ? (<img src={item.image} alt={item.name} className="w-5 h-5 rounded-full"/>) : (<User className="w-5 h-5 text-muted-foreground"/>)}
|
||||||
key={item.id}
|
|
||||||
className="flex items-center gap-2 px-3 py-1.5 bg-muted/50 rounded-full hover:bg-muted transition-colors group cursor-pointer"
|
|
||||||
onClick={() => onSelect(item)}
|
|
||||||
>
|
|
||||||
{item.image ? (
|
|
||||||
<img
|
|
||||||
src={item.image}
|
|
||||||
alt={item.name}
|
|
||||||
className="w-5 h-5 rounded-full"
|
|
||||||
/>
|
|
||||||
) : (
|
|
||||||
<User className="w-5 h-5 text-muted-foreground" />
|
|
||||||
)}
|
|
||||||
<span className="text-sm">@{item.username}</span>
|
<span className="text-sm">@{item.username}</span>
|
||||||
<Button
|
<Button variant="ghost" size="icon" className="h-4 w-4 opacity-0 group-hover:opacity-100 transition-opacity" onClick={(e) => {
|
||||||
variant="ghost"
|
|
||||||
size="icon"
|
|
||||||
className="h-4 w-4 opacity-0 group-hover:opacity-100 transition-opacity"
|
|
||||||
onClick={(e) => {
|
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
onRemove(item.id);
|
onRemove(item.id);
|
||||||
}}
|
}}>
|
||||||
>
|
<X className="h-3 w-3"/>
|
||||||
<X className="h-3 w-3" />
|
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>))}
|
||||||
))}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>);
|
||||||
);
|
|
||||||
}
|
}
|
||||||
@@ -1,63 +1,39 @@
|
|||||||
import { Badge } from "@/components/ui/badge";
|
import { Badge } from "@/components/ui/badge";
|
||||||
import {
|
import { Tooltip, TooltipContent, TooltipTrigger, } from "@/components/ui/tooltip";
|
||||||
Tooltip,
|
|
||||||
TooltipContent,
|
|
||||||
TooltipTrigger,
|
|
||||||
} from "@/components/ui/tooltip";
|
|
||||||
import { openExternal } from "@/lib/utils";
|
import { openExternal } from "@/lib/utils";
|
||||||
import { formatRelativeTime } from "@/lib/relative-time";
|
import { formatRelativeTime } from "@/lib/relative-time";
|
||||||
|
|
||||||
interface HeaderProps {
|
interface HeaderProps {
|
||||||
version: string;
|
version: string;
|
||||||
hasUpdate: boolean;
|
hasUpdate: boolean;
|
||||||
releaseDate?: string | null;
|
releaseDate?: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function Header({ version, hasUpdate, releaseDate }: HeaderProps) {
|
export function Header({ version, hasUpdate, releaseDate }: HeaderProps) {
|
||||||
return (
|
return (<div className="relative">
|
||||||
<div className="relative">
|
|
||||||
<div className="text-center space-y-2">
|
<div className="text-center space-y-2">
|
||||||
<div className="flex items-center justify-center gap-3">
|
<div className="flex items-center justify-center gap-3">
|
||||||
<img
|
<img src="/icon.svg" alt="Twitter/X Media Batch Downloader" className="w-12 h-12 cursor-pointer" onClick={() => window.location.reload()}/>
|
||||||
src="/icon.svg"
|
<h1 className="text-3xl font-bold cursor-pointer" onClick={() => window.location.reload()}>
|
||||||
alt="Twitter/X Media Batch Downloader"
|
|
||||||
className="w-12 h-12 cursor-pointer"
|
|
||||||
onClick={() => window.location.reload()}
|
|
||||||
/>
|
|
||||||
<h1
|
|
||||||
className="text-3xl font-bold cursor-pointer"
|
|
||||||
onClick={() => window.location.reload()}
|
|
||||||
>
|
|
||||||
Twitter/X Media Batch Downloader
|
Twitter/X Media Batch Downloader
|
||||||
</h1>
|
</h1>
|
||||||
<div className="relative">
|
<div className="relative">
|
||||||
<Tooltip>
|
<Tooltip>
|
||||||
<TooltipTrigger asChild>
|
<TooltipTrigger asChild>
|
||||||
<Badge variant="default" asChild>
|
<Badge variant="default" asChild>
|
||||||
<button
|
<button type="button" onClick={() => openExternal("https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases")} className="cursor-pointer hover:opacity-80 transition-opacity">
|
||||||
type="button"
|
|
||||||
onClick={() => openExternal("https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases")}
|
|
||||||
className="cursor-pointer hover:opacity-80 transition-opacity"
|
|
||||||
>
|
|
||||||
v{version}
|
v{version}
|
||||||
</button>
|
</button>
|
||||||
</Badge>
|
</Badge>
|
||||||
</TooltipTrigger>
|
</TooltipTrigger>
|
||||||
{hasUpdate && releaseDate && (
|
{hasUpdate && releaseDate && (<TooltipContent>
|
||||||
<TooltipContent>
|
|
||||||
<p>{formatRelativeTime(releaseDate)}</p>
|
<p>{formatRelativeTime(releaseDate)}</p>
|
||||||
</TooltipContent>
|
</TooltipContent>)}
|
||||||
)}
|
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
{hasUpdate && (
|
{hasUpdate && (<span className="absolute -top-1 -right-1 flex h-3 w-3">
|
||||||
<span className="absolute -top-1 -right-1 flex h-3 w-3">
|
|
||||||
<span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-green-400 opacity-75"></span>
|
<span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-green-400 opacity-75"></span>
|
||||||
<span className="relative inline-flex rounded-full h-3 w-3 bg-green-500"></span>
|
<span className="relative inline-flex rounded-full h-3 w-3 bg-green-500"></span>
|
||||||
</span>
|
</span>)}
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>);
|
||||||
);
|
|
||||||
}
|
}
|
||||||
+891
-1047
File diff suppressed because it is too large.
Load diff
@@ -2,334 +2,378 @@ import { useState, useEffect } from "react";
|
|||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { InputWithContext } from "@/components/ui/input-with-context";
|
import { InputWithContext } from "@/components/ui/input-with-context";
|
||||||
import { Label } from "@/components/ui/label";
|
import { Label } from "@/components/ui/label";
|
||||||
import {
|
import { XCircle, Calendar, StopCircle, Globe, Lock, Bookmark, Heart, Cookie, Eye, EyeOff, ChevronDown, ChevronUp, Info, RotateCcw, Trash2, Clock, CloudDownload, User, Users, FileText, Hourglass, CheckCircle, AlertCircle, SlidersHorizontal, } from "lucide-react";
|
||||||
Search,
|
|
||||||
XCircle,
|
|
||||||
Calendar,
|
|
||||||
StopCircle,
|
|
||||||
Globe,
|
|
||||||
Lock,
|
|
||||||
Bookmark,
|
|
||||||
Heart,
|
|
||||||
Key,
|
|
||||||
Eye,
|
|
||||||
EyeOff,
|
|
||||||
ChevronDown,
|
|
||||||
ChevronUp,
|
|
||||||
Info,
|
|
||||||
RotateCcw,
|
|
||||||
Trash2,
|
|
||||||
} from "lucide-react";
|
|
||||||
import { Spinner } from "@/components/ui/spinner";
|
import { Spinner } from "@/components/ui/spinner";
|
||||||
|
function formatNumberWithComma(num: number): string {
|
||||||
|
return num.toLocaleString();
|
||||||
|
}
|
||||||
import { Checkbox } from "@/components/ui/checkbox";
|
import { Checkbox } from "@/components/ui/checkbox";
|
||||||
import {
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select";
|
||||||
Select,
|
import { Tooltip, TooltipContent, TooltipTrigger, } from "@/components/ui/tooltip";
|
||||||
SelectContent,
|
|
||||||
SelectItem,
|
|
||||||
SelectTrigger,
|
|
||||||
SelectValue,
|
|
||||||
} from "@/components/ui/select";
|
|
||||||
import {
|
|
||||||
Tooltip,
|
|
||||||
TooltipContent,
|
|
||||||
TooltipTrigger,
|
|
||||||
} from "@/components/ui/tooltip";
|
|
||||||
import { Settings as SettingsIcon } from "lucide-react";
|
|
||||||
import { FetchHistory } from "@/components/FetchHistory";
|
import { FetchHistory } from "@/components/FetchHistory";
|
||||||
import type { HistoryItem } from "@/components/FetchHistory";
|
import type { HistoryItem } from "@/components/FetchHistory";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
|
import { getSettings, updateSettings, type FetchMode as SettingsFetchMode, type MediaType as SettingsMediaType } from "@/lib/settings";
|
||||||
|
import { GetStoredAuthToken, SetStoredAuthToken } from "../../wailsjs/go/main/App";
|
||||||
export type FetchMode = "public" | "private";
|
export type FetchMode = "public" | "private";
|
||||||
export type PrivateType = "bookmarks" | "likes";
|
export type PrivateType = "bookmarks" | "likes";
|
||||||
|
export type FetchType = "single" | "multiple";
|
||||||
// Local storage keys for auth tokens
|
const LEGACY_PUBLIC_AUTH_TOKEN_KEY = "twitter_public_auth_token";
|
||||||
const PUBLIC_AUTH_TOKEN_KEY = "twitter_public_auth_token";
|
const LEGACY_PRIVATE_AUTH_TOKEN_KEY = "twitter_private_auth_token";
|
||||||
const PRIVATE_AUTH_TOKEN_KEY = "twitter_private_auth_token";
|
let sessionPublicAuthToken = "";
|
||||||
|
let sessionPrivateAuthToken = "";
|
||||||
interface SearchBarProps {
|
export interface MultipleAccount {
|
||||||
username: string;
|
id: string;
|
||||||
loading: boolean;
|
username: string;
|
||||||
onUsernameChange: (username: string) => void;
|
status: "pending" | "fetching" | "completed" | "incomplete" | "failed";
|
||||||
onFetch: (
|
accountInfo?: {
|
||||||
useDateRange: boolean,
|
name: string;
|
||||||
startDate?: string,
|
nick: string;
|
||||||
endDate?: string,
|
profile_image: string;
|
||||||
mediaType?: string,
|
};
|
||||||
retweets?: boolean,
|
mediaCount: number;
|
||||||
mode?: FetchMode,
|
previousMediaCount: number;
|
||||||
privateType?: PrivateType,
|
elapsedTime: number;
|
||||||
authToken?: string,
|
remainingTime: number | null;
|
||||||
isResume?: boolean
|
error?: string;
|
||||||
) => void;
|
showDiff?: boolean;
|
||||||
onStopFetch: () => void;
|
cursor?: string;
|
||||||
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;
|
|
||||||
}
|
}
|
||||||
|
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[];
|
||||||
|
onImportFile?: () => void;
|
||||||
|
onFetchAll?: (authToken: string) => void;
|
||||||
|
onStopAll?: () => void;
|
||||||
|
onStopAccount?: (accountId: string) => void;
|
||||||
|
onRetryAccount?: (accountId: string, authToken: string) => 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 = [], onImportFile, onFetchAll, onStopAll, onStopAccount, onRetryAccount, isFetchingAll = false, mode: externalMode, privateType: externalPrivateType, onModeChange, }: SearchBarProps) {
|
||||||
|
const [useDateRange, setUseDateRange] = useState(false);
|
||||||
|
const [startDate, setStartDate] = useState("");
|
||||||
|
const [endDate, setEndDate] = useState("");
|
||||||
|
const [mediaType, setMediaType] = useState<SettingsMediaType>(getSettings().mediaType);
|
||||||
|
const [retweets, setRetweets] = useState(getSettings().includeRetweets);
|
||||||
|
const mode = externalMode || "public";
|
||||||
|
const privateType = externalPrivateType || "bookmarks";
|
||||||
|
const [showAuthInput, setShowAuthInput] = useState(false);
|
||||||
|
const [showAdvanced, setShowAdvanced] = useState(false);
|
||||||
|
const [currentFetchMode, setCurrentFetchMode] = useState<SettingsFetchMode>(getSettings().fetchMode);
|
||||||
|
const [publicAuthToken, setPublicAuthToken] = useState(() => sessionPublicAuthToken || localStorage.getItem(LEGACY_PUBLIC_AUTH_TOKEN_KEY) || "");
|
||||||
|
const [privateAuthToken, setPrivateAuthToken] = useState(() => sessionPrivateAuthToken || localStorage.getItem(LEGACY_PRIVATE_AUTH_TOKEN_KEY) || "");
|
||||||
|
const [showPublicToken, setShowPublicToken] = useState(false);
|
||||||
|
const [showPrivateToken, setShowPrivateToken] = useState(false);
|
||||||
|
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) || "";
|
||||||
|
try {
|
||||||
|
if (legacyPublicToken) {
|
||||||
|
await SetStoredAuthToken("public", legacyPublicToken);
|
||||||
|
}
|
||||||
|
if (legacyPrivateToken) {
|
||||||
|
await SetStoredAuthToken("private", legacyPrivateToken);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
export function SearchBar({
|
try {
|
||||||
username,
|
const [storedPublicToken, storedPrivateToken] = await Promise.all([
|
||||||
loading,
|
GetStoredAuthToken("public"),
|
||||||
onUsernameChange,
|
GetStoredAuthToken("private"),
|
||||||
onFetch,
|
]);
|
||||||
onStopFetch,
|
if (!active) {
|
||||||
onResume,
|
return;
|
||||||
onClearResume,
|
}
|
||||||
resumeInfo,
|
sessionPublicAuthToken = storedPublicToken || "";
|
||||||
history,
|
setPublicAuthToken(storedPublicToken || "");
|
||||||
onHistorySelect,
|
sessionPrivateAuthToken = storedPrivateToken || "";
|
||||||
onHistoryRemove,
|
setPrivateAuthToken(storedPrivateToken || "");
|
||||||
hasResult,
|
}
|
||||||
}: SearchBarProps) {
|
catch (error) {
|
||||||
const [useDateRange, setUseDateRange] = useState(false);
|
console.error("Failed to load auth token from secure storage:", error);
|
||||||
const [startDate, setStartDate] = useState("");
|
}
|
||||||
const [endDate, setEndDate] = useState("");
|
};
|
||||||
const [mediaType, setMediaType] = useState("all");
|
void syncStoredTokens();
|
||||||
const [retweets, setRetweets] = useState(false);
|
return () => {
|
||||||
const [mode, setMode] = useState<FetchMode>("public");
|
active = false;
|
||||||
const [privateType, setPrivateType] = useState<PrivateType>("bookmarks");
|
};
|
||||||
const [showAuthInput, setShowAuthInput] = useState(false);
|
}, []);
|
||||||
const [showAdvanced, setShowAdvanced] = useState(false);
|
const handlePublicTokenChange = async (value: string) => {
|
||||||
|
sessionPublicAuthToken = value;
|
||||||
// Separate auth tokens for public and private modes
|
setPublicAuthToken(value);
|
||||||
const [publicAuthToken, setPublicAuthToken] = useState("");
|
try {
|
||||||
const [privateAuthToken, setPrivateAuthToken] = useState("");
|
await SetStoredAuthToken("public", value);
|
||||||
const [showPublicToken, setShowPublicToken] = useState(false);
|
}
|
||||||
const [showPrivateToken, setShowPrivateToken] = useState(false);
|
catch (error) {
|
||||||
|
console.error("Failed to store public auth token securely:", error);
|
||||||
// Load saved auth tokens on mount
|
}
|
||||||
useEffect(() => {
|
};
|
||||||
const savedPublicToken = localStorage.getItem(PUBLIC_AUTH_TOKEN_KEY) || "";
|
const handlePrivateTokenChange = async (value: string) => {
|
||||||
const savedPrivateToken = localStorage.getItem(PRIVATE_AUTH_TOKEN_KEY) || "";
|
sessionPrivateAuthToken = value;
|
||||||
setPublicAuthToken(savedPublicToken);
|
setPrivateAuthToken(value);
|
||||||
setPrivateAuthToken(savedPrivateToken);
|
try {
|
||||||
}, []);
|
await SetStoredAuthToken("private", value);
|
||||||
|
}
|
||||||
// Save auth tokens when they change
|
catch (error) {
|
||||||
const handlePublicTokenChange = (value: string) => {
|
console.error("Failed to store private auth token securely:", error);
|
||||||
setPublicAuthToken(value);
|
}
|
||||||
localStorage.setItem(PUBLIC_AUTH_TOKEN_KEY, value);
|
};
|
||||||
};
|
const handleFetch = () => {
|
||||||
|
const authToken = mode === "public" ? publicAuthToken : privateAuthToken;
|
||||||
const handlePrivateTokenChange = (value: string) => {
|
onFetch(useDateRange, startDate, endDate, mediaType, retweets, mode, privateType, authToken, false);
|
||||||
setPrivateAuthToken(value);
|
};
|
||||||
localStorage.setItem(PRIVATE_AUTH_TOKEN_KEY, value);
|
const handleResume = () => {
|
||||||
};
|
const authToken = mode === "public" ? publicAuthToken : privateAuthToken;
|
||||||
|
if (onResume) {
|
||||||
const handleFetch = () => {
|
onResume(authToken, mediaType, retweets);
|
||||||
const authToken = mode === "public" ? publicAuthToken : privateAuthToken;
|
}
|
||||||
onFetch(useDateRange, startDate, endDate, mediaType, retweets, mode, privateType, authToken, false);
|
};
|
||||||
};
|
const currentAuthToken = mode === "public" ? publicAuthToken : privateAuthToken;
|
||||||
|
const hasAuthToken = currentAuthToken.trim().length > 0;
|
||||||
const handleResume = () => {
|
const isLikesMode = mode === "private" && privateType === "likes";
|
||||||
const authToken = mode === "public" ? publicAuthToken : privateAuthToken;
|
const isBookmarksMode = mode === "private" && privateType === "bookmarks";
|
||||||
if (onResume) {
|
const formatTime = (seconds: number): string => {
|
||||||
onResume(authToken, mediaType, retweets);
|
const mins = Math.floor(seconds / 60);
|
||||||
}
|
const secs = seconds % 60;
|
||||||
};
|
return `${mins}:${String(secs).padStart(2, "0")}`;
|
||||||
|
};
|
||||||
const currentAuthToken = mode === "public" ? publicAuthToken : privateAuthToken;
|
return (<div className="space-y-3">
|
||||||
const hasAuthToken = currentAuthToken.trim().length > 0;
|
|
||||||
// Likes needs username (URL is /username/likes), bookmarks doesn't
|
<div className="flex justify-center gap-2">
|
||||||
const isLikesMode = mode === "private" && privateType === "likes";
|
<div className="flex gap-0.5 p-0.5 bg-muted rounded-lg w-fit">
|
||||||
const isBookmarksMode = mode === "private" && privateType === "bookmarks";
|
<button type="button" onClick={() => onFetchTypeChange?.("single")} className={cn("flex items-center gap-1 px-2 py-1 rounded-md text-xs font-medium transition-all cursor-pointer", fetchType === "single"
|
||||||
|
? "bg-background text-foreground shadow-sm"
|
||||||
return (
|
: "text-muted-foreground hover:text-foreground")}>
|
||||||
<div className="space-y-3">
|
<User className="h-3 w-3"/>
|
||||||
{/* Mode Toggle */}
|
Single
|
||||||
<div className="flex justify-center">
|
|
||||||
<div className="flex gap-1 p-1 bg-muted rounded-lg w-fit">
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => setMode("public")}
|
|
||||||
className={cn(
|
|
||||||
"flex items-center gap-2 px-4 py-2 rounded-md text-sm font-medium transition-all cursor-pointer",
|
|
||||||
mode === "public"
|
|
||||||
? "bg-background text-foreground shadow-sm"
|
|
||||||
: "text-muted-foreground hover:text-foreground"
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<Globe className="h-4 w-4" />
|
|
||||||
Public
|
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button type="button" onClick={() => onFetchTypeChange?.("multiple")} className={cn("flex items-center gap-1 px-2 py-1 rounded-md text-xs font-medium transition-all cursor-pointer", fetchType === "multiple"
|
||||||
type="button"
|
? "bg-background text-foreground shadow-sm"
|
||||||
onClick={() => setMode("private")}
|
: "text-muted-foreground hover:text-foreground")}>
|
||||||
className={cn(
|
<Users className="h-3 w-3"/>
|
||||||
"flex items-center gap-2 px-4 py-2 rounded-md text-sm font-medium transition-all cursor-pointer",
|
Multiple
|
||||||
mode === "private"
|
|
||||||
? "bg-background text-foreground shadow-sm"
|
|
||||||
: "text-muted-foreground hover:text-foreground"
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<Lock className="h-4 w-4" />
|
|
||||||
Private
|
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
{fetchType === "single" && (<div className="flex gap-0.5 p-0.5 bg-muted rounded-lg w-fit">
|
||||||
|
<button type="button" onClick={() => {
|
||||||
|
onModeChange?.("public");
|
||||||
|
}} className={cn("flex items-center gap-1 px-2 py-1 rounded-md text-xs font-medium transition-all cursor-pointer", 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 items-center gap-1 px-2 py-1 rounded-md text-xs font-medium transition-all cursor-pointer", mode === "private"
|
||||||
|
? "bg-background text-foreground shadow-sm"
|
||||||
|
: "text-muted-foreground hover:text-foreground")}>
|
||||||
|
<Lock className="h-3 w-3"/>
|
||||||
|
Private
|
||||||
|
</button>
|
||||||
|
</div>)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Username Input - for public mode and likes mode */}
|
|
||||||
{(mode === "public" || isLikesMode) && (
|
{fetchType === "multiple" && (<div className="space-y-2">
|
||||||
<div className="space-y-2">
|
<div className="flex items-center gap-2">
|
||||||
|
<Label htmlFor="import-txt" className="text-sm">
|
||||||
|
Import Accounts
|
||||||
|
</Label>
|
||||||
|
<Tooltip>
|
||||||
|
<TooltipTrigger asChild>
|
||||||
|
<Info className="h-4 w-4 text-muted-foreground cursor-help"/>
|
||||||
|
</TooltipTrigger>
|
||||||
|
<TooltipContent className="max-w-xs">
|
||||||
|
<p className="text-sm">
|
||||||
|
One username per line, example:
|
||||||
|
<br />
|
||||||
|
<span className="font-mono text-xs">masteraoko</span>
|
||||||
|
<br />
|
||||||
|
<span className="font-mono text-xs">xbatchdemo</span>
|
||||||
|
<br />
|
||||||
|
<span className="font-mono text-xs">takomayuyi</span>
|
||||||
|
</p>
|
||||||
|
</TooltipContent>
|
||||||
|
</Tooltip>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Button id="import-txt" variant="outline" onClick={onImportFile} className="flex items-center gap-2 flex-1">
|
||||||
|
<FileText className="h-4 w-4"/>
|
||||||
|
Import TXT File
|
||||||
|
</Button>
|
||||||
|
<Button variant="default" onClick={() => onFetchAll?.(publicAuthToken)} disabled={multipleAccounts.length === 0 || isFetchingAll} className="flex items-center gap-2 flex-1">
|
||||||
|
{isFetchingAll ? (<>
|
||||||
|
<Spinner />
|
||||||
|
Fetching All...
|
||||||
|
</>) : (<>
|
||||||
|
<CloudDownload className="h-4 w-4"/>
|
||||||
|
Fetch All
|
||||||
|
</>)}
|
||||||
|
</Button>
|
||||||
|
{isFetchingAll && (<Button variant="destructive" onClick={onStopAll} className="flex items-center gap-2">
|
||||||
|
<StopCircle className="h-4 w-4"/>
|
||||||
|
Stop All
|
||||||
|
</Button>)}
|
||||||
|
</div>
|
||||||
|
</div>)}
|
||||||
|
|
||||||
|
|
||||||
|
{fetchType === "single" && (mode === "public" || isLikesMode) && (<div className="space-y-2">
|
||||||
<Label htmlFor="username">
|
<Label htmlFor="username">
|
||||||
{isLikesMode ? "Your Username" : "Username"}
|
X/Twitter URL or Username
|
||||||
</Label>
|
</Label>
|
||||||
|
|
||||||
<div className="flex gap-2">
|
<div className="flex gap-2">
|
||||||
<div className="relative flex-1">
|
<div className="relative flex-1">
|
||||||
<InputWithContext
|
<InputWithContext id="username" placeholder={isLikesMode
|
||||||
id="username"
|
? "your_username or @your_username or https://x.com/your_username"
|
||||||
placeholder={
|
: "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"/>
|
||||||
isLikesMode
|
{username && (<button type="button" className="absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground transition-colors cursor-pointer" onClick={() => onUsernameChange("")}>
|
||||||
? "your_username or @your_username or https://x.com/your_username"
|
<XCircle className="h-4 w-4"/>
|
||||||
: "masteraoko or @masteraoko or https://x.com/masteraoko"
|
</button>)}
|
||||||
}
|
|
||||||
value={username}
|
|
||||||
onChange={(e) => onUsernameChange(e.target.value)}
|
|
||||||
onKeyDown={(e) => e.key === "Enter" && handleFetch()}
|
|
||||||
className="pr-8"
|
|
||||||
/>
|
|
||||||
{username && (
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
className="absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground transition-colors cursor-pointer"
|
|
||||||
onClick={() => onUsernameChange("")}
|
|
||||||
>
|
|
||||||
<XCircle className="h-4 w-4" />
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
{loading && (
|
{loading && (<>
|
||||||
<Button variant="destructive" onClick={onStopFetch}>
|
|
||||||
<StopCircle className="h-4 w-4" />
|
{(remainingTime !== null || elapsedTime > 0) && (<div className="flex items-center gap-1.5 px-3 py-1.5 border rounded-md bg-muted/50 text-sm w-21.25">
|
||||||
Stop
|
<Clock className="h-3.5 w-3.5 text-muted-foreground shrink-0"/>
|
||||||
</Button>
|
<span className="font-mono">
|
||||||
)}
|
{remainingTime !== null && remainingTime >= 0
|
||||||
{/* Resume button - show when there's resumable data */}
|
? `${Math.floor(remainingTime / 60)}:${String(remainingTime % 60).padStart(2, "0")}`
|
||||||
{!loading && resumeInfo?.canResume && mode === "public" && (
|
: `${Math.floor(elapsedTime / 60)}:${String(elapsedTime % 60).padStart(2, "0")}`}
|
||||||
<>
|
</span>
|
||||||
|
</div>)}
|
||||||
|
<Button variant="destructive" onClick={onStopFetch}>
|
||||||
|
<StopCircle className="h-4 w-4"/>
|
||||||
|
Stop
|
||||||
|
</Button>
|
||||||
|
</>)}
|
||||||
|
|
||||||
|
{!loading && resumeInfo?.canResume && mode === "public" && (<>
|
||||||
<Tooltip>
|
<Tooltip>
|
||||||
<TooltipTrigger asChild>
|
<TooltipTrigger asChild>
|
||||||
<Button variant="outline" size="icon" onClick={onClearResume}>
|
<Button variant="outline" size="icon" onClick={onClearResume}>
|
||||||
<Trash2 className="h-4 w-4" />
|
<Trash2 className="h-4 w-4"/>
|
||||||
</Button>
|
</Button>
|
||||||
</TooltipTrigger>
|
</TooltipTrigger>
|
||||||
<TooltipContent>Clear resume data</TooltipContent>
|
<TooltipContent>Clear Resume</TooltipContent>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
<Button variant="secondary" onClick={handleResume} disabled={!hasAuthToken}>
|
<Button variant="secondary" onClick={handleResume} disabled={!hasAuthToken}>
|
||||||
<RotateCcw className="h-4 w-4" />
|
<RotateCcw className="h-4 w-4"/>
|
||||||
Resume ({resumeInfo.mediaCount})
|
Resume ({resumeInfo.mediaCount.toLocaleString()})
|
||||||
</Button>
|
</Button>
|
||||||
</>
|
</>)}
|
||||||
)}
|
|
||||||
<Button onClick={handleFetch} disabled={loading || !hasAuthToken}>
|
<Button onClick={handleFetch} disabled={loading || !hasAuthToken}>
|
||||||
{loading ? (
|
{loading ? (<>
|
||||||
<>
|
|
||||||
<Spinner />
|
<Spinner />
|
||||||
Fetching...
|
Fetching...
|
||||||
</>
|
</>) : (<>
|
||||||
) : (
|
{isLikesMode ? <Heart className="h-4 w-4"/> : <CloudDownload className="h-4 w-4"/>}
|
||||||
<>
|
|
||||||
{isLikesMode ? <Heart className="h-4 w-4" /> : <Search className="h-4 w-4" />}
|
|
||||||
{isLikesMode ? "Fetch Likes" : "Fetch"}
|
{isLikesMode ? "Fetch Likes" : "Fetch"}
|
||||||
</>
|
</>)}
|
||||||
)}
|
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>)}
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Auth Token & Advanced Settings Row */}
|
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
{/* Auth Token Button */}
|
|
||||||
<button
|
<button type="button" onClick={() => setShowAuthInput(!showAuthInput)} className="flex items-center gap-2 px-4 py-2 border rounded-lg text-sm font-medium hover:bg-muted/50 transition-colors cursor-pointer">
|
||||||
type="button"
|
<Cookie className={cn("h-4 w-4", hasAuthToken ? "text-green-500" : "text-destructive")}/>
|
||||||
onClick={() => setShowAuthInput(!showAuthInput)}
|
|
||||||
className="flex items-center gap-2 px-4 py-2 border rounded-lg text-sm font-medium hover:bg-muted/50 transition-colors cursor-pointer"
|
|
||||||
>
|
|
||||||
<Key className={cn("h-4 w-4", hasAuthToken ? "text-green-500" : "text-destructive")} />
|
|
||||||
Auth Token
|
Auth Token
|
||||||
{showAuthInput ? <ChevronUp className="h-4 w-4" /> : <ChevronDown className="h-4 w-4" />}
|
{showAuthInput ? <ChevronUp className="h-4 w-4"/> : <ChevronDown className="h-4 w-4"/>}
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
{/* Advanced Settings Button */}
|
|
||||||
<button
|
<button type="button" onClick={() => setShowAdvanced(!showAdvanced)} className="flex items-center gap-2 px-4 py-2 border rounded-lg text-sm font-medium hover:bg-muted/50 transition-colors cursor-pointer">
|
||||||
type="button"
|
<SlidersHorizontal className="h-4 w-4"/>
|
||||||
onClick={() => setShowAdvanced(!showAdvanced)}
|
|
||||||
className="flex items-center gap-2 px-4 py-2 border rounded-lg text-sm font-medium hover:bg-muted/50 transition-colors cursor-pointer"
|
|
||||||
>
|
|
||||||
<SettingsIcon className="h-4 w-4" />
|
|
||||||
Advanced Settings
|
Advanced Settings
|
||||||
{showAdvanced ? <ChevronUp className="h-4 w-4" /> : <ChevronDown className="h-4 w-4" />}
|
{showAdvanced ? <ChevronUp className="h-4 w-4"/> : <ChevronDown className="h-4 w-4"/>}
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
{/* Private Mode Options - My Bookmarks / My Likes */}
|
|
||||||
{mode === "private" && (
|
{mode === "private" && fetchType === "single" && (<>
|
||||||
<>
|
<button type="button" onClick={() => {
|
||||||
<button
|
onModeChange?.("private", "bookmarks");
|
||||||
type="button"
|
}} className={cn("flex items-center gap-2 px-4 py-2 rounded-lg border text-sm font-medium transition-all cursor-pointer", privateType === "bookmarks"
|
||||||
onClick={() => setPrivateType("bookmarks")}
|
? "border-primary bg-primary/10 text-primary"
|
||||||
className={cn(
|
: "border-border hover:border-primary/50")}>
|
||||||
"flex items-center gap-2 px-4 py-2 rounded-lg border text-sm font-medium transition-all cursor-pointer",
|
<Bookmark className="h-4 w-4"/>
|
||||||
privateType === "bookmarks"
|
|
||||||
? "border-primary bg-primary/10 text-primary"
|
|
||||||
: "border-border hover:border-primary/50"
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<Bookmark className="h-4 w-4" />
|
|
||||||
My Bookmarks
|
My Bookmarks
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button type="button" onClick={() => {
|
||||||
type="button"
|
onModeChange?.("private", "likes");
|
||||||
onClick={() => setPrivateType("likes")}
|
}} className={cn("flex items-center gap-2 px-4 py-2 rounded-lg border text-sm font-medium transition-all cursor-pointer", privateType === "likes"
|
||||||
className={cn(
|
? "border-primary bg-primary/10 text-primary"
|
||||||
"flex items-center gap-2 px-4 py-2 rounded-lg border text-sm font-medium transition-all cursor-pointer",
|
: "border-border hover:border-primary/50")}>
|
||||||
privateType === "likes"
|
<Heart className="h-4 w-4"/>
|
||||||
? "border-primary bg-primary/10 text-primary"
|
|
||||||
: "border-border hover:border-primary/50"
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<Heart className="h-4 w-4" />
|
|
||||||
My Likes
|
My Likes
|
||||||
</button>
|
</button>
|
||||||
</>
|
</>)}
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Bookmarks Mode - Fetch button inline */}
|
|
||||||
{isBookmarksMode && (
|
{isBookmarksMode && (<div className="flex items-center gap-2 ml-auto">
|
||||||
<div className="flex items-center gap-2 ml-auto">
|
{loading && (<>
|
||||||
{loading && (
|
|
||||||
<Button variant="destructive" onClick={onStopFetch}>
|
{(remainingTime !== null || elapsedTime > 0) && (<div className="flex items-center gap-1.5 px-3 py-1.5 border rounded-md bg-muted/50 text-sm w-21.25">
|
||||||
<StopCircle className="h-4 w-4" />
|
<Clock className="h-3.5 w-3.5 text-muted-foreground shrink-0"/>
|
||||||
Stop
|
<span className="font-mono">
|
||||||
</Button>
|
{remainingTime !== null && remainingTime >= 0
|
||||||
)}
|
? `${Math.floor(remainingTime / 60)}:${String(remainingTime % 60).padStart(2, "0")}`
|
||||||
|
: `${Math.floor(elapsedTime / 60)}:${String(elapsedTime % 60).padStart(2, "0")}`}
|
||||||
|
</span>
|
||||||
|
</div>)}
|
||||||
|
<Button variant="destructive" onClick={onStopFetch}>
|
||||||
|
<StopCircle className="h-4 w-4"/>
|
||||||
|
Stop
|
||||||
|
</Button>
|
||||||
|
</>)}
|
||||||
<Button onClick={handleFetch} disabled={loading || !hasAuthToken}>
|
<Button onClick={handleFetch} disabled={loading || !hasAuthToken}>
|
||||||
{loading ? (
|
{loading ? (<>
|
||||||
<>
|
|
||||||
<Spinner />
|
<Spinner />
|
||||||
Fetching...
|
Fetching...
|
||||||
</>
|
</>) : (<>
|
||||||
) : (
|
<Bookmark className="h-4 w-4"/>
|
||||||
<>
|
|
||||||
<Bookmark className="h-4 w-4" />
|
|
||||||
Fetch Bookmarks
|
Fetch Bookmarks
|
||||||
</>
|
</>)}
|
||||||
)}
|
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>)}
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Auth Token Input (collapsible) */}
|
|
||||||
{showAuthInput && (
|
{showAuthInput && (<div className="p-3 border rounded-lg bg-muted/30">
|
||||||
<div className="p-3 border rounded-lg bg-muted/30">
|
|
||||||
<div className="flex items-center gap-3">
|
<div className="flex items-center gap-3">
|
||||||
<div className="flex items-center gap-1.5">
|
<div className="flex items-center gap-1.5">
|
||||||
<Label htmlFor="auth-token" className="text-sm whitespace-nowrap">
|
<Label htmlFor="auth-token" className="text-sm whitespace-nowrap">
|
||||||
@@ -337,147 +381,218 @@ export function SearchBar({
|
|||||||
</Label>
|
</Label>
|
||||||
<Tooltip>
|
<Tooltip>
|
||||||
<TooltipTrigger asChild>
|
<TooltipTrigger asChild>
|
||||||
<Info className="h-4 w-4 text-muted-foreground cursor-help" />
|
<Info className="h-4 w-4 text-muted-foreground cursor-help"/>
|
||||||
</TooltipTrigger>
|
</TooltipTrigger>
|
||||||
<TooltipContent className="text-center">
|
<TooltipContent className="text-center">
|
||||||
{mode === "private" ? (
|
{mode === "private" ? (<p>Use auth token from the account whose bookmarks/likes you want to fetch</p>) : (<p>Recommended to use a dummy account, not your main account.<br />Excessive usage may cause suspension</p>)}
|
||||||
<p>Use auth token from the account whose bookmarks/likes you want to fetch</p>
|
|
||||||
) : (
|
|
||||||
<p>Recommended to use a dummy account, not your main account.<br />Excessive usage may cause suspension</p>
|
|
||||||
)}
|
|
||||||
</TooltipContent>
|
</TooltipContent>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
</div>
|
</div>
|
||||||
<div className="relative flex-1">
|
<div className="relative flex-1">
|
||||||
<InputWithContext
|
<InputWithContext id="auth-token" type={mode === "public"
|
||||||
id="auth-token"
|
? showPublicToken
|
||||||
type={
|
? "text"
|
||||||
mode === "public"
|
: "password"
|
||||||
? showPublicToken
|
: showPrivateToken
|
||||||
? "text"
|
? "text"
|
||||||
: "password"
|
: "password"} placeholder="Enter your auth_token cookie value" value={currentAuthToken} onChange={(e) => mode === "public"
|
||||||
: showPrivateToken
|
? handlePublicTokenChange(e.target.value)
|
||||||
? "text"
|
: handlePrivateTokenChange(e.target.value)} className="pr-10 bg-background"/>
|
||||||
: "password"
|
<button type="button" className="absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground transition-colors" onClick={() => mode === "public"
|
||||||
}
|
? setShowPublicToken(!showPublicToken)
|
||||||
placeholder="Enter your auth_token cookie value"
|
: setShowPrivateToken(!showPrivateToken)}>
|
||||||
value={currentAuthToken}
|
{(mode === "public" ? showPublicToken : showPrivateToken) ? (<EyeOff className="h-4 w-4"/>) : (<Eye className="h-4 w-4"/>)}
|
||||||
onChange={(e) =>
|
|
||||||
mode === "public"
|
|
||||||
? handlePublicTokenChange(e.target.value)
|
|
||||||
: handlePrivateTokenChange(e.target.value)
|
|
||||||
}
|
|
||||||
className="pr-10 bg-background"
|
|
||||||
/>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
className="absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground transition-colors"
|
|
||||||
onClick={() =>
|
|
||||||
mode === "public"
|
|
||||||
? setShowPublicToken(!showPublicToken)
|
|
||||||
: setShowPrivateToken(!showPrivateToken)
|
|
||||||
}
|
|
||||||
>
|
|
||||||
{(mode === "public" ? showPublicToken : showPrivateToken) ? (
|
|
||||||
<EyeOff className="h-4 w-4" />
|
|
||||||
) : (
|
|
||||||
<Eye className="h-4 w-4" />
|
|
||||||
)}
|
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>)}
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Advanced Settings (collapsible) */}
|
|
||||||
{showAdvanced && (
|
{showAdvanced && (<div className="p-3 border rounded-lg bg-muted/30 space-y-3">
|
||||||
<div className="p-3 border rounded-lg bg-muted/30 space-y-3">
|
|
||||||
{/* Options Row */}
|
<div className="flex items-center gap-4 flex-wrap">
|
||||||
<div className="flex items-center gap-4">
|
|
||||||
{/* Media Type */}
|
<div className="flex items-center gap-2">
|
||||||
|
<Label htmlFor="fetch-mode" className="text-sm">
|
||||||
|
Fetch Mode
|
||||||
|
</Label>
|
||||||
|
<Select value={currentFetchMode} onValueChange={(value: SettingsFetchMode) => {
|
||||||
|
updateSettings({ fetchMode: value });
|
||||||
|
setCurrentFetchMode(value);
|
||||||
|
}}>
|
||||||
|
<SelectTrigger id="fetch-mode" className="w-auto h-8 bg-background">
|
||||||
|
<SelectValue />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="batch">Batch</SelectItem>
|
||||||
|
<SelectItem value="single">Single</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<Label htmlFor="media-type" className="text-sm">
|
<Label htmlFor="media-type" className="text-sm">
|
||||||
Media Type
|
Media Type
|
||||||
</Label>
|
</Label>
|
||||||
<Select value={mediaType} onValueChange={setMediaType}>
|
<Select value={mediaType} onValueChange={(value: SettingsMediaType) => {
|
||||||
|
updateSettings({ mediaType: value });
|
||||||
|
setMediaType(value);
|
||||||
|
}}>
|
||||||
<SelectTrigger id="media-type" className="w-auto h-8 bg-background">
|
<SelectTrigger id="media-type" className="w-auto h-8 bg-background">
|
||||||
<SelectValue />
|
<SelectValue />
|
||||||
</SelectTrigger>
|
</SelectTrigger>
|
||||||
<SelectContent>
|
<SelectContent>
|
||||||
<SelectItem value="all">All Media</SelectItem>
|
<SelectItem value="all">All Media</SelectItem>
|
||||||
<SelectItem value="image">Images Only</SelectItem>
|
<SelectItem value="image">Images</SelectItem>
|
||||||
<SelectItem value="video">Videos Only</SelectItem>
|
<SelectItem value="video">Videos</SelectItem>
|
||||||
<SelectItem value="gif">GIFs Only</SelectItem>
|
<SelectItem value="gif">GIFs</SelectItem>
|
||||||
<SelectItem value="text">Text Only (No Media)</SelectItem>
|
<SelectItem value="text">Text (No Media)</SelectItem>
|
||||||
</SelectContent>
|
</SelectContent>
|
||||||
</Select>
|
</Select>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Include Retweets */}
|
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<Checkbox
|
<Checkbox id="retweets" checked={retweets} onCheckedChange={(checked) => {
|
||||||
id="retweets"
|
const value = checked as boolean;
|
||||||
checked={retweets}
|
updateSettings({ includeRetweets: value });
|
||||||
onCheckedChange={(checked) => setRetweets(checked as boolean)}
|
setRetweets(value);
|
||||||
className="bg-background"
|
}} className="bg-background"/>
|
||||||
/>
|
|
||||||
<Label htmlFor="retweets" className="text-sm cursor-pointer">
|
<Label htmlFor="retweets" className="text-sm cursor-pointer">
|
||||||
Include Retweets
|
Include Retweets
|
||||||
</Label>
|
</Label>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Date Range Toggle - only for public mode */}
|
|
||||||
{mode === "public" && (
|
{mode === "public" && (<>
|
||||||
<>
|
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<Checkbox
|
<Checkbox id="date-range" checked={useDateRange} onCheckedChange={(checked) => setUseDateRange(checked as boolean)} className="bg-background"/>
|
||||||
id="date-range"
|
<Label htmlFor="date-range" className="text-sm cursor-pointer flex items-center gap-1">
|
||||||
checked={useDateRange}
|
<Calendar className="h-4 w-4"/>
|
||||||
onCheckedChange={(checked) => setUseDateRange(checked as boolean)}
|
|
||||||
className="bg-background"
|
|
||||||
/>
|
|
||||||
<Label
|
|
||||||
htmlFor="date-range"
|
|
||||||
className="text-sm cursor-pointer flex items-center gap-1"
|
|
||||||
>
|
|
||||||
<Calendar className="h-4 w-4" />
|
|
||||||
Date Range
|
Date Range
|
||||||
</Label>
|
</Label>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Date Range Inputs - inline */}
|
|
||||||
{useDateRange && (
|
{useDateRange && (<>
|
||||||
<>
|
<InputWithContext id="start-date" type="date" value={startDate} onChange={(e) => setStartDate(e.target.value)} className="w-35 h-8 bg-background"/>
|
||||||
<InputWithContext
|
|
||||||
id="start-date"
|
|
||||||
type="date"
|
|
||||||
value={startDate}
|
|
||||||
onChange={(e) => setStartDate(e.target.value)}
|
|
||||||
className="w-[140px] h-8 bg-background"
|
|
||||||
/>
|
|
||||||
<span className="text-sm text-muted-foreground">-</span>
|
<span className="text-sm text-muted-foreground">-</span>
|
||||||
<InputWithContext
|
<InputWithContext id="end-date" type="date" value={endDate} onChange={(e) => setEndDate(e.target.value)} className="w-35 h-8 bg-background"/>
|
||||||
id="end-date"
|
</>)}
|
||||||
type="date"
|
</>)}
|
||||||
value={endDate}
|
|
||||||
onChange={(e) => setEndDate(e.target.value)}
|
|
||||||
className="w-[140px] h-8 bg-background"
|
|
||||||
/>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>)}
|
||||||
)}
|
|
||||||
|
|
||||||
{!hasResult && mode === "public" && (
|
|
||||||
<FetchHistory
|
{fetchType === "multiple" && multipleAccounts.length > 0 && (<div className="p-3 border rounded-lg bg-muted/30">
|
||||||
history={history}
|
<div className="flex items-center gap-6 text-sm">
|
||||||
onSelect={onHistorySelect}
|
<div className="flex items-center gap-2">
|
||||||
onRemove={onHistoryRemove}
|
<CheckCircle className="h-4 w-4 text-green-600 dark:text-green-400"/>
|
||||||
/>
|
<span className="text-muted-foreground">Completed:</span>
|
||||||
)}
|
<span className="font-medium">
|
||||||
</div>
|
{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="flex items-center gap-2 ml-auto">
|
||||||
|
<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>
|
||||||
|
</div>
|
||||||
|
</div>)}
|
||||||
|
|
||||||
|
|
||||||
|
{fetchType === "multiple" && multipleAccounts.length > 0 && (<div className="space-y-2">
|
||||||
|
<p className="text-sm text-muted-foreground">Accounts to Fetch ({formatNumberWithComma(multipleAccounts.length)})</p>
|
||||||
|
<div className="space-y-2 max-h-100 overflow-y-auto">
|
||||||
|
{multipleAccounts.map((account) => (<div key={account.id} className="p-3 border rounded-lg bg-card">
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
{account.accountInfo ? (<img src={account.accountInfo.profile_image} alt={account.accountInfo.nick} className="w-10 h-10 rounded-full"/>) : (<div className="w-10 h-10 rounded-full bg-muted flex items-center justify-center">
|
||||||
|
<User className="h-5 w-5 text-muted-foreground"/>
|
||||||
|
</div>)}
|
||||||
|
<div className="flex-1 min-w-0">
|
||||||
|
{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="flex items-center gap-2 mt-1">
|
||||||
|
<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 text-green-600 dark:text-green-400 font-medium">
|
||||||
|
+{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 items-center gap-1.5 px-3 py-1.5 border rounded-md bg-muted/50 text-sm w-21.25">
|
||||||
|
<Clock className="h-3.5 w-3.5 text-muted-foreground shrink-0"/>
|
||||||
|
<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="text-xs px-2 py-1 bg-gray-500/20 text-gray-600 dark:text-gray-400 rounded flex items-center gap-1.5">
|
||||||
|
<Hourglass className="h-3 w-3"/>
|
||||||
|
Pending
|
||||||
|
</span>)}
|
||||||
|
{account.status === "completed" && (<span className="text-xs px-2 py-1 bg-green-500/20 text-green-600 dark:text-green-400 rounded flex items-center gap-1.5">
|
||||||
|
<CheckCircle className="h-3 w-3"/>
|
||||||
|
Completed
|
||||||
|
</span>)}
|
||||||
|
{account.status === "incomplete" && (<>
|
||||||
|
<span className="text-xs px-2 py-1 bg-yellow-500/20 text-yellow-600 dark:text-yellow-400 rounded flex items-center gap-1.5">
|
||||||
|
<AlertCircle className="h-3 w-3"/>
|
||||||
|
Incomplete
|
||||||
|
</span>
|
||||||
|
<Button variant="outline" size="sm" onClick={() => onRetryAccount?.(account.id, publicAuthToken)} disabled={isFetchingAll} className="flex items-center gap-2">
|
||||||
|
<RotateCcw className="h-3.5 w-3.5"/>
|
||||||
|
Retry
|
||||||
|
</Button>
|
||||||
|
</>)}
|
||||||
|
{account.status === "failed" && (<>
|
||||||
|
<span className="text-xs px-2 py-1 bg-red-500/20 text-red-600 dark:text-red-400 rounded flex items-center gap-1.5">
|
||||||
|
<XCircle className="h-3 w-3"/>
|
||||||
|
Failed
|
||||||
|
</span>
|
||||||
|
<Button variant="outline" size="sm" onClick={() => onRetryAccount?.(account.id, publicAuthToken)} disabled={isFetchingAll} className="flex items-center gap-2">
|
||||||
|
<RotateCcw className="h-3.5 w-3.5"/>
|
||||||
|
Retry
|
||||||
|
</Button>
|
||||||
|
</>)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>))}
|
||||||
|
</div>
|
||||||
|
</div>)}
|
||||||
|
|
||||||
|
{!hasResult && mode === "public" && fetchType === "single" && (<FetchHistory history={history} onSelect={onHistorySelect} onRemove={onHistoryRemove}/>)}
|
||||||
|
</div>);
|
||||||
}
|
}
|
||||||
@@ -1,327 +0,0 @@
|
|||||||
import { useState, useEffect } from "react";
|
|
||||||
import { Button } from "@/components/ui/button";
|
|
||||||
import { InputWithContext } from "@/components/ui/input-with-context";
|
|
||||||
import { Label } from "@/components/ui/label";
|
|
||||||
import {
|
|
||||||
Dialog,
|
|
||||||
DialogContent,
|
|
||||||
DialogFooter,
|
|
||||||
DialogTitle,
|
|
||||||
DialogTrigger,
|
|
||||||
} from "@/components/ui/dialog";
|
|
||||||
import {
|
|
||||||
Select,
|
|
||||||
SelectContent,
|
|
||||||
SelectItem,
|
|
||||||
SelectTrigger,
|
|
||||||
SelectValue,
|
|
||||||
} from "@/components/ui/select";
|
|
||||||
import { Settings as SettingsIcon, FolderOpen, Save, RotateCcw, X, Info, Download, Check, Volume2 } from "lucide-react";
|
|
||||||
import { Spinner } from "@/components/ui/spinner";
|
|
||||||
import {
|
|
||||||
Tooltip,
|
|
||||||
TooltipContent,
|
|
||||||
TooltipTrigger,
|
|
||||||
} from "@/components/ui/tooltip";
|
|
||||||
import { Switch } from "@/components/ui/switch";
|
|
||||||
import { getSettings, getSettingsWithDefaults, saveSettings, resetToDefaultSettings, applyThemeMode, type Settings as SettingsType } from "@/lib/settings";
|
|
||||||
import { themes, applyTheme } from "@/lib/themes";
|
|
||||||
import { toastWithSound as toast } from "@/lib/toast-with-sound";
|
|
||||||
import { SelectFolder, IsFFmpegInstalled, DownloadFFmpeg } from "../../wailsjs/go/main/App";
|
|
||||||
|
|
||||||
export function Settings() {
|
|
||||||
const [open, setOpen] = useState(false);
|
|
||||||
const [savedSettings, setSavedSettings] = useState<SettingsType>(getSettings());
|
|
||||||
const [tempSettings, setTempSettings] = useState<SettingsType>(savedSettings);
|
|
||||||
const [, setIsLoadingDefaults] = useState(false);
|
|
||||||
const [isDark, setIsDark] = useState(document.documentElement.classList.contains('dark'));
|
|
||||||
const [ffmpegInstalled, setFfmpegInstalled] = useState(false);
|
|
||||||
const [downloadingFFmpeg, setDownloadingFFmpeg] = useState(false);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
applyThemeMode(savedSettings.themeMode);
|
|
||||||
applyTheme(savedSettings.theme);
|
|
||||||
|
|
||||||
const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");
|
|
||||||
const handleChange = () => {
|
|
||||||
if (savedSettings.themeMode === "auto") {
|
|
||||||
applyThemeMode("auto");
|
|
||||||
applyTheme(savedSettings.theme);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
mediaQuery.addEventListener("change", handleChange);
|
|
||||||
return () => mediaQuery.removeEventListener("change", handleChange);
|
|
||||||
}, [savedSettings.themeMode, savedSettings.theme]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (open) {
|
|
||||||
applyThemeMode(tempSettings.themeMode);
|
|
||||||
applyTheme(tempSettings.theme);
|
|
||||||
|
|
||||||
setTimeout(() => {
|
|
||||||
setIsDark(document.documentElement.classList.contains('dark'));
|
|
||||||
}, 0);
|
|
||||||
|
|
||||||
const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");
|
|
||||||
const handleChange = () => {
|
|
||||||
if (tempSettings.themeMode === "auto") {
|
|
||||||
applyThemeMode("auto");
|
|
||||||
applyTheme(tempSettings.theme);
|
|
||||||
setTimeout(() => {
|
|
||||||
setIsDark(document.documentElement.classList.contains('dark'));
|
|
||||||
}, 0);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
mediaQuery.addEventListener("change", handleChange);
|
|
||||||
return () => mediaQuery.removeEventListener("change", handleChange);
|
|
||||||
}
|
|
||||||
}, [open, tempSettings.themeMode, tempSettings.theme]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const loadDefaults = async () => {
|
|
||||||
if (!savedSettings.downloadPath) {
|
|
||||||
setIsLoadingDefaults(true);
|
|
||||||
const settingsWithDefaults = await getSettingsWithDefaults();
|
|
||||||
setSavedSettings(settingsWithDefaults);
|
|
||||||
setTempSettings(settingsWithDefaults);
|
|
||||||
setIsLoadingDefaults(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
loadDefaults();
|
|
||||||
|
|
||||||
// Check FFmpeg status
|
|
||||||
IsFFmpegInstalled().then(setFfmpegInstalled);
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (open) {
|
|
||||||
setTempSettings(savedSettings);
|
|
||||||
}
|
|
||||||
}, [open, savedSettings]);
|
|
||||||
|
|
||||||
const handleSave = () => {
|
|
||||||
saveSettings(tempSettings);
|
|
||||||
setSavedSettings(tempSettings);
|
|
||||||
setOpen(false);
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleReset = async () => {
|
|
||||||
const defaultSettings = await resetToDefaultSettings();
|
|
||||||
setTempSettings(defaultSettings);
|
|
||||||
setSavedSettings(defaultSettings);
|
|
||||||
applyThemeMode(defaultSettings.themeMode);
|
|
||||||
applyTheme(defaultSettings.theme);
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleCancel = () => {
|
|
||||||
applyThemeMode(savedSettings.themeMode);
|
|
||||||
applyTheme(savedSettings.theme);
|
|
||||||
setTempSettings(savedSettings);
|
|
||||||
setOpen(false);
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleOpenChange = (newOpen: boolean) => {
|
|
||||||
if (!newOpen) {
|
|
||||||
applyThemeMode(savedSettings.themeMode);
|
|
||||||
applyTheme(savedSettings.theme);
|
|
||||||
setTempSettings(savedSettings);
|
|
||||||
}
|
|
||||||
setOpen(newOpen);
|
|
||||||
};
|
|
||||||
|
|
||||||
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);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleDownloadFFmpeg = async () => {
|
|
||||||
setDownloadingFFmpeg(true);
|
|
||||||
try {
|
|
||||||
await DownloadFFmpeg();
|
|
||||||
setFfmpegInstalled(true);
|
|
||||||
toast.success("FFmpeg downloaded successfully");
|
|
||||||
} catch (error) {
|
|
||||||
toast.error("Failed to download FFmpeg");
|
|
||||||
console.error("Error downloading FFmpeg:", error);
|
|
||||||
} finally {
|
|
||||||
setDownloadingFFmpeg(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Dialog open={open} onOpenChange={handleOpenChange}>
|
|
||||||
<DialogTrigger asChild>
|
|
||||||
<Button variant="outline" size="icon">
|
|
||||||
<SettingsIcon className="h-5 w-5" />
|
|
||||||
</Button>
|
|
||||||
</DialogTrigger>
|
|
||||||
<DialogContent className="sm:max-w-[480px] flex flex-col p-6 [&>button]:hidden" aria-describedby={undefined}>
|
|
||||||
<div className="absolute right-4 top-4">
|
|
||||||
<Button
|
|
||||||
variant="ghost"
|
|
||||||
size="icon"
|
|
||||||
className="h-6 w-6 opacity-70 hover:opacity-100"
|
|
||||||
onClick={handleCancel}
|
|
||||||
>
|
|
||||||
<X className="h-4 w-4" />
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
<DialogTitle className="text-sm font-medium">Settings</DialogTitle>
|
|
||||||
|
|
||||||
{/* 2 Column Grid Layout */}
|
|
||||||
<div className="grid grid-cols-2 gap-x-6 gap-y-4 py-2">
|
|
||||||
{/* LEFT COLUMN */}
|
|
||||||
{/* Download Path */}
|
|
||||||
<div className="space-y-2 col-span-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"
|
|
||||||
/>
|
|
||||||
<Tooltip>
|
|
||||||
<TooltipTrigger asChild>
|
|
||||||
<Button type="button" onClick={handleBrowseFolder} size="icon">
|
|
||||||
<FolderOpen className="h-4 w-4" />
|
|
||||||
</Button>
|
|
||||||
</TooltipTrigger>
|
|
||||||
<TooltipContent>Browse Folder</TooltipContent>
|
|
||||||
</Tooltip>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* LEFT: Mode */}
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label htmlFor="theme-mode">Mode</Label>
|
|
||||||
<Select
|
|
||||||
value={tempSettings.themeMode}
|
|
||||||
onValueChange={(value) => setTempSettings((prev) => ({ ...prev, themeMode: value as any }))}
|
|
||||||
>
|
|
||||||
<SelectTrigger id="theme-mode">
|
|
||||||
<SelectValue placeholder="Select theme mode" />
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
<SelectItem value="auto">Auto</SelectItem>
|
|
||||||
<SelectItem value="light">Light</SelectItem>
|
|
||||||
<SelectItem value="dark">Dark</SelectItem>
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* RIGHT: GIF Conversion */}
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label className="flex items-center gap-2">
|
|
||||||
GIF Conversion
|
|
||||||
<Tooltip>
|
|
||||||
<TooltipTrigger asChild>
|
|
||||||
<Info className="h-3.5 w-3.5 text-muted-foreground cursor-help" />
|
|
||||||
</TooltipTrigger>
|
|
||||||
<TooltipContent side="top">
|
|
||||||
<p>FFmpeg is required to convert Twitter's MP4 to actual GIF format</p>
|
|
||||||
</TooltipContent>
|
|
||||||
</Tooltip>
|
|
||||||
</Label>
|
|
||||||
<div className="h-9 flex items-center">
|
|
||||||
{ffmpegInstalled ? (
|
|
||||||
<div className="flex items-center gap-2 text-sm text-green-600 dark:text-green-400">
|
|
||||||
<Check className="h-4 w-4" />
|
|
||||||
Installed
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<Button
|
|
||||||
variant="outline"
|
|
||||||
size="sm"
|
|
||||||
className="h-9"
|
|
||||||
onClick={handleDownloadFFmpeg}
|
|
||||||
disabled={downloadingFFmpeg}
|
|
||||||
>
|
|
||||||
{downloadingFFmpeg ? (
|
|
||||||
<>
|
|
||||||
<Spinner />
|
|
||||||
Downloading...
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
<Download className="h-4 w-4" />
|
|
||||||
Download FFmpeg
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* LEFT: Accent */}
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label htmlFor="theme">Accent</Label>
|
|
||||||
<Select
|
|
||||||
value={tempSettings.theme}
|
|
||||||
onValueChange={(value) => setTempSettings((prev) => ({ ...prev, theme: value }))}
|
|
||||||
>
|
|
||||||
<SelectTrigger id="theme">
|
|
||||||
<SelectValue placeholder="Select a theme" />
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
{themes.map((theme) => (
|
|
||||||
<SelectItem key={theme.name} value={theme.name}>
|
|
||||||
<span className="flex items-center gap-2">
|
|
||||||
<span
|
|
||||||
className="w-3 h-3 rounded-full border border-border"
|
|
||||||
style={{
|
|
||||||
backgroundColor: isDark
|
|
||||||
? theme.cssVars.dark.primary
|
|
||||||
: theme.cssVars.light.primary
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
{theme.label}
|
|
||||||
</span>
|
|
||||||
</SelectItem>
|
|
||||||
))}
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* RIGHT: Sound Effects */}
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label htmlFor="sfx-enabled" className="flex items-center gap-2">
|
|
||||||
<Volume2 className="h-4 w-4 text-muted-foreground" />
|
|
||||||
Sound Effects
|
|
||||||
</Label>
|
|
||||||
<div className="h-9 flex items-center">
|
|
||||||
<Switch
|
|
||||||
id="sfx-enabled"
|
|
||||||
checked={tempSettings.sfxEnabled}
|
|
||||||
onCheckedChange={(checked) => setTempSettings(prev => ({ ...prev, sfxEnabled: checked }))}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<DialogFooter className="gap-2 sm:justify-between">
|
|
||||||
<Button variant="outline" onClick={handleReset} className="gap-1.5">
|
|
||||||
<RotateCcw className="h-4 w-4" />
|
|
||||||
Reset to Default
|
|
||||||
</Button>
|
|
||||||
<div className="flex gap-2">
|
|
||||||
<Button variant="outline" onClick={handleCancel}>
|
|
||||||
Cancel
|
|
||||||
</Button>
|
|
||||||
<Button onClick={handleSave} className="gap-1.5">
|
|
||||||
<Save className="h-4 w-4" />
|
|
||||||
Save Changes
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</DialogFooter>
|
|
||||||
</DialogContent>
|
|
||||||
</Dialog>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -1,86 +1,139 @@
|
|||||||
import { Home, Settings, Bug, Database, LayoutGrid } from "lucide-react";
|
import { useState } from "react";
|
||||||
import {
|
import { HomeIcon } from "@/components/ui/home";
|
||||||
Tooltip,
|
import { SettingsIcon } from "@/components/ui/settings";
|
||||||
TooltipContent,
|
import { ArchiveIcon } from "@/components/ui/archive";
|
||||||
TooltipTrigger,
|
import { TerminalIcon } from "@/components/ui/terminal";
|
||||||
} from "@/components/ui/tooltip";
|
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 { Button } from "@/components/ui/button";
|
||||||
import { openExternal } from "@/lib/utils";
|
import { openExternal } from "@/lib/utils";
|
||||||
|
export type PageType = "main" | "settings" | "debug" | "database" | "support";
|
||||||
export type PageType = "main" | "settings" | "debug" | "database";
|
|
||||||
|
|
||||||
interface SidebarProps {
|
interface SidebarProps {
|
||||||
currentPage: PageType;
|
currentPage: PageType;
|
||||||
onPageChange: (page: PageType) => void;
|
onPageChange: (page: PageType) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function Sidebar({ currentPage, onPageChange }: SidebarProps) {
|
export function Sidebar({ currentPage, onPageChange }: SidebarProps) {
|
||||||
const navItems = [
|
const [isIssuesDialogOpen, setIsIssuesDialogOpen] = useState(false);
|
||||||
{ id: "main" as PageType, icon: Home, label: "Home" },
|
const [hasIssueAgreement, setHasIssueAgreement] = useState(false);
|
||||||
{ id: "settings" as PageType, icon: Settings, label: "Settings" },
|
const handleIssuesDialogChange = (open: boolean) => {
|
||||||
{ id: "database" as PageType, icon: Database, label: "Saved Accounts" },
|
setIsIssuesDialogOpen(open);
|
||||||
{ id: "debug" as PageType, icon: Bug, label: "Debug Logs" },
|
if (!open) {
|
||||||
];
|
setHasIssueAgreement(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">
|
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">
|
<div className="flex flex-col gap-2 flex-1">
|
||||||
{navItems.map((item) => (
|
|
||||||
<Tooltip key={item.id} delayDuration={0}>
|
|
||||||
<TooltipTrigger asChild>
|
|
||||||
<Button
|
|
||||||
variant={currentPage === item.id ? "secondary" : "ghost"}
|
|
||||||
size="icon"
|
|
||||||
className="h-10 w-10"
|
|
||||||
onClick={() => onPageChange(item.id)}
|
|
||||||
>
|
|
||||||
<item.icon className="h-5 w-5" />
|
|
||||||
</Button>
|
|
||||||
</TooltipTrigger>
|
|
||||||
<TooltipContent side="right">
|
|
||||||
<p>{item.label}</p>
|
|
||||||
</TooltipContent>
|
|
||||||
</Tooltip>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* GitHub - below debug */}
|
|
||||||
<Tooltip delayDuration={0}>
|
|
||||||
<TooltipTrigger asChild>
|
|
||||||
<Button
|
|
||||||
variant="ghost"
|
|
||||||
size="icon"
|
|
||||||
className="h-10 w-10"
|
|
||||||
onClick={() => openExternal("https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/issues")}
|
|
||||||
>
|
|
||||||
<svg viewBox="0 0 24 24" className="h-5 w-5" fill="currentColor">
|
|
||||||
<path d="M12 0c-6.626 0-12 5.373-12 12 0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23.957-.266 1.983-.399 3.003-.404 1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576 4.765-1.589 8.199-6.086 8.199-11.386 0-6.627-5.373-12-12-12z" />
|
|
||||||
</svg>
|
|
||||||
</Button>
|
|
||||||
</TooltipTrigger>
|
|
||||||
<TooltipContent side="right">
|
|
||||||
<p>Report Bug</p>
|
|
||||||
</TooltipContent>
|
|
||||||
</Tooltip>
|
|
||||||
|
|
||||||
{/* Other Projects at bottom */}
|
|
||||||
<div className="mt-auto">
|
|
||||||
<Tooltip delayDuration={0}>
|
<Tooltip delayDuration={0}>
|
||||||
<TooltipTrigger asChild>
|
<TooltipTrigger asChild>
|
||||||
<Button
|
<Button variant={currentPage === "main" ? "secondary" : "ghost"} size="icon" className="h-10 w-10" onClick={() => onPageChange("main")}>
|
||||||
variant="ghost"
|
<HomeIcon size={20}/>
|
||||||
size="icon"
|
|
||||||
className="h-10 w-10"
|
|
||||||
onClick={() => openExternal("https://exyezed.cc/")}
|
|
||||||
>
|
|
||||||
<LayoutGrid className="h-5 w-5" />
|
|
||||||
</Button>
|
</Button>
|
||||||
</TooltipTrigger>
|
</TooltipTrigger>
|
||||||
<TooltipContent side="right">
|
<TooltipContent side="right">
|
||||||
<p>Other Projects</p>
|
<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>
|
</TooltipContent>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
</div>
|
</div>
|
||||||
</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 on Ko-fi</p>
|
||||||
|
</TooltipContent>
|
||||||
|
</Tooltip>
|
||||||
|
</div>
|
||||||
|
</div>);
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
import { useState } from "react";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { CircleCheck, Copy } from "lucide-react";
|
||||||
|
import { openExternal } from "@/lib/utils";
|
||||||
|
import KofiLogo from "@/assets/ko-fi.gif";
|
||||||
|
import KofiSvg from "@/assets/kofi_symbol.svg";
|
||||||
|
import UsdtBarcode from "@/assets/usdt.jpg";
|
||||||
|
|
||||||
|
const USDT_ADDRESS = "THnzAAwZgp2Sq5CAXLP2njQDhTvgZG9EWs";
|
||||||
|
|
||||||
|
export function SupportPage() {
|
||||||
|
const [copiedUsdt, setCopiedUsdt] = useState(false);
|
||||||
|
|
||||||
|
return (<div className="flex min-h-[70vh] items-center justify-center p-4">
|
||||||
|
<div className="flex w-full max-w-3xl flex-col items-stretch rounded-xl border bg-card shadow-sm md:flex-row">
|
||||||
|
<div className="flex flex-1 flex-col items-center justify-between space-y-6 border-b p-6 md:border-r md:border-b-0">
|
||||||
|
<div className="flex flex-col items-center space-y-4">
|
||||||
|
<div className="relative flex h-32 w-full items-center justify-center">
|
||||||
|
<img src={KofiLogo} className="pointer-events-none absolute w-72" alt="Ko-fi"/>
|
||||||
|
</div>
|
||||||
|
<h4 className="font-semibold text-foreground">Support via Ko-fi</h4>
|
||||||
|
<p className="px-4 text-center text-sm text-muted-foreground">
|
||||||
|
Enjoying the project? You can support ongoing development by buying me a coffee.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<Button className="h-10 w-full gap-2 bg-[#72a4f2] text-sm font-semibold text-white hover:bg-[#5f8cd6]" onClick={() => openExternal("https://ko-fi.com/afkarxyz")}>
|
||||||
|
<img src={KofiSvg} className="h-5 w-5 shrink-0" alt="" aria-hidden="true"/>
|
||||||
|
Support me on Ko-fi
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex flex-1 flex-col items-center justify-between space-y-6 p-6">
|
||||||
|
<div className="flex w-full flex-col items-center space-y-4">
|
||||||
|
<div className="flex h-32 items-center justify-center">
|
||||||
|
<div className="rounded-xl border bg-white p-2 shadow-sm">
|
||||||
|
<img src={UsdtBarcode} className="h-24 w-24 object-contain" alt="USDT Barcode"/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<h4 className="font-semibold text-foreground">USDT (TRC20)</h4>
|
||||||
|
<p className="px-4 text-center text-sm text-muted-foreground">
|
||||||
|
Crypto donations are also accepted. Scan the QR code or copy the address.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div className="flex h-10 w-full items-center justify-between gap-2 rounded-lg border bg-muted/50 py-1.5 pr-1.5 pl-3">
|
||||||
|
<code className="truncate text-xs font-mono text-muted-foreground" title={USDT_ADDRESS}>
|
||||||
|
{USDT_ADDRESS}
|
||||||
|
</code>
|
||||||
|
<Button variant="ghost" size="icon" className="h-7 w-7 shrink-0 hover:bg-background" onClick={() => {
|
||||||
|
navigator.clipboard.writeText(USDT_ADDRESS);
|
||||||
|
setCopiedUsdt(true);
|
||||||
|
setTimeout(() => setCopiedUsdt(false), 500);
|
||||||
|
}}>
|
||||||
|
{copiedUsdt ? <CircleCheck className="h-3.5 w-3.5 text-green-500"/> : <Copy className="h-3.5 w-3.5"/>}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>);
|
||||||
|
}
|
||||||
@@ -1,55 +1,30 @@
|
|||||||
import { X, Minus, Maximize } from "lucide-react";
|
import { X, Minus, Maximize } from "lucide-react";
|
||||||
import { WindowMinimise, WindowToggleMaximise, Quit } from "../../wailsjs/runtime/runtime";
|
import { WindowMinimise, WindowToggleMaximise, Quit } from "../../wailsjs/runtime/runtime";
|
||||||
|
|
||||||
export function TitleBar() {
|
export function TitleBar() {
|
||||||
const handleMinimize = () => {
|
const handleMinimize = () => {
|
||||||
WindowMinimise();
|
WindowMinimise();
|
||||||
};
|
};
|
||||||
|
const handleMaximize = () => {
|
||||||
const handleMaximize = () => {
|
WindowToggleMaximise();
|
||||||
WindowToggleMaximise();
|
};
|
||||||
};
|
const handleClose = () => {
|
||||||
|
Quit();
|
||||||
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}/>
|
||||||
return (
|
|
||||||
<>
|
|
||||||
{/* Draggable area */}
|
|
||||||
<div
|
|
||||||
className="fixed top-0 left-14 right-0 h-10 z-40 bg-background/80 backdrop-blur-sm"
|
|
||||||
style={{ "--wails-draggable": "drag" } as React.CSSProperties}
|
|
||||||
onDoubleClick={handleMaximize}
|
|
||||||
/>
|
|
||||||
|
|
||||||
{/* Window control buttons - Windows style, right side */}
|
|
||||||
<div className="fixed top-1.5 right-2 z-50 flex h-7 gap-0.5">
|
<div className="fixed top-1.5 right-2 z-50 flex h-7 gap-0.5">
|
||||||
<button
|
<button onClick={handleMinimize} className="w-8 h-7 flex items-center justify-center hover:bg-muted transition-colors rounded" style={{ "--wails-draggable": "no-drag" } as React.CSSProperties} aria-label="Minimize">
|
||||||
onClick={handleMinimize}
|
<Minus className="w-3.5 h-3.5"/>
|
||||||
className="w-8 h-7 flex items-center justify-center hover:bg-muted transition-colors rounded"
|
|
||||||
style={{ "--wails-draggable": "no-drag" } as React.CSSProperties}
|
|
||||||
aria-label="Minimize"
|
|
||||||
>
|
|
||||||
<Minus className="w-3.5 h-3.5" />
|
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button onClick={handleMaximize} className="w-8 h-7 flex items-center justify-center hover:bg-muted transition-colors rounded" style={{ "--wails-draggable": "no-drag" } as React.CSSProperties} aria-label="Maximize">
|
||||||
onClick={handleMaximize}
|
<Maximize className="w-3.5 h-3.5"/>
|
||||||
className="w-8 h-7 flex items-center justify-center hover:bg-muted transition-colors rounded"
|
|
||||||
style={{ "--wails-draggable": "no-drag" } as React.CSSProperties}
|
|
||||||
aria-label="Maximize"
|
|
||||||
>
|
|
||||||
<Maximize className="w-3.5 h-3.5" />
|
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button onClick={handleClose} className="w-8 h-7 flex items-center justify-center hover:bg-destructive hover:text-white transition-colors rounded" style={{ "--wails-draggable": "no-drag" } as React.CSSProperties} aria-label="Close">
|
||||||
onClick={handleClose}
|
<X className="w-3.5 h-3.5"/>
|
||||||
className="w-8 h-7 flex items-center justify-center hover:bg-destructive hover:text-white transition-colors rounded"
|
|
||||||
style={{ "--wails-draggable": "no-drag" } as React.CSSProperties}
|
|
||||||
aria-label="Close"
|
|
||||||
>
|
|
||||||
<X className="w-3.5 h-3.5" />
|
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</>
|
</>);
|
||||||
);
|
|
||||||
}
|
}
|
||||||
@@ -1,66 +0,0 @@
|
|||||||
"use client"
|
|
||||||
|
|
||||||
import * as React from "react"
|
|
||||||
import * as AccordionPrimitive from "@radix-ui/react-accordion"
|
|
||||||
import { ChevronDownIcon } from "lucide-react"
|
|
||||||
|
|
||||||
import { cn } from "@/lib/utils"
|
|
||||||
|
|
||||||
function Accordion({
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof AccordionPrimitive.Root>) {
|
|
||||||
return <AccordionPrimitive.Root data-slot="accordion" {...props} />
|
|
||||||
}
|
|
||||||
|
|
||||||
function AccordionItem({
|
|
||||||
className,
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof AccordionPrimitive.Item>) {
|
|
||||||
return (
|
|
||||||
<AccordionPrimitive.Item
|
|
||||||
data-slot="accordion-item"
|
|
||||||
className={cn("border-b last:border-b-0", className)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function AccordionTrigger({
|
|
||||||
className,
|
|
||||||
children,
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof AccordionPrimitive.Trigger>) {
|
|
||||||
return (
|
|
||||||
<AccordionPrimitive.Header className="flex">
|
|
||||||
<AccordionPrimitive.Trigger
|
|
||||||
data-slot="accordion-trigger"
|
|
||||||
className={cn(
|
|
||||||
"focus-visible:border-ring focus-visible:ring-ring/50 flex flex-1 items-start justify-between gap-4 rounded-md py-4 text-left text-sm font-medium transition-all outline-none hover:underline focus-visible:ring-[3px] disabled:pointer-events-none disabled:opacity-50 [&[data-state=open]>svg]:rotate-180",
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
{children}
|
|
||||||
<ChevronDownIcon className="text-muted-foreground pointer-events-none size-4 shrink-0 translate-y-0.5 transition-transform duration-200" />
|
|
||||||
</AccordionPrimitive.Trigger>
|
|
||||||
</AccordionPrimitive.Header>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function AccordionContent({
|
|
||||||
className,
|
|
||||||
children,
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof AccordionPrimitive.Content>) {
|
|
||||||
return (
|
|
||||||
<AccordionPrimitive.Content
|
|
||||||
data-slot="accordion-content"
|
|
||||||
className="data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down overflow-hidden text-sm"
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
<div className={cn("pt-0 pb-4", className)}>{children}</div>
|
|
||||||
</AccordionPrimitive.Content>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
export { Accordion, AccordionItem, AccordionTrigger, AccordionContent }
|
|
||||||
@@ -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 };
|
||||||
@@ -1,46 +1,24 @@
|
|||||||
import * as React from "react"
|
import * as React from "react";
|
||||||
import { Slot } from "@radix-ui/react-slot"
|
import { Slot } from "@radix-ui/react-slot";
|
||||||
import { cva, type VariantProps } from "class-variance-authority"
|
import { cva, type VariantProps } from "class-variance-authority";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
import { cn } from "@/lib/utils"
|
const badgeVariants = cva("inline-flex items-center justify-center rounded-full border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden", {
|
||||||
|
|
||||||
const badgeVariants = cva(
|
|
||||||
"inline-flex items-center justify-center rounded-full border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",
|
|
||||||
{
|
|
||||||
variants: {
|
variants: {
|
||||||
variant: {
|
variant: {
|
||||||
default:
|
default: "border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",
|
||||||
"border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",
|
secondary: "border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",
|
||||||
secondary:
|
destructive: "border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
|
||||||
"border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",
|
outline: "text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
|
||||||
destructive:
|
},
|
||||||
"border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
|
|
||||||
outline:
|
|
||||||
"text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
defaultVariants: {
|
defaultVariants: {
|
||||||
variant: "default",
|
variant: "default",
|
||||||
},
|
},
|
||||||
}
|
});
|
||||||
)
|
function Badge({ className, variant, asChild = false, ...props }: React.ComponentProps<"span"> & VariantProps<typeof badgeVariants> & {
|
||||||
|
asChild?: boolean;
|
||||||
function Badge({
|
}) {
|
||||||
className,
|
const Comp = asChild ? Slot : "span";
|
||||||
variant,
|
return (<Comp data-slot="badge" className={cn(badgeVariants({ variant }), className)} {...props}/>);
|
||||||
asChild = false,
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<"span"> &
|
|
||||||
VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
|
|
||||||
const Comp = asChild ? Slot : "span"
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Comp
|
|
||||||
data-slot="badge"
|
|
||||||
className={cn(badgeVariants({ variant }), className)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
export { Badge, badgeVariants };
|
||||||
export { Badge, badgeVariants }
|
|
||||||
@@ -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,131 @@
|
|||||||
|
"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 };
|
||||||
@@ -1,60 +1,35 @@
|
|||||||
import * as React from "react"
|
import * as React from "react";
|
||||||
import { Slot } from "@radix-ui/react-slot"
|
import { Slot } from "@radix-ui/react-slot";
|
||||||
import { cva, type VariantProps } from "class-variance-authority"
|
import { cva, type VariantProps } from "class-variance-authority";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
import { cn } from "@/lib/utils"
|
const buttonVariants = cva("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all cursor-pointer disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive", {
|
||||||
|
|
||||||
const buttonVariants = cva(
|
|
||||||
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all cursor-pointer disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
|
|
||||||
{
|
|
||||||
variants: {
|
variants: {
|
||||||
variant: {
|
variant: {
|
||||||
default: "bg-primary text-primary-foreground hover:bg-primary/90",
|
default: "bg-primary text-primary-foreground hover:bg-primary/90",
|
||||||
destructive:
|
destructive: "bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
|
||||||
"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
|
outline: "border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",
|
||||||
outline:
|
secondary: "bg-secondary text-secondary-foreground hover:bg-secondary/80",
|
||||||
"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",
|
ghost: "hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
|
||||||
secondary:
|
link: "text-primary underline-offset-4 hover:underline",
|
||||||
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
|
},
|
||||||
ghost:
|
size: {
|
||||||
"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
|
default: "h-9 px-4 py-2 has-[>svg]:px-3",
|
||||||
link: "text-primary underline-offset-4 hover:underline",
|
sm: "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",
|
||||||
},
|
lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
|
||||||
size: {
|
icon: "size-9",
|
||||||
default: "h-9 px-4 py-2 has-[>svg]:px-3",
|
"icon-sm": "size-8",
|
||||||
sm: "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",
|
"icon-lg": "size-10",
|
||||||
lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
|
},
|
||||||
icon: "size-9",
|
|
||||||
"icon-sm": "size-8",
|
|
||||||
"icon-lg": "size-10",
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
defaultVariants: {
|
defaultVariants: {
|
||||||
variant: "default",
|
variant: "default",
|
||||||
size: "default",
|
size: "default",
|
||||||
},
|
},
|
||||||
}
|
});
|
||||||
)
|
function Button({ className, variant, size, asChild = false, ...props }: React.ComponentProps<"button"> & VariantProps<typeof buttonVariants> & {
|
||||||
|
asChild?: boolean;
|
||||||
function Button({
|
}) {
|
||||||
className,
|
const Comp = asChild ? Slot : "button";
|
||||||
variant,
|
return (<Comp data-slot="button" className={cn(buttonVariants({ variant, size, className }))} {...props}/>);
|
||||||
size,
|
|
||||||
asChild = false,
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<"button"> &
|
|
||||||
VariantProps<typeof buttonVariants> & {
|
|
||||||
asChild?: boolean
|
|
||||||
}) {
|
|
||||||
const Comp = asChild ? Slot : "button"
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Comp
|
|
||||||
data-slot="button"
|
|
||||||
className={cn(buttonVariants({ variant, size, className }))}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
export { Button, buttonVariants };
|
||||||
export { Button, buttonVariants }
|
|
||||||
@@ -1,92 +0,0 @@
|
|||||||
import * as React from "react"
|
|
||||||
|
|
||||||
import { cn } from "@/lib/utils"
|
|
||||||
|
|
||||||
function Card({ className, ...props }: React.ComponentProps<"div">) {
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
data-slot="card"
|
|
||||||
className={cn(
|
|
||||||
"bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
data-slot="card-header"
|
|
||||||
className={cn(
|
|
||||||
"@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-2 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
data-slot="card-title"
|
|
||||||
className={cn("leading-none font-semibold", className)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
data-slot="card-description"
|
|
||||||
className={cn("text-muted-foreground text-sm", className)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
data-slot="card-action"
|
|
||||||
className={cn(
|
|
||||||
"col-start-2 row-span-2 row-start-1 self-start justify-self-end",
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
data-slot="card-content"
|
|
||||||
className={cn("px-6", className)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
data-slot="card-footer"
|
|
||||||
className={cn("flex items-center px-6 [.border-t]:pt-6", className)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
export {
|
|
||||||
Card,
|
|
||||||
CardHeader,
|
|
||||||
CardFooter,
|
|
||||||
CardTitle,
|
|
||||||
CardAction,
|
|
||||||
CardDescription,
|
|
||||||
CardContent,
|
|
||||||
}
|
|
||||||
@@ -1,32 +1,13 @@
|
|||||||
"use client"
|
"use client";
|
||||||
|
import * as React from "react";
|
||||||
import * as React from "react"
|
import * as CheckboxPrimitive from "@radix-ui/react-checkbox";
|
||||||
import * as CheckboxPrimitive from "@radix-ui/react-checkbox"
|
import { CheckIcon } from "lucide-react";
|
||||||
import { CheckIcon } from "lucide-react"
|
import { cn } from "@/lib/utils";
|
||||||
|
function Checkbox({ className, ...props }: React.ComponentProps<typeof CheckboxPrimitive.Root>) {
|
||||||
import { cn } from "@/lib/utils"
|
return (<CheckboxPrimitive.Root data-slot="checkbox" className={cn("peer border-input dark:bg-input/30 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:data-[state=checked]:bg-primary data-[state=checked]:border-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive size-4 shrink-0 rounded-[4px] border shadow-xs transition-shadow outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50", className)} {...props}>
|
||||||
|
<CheckboxPrimitive.Indicator data-slot="checkbox-indicator" className="grid place-content-center text-current transition-none">
|
||||||
function Checkbox({
|
<CheckIcon className="size-3.5"/>
|
||||||
className,
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof CheckboxPrimitive.Root>) {
|
|
||||||
return (
|
|
||||||
<CheckboxPrimitive.Root
|
|
||||||
data-slot="checkbox"
|
|
||||||
className={cn(
|
|
||||||
"peer border-input dark:bg-input/30 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:data-[state=checked]:bg-primary data-[state=checked]:border-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive size-4 shrink-0 rounded-[4px] border shadow-xs transition-shadow outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
<CheckboxPrimitive.Indicator
|
|
||||||
data-slot="checkbox-indicator"
|
|
||||||
className="grid place-content-center text-current transition-none"
|
|
||||||
>
|
|
||||||
<CheckIcon className="size-3.5" />
|
|
||||||
</CheckboxPrimitive.Indicator>
|
</CheckboxPrimitive.Indicator>
|
||||||
</CheckboxPrimitive.Root>
|
</CheckboxPrimitive.Root>);
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
export { Checkbox };
|
||||||
export { Checkbox }
|
|
||||||
@@ -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 };
|
||||||
@@ -1,252 +1,77 @@
|
|||||||
"use client"
|
"use client";
|
||||||
|
import * as React from "react";
|
||||||
import * as React from "react"
|
import * as ContextMenuPrimitive from "@radix-ui/react-context-menu";
|
||||||
import * as ContextMenuPrimitive from "@radix-ui/react-context-menu"
|
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react";
|
||||||
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react"
|
import { cn } from "@/lib/utils";
|
||||||
|
function ContextMenu({ ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Root>) {
|
||||||
import { cn } from "@/lib/utils"
|
return <ContextMenuPrimitive.Root data-slot="context-menu" {...props}/>;
|
||||||
|
|
||||||
function ContextMenu({
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Root>) {
|
|
||||||
return <ContextMenuPrimitive.Root data-slot="context-menu" {...props} />
|
|
||||||
}
|
}
|
||||||
|
function ContextMenuTrigger({ ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Trigger>) {
|
||||||
function ContextMenuTrigger({
|
return (<ContextMenuPrimitive.Trigger data-slot="context-menu-trigger" {...props}/>);
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Trigger>) {
|
|
||||||
return (
|
|
||||||
<ContextMenuPrimitive.Trigger data-slot="context-menu-trigger" {...props} />
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
function ContextMenuGroup({ ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Group>) {
|
||||||
function ContextMenuGroup({
|
return (<ContextMenuPrimitive.Group data-slot="context-menu-group" {...props}/>);
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Group>) {
|
|
||||||
return (
|
|
||||||
<ContextMenuPrimitive.Group data-slot="context-menu-group" {...props} />
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
function ContextMenuPortal({ ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Portal>) {
|
||||||
function ContextMenuPortal({
|
return (<ContextMenuPrimitive.Portal data-slot="context-menu-portal" {...props}/>);
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Portal>) {
|
|
||||||
return (
|
|
||||||
<ContextMenuPrimitive.Portal data-slot="context-menu-portal" {...props} />
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
function ContextMenuSub({ ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Sub>) {
|
||||||
function ContextMenuSub({
|
return <ContextMenuPrimitive.Sub data-slot="context-menu-sub" {...props}/>;
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Sub>) {
|
|
||||||
return <ContextMenuPrimitive.Sub data-slot="context-menu-sub" {...props} />
|
|
||||||
}
|
}
|
||||||
|
function ContextMenuRadioGroup({ ...props }: React.ComponentProps<typeof ContextMenuPrimitive.RadioGroup>) {
|
||||||
function ContextMenuRadioGroup({
|
return (<ContextMenuPrimitive.RadioGroup data-slot="context-menu-radio-group" {...props}/>);
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof ContextMenuPrimitive.RadioGroup>) {
|
|
||||||
return (
|
|
||||||
<ContextMenuPrimitive.RadioGroup
|
|
||||||
data-slot="context-menu-radio-group"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
function ContextMenuSubTrigger({ className, inset, children, ...props }: React.ComponentProps<typeof ContextMenuPrimitive.SubTrigger> & {
|
||||||
function ContextMenuSubTrigger({
|
inset?: boolean;
|
||||||
className,
|
|
||||||
inset,
|
|
||||||
children,
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof ContextMenuPrimitive.SubTrigger> & {
|
|
||||||
inset?: boolean
|
|
||||||
}) {
|
}) {
|
||||||
return (
|
return (<ContextMenuPrimitive.SubTrigger data-slot="context-menu-sub-trigger" data-inset={inset} className={cn("focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground flex cursor-default items-center rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-inset:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4", className)} {...props}>
|
||||||
<ContextMenuPrimitive.SubTrigger
|
|
||||||
data-slot="context-menu-sub-trigger"
|
|
||||||
data-inset={inset}
|
|
||||||
className={cn(
|
|
||||||
"focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground flex cursor-default items-center rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-inset:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
{children}
|
{children}
|
||||||
<ChevronRightIcon className="ml-auto" />
|
<ChevronRightIcon className="ml-auto"/>
|
||||||
</ContextMenuPrimitive.SubTrigger>
|
</ContextMenuPrimitive.SubTrigger>);
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
function ContextMenuSubContent({ className, ...props }: React.ComponentProps<typeof ContextMenuPrimitive.SubContent>) {
|
||||||
function ContextMenuSubContent({
|
return (<ContextMenuPrimitive.SubContent data-slot="context-menu-sub-content" className={cn("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-32 origin-(--radix-context-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg", className)} {...props}/>);
|
||||||
className,
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof ContextMenuPrimitive.SubContent>) {
|
|
||||||
return (
|
|
||||||
<ContextMenuPrimitive.SubContent
|
|
||||||
data-slot="context-menu-sub-content"
|
|
||||||
className={cn(
|
|
||||||
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-32 origin-(--radix-context-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
function ContextMenuContent({ className, ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Content>) {
|
||||||
function ContextMenuContent({
|
return (<ContextMenuPrimitive.Portal>
|
||||||
className,
|
<ContextMenuPrimitive.Content data-slot="context-menu-content" className={cn("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-context-menu-content-available-height) min-w-32 origin-(--radix-context-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md", className)} {...props}/>
|
||||||
...props
|
</ContextMenuPrimitive.Portal>);
|
||||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Content>) {
|
|
||||||
return (
|
|
||||||
<ContextMenuPrimitive.Portal>
|
|
||||||
<ContextMenuPrimitive.Content
|
|
||||||
data-slot="context-menu-content"
|
|
||||||
className={cn(
|
|
||||||
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-context-menu-content-available-height) min-w-32 origin-(--radix-context-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md",
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
</ContextMenuPrimitive.Portal>
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
function ContextMenuItem({ className, inset, variant = "default", ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Item> & {
|
||||||
function ContextMenuItem({
|
inset?: boolean;
|
||||||
className,
|
variant?: "default" | "destructive";
|
||||||
inset,
|
|
||||||
variant = "default",
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Item> & {
|
|
||||||
inset?: boolean
|
|
||||||
variant?: "default" | "destructive"
|
|
||||||
}) {
|
}) {
|
||||||
return (
|
return (<ContextMenuPrimitive.Item data-slot="context-menu-item" data-inset={inset} data-variant={variant} className={cn("focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:text-destructive! [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-disabled:pointer-events-none data-disabled:opacity-50 data-inset:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4", className)} {...props}/>);
|
||||||
<ContextMenuPrimitive.Item
|
|
||||||
data-slot="context-menu-item"
|
|
||||||
data-inset={inset}
|
|
||||||
data-variant={variant}
|
|
||||||
className={cn(
|
|
||||||
"focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:text-destructive! [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-disabled:pointer-events-none data-disabled:opacity-50 data-inset:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
function ContextMenuCheckboxItem({ className, children, checked, ...props }: React.ComponentProps<typeof ContextMenuPrimitive.CheckboxItem>) {
|
||||||
function ContextMenuCheckboxItem({
|
return (<ContextMenuPrimitive.CheckboxItem data-slot="context-menu-checkbox-item" className={cn("focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4", className)} checked={checked} {...props}>
|
||||||
className,
|
|
||||||
children,
|
|
||||||
checked,
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof ContextMenuPrimitive.CheckboxItem>) {
|
|
||||||
return (
|
|
||||||
<ContextMenuPrimitive.CheckboxItem
|
|
||||||
data-slot="context-menu-checkbox-item"
|
|
||||||
className={cn(
|
|
||||||
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
checked={checked}
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||||
<ContextMenuPrimitive.ItemIndicator>
|
<ContextMenuPrimitive.ItemIndicator>
|
||||||
<CheckIcon className="size-4" />
|
<CheckIcon className="size-4"/>
|
||||||
</ContextMenuPrimitive.ItemIndicator>
|
</ContextMenuPrimitive.ItemIndicator>
|
||||||
</span>
|
</span>
|
||||||
{children}
|
{children}
|
||||||
</ContextMenuPrimitive.CheckboxItem>
|
</ContextMenuPrimitive.CheckboxItem>);
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
function ContextMenuRadioItem({ className, children, ...props }: React.ComponentProps<typeof ContextMenuPrimitive.RadioItem>) {
|
||||||
function ContextMenuRadioItem({
|
return (<ContextMenuPrimitive.RadioItem data-slot="context-menu-radio-item" className={cn("focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4", className)} {...props}>
|
||||||
className,
|
|
||||||
children,
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof ContextMenuPrimitive.RadioItem>) {
|
|
||||||
return (
|
|
||||||
<ContextMenuPrimitive.RadioItem
|
|
||||||
data-slot="context-menu-radio-item"
|
|
||||||
className={cn(
|
|
||||||
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||||
<ContextMenuPrimitive.ItemIndicator>
|
<ContextMenuPrimitive.ItemIndicator>
|
||||||
<CircleIcon className="size-2 fill-current" />
|
<CircleIcon className="size-2 fill-current"/>
|
||||||
</ContextMenuPrimitive.ItemIndicator>
|
</ContextMenuPrimitive.ItemIndicator>
|
||||||
</span>
|
</span>
|
||||||
{children}
|
{children}
|
||||||
</ContextMenuPrimitive.RadioItem>
|
</ContextMenuPrimitive.RadioItem>);
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
function ContextMenuLabel({ className, inset, ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Label> & {
|
||||||
function ContextMenuLabel({
|
inset?: boolean;
|
||||||
className,
|
|
||||||
inset,
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Label> & {
|
|
||||||
inset?: boolean
|
|
||||||
}) {
|
}) {
|
||||||
return (
|
return (<ContextMenuPrimitive.Label data-slot="context-menu-label" data-inset={inset} className={cn("text-foreground px-2 py-1.5 text-sm font-medium data-inset:pl-8", className)} {...props}/>);
|
||||||
<ContextMenuPrimitive.Label
|
|
||||||
data-slot="context-menu-label"
|
|
||||||
data-inset={inset}
|
|
||||||
className={cn(
|
|
||||||
"text-foreground px-2 py-1.5 text-sm font-medium data-inset:pl-8",
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
function ContextMenuSeparator({ className, ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Separator>) {
|
||||||
function ContextMenuSeparator({
|
return (<ContextMenuPrimitive.Separator data-slot="context-menu-separator" className={cn("bg-border -mx-1 my-1 h-px", className)} {...props}/>);
|
||||||
className,
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Separator>) {
|
|
||||||
return (
|
|
||||||
<ContextMenuPrimitive.Separator
|
|
||||||
data-slot="context-menu-separator"
|
|
||||||
className={cn("bg-border -mx-1 my-1 h-px", className)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
function ContextMenuShortcut({ className, ...props }: React.ComponentProps<"span">) {
|
||||||
function ContextMenuShortcut({
|
return (<span data-slot="context-menu-shortcut" className={cn("text-muted-foreground ml-auto text-xs tracking-widest", className)} {...props}/>);
|
||||||
className,
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<"span">) {
|
|
||||||
return (
|
|
||||||
<span
|
|
||||||
data-slot="context-menu-shortcut"
|
|
||||||
className={cn(
|
|
||||||
"text-muted-foreground ml-auto text-xs tracking-widest",
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
export {
|
|
||||||
ContextMenu,
|
|
||||||
ContextMenuTrigger,
|
|
||||||
ContextMenuContent,
|
|
||||||
ContextMenuItem,
|
|
||||||
ContextMenuCheckboxItem,
|
|
||||||
ContextMenuRadioItem,
|
|
||||||
ContextMenuLabel,
|
|
||||||
ContextMenuSeparator,
|
|
||||||
ContextMenuShortcut,
|
|
||||||
ContextMenuGroup,
|
|
||||||
ContextMenuPortal,
|
|
||||||
ContextMenuSub,
|
|
||||||
ContextMenuSubContent,
|
|
||||||
ContextMenuSubTrigger,
|
|
||||||
ContextMenuRadioGroup,
|
|
||||||
}
|
}
|
||||||
|
export { ContextMenu, ContextMenuTrigger, ContextMenuContent, ContextMenuItem, ContextMenuCheckboxItem, ContextMenuRadioItem, ContextMenuLabel, ContextMenuSeparator, ContextMenuShortcut, ContextMenuGroup, ContextMenuPortal, ContextMenuSub, ContextMenuSubContent, ContextMenuSubTrigger, ContextMenuRadioGroup, };
|
||||||
@@ -1,143 +1,47 @@
|
|||||||
"use client"
|
"use client";
|
||||||
|
import * as React from "react";
|
||||||
import * as React from "react"
|
import * as DialogPrimitive from "@radix-ui/react-dialog";
|
||||||
import * as DialogPrimitive from "@radix-ui/react-dialog"
|
import { XIcon } from "lucide-react";
|
||||||
import { XIcon } from "lucide-react"
|
import { cn } from "@/lib/utils";
|
||||||
|
function Dialog({ ...props }: React.ComponentProps<typeof DialogPrimitive.Root>) {
|
||||||
import { cn } from "@/lib/utils"
|
return <DialogPrimitive.Root data-slot="dialog" {...props}/>;
|
||||||
|
|
||||||
function Dialog({
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof DialogPrimitive.Root>) {
|
|
||||||
return <DialogPrimitive.Root data-slot="dialog" {...props} />
|
|
||||||
}
|
}
|
||||||
|
function DialogTrigger({ ...props }: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
|
||||||
function DialogTrigger({
|
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props}/>;
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
|
|
||||||
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
|
|
||||||
}
|
}
|
||||||
|
function DialogPortal({ ...props }: React.ComponentProps<typeof DialogPrimitive.Portal>) {
|
||||||
function DialogPortal({
|
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props}/>;
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof DialogPrimitive.Portal>) {
|
|
||||||
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
|
|
||||||
}
|
}
|
||||||
|
function DialogClose({ ...props }: React.ComponentProps<typeof DialogPrimitive.Close>) {
|
||||||
function DialogClose({
|
return <DialogPrimitive.Close data-slot="dialog-close" {...props}/>;
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof DialogPrimitive.Close>) {
|
|
||||||
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
|
|
||||||
}
|
}
|
||||||
|
function DialogOverlay({ className, ...props }: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
|
||||||
function DialogOverlay({
|
return (<DialogPrimitive.Overlay data-slot="dialog-overlay" className={cn("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50", className)} {...props}/>);
|
||||||
className,
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
|
|
||||||
return (
|
|
||||||
<DialogPrimitive.Overlay
|
|
||||||
data-slot="dialog-overlay"
|
|
||||||
className={cn(
|
|
||||||
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
function DialogContent({ className, children, showCloseButton = true, ...props }: React.ComponentProps<typeof DialogPrimitive.Content> & {
|
||||||
function DialogContent({
|
showCloseButton?: boolean;
|
||||||
className,
|
|
||||||
children,
|
|
||||||
showCloseButton = true,
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof DialogPrimitive.Content> & {
|
|
||||||
showCloseButton?: boolean
|
|
||||||
}) {
|
}) {
|
||||||
return (
|
return (<DialogPortal data-slot="dialog-portal">
|
||||||
<DialogPortal data-slot="dialog-portal">
|
|
||||||
<DialogOverlay />
|
<DialogOverlay />
|
||||||
<DialogPrimitive.Content
|
<DialogPrimitive.Content data-slot="dialog-content" className={cn("bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg", className)} {...props}>
|
||||||
data-slot="dialog-content"
|
|
||||||
className={cn(
|
|
||||||
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
{children}
|
{children}
|
||||||
{showCloseButton && (
|
{showCloseButton && (<DialogPrimitive.Close data-slot="dialog-close" className="ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4">
|
||||||
<DialogPrimitive.Close
|
|
||||||
data-slot="dialog-close"
|
|
||||||
className="ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"
|
|
||||||
>
|
|
||||||
<XIcon />
|
<XIcon />
|
||||||
<span className="sr-only">Close</span>
|
<span className="sr-only">Close</span>
|
||||||
</DialogPrimitive.Close>
|
</DialogPrimitive.Close>)}
|
||||||
)}
|
|
||||||
</DialogPrimitive.Content>
|
</DialogPrimitive.Content>
|
||||||
</DialogPortal>
|
</DialogPortal>);
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
|
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
return (
|
return (<div data-slot="dialog-header" className={cn("flex flex-col gap-2 text-center sm:text-left", className)} {...props}/>);
|
||||||
<div
|
|
||||||
data-slot="dialog-header"
|
|
||||||
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function DialogFooter({ className, ...props }: React.ComponentProps<"div">) {
|
function DialogFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
return (
|
return (<div data-slot="dialog-footer" className={cn("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end", className)} {...props}/>);
|
||||||
<div
|
|
||||||
data-slot="dialog-footer"
|
|
||||||
className={cn(
|
|
||||||
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
function DialogTitle({ className, ...props }: React.ComponentProps<typeof DialogPrimitive.Title>) {
|
||||||
function DialogTitle({
|
return (<DialogPrimitive.Title data-slot="dialog-title" className={cn("text-lg leading-none font-semibold", className)} {...props}/>);
|
||||||
className,
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof DialogPrimitive.Title>) {
|
|
||||||
return (
|
|
||||||
<DialogPrimitive.Title
|
|
||||||
data-slot="dialog-title"
|
|
||||||
className={cn("text-lg leading-none font-semibold", className)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
function DialogDescription({ className, ...props }: React.ComponentProps<typeof DialogPrimitive.Description>) {
|
||||||
function DialogDescription({
|
return (<DialogPrimitive.Description data-slot="dialog-description" className={cn("text-muted-foreground text-sm", className)} {...props}/>);
|
||||||
className,
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof DialogPrimitive.Description>) {
|
|
||||||
return (
|
|
||||||
<DialogPrimitive.Description
|
|
||||||
data-slot="dialog-description"
|
|
||||||
className={cn("text-muted-foreground text-sm", className)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
export {
|
|
||||||
Dialog,
|
|
||||||
DialogClose,
|
|
||||||
DialogContent,
|
|
||||||
DialogDescription,
|
|
||||||
DialogFooter,
|
|
||||||
DialogHeader,
|
|
||||||
DialogOverlay,
|
|
||||||
DialogPortal,
|
|
||||||
DialogTitle,
|
|
||||||
DialogTrigger,
|
|
||||||
}
|
}
|
||||||
|
export { Dialog, DialogClose, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogOverlay, DialogPortal, DialogTitle, DialogTrigger, };
|
||||||
@@ -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, };
|
||||||
@@ -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 };
|
||||||
@@ -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 };
|
||||||
@@ -1,216 +1,172 @@
|
|||||||
import * as React from "react";
|
import * as React from "react";
|
||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
import {
|
import { ContextMenu, ContextMenuContent, ContextMenuItem, ContextMenuSeparator, ContextMenuTrigger, } from "@/components/ui/context-menu";
|
||||||
ContextMenu,
|
|
||||||
ContextMenuContent,
|
|
||||||
ContextMenuItem,
|
|
||||||
ContextMenuSeparator,
|
|
||||||
ContextMenuTrigger,
|
|
||||||
} from "@/components/ui/context-menu";
|
|
||||||
import { Scissors, Copy, Clipboard, Type } from "lucide-react";
|
import { Scissors, Copy, Clipboard, Type } from "lucide-react";
|
||||||
|
export interface InputWithContextProps extends React.InputHTMLAttributes<HTMLInputElement> {
|
||||||
export interface InputWithContextProps
|
onValueChange?: (value: string) => void;
|
||||||
extends React.InputHTMLAttributes<HTMLInputElement> {
|
|
||||||
onValueChange?: (value: string) => void;
|
|
||||||
}
|
}
|
||||||
|
const InputWithContext = React.forwardRef<HTMLInputElement, InputWithContextProps>(({ className, type, onValueChange, onChange, ...props }, ref) => {
|
||||||
const InputWithContext = React.forwardRef<HTMLInputElement, InputWithContextProps>(
|
|
||||||
({ className, type, onValueChange, onChange, ...props }, ref) => {
|
|
||||||
const inputRef = React.useRef<HTMLInputElement>(null);
|
const inputRef = React.useRef<HTMLInputElement>(null);
|
||||||
const [hasSelection, setHasSelection] = React.useState(false);
|
const [hasSelection, setHasSelection] = React.useState(false);
|
||||||
const [canPaste, setCanPaste] = React.useState(false);
|
const [canPaste, setCanPaste] = React.useState(false);
|
||||||
|
const [uncontrolledHasValue, setUncontrolledHasValue] = React.useState(() => {
|
||||||
// Combine refs
|
const defaultValue = props.defaultValue;
|
||||||
|
return defaultValue !== undefined && defaultValue !== null && String(defaultValue).length > 0;
|
||||||
|
});
|
||||||
|
const hasValue = props.value !== undefined && props.value !== null
|
||||||
|
? String(props.value).length > 0
|
||||||
|
: uncontrolledHasValue;
|
||||||
React.useImperativeHandle(ref, () => inputRef.current as HTMLInputElement);
|
React.useImperativeHandle(ref, () => inputRef.current as HTMLInputElement);
|
||||||
|
|
||||||
// Check selection state
|
|
||||||
const updateSelectionState = () => {
|
const updateSelectionState = () => {
|
||||||
const input = inputRef.current;
|
const input = inputRef.current;
|
||||||
if (!input) return;
|
if (!input)
|
||||||
const start = input.selectionStart ?? 0;
|
return;
|
||||||
const end = input.selectionEnd ?? 0;
|
|
||||||
setHasSelection(start !== end);
|
|
||||||
};
|
|
||||||
|
|
||||||
// Check clipboard permission when user explicitly opens the context menu.
|
|
||||||
const checkClipboard = async () => {
|
|
||||||
try {
|
|
||||||
const text = await navigator.clipboard.readText();
|
|
||||||
setCanPaste(text.length > 0);
|
|
||||||
} catch {
|
|
||||||
setCanPaste(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleCut = async () => {
|
|
||||||
const input = inputRef.current;
|
|
||||||
if (!input) return;
|
|
||||||
|
|
||||||
const start = input.selectionStart ?? 0;
|
|
||||||
const end = input.selectionEnd ?? 0;
|
|
||||||
const selectedText = input.value.substring(start, end);
|
|
||||||
|
|
||||||
if (selectedText) {
|
|
||||||
try {
|
|
||||||
await navigator.clipboard.writeText(selectedText);
|
|
||||||
const newValue = input.value.substring(0, start) + input.value.substring(end);
|
|
||||||
|
|
||||||
// Update value and trigger change
|
|
||||||
input.value = newValue;
|
|
||||||
input.setSelectionRange(start, start);
|
|
||||||
|
|
||||||
// Trigger React onChange
|
|
||||||
if (onChange) {
|
|
||||||
const event = {
|
|
||||||
target: input,
|
|
||||||
currentTarget: input,
|
|
||||||
} as React.ChangeEvent<HTMLInputElement>;
|
|
||||||
onChange(event);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (onValueChange) {
|
|
||||||
onValueChange(newValue);
|
|
||||||
}
|
|
||||||
|
|
||||||
input.focus();
|
|
||||||
} catch (err) {
|
|
||||||
console.error("Failed to cut:", err);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleCopy = async () => {
|
|
||||||
const input = inputRef.current;
|
|
||||||
if (!input) return;
|
|
||||||
|
|
||||||
const start = input.selectionStart ?? 0;
|
|
||||||
const end = input.selectionEnd ?? 0;
|
|
||||||
const selectedText = input.value.substring(start, end);
|
|
||||||
|
|
||||||
if (selectedText) {
|
|
||||||
try {
|
|
||||||
await navigator.clipboard.writeText(selectedText);
|
|
||||||
input.focus();
|
|
||||||
} catch (err) {
|
|
||||||
console.error("Failed to copy:", err);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handlePaste = async () => {
|
|
||||||
const input = inputRef.current;
|
|
||||||
if (!input) return;
|
|
||||||
|
|
||||||
try {
|
|
||||||
const text = await navigator.clipboard.readText();
|
|
||||||
const start = input.selectionStart ?? 0;
|
const start = input.selectionStart ?? 0;
|
||||||
const end = input.selectionEnd ?? 0;
|
const end = input.selectionEnd ?? 0;
|
||||||
|
setHasSelection(start !== end);
|
||||||
const newValue =
|
};
|
||||||
input.value.substring(0, start) + text + input.value.substring(end);
|
const checkClipboard = async () => {
|
||||||
|
try {
|
||||||
// Update value and trigger change
|
const text = await navigator.clipboard.readText();
|
||||||
input.value = newValue;
|
setCanPaste(text.length > 0);
|
||||||
const newPosition = start + text.length;
|
}
|
||||||
input.setSelectionRange(newPosition, newPosition);
|
catch {
|
||||||
|
setCanPaste(false);
|
||||||
// Trigger React onChange
|
}
|
||||||
if (onChange) {
|
};
|
||||||
const event = {
|
const handleCut = async () => {
|
||||||
target: input,
|
const input = inputRef.current;
|
||||||
currentTarget: input,
|
if (!input)
|
||||||
} as React.ChangeEvent<HTMLInputElement>;
|
return;
|
||||||
onChange(event);
|
const start = input.selectionStart ?? 0;
|
||||||
}
|
const end = input.selectionEnd ?? 0;
|
||||||
|
const selectedText = input.value.substring(start, end);
|
||||||
if (onValueChange) {
|
if (selectedText) {
|
||||||
onValueChange(newValue);
|
try {
|
||||||
}
|
await navigator.clipboard.writeText(selectedText);
|
||||||
|
const newValue = input.value.substring(0, start) + input.value.substring(end);
|
||||||
input.focus();
|
input.value = newValue;
|
||||||
await checkClipboard();
|
input.setSelectionRange(start, start);
|
||||||
} catch (err) {
|
if (onChange) {
|
||||||
console.error("Failed to paste:", err);
|
const event = {
|
||||||
}
|
target: input,
|
||||||
|
currentTarget: input,
|
||||||
|
} as React.ChangeEvent<HTMLInputElement>;
|
||||||
|
onChange(event);
|
||||||
|
}
|
||||||
|
if (onValueChange) {
|
||||||
|
onValueChange(newValue);
|
||||||
|
}
|
||||||
|
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 handleSelectAll = () => {
|
||||||
const input = inputRef.current;
|
const input = inputRef.current;
|
||||||
if (!input) return;
|
if (!input)
|
||||||
input.select();
|
return;
|
||||||
input.focus();
|
input.select();
|
||||||
updateSelectionState();
|
input.focus();
|
||||||
|
updateSelectionState();
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
if (onChange) {
|
if (onChange) {
|
||||||
onChange(e);
|
onChange(e);
|
||||||
}
|
}
|
||||||
if (onValueChange) {
|
if (onValueChange) {
|
||||||
onValueChange(e.target.value);
|
onValueChange(e.target.value);
|
||||||
}
|
}
|
||||||
|
if (props.value === undefined) {
|
||||||
|
setUncontrolledHasValue(e.target.value.length > 0);
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
return (<ContextMenu onOpenChange={(open) => {
|
||||||
return (
|
if (open) {
|
||||||
<ContextMenu
|
checkClipboard();
|
||||||
onOpenChange={(open) => {
|
}
|
||||||
if (open) {
|
}}>
|
||||||
checkClipboard();
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<ContextMenuTrigger asChild>
|
<ContextMenuTrigger asChild>
|
||||||
<Input
|
<Input ref={inputRef} type={type} className={className} onChange={handleInputChange} onSelect={updateSelectionState} onMouseUp={updateSelectionState} onKeyUp={updateSelectionState} {...props}/>
|
||||||
ref={inputRef}
|
|
||||||
type={type}
|
|
||||||
className={className}
|
|
||||||
onChange={handleInputChange}
|
|
||||||
onSelect={updateSelectionState}
|
|
||||||
onMouseUp={updateSelectionState}
|
|
||||||
onKeyUp={updateSelectionState}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
</ContextMenuTrigger>
|
</ContextMenuTrigger>
|
||||||
<ContextMenuContent className="w-48">
|
<ContextMenuContent className="w-48">
|
||||||
<ContextMenuItem
|
<ContextMenuItem onSelect={handleCut} disabled={!hasSelection || props.disabled || props.readOnly}>
|
||||||
onSelect={handleCut}
|
<Scissors className="mr-2 h-4 w-4"/>
|
||||||
disabled={!hasSelection || props.disabled || props.readOnly}
|
|
||||||
>
|
|
||||||
<Scissors className="mr-2 h-4 w-4" />
|
|
||||||
Cut
|
Cut
|
||||||
<span className="ml-auto text-xs text-muted-foreground">Ctrl+X</span>
|
<span className="ml-auto text-xs text-muted-foreground">Ctrl+X</span>
|
||||||
</ContextMenuItem>
|
</ContextMenuItem>
|
||||||
<ContextMenuItem
|
<ContextMenuItem onSelect={handleCopy} disabled={!hasSelection || props.disabled}>
|
||||||
onSelect={handleCopy}
|
<Copy className="mr-2 h-4 w-4"/>
|
||||||
disabled={!hasSelection || props.disabled}
|
|
||||||
>
|
|
||||||
<Copy className="mr-2 h-4 w-4" />
|
|
||||||
Copy
|
Copy
|
||||||
<span className="ml-auto text-xs text-muted-foreground">Ctrl+C</span>
|
<span className="ml-auto text-xs text-muted-foreground">Ctrl+C</span>
|
||||||
</ContextMenuItem>
|
</ContextMenuItem>
|
||||||
<ContextMenuItem
|
<ContextMenuItem onSelect={handlePaste} disabled={!canPaste || props.disabled || props.readOnly}>
|
||||||
onSelect={handlePaste}
|
<Clipboard className="mr-2 h-4 w-4"/>
|
||||||
disabled={!canPaste || props.disabled || props.readOnly}
|
|
||||||
>
|
|
||||||
<Clipboard className="mr-2 h-4 w-4" />
|
|
||||||
Paste
|
Paste
|
||||||
<span className="ml-auto text-xs text-muted-foreground">Ctrl+V</span>
|
<span className="ml-auto text-xs text-muted-foreground">Ctrl+V</span>
|
||||||
</ContextMenuItem>
|
</ContextMenuItem>
|
||||||
<ContextMenuSeparator />
|
<ContextMenuSeparator />
|
||||||
<ContextMenuItem
|
<ContextMenuItem onSelect={handleSelectAll} disabled={!hasValue || props.disabled}>
|
||||||
onSelect={handleSelectAll}
|
<Type className="mr-2 h-4 w-4"/>
|
||||||
disabled={!inputRef.current?.value || props.disabled}
|
|
||||||
>
|
|
||||||
<Type className="mr-2 h-4 w-4" />
|
|
||||||
Select All
|
Select All
|
||||||
<span className="ml-auto text-xs text-muted-foreground">Ctrl+A</span>
|
<span className="ml-auto text-xs text-muted-foreground">Ctrl+A</span>
|
||||||
</ContextMenuItem>
|
</ContextMenuItem>
|
||||||
</ContextMenuContent>
|
</ContextMenuContent>
|
||||||
</ContextMenu>
|
</ContextMenu>);
|
||||||
);
|
});
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
InputWithContext.displayName = "InputWithContext";
|
InputWithContext.displayName = "InputWithContext";
|
||||||
|
|
||||||
export { InputWithContext };
|
export { InputWithContext };
|
||||||
@@ -1,21 +1,6 @@
|
|||||||
import * as React from "react"
|
import * as React from "react";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
import { cn } from "@/lib/utils"
|
|
||||||
|
|
||||||
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
|
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
|
||||||
return (
|
return (<input type={type} data-slot="input" className={cn("file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm", "focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]", "aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive", className)} {...props}/>);
|
||||||
<input
|
|
||||||
type={type}
|
|
||||||
data-slot="input"
|
|
||||||
className={cn(
|
|
||||||
"file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
|
||||||
"focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
|
|
||||||
"aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
export { Input };
|
||||||
export { Input }
|
|
||||||
@@ -1,24 +1,8 @@
|
|||||||
"use client"
|
"use client";
|
||||||
|
import * as React from "react";
|
||||||
import * as React from "react"
|
import * as LabelPrimitive from "@radix-ui/react-label";
|
||||||
import * as LabelPrimitive from "@radix-ui/react-label"
|
import { cn } from "@/lib/utils";
|
||||||
|
function Label({ className, ...props }: React.ComponentProps<typeof LabelPrimitive.Root>) {
|
||||||
import { cn } from "@/lib/utils"
|
return (<LabelPrimitive.Root data-slot="label" className={cn("flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50", className)} {...props}/>);
|
||||||
|
|
||||||
function Label({
|
|
||||||
className,
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
|
|
||||||
return (
|
|
||||||
<LabelPrimitive.Root
|
|
||||||
data-slot="label"
|
|
||||||
className={cn(
|
|
||||||
"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
export { Label };
|
||||||
export { Label }
|
|
||||||
@@ -1,127 +0,0 @@
|
|||||||
import * as React from "react"
|
|
||||||
import {
|
|
||||||
ChevronLeftIcon,
|
|
||||||
ChevronRightIcon,
|
|
||||||
MoreHorizontalIcon,
|
|
||||||
} from "lucide-react"
|
|
||||||
|
|
||||||
import { cn } from "@/lib/utils"
|
|
||||||
import { Button, buttonVariants } from "@/components/ui/button"
|
|
||||||
|
|
||||||
function Pagination({ className, ...props }: React.ComponentProps<"nav">) {
|
|
||||||
return (
|
|
||||||
<nav
|
|
||||||
role="navigation"
|
|
||||||
aria-label="pagination"
|
|
||||||
data-slot="pagination"
|
|
||||||
className={cn("mx-auto flex w-full justify-center", className)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function PaginationContent({
|
|
||||||
className,
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<"ul">) {
|
|
||||||
return (
|
|
||||||
<ul
|
|
||||||
data-slot="pagination-content"
|
|
||||||
className={cn("flex flex-row items-center gap-1", className)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function PaginationItem({ ...props }: React.ComponentProps<"li">) {
|
|
||||||
return <li data-slot="pagination-item" {...props} />
|
|
||||||
}
|
|
||||||
|
|
||||||
type PaginationLinkProps = {
|
|
||||||
isActive?: boolean
|
|
||||||
} & Pick<React.ComponentProps<typeof Button>, "size"> &
|
|
||||||
React.ComponentProps<"a">
|
|
||||||
|
|
||||||
function PaginationLink({
|
|
||||||
className,
|
|
||||||
isActive,
|
|
||||||
size = "icon",
|
|
||||||
...props
|
|
||||||
}: PaginationLinkProps) {
|
|
||||||
return (
|
|
||||||
<a
|
|
||||||
aria-current={isActive ? "page" : undefined}
|
|
||||||
data-slot="pagination-link"
|
|
||||||
data-active={isActive}
|
|
||||||
className={cn(
|
|
||||||
buttonVariants({
|
|
||||||
variant: isActive ? "outline" : "ghost",
|
|
||||||
size,
|
|
||||||
}),
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function PaginationPrevious({
|
|
||||||
className,
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof PaginationLink>) {
|
|
||||||
return (
|
|
||||||
<PaginationLink
|
|
||||||
aria-label="Go to previous page"
|
|
||||||
size="default"
|
|
||||||
className={cn("gap-1 px-2.5 sm:pl-2.5", className)}
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
<ChevronLeftIcon />
|
|
||||||
<span className="hidden sm:block">Previous</span>
|
|
||||||
</PaginationLink>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function PaginationNext({
|
|
||||||
className,
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof PaginationLink>) {
|
|
||||||
return (
|
|
||||||
<PaginationLink
|
|
||||||
aria-label="Go to next page"
|
|
||||||
size="default"
|
|
||||||
className={cn("gap-1 px-2.5 sm:pr-2.5", className)}
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
<span className="hidden sm:block">Next</span>
|
|
||||||
<ChevronRightIcon />
|
|
||||||
</PaginationLink>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function PaginationEllipsis({
|
|
||||||
className,
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<"span">) {
|
|
||||||
return (
|
|
||||||
<span
|
|
||||||
aria-hidden
|
|
||||||
data-slot="pagination-ellipsis"
|
|
||||||
className={cn("flex size-9 items-center justify-center", className)}
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
<MoreHorizontalIcon className="size-4" />
|
|
||||||
<span className="sr-only">More pages</span>
|
|
||||||
</span>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
export {
|
|
||||||
Pagination,
|
|
||||||
PaginationContent,
|
|
||||||
PaginationLink,
|
|
||||||
PaginationItem,
|
|
||||||
PaginationPrevious,
|
|
||||||
PaginationNext,
|
|
||||||
PaginationEllipsis,
|
|
||||||
}
|
|
||||||
@@ -1,31 +1,10 @@
|
|||||||
"use client"
|
"use client";
|
||||||
|
import * as React from "react";
|
||||||
import * as React from "react"
|
import * as ProgressPrimitive from "@radix-ui/react-progress";
|
||||||
import * as ProgressPrimitive from "@radix-ui/react-progress"
|
import { cn } from "@/lib/utils";
|
||||||
|
function Progress({ className, value, ...props }: React.ComponentProps<typeof ProgressPrimitive.Root>) {
|
||||||
import { cn } from "@/lib/utils"
|
return (<ProgressPrimitive.Root data-slot="progress" className={cn("bg-primary/20 relative h-2 w-full overflow-hidden rounded-full", className)} {...props}>
|
||||||
|
<ProgressPrimitive.Indicator data-slot="progress-indicator" className="bg-primary h-full w-full flex-1 transition-all" style={{ transform: `translateX(-${100 - (value || 0)}%)` }}/>
|
||||||
function Progress({
|
</ProgressPrimitive.Root>);
|
||||||
className,
|
|
||||||
value,
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof ProgressPrimitive.Root>) {
|
|
||||||
return (
|
|
||||||
<ProgressPrimitive.Root
|
|
||||||
data-slot="progress"
|
|
||||||
className={cn(
|
|
||||||
"bg-primary/20 relative h-2 w-full overflow-hidden rounded-full",
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
<ProgressPrimitive.Indicator
|
|
||||||
data-slot="progress-indicator"
|
|
||||||
className="bg-primary h-full w-full flex-1 transition-all"
|
|
||||||
style={{ transform: `translateX(-${100 - (value || 0)}%)` }}
|
|
||||||
/>
|
|
||||||
</ProgressPrimitive.Root>
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
export { Progress };
|
||||||
export { Progress }
|
|
||||||
@@ -1,45 +0,0 @@
|
|||||||
"use client"
|
|
||||||
|
|
||||||
import * as React from "react"
|
|
||||||
import * as RadioGroupPrimitive from "@radix-ui/react-radio-group"
|
|
||||||
import { CircleIcon } from "lucide-react"
|
|
||||||
|
|
||||||
import { cn } from "@/lib/utils"
|
|
||||||
|
|
||||||
function RadioGroup({
|
|
||||||
className,
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof RadioGroupPrimitive.Root>) {
|
|
||||||
return (
|
|
||||||
<RadioGroupPrimitive.Root
|
|
||||||
data-slot="radio-group"
|
|
||||||
className={cn("grid gap-3", className)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function RadioGroupItem({
|
|
||||||
className,
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof RadioGroupPrimitive.Item>) {
|
|
||||||
return (
|
|
||||||
<RadioGroupPrimitive.Item
|
|
||||||
data-slot="radio-group-item"
|
|
||||||
className={cn(
|
|
||||||
"border-input text-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 dark:bg-input/30 aspect-square size-4 shrink-0 rounded-full border shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
<RadioGroupPrimitive.Indicator
|
|
||||||
data-slot="radio-group-indicator"
|
|
||||||
className="relative flex items-center justify-center"
|
|
||||||
>
|
|
||||||
<CircleIcon className="fill-primary absolute top-1/2 left-1/2 size-2 -translate-x-1/2 -translate-y-1/2" />
|
|
||||||
</RadioGroupPrimitive.Indicator>
|
|
||||||
</RadioGroupPrimitive.Item>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
export { RadioGroup, RadioGroupItem }
|
|
||||||
@@ -1,185 +1,63 @@
|
|||||||
import * as React from "react"
|
import * as React from "react";
|
||||||
import * as SelectPrimitive from "@radix-ui/react-select"
|
import * as SelectPrimitive from "@radix-ui/react-select";
|
||||||
import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-react"
|
import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-react";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
import { cn } from "@/lib/utils"
|
function Select({ ...props }: React.ComponentProps<typeof SelectPrimitive.Root>) {
|
||||||
|
return <SelectPrimitive.Root data-slot="select" {...props}/>;
|
||||||
function Select({
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof SelectPrimitive.Root>) {
|
|
||||||
return <SelectPrimitive.Root data-slot="select" {...props} />
|
|
||||||
}
|
}
|
||||||
|
function SelectGroup({ ...props }: React.ComponentProps<typeof SelectPrimitive.Group>) {
|
||||||
function SelectGroup({
|
return <SelectPrimitive.Group data-slot="select-group" {...props}/>;
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof SelectPrimitive.Group>) {
|
|
||||||
return <SelectPrimitive.Group data-slot="select-group" {...props} />
|
|
||||||
}
|
}
|
||||||
|
function SelectValue({ ...props }: React.ComponentProps<typeof SelectPrimitive.Value>) {
|
||||||
function SelectValue({
|
return <SelectPrimitive.Value data-slot="select-value" {...props}/>;
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof SelectPrimitive.Value>) {
|
|
||||||
return <SelectPrimitive.Value data-slot="select-value" {...props} />
|
|
||||||
}
|
}
|
||||||
|
function SelectTrigger({ className, size = "default", children, ...props }: React.ComponentProps<typeof SelectPrimitive.Trigger> & {
|
||||||
function SelectTrigger({
|
size?: "sm" | "default";
|
||||||
className,
|
|
||||||
size = "default",
|
|
||||||
children,
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof SelectPrimitive.Trigger> & {
|
|
||||||
size?: "sm" | "default"
|
|
||||||
}) {
|
}) {
|
||||||
return (
|
return (<SelectPrimitive.Trigger data-slot="select-trigger" data-size={size} className={cn("border-input data-placeholder:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-fit items-center justify-between gap-2 rounded-md border bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4", className)} {...props}>
|
||||||
<SelectPrimitive.Trigger
|
|
||||||
data-slot="select-trigger"
|
|
||||||
data-size={size}
|
|
||||||
className={cn(
|
|
||||||
"border-input data-placeholder:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-fit items-center justify-between gap-2 rounded-md border bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
{children}
|
{children}
|
||||||
<SelectPrimitive.Icon asChild>
|
<SelectPrimitive.Icon asChild>
|
||||||
<ChevronDownIcon className="size-4 opacity-50" />
|
<ChevronDownIcon className="size-4 opacity-50"/>
|
||||||
</SelectPrimitive.Icon>
|
</SelectPrimitive.Icon>
|
||||||
</SelectPrimitive.Trigger>
|
</SelectPrimitive.Trigger>);
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
function SelectContent({ className, children, position = "popper", align = "center", ...props }: React.ComponentProps<typeof SelectPrimitive.Content>) {
|
||||||
function SelectContent({
|
return (<SelectPrimitive.Portal>
|
||||||
className,
|
<SelectPrimitive.Content data-slot="select-content" className={cn("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-32 origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border shadow-md", position === "popper" &&
|
||||||
children,
|
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1", className)} position={position} align={align} {...props}>
|
||||||
position = "popper",
|
|
||||||
align = "center",
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof SelectPrimitive.Content>) {
|
|
||||||
return (
|
|
||||||
<SelectPrimitive.Portal>
|
|
||||||
<SelectPrimitive.Content
|
|
||||||
data-slot="select-content"
|
|
||||||
className={cn(
|
|
||||||
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-32 origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border shadow-md",
|
|
||||||
position === "popper" &&
|
|
||||||
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
position={position}
|
|
||||||
align={align}
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
<SelectScrollUpButton />
|
<SelectScrollUpButton />
|
||||||
<SelectPrimitive.Viewport
|
<SelectPrimitive.Viewport className={cn("p-1", position === "popper" &&
|
||||||
className={cn(
|
"h-(--radix-select-trigger-height) w-full min-w-(--radix-select-trigger-width) scroll-my-1")}>
|
||||||
"p-1",
|
|
||||||
position === "popper" &&
|
|
||||||
"h-(--radix-select-trigger-height) w-full min-w-(--radix-select-trigger-width) scroll-my-1"
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
{children}
|
{children}
|
||||||
</SelectPrimitive.Viewport>
|
</SelectPrimitive.Viewport>
|
||||||
<SelectScrollDownButton />
|
<SelectScrollDownButton />
|
||||||
</SelectPrimitive.Content>
|
</SelectPrimitive.Content>
|
||||||
</SelectPrimitive.Portal>
|
</SelectPrimitive.Portal>);
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
function SelectLabel({ className, ...props }: React.ComponentProps<typeof SelectPrimitive.Label>) {
|
||||||
function SelectLabel({
|
return (<SelectPrimitive.Label data-slot="select-label" className={cn("text-muted-foreground px-2 py-1.5 text-xs", className)} {...props}/>);
|
||||||
className,
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof SelectPrimitive.Label>) {
|
|
||||||
return (
|
|
||||||
<SelectPrimitive.Label
|
|
||||||
data-slot="select-label"
|
|
||||||
className={cn("text-muted-foreground px-2 py-1.5 text-xs", className)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
function SelectItem({ className, children, ...props }: React.ComponentProps<typeof SelectPrimitive.Item>) {
|
||||||
function SelectItem({
|
return (<SelectPrimitive.Item data-slot="select-item" className={cn("focus:bg-accent focus:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2", className)} {...props}>
|
||||||
className,
|
|
||||||
children,
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof SelectPrimitive.Item>) {
|
|
||||||
return (
|
|
||||||
<SelectPrimitive.Item
|
|
||||||
data-slot="select-item"
|
|
||||||
className={cn(
|
|
||||||
"focus:bg-accent focus:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
<span className="absolute right-2 flex size-3.5 items-center justify-center">
|
<span className="absolute right-2 flex size-3.5 items-center justify-center">
|
||||||
<SelectPrimitive.ItemIndicator>
|
<SelectPrimitive.ItemIndicator>
|
||||||
<CheckIcon className="size-4" />
|
<CheckIcon className="size-4"/>
|
||||||
</SelectPrimitive.ItemIndicator>
|
</SelectPrimitive.ItemIndicator>
|
||||||
</span>
|
</span>
|
||||||
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
|
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
|
||||||
</SelectPrimitive.Item>
|
</SelectPrimitive.Item>);
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
function SelectSeparator({ className, ...props }: React.ComponentProps<typeof SelectPrimitive.Separator>) {
|
||||||
function SelectSeparator({
|
return (<SelectPrimitive.Separator data-slot="select-separator" className={cn("bg-border pointer-events-none -mx-1 my-1 h-px", className)} {...props}/>);
|
||||||
className,
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof SelectPrimitive.Separator>) {
|
|
||||||
return (
|
|
||||||
<SelectPrimitive.Separator
|
|
||||||
data-slot="select-separator"
|
|
||||||
className={cn("bg-border pointer-events-none -mx-1 my-1 h-px", className)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
function SelectScrollUpButton({ className, ...props }: React.ComponentProps<typeof SelectPrimitive.ScrollUpButton>) {
|
||||||
function SelectScrollUpButton({
|
return (<SelectPrimitive.ScrollUpButton data-slot="select-scroll-up-button" className={cn("flex cursor-default items-center justify-center py-1", className)} {...props}>
|
||||||
className,
|
<ChevronUpIcon className="size-4"/>
|
||||||
...props
|
</SelectPrimitive.ScrollUpButton>);
|
||||||
}: React.ComponentProps<typeof SelectPrimitive.ScrollUpButton>) {
|
|
||||||
return (
|
|
||||||
<SelectPrimitive.ScrollUpButton
|
|
||||||
data-slot="select-scroll-up-button"
|
|
||||||
className={cn(
|
|
||||||
"flex cursor-default items-center justify-center py-1",
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
<ChevronUpIcon className="size-4" />
|
|
||||||
</SelectPrimitive.ScrollUpButton>
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
function SelectScrollDownButton({ className, ...props }: React.ComponentProps<typeof SelectPrimitive.ScrollDownButton>) {
|
||||||
function SelectScrollDownButton({
|
return (<SelectPrimitive.ScrollDownButton data-slot="select-scroll-down-button" className={cn("flex cursor-default items-center justify-center py-1", className)} {...props}>
|
||||||
className,
|
<ChevronDownIcon className="size-4"/>
|
||||||
...props
|
</SelectPrimitive.ScrollDownButton>);
|
||||||
}: React.ComponentProps<typeof SelectPrimitive.ScrollDownButton>) {
|
|
||||||
return (
|
|
||||||
<SelectPrimitive.ScrollDownButton
|
|
||||||
data-slot="select-scroll-down-button"
|
|
||||||
className={cn(
|
|
||||||
"flex cursor-default items-center justify-center py-1",
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
<ChevronDownIcon className="size-4" />
|
|
||||||
</SelectPrimitive.ScrollDownButton>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
export {
|
|
||||||
Select,
|
|
||||||
SelectContent,
|
|
||||||
SelectGroup,
|
|
||||||
SelectItem,
|
|
||||||
SelectLabel,
|
|
||||||
SelectScrollDownButton,
|
|
||||||
SelectScrollUpButton,
|
|
||||||
SelectSeparator,
|
|
||||||
SelectTrigger,
|
|
||||||
SelectValue,
|
|
||||||
}
|
}
|
||||||
|
export { Select, SelectContent, SelectGroup, SelectItem, SelectLabel, SelectScrollDownButton, SelectScrollUpButton, SelectSeparator, SelectTrigger, SelectValue, };
|
||||||
@@ -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 };
|
||||||
@@ -1,47 +1,27 @@
|
|||||||
import {
|
import { CircleCheckIcon, InfoIcon, Loader2Icon, OctagonXIcon, TriangleAlertIcon, } from "lucide-react";
|
||||||
CircleCheckIcon,
|
import { useTheme } from "next-themes";
|
||||||
InfoIcon,
|
import { Toaster as Sonner, type ToasterProps } from "sonner";
|
||||||
Loader2Icon,
|
|
||||||
OctagonXIcon,
|
|
||||||
TriangleAlertIcon,
|
|
||||||
} from "lucide-react"
|
|
||||||
import { useTheme } from "next-themes"
|
|
||||||
import { Toaster as Sonner, type ToasterProps } from "sonner"
|
|
||||||
|
|
||||||
const Toaster = ({ ...props }: ToasterProps) => {
|
const Toaster = ({ ...props }: ToasterProps) => {
|
||||||
const { theme = "system" } = useTheme()
|
const { theme = "system" } = useTheme();
|
||||||
|
return (<Sonner theme={theme as ToasterProps["theme"]} className="toaster group" icons={{
|
||||||
return (
|
success: <CircleCheckIcon className="size-4"/>,
|
||||||
<Sonner
|
info: <InfoIcon className="size-4"/>,
|
||||||
theme={theme as ToasterProps["theme"]}
|
warning: <TriangleAlertIcon className="size-4"/>,
|
||||||
className="toaster group"
|
error: <OctagonXIcon className="size-4"/>,
|
||||||
icons={{
|
loading: <Loader2Icon className="size-4 animate-spin"/>,
|
||||||
success: <CircleCheckIcon className="size-4" />,
|
}} toastOptions={{
|
||||||
info: <InfoIcon className="size-4" />,
|
classNames: {
|
||||||
warning: <TriangleAlertIcon className="size-4" />,
|
success: "border-green-500 bg-green-50 text-green-900 dark:bg-green-950 dark:text-green-100 [&>svg]:text-green-500",
|
||||||
error: <OctagonXIcon className="size-4" />,
|
error: "border-red-500 bg-red-50 text-red-900 dark:bg-red-950 dark:text-red-100 [&>svg]:text-red-500",
|
||||||
loading: <Loader2Icon className="size-4 animate-spin" />,
|
warning: "border-yellow-500 bg-yellow-50 text-yellow-900 dark:bg-yellow-950 dark:text-yellow-100 [&>svg]:text-yellow-500",
|
||||||
}}
|
info: "border-blue-500 bg-blue-50 text-blue-900 dark:bg-blue-950 dark:text-blue-100 [&>svg]:text-blue-500",
|
||||||
toastOptions={{
|
},
|
||||||
classNames: {
|
}} style={{
|
||||||
success: "border-green-500 bg-green-50 text-green-900 dark:bg-green-950 dark:text-green-100 [&>svg]:text-green-500",
|
"--normal-bg": "var(--popover)",
|
||||||
error: "border-red-500 bg-red-50 text-red-900 dark:bg-red-950 dark:text-red-100 [&>svg]:text-red-500",
|
"--normal-text": "var(--popover-foreground)",
|
||||||
warning: "border-yellow-500 bg-yellow-50 text-yellow-900 dark:bg-yellow-950 dark:text-yellow-100 [&>svg]:text-yellow-500",
|
"--normal-border": "var(--border)",
|
||||||
info: "border-blue-500 bg-blue-50 text-blue-900 dark:bg-blue-950 dark:text-blue-100 [&>svg]:text-blue-500",
|
"--border-radius": "var(--radius)",
|
||||||
},
|
left: "calc(56px + 1rem)",
|
||||||
}}
|
} as React.CSSProperties} {...props}/>);
|
||||||
style={
|
};
|
||||||
{
|
export { Toaster };
|
||||||
"--normal-bg": "var(--popover)",
|
|
||||||
"--normal-text": "var(--popover-foreground)",
|
|
||||||
"--normal-border": "var(--border)",
|
|
||||||
"--border-radius": "var(--radius)",
|
|
||||||
left: "calc(56px + 1rem)",
|
|
||||||
} as React.CSSProperties
|
|
||||||
}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
export { Toaster }
|
|
||||||
@@ -1,15 +1,6 @@
|
|||||||
import { Loader2 } from "lucide-react"
|
import { Loader2 } from "lucide-react";
|
||||||
import { cn } from "@/lib/utils"
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
function Spinner({ className, ...props }: React.ComponentProps<"svg">) {
|
function Spinner({ className, ...props }: React.ComponentProps<"svg">) {
|
||||||
return (
|
return (<Loader2 role="status" aria-label="Loading" className={cn("size-4 animate-spin", className)} {...props}/>);
|
||||||
<Loader2
|
|
||||||
role="status"
|
|
||||||
aria-label="Loading"
|
|
||||||
className={cn("size-4 animate-spin", className)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
export { Spinner };
|
||||||
export { Spinner }
|
|
||||||
@@ -1,31 +1,10 @@
|
|||||||
"use client"
|
"use client";
|
||||||
|
import * as React from "react";
|
||||||
import * as React from "react"
|
import * as SwitchPrimitive from "@radix-ui/react-switch";
|
||||||
import * as SwitchPrimitive from "@radix-ui/react-switch"
|
import { cn } from "@/lib/utils";
|
||||||
|
function Switch({ className, ...props }: React.ComponentProps<typeof SwitchPrimitive.Root>) {
|
||||||
import { cn } from "@/lib/utils"
|
return (<SwitchPrimitive.Root data-slot="switch" className={cn("peer data-[state=checked]:bg-primary data-[state=unchecked]:bg-input focus-visible:border-ring focus-visible:ring-ring/50 inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border border-transparent shadow-xs transition-all outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50", className)} {...props}>
|
||||||
|
<SwitchPrimitive.Thumb data-slot="switch-thumb" className={cn("pointer-events-none block size-4 rounded-full shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0 data-[state=checked]:bg-primary-foreground data-[state=unchecked]:bg-background")}/>
|
||||||
function Switch({
|
</SwitchPrimitive.Root>);
|
||||||
className,
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof SwitchPrimitive.Root>) {
|
|
||||||
return (
|
|
||||||
<SwitchPrimitive.Root
|
|
||||||
data-slot="switch"
|
|
||||||
className={cn(
|
|
||||||
"peer data-[state=checked]:bg-primary data-[state=unchecked]:bg-input focus-visible:border-ring focus-visible:ring-ring/50 inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border border-transparent shadow-xs transition-all outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
<SwitchPrimitive.Thumb
|
|
||||||
data-slot="switch-thumb"
|
|
||||||
className={cn(
|
|
||||||
"pointer-events-none block size-4 rounded-full shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0 data-[state=checked]:bg-primary-foreground data-[state=unchecked]:bg-background"
|
|
||||||
)}
|
|
||||||
/>
|
|
||||||
</SwitchPrimitive.Root>
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
export { Switch };
|
||||||
export { Switch }
|
|
||||||
@@ -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 };
|
||||||
@@ -1,61 +1,24 @@
|
|||||||
"use client"
|
"use client";
|
||||||
|
import * as React from "react";
|
||||||
import * as React from "react"
|
import * as TooltipPrimitive from "@radix-ui/react-tooltip";
|
||||||
import * as TooltipPrimitive from "@radix-ui/react-tooltip"
|
import { cn } from "@/lib/utils";
|
||||||
|
function TooltipProvider({ delayDuration = 0, ...props }: React.ComponentProps<typeof TooltipPrimitive.Provider>) {
|
||||||
import { cn } from "@/lib/utils"
|
return (<TooltipPrimitive.Provider data-slot="tooltip-provider" delayDuration={delayDuration} {...props}/>);
|
||||||
|
|
||||||
function TooltipProvider({
|
|
||||||
delayDuration = 0,
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof TooltipPrimitive.Provider>) {
|
|
||||||
return (
|
|
||||||
<TooltipPrimitive.Provider
|
|
||||||
data-slot="tooltip-provider"
|
|
||||||
delayDuration={delayDuration}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
function Tooltip({ ...props }: React.ComponentProps<typeof TooltipPrimitive.Root>) {
|
||||||
function Tooltip({
|
return (<TooltipProvider>
|
||||||
...props
|
<TooltipPrimitive.Root data-slot="tooltip" {...props}/>
|
||||||
}: React.ComponentProps<typeof TooltipPrimitive.Root>) {
|
</TooltipProvider>);
|
||||||
return (
|
|
||||||
<TooltipProvider>
|
|
||||||
<TooltipPrimitive.Root data-slot="tooltip" {...props} />
|
|
||||||
</TooltipProvider>
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
function TooltipTrigger({ ...props }: React.ComponentProps<typeof TooltipPrimitive.Trigger>) {
|
||||||
function TooltipTrigger({
|
return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props}/>;
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof TooltipPrimitive.Trigger>) {
|
|
||||||
return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props} />
|
|
||||||
}
|
}
|
||||||
|
function TooltipContent({ className, sideOffset = 0, children, ...props }: React.ComponentProps<typeof TooltipPrimitive.Content>) {
|
||||||
function TooltipContent({
|
return (<TooltipPrimitive.Portal>
|
||||||
className,
|
<TooltipPrimitive.Content data-slot="tooltip-content" sideOffset={sideOffset} className={cn("bg-foreground text-background animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance", className)} {...props}>
|
||||||
sideOffset = 0,
|
|
||||||
children,
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof TooltipPrimitive.Content>) {
|
|
||||||
return (
|
|
||||||
<TooltipPrimitive.Portal>
|
|
||||||
<TooltipPrimitive.Content
|
|
||||||
data-slot="tooltip-content"
|
|
||||||
sideOffset={sideOffset}
|
|
||||||
className={cn(
|
|
||||||
"bg-foreground text-background animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
{children}
|
{children}
|
||||||
<TooltipPrimitive.Arrow className="bg-foreground fill-foreground z-50 size-2.5 translate-y-[calc(-50%-2px)] rotate-45 rounded-[2px]" />
|
<TooltipPrimitive.Arrow className="bg-foreground fill-foreground z-50 size-2.5 translate-y-[calc(-50%-2px)] rotate-45 rounded-[2px]"/>
|
||||||
</TooltipPrimitive.Content>
|
</TooltipPrimitive.Content>
|
||||||
</TooltipPrimitive.Portal>
|
</TooltipPrimitive.Portal>);
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider };
|
||||||
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }
|
|
||||||
+77
-44
@@ -26,19 +26,6 @@
|
|||||||
--color-border: var(--border);
|
--color-border: var(--border);
|
||||||
--color-input: var(--input);
|
--color-input: var(--input);
|
||||||
--color-ring: var(--ring);
|
--color-ring: var(--ring);
|
||||||
--color-chart-1: var(--chart-1);
|
|
||||||
--color-chart-2: var(--chart-2);
|
|
||||||
--color-chart-3: var(--chart-3);
|
|
||||||
--color-chart-4: var(--chart-4);
|
|
||||||
--color-chart-5: var(--chart-5);
|
|
||||||
--color-sidebar: var(--sidebar);
|
|
||||||
--color-sidebar-foreground: var(--sidebar-foreground);
|
|
||||||
--color-sidebar-primary: var(--sidebar-primary);
|
|
||||||
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
|
|
||||||
--color-sidebar-accent: var(--sidebar-accent);
|
|
||||||
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
|
|
||||||
--color-sidebar-border: var(--sidebar-border);
|
|
||||||
--color-sidebar-ring: var(--sidebar-ring);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
:root {
|
:root {
|
||||||
@@ -61,19 +48,6 @@
|
|||||||
--border: oklch(0.922 0 0);
|
--border: oklch(0.922 0 0);
|
||||||
--input: oklch(0.922 0 0);
|
--input: oklch(0.922 0 0);
|
||||||
--ring: oklch(0.708 0 0);
|
--ring: oklch(0.708 0 0);
|
||||||
--chart-1: oklch(0.646 0.222 41.116);
|
|
||||||
--chart-2: oklch(0.6 0.118 184.704);
|
|
||||||
--chart-3: oklch(0.398 0.07 227.392);
|
|
||||||
--chart-4: oklch(0.828 0.189 84.429);
|
|
||||||
--chart-5: oklch(0.769 0.188 70.08);
|
|
||||||
--sidebar: oklch(0.985 0 0);
|
|
||||||
--sidebar-foreground: oklch(0.145 0 0);
|
|
||||||
--sidebar-primary: oklch(0.205 0 0);
|
|
||||||
--sidebar-primary-foreground: oklch(0.985 0 0);
|
|
||||||
--sidebar-accent: oklch(0.97 0 0);
|
|
||||||
--sidebar-accent-foreground: oklch(0.205 0 0);
|
|
||||||
--sidebar-border: oklch(0.922 0 0);
|
|
||||||
--sidebar-ring: oklch(0.708 0 0);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.dark {
|
.dark {
|
||||||
@@ -95,22 +69,16 @@
|
|||||||
--border: oklch(1 0 0 / 10%);
|
--border: oklch(1 0 0 / 10%);
|
||||||
--input: oklch(1 0 0 / 15%);
|
--input: oklch(1 0 0 / 15%);
|
||||||
--ring: oklch(0.556 0 0);
|
--ring: oklch(0.556 0 0);
|
||||||
--chart-1: oklch(0.488 0.243 264.376);
|
|
||||||
--chart-2: oklch(0.696 0.17 162.48);
|
|
||||||
--chart-3: oklch(0.769 0.188 70.08);
|
|
||||||
--chart-4: oklch(0.627 0.265 303.9);
|
|
||||||
--chart-5: oklch(0.645 0.246 16.439);
|
|
||||||
--sidebar: oklch(0.205 0 0);
|
|
||||||
--sidebar-foreground: oklch(0.985 0 0);
|
|
||||||
--sidebar-primary: oklch(0.488 0.243 264.376);
|
|
||||||
--sidebar-primary-foreground: oklch(0.985 0 0);
|
|
||||||
--sidebar-accent: oklch(0.269 0 0);
|
|
||||||
--sidebar-accent-foreground: oklch(0.985 0 0);
|
|
||||||
--sidebar-border: oklch(1 0 0 / 10%);
|
|
||||||
--sidebar-ring: oklch(0.556 0 0);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@layer base {
|
@layer base {
|
||||||
|
html,
|
||||||
|
body,
|
||||||
|
#root {
|
||||||
|
height: 100%;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
* {
|
* {
|
||||||
@apply border-border outline-ring/50;
|
@apply border-border outline-ring/50;
|
||||||
}
|
}
|
||||||
@@ -164,6 +132,54 @@
|
|||||||
@apply text-blue-600;
|
@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 mode toast styling */
|
||||||
.dark [data-sonner-toast][data-type="success"] {
|
.dark [data-sonner-toast][data-type="success"] {
|
||||||
@apply bg-green-950 border-green-800 text-green-100;
|
@apply bg-green-950 border-green-800 text-green-100;
|
||||||
@@ -225,6 +241,28 @@
|
|||||||
scrollbar-color: var(--primary) var(--secondary);
|
scrollbar-color: var(--primary) var(--secondary);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
input::-ms-reveal,
|
||||||
|
input::-ms-clear {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
input[type="number"] {
|
||||||
|
color-scheme: light;
|
||||||
|
}
|
||||||
|
|
||||||
|
.dark input[type="number"] {
|
||||||
|
color-scheme: dark;
|
||||||
|
}
|
||||||
|
|
||||||
|
input[type="number"]::-webkit-outer-spin-button,
|
||||||
|
input[type="number"]::-webkit-inner-spin-button {
|
||||||
|
margin: 0;
|
||||||
|
background: transparent;
|
||||||
|
border: 0;
|
||||||
|
box-shadow: none;
|
||||||
|
opacity: 1;
|
||||||
|
}
|
||||||
|
|
||||||
/* Custom scrollbar class untuk komponen tertentu */
|
/* Custom scrollbar class untuk komponen tertentu */
|
||||||
.custom-scrollbar::-webkit-scrollbar {
|
.custom-scrollbar::-webkit-scrollbar {
|
||||||
width: 6px;
|
width: 6px;
|
||||||
@@ -244,8 +282,3 @@
|
|||||||
.custom-scrollbar::-webkit-scrollbar-thumb:hover {
|
.custom-scrollbar::-webkit-scrollbar-thumb:hover {
|
||||||
filter: brightness(1.2);
|
filter: brightness(1.2);
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Date input styling for dark mode */
|
|
||||||
.dark input[type="date"]::-webkit-calendar-picker-indicator {
|
|
||||||
filter: invert(1);
|
|
||||||
}
|
|
||||||
+70
-97
@@ -1,106 +1,79 @@
|
|||||||
// Audio utility for toast notifications using Web Audio API
|
|
||||||
|
|
||||||
class AudioManager {
|
class AudioManager {
|
||||||
private audioContext: AudioContext | null = null;
|
private audioContext: AudioContext | null = null;
|
||||||
|
private getAudioContext(): AudioContext {
|
||||||
private getAudioContext(): AudioContext {
|
if (!this.audioContext) {
|
||||||
if (!this.audioContext) {
|
const AudioContextConstructor = window.AudioContext || (window as Window & {
|
||||||
this.audioContext = new (window.AudioContext || (window as any).webkitAudioContext)();
|
webkitAudioContext?: typeof AudioContext;
|
||||||
|
}).webkitAudioContext;
|
||||||
|
if (!AudioContextConstructor) {
|
||||||
|
throw new Error("Web Audio API is not supported in this browser");
|
||||||
|
}
|
||||||
|
const context = new AudioContextConstructor();
|
||||||
|
this.audioContext = context;
|
||||||
|
return context;
|
||||||
|
}
|
||||||
|
return this.audioContext;
|
||||||
}
|
}
|
||||||
return this.audioContext;
|
private playTone(frequency: number, duration: number, type: OscillatorType = 'sine', volume: number = 0.3) {
|
||||||
}
|
try {
|
||||||
|
const ctx = this.getAudioContext();
|
||||||
// Generate a simple tone using oscillator
|
const oscillator = ctx.createOscillator();
|
||||||
private playTone(frequency: number, duration: number, type: OscillatorType = 'sine', volume: number = 0.3) {
|
const gainNode = ctx.createGain();
|
||||||
try {
|
oscillator.connect(gainNode);
|
||||||
const ctx = this.getAudioContext();
|
gainNode.connect(ctx.destination);
|
||||||
const oscillator = ctx.createOscillator();
|
oscillator.frequency.value = frequency;
|
||||||
const gainNode = ctx.createGain();
|
oscillator.type = type;
|
||||||
|
gainNode.gain.setValueAtTime(volume, ctx.currentTime);
|
||||||
oscillator.connect(gainNode);
|
gainNode.gain.exponentialRampToValueAtTime(0.01, ctx.currentTime + duration);
|
||||||
gainNode.connect(ctx.destination);
|
oscillator.start(ctx.currentTime);
|
||||||
|
oscillator.stop(ctx.currentTime + duration);
|
||||||
oscillator.frequency.value = frequency;
|
}
|
||||||
oscillator.type = type;
|
catch (error) {
|
||||||
|
console.error('Error playing audio:', error);
|
||||||
gainNode.gain.setValueAtTime(volume, ctx.currentTime);
|
}
|
||||||
gainNode.gain.exponentialRampToValueAtTime(0.01, ctx.currentTime + duration);
|
|
||||||
|
|
||||||
oscillator.start(ctx.currentTime);
|
|
||||||
oscillator.stop(ctx.currentTime + duration);
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error playing audio:', error);
|
|
||||||
}
|
}
|
||||||
}
|
playSuccess() {
|
||||||
|
const ctx = this.getAudioContext();
|
||||||
// Success sound - pleasant ascending tones
|
const now = ctx.currentTime;
|
||||||
playSuccess() {
|
this.playToneAt(523.25, 0.08, 'sine', 0.2, now);
|
||||||
const ctx = this.getAudioContext();
|
this.playToneAt(659.25, 0.08, 'sine', 0.2, now + 0.08);
|
||||||
const now = ctx.currentTime;
|
this.playToneAt(783.99, 0.15, 'sine', 0.25, now + 0.16);
|
||||||
|
}
|
||||||
// First tone
|
playError() {
|
||||||
this.playToneAt(523.25, 0.08, 'sine', 0.2, now); // C5
|
const ctx = this.getAudioContext();
|
||||||
// Second tone
|
const now = ctx.currentTime;
|
||||||
this.playToneAt(659.25, 0.08, 'sine', 0.2, now + 0.08); // E5
|
this.playToneAt(392.00, 0.1, 'square', 0.15, now);
|
||||||
// Third tone
|
this.playToneAt(329.63, 0.2, 'square', 0.2, now + 0.1);
|
||||||
this.playToneAt(783.99, 0.15, 'sine', 0.25, now + 0.16); // G5
|
}
|
||||||
}
|
playWarning() {
|
||||||
|
const ctx = this.getAudioContext();
|
||||||
// Error sound - descending tones
|
const now = ctx.currentTime;
|
||||||
playError() {
|
this.playToneAt(440.00, 0.1, 'triangle', 0.2, now);
|
||||||
const ctx = this.getAudioContext();
|
this.playToneAt(493.88, 0.1, 'triangle', 0.2, now + 0.12);
|
||||||
const now = ctx.currentTime;
|
}
|
||||||
|
playInfo() {
|
||||||
// First tone
|
this.playTone(523.25, 0.15, 'sine', 0.15);
|
||||||
this.playToneAt(392.00, 0.1, 'square', 0.15, now); // G4
|
}
|
||||||
// Second tone
|
private playToneAt(frequency: number, duration: number, type: OscillatorType, volume: number, startTime: number) {
|
||||||
this.playToneAt(329.63, 0.2, 'square', 0.2, now + 0.1); // E4
|
try {
|
||||||
}
|
const ctx = this.getAudioContext();
|
||||||
|
const oscillator = ctx.createOscillator();
|
||||||
// Warning sound - alternating tones
|
const gainNode = ctx.createGain();
|
||||||
playWarning() {
|
oscillator.connect(gainNode);
|
||||||
const ctx = this.getAudioContext();
|
gainNode.connect(ctx.destination);
|
||||||
const now = ctx.currentTime;
|
oscillator.frequency.value = frequency;
|
||||||
|
oscillator.type = type;
|
||||||
// First tone
|
gainNode.gain.setValueAtTime(volume, startTime);
|
||||||
this.playToneAt(440.00, 0.1, 'triangle', 0.2, now); // A4
|
gainNode.gain.exponentialRampToValueAtTime(0.01, startTime + duration);
|
||||||
// Second tone
|
oscillator.start(startTime);
|
||||||
this.playToneAt(493.88, 0.1, 'triangle', 0.2, now + 0.12); // B4
|
oscillator.stop(startTime + duration);
|
||||||
}
|
}
|
||||||
|
catch (error) {
|
||||||
// Info sound - single soft tone
|
console.error('Error playing audio:', error);
|
||||||
playInfo() {
|
}
|
||||||
this.playTone(523.25, 0.15, 'sine', 0.15); // C5
|
|
||||||
}
|
|
||||||
|
|
||||||
// Helper method to play tone at specific time
|
|
||||||
private playToneAt(frequency: number, duration: number, type: OscillatorType, volume: number, startTime: number) {
|
|
||||||
try {
|
|
||||||
const ctx = this.getAudioContext();
|
|
||||||
const oscillator = ctx.createOscillator();
|
|
||||||
const gainNode = ctx.createGain();
|
|
||||||
|
|
||||||
oscillator.connect(gainNode);
|
|
||||||
gainNode.connect(ctx.destination);
|
|
||||||
|
|
||||||
oscillator.frequency.value = frequency;
|
|
||||||
oscillator.type = type;
|
|
||||||
|
|
||||||
gainNode.gain.setValueAtTime(volume, startTime);
|
|
||||||
gainNode.gain.exponentialRampToValueAtTime(0.01, startTime + duration);
|
|
||||||
|
|
||||||
oscillator.start(startTime);
|
|
||||||
oscillator.stop(startTime + duration);
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error playing audio:', error);
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Export singleton instance
|
|
||||||
export const audioManager = new AudioManager();
|
export const audioManager = new AudioManager();
|
||||||
|
|
||||||
// Helper functions for easy use
|
|
||||||
export const playSuccessSound = () => audioManager.playSuccess();
|
export const playSuccessSound = () => audioManager.playSuccess();
|
||||||
export const playErrorSound = () => audioManager.playError();
|
export const playErrorSound = () => audioManager.playError();
|
||||||
export const playWarningSound = () => audioManager.playWarning();
|
export const playWarningSound = () => audioManager.playWarning();
|
||||||
|
|||||||
+165
-159
@@ -1,179 +1,185 @@
|
|||||||
/**
|
import type { TimelineEntry } from "@/types/api";
|
||||||
* Fetch State Manager
|
|
||||||
* Manages resumable fetch state for large accounts
|
|
||||||
*/
|
|
||||||
|
|
||||||
import type { TwitterResponse, TimelineEntry, AccountInfo } from "@/types/api";
|
|
||||||
|
|
||||||
const FETCH_STATE_KEY = "twitter_fetch_state";
|
const FETCH_STATE_KEY = "twitter_fetch_state";
|
||||||
|
const CURSOR_STATE_KEY = "twitter_cursor_state";
|
||||||
export interface FetchState {
|
export interface FetchState {
|
||||||
username: string;
|
username: string;
|
||||||
cursor: string;
|
cursor: string;
|
||||||
timeline: TimelineEntry[];
|
totalFetched: number;
|
||||||
accountInfo: AccountInfo | null;
|
completed: boolean;
|
||||||
totalFetched: number;
|
lastUpdated: number;
|
||||||
completed: boolean;
|
mediaType: string;
|
||||||
lastUpdated: number;
|
retweets: boolean;
|
||||||
authToken: string; // Encrypted/hashed for security
|
timelineType: string;
|
||||||
mediaType: string;
|
|
||||||
retweets: boolean;
|
|
||||||
timelineType: string;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
function normalizeFetchState(state: FetchState | null | undefined): FetchState | null {
|
||||||
* Save current fetch state for resume capability
|
if (!state) {
|
||||||
*/
|
return null;
|
||||||
export function saveFetchState(state: Partial<FetchState> & { username: string }): void {
|
}
|
||||||
try {
|
|
||||||
const existing = getFetchState(state.username);
|
return {
|
||||||
const updated: FetchState = {
|
...state,
|
||||||
username: state.username,
|
cursor: state.cursor || "",
|
||||||
cursor: state.cursor || "",
|
totalFetched: state.totalFetched ?? 0,
|
||||||
timeline: state.timeline || existing?.timeline || [],
|
mediaType: state.mediaType || "all",
|
||||||
accountInfo: state.accountInfo || existing?.accountInfo || null,
|
retweets: state.retweets ?? false,
|
||||||
totalFetched: state.totalFetched ?? existing?.totalFetched ?? 0,
|
timelineType: state.timelineType || "timeline",
|
||||||
completed: state.completed ?? false,
|
|
||||||
lastUpdated: Date.now(),
|
|
||||||
authToken: state.authToken || existing?.authToken || "",
|
|
||||||
mediaType: state.mediaType || existing?.mediaType || "all",
|
|
||||||
retweets: state.retweets ?? existing?.retweets ?? false,
|
|
||||||
timelineType: state.timelineType || existing?.timelineType || "timeline",
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// Get all states
|
|
||||||
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 saveFetchState(state: Partial<FetchState> & {
|
||||||
* Get fetch state for a specific username
|
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 {
|
export function getFetchState(username: string): FetchState | null {
|
||||||
try {
|
try {
|
||||||
const allStates = getAllFetchStates();
|
const allStates = getAllFetchStates();
|
||||||
return allStates[username.toLowerCase()] || null;
|
return normalizeFetchState(allStates[username.toLowerCase()]);
|
||||||
} catch (error) {
|
}
|
||||||
console.error("Failed to get fetch state:", error);
|
catch (error) {
|
||||||
return null;
|
console.error("Failed to get fetch state:", error);
|
||||||
}
|
return null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Get all fetch states
|
|
||||||
*/
|
|
||||||
export function getAllFetchStates(): Record<string, FetchState> {
|
export function getAllFetchStates(): Record<string, FetchState> {
|
||||||
try {
|
try {
|
||||||
const stored = localStorage.getItem(FETCH_STATE_KEY);
|
const stored = localStorage.getItem(FETCH_STATE_KEY);
|
||||||
if (stored) {
|
if (stored) {
|
||||||
return JSON.parse(stored);
|
const parsed = JSON.parse(stored);
|
||||||
|
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
|
||||||
|
const normalized: Record<string, FetchState> = {};
|
||||||
|
for (const [key, value] of Object.entries(parsed as Record<string, FetchState | null | undefined>)) {
|
||||||
|
const state = normalizeFetchState(value);
|
||||||
|
if (state) {
|
||||||
|
normalized[key] = state;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return normalized;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} catch (error) {
|
catch (error) {
|
||||||
console.error("Failed to parse fetch states:", error);
|
console.error("Failed to parse fetch states:", error);
|
||||||
}
|
}
|
||||||
return {};
|
return {};
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Check if there's a resumable fetch for username
|
|
||||||
*/
|
|
||||||
export function hasResumableFetch(username: string): boolean {
|
export function hasResumableFetch(username: string): boolean {
|
||||||
const state = getFetchState(username);
|
const state = getFetchState(username);
|
||||||
if (!state) return false;
|
if (!state)
|
||||||
|
return false;
|
||||||
// Has cursor and not completed
|
return !!state.cursor && !state.completed && state.totalFetched > 0;
|
||||||
return !!state.cursor && !state.completed && state.timeline.length > 0;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Get resumable fetch info for display
|
|
||||||
*/
|
|
||||||
export function getResumableInfo(username: string): {
|
export function getResumableInfo(username: string): {
|
||||||
canResume: boolean;
|
canResume: boolean;
|
||||||
mediaCount: number;
|
mediaCount: number;
|
||||||
lastUpdated: Date | null;
|
lastUpdated: Date | null;
|
||||||
} {
|
} {
|
||||||
const state = getFetchState(username);
|
const state = getFetchState(username);
|
||||||
if (!state || state.completed || !state.cursor) {
|
if (!state || state.completed || !state.cursor) {
|
||||||
return { canResume: false, mediaCount: 0, lastUpdated: null };
|
return { canResume: false, mediaCount: 0, lastUpdated: null };
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
canResume: true,
|
|
||||||
mediaCount: state.timeline.length,
|
|
||||||
lastUpdated: new Date(state.lastUpdated),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Clear fetch state for username
|
|
||||||
*/
|
|
||||||
export function clearFetchState(username: string): void {
|
|
||||||
try {
|
|
||||||
const allStates = getAllFetchStates();
|
|
||||||
delete allStates[username.toLowerCase()];
|
|
||||||
localStorage.setItem(FETCH_STATE_KEY, JSON.stringify(allStates));
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Failed to clear fetch state:", error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Clear all incomplete fetch states (cleanup)
|
|
||||||
*/
|
|
||||||
export function clearAllIncompleteFetchStates(): void {
|
|
||||||
try {
|
|
||||||
const allStates = getAllFetchStates();
|
|
||||||
const completed: Record<string, FetchState> = {};
|
|
||||||
|
|
||||||
for (const [key, state] of Object.entries(allStates)) {
|
|
||||||
if (state.completed) {
|
|
||||||
completed[key] = state;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
return {
|
||||||
localStorage.setItem(FETCH_STATE_KEY, JSON.stringify(completed));
|
canResume: true,
|
||||||
} catch (error) {
|
mediaCount: state.totalFetched,
|
||||||
console.error("Failed to clear fetch states:", error);
|
lastUpdated: new Date(state.lastUpdated),
|
||||||
}
|
};
|
||||||
}
|
}
|
||||||
|
export function clearFetchState(username: string): void {
|
||||||
/**
|
try {
|
||||||
* Convert fetch state to TwitterResponse format
|
const allStates = getAllFetchStates();
|
||||||
*/
|
delete allStates[username.toLowerCase()];
|
||||||
export function stateToResponse(state: FetchState): TwitterResponse | null {
|
localStorage.setItem(FETCH_STATE_KEY, JSON.stringify(allStates));
|
||||||
if (!state.accountInfo) return null;
|
}
|
||||||
|
catch (error) {
|
||||||
return {
|
console.error("Failed to clear fetch state:", error);
|
||||||
account_info: state.accountInfo,
|
}
|
||||||
total_urls: state.timeline.length,
|
|
||||||
timeline: state.timeline,
|
|
||||||
metadata: {
|
|
||||||
new_entries: state.timeline.length,
|
|
||||||
page: 0,
|
|
||||||
batch_size: 0,
|
|
||||||
has_more: !state.completed,
|
|
||||||
cursor: state.cursor,
|
|
||||||
completed: state.completed,
|
|
||||||
},
|
|
||||||
cursor: state.cursor,
|
|
||||||
completed: state.completed,
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
export function clearAllIncompleteFetchStates(): void {
|
||||||
/**
|
try {
|
||||||
* Merge new timeline entries with existing (deduplicate by tweet_id)
|
const allStates = getAllFetchStates();
|
||||||
*/
|
const completed: Record<string, FetchState> = {};
|
||||||
export function mergeTimelines(
|
for (const [key, state] of Object.entries(allStates)) {
|
||||||
existing: TimelineEntry[],
|
if (state.completed) {
|
||||||
newEntries: TimelineEntry[]
|
completed[key] = state;
|
||||||
): TimelineEntry[] {
|
}
|
||||||
const seenIds = new Set(existing.map((e) => e.tweet_id));
|
}
|
||||||
const unique = newEntries.filter((e) => !seenIds.has(e.tweet_id));
|
localStorage.setItem(FETCH_STATE_KEY, JSON.stringify(completed));
|
||||||
return [...existing, ...unique];
|
}
|
||||||
|
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];
|
||||||
}
|
}
|
||||||
+46
-59
@@ -1,66 +1,53 @@
|
|||||||
export type LogLevel = "info" | "success" | "warning" | "error" | "debug";
|
export type LogLevel = "info" | "success" | "warning" | "error" | "debug";
|
||||||
|
|
||||||
export interface LogEntry {
|
export interface LogEntry {
|
||||||
timestamp: Date;
|
timestamp: Date;
|
||||||
level: LogLevel;
|
level: LogLevel;
|
||||||
message: string;
|
message: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
class Logger {
|
class Logger {
|
||||||
private logs: LogEntry[] = [];
|
private logs: LogEntry[] = [];
|
||||||
private maxLogs = 500;
|
private maxLogs = 500;
|
||||||
private listeners: Set<() => void> = new Set();
|
private listeners: Set<() => void> = new Set();
|
||||||
|
private addLog(level: LogLevel, message: string) {
|
||||||
private addLog(level: LogLevel, message: string) {
|
const entry: LogEntry = {
|
||||||
const entry: LogEntry = {
|
timestamp: new Date(),
|
||||||
timestamp: new Date(),
|
level,
|
||||||
level,
|
message: message.toLowerCase(),
|
||||||
message: message.toLowerCase(),
|
};
|
||||||
};
|
this.logs.push(entry);
|
||||||
this.logs.push(entry);
|
if (this.logs.length > this.maxLogs) {
|
||||||
if (this.logs.length > this.maxLogs) {
|
this.logs.shift();
|
||||||
this.logs.shift();
|
}
|
||||||
|
this.notifyListeners();
|
||||||
|
}
|
||||||
|
info(message: string) {
|
||||||
|
this.addLog("info", message);
|
||||||
|
}
|
||||||
|
success(message: string) {
|
||||||
|
this.addLog("success", message);
|
||||||
|
}
|
||||||
|
warning(message: string) {
|
||||||
|
this.addLog("warning", message);
|
||||||
|
}
|
||||||
|
error(message: string) {
|
||||||
|
this.addLog("error", message);
|
||||||
|
}
|
||||||
|
debug(message: string) {
|
||||||
|
this.addLog("debug", message);
|
||||||
|
}
|
||||||
|
getLogs(): LogEntry[] {
|
||||||
|
return [...this.logs];
|
||||||
|
}
|
||||||
|
clear() {
|
||||||
|
this.logs = [];
|
||||||
|
this.notifyListeners();
|
||||||
|
}
|
||||||
|
subscribe(listener: () => void) {
|
||||||
|
this.listeners.add(listener);
|
||||||
|
return () => this.listeners.delete(listener);
|
||||||
|
}
|
||||||
|
private notifyListeners() {
|
||||||
|
this.listeners.forEach((listener) => listener());
|
||||||
}
|
}
|
||||||
this.notifyListeners();
|
|
||||||
}
|
|
||||||
|
|
||||||
info(message: string) {
|
|
||||||
this.addLog("info", message);
|
|
||||||
}
|
|
||||||
|
|
||||||
success(message: string) {
|
|
||||||
this.addLog("success", message);
|
|
||||||
}
|
|
||||||
|
|
||||||
warning(message: string) {
|
|
||||||
this.addLog("warning", message);
|
|
||||||
}
|
|
||||||
|
|
||||||
error(message: string) {
|
|
||||||
this.addLog("error", message);
|
|
||||||
}
|
|
||||||
|
|
||||||
debug(message: string) {
|
|
||||||
this.addLog("debug", message);
|
|
||||||
}
|
|
||||||
|
|
||||||
getLogs(): LogEntry[] {
|
|
||||||
return [...this.logs];
|
|
||||||
}
|
|
||||||
|
|
||||||
clear() {
|
|
||||||
this.logs = [];
|
|
||||||
this.notifyListeners();
|
|
||||||
}
|
|
||||||
|
|
||||||
subscribe(listener: () => void) {
|
|
||||||
this.listeners.add(listener);
|
|
||||||
return () => this.listeners.delete(listener);
|
|
||||||
}
|
|
||||||
|
|
||||||
private notifyListeners() {
|
|
||||||
this.listeners.forEach((listener) => listener());
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export const logger = new Logger();
|
export const logger = new Logger();
|
||||||
@@ -1,59 +1,57 @@
|
|||||||
/**
|
|
||||||
* Format a date to relative time string with max 2 units
|
|
||||||
* e.g., "23 hours 32 minutes ago", "1 day 14 hours ago"
|
|
||||||
*/
|
|
||||||
export function formatRelativeTime(date: Date | string | number): string {
|
export function formatRelativeTime(date: Date | string | number): string {
|
||||||
const now = new Date();
|
const now = new Date();
|
||||||
const target = new Date(date);
|
const target = new Date(date);
|
||||||
const diffMs = now.getTime() - target.getTime();
|
const diffMs = now.getTime() - target.getTime();
|
||||||
|
if (diffMs < 0)
|
||||||
if (diffMs < 0) return "just now";
|
return "just now";
|
||||||
|
const seconds = Math.floor(diffMs / 1000);
|
||||||
const seconds = Math.floor(diffMs / 1000);
|
const minutes = Math.floor(seconds / 60);
|
||||||
const minutes = Math.floor(seconds / 60);
|
const hours = Math.floor(minutes / 60);
|
||||||
const hours = Math.floor(minutes / 60);
|
const days = Math.floor(hours / 24);
|
||||||
const days = Math.floor(hours / 24);
|
const weeks = Math.floor(days / 7);
|
||||||
const weeks = Math.floor(days / 7);
|
const months = Math.floor(days / 30);
|
||||||
const months = Math.floor(days / 30);
|
const years = Math.floor(days / 365);
|
||||||
const years = Math.floor(days / 365);
|
const parts: string[] = [];
|
||||||
|
if (years > 0) {
|
||||||
const parts: string[] = [];
|
parts.push(`${years} ${years === 1 ? "year" : "years"}`);
|
||||||
|
const remainingMonths = Math.floor((days % 365) / 30);
|
||||||
if (years > 0) {
|
if (remainingMonths > 0) {
|
||||||
parts.push(`${years} ${years === 1 ? "year" : "years"}`);
|
parts.push(`${remainingMonths} ${remainingMonths === 1 ? "month" : "months"}`);
|
||||||
const remainingMonths = Math.floor((days % 365) / 30);
|
}
|
||||||
if (remainingMonths > 0) {
|
|
||||||
parts.push(`${remainingMonths} ${remainingMonths === 1 ? "month" : "months"}`);
|
|
||||||
}
|
}
|
||||||
} else if (months > 0) {
|
else if (months > 0) {
|
||||||
parts.push(`${months} ${months === 1 ? "month" : "months"}`);
|
parts.push(`${months} ${months === 1 ? "month" : "months"}`);
|
||||||
const remainingDays = days % 30;
|
const remainingDays = days % 30;
|
||||||
if (remainingDays > 0) {
|
if (remainingDays > 0) {
|
||||||
parts.push(`${remainingDays} ${remainingDays === 1 ? "day" : "days"}`);
|
parts.push(`${remainingDays} ${remainingDays === 1 ? "day" : "days"}`);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} else if (weeks > 0) {
|
else if (weeks > 0) {
|
||||||
parts.push(`${weeks} ${weeks === 1 ? "week" : "weeks"}`);
|
parts.push(`${weeks} ${weeks === 1 ? "week" : "weeks"}`);
|
||||||
const remainingDays = days % 7;
|
const remainingDays = days % 7;
|
||||||
if (remainingDays > 0) {
|
if (remainingDays > 0) {
|
||||||
parts.push(`${remainingDays} ${remainingDays === 1 ? "day" : "days"}`);
|
parts.push(`${remainingDays} ${remainingDays === 1 ? "day" : "days"}`);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} else if (days > 0) {
|
else if (days > 0) {
|
||||||
parts.push(`${days} ${days === 1 ? "day" : "days"}`);
|
parts.push(`${days} ${days === 1 ? "day" : "days"}`);
|
||||||
const remainingHours = hours % 24;
|
const remainingHours = hours % 24;
|
||||||
if (remainingHours > 0) {
|
if (remainingHours > 0) {
|
||||||
parts.push(`${remainingHours} ${remainingHours === 1 ? "hour" : "hours"}`);
|
parts.push(`${remainingHours} ${remainingHours === 1 ? "hour" : "hours"}`);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} else if (hours > 0) {
|
else if (hours > 0) {
|
||||||
parts.push(`${hours} ${hours === 1 ? "hour" : "hours"}`);
|
parts.push(`${hours} ${hours === 1 ? "hour" : "hours"}`);
|
||||||
const remainingMinutes = minutes % 60;
|
const remainingMinutes = minutes % 60;
|
||||||
if (remainingMinutes > 0) {
|
if (remainingMinutes > 0) {
|
||||||
parts.push(`${remainingMinutes} ${remainingMinutes === 1 ? "minute" : "minutes"}`);
|
parts.push(`${remainingMinutes} ${remainingMinutes === 1 ? "minute" : "minutes"}`);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} else if (minutes > 0) {
|
else if (minutes > 0) {
|
||||||
parts.push(`${minutes} ${minutes === 1 ? "minute" : "minutes"}`);
|
parts.push(`${minutes} ${minutes === 1 ? "minute" : "minutes"}`);
|
||||||
} else {
|
}
|
||||||
return "just now";
|
else {
|
||||||
}
|
return "just now";
|
||||||
|
}
|
||||||
return "Released " + parts.slice(0, 2).join(" ") + " ago";
|
return "Released " + parts.slice(0, 2).join(" ") + " ago";
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
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);
|
||||||
|
}
|
||||||
+402
-82
@@ -1,120 +1,440 @@
|
|||||||
import { GetDefaults } from "../../wailsjs/go/main/App";
|
import { GetDefaults } from "../../wailsjs/go/main/App";
|
||||||
|
|
||||||
export type FontFamily = "google-sans" | "inter" | "poppins" | "roboto" | "dm-sans" | "plus-jakarta-sans" | "manrope" | "space-grotesk";
|
export type BuiltInFontFamily =
|
||||||
|
| "google-sans"
|
||||||
|
| "inter"
|
||||||
|
| "poppins"
|
||||||
|
| "roboto"
|
||||||
|
| "dm-sans"
|
||||||
|
| "plus-jakarta-sans"
|
||||||
|
| "manrope"
|
||||||
|
| "space-grotesk"
|
||||||
|
| "noto-sans"
|
||||||
|
| "nunito-sans"
|
||||||
|
| "figtree"
|
||||||
|
| "raleway"
|
||||||
|
| "public-sans"
|
||||||
|
| "outfit"
|
||||||
|
| "jetbrains-mono"
|
||||||
|
| "geist-sans"
|
||||||
|
| "bricolage-grotesque";
|
||||||
|
|
||||||
|
export type CustomFontFamily = `custom-${string}`;
|
||||||
|
export type FontFamily = BuiltInFontFamily | CustomFontFamily;
|
||||||
|
|
||||||
|
export interface CustomFontOption {
|
||||||
|
value: CustomFontFamily;
|
||||||
|
label: string;
|
||||||
|
fontFamily: string;
|
||||||
|
url: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FontOption {
|
||||||
|
value: FontFamily;
|
||||||
|
label: string;
|
||||||
|
fontFamily: string;
|
||||||
|
url?: string;
|
||||||
|
}
|
||||||
|
|
||||||
export type GifQuality = "fast" | "better";
|
export type GifQuality = "fast" | "better";
|
||||||
export type GifResolution = "original" | "high" | "medium" | "low";
|
export type GifResolution = "original" | "high" | "medium" | "low";
|
||||||
|
export type FetchMode = "single" | "batch";
|
||||||
|
export type MediaType = "all" | "image" | "video" | "gif" | "text";
|
||||||
|
|
||||||
export interface Settings {
|
export interface Settings {
|
||||||
downloadPath: string;
|
downloadPath: string;
|
||||||
theme: string;
|
theme: string;
|
||||||
themeMode: "auto" | "light" | "dark";
|
themeMode: "auto" | "light" | "dark";
|
||||||
fontFamily: FontFamily;
|
fontFamily: FontFamily;
|
||||||
sfxEnabled: boolean;
|
customFonts: CustomFontOption[];
|
||||||
gifQuality: GifQuality;
|
sfxEnabled: boolean;
|
||||||
gifResolution: GifResolution;
|
gifQuality: GifQuality;
|
||||||
|
gifResolution: GifResolution;
|
||||||
|
proxy: string;
|
||||||
|
fetchTimeout: number;
|
||||||
|
fetchMode: FetchMode;
|
||||||
|
mediaType: MediaType;
|
||||||
|
includeRetweets: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const DEFAULT_SETTINGS: Settings = {
|
export const DEFAULT_SETTINGS: Settings = {
|
||||||
downloadPath: "",
|
downloadPath: "",
|
||||||
theme: "yellow",
|
theme: "yellow",
|
||||||
themeMode: "auto",
|
themeMode: "auto",
|
||||||
fontFamily: "google-sans",
|
fontFamily: "google-sans",
|
||||||
sfxEnabled: true,
|
customFonts: [],
|
||||||
gifQuality: "fast",
|
sfxEnabled: true,
|
||||||
gifResolution: "high",
|
gifQuality: "fast",
|
||||||
|
gifResolution: "original",
|
||||||
|
proxy: "",
|
||||||
|
fetchTimeout: 60,
|
||||||
|
fetchMode: "batch",
|
||||||
|
mediaType: "all",
|
||||||
|
includeRetweets: false,
|
||||||
};
|
};
|
||||||
|
|
||||||
export const FONT_OPTIONS: { value: FontFamily; label: string; fontFamily: string }[] = [
|
export const FONT_OPTIONS: FontOption[] = [
|
||||||
{ value: "google-sans", label: "Google Sans Flex", fontFamily: '"Google Sans Flex", system-ui, sans-serif' },
|
{
|
||||||
{ value: "inter", label: "Inter", fontFamily: '"Inter", system-ui, sans-serif' },
|
value: "bricolage-grotesque",
|
||||||
{ value: "poppins", label: "Poppins", fontFamily: '"Poppins", system-ui, sans-serif' },
|
label: "Bricolage Grotesque",
|
||||||
{ value: "roboto", label: "Roboto", fontFamily: '"Roboto", system-ui, sans-serif' },
|
fontFamily: '"Bricolage Grotesque", system-ui, sans-serif',
|
||||||
{ value: "dm-sans", label: "DM Sans", fontFamily: '"DM Sans", system-ui, sans-serif' },
|
},
|
||||||
{ value: "plus-jakarta-sans", label: "Plus Jakarta Sans", fontFamily: '"Plus Jakarta Sans", system-ui, sans-serif' },
|
{
|
||||||
{ value: "manrope", label: "Manrope", fontFamily: '"Manrope", system-ui, sans-serif' },
|
value: "dm-sans",
|
||||||
{ value: "space-grotesk", label: "Space Grotesk", fontFamily: '"Space Grotesk", system-ui, sans-serif' },
|
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',
|
||||||
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
export function applyFont(fontFamily: FontFamily): void {
|
const BUILT_IN_FONT_VALUES = new Set(FONT_OPTIONS.map((font) => font.value));
|
||||||
const font = FONT_OPTIONS.find(f => f.value === fontFamily);
|
const SETTINGS_KEY = "twitter-media-downloader-settings";
|
||||||
if (font) {
|
const GOOGLE_FONT_LINK_ID_PREFIX = "twitter-media-custom-font-";
|
||||||
document.documentElement.style.setProperty('--font-sans', font.fontFamily);
|
const GOOGLE_FONTS_CSS_HOST = "fonts.googleapis.com";
|
||||||
document.body.style.fontFamily = font.fontFamily;
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
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> {
|
async function fetchDefaultPath(): Promise<string> {
|
||||||
try {
|
try {
|
||||||
const data = await GetDefaults();
|
const data = await GetDefaults();
|
||||||
return data.downloadPath || "";
|
return data.downloadPath || "";
|
||||||
} catch (error) {
|
}
|
||||||
console.error("Failed to fetch default path:", error);
|
catch (error) {
|
||||||
return "";
|
console.error("Failed to fetch default path:", error);
|
||||||
}
|
return "";
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const SETTINGS_KEY = "twitter-media-downloader-settings";
|
function toNormalizedSettings(settings: Partial<Settings>): Settings {
|
||||||
|
const customFonts = normalizeCustomFonts(settings.customFonts);
|
||||||
|
return {
|
||||||
|
...DEFAULT_SETTINGS,
|
||||||
|
...settings,
|
||||||
|
customFonts,
|
||||||
|
fontFamily: normalizeFontFamily(settings.fontFamily, customFonts),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
export function getSettings(): Settings {
|
export function getSettings(): Settings {
|
||||||
try {
|
try {
|
||||||
const stored = localStorage.getItem(SETTINGS_KEY);
|
const stored = localStorage.getItem(SETTINGS_KEY);
|
||||||
if (stored) {
|
if (stored) {
|
||||||
const parsed = JSON.parse(stored);
|
return toNormalizedSettings(JSON.parse(stored) as Partial<Settings>);
|
||||||
return { ...DEFAULT_SETTINGS, ...parsed };
|
}
|
||||||
}
|
}
|
||||||
} catch (error) {
|
catch (error) {
|
||||||
console.error("Failed to load settings:", error);
|
console.error("Failed to load settings:", error);
|
||||||
}
|
}
|
||||||
return DEFAULT_SETTINGS;
|
return DEFAULT_SETTINGS;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getSettingsWithDefaults(): Promise<Settings> {
|
export async function getSettingsWithDefaults(): Promise<Settings> {
|
||||||
const settings = getSettings();
|
const settings = getSettings();
|
||||||
|
if (!settings.downloadPath) {
|
||||||
// If downloadPath is empty, fetch from backend
|
settings.downloadPath = await fetchDefaultPath();
|
||||||
if (!settings.downloadPath) {
|
}
|
||||||
settings.downloadPath = await fetchDefaultPath();
|
return toNormalizedSettings(settings);
|
||||||
}
|
|
||||||
|
|
||||||
return settings;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function saveSettings(settings: Settings): void {
|
export function saveSettings(settings: Settings): void {
|
||||||
try {
|
try {
|
||||||
localStorage.setItem(SETTINGS_KEY, JSON.stringify(settings));
|
const normalizedSettings = toNormalizedSettings(settings);
|
||||||
} catch (error) {
|
localStorage.setItem(SETTINGS_KEY, JSON.stringify(normalizedSettings));
|
||||||
console.error("Failed to save settings:", error);
|
}
|
||||||
}
|
catch (error) {
|
||||||
|
console.error("Failed to save settings:", error);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function updateSettings(partial: Partial<Settings>): Settings {
|
export function updateSettings(partial: Partial<Settings>): Settings {
|
||||||
const current = getSettings();
|
const current = getSettings();
|
||||||
const updated = { ...current, ...partial };
|
const updated = toNormalizedSettings({ ...current, ...partial });
|
||||||
saveSettings(updated);
|
saveSettings(updated);
|
||||||
return updated;
|
return updated;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function resetToDefaultSettings(): Promise<Settings> {
|
export async function resetToDefaultSettings(): Promise<Settings> {
|
||||||
const defaultPath = await fetchDefaultPath();
|
const defaultPath = await fetchDefaultPath();
|
||||||
const defaultSettings = {
|
const defaultSettings = toNormalizedSettings({
|
||||||
...DEFAULT_SETTINGS,
|
...DEFAULT_SETTINGS,
|
||||||
downloadPath: defaultPath,
|
downloadPath: defaultPath,
|
||||||
};
|
});
|
||||||
saveSettings(defaultSettings);
|
saveSettings(defaultSettings);
|
||||||
return defaultSettings;
|
return defaultSettings;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function loadCustomFonts(): Promise<CustomFontOption[]> {
|
||||||
|
return normalizeCustomFonts(getSettings().customFonts);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function saveCustomFonts(customFonts: CustomFontOption[]): Promise<CustomFontOption[]> {
|
||||||
|
const normalizedFonts = normalizeCustomFonts(customFonts);
|
||||||
|
const settings = getSettings();
|
||||||
|
saveSettings({
|
||||||
|
...settings,
|
||||||
|
customFonts: normalizedFonts,
|
||||||
|
fontFamily: normalizeFontFamily(settings.fontFamily, normalizedFonts),
|
||||||
|
});
|
||||||
|
return normalizedFonts;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function applyThemeMode(mode: "auto" | "light" | "dark"): void {
|
export function applyThemeMode(mode: "auto" | "light" | "dark"): void {
|
||||||
if (mode === "auto") {
|
if (mode === "auto") {
|
||||||
const prefersDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
|
const prefersDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
|
||||||
if (prefersDark) {
|
if (prefersDark) {
|
||||||
document.documentElement.classList.add("dark");
|
document.documentElement.classList.add("dark");
|
||||||
} else {
|
}
|
||||||
document.documentElement.classList.remove("dark");
|
else {
|
||||||
|
document.documentElement.classList.remove("dark");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (mode === "dark") {
|
||||||
|
document.documentElement.classList.add("dark");
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
document.documentElement.classList.remove("dark");
|
||||||
}
|
}
|
||||||
} else if (mode === "dark") {
|
|
||||||
document.documentElement.classList.add("dark");
|
|
||||||
} else {
|
|
||||||
document.documentElement.classList.remove("dark");
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
+270
-465
@@ -1,470 +1,275 @@
|
|||||||
export interface Theme {
|
export interface Theme {
|
||||||
name: string;
|
name: string;
|
||||||
label: string;
|
label: string;
|
||||||
cssVars: {
|
cssVars: {
|
||||||
light: Record<string, string>;
|
light: Record<string, string>;
|
||||||
dark: Record<string, string>;
|
dark: Record<string, string>;
|
||||||
};
|
};
|
||||||
|
}
|
||||||
|
const baseLightColors: Record<string, string> = {
|
||||||
|
background: "oklch(1 0 0)",
|
||||||
|
foreground: "oklch(0.145 0 0)",
|
||||||
|
card: "oklch(1 0 0)",
|
||||||
|
"card-foreground": "oklch(0.145 0 0)",
|
||||||
|
popover: "oklch(1 0 0)",
|
||||||
|
"popover-foreground": "oklch(0.145 0 0)",
|
||||||
|
secondary: "oklch(0.967 0.001 286.375)",
|
||||||
|
"secondary-foreground": "oklch(0.21 0.006 285.885)",
|
||||||
|
muted: "oklch(0.97 0 0)",
|
||||||
|
"muted-foreground": "oklch(0.556 0 0)",
|
||||||
|
accent: "oklch(0.97 0 0)",
|
||||||
|
"accent-foreground": "oklch(0.205 0 0)",
|
||||||
|
destructive: "oklch(0.58 0.22 27)",
|
||||||
|
border: "oklch(0.922 0 0)",
|
||||||
|
input: "oklch(0.922 0 0)",
|
||||||
|
ring: "oklch(0.708 0 0)",
|
||||||
|
};
|
||||||
|
const baseDarkColors: Record<string, string> = {
|
||||||
|
background: "oklch(0.145 0 0)",
|
||||||
|
foreground: "oklch(0.985 0 0)",
|
||||||
|
card: "oklch(0.205 0 0)",
|
||||||
|
"card-foreground": "oklch(0.985 0 0)",
|
||||||
|
popover: "oklch(0.205 0 0)",
|
||||||
|
"popover-foreground": "oklch(0.985 0 0)",
|
||||||
|
secondary: "oklch(0.274 0.006 286.033)",
|
||||||
|
"secondary-foreground": "oklch(0.985 0 0)",
|
||||||
|
muted: "oklch(0.269 0 0)",
|
||||||
|
"muted-foreground": "oklch(0.708 0 0)",
|
||||||
|
accent: "oklch(0.371 0 0)",
|
||||||
|
"accent-foreground": "oklch(0.985 0 0)",
|
||||||
|
destructive: "oklch(0.704 0.191 22.216)",
|
||||||
|
border: "oklch(1 0 0 / 10%)",
|
||||||
|
input: "oklch(1 0 0 / 15%)",
|
||||||
|
ring: "oklch(0.556 0 0)",
|
||||||
|
};
|
||||||
|
interface PrimaryColors {
|
||||||
|
light: {
|
||||||
|
primary: string;
|
||||||
|
"primary-foreground": string;
|
||||||
|
};
|
||||||
|
dark: {
|
||||||
|
primary: string;
|
||||||
|
"primary-foreground": string;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const primaryColors: Record<string, PrimaryColors> = {
|
||||||
|
amber: {
|
||||||
|
light: {
|
||||||
|
primary: "oklch(0.67 0.16 58)",
|
||||||
|
"primary-foreground": "oklch(0.99 0.02 95)",
|
||||||
|
},
|
||||||
|
dark: {
|
||||||
|
primary: "oklch(0.77 0.16 70)",
|
||||||
|
"primary-foreground": "oklch(0.28 0.07 46)",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
blue: {
|
||||||
|
light: {
|
||||||
|
primary: "oklch(0.488 0.243 264.376)",
|
||||||
|
"primary-foreground": "oklch(0.97 0.014 254.604)",
|
||||||
|
},
|
||||||
|
dark: {
|
||||||
|
primary: "oklch(0.42 0.18 266)",
|
||||||
|
"primary-foreground": "oklch(0.97 0.014 254.604)",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
cyan: {
|
||||||
|
light: {
|
||||||
|
primary: "oklch(0.61 0.11 222)",
|
||||||
|
"primary-foreground": "oklch(0.98 0.02 201)",
|
||||||
|
},
|
||||||
|
dark: {
|
||||||
|
primary: "oklch(0.71 0.13 215)",
|
||||||
|
"primary-foreground": "oklch(0.30 0.05 230)",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
emerald: {
|
||||||
|
light: {
|
||||||
|
primary: "oklch(0.60 0.13 163)",
|
||||||
|
"primary-foreground": "oklch(0.98 0.02 166)",
|
||||||
|
},
|
||||||
|
dark: {
|
||||||
|
primary: "oklch(0.70 0.15 162)",
|
||||||
|
"primary-foreground": "oklch(0.26 0.05 173)",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
fuchsia: {
|
||||||
|
light: {
|
||||||
|
primary: "oklch(0.59 0.26 323)",
|
||||||
|
"primary-foreground": "oklch(0.98 0.02 320)",
|
||||||
|
},
|
||||||
|
dark: {
|
||||||
|
primary: "oklch(0.67 0.26 322)",
|
||||||
|
"primary-foreground": "oklch(0.98 0.02 320)",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
green: {
|
||||||
|
light: {
|
||||||
|
primary: "oklch(0.648 0.2 131.684)",
|
||||||
|
"primary-foreground": "oklch(0.986 0.031 120.757)",
|
||||||
|
},
|
||||||
|
dark: {
|
||||||
|
primary: "oklch(0.648 0.2 131.684)",
|
||||||
|
"primary-foreground": "oklch(0.986 0.031 120.757)",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
indigo: {
|
||||||
|
light: {
|
||||||
|
primary: "oklch(0.51 0.23 277)",
|
||||||
|
"primary-foreground": "oklch(0.96 0.02 272)",
|
||||||
|
},
|
||||||
|
dark: {
|
||||||
|
primary: "oklch(0.59 0.20 277)",
|
||||||
|
"primary-foreground": "oklch(0.96 0.02 272)",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
lime: {
|
||||||
|
light: {
|
||||||
|
primary: "oklch(0.65 0.18 132)",
|
||||||
|
"primary-foreground": "oklch(0.99 0.03 121)",
|
||||||
|
},
|
||||||
|
dark: {
|
||||||
|
primary: "oklch(0.77 0.20 131)",
|
||||||
|
"primary-foreground": "oklch(0.27 0.07 132)",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
neutral: {
|
||||||
|
light: {
|
||||||
|
primary: "oklch(0.205 0 0)",
|
||||||
|
"primary-foreground": "oklch(0.985 0 0)",
|
||||||
|
},
|
||||||
|
dark: {
|
||||||
|
primary: "oklch(0.922 0 0)",
|
||||||
|
"primary-foreground": "oklch(0.205 0 0)",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
orange: {
|
||||||
|
light: {
|
||||||
|
primary: "oklch(0.646 0.222 41.116)",
|
||||||
|
"primary-foreground": "oklch(0.98 0.016 73.684)",
|
||||||
|
},
|
||||||
|
dark: {
|
||||||
|
primary: "oklch(0.705 0.213 47.604)",
|
||||||
|
"primary-foreground": "oklch(0.98 0.016 73.684)",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
pink: {
|
||||||
|
light: {
|
||||||
|
primary: "oklch(0.59 0.22 1)",
|
||||||
|
"primary-foreground": "oklch(0.97 0.01 343)",
|
||||||
|
},
|
||||||
|
dark: {
|
||||||
|
primary: "oklch(0.66 0.21 354)",
|
||||||
|
"primary-foreground": "oklch(0.97 0.01 343)",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
purple: {
|
||||||
|
light: {
|
||||||
|
primary: "oklch(0.56 0.25 302)",
|
||||||
|
"primary-foreground": "oklch(0.98 0.01 308)",
|
||||||
|
},
|
||||||
|
dark: {
|
||||||
|
primary: "oklch(0.63 0.23 304)",
|
||||||
|
"primary-foreground": "oklch(0.98 0.01 308)",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
red: {
|
||||||
|
light: {
|
||||||
|
primary: "oklch(0.577 0.245 27.325)",
|
||||||
|
"primary-foreground": "oklch(0.971 0.013 17.38)",
|
||||||
|
},
|
||||||
|
dark: {
|
||||||
|
primary: "oklch(0.637 0.237 25.331)",
|
||||||
|
"primary-foreground": "oklch(0.971 0.013 17.38)",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
rose: {
|
||||||
|
light: {
|
||||||
|
primary: "oklch(0.586 0.253 17.585)",
|
||||||
|
"primary-foreground": "oklch(0.969 0.015 12.422)",
|
||||||
|
},
|
||||||
|
dark: {
|
||||||
|
primary: "oklch(0.645 0.246 16.439)",
|
||||||
|
"primary-foreground": "oklch(0.969 0.015 12.422)",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
sky: {
|
||||||
|
light: {
|
||||||
|
primary: "oklch(0.59 0.14 242)",
|
||||||
|
"primary-foreground": "oklch(0.98 0.01 237)",
|
||||||
|
},
|
||||||
|
dark: {
|
||||||
|
primary: "oklch(0.68 0.15 237)",
|
||||||
|
"primary-foreground": "oklch(0.29 0.06 243)",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
teal: {
|
||||||
|
light: {
|
||||||
|
primary: "oklch(0.60 0.10 185)",
|
||||||
|
"primary-foreground": "oklch(0.98 0.01 181)",
|
||||||
|
},
|
||||||
|
dark: {
|
||||||
|
primary: "oklch(0.70 0.12 183)",
|
||||||
|
"primary-foreground": "oklch(0.28 0.04 193)",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
violet: {
|
||||||
|
light: {
|
||||||
|
primary: "oklch(0.541 0.281 293.009)",
|
||||||
|
"primary-foreground": "oklch(0.969 0.016 293.756)",
|
||||||
|
},
|
||||||
|
dark: {
|
||||||
|
primary: "oklch(0.606 0.25 292.717)",
|
||||||
|
"primary-foreground": "oklch(0.969 0.016 293.756)",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
yellow: {
|
||||||
|
light: {
|
||||||
|
primary: "oklch(0.852 0.199 91.936)",
|
||||||
|
"primary-foreground": "oklch(0.421 0.095 57.708)",
|
||||||
|
},
|
||||||
|
dark: {
|
||||||
|
primary: "oklch(0.795 0.184 86.047)",
|
||||||
|
"primary-foreground": "oklch(0.421 0.095 57.708)",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
function createTheme(name: string, label: string, primary: PrimaryColors): Theme {
|
||||||
|
return {
|
||||||
|
name,
|
||||||
|
label,
|
||||||
|
cssVars: {
|
||||||
|
light: { ...baseLightColors, ...primary.light },
|
||||||
|
dark: { ...baseDarkColors, ...primary.dark },
|
||||||
|
},
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export const themes: Theme[] = [
|
export const themes: Theme[] = [
|
||||||
{
|
createTheme("amber", "Amber", primaryColors.amber),
|
||||||
name: "neutral",
|
createTheme("blue", "Blue", primaryColors.blue),
|
||||||
label: "Default",
|
createTheme("cyan", "Cyan", primaryColors.cyan),
|
||||||
cssVars: {
|
createTheme("emerald", "Emerald", primaryColors.emerald),
|
||||||
light: {
|
createTheme("fuchsia", "Fuchsia", primaryColors.fuchsia),
|
||||||
background: "oklch(1 0 0)",
|
createTheme("green", "Green", primaryColors.green),
|
||||||
foreground: "oklch(0.145 0 0)",
|
createTheme("indigo", "Indigo", primaryColors.indigo),
|
||||||
card: "oklch(1 0 0)",
|
createTheme("lime", "Lime", primaryColors.lime),
|
||||||
"card-foreground": "oklch(0.145 0 0)",
|
createTheme("neutral", "Neutral", primaryColors.neutral),
|
||||||
popover: "oklch(1 0 0)",
|
createTheme("orange", "Orange", primaryColors.orange),
|
||||||
"popover-foreground": "oklch(0.145 0 0)",
|
createTheme("pink", "Pink", primaryColors.pink),
|
||||||
primary: "oklch(0.205 0 0)",
|
createTheme("purple", "Purple", primaryColors.purple),
|
||||||
"primary-foreground": "oklch(0.985 0 0)",
|
createTheme("red", "Red", primaryColors.red),
|
||||||
secondary: "oklch(0.97 0 0)",
|
createTheme("rose", "Rose", primaryColors.rose),
|
||||||
"secondary-foreground": "oklch(0.205 0 0)",
|
createTheme("sky", "Sky", primaryColors.sky),
|
||||||
muted: "oklch(0.97 0 0)",
|
createTheme("teal", "Teal", primaryColors.teal),
|
||||||
"muted-foreground": "oklch(0.556 0 0)",
|
createTheme("violet", "Violet", primaryColors.violet),
|
||||||
accent: "oklch(0.97 0 0)",
|
createTheme("yellow", "Yellow", primaryColors.yellow),
|
||||||
"accent-foreground": "oklch(0.205 0 0)",
|
].sort((a, b) => a.name.localeCompare(b.name));
|
||||||
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)",
|
|
||||||
"chart-1": "oklch(0.646 0.222 41.116)",
|
|
||||||
"chart-2": "oklch(0.6 0.118 184.704)",
|
|
||||||
"chart-3": "oklch(0.398 0.07 227.392)",
|
|
||||||
"chart-4": "oklch(0.828 0.189 84.429)",
|
|
||||||
"chart-5": "oklch(0.769 0.188 70.08)",
|
|
||||||
},
|
|
||||||
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)",
|
|
||||||
"chart-1": "oklch(0.488 0.243 264.376)",
|
|
||||||
"chart-2": "oklch(0.696 0.17 162.48)",
|
|
||||||
"chart-3": "oklch(0.769 0.188 70.08)",
|
|
||||||
"chart-4": "oklch(0.627 0.265 303.9)",
|
|
||||||
"chart-5": "oklch(0.645 0.246 16.439)",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "blue",
|
|
||||||
label: "Blue",
|
|
||||||
cssVars: {
|
|
||||||
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.488 0.243 264.376)",
|
|
||||||
"primary-foreground": "oklch(0.97 0.014 254.604)",
|
|
||||||
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.708 0 0)",
|
|
||||||
"chart-1": "oklch(0.809 0.105 251.813)",
|
|
||||||
"chart-2": "oklch(0.623 0.214 259.815)",
|
|
||||||
"chart-3": "oklch(0.546 0.245 262.881)",
|
|
||||||
"chart-4": "oklch(0.488 0.243 264.376)",
|
|
||||||
"chart-5": "oklch(0.424 0.199 265.638)",
|
|
||||||
},
|
|
||||||
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.488 0.243 264.376)",
|
|
||||||
"primary-foreground": "oklch(0.97 0.014 254.604)",
|
|
||||||
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.556 0 0)",
|
|
||||||
"chart-1": "oklch(0.809 0.105 251.813)",
|
|
||||||
"chart-2": "oklch(0.623 0.214 259.815)",
|
|
||||||
"chart-3": "oklch(0.546 0.245 262.881)",
|
|
||||||
"chart-4": "oklch(0.488 0.243 264.376)",
|
|
||||||
"chart-5": "oklch(0.424 0.199 265.638)",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "green",
|
|
||||||
label: "Green",
|
|
||||||
cssVars: {
|
|
||||||
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.648 0.2 131.684)",
|
|
||||||
"primary-foreground": "oklch(0.986 0.031 120.757)",
|
|
||||||
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.841 0.238 128.85)",
|
|
||||||
"chart-1": "oklch(0.871 0.15 154.449)",
|
|
||||||
"chart-2": "oklch(0.723 0.219 149.579)",
|
|
||||||
"chart-3": "oklch(0.627 0.194 149.214)",
|
|
||||||
"chart-4": "oklch(0.527 0.154 150.069)",
|
|
||||||
"chart-5": "oklch(0.448 0.119 151.328)",
|
|
||||||
},
|
|
||||||
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.648 0.2 131.684)",
|
|
||||||
"primary-foreground": "oklch(0.986 0.031 120.757)",
|
|
||||||
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.405 0.101 131.063)",
|
|
||||||
"chart-1": "oklch(0.871 0.15 154.449)",
|
|
||||||
"chart-2": "oklch(0.723 0.219 149.579)",
|
|
||||||
"chart-3": "oklch(0.627 0.194 149.214)",
|
|
||||||
"chart-4": "oklch(0.527 0.154 150.069)",
|
|
||||||
"chart-5": "oklch(0.448 0.119 151.328)",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "orange",
|
|
||||||
label: "Orange",
|
|
||||||
cssVars: {
|
|
||||||
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.646 0.222 41.116)",
|
|
||||||
"primary-foreground": "oklch(0.98 0.016 73.684)",
|
|
||||||
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.75 0.183 55.934)",
|
|
||||||
"chart-1": "oklch(0.837 0.128 66.29)",
|
|
||||||
"chart-2": "oklch(0.705 0.213 47.604)",
|
|
||||||
"chart-3": "oklch(0.646 0.222 41.116)",
|
|
||||||
"chart-4": "oklch(0.553 0.195 38.402)",
|
|
||||||
"chart-5": "oklch(0.47 0.157 37.304)",
|
|
||||||
},
|
|
||||||
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.705 0.213 47.604)",
|
|
||||||
"primary-foreground": "oklch(0.98 0.016 73.684)",
|
|
||||||
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.408 0.123 38.172)",
|
|
||||||
"chart-1": "oklch(0.837 0.128 66.29)",
|
|
||||||
"chart-2": "oklch(0.705 0.213 47.604)",
|
|
||||||
"chart-3": "oklch(0.646 0.222 41.116)",
|
|
||||||
"chart-4": "oklch(0.553 0.195 38.402)",
|
|
||||||
"chart-5": "oklch(0.47 0.157 37.304)",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "red",
|
|
||||||
label: "Red",
|
|
||||||
cssVars: {
|
|
||||||
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.577 0.245 27.325)",
|
|
||||||
"primary-foreground": "oklch(0.971 0.013 17.38)",
|
|
||||||
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.704 0.191 22.216)",
|
|
||||||
"chart-1": "oklch(0.808 0.114 19.571)",
|
|
||||||
"chart-2": "oklch(0.637 0.237 25.331)",
|
|
||||||
"chart-3": "oklch(0.577 0.245 27.325)",
|
|
||||||
"chart-4": "oklch(0.505 0.213 27.518)",
|
|
||||||
"chart-5": "oklch(0.444 0.177 26.899)",
|
|
||||||
},
|
|
||||||
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.637 0.237 25.331)",
|
|
||||||
"primary-foreground": "oklch(0.971 0.013 17.38)",
|
|
||||||
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.396 0.141 25.723)",
|
|
||||||
"chart-1": "oklch(0.808 0.114 19.571)",
|
|
||||||
"chart-2": "oklch(0.637 0.237 25.331)",
|
|
||||||
"chart-3": "oklch(0.577 0.245 27.325)",
|
|
||||||
"chart-4": "oklch(0.505 0.213 27.518)",
|
|
||||||
"chart-5": "oklch(0.444 0.177 26.899)",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "rose",
|
|
||||||
label: "Rose",
|
|
||||||
cssVars: {
|
|
||||||
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.586 0.253 17.585)",
|
|
||||||
"primary-foreground": "oklch(0.969 0.015 12.422)",
|
|
||||||
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.712 0.194 13.428)",
|
|
||||||
"chart-1": "oklch(0.81 0.117 11.638)",
|
|
||||||
"chart-2": "oklch(0.645 0.246 16.439)",
|
|
||||||
"chart-3": "oklch(0.586 0.253 17.585)",
|
|
||||||
"chart-4": "oklch(0.514 0.222 16.935)",
|
|
||||||
"chart-5": "oklch(0.455 0.188 13.697)",
|
|
||||||
},
|
|
||||||
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.645 0.246 16.439)",
|
|
||||||
"primary-foreground": "oklch(0.969 0.015 12.422)",
|
|
||||||
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.41 0.159 10.272)",
|
|
||||||
"chart-1": "oklch(0.81 0.117 11.638)",
|
|
||||||
"chart-2": "oklch(0.645 0.246 16.439)",
|
|
||||||
"chart-3": "oklch(0.586 0.253 17.585)",
|
|
||||||
"chart-4": "oklch(0.514 0.222 16.935)",
|
|
||||||
"chart-5": "oklch(0.455 0.188 13.697)",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "violet",
|
|
||||||
label: "Violet",
|
|
||||||
cssVars: {
|
|
||||||
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.541 0.281 293.009)",
|
|
||||||
"primary-foreground": "oklch(0.969 0.016 293.756)",
|
|
||||||
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.702 0.183 293.541)",
|
|
||||||
"chart-1": "oklch(0.811 0.111 293.571)",
|
|
||||||
"chart-2": "oklch(0.606 0.25 292.717)",
|
|
||||||
"chart-3": "oklch(0.541 0.281 293.009)",
|
|
||||||
"chart-4": "oklch(0.491 0.27 292.581)",
|
|
||||||
"chart-5": "oklch(0.432 0.232 292.759)",
|
|
||||||
},
|
|
||||||
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.606 0.25 292.717)",
|
|
||||||
"primary-foreground": "oklch(0.969 0.016 293.756)",
|
|
||||||
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.38 0.189 293.745)",
|
|
||||||
"chart-1": "oklch(0.811 0.111 293.571)",
|
|
||||||
"chart-2": "oklch(0.606 0.25 292.717)",
|
|
||||||
"chart-3": "oklch(0.541 0.281 293.009)",
|
|
||||||
"chart-4": "oklch(0.491 0.27 292.581)",
|
|
||||||
"chart-5": "oklch(0.432 0.232 292.759)",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "yellow",
|
|
||||||
label: "Yellow",
|
|
||||||
cssVars: {
|
|
||||||
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.852 0.199 91.936)",
|
|
||||||
"primary-foreground": "oklch(0.421 0.095 57.708)",
|
|
||||||
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.852 0.199 91.936)",
|
|
||||||
"chart-1": "oklch(0.905 0.182 98.111)",
|
|
||||||
"chart-2": "oklch(0.795 0.184 86.047)",
|
|
||||||
"chart-3": "oklch(0.681 0.162 75.834)",
|
|
||||||
"chart-4": "oklch(0.554 0.135 66.442)",
|
|
||||||
"chart-5": "oklch(0.476 0.114 61.907)",
|
|
||||||
},
|
|
||||||
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.795 0.184 86.047)",
|
|
||||||
"primary-foreground": "oklch(0.421 0.095 57.708)",
|
|
||||||
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.421 0.095 57.708)",
|
|
||||||
"chart-1": "oklch(0.905 0.182 98.111)",
|
|
||||||
"chart-2": "oklch(0.795 0.184 86.047)",
|
|
||||||
"chart-3": "oklch(0.681 0.162 75.834)",
|
|
||||||
"chart-4": "oklch(0.554 0.135 66.442)",
|
|
||||||
"chart-5": "oklch(0.476 0.114 61.907)",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
export function applyTheme(themeName: string) {
|
export function applyTheme(themeName: string) {
|
||||||
const theme = themes.find((t) => t.name === themeName) || themes[0];
|
const theme = themes.find((t) => t.name === themeName) || themes[0];
|
||||||
const root = document.documentElement;
|
const root = document.documentElement;
|
||||||
const isDark = root.classList.contains("dark");
|
const isDark = root.classList.contains("dark");
|
||||||
const vars = isDark ? theme.cssVars.dark : theme.cssVars.light;
|
const vars = isDark ? theme.cssVars.dark : theme.cssVars.light;
|
||||||
|
Object.entries(vars).forEach(([key, value]) => {
|
||||||
Object.entries(vars).forEach(([key, value]) => {
|
root.style.setProperty(`--${key}`, value);
|
||||||
root.style.setProperty(`--${key}`, value);
|
});
|
||||||
});
|
|
||||||
}
|
}
|
||||||
@@ -1,55 +1,45 @@
|
|||||||
import { toast } from "sonner";
|
import { toast, type ExternalToast } from "sonner";
|
||||||
import {
|
import { playSuccessSound, playErrorSound, playWarningSound, playInfoSound, } from "./audio";
|
||||||
playSuccessSound,
|
|
||||||
playErrorSound,
|
|
||||||
playWarningSound,
|
|
||||||
playInfoSound,
|
|
||||||
} from "./audio";
|
|
||||||
import { logger } from "./logger";
|
import { logger } from "./logger";
|
||||||
import { getSettings } from "./settings";
|
import { getSettings } from "./settings";
|
||||||
|
|
||||||
const toastStyle = {
|
const toastStyle = {
|
||||||
className: "font-mono lowercase",
|
className: "font-mono lowercase",
|
||||||
};
|
};
|
||||||
|
|
||||||
// Helper to check if SFX is enabled
|
|
||||||
const isSfxEnabled = () => getSettings().sfxEnabled;
|
const isSfxEnabled = () => getSettings().sfxEnabled;
|
||||||
|
|
||||||
// Wrapper functions for toast with sound effects
|
|
||||||
export const toastWithSound = {
|
export const toastWithSound = {
|
||||||
success: (message: string, data?: any) => {
|
success: (message: string, data?: ExternalToast) => {
|
||||||
const msg = message.toLowerCase();
|
const msg = message.toLowerCase();
|
||||||
logger.success(msg);
|
logger.success(msg);
|
||||||
if (isSfxEnabled()) playSuccessSound();
|
if (isSfxEnabled())
|
||||||
return toast.success(msg, { ...toastStyle, ...data });
|
playSuccessSound();
|
||||||
},
|
return toast.success(msg, { ...toastStyle, ...data });
|
||||||
|
},
|
||||||
error: (message: string, data?: any) => {
|
error: (message: string, data?: ExternalToast) => {
|
||||||
const msg = message.toLowerCase();
|
const msg = message.toLowerCase();
|
||||||
logger.error(msg);
|
logger.error(msg);
|
||||||
if (isSfxEnabled()) playErrorSound();
|
if (isSfxEnabled())
|
||||||
return toast.error(msg, { ...toastStyle, ...data });
|
playErrorSound();
|
||||||
},
|
return toast.error(msg, { ...toastStyle, ...data });
|
||||||
|
},
|
||||||
warning: (message: string, data?: any) => {
|
warning: (message: string, data?: ExternalToast) => {
|
||||||
const msg = message.toLowerCase();
|
const msg = message.toLowerCase();
|
||||||
logger.warning(msg);
|
logger.warning(msg);
|
||||||
if (isSfxEnabled()) playWarningSound();
|
if (isSfxEnabled())
|
||||||
return toast.warning(msg, { ...toastStyle, ...data });
|
playWarningSound();
|
||||||
},
|
return toast.warning(msg, { ...toastStyle, ...data });
|
||||||
|
},
|
||||||
info: (message: string, data?: any) => {
|
info: (message: string, data?: ExternalToast) => {
|
||||||
const msg = message.toLowerCase();
|
const msg = message.toLowerCase();
|
||||||
logger.info(msg);
|
logger.info(msg);
|
||||||
if (isSfxEnabled()) playInfoSound();
|
if (isSfxEnabled())
|
||||||
return toast.info(msg, { ...toastStyle, ...data });
|
playInfoSound();
|
||||||
},
|
return toast.info(msg, { ...toastStyle, ...data });
|
||||||
|
},
|
||||||
// Default toast without specific type
|
message: (message: string, data?: ExternalToast) => {
|
||||||
message: (message: string, data?: any) => {
|
const msg = message.toLowerCase();
|
||||||
const msg = message.toLowerCase();
|
logger.info(msg);
|
||||||
logger.info(msg);
|
if (isSfxEnabled())
|
||||||
if (isSfxEnabled()) playInfoSound();
|
playInfoSound();
|
||||||
return toast(msg, { ...toastStyle, ...data });
|
return toast(msg, { ...toastStyle, ...data });
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
+35
-39
@@ -1,44 +1,40 @@
|
|||||||
import { clsx, type ClassValue } from "clsx"
|
import { clsx, type ClassValue } from "clsx";
|
||||||
import { twMerge } from "tailwind-merge"
|
import { twMerge } from "tailwind-merge";
|
||||||
import { BrowserOpenURL } from "../../wailsjs/runtime/runtime"
|
import { BrowserOpenURL } from "../../wailsjs/runtime/runtime";
|
||||||
|
|
||||||
export function cn(...inputs: ClassValue[]) {
|
export function cn(...inputs: ClassValue[]) {
|
||||||
return twMerge(clsx(inputs))
|
return twMerge(clsx(inputs));
|
||||||
}
|
}
|
||||||
|
|
||||||
export function sanitizePath(input: string, os: string): string {
|
export function sanitizePath(input: string, os: string): string {
|
||||||
if (os === "Windows") {
|
if (os === "Windows") {
|
||||||
return input.replace(/[<>:"/\\|?*]/g, "_");
|
return input.replace(/[<>:"/\\|?*]/g, "_");
|
||||||
}
|
}
|
||||||
return input.replace(/\//g, "_");
|
return input.replace(/\//g, "_");
|
||||||
}
|
}
|
||||||
|
export function joinPath(os: string, ...parts: string[]): string {
|
||||||
export function joinPath(os: string, ...parts: string[]): string {
|
const sep = os === "Windows" ? "\\" : "/";
|
||||||
const sep = os === "Windows" ? "\\" : "/";
|
const filtered = parts.filter(Boolean);
|
||||||
|
if (filtered.length === 0)
|
||||||
const filtered = parts.filter(Boolean);
|
return "";
|
||||||
if (filtered.length === 0) return "";
|
const joined = filtered
|
||||||
|
.map((p, i) => {
|
||||||
const joined = filtered
|
if (i === 0) {
|
||||||
.map((p, i) => {
|
return p.replace(/[/\\]+$/g, "");
|
||||||
if (i === 0) {
|
}
|
||||||
return p.replace(/[/\\]+$/g, "");
|
return p.replace(/^[/\\]+|[/\\]+$/g, "");
|
||||||
}
|
})
|
||||||
return p.replace(/^[/\\]+|[/\\]+$/g, "");
|
.filter(Boolean)
|
||||||
})
|
.join(sep);
|
||||||
.filter(Boolean)
|
return joined;
|
||||||
.join(sep);
|
}
|
||||||
|
export function openExternal(url: string) {
|
||||||
return joined;
|
if (!url)
|
||||||
}
|
return;
|
||||||
|
try {
|
||||||
export function openExternal(url: string) {
|
BrowserOpenURL(url);
|
||||||
if (!url) return;
|
}
|
||||||
try {
|
catch {
|
||||||
BrowserOpenURL(url);
|
if (typeof window !== "undefined") {
|
||||||
} catch (error) {
|
window.open(url, "_blank", "noopener,noreferrer");
|
||||||
if (typeof window !== "undefined") {
|
}
|
||||||
window.open(url, "_blank", "noopener,noreferrer");
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
export function compareVersionNumbers(left: string, right: string) {
|
||||||
|
const toParts = (value: string) => value
|
||||||
|
.trim()
|
||||||
|
.replace(/^[^\d]*/, "")
|
||||||
|
.split(/[^0-9]+/)
|
||||||
|
.filter(Boolean)
|
||||||
|
.map((part) => Number.parseInt(part, 10));
|
||||||
|
const leftParts = toParts(left);
|
||||||
|
const rightParts = toParts(right);
|
||||||
|
const maxLength = Math.max(leftParts.length, rightParts.length);
|
||||||
|
for (let index = 0; index < maxLength; index += 1) {
|
||||||
|
const leftPart = leftParts[index] ?? 0;
|
||||||
|
const rightPart = rightParts[index] ?? 0;
|
||||||
|
if (leftPart > rightPart) {
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
if (leftPart < rightPart) {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
@@ -3,10 +3,7 @@ import { createRoot } from "react-dom/client";
|
|||||||
import "./index.css";
|
import "./index.css";
|
||||||
import App from "./App.tsx";
|
import App from "./App.tsx";
|
||||||
import { Toaster } from "@/components/ui/sonner";
|
import { Toaster } from "@/components/ui/sonner";
|
||||||
|
createRoot(document.getElementById("root")!).render(<StrictMode>
|
||||||
createRoot(document.getElementById("root")!).render(
|
|
||||||
<StrictMode>
|
|
||||||
<App />
|
<App />
|
||||||
<Toaster position="bottom-left" duration={1000} />
|
<Toaster position="bottom-left" duration={1000}/>
|
||||||
</StrictMode>
|
</StrictMode>);
|
||||||
);
|
|
||||||
+55
-62
@@ -1,76 +1,69 @@
|
|||||||
// Twitter/X Media Batch Downloader Types
|
|
||||||
|
|
||||||
export interface AccountInfo {
|
export interface AccountInfo {
|
||||||
name: string; // username/handle from extractor
|
name: string;
|
||||||
nick: string; // display name from extractor
|
nick: string;
|
||||||
date: string;
|
date: string;
|
||||||
followers_count: number;
|
followers_count: number;
|
||||||
friends_count: number;
|
friends_count: number;
|
||||||
profile_image: string;
|
profile_image: string;
|
||||||
statuses_count: number;
|
statuses_count: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface TimelineEntry {
|
export interface TimelineEntry {
|
||||||
url: string;
|
url: string;
|
||||||
date: string;
|
date: string;
|
||||||
tweet_id: string;
|
tweet_id: string;
|
||||||
type: string; // photo, video, gif, text
|
type: string;
|
||||||
is_retweet: boolean;
|
is_retweet: boolean;
|
||||||
extension: string;
|
extension: string;
|
||||||
width: number;
|
width: number;
|
||||||
height: number;
|
height: number;
|
||||||
content?: string;
|
content?: string;
|
||||||
view_count?: number;
|
view_count?: number;
|
||||||
bookmark_count?: number;
|
bookmark_count?: number;
|
||||||
favorite_count?: number;
|
favorite_count?: number;
|
||||||
retweet_count?: number;
|
retweet_count?: number;
|
||||||
reply_count?: number;
|
reply_count?: number;
|
||||||
source?: string;
|
source?: string;
|
||||||
verified?: boolean;
|
verified?: boolean;
|
||||||
|
original_filename?: string;
|
||||||
|
author_username?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ExtractMetadata {
|
export interface ExtractMetadata {
|
||||||
new_entries: number;
|
new_entries: number;
|
||||||
page: number;
|
page: number;
|
||||||
batch_size: number;
|
batch_size: number;
|
||||||
has_more: boolean;
|
has_more: boolean;
|
||||||
cursor?: string; // Cursor for resume capability
|
cursor?: string;
|
||||||
completed?: boolean; // True if all media fetched
|
completed?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface TwitterResponse {
|
export interface TwitterResponse {
|
||||||
account_info: AccountInfo;
|
account_info: AccountInfo;
|
||||||
total_urls: number;
|
total_urls: number;
|
||||||
timeline: TimelineEntry[];
|
timeline: TimelineEntry[];
|
||||||
metadata: ExtractMetadata;
|
metadata: ExtractMetadata;
|
||||||
cursor?: string; // Cursor for next fetch (from CLI)
|
cursor?: string;
|
||||||
completed?: boolean; // True if fetch completed
|
completed?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface TimelineRequest {
|
export interface TimelineRequest {
|
||||||
username: string;
|
username: string;
|
||||||
auth_token: string;
|
auth_token: string;
|
||||||
timeline_type: string; // media, timeline, tweets, with_replies, likes
|
timeline_type: string;
|
||||||
batch_size: number;
|
batch_size: number;
|
||||||
page: number;
|
page: number;
|
||||||
media_type: string; // all, image, video, gif
|
media_type: string;
|
||||||
retweets: boolean;
|
retweets: boolean;
|
||||||
cursor?: string; // Resume from this cursor position
|
cursor?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface DateRangeRequest {
|
export interface DateRangeRequest {
|
||||||
username: string;
|
username: string;
|
||||||
auth_token: string;
|
auth_token: string;
|
||||||
start_date: string; // YYYY-MM-DD
|
start_date: string;
|
||||||
end_date: string; // YYYY-MM-DD
|
end_date: string;
|
||||||
media_filter: string;
|
media_filter: string;
|
||||||
retweets: boolean;
|
retweets: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Settings types
|
|
||||||
export interface Settings {
|
export interface Settings {
|
||||||
downloadPath: string;
|
downloadPath: string;
|
||||||
theme: string;
|
theme: string;
|
||||||
themeMode: "auto" | "light" | "dark";
|
themeMode: "auto" | "light" | "dark";
|
||||||
sfxEnabled: boolean;
|
sfxEnabled: boolean;
|
||||||
}
|
}
|
||||||
Vendored
+2
@@ -0,0 +1,2 @@
|
|||||||
|
/// <reference types="vite/client" />
|
||||||
|
declare const __APP_VERSION__: string;
|
||||||
+17
-12
@@ -1,14 +1,19 @@
|
|||||||
import path from "path"
|
import fs from "fs";
|
||||||
import tailwindcss from "@tailwindcss/vite"
|
import path from "path";
|
||||||
import react from "@vitejs/plugin-react"
|
import tailwindcss from "@tailwindcss/vite";
|
||||||
import { defineConfig } from "vite"
|
import react from "@vitejs/plugin-react";
|
||||||
|
import { defineConfig } from "vite";
|
||||||
// https://vite.dev/config/
|
const wailsJsonPath = path.resolve(__dirname, "../wails.json");
|
||||||
|
const wailsJson = JSON.parse(fs.readFileSync(wailsJsonPath, "utf-8"));
|
||||||
|
const appVersion = wailsJson.info.productVersion;
|
||||||
export default defineConfig({
|
export default defineConfig({
|
||||||
plugins: [react(), tailwindcss()],
|
plugins: [react(), tailwindcss()],
|
||||||
resolve: {
|
resolve: {
|
||||||
alias: {
|
alias: {
|
||||||
"@": path.resolve(__dirname, "./src"),
|
"@": path.resolve(__dirname, "./src"),
|
||||||
|
},
|
||||||
},
|
},
|
||||||
},
|
define: {
|
||||||
})
|
__APP_VERSION__: JSON.stringify(appVersion),
|
||||||
|
},
|
||||||
|
});
|
||||||
Vendored
+86
@@ -0,0 +1,86 @@
|
|||||||
|
// 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 ExportAccountJSON(arg1:number,arg2:string):Promise<string>;
|
||||||
|
|
||||||
|
export function ExportAccountsTXT(arg1:Array<number>,arg2:string):Promise<string>;
|
||||||
|
|
||||||
|
export function ExtractDateRange(arg1:main.DateRangeRequest):Promise<string>;
|
||||||
|
|
||||||
|
export function ExtractTimeline(arg1:main.TimelineRequest):Promise<string>;
|
||||||
|
|
||||||
|
export function GetAccountFromDB(arg1:number):Promise<string>;
|
||||||
|
|
||||||
|
export function GetAllAccountsFromDB():Promise<Array<backend.AccountListItem>>;
|
||||||
|
|
||||||
|
export function GetAllGroups():Promise<Array<Record<string, string>>>;
|
||||||
|
|
||||||
|
export function GetDefaults():Promise<Record<string, string>>;
|
||||||
|
|
||||||
|
export function 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>;
|
||||||
@@ -0,0 +1,167 @@
|
|||||||
|
// @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 ExportAccountJSON(arg1, arg2) {
|
||||||
|
return window['go']['main']['App']['ExportAccountJSON'](arg1, arg2);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ExportAccountsTXT(arg1, arg2) {
|
||||||
|
return window['go']['main']['App']['ExportAccountsTXT'](arg1, arg2);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ExtractDateRange(arg1) {
|
||||||
|
return window['go']['main']['App']['ExtractDateRange'](arg1);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ExtractTimeline(arg1) {
|
||||||
|
return window['go']['main']['App']['ExtractTimeline'](arg1);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function GetAccountFromDB(arg1) {
|
||||||
|
return window['go']['main']['App']['GetAccountFromDB'](arg1);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function GetAllAccountsFromDB() {
|
||||||
|
return window['go']['main']['App']['GetAllAccountsFromDB']();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function GetAllGroups() {
|
||||||
|
return window['go']['main']['App']['GetAllGroups']();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function GetDefaults() {
|
||||||
|
return window['go']['main']['App']['GetDefaults']();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function 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);
|
||||||
|
}
|
||||||
@@ -0,0 +1,279 @@
|
|||||||
|
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;
|
||||||
|
proxy?: string;
|
||||||
|
|
||||||
|
static createFrom(source: any = {}) {
|
||||||
|
return new DownloadMediaRequest(source);
|
||||||
|
}
|
||||||
|
|
||||||
|
constructor(source: any = {}) {
|
||||||
|
if ('string' === typeof source) source = JSON.parse(source);
|
||||||
|
this.urls = source["urls"];
|
||||||
|
this.output_dir = source["output_dir"];
|
||||||
|
this.username = source["username"];
|
||||||
|
this.proxy = source["proxy"];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
export class DownloadMediaResponse {
|
||||||
|
success: boolean;
|
||||||
|
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;
|
||||||
|
|
||||||
|
static createFrom(source: any = {}) {
|
||||||
|
return new MediaItemRequest(source);
|
||||||
|
}
|
||||||
|
|
||||||
|
constructor(source: any = {}) {
|
||||||
|
if ('string' === typeof source) source = JSON.parse(source);
|
||||||
|
this.url = source["url"];
|
||||||
|
this.date = source["date"];
|
||||||
|
this.tweet_id = source["tweet_id"];
|
||||||
|
this.type = source["type"];
|
||||||
|
this.content = source["content"];
|
||||||
|
this.original_filename = source["original_filename"];
|
||||||
|
this.author_username = source["author_username"];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
export class DownloadMediaWithMetadataRequest {
|
||||||
|
items: MediaItemRequest[];
|
||||||
|
output_dir: string;
|
||||||
|
username: string;
|
||||||
|
proxy?: string;
|
||||||
|
|
||||||
|
static createFrom(source: any = {}) {
|
||||||
|
return new DownloadMediaWithMetadataRequest(source);
|
||||||
|
}
|
||||||
|
|
||||||
|
constructor(source: any = {}) {
|
||||||
|
if ('string' === typeof source) source = JSON.parse(source);
|
||||||
|
this.items = this.convertValues(source["items"], MediaItemRequest);
|
||||||
|
this.output_dir = source["output_dir"];
|
||||||
|
this.username = source["username"];
|
||||||
|
this.proxy = source["proxy"];
|
||||||
|
}
|
||||||
|
|
||||||
|
convertValues(a: any, classs: any, asMap: boolean = false): any {
|
||||||
|
if (!a) {
|
||||||
|
return a;
|
||||||
|
}
|
||||||
|
if (a.slice && a.map) {
|
||||||
|
return (a as any[]).map(elem => this.convertValues(elem, classs));
|
||||||
|
} else if ("object" === typeof a) {
|
||||||
|
if (asMap) {
|
||||||
|
for (const key of Object.keys(a)) {
|
||||||
|
a[key] = new classs(a[key]);
|
||||||
|
}
|
||||||
|
return a;
|
||||||
|
}
|
||||||
|
return new classs(a);
|
||||||
|
}
|
||||||
|
return a;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
export class ImportAccountResponse {
|
||||||
|
success: boolean;
|
||||||
|
username: string;
|
||||||
|
message: string;
|
||||||
|
|
||||||
|
static createFrom(source: any = {}) {
|
||||||
|
return new ImportAccountResponse(source);
|
||||||
|
}
|
||||||
|
|
||||||
|
constructor(source: any = {}) {
|
||||||
|
if ('string' === typeof source) source = JSON.parse(source);
|
||||||
|
this.success = source["success"];
|
||||||
|
this.username = source["username"];
|
||||||
|
this.message = source["message"];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class TimelineRequest {
|
||||||
|
username: string;
|
||||||
|
auth_token: string;
|
||||||
|
timeline_type: string;
|
||||||
|
batch_size: number;
|
||||||
|
page: number;
|
||||||
|
media_type: string;
|
||||||
|
retweets: boolean;
|
||||||
|
cursor?: string;
|
||||||
|
|
||||||
|
static createFrom(source: any = {}) {
|
||||||
|
return new TimelineRequest(source);
|
||||||
|
}
|
||||||
|
|
||||||
|
constructor(source: any = {}) {
|
||||||
|
if ('string' === typeof source) source = JSON.parse(source);
|
||||||
|
this.username = source["username"];
|
||||||
|
this.auth_token = source["auth_token"];
|
||||||
|
this.timeline_type = source["timeline_type"];
|
||||||
|
this.batch_size = source["batch_size"];
|
||||||
|
this.page = source["page"];
|
||||||
|
this.media_type = source["media_type"];
|
||||||
|
this.retweets = source["retweets"];
|
||||||
|
this.cursor = source["cursor"];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
@@ -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
@@ -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>;
|
||||||
@@ -0,0 +1,298 @@
|
|||||||
|
/*
|
||||||
|
_ __ _ __
|
||||||
|
| | / /___ _(_) /____
|
||||||
|
| | /| / / __ `/ / / ___/
|
||||||
|
| |/ |/ / /_/ / / (__ )
|
||||||
|
|__/|__/\__,_/_/_/____/
|
||||||
|
The electron alternative for Go
|
||||||
|
(c) Lea Anthony 2019-present
|
||||||
|
*/
|
||||||
|
|
||||||
|
export function LogPrint(message) {
|
||||||
|
window.runtime.LogPrint(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function LogTrace(message) {
|
||||||
|
window.runtime.LogTrace(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function LogDebug(message) {
|
||||||
|
window.runtime.LogDebug(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function LogInfo(message) {
|
||||||
|
window.runtime.LogInfo(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function LogWarning(message) {
|
||||||
|
window.runtime.LogWarning(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function LogError(message) {
|
||||||
|
window.runtime.LogError(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function LogFatal(message) {
|
||||||
|
window.runtime.LogFatal(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function EventsOnMultiple(eventName, callback, maxCallbacks) {
|
||||||
|
return window.runtime.EventsOnMultiple(eventName, callback, maxCallbacks);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function EventsOn(eventName, callback) {
|
||||||
|
return EventsOnMultiple(eventName, callback, -1);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function EventsOff(eventName, ...additionalEventNames) {
|
||||||
|
return window.runtime.EventsOff(eventName, ...additionalEventNames);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function EventsOffAll() {
|
||||||
|
return window.runtime.EventsOffAll();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function EventsOnce(eventName, callback) {
|
||||||
|
return EventsOnMultiple(eventName, callback, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function EventsEmit(eventName) {
|
||||||
|
let args = [eventName].slice.call(arguments);
|
||||||
|
return window.runtime.EventsEmit.apply(null, args);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function WindowReload() {
|
||||||
|
window.runtime.WindowReload();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function WindowReloadApp() {
|
||||||
|
window.runtime.WindowReloadApp();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function WindowSetAlwaysOnTop(b) {
|
||||||
|
window.runtime.WindowSetAlwaysOnTop(b);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function WindowSetSystemDefaultTheme() {
|
||||||
|
window.runtime.WindowSetSystemDefaultTheme();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function WindowSetLightTheme() {
|
||||||
|
window.runtime.WindowSetLightTheme();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function WindowSetDarkTheme() {
|
||||||
|
window.runtime.WindowSetDarkTheme();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function WindowCenter() {
|
||||||
|
window.runtime.WindowCenter();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function WindowSetTitle(title) {
|
||||||
|
window.runtime.WindowSetTitle(title);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function WindowFullscreen() {
|
||||||
|
window.runtime.WindowFullscreen();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function WindowUnfullscreen() {
|
||||||
|
window.runtime.WindowUnfullscreen();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function WindowIsFullscreen() {
|
||||||
|
return window.runtime.WindowIsFullscreen();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function WindowGetSize() {
|
||||||
|
return window.runtime.WindowGetSize();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function WindowSetSize(width, height) {
|
||||||
|
window.runtime.WindowSetSize(width, height);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function WindowSetMaxSize(width, height) {
|
||||||
|
window.runtime.WindowSetMaxSize(width, height);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function WindowSetMinSize(width, height) {
|
||||||
|
window.runtime.WindowSetMinSize(width, height);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function WindowSetPosition(x, y) {
|
||||||
|
window.runtime.WindowSetPosition(x, y);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function WindowGetPosition() {
|
||||||
|
return window.runtime.WindowGetPosition();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function WindowHide() {
|
||||||
|
window.runtime.WindowHide();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function WindowShow() {
|
||||||
|
window.runtime.WindowShow();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function WindowMaximise() {
|
||||||
|
window.runtime.WindowMaximise();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function WindowToggleMaximise() {
|
||||||
|
window.runtime.WindowToggleMaximise();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function WindowUnmaximise() {
|
||||||
|
window.runtime.WindowUnmaximise();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function WindowIsMaximised() {
|
||||||
|
return window.runtime.WindowIsMaximised();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function WindowMinimise() {
|
||||||
|
window.runtime.WindowMinimise();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function WindowUnminimise() {
|
||||||
|
window.runtime.WindowUnminimise();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function WindowSetBackgroundColour(R, G, B, A) {
|
||||||
|
window.runtime.WindowSetBackgroundColour(R, G, B, A);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ScreenGetAll() {
|
||||||
|
return window.runtime.ScreenGetAll();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function WindowIsMinimised() {
|
||||||
|
return window.runtime.WindowIsMinimised();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function WindowIsNormal() {
|
||||||
|
return window.runtime.WindowIsNormal();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function BrowserOpenURL(url) {
|
||||||
|
window.runtime.BrowserOpenURL(url);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function Environment() {
|
||||||
|
return window.runtime.Environment();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function Quit() {
|
||||||
|
window.runtime.Quit();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function Hide() {
|
||||||
|
window.runtime.Hide();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function Show() {
|
||||||
|
window.runtime.Show();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ClipboardGetText() {
|
||||||
|
return window.runtime.ClipboardGetText();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ClipboardSetText(text) {
|
||||||
|
return window.runtime.ClipboardSetText(text);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Callback for OnFileDrop returns a slice of file path strings when a drop is finished.
|
||||||
|
*
|
||||||
|
* @export
|
||||||
|
* @callback OnFileDropCallback
|
||||||
|
* @param {number} x - x coordinate of the drop
|
||||||
|
* @param {number} y - y coordinate of the drop
|
||||||
|
* @param {string[]} paths - A list of file paths.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* OnFileDrop listens to drag and drop events and calls the callback with the coordinates of the drop and an array of path strings.
|
||||||
|
*
|
||||||
|
* @export
|
||||||
|
* @param {OnFileDropCallback} callback - Callback for OnFileDrop returns a slice of file path strings when a drop is finished.
|
||||||
|
* @param {boolean} [useDropTarget=true] - Only call the callback when the drop finished on an element that has the drop target style. (--wails-drop-target)
|
||||||
|
*/
|
||||||
|
export function OnFileDrop(callback, useDropTarget) {
|
||||||
|
return window.runtime.OnFileDrop(callback, useDropTarget);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* OnFileDropOff removes the drag and drop listeners and handlers.
|
||||||
|
*/
|
||||||
|
export function OnFileDropOff() {
|
||||||
|
return window.runtime.OnFileDropOff();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function CanResolveFilePaths() {
|
||||||
|
return window.runtime.CanResolveFilePaths();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ResolveFilePaths(files) {
|
||||||
|
return window.runtime.ResolveFilePaths(files);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function InitializeNotifications() {
|
||||||
|
return window.runtime.InitializeNotifications();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function CleanupNotifications() {
|
||||||
|
return window.runtime.CleanupNotifications();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function IsNotificationAvailable() {
|
||||||
|
return window.runtime.IsNotificationAvailable();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function RequestNotificationAuthorization() {
|
||||||
|
return window.runtime.RequestNotificationAuthorization();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function CheckNotificationAuthorization() {
|
||||||
|
return window.runtime.CheckNotificationAuthorization();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function SendNotification(options) {
|
||||||
|
return window.runtime.SendNotification(options);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function SendNotificationWithActions(options) {
|
||||||
|
return window.runtime.SendNotificationWithActions(options);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function RegisterNotificationCategory(category) {
|
||||||
|
return window.runtime.RegisterNotificationCategory(category);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function RemoveNotificationCategory(categoryId) {
|
||||||
|
return window.runtime.RemoveNotificationCategory(categoryId);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function RemoveAllPendingNotifications() {
|
||||||
|
return window.runtime.RemoveAllPendingNotifications();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function RemovePendingNotification(identifier) {
|
||||||
|
return window.runtime.RemovePendingNotification(identifier);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function RemoveAllDeliveredNotifications() {
|
||||||
|
return window.runtime.RemoveAllDeliveredNotifications();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function RemoveDeliveredNotification(identifier) {
|
||||||
|
return window.runtime.RemoveDeliveredNotification(identifier);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function RemoveNotification(identifier) {
|
||||||
|
return window.runtime.RemoveNotification(identifier);
|
||||||
|
}
|
||||||
@@ -3,15 +3,18 @@ module twitterxmediabatchdownloader
|
|||||||
go 1.25.4
|
go 1.25.4
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/mattn/go-sqlite3 v1.14.32
|
github.com/wailsapp/wails/v2 v2.12.0
|
||||||
github.com/ulikunitz/xz v0.5.15
|
github.com/zalando/go-keyring v0.2.8
|
||||||
github.com/wailsapp/wails/v2 v2.11.0
|
modernc.org/sqlite v1.50.1
|
||||||
)
|
)
|
||||||
|
|
||||||
require (
|
require (
|
||||||
|
git.sr.ht/~jackmordaunt/go-toast/v2 v2.0.3 // indirect
|
||||||
github.com/bep/debounce v1.2.1 // indirect
|
github.com/bep/debounce v1.2.1 // indirect
|
||||||
|
github.com/danieljoos/wincred v1.2.3 // indirect
|
||||||
|
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||||
github.com/go-ole/go-ole v1.3.0 // indirect
|
github.com/go-ole/go-ole v1.3.0 // indirect
|
||||||
github.com/godbus/dbus/v5 v5.2.0 // indirect
|
github.com/godbus/dbus/v5 v5.2.2 // indirect
|
||||||
github.com/google/uuid v1.6.0 // indirect
|
github.com/google/uuid v1.6.0 // indirect
|
||||||
github.com/gorilla/websocket v1.5.3 // indirect
|
github.com/gorilla/websocket v1.5.3 // indirect
|
||||||
github.com/jchv/go-winloader v0.0.0-20250406163304-c1995be93bd1 // indirect
|
github.com/jchv/go-winloader v0.0.0-20250406163304-c1995be93bd1 // indirect
|
||||||
@@ -23,8 +26,10 @@ require (
|
|||||||
github.com/leaanthony/u v1.1.1 // indirect
|
github.com/leaanthony/u v1.1.1 // indirect
|
||||||
github.com/mattn/go-colorable v0.1.14 // indirect
|
github.com/mattn/go-colorable v0.1.14 // indirect
|
||||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||||
|
github.com/ncruces/go-strftime v1.0.0 // indirect
|
||||||
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect
|
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect
|
||||||
github.com/pkg/errors v0.9.1 // indirect
|
github.com/pkg/errors v0.9.1 // indirect
|
||||||
|
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||||
github.com/rivo/uniseg v0.4.7 // indirect
|
github.com/rivo/uniseg v0.4.7 // indirect
|
||||||
github.com/samber/lo v1.52.0 // indirect
|
github.com/samber/lo v1.52.0 // indirect
|
||||||
github.com/tkrajina/go-reflector v0.5.8 // indirect
|
github.com/tkrajina/go-reflector v0.5.8 // indirect
|
||||||
@@ -34,6 +39,9 @@ require (
|
|||||||
github.com/wailsapp/mimetype v1.4.1 // indirect
|
github.com/wailsapp/mimetype v1.4.1 // indirect
|
||||||
golang.org/x/crypto v0.45.0 // indirect
|
golang.org/x/crypto v0.45.0 // indirect
|
||||||
golang.org/x/net v0.47.0 // indirect
|
golang.org/x/net v0.47.0 // indirect
|
||||||
golang.org/x/sys v0.38.0 // indirect
|
golang.org/x/sys v0.42.0 // indirect
|
||||||
golang.org/x/text v0.31.0 // indirect
|
golang.org/x/text v0.31.0 // indirect
|
||||||
|
modernc.org/libc v1.72.3 // indirect
|
||||||
|
modernc.org/mathutil v1.7.1 // indirect
|
||||||
|
modernc.org/memory v1.11.0 // indirect
|
||||||
)
|
)
|
||||||
@@ -1,15 +1,25 @@
|
|||||||
|
git.sr.ht/~jackmordaunt/go-toast/v2 v2.0.3 h1:N3IGoHHp9pb6mj1cbXbuaSXV/UMKwmbKLf53nQmtqMA=
|
||||||
|
git.sr.ht/~jackmordaunt/go-toast/v2 v2.0.3/go.mod h1:QtOLZGz8olr4qH2vWK0QH0w0O4T9fEIjMuWpKUsH7nc=
|
||||||
github.com/bep/debounce v1.2.1 h1:v67fRdBA9UQu2NhLFXrSg0Brw7CexQekrBwDMM8bzeY=
|
github.com/bep/debounce v1.2.1 h1:v67fRdBA9UQu2NhLFXrSg0Brw7CexQekrBwDMM8bzeY=
|
||||||
github.com/bep/debounce v1.2.1/go.mod h1:H8yggRPQKLUhUoqrJC1bO2xNya7vanpDl7xR3ISbCJ0=
|
github.com/bep/debounce v1.2.1/go.mod h1:H8yggRPQKLUhUoqrJC1bO2xNya7vanpDl7xR3ISbCJ0=
|
||||||
|
github.com/danieljoos/wincred v1.2.3 h1:v7dZC2x32Ut3nEfRH+vhoZGvN72+dQ/snVXo/vMFLdQ=
|
||||||
|
github.com/danieljoos/wincred v1.2.3/go.mod h1:6qqX0WNrS4RzPZ1tnroDzq9kY3fu1KwE7MRLQK4X0bs=
|
||||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
|
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
|
||||||
|
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
||||||
github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE=
|
github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE=
|
||||||
github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78=
|
github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78=
|
||||||
github.com/godbus/dbus/v5 v5.2.0 h1:3WexO+U+yg9T70v9FdHr9kCxYlazaAXUhx2VMkbfax8=
|
github.com/godbus/dbus/v5 v5.2.2 h1:TUR3TgtSVDmjiXOgAAyaZbYmIeP3DPkld3jgKGV8mXQ=
|
||||||
github.com/godbus/dbus/v5 v5.2.0/go.mod h1:3AAv2+hPq5rdnr5txxxRwiGjPXamgoIHgz9FPBfOp3c=
|
github.com/godbus/dbus/v5 v5.2.2/go.mod h1:3AAv2+hPq5rdnr5txxxRwiGjPXamgoIHgz9FPBfOp3c=
|
||||||
|
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs=
|
||||||
|
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA=
|
||||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||||
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
||||||
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||||
|
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
|
||||||
|
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
|
||||||
github.com/jchv/go-winloader v0.0.0-20250406163304-c1995be93bd1 h1:njuLRcjAuMKr7kI3D85AXWkw6/+v9PwtV6M6o11sWHQ=
|
github.com/jchv/go-winloader v0.0.0-20250406163304-c1995be93bd1 h1:njuLRcjAuMKr7kI3D85AXWkw6/+v9PwtV6M6o11sWHQ=
|
||||||
github.com/jchv/go-winloader v0.0.0-20250406163304-c1995be93bd1/go.mod h1:alcuEEnZsY1WQsagKhZDsoPCRoOijYqhZvPwLG0kzVs=
|
github.com/jchv/go-winloader v0.0.0-20250406163304-c1995be93bd1/go.mod h1:alcuEEnZsY1WQsagKhZDsoPCRoOijYqhZvPwLG0kzVs=
|
||||||
github.com/labstack/echo/v4 v4.13.4 h1:oTZZW+T3s9gAu5L8vmzihV7/lkXGZuITzTQkTEhcXEA=
|
github.com/labstack/echo/v4 v4.13.4 h1:oTZZW+T3s9gAu5L8vmzihV7/lkXGZuITzTQkTEhcXEA=
|
||||||
@@ -33,25 +43,27 @@ github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHP
|
|||||||
github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
|
github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
|
||||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||||
github.com/mattn/go-sqlite3 v1.14.32 h1:JD12Ag3oLy1zQA+BNn74xRgaBbdhbNIDYvQUEuuErjs=
|
github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
|
||||||
github.com/mattn/go-sqlite3 v1.14.32/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
|
github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
|
||||||
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ=
|
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ=
|
||||||
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU=
|
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU=
|
||||||
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
|
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
|
||||||
|
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||||
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
|
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
|
||||||
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
|
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
|
||||||
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
|
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
|
||||||
github.com/samber/lo v1.52.0 h1:Rvi+3BFHES3A8meP33VPAxiBZX/Aws5RxrschYGjomw=
|
github.com/samber/lo v1.52.0 h1:Rvi+3BFHES3A8meP33VPAxiBZX/Aws5RxrschYGjomw=
|
||||||
github.com/samber/lo v1.52.0/go.mod h1:4+MXEGsJzbKGaUEQFKBq2xtfuznW9oz/WrgyzMzRoM0=
|
github.com/samber/lo v1.52.0/go.mod h1:4+MXEGsJzbKGaUEQFKBq2xtfuznW9oz/WrgyzMzRoM0=
|
||||||
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
|
github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY=
|
||||||
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
|
||||||
|
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||||
|
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||||
github.com/tkrajina/go-reflector v0.5.8 h1:yPADHrwmUbMq4RGEyaOUpz2H90sRsETNVpjzo3DLVQQ=
|
github.com/tkrajina/go-reflector v0.5.8 h1:yPADHrwmUbMq4RGEyaOUpz2H90sRsETNVpjzo3DLVQQ=
|
||||||
github.com/tkrajina/go-reflector v0.5.8/go.mod h1:ECbqLgccecY5kPmPmXg1MrHW585yMcDkVl6IvJe64T4=
|
github.com/tkrajina/go-reflector v0.5.8/go.mod h1:ECbqLgccecY5kPmPmXg1MrHW585yMcDkVl6IvJe64T4=
|
||||||
github.com/ulikunitz/xz v0.5.15 h1:9DNdB5s+SgV3bQ2ApL10xRc35ck0DuIX/isZvIk+ubY=
|
|
||||||
github.com/ulikunitz/xz v0.5.15/go.mod h1:nbz6k7qbPmH4IRqmfOplQw/tblSgqTqBwxkY0oWt/14=
|
|
||||||
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
|
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
|
||||||
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
|
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
|
||||||
github.com/valyala/fasttemplate v1.2.2 h1:lxLXG0uE3Qnshl9QyaK6XJxMXlQZELvChBOCmQD0Loo=
|
github.com/valyala/fasttemplate v1.2.2 h1:lxLXG0uE3Qnshl9QyaK6XJxMXlQZELvChBOCmQD0Loo=
|
||||||
@@ -60,24 +72,60 @@ github.com/wailsapp/go-webview2 v1.0.23 h1:jmv8qhz1lHibCc79bMM/a/FqOnnzOGEisLav+
|
|||||||
github.com/wailsapp/go-webview2 v1.0.23/go.mod h1:qJmWAmAmaniuKGZPWwne+uor3AHMB5PFhqiK0Bbj8kc=
|
github.com/wailsapp/go-webview2 v1.0.23/go.mod h1:qJmWAmAmaniuKGZPWwne+uor3AHMB5PFhqiK0Bbj8kc=
|
||||||
github.com/wailsapp/mimetype v1.4.1 h1:pQN9ycO7uo4vsUUuPeHEYoUkLVkaRntMnHJxVwYhwHs=
|
github.com/wailsapp/mimetype v1.4.1 h1:pQN9ycO7uo4vsUUuPeHEYoUkLVkaRntMnHJxVwYhwHs=
|
||||||
github.com/wailsapp/mimetype v1.4.1/go.mod h1:9aV5k31bBOv5z6u+QP8TltzvNGJPmNJD4XlAL3U+j3o=
|
github.com/wailsapp/mimetype v1.4.1/go.mod h1:9aV5k31bBOv5z6u+QP8TltzvNGJPmNJD4XlAL3U+j3o=
|
||||||
github.com/wailsapp/wails/v2 v2.11.0 h1:seLacV8pqupq32IjS4Y7V8ucab0WZwtK6VvUVxSBtqQ=
|
github.com/wailsapp/wails/v2 v2.12.0 h1:BHO/kLNWFHYjCzucxbzAYZWUjub1Tvb4cSguQozHn5c=
|
||||||
github.com/wailsapp/wails/v2 v2.11.0/go.mod h1:jrf0ZaM6+GBc1wRmXsM8cIvzlg0karYin3erahI4+0k=
|
github.com/wailsapp/wails/v2 v2.12.0/go.mod h1:mo1bzK1DEJrobt7YrBjgxvb5Sihb1mhAY09hppbibQg=
|
||||||
|
github.com/zalando/go-keyring v0.2.8 h1:6sD/Ucpl7jNq10rM2pgqTs0sZ9V3qMrqfIIy5YPccHs=
|
||||||
|
github.com/zalando/go-keyring v0.2.8/go.mod h1:tsMo+VpRq5NGyKfxoBVjCuMrG47yj8cmakZDO5QGii0=
|
||||||
golang.org/x/crypto v0.45.0 h1:jMBrvKuj23MTlT0bQEOBcAE0mjg8mK9RXFhRH6nyF3Q=
|
golang.org/x/crypto v0.45.0 h1:jMBrvKuj23MTlT0bQEOBcAE0mjg8mK9RXFhRH6nyF3Q=
|
||||||
golang.org/x/crypto v0.45.0/go.mod h1:XTGrrkGJve7CYK7J8PEww4aY7gM3qMCElcJQ8n8JdX4=
|
golang.org/x/crypto v0.45.0/go.mod h1:XTGrrkGJve7CYK7J8PEww4aY7gM3qMCElcJQ8n8JdX4=
|
||||||
|
golang.org/x/mod v0.33.0 h1:tHFzIWbBifEmbwtGz65eaWyGiGZatSrT9prnU8DbVL8=
|
||||||
|
golang.org/x/mod v0.33.0/go.mod h1:swjeQEj+6r7fODbD2cqrnje9PnziFuw4bmLbBZFrQ5w=
|
||||||
golang.org/x/net v0.0.0-20210505024714-0287a6fb4125/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
golang.org/x/net v0.0.0-20210505024714-0287a6fb4125/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
||||||
golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY=
|
golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY=
|
||||||
golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU=
|
golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU=
|
||||||
|
golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
|
||||||
|
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||||
golang.org/x/sys v0.0.0-20200810151505-1b9f1253b3ed/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/sys v0.0.0-20200810151505-1b9f1253b3ed/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc=
|
golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=
|
||||||
golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||||
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||||
golang.org/x/text v0.31.0 h1:aC8ghyu4JhP8VojJ2lEHBnochRno1sgL6nEi9WGFGMM=
|
golang.org/x/text v0.31.0 h1:aC8ghyu4JhP8VojJ2lEHBnochRno1sgL6nEi9WGFGMM=
|
||||||
golang.org/x/text v0.31.0/go.mod h1:tKRAlv61yKIjGGHX/4tP1LTbc13YSec1pxVEWXzfoeM=
|
golang.org/x/text v0.31.0/go.mod h1:tKRAlv61yKIjGGHX/4tP1LTbc13YSec1pxVEWXzfoeM=
|
||||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||||
|
golang.org/x/tools v0.42.0 h1:uNgphsn75Tdz5Ji2q36v/nsFSfR/9BRFvqhGBaJGd5k=
|
||||||
|
golang.org/x/tools v0.42.0/go.mod h1:Ma6lCIwGZvHK6XtgbswSoWroEkhugApmsXyrUmBhfr0=
|
||||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
|
modernc.org/cc/v4 v4.28.2 h1:3tQ0lf2ADtoby2EtSP+J7IE2SHwEJdP8ioR59wx7XpY=
|
||||||
|
modernc.org/cc/v4 v4.28.2/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI=
|
||||||
|
modernc.org/ccgo/v4 v4.34.0 h1:yRLPFZieg532OT4rp4JFNIVcquwalMX26G95WQDqwCQ=
|
||||||
|
modernc.org/ccgo/v4 v4.34.0/go.mod h1:AS5WYMyBakQ+fhsHhtP8mWB82KTGPkNNJDGfGQCe0/A=
|
||||||
|
modernc.org/fileutil v1.4.0 h1:j6ZzNTftVS054gi281TyLjHPp6CPHr2KCxEXjEbD6SM=
|
||||||
|
modernc.org/fileutil v1.4.0/go.mod h1:EqdKFDxiByqxLk8ozOxObDSfcVOv/54xDs/DUHdvCUU=
|
||||||
|
modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI=
|
||||||
|
modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito=
|
||||||
|
modernc.org/gc/v3 v3.1.2 h1:ZtDCnhonXSZexk/AYsegNRV1lJGgaNZJuKjJSWKyEqo=
|
||||||
|
modernc.org/gc/v3 v3.1.2/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY=
|
||||||
|
modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks=
|
||||||
|
modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI=
|
||||||
|
modernc.org/libc v1.72.3 h1:ZnDF4tXn4NBXFutMMQC4vtbTFSXhhKzR73fv0beZEAU=
|
||||||
|
modernc.org/libc v1.72.3/go.mod h1:dn0dZNnnn1clLyvRxLxYExxiKRZIRENOfqQ8XEeg4Qs=
|
||||||
|
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
|
||||||
|
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
|
||||||
|
modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI=
|
||||||
|
modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
|
||||||
|
modernc.org/opt v0.2.0 h1:tGyef5ApycA7FSEOMraay9SaTk5zmbx7Tu+cJs4QKZg=
|
||||||
|
modernc.org/opt v0.2.0/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=
|
||||||
|
modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=
|
||||||
|
modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=
|
||||||
|
modernc.org/sqlite v1.50.1 h1:l+cQvn0sd0zJJtfygGHuQJ5AjlrwXmWPw4KP3ZMwr9w=
|
||||||
|
modernc.org/sqlite v1.50.1/go.mod h1:tcNzv5p84E0skkmJn038y+hWJbLQXQqEnQfeh5r2JLM=
|
||||||
|
modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=
|
||||||
|
modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=
|
||||||
|
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
|
||||||
|
modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=
|
||||||
@@ -1,62 +0,0 @@
|
|||||||
# Building Extractor Binary
|
|
||||||
|
|
||||||
This guide explains how to build the `extractor` binary from `twitter_cli.py`.
|
|
||||||
|
|
||||||
## Quick Start - Use Pre-built Binary
|
|
||||||
|
|
||||||
**You don't need to build the binary yourself!** After running the main application once, the pre-built binary is automatically extracted to:
|
|
||||||
|
|
||||||
```
|
|
||||||
Windows: C:\Users\YourUsername\.twitterxmediabatchdownloader\extractor.exe
|
|
||||||
Linux: ~/.twitterxmediabatchdownloader/extractor
|
|
||||||
macOS: ~/.twitterxmediabatchdownloader/extractor
|
|
||||||
```
|
|
||||||
|
|
||||||
You can use this binary directly for CLI operations without rebuilding.
|
|
||||||
|
|
||||||
### Using the Pre-built Binary
|
|
||||||
|
|
||||||
```powershell
|
|
||||||
# Windows
|
|
||||||
C:\Users\YourUsername\.twitterxmediabatchdownloader\extractor.exe https://x.com/username/media --limit 10 --json --guest
|
|
||||||
|
|
||||||
# Linux/macOS
|
|
||||||
~/.twitterxmediabatchdownloader/extractor https://x.com/username/media --limit 10 --json --guest
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Building from Source (Optional)
|
|
||||||
|
|
||||||
If you need to rebuild the binary (e.g., after modifying `twitter_cli.py`):
|
|
||||||
|
|
||||||
### Prerequisites
|
|
||||||
|
|
||||||
```bash
|
|
||||||
pip install pyinstaller
|
|
||||||
# or
|
|
||||||
pip install nuitka
|
|
||||||
```
|
|
||||||
|
|
||||||
### Build Commands
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# PyInstaller (faster build, larger file)
|
|
||||||
pyinstaller --onefile --name extractor --collect-all gallery_dl twitter_cli.py
|
|
||||||
|
|
||||||
# Nuitka (slower build, better performance, smaller file)
|
|
||||||
python -m nuitka --onefile --output-filename=extractor.exe --include-package=gallery_dl --include-package-data=gallery_dl twitter_cli.py
|
|
||||||
```
|
|
||||||
|
|
||||||
### Output Location
|
|
||||||
|
|
||||||
- PyInstaller: `dist/extractor` or `dist/extractor.exe`
|
|
||||||
- Nuitka: `extractor` or `extractor.exe` (in current directory)
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Notes
|
|
||||||
|
|
||||||
- The main application automatically manages the binary (extracts, updates, and uses it)
|
|
||||||
- Manual building is only needed if you're developing or customizing the extractor
|
|
||||||
- The pre-built binary is kept in sync with the application version
|
|
||||||
-331
@@ -1,331 +0,0 @@
|
|||||||
# twitter_cli.py — Usage Guide
|
|
||||||
|
|
||||||
CLI tool for extracting media and metadata from Twitter/X using gallery-dl extractor.
|
|
||||||
|
|
||||||
## Quickstart
|
|
||||||
|
|
||||||
1. **Set up environment**
|
|
||||||
```powershell
|
|
||||||
cd helper
|
|
||||||
python -m venv .venv
|
|
||||||
.\.venv\Scripts\Activate.ps1
|
|
||||||
pip install -r requirements.txt
|
|
||||||
```
|
|
||||||
|
|
||||||
2. **Verify gallery-dl**
|
|
||||||
```powershell
|
|
||||||
python -c "import gallery_dl; print(gallery_dl.__version__)"
|
|
||||||
```
|
|
||||||
|
|
||||||
3. **Quick test** (using demo account):
|
|
||||||
```powershell
|
|
||||||
python twitter_cli.py https://x.com/xbatchdemo/media --limit 1 --json --guest
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Command Line Arguments
|
|
||||||
|
|
||||||
### Required
|
|
||||||
- `url` — Twitter/X URL (timeline, media, likes, search, etc.)
|
|
||||||
|
|
||||||
### Authentication
|
|
||||||
- `--auth-token TOKEN` — Your auth_token cookie value
|
|
||||||
- `--guest` — Force guest mode (no authentication)
|
|
||||||
|
|
||||||
### Content Options
|
|
||||||
- `--retweets {skip|include|original}` — Control retweets (default: skip)
|
|
||||||
- `--no-videos` — Skip video downloads
|
|
||||||
- `--text-tweets` — Include tweets without media
|
|
||||||
- `--type {photo|video|animated_gif|all}` — Filter by media type (default: all)
|
|
||||||
|
|
||||||
### Quality & Format
|
|
||||||
- `--size SIZE` — Image size: `orig`, `4096x4096`, `large`, `medium`, `small` (default: orig)
|
|
||||||
|
|
||||||
### Fetch Control
|
|
||||||
- `--limit N` — Maximum media items to fetch (0 = unlimited)
|
|
||||||
- `--cursor CURSOR` — Resume from specific cursor position
|
|
||||||
|
|
||||||
### Output Options
|
|
||||||
- `--json` — Output results as JSON
|
|
||||||
- `--metadata` — Include tweet metadata (author, counts, etc.)
|
|
||||||
- `--output FILE` / `-o FILE` — Save to JSON file with resume capability
|
|
||||||
- `--resume FILE` / `-r FILE` — Resume from previous JSON file
|
|
||||||
- `--progress` — Show progress during fetch
|
|
||||||
|
|
||||||
### Advanced
|
|
||||||
- `--set KEY=VALUE` — Set gallery-dl extractor options (repeatable)
|
|
||||||
- `-v` / `--verbose` — Show detailed metadata during fetch
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Usage Examples
|
|
||||||
|
|
||||||
### Basic Fetch
|
|
||||||
|
|
||||||
```powershell
|
|
||||||
# Guest mode (no auth)
|
|
||||||
python twitter_cli.py https://x.com/username/media --limit 10 --json --guest
|
|
||||||
|
|
||||||
# With authentication
|
|
||||||
python twitter_cli.py https://x.com/username/media --limit 10 --json --auth-token YOUR_TOKEN
|
|
||||||
```
|
|
||||||
|
|
||||||
### Media Type Filtering
|
|
||||||
|
|
||||||
```powershell
|
|
||||||
# Photos only
|
|
||||||
python twitter_cli.py https://x.com/username/media --type photo --json --guest
|
|
||||||
|
|
||||||
# Videos only
|
|
||||||
python twitter_cli.py https://x.com/username/media --type video --json --guest
|
|
||||||
|
|
||||||
# Animated GIFs only
|
|
||||||
python twitter_cli.py https://x.com/username/media --type animated_gif --json --guest
|
|
||||||
```
|
|
||||||
|
|
||||||
### With Metadata
|
|
||||||
|
|
||||||
```powershell
|
|
||||||
# Include tweet metadata (author, date, counts)
|
|
||||||
python twitter_cli.py https://x.com/username/media --limit 5 --json --metadata --guest
|
|
||||||
```
|
|
||||||
|
|
||||||
### Retweets Control
|
|
||||||
|
|
||||||
```powershell
|
|
||||||
# Skip retweets (default)
|
|
||||||
python twitter_cli.py https://x.com/username/timeline --retweets skip --json --guest
|
|
||||||
|
|
||||||
# Include retweets
|
|
||||||
python twitter_cli.py https://x.com/username/timeline --retweets include --json --guest
|
|
||||||
|
|
||||||
# Get original tweet from retweets
|
|
||||||
python twitter_cli.py https://x.com/username/timeline --retweets original --json --guest
|
|
||||||
```
|
|
||||||
|
|
||||||
### Save & Resume
|
|
||||||
|
|
||||||
```powershell
|
|
||||||
# Save to file (with resume capability)
|
|
||||||
python twitter_cli.py https://x.com/username/media --limit 100 --output results.json --progress --guest
|
|
||||||
|
|
||||||
# Resume from saved file
|
|
||||||
python twitter_cli.py https://x.com/username/media --resume results.json --limit 100 --output results.json --guest
|
|
||||||
|
|
||||||
# Fetch all remaining
|
|
||||||
python twitter_cli.py https://x.com/username/media --resume results.json --limit 0 --output results.json --guest
|
|
||||||
```
|
|
||||||
|
|
||||||
### Private Content (Requires Auth)
|
|
||||||
|
|
||||||
```powershell
|
|
||||||
# Your likes
|
|
||||||
python twitter_cli.py https://x.com/username/likes --limit 20 --json --auth-token YOUR_TOKEN
|
|
||||||
|
|
||||||
# Your bookmarks
|
|
||||||
python twitter_cli.py https://x.com/i/bookmarks --limit 20 --json --auth-token YOUR_TOKEN
|
|
||||||
```
|
|
||||||
|
|
||||||
### Search
|
|
||||||
|
|
||||||
```powershell
|
|
||||||
# Search with filters
|
|
||||||
python twitter_cli.py "https://x.com/search?q=from:username filter:media" --limit 50 --json --guest
|
|
||||||
|
|
||||||
# Date range search
|
|
||||||
python twitter_cli.py "https://x.com/search?q=from:username since:2024-01-01 until:2024-12-31" --json --guest
|
|
||||||
```
|
|
||||||
|
|
||||||
### Advanced Filtering
|
|
||||||
|
|
||||||
```powershell
|
|
||||||
# Filter by date (2024 only)
|
|
||||||
python twitter_cli.py https://x.com/username/media --json --metadata --set filter="date.year == 2024" --guest
|
|
||||||
|
|
||||||
# Filter by engagement (>1000 likes)
|
|
||||||
python twitter_cli.py https://x.com/username/media --json --metadata --set filter="favorite_count > 1000" --guest
|
|
||||||
|
|
||||||
# Combine filters (photos from 2024 with >100 likes)
|
|
||||||
python twitter_cli.py https://x.com/username/media --type photo --json --metadata --set filter="date.year == 2024 and favorite_count > 100" --guest
|
|
||||||
```
|
|
||||||
|
|
||||||
### Text-Only Tweets
|
|
||||||
|
|
||||||
```powershell
|
|
||||||
# Fetch tweets without media
|
|
||||||
python twitter_cli.py https://x.com/username/tweets --text-tweets --json --metadata --guest
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Output Format
|
|
||||||
|
|
||||||
### JSON Structure
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"media": [
|
|
||||||
{
|
|
||||||
"url": "https://pbs.twimg.com/media/...",
|
|
||||||
"tweet_id": 1234567890,
|
|
||||||
"extension": "jpg",
|
|
||||||
"width": 2048,
|
|
||||||
"height": 1536,
|
|
||||||
"type": "photo"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"metadata": [
|
|
||||||
{
|
|
||||||
"tweet_id": 1234567890,
|
|
||||||
"date": "2024-01-15T10:30:00+00:00",
|
|
||||||
"author": {
|
|
||||||
"id": 123456,
|
|
||||||
"name": "username",
|
|
||||||
"nick": "Display Name"
|
|
||||||
},
|
|
||||||
"content": "Tweet text content",
|
|
||||||
"favorite_count": 150,
|
|
||||||
"retweet_count": 25,
|
|
||||||
"reply_count": 5,
|
|
||||||
"view_count": 5000
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"cursor": "1/DAABCgABG7OZH1D___0KAAIW...",
|
|
||||||
"total": 100,
|
|
||||||
"completed": false
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### Resume File Structure
|
|
||||||
|
|
||||||
When using `--output`, the file includes:
|
|
||||||
- `url` — Original URL
|
|
||||||
- `cursor` — Position for resume
|
|
||||||
- `total` — Total items fetched
|
|
||||||
- `completed` — Whether fetch is complete
|
|
||||||
- `media` — All media items
|
|
||||||
- `metadata` — All metadata (if requested)
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Pagination & Resume
|
|
||||||
|
|
||||||
### How It Works
|
|
||||||
|
|
||||||
- Twitter API returns ~100-200 items per batch
|
|
||||||
- Cursor tracks position for next fetch
|
|
||||||
- System ensures cursor availability before stopping
|
|
||||||
- Resume continues from exact position (no duplicates)
|
|
||||||
|
|
||||||
### Resume Workflow
|
|
||||||
|
|
||||||
```powershell
|
|
||||||
# Step 1: Initial fetch (saves state)
|
|
||||||
python twitter_cli.py https://x.com/user/media --limit 100 --output data.json --progress --guest
|
|
||||||
# Output: Saved 202 media to data.json [partial (can resume)]
|
|
||||||
|
|
||||||
# Step 2: Resume and fetch more
|
|
||||||
python twitter_cli.py https://x.com/user/media --resume data.json --limit 100 --output data.json --guest
|
|
||||||
# Output: Resuming from cursor, 202 media already fetched
|
|
||||||
# Added 100 new media (total: 302)
|
|
||||||
|
|
||||||
# Step 3: Fetch all remaining
|
|
||||||
python twitter_cli.py https://x.com/user/media --resume data.json --limit 0 --output data.json --guest
|
|
||||||
# Output: Added 244 new media (total: 546) [completed]
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Supported URL Patterns
|
|
||||||
|
|
||||||
### User Timelines
|
|
||||||
- `https://x.com/username/media` — Media timeline
|
|
||||||
- `https://x.com/username/timeline` — Full timeline
|
|
||||||
- `https://x.com/username/tweets` — Tweets only
|
|
||||||
- `https://x.com/username/with_replies` — With replies
|
|
||||||
- `https://x.com/username/likes` — Liked tweets (requires auth)
|
|
||||||
|
|
||||||
### Private Content
|
|
||||||
- `https://x.com/i/bookmarks` — Your bookmarks (requires auth)
|
|
||||||
|
|
||||||
### Search
|
|
||||||
- `https://x.com/search?q=QUERY` — Search tweets
|
|
||||||
- `https://x.com/hashtag/NAME` — Hashtag search
|
|
||||||
|
|
||||||
### Individual Tweet
|
|
||||||
- `https://x.com/username/status/1234567890` — Single tweet
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Search Operators
|
|
||||||
|
|
||||||
Use in search URLs:
|
|
||||||
|
|
||||||
| Operator | Example | Description |
|
|
||||||
|----------|---------|-------------|
|
|
||||||
| `from:USER` | `from:username` | Tweets from user |
|
|
||||||
| `to:USER` | `to:username` | Tweets mentioning user |
|
|
||||||
| `filter:media` | `cats filter:media` | Only with media |
|
|
||||||
| `filter:images` | `cats filter:images` | Only images |
|
|
||||||
| `filter:videos` | `cats filter:videos` | Only videos |
|
|
||||||
| `since:DATE` | `since:2024-01-01` | After date |
|
|
||||||
| `until:DATE` | `until:2024-12-31` | Before date |
|
|
||||||
| `-filter:retweets` | `cats -filter:retweets` | Exclude retweets |
|
|
||||||
| `min_faves:N` | `min_faves:1000` | Min likes |
|
|
||||||
| `min_retweets:N` | `min_retweets:100` | Min retweets |
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Authentication
|
|
||||||
|
|
||||||
### Getting Your Auth Token
|
|
||||||
|
|
||||||
1. Open Twitter/X in your browser
|
|
||||||
2. Open Developer Tools (F12)
|
|
||||||
3. Go to Application/Storage → Cookies
|
|
||||||
4. Find cookie named `auth_token`
|
|
||||||
5. Copy its value
|
|
||||||
|
|
||||||
### Security Notes
|
|
||||||
|
|
||||||
- Use a dummy/secondary account for scraping
|
|
||||||
- Don't share your auth token
|
|
||||||
- Excessive usage may cause account suspension
|
|
||||||
- Guest mode has stricter rate limits
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Rate Limits
|
|
||||||
|
|
||||||
- **Guest mode**: Lower limits, may hit rate limit faster
|
|
||||||
- **Authenticated**: Higher limits but still restricted
|
|
||||||
- **Rate limit hit**: Script will wait and retry automatically
|
|
||||||
- **Best practice**: Use `--limit` to control fetch size
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Tips & Tricks
|
|
||||||
|
|
||||||
### 1. Progressive Fetch with Resume
|
|
||||||
```powershell
|
|
||||||
# Fetch in batches to avoid long waits
|
|
||||||
python twitter_cli.py URL --limit 200 --output data.json --progress --guest
|
|
||||||
python twitter_cli.py URL --resume data.json --limit 200 --output data.json --guest
|
|
||||||
```
|
|
||||||
|
|
||||||
### 2. Combine Type Filter with Custom Filter
|
|
||||||
```powershell
|
|
||||||
# Photos from 2024 with high engagement
|
|
||||||
python twitter_cli.py URL --type photo --metadata --set filter="date.year == 2024 and favorite_count > 500" --json --guest
|
|
||||||
```
|
|
||||||
|
|
||||||
### 3. Use Progress Flag for Long Fetches
|
|
||||||
```powershell
|
|
||||||
python twitter_cli.py URL --limit 1000 --progress --output data.json --guest
|
|
||||||
```
|
|
||||||
|
|
||||||
### 4. Check Cursor Availability
|
|
||||||
- If `completed: false` in output → can resume
|
|
||||||
- If `completed: true` → all data fetched
|
|
||||||
- If `cursor: null` → no more data available
|
|
||||||
@@ -1,309 +0,0 @@
|
|||||||
"""Command-line helper for gallery-dl's Twitter extractor.
|
|
||||||
|
|
||||||
Features:
|
|
||||||
- Cursor-based resume: Use --output to save progress, --resume to continue
|
|
||||||
- Progress tracking: See fetch progress in real-time
|
|
||||||
- Rate limit: Automatically handled by gallery-dl
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import argparse
|
|
||||||
import json
|
|
||||||
import os
|
|
||||||
import sys
|
|
||||||
from typing import Dict, List, Optional
|
|
||||||
|
|
||||||
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
|
|
||||||
|
|
||||||
from twitter_common import ( # type: ignore
|
|
||||||
TwitterRequest,
|
|
||||||
coerce_literal,
|
|
||||||
load_resume_state,
|
|
||||||
merge_options,
|
|
||||||
run_request_dict,
|
|
||||||
save_state,
|
|
||||||
)
|
|
||||||
|
|
||||||
DEFAULT_AUTH_TOKEN = ""
|
|
||||||
|
|
||||||
|
|
||||||
def parse_args() -> argparse.Namespace:
|
|
||||||
parser = argparse.ArgumentParser(
|
|
||||||
description="Light-weight CLI wrapper around gallery-dl's Twitter extractor",
|
|
||||||
)
|
|
||||||
parser.add_argument("url", help="Any supported Twitter/X URL (timeline, media, likes, ...)")
|
|
||||||
parser.add_argument(
|
|
||||||
"--auth-token",
|
|
||||||
default=DEFAULT_AUTH_TOKEN,
|
|
||||||
help="Value of the auth_token cookie (leave empty to skip)",
|
|
||||||
)
|
|
||||||
parser.add_argument(
|
|
||||||
"--guest",
|
|
||||||
action="store_true",
|
|
||||||
help="Force guest mode (do not send auth_token)",
|
|
||||||
)
|
|
||||||
parser.add_argument(
|
|
||||||
"--retweets",
|
|
||||||
choices=["skip", "include", "original"],
|
|
||||||
default="skip",
|
|
||||||
help="Control retweet handling (skip, include, or swap for originals)",
|
|
||||||
)
|
|
||||||
parser.add_argument(
|
|
||||||
"--no-videos",
|
|
||||||
action="store_true",
|
|
||||||
help="Skip video/animated GIF variants",
|
|
||||||
)
|
|
||||||
parser.add_argument(
|
|
||||||
"--size",
|
|
||||||
default="orig",
|
|
||||||
help="Image size to request (orig, 4096x4096, large, ...)",
|
|
||||||
)
|
|
||||||
parser.add_argument(
|
|
||||||
"--limit",
|
|
||||||
type=int,
|
|
||||||
default=0,
|
|
||||||
help="Stop after N media files (0 = all)",
|
|
||||||
)
|
|
||||||
parser.add_argument(
|
|
||||||
"--json",
|
|
||||||
action="store_true",
|
|
||||||
help="Emit JSON instead of plain URLs",
|
|
||||||
)
|
|
||||||
parser.add_argument(
|
|
||||||
"--metadata",
|
|
||||||
action="store_true",
|
|
||||||
help="Include tweet metadata in output",
|
|
||||||
)
|
|
||||||
parser.add_argument(
|
|
||||||
"--text-tweets",
|
|
||||||
action="store_true",
|
|
||||||
help="Include text tweets (without media)",
|
|
||||||
)
|
|
||||||
parser.add_argument(
|
|
||||||
"--type",
|
|
||||||
choices=["photo", "video", "animated_gif", "all"],
|
|
||||||
default="all",
|
|
||||||
help="Filter by media type (photo, video, animated_gif, or all)",
|
|
||||||
)
|
|
||||||
parser.add_argument(
|
|
||||||
"--verbose",
|
|
||||||
"-v",
|
|
||||||
action="store_true",
|
|
||||||
help="Echo tweet metadata to stderr while crawling",
|
|
||||||
)
|
|
||||||
parser.add_argument(
|
|
||||||
"--set",
|
|
||||||
metavar="KEY=VALUE",
|
|
||||||
action="append",
|
|
||||||
default=[],
|
|
||||||
help="Add override for extractor.twitter.* options (repeatable)",
|
|
||||||
)
|
|
||||||
parser.add_argument(
|
|
||||||
"--output",
|
|
||||||
"-o",
|
|
||||||
metavar="FILE",
|
|
||||||
help="Save results to JSON file (includes cursor for resume)",
|
|
||||||
)
|
|
||||||
parser.add_argument(
|
|
||||||
"--resume",
|
|
||||||
"-r",
|
|
||||||
metavar="FILE",
|
|
||||||
help="Resume from previous JSON file (continues from saved cursor)",
|
|
||||||
)
|
|
||||||
parser.add_argument(
|
|
||||||
"--cursor",
|
|
||||||
metavar="CURSOR",
|
|
||||||
help="Resume from specific cursor position",
|
|
||||||
)
|
|
||||||
parser.add_argument(
|
|
||||||
"--progress",
|
|
||||||
action="store_true",
|
|
||||||
help="Show progress during fetch",
|
|
||||||
)
|
|
||||||
return parser.parse_args()
|
|
||||||
|
|
||||||
|
|
||||||
def _retweets_value(mode: str):
|
|
||||||
if mode == "original":
|
|
||||||
return "original"
|
|
||||||
if mode == "include":
|
|
||||||
return True
|
|
||||||
return False
|
|
||||||
|
|
||||||
|
|
||||||
def _parse_overrides(entries: List[str]) -> Dict[str, object]:
|
|
||||||
overrides: Dict[str, object] = {}
|
|
||||||
for entry in entries:
|
|
||||||
if "=" not in entry:
|
|
||||||
raise ValueError(f"Format must be KEY=VALUE, got: {entry}")
|
|
||||||
key, raw = entry.split("=", 1)
|
|
||||||
overrides[key.strip()] = coerce_literal(raw.strip())
|
|
||||||
return overrides
|
|
||||||
|
|
||||||
|
|
||||||
def _progress_callback(count: int, cursor: Optional[str]) -> None:
|
|
||||||
"""Print progress to stderr."""
|
|
||||||
cursor_info = f" (cursor: {cursor[:20]}...)" if cursor and len(cursor) > 20 else ""
|
|
||||||
cursor_info = f" (cursor: {cursor})" if cursor and len(cursor) <= 20 else cursor_info
|
|
||||||
print(f"Fetching... {count} media{cursor_info}", file=sys.stderr)
|
|
||||||
|
|
||||||
|
|
||||||
def main() -> None:
|
|
||||||
args = parse_args()
|
|
||||||
|
|
||||||
# Handle resume from file
|
|
||||||
resume_cursor: Optional[str] = None
|
|
||||||
previous_media: List[Dict] = []
|
|
||||||
previous_metadata: List[Dict] = []
|
|
||||||
seen_urls: set = set()
|
|
||||||
url = args.url
|
|
||||||
|
|
||||||
# Convert --type to filter expression
|
|
||||||
type_filter = None
|
|
||||||
if args.type != "all":
|
|
||||||
type_filter = f"type == '{args.type}'"
|
|
||||||
|
|
||||||
if args.resume:
|
|
||||||
state = load_resume_state(args.resume)
|
|
||||||
if state:
|
|
||||||
if state.get("completed"):
|
|
||||||
print(f"Previous fetch already completed ({state.get('total', 0)} media)", file=sys.stderr)
|
|
||||||
print("Use --output to start fresh or remove the file", file=sys.stderr)
|
|
||||||
sys.exit(0)
|
|
||||||
resume_cursor = state.get("cursor")
|
|
||||||
previous_media = state.get("media", [])
|
|
||||||
previous_metadata = state.get("metadata", [])
|
|
||||||
# Track seen URLs to avoid duplicates
|
|
||||||
seen_urls = {m.get("url") for m in previous_media if m.get("url")}
|
|
||||||
url = state.get("url", args.url)
|
|
||||||
|
|
||||||
if resume_cursor:
|
|
||||||
print(f"Resuming from cursor, {len(previous_media)} media already fetched", file=sys.stderr)
|
|
||||||
else:
|
|
||||||
print(f"No cursor available, will deduplicate {len(previous_media)} existing media", file=sys.stderr)
|
|
||||||
else:
|
|
||||||
print(f"Could not load resume file: {args.resume}", file=sys.stderr)
|
|
||||||
sys.exit(1)
|
|
||||||
|
|
||||||
# Manual cursor override
|
|
||||||
if args.cursor:
|
|
||||||
resume_cursor = args.cursor
|
|
||||||
|
|
||||||
include_videos = not args.no_videos
|
|
||||||
auth_token = None if args.guest or not args.auth_token.strip() else args.auth_token
|
|
||||||
|
|
||||||
# Parse user overrides
|
|
||||||
user_overrides = _parse_overrides(args.set)
|
|
||||||
|
|
||||||
# Add type filter if specified (merge with existing filter if any)
|
|
||||||
if type_filter:
|
|
||||||
existing_filter = user_overrides.get("filter")
|
|
||||||
if existing_filter:
|
|
||||||
# Combine with AND
|
|
||||||
user_overrides["filter"] = f"({existing_filter}) and ({type_filter})"
|
|
||||||
else:
|
|
||||||
user_overrides["filter"] = type_filter
|
|
||||||
|
|
||||||
options = merge_options(
|
|
||||||
{
|
|
||||||
"auth_token": auth_token,
|
|
||||||
"retweets": _retweets_value(args.retweets),
|
|
||||||
"videos": include_videos,
|
|
||||||
"size": args.size,
|
|
||||||
"text-tweets": args.text_tweets,
|
|
||||||
},
|
|
||||||
user_overrides,
|
|
||||||
)
|
|
||||||
|
|
||||||
request = TwitterRequest(
|
|
||||||
url=url,
|
|
||||||
limit=args.limit,
|
|
||||||
metadata=(args.metadata or args.verbose),
|
|
||||||
options=options,
|
|
||||||
cursor=resume_cursor,
|
|
||||||
)
|
|
||||||
|
|
||||||
progress_cb = _progress_callback if (args.progress or args.verbose) else None
|
|
||||||
|
|
||||||
# Pass seen_urls for deduplication if no cursor available
|
|
||||||
skip_urls = seen_urls if (not resume_cursor and seen_urls) else None
|
|
||||||
|
|
||||||
try:
|
|
||||||
result = run_request_dict(request, on_progress=progress_cb, skip_urls=skip_urls)
|
|
||||||
except KeyboardInterrupt:
|
|
||||||
print("\nInterrupted by user", file=sys.stderr)
|
|
||||||
sys.exit(130)
|
|
||||||
except Exception as exc:
|
|
||||||
print(f"Error: {exc}", file=sys.stderr)
|
|
||||||
sys.exit(1)
|
|
||||||
|
|
||||||
# Merge with previous results if resuming
|
|
||||||
if previous_media:
|
|
||||||
if resume_cursor:
|
|
||||||
# With cursor: filter duplicates that might occur at boundary
|
|
||||||
new_media = [m for m in result["media"] if m.get("url") not in seen_urls]
|
|
||||||
result["media"] = previous_media + new_media
|
|
||||||
result["metadata"] = previous_metadata + result["metadata"]
|
|
||||||
else:
|
|
||||||
# Without cursor: results already deduplicated via skip_urls
|
|
||||||
result["media"] = previous_media + result["media"]
|
|
||||||
result["metadata"] = previous_metadata + result["metadata"]
|
|
||||||
|
|
||||||
result["total"] = len(result["media"])
|
|
||||||
new_count = result["total"] - len(previous_media)
|
|
||||||
|
|
||||||
if new_count > 0:
|
|
||||||
print(f"Added {new_count} new media (total: {result['total']})", file=sys.stderr)
|
|
||||||
else:
|
|
||||||
print(f"No new media found", file=sys.stderr)
|
|
||||||
|
|
||||||
media = result["media"]
|
|
||||||
metadata = result["metadata"]
|
|
||||||
|
|
||||||
# Save to file if --output specified
|
|
||||||
if args.output:
|
|
||||||
save_state(args.output, result, url)
|
|
||||||
status = "completed" if result.get("completed") else "partial (can resume)"
|
|
||||||
print(f"Saved {len(media)} media to {args.output} [{status}]", file=sys.stderr)
|
|
||||||
if not result.get("completed") and result.get("cursor"):
|
|
||||||
print(f"Resume with: --resume {args.output}", file=sys.stderr)
|
|
||||||
|
|
||||||
if args.verbose:
|
|
||||||
for entry in metadata:
|
|
||||||
author = (entry.get("author") or {}).get("name")
|
|
||||||
print(
|
|
||||||
f"Processing tweet {entry.get('tweet_id')} / {author}",
|
|
||||||
file=sys.stderr,
|
|
||||||
)
|
|
||||||
|
|
||||||
if args.json:
|
|
||||||
payload: Dict[str, object] = {
|
|
||||||
"media": media,
|
|
||||||
"total": len(media),
|
|
||||||
"completed": result.get("completed", True),
|
|
||||||
}
|
|
||||||
if result.get("cursor"):
|
|
||||||
payload["cursor"] = result["cursor"]
|
|
||||||
if args.metadata:
|
|
||||||
payload["metadata"] = metadata
|
|
||||||
print(json.dumps(payload, indent=2, default=str))
|
|
||||||
else:
|
|
||||||
for item in media:
|
|
||||||
print(item["url"])
|
|
||||||
if args.metadata:
|
|
||||||
print("\n# Metadata", file=sys.stderr)
|
|
||||||
for entry in metadata:
|
|
||||||
print(
|
|
||||||
f"{entry['tweet_id']}: {entry['content']}",
|
|
||||||
file=sys.stderr,
|
|
||||||
)
|
|
||||||
|
|
||||||
# Print summary
|
|
||||||
print(f"\nTotal: {len(media)} media", file=sys.stderr)
|
|
||||||
if not result.get("completed") and result.get("cursor"):
|
|
||||||
print(f"Cursor for resume: {result['cursor']}", file=sys.stderr)
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
main()
|
|
||||||
Loaded 100 of 104 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user