mirror of
https://github.com/Alvin-Zilverstand/Twitter-X-Media-Batch-Downloader.git
synced 2026-11-24 23:33:11 +01:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2ada5da9bf | ||
|
|
3fb8bda2ff | ||
|
|
b4dfb75f5b | ||
|
|
7e584aff2c | ||
|
|
76acb6f5e1 | ||
|
|
6bd03678f8 | ||
|
|
e400df6ea7 | ||
|
|
52ffa5ba17 | ||
|
|
c42808431c | ||
|
|
e05a9379fc | ||
|
|
33be717065 | ||
|
|
c3ae949a38 |
No files matched your search
@@ -15,7 +15,7 @@ body:
|
|||||||
id: problem
|
id: problem
|
||||||
attributes:
|
attributes:
|
||||||
label: Problem
|
label: Problem
|
||||||
placeholder: e.g. Fetching @username/media stops after a few items, or GIF conversion fails with no clear error.
|
placeholder: "e.g. Fetching @username/media stops after a few items, or GIF conversion fails with no clear error."
|
||||||
validations:
|
validations:
|
||||||
required: true
|
required: true
|
||||||
|
|
||||||
@@ -23,7 +23,7 @@ body:
|
|||||||
id: target
|
id: target
|
||||||
attributes:
|
attributes:
|
||||||
label: X/Twitter URL or Username
|
label: X/Twitter URL or Username
|
||||||
placeholder: e.g. https://x.com/username/media or @username
|
placeholder: "e.g. https://x.com/username/media or @username"
|
||||||
validations:
|
validations:
|
||||||
required: true
|
required: true
|
||||||
|
|
||||||
@@ -43,7 +43,7 @@ body:
|
|||||||
id: logs
|
id: logs
|
||||||
attributes:
|
attributes:
|
||||||
label: Error Message / Logs / Screenshot
|
label: Error Message / Logs / Screenshot
|
||||||
placeholder: e.g. failed to extract timeline: parse_error ...
|
placeholder: "e.g. failed to extract timeline: parse_error ..."
|
||||||
validations:
|
validations:
|
||||||
required: true
|
required: true
|
||||||
|
|
||||||
@@ -55,7 +55,7 @@ body:
|
|||||||
id: version
|
id: version
|
||||||
attributes:
|
attributes:
|
||||||
label: Twitter/X Media Batch Downloader Version
|
label: Twitter/X Media Batch Downloader Version
|
||||||
placeholder: e.g. v4.4
|
placeholder: "e.g. v4.4"
|
||||||
validations:
|
validations:
|
||||||
required: true
|
required: true
|
||||||
|
|
||||||
@@ -63,6 +63,6 @@ body:
|
|||||||
id: os
|
id: os
|
||||||
attributes:
|
attributes:
|
||||||
label: OS
|
label: OS
|
||||||
placeholder: e.g. Windows 11 23H2
|
placeholder: "e.g. Windows 11 23H2"
|
||||||
validations:
|
validations:
|
||||||
required: true
|
required: true
|
||||||
+39
-11
@@ -151,8 +151,28 @@ jobs:
|
|||||||
retention-days: 7
|
retention-days: 7
|
||||||
|
|
||||||
build-linux:
|
build-linux:
|
||||||
name: Build Linux
|
name: Build Linux (${{ matrix.display_name }})
|
||||||
runs-on: ubuntu-24.04
|
runs-on: ${{ matrix.runner }}
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
include:
|
||||||
|
- display_name: amd64
|
||||||
|
runner: ubuntu-24.04
|
||||||
|
wails_platform: linux/amd64
|
||||||
|
artifact_name: linux-portable
|
||||||
|
output_name: TwitterXMediaBatchDownloader.AppImage
|
||||||
|
appimage_arch: x86_64
|
||||||
|
appimagetool_arch: x86_64
|
||||||
|
pkgconfig_dir: /usr/lib/x86_64-linux-gnu/pkgconfig
|
||||||
|
- display_name: arm64
|
||||||
|
runner: ubuntu-24.04-arm
|
||||||
|
wails_platform: linux/arm64
|
||||||
|
artifact_name: linux-portable-arm
|
||||||
|
output_name: TwitterXMediaBatchDownloader-ARM.AppImage
|
||||||
|
appimage_arch: aarch64
|
||||||
|
appimagetool_arch: aarch64
|
||||||
|
pkgconfig_dir: /usr/lib/aarch64-linux-gnu/pkgconfig
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout code
|
- name: Checkout code
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
@@ -189,7 +209,7 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
sudo apt-get update
|
sudo apt-get update
|
||||||
sudo apt-get install -y libgtk-3-dev libwebkit2gtk-4.1-dev libfuse2 imagemagick upx-ucl
|
sudo apt-get install -y libgtk-3-dev libwebkit2gtk-4.1-dev libfuse2 imagemagick upx-ucl
|
||||||
sudo ln -sf /usr/lib/x86_64-linux-gnu/pkgconfig/webkit2gtk-4.1.pc /usr/lib/x86_64-linux-gnu/pkgconfig/webkit2gtk-4.0.pc
|
sudo ln -sf "${{ matrix.pkgconfig_dir }}/webkit2gtk-4.1.pc" "${{ matrix.pkgconfig_dir }}/webkit2gtk-4.0.pc"
|
||||||
|
|
||||||
- name: Install Wails CLI
|
- name: Install Wails CLI
|
||||||
run: go install github.com/wailsapp/wails/v2/cmd/wails@latest
|
run: go install github.com/wailsapp/wails/v2/cmd/wails@latest
|
||||||
@@ -201,7 +221,7 @@ jobs:
|
|||||||
pnpm run generate-icon
|
pnpm run generate-icon
|
||||||
|
|
||||||
- name: Build application
|
- name: Build application
|
||||||
run: wails build -platform linux/amd64
|
run: wails build -platform ${{ matrix.wails_platform }}
|
||||||
|
|
||||||
- name: Compress with UPX
|
- name: Compress with UPX
|
||||||
run: upx --best --lzma "build/bin/${{ env.APP_NAME }}"
|
run: upx --best --lzma "build/bin/${{ env.APP_NAME }}"
|
||||||
@@ -211,13 +231,13 @@ jobs:
|
|||||||
uses: actions/cache@v4
|
uses: actions/cache@v4
|
||||||
with:
|
with:
|
||||||
path: appimagetool
|
path: appimagetool
|
||||||
key: appimagetool-x86_64-v2
|
key: appimagetool-${{ matrix.appimagetool_arch }}-v2
|
||||||
|
|
||||||
- name: Download appimagetool
|
- name: Download appimagetool
|
||||||
if: steps.cache-appimagetool.outputs.cache-hit != 'true'
|
if: steps.cache-appimagetool.outputs.cache-hit != 'true'
|
||||||
run: |
|
run: |
|
||||||
wget --timeout=30 --tries=5 --retry-connrefused --waitretry=5 -O appimagetool "https://github.com/AppImage/appimagetool/releases/download/continuous/appimagetool-x86_64.AppImage" || \
|
wget --timeout=30 --tries=5 --retry-connrefused --waitretry=5 -O appimagetool "https://github.com/AppImage/appimagetool/releases/download/continuous/appimagetool-${{ matrix.appimagetool_arch }}.AppImage" || \
|
||||||
wget --timeout=30 --tries=5 --retry-connrefused --waitretry=5 -O appimagetool "https://github.com/AppImage/appimagetool/releases/download/1.9.1/appimagetool-x86_64.AppImage"
|
wget --timeout=30 --tries=5 --retry-connrefused --waitretry=5 -O appimagetool "https://github.com/AppImage/appimagetool/releases/download/1.9.1/appimagetool-${{ matrix.appimagetool_arch }}.AppImage"
|
||||||
|
|
||||||
- name: Make appimagetool executable
|
- name: Make appimagetool executable
|
||||||
run: chmod +x appimagetool
|
run: chmod +x appimagetool
|
||||||
@@ -266,13 +286,13 @@ jobs:
|
|||||||
chmod +x AppDir/AppRun
|
chmod +x AppDir/AppRun
|
||||||
|
|
||||||
mkdir -p dist
|
mkdir -p dist
|
||||||
ARCH=x86_64 ./appimagetool --no-appstream AppDir "dist/${{ env.APP_NAME }}.AppImage"
|
ARCH=${{ matrix.appimage_arch }} ./appimagetool --no-appstream AppDir "dist/${{ matrix.output_name }}"
|
||||||
|
|
||||||
- name: Upload artifacts
|
- name: Upload artifacts
|
||||||
uses: actions/upload-artifact@v4
|
uses: actions/upload-artifact@v4
|
||||||
with:
|
with:
|
||||||
name: linux-portable
|
name: ${{ matrix.artifact_name }}
|
||||||
path: dist/${{ env.APP_NAME }}.AppImage
|
path: dist/${{ matrix.output_name }}
|
||||||
retention-days: 7
|
retention-days: 7
|
||||||
|
|
||||||
create-release:
|
create-release:
|
||||||
@@ -307,7 +327,8 @@ jobs:
|
|||||||
|
|
||||||
- `TwitterXMediaBatchDownloader.exe` - Windows
|
- `TwitterXMediaBatchDownloader.exe` - Windows
|
||||||
- `TwitterXMediaBatchDownloader.dmg` - macOS
|
- `TwitterXMediaBatchDownloader.dmg` - macOS
|
||||||
- `TwitterXMediaBatchDownloader.AppImage` - Linux
|
- `TwitterXMediaBatchDownloader.AppImage` - Linux AMD64
|
||||||
|
- `TwitterXMediaBatchDownloader-ARM.AppImage` - Linux ARM64
|
||||||
|
|
||||||
<details>
|
<details>
|
||||||
<summary><b>Linux Requirements</b></summary>
|
<summary><b>Linux Requirements</b></summary>
|
||||||
@@ -335,10 +356,17 @@ jobs:
|
|||||||
./TwitterXMediaBatchDownloader.AppImage
|
./TwitterXMediaBatchDownloader.AppImage
|
||||||
```
|
```
|
||||||
|
|
||||||
|
For ARM64:
|
||||||
|
```bash
|
||||||
|
chmod +x TwitterXMediaBatchDownloader-ARM.AppImage
|
||||||
|
./TwitterXMediaBatchDownloader-ARM.AppImage
|
||||||
|
```
|
||||||
|
|
||||||
</details>
|
</details>
|
||||||
files: |
|
files: |
|
||||||
artifacts/windows-portable/${{ env.APP_NAME }}.exe
|
artifacts/windows-portable/${{ env.APP_NAME }}.exe
|
||||||
artifacts/macos-portable/${{ env.APP_NAME }}.dmg
|
artifacts/macos-portable/${{ env.APP_NAME }}.dmg
|
||||||
artifacts/linux-portable/${{ env.APP_NAME }}.AppImage
|
artifacts/linux-portable/${{ env.APP_NAME }}.AppImage
|
||||||
|
artifacts/linux-portable-arm/${{ env.APP_NAME }}-ARM.AppImage
|
||||||
env:
|
env:
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
@@ -1,19 +1,36 @@
|
|||||||
# Twitter/X Media Batch Downloader
|
<div align="left">
|
||||||
|
<h1>Twitter/X Media Batch Downloader</h1>
|
||||||
A GUI tool to download original-quality images and videos from Twitter/X accounts.
|
<p>
|
||||||
|
Downloads original-quality images and videos from Twitter/X accounts.
|
||||||

|
</p>
|
||||||

|
<p>
|
||||||

|
<a href="https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/stargazers"><img
|
||||||
|
src="https://img.shields.io/github/stars/afkarxyz/Twitter-X-Media-Batch-Downloader?color=ffcb47&labelColor=black&logo=github&label=Stars" /></a><a
|
||||||
|
href="https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases"><img
|
||||||
|
src="https://img.shields.io/github/downloads/afkarxyz/Twitter-X-Media-Batch-Downloader/total?color=22c55e&labelColor=black&logo=github&label=Downloads" /></a><a
|
||||||
|
href="https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases/latest"><img
|
||||||
|
src="https://img.shields.io/github/v/release/afkarxyz/Twitter-X-Media-Batch-Downloader?color=8b5cf6&labelColor=black&logo=github&label=Latest%20Release" /></a><a
|
||||||
|
href="https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases/latest"><img
|
||||||
|
src="https://img.shields.io/badge/Windows-10%2B-369eff?labelColor=black&logo=data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI1MTIiIGhlaWdodD0iNTEyIiB2aWV3Qm94PSIwIDAgMjAgMjAiPjxwYXRoIGZpbGw9IiNmZmZmZmYiIGZpbGwtcnVsZT0iZXZlbm9kZCIgZD0iTTIwIDEwLjg3M1YyMEw4LjQ3OSAxOC41MzdsLjAwMS03LjY2NEgyMFptLTEzLjEyIDBsLS4wMDEgNy40NjFMMCAxNy40NjF2LTYuNTg4aDYuODhaTTIwIDkuMjczSDguNDhsLS4wMDEtNy44MUwyMCAwdjkuMjczWk02Ljg3OSAxLjY2NmwuMDAxIDcuNjA3SDBWMi41MzlsNi44NzktLjg3M1oiLz48L3N2Zz4=" /></a><a
|
||||||
|
href="https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases/latest"><img
|
||||||
|
src="https://img.shields.io/badge/macOS-10.13%2B-FFFFFF?labelColor=black&logo=apple&logoColor=white" /></a><a
|
||||||
|
href="https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases/latest"><img
|
||||||
|
src="https://img.shields.io/badge/Linux-Any-FCC624?labelColor=black&logo=linux&logoColor=white" /></a>
|
||||||
|
<br />
|
||||||
|
<br />
|
||||||
|
<a href="https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases/latest" target="_blank"><img
|
||||||
|
src="https://github.com/user-attachments/assets/cef7b7e6-5a64-497a-91fe-b6fb549f3b09" alt="Twitter/X Media Batch Downloader" /></a>
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
### [Download](https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases)
|
### [Download](https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases)
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||
- If you're familiar with userscripts, install it [**here**](https://greasyfork.org/en/scripts/523157)
|
- If you're familiar with userscripts, install it [**here**](https://greasyfork.org/en/scripts/523157)
|
||||||
|
|
||||||
- To install the Chrome extension version, click [**here**](https://chromewebstore.google.com/detail/cboceolmgkoobpfjiojkigmihijfgmdo)
|
- To install the Chrome extension version, click [**here**](https://chromewebstore.google.com/detail/cboceolmgkoobpfjiojkigmihijfgmdo)
|
||||||
|
|
||||||
|
- Also available on the web at [**TwitterDL.app**](https://twitterdl.app)
|
||||||
|
|
||||||
## How to Obtain Auth Token
|
## How to Obtain Auth Token
|
||||||
|
|
||||||
> [!Warning]
|
> [!Warning]
|
||||||
@@ -22,8 +39,6 @@ A GUI tool to download original-quality images and videos from Twitter/X account
|
|||||||
> - Using an auth token or cookies has the potential to get the **account suspended.**
|
> - Using an auth token or cookies has the potential to get the **account suspended.**
|
||||||
> - If too many media files are fetched, it may trigger a **rate limit**, and the media retrieval will fail.
|
> - If too many media files are fetched, it may trigger a **rate limit**, and the media retrieval will fail.
|
||||||
|
|
||||||
### [Video Tutorial](https://www.patreon.com/posts/how-to-obtain-127206894)
|
|
||||||
|
|
||||||
1. Go to [Twitter's website](https://www.x.com/)
|
1. Go to [Twitter's website](https://www.x.com/)
|
||||||
2. Log into your account
|
2. Log into your account
|
||||||
3. Open the Developer Tools by pressing <kbd>F12</kbd>
|
3. Open the Developer Tools by pressing <kbd>F12</kbd>
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
"sync"
|
||||||
"twitterxmediabatchdownloader/backend"
|
"twitterxmediabatchdownloader/backend"
|
||||||
|
|
||||||
"github.com/wailsapp/wails/v2/pkg/runtime"
|
"github.com/wailsapp/wails/v2/pkg/runtime"
|
||||||
@@ -13,8 +14,9 @@ import (
|
|||||||
|
|
||||||
type App struct {
|
type App struct {
|
||||||
ctx context.Context
|
ctx context.Context
|
||||||
downloadCtx context.Context
|
downloadMu sync.Mutex
|
||||||
downloadCancel context.CancelFunc
|
downloadCancel context.CancelFunc
|
||||||
|
downloadActive bool
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewApp() *App {
|
func NewApp() *App {
|
||||||
@@ -42,14 +44,20 @@ func (a *App) CleanupExtractorProcesses() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type TimelineRequest struct {
|
type TimelineRequest struct {
|
||||||
Username string `json:"username"`
|
Username string `json:"username"`
|
||||||
AuthToken string `json:"auth_token"`
|
AuthToken string `json:"auth_token"`
|
||||||
TimelineType string `json:"timeline_type"`
|
TimelineType string `json:"timeline_type"`
|
||||||
BatchSize int `json:"batch_size"`
|
BatchSize int `json:"batch_size"`
|
||||||
Page int `json:"page"`
|
Page int `json:"page"`
|
||||||
MediaType string `json:"media_type"`
|
MediaType string `json:"media_type"`
|
||||||
Retweets bool `json:"retweets"`
|
Retweets bool `json:"retweets"`
|
||||||
Cursor string `json:"cursor,omitempty"`
|
Cursor string `json:"cursor,omitempty"`
|
||||||
|
IncludePhotos bool `json:"include_photos"`
|
||||||
|
IncludeVideos bool `json:"include_videos"`
|
||||||
|
IncludeGifs bool `json:"include_gifs"`
|
||||||
|
IncludeText bool `json:"include_text"`
|
||||||
|
VideoQuality string `json:"video_quality,omitempty"`
|
||||||
|
ImageSize string `json:"image_size,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type DateRangeRequest struct {
|
type DateRangeRequest struct {
|
||||||
@@ -71,14 +79,20 @@ func (a *App) ExtractTimeline(req TimelineRequest) (string, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
backendReq := backend.TimelineRequest{
|
backendReq := backend.TimelineRequest{
|
||||||
Username: req.Username,
|
Username: req.Username,
|
||||||
AuthToken: req.AuthToken,
|
AuthToken: req.AuthToken,
|
||||||
TimelineType: req.TimelineType,
|
TimelineType: req.TimelineType,
|
||||||
BatchSize: req.BatchSize,
|
BatchSize: req.BatchSize,
|
||||||
Page: req.Page,
|
Page: req.Page,
|
||||||
MediaType: req.MediaType,
|
MediaType: req.MediaType,
|
||||||
Retweets: req.Retweets,
|
Retweets: req.Retweets,
|
||||||
Cursor: req.Cursor,
|
Cursor: req.Cursor,
|
||||||
|
IncludePhotos: req.IncludePhotos,
|
||||||
|
IncludeVideos: req.IncludeVideos,
|
||||||
|
IncludeGifs: req.IncludeGifs,
|
||||||
|
IncludeText: req.IncludeText,
|
||||||
|
VideoQuality: req.VideoQuality,
|
||||||
|
ImageSize: req.ImageSize,
|
||||||
}
|
}
|
||||||
|
|
||||||
response, err := backend.ExtractTimeline(backendReq)
|
response, err := backend.ExtractTimeline(backendReq)
|
||||||
@@ -145,6 +159,29 @@ func (a *App) OpenFolder(path string) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type DownloadProfileImageRequest struct {
|
||||||
|
URL string `json:"url"`
|
||||||
|
OutputDir string `json:"output_dir"`
|
||||||
|
Username string `json:"username"`
|
||||||
|
Kind string `json:"kind"`
|
||||||
|
Proxy string `json:"proxy,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) DownloadProfileImage(req DownloadProfileImageRequest) (string, error) {
|
||||||
|
if req.URL == "" {
|
||||||
|
return "", fmt.Errorf("image url is required")
|
||||||
|
}
|
||||||
|
outputDir := req.OutputDir
|
||||||
|
if outputDir == "" {
|
||||||
|
outputDir = backend.GetDefaultDownloadPath()
|
||||||
|
}
|
||||||
|
path, err := backend.DownloadProfileImage(req.URL, outputDir, req.Username, req.Kind, req.Proxy)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return path, nil
|
||||||
|
}
|
||||||
|
|
||||||
func (a *App) SelectFolder(defaultPath string) (string, error) {
|
func (a *App) SelectFolder(defaultPath string) (string, error) {
|
||||||
return backend.SelectFolderDialog(a.ctx, defaultPath)
|
return backend.SelectFolderDialog(a.ctx, defaultPath)
|
||||||
}
|
}
|
||||||
@@ -180,14 +217,22 @@ func (a *App) GetExtractorVersionStatus() backend.ExtractorVersionStatus {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (a *App) Quit() {
|
func (a *App) Quit() {
|
||||||
|
if a.ctx != nil {
|
||||||
|
runtime.Quit(a.ctx)
|
||||||
|
return
|
||||||
|
}
|
||||||
panic("quit")
|
panic("quit")
|
||||||
}
|
}
|
||||||
|
|
||||||
type DownloadMediaRequest struct {
|
type DownloadMediaRequest struct {
|
||||||
URLs []string `json:"urls"`
|
URLs []string `json:"urls"`
|
||||||
OutputDir string `json:"output_dir"`
|
OutputDir string `json:"output_dir"`
|
||||||
Username string `json:"username"`
|
Username string `json:"username"`
|
||||||
Proxy string `json:"proxy,omitempty"`
|
ConcurrentDownloads int `json:"concurrent_downloads,omitempty"`
|
||||||
|
SkipExisting bool `json:"skip_existing"`
|
||||||
|
DeleteIncompleteFiles bool `json:"delete_incomplete_files"`
|
||||||
|
RetryAttempts int `json:"retry_attempts,omitempty"`
|
||||||
|
Proxy string `json:"proxy,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type MediaItemRequest struct {
|
type MediaItemRequest struct {
|
||||||
@@ -198,13 +243,23 @@ type MediaItemRequest struct {
|
|||||||
Content string `json:"content,omitempty"`
|
Content string `json:"content,omitempty"`
|
||||||
OriginalFilename string `json:"original_filename,omitempty"`
|
OriginalFilename string `json:"original_filename,omitempty"`
|
||||||
AuthorUsername string `json:"author_username,omitempty"`
|
AuthorUsername string `json:"author_username,omitempty"`
|
||||||
|
AccountName string `json:"account_name,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type DownloadMediaWithMetadataRequest struct {
|
type DownloadMediaWithMetadataRequest struct {
|
||||||
Items []MediaItemRequest `json:"items"`
|
Items []MediaItemRequest `json:"items"`
|
||||||
OutputDir string `json:"output_dir"`
|
OutputDir string `json:"output_dir"`
|
||||||
Username string `json:"username"`
|
Username string `json:"username"`
|
||||||
Proxy string `json:"proxy,omitempty"`
|
ConcurrentDownloads int `json:"concurrent_downloads,omitempty"`
|
||||||
|
SkipExisting bool `json:"skip_existing"`
|
||||||
|
DeleteIncompleteFiles bool `json:"delete_incomplete_files"`
|
||||||
|
RetryAttempts int `json:"retry_attempts,omitempty"`
|
||||||
|
Proxy string `json:"proxy,omitempty"`
|
||||||
|
FilenameTemplate string `json:"filename_template,omitempty"`
|
||||||
|
FolderTemplate string `json:"folder_template,omitempty"`
|
||||||
|
AutoConvertGIFs bool `json:"auto_convert_gifs,omitempty"`
|
||||||
|
GIFQuality string `json:"gif_quality,omitempty"`
|
||||||
|
GIFResolution string `json:"gif_resolution,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type DownloadMediaResponse struct {
|
type DownloadMediaResponse struct {
|
||||||
@@ -234,7 +289,14 @@ func (a *App) DownloadMedia(req DownloadMediaRequest) (DownloadMediaResponse, er
|
|||||||
outputDir = filepath.Join(outputDir, req.Username)
|
outputDir = filepath.Join(outputDir, req.Username)
|
||||||
}
|
}
|
||||||
|
|
||||||
downloaded, failed, err := backend.DownloadMediaFiles(req.URLs, outputDir, req.Proxy)
|
options := backend.DownloadOptions{
|
||||||
|
ConcurrentDownloads: req.ConcurrentDownloads,
|
||||||
|
SkipExistingFiles: req.SkipExisting,
|
||||||
|
DeleteIncompleteFiles: req.DeleteIncompleteFiles,
|
||||||
|
RetryAttempts: req.RetryAttempts,
|
||||||
|
}
|
||||||
|
|
||||||
|
downloaded, failed, err := backend.DownloadMediaFiles(req.URLs, outputDir, options, req.Proxy)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return DownloadMediaResponse{
|
return DownloadMediaResponse{
|
||||||
Success: false,
|
Success: false,
|
||||||
@@ -292,7 +354,7 @@ func (a *App) DownloadMediaWithMetadata(req DownloadMediaWithMetadataRequest) (D
|
|||||||
}
|
}
|
||||||
|
|
||||||
username := req.Username
|
username := req.Username
|
||||||
if item.AuthorUsername != "" {
|
if (req.Username == "bookmarks" || req.Username == "likes") && item.AuthorUsername != "" {
|
||||||
username = item.AuthorUsername
|
username = item.AuthorUsername
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -302,16 +364,21 @@ func (a *App) DownloadMediaWithMetadata(req DownloadMediaWithMetadataRequest) (D
|
|||||||
TweetID: int64(item.TweetID),
|
TweetID: int64(item.TweetID),
|
||||||
Type: item.Type,
|
Type: item.Type,
|
||||||
Username: username,
|
Username: username,
|
||||||
|
AccountName: item.AccountName,
|
||||||
Content: item.Content,
|
Content: item.Content,
|
||||||
OriginalFilename: originalFilename,
|
OriginalFilename: originalFilename,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
a.downloadCtx, a.downloadCancel = context.WithCancel(context.Background())
|
downloadCtx, err := a.startDownloadOperation()
|
||||||
defer func() {
|
if err != nil {
|
||||||
a.downloadCtx = nil
|
return DownloadMediaResponse{
|
||||||
a.downloadCancel = nil
|
Success: false,
|
||||||
}()
|
Cancelled: false,
|
||||||
|
Message: err.Error(),
|
||||||
|
}, err
|
||||||
|
}
|
||||||
|
defer a.finishDownloadOperation()
|
||||||
|
|
||||||
progressCallback := func(current, total int) {
|
progressCallback := func(current, total int) {
|
||||||
percent := 0
|
percent := 0
|
||||||
@@ -333,7 +400,28 @@ func (a *App) DownloadMediaWithMetadata(req DownloadMediaWithMetadataRequest) (D
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
downloaded, skipped, failed, err := backend.DownloadMediaWithMetadataProgressAndStatus(items, outputDir, req.Username, progressCallback, itemStatusCallback, a.downloadCtx, req.Proxy)
|
options := backend.DownloadOptions{
|
||||||
|
ConcurrentDownloads: req.ConcurrentDownloads,
|
||||||
|
SkipExistingFiles: req.SkipExisting,
|
||||||
|
DeleteIncompleteFiles: req.DeleteIncompleteFiles,
|
||||||
|
RetryAttempts: req.RetryAttempts,
|
||||||
|
FilenameTemplate: req.FilenameTemplate,
|
||||||
|
FolderTemplate: req.FolderTemplate,
|
||||||
|
AutoConvertGIFs: req.AutoConvertGIFs,
|
||||||
|
GIFQuality: req.GIFQuality,
|
||||||
|
GIFResolution: req.GIFResolution,
|
||||||
|
}
|
||||||
|
|
||||||
|
downloaded, skipped, failed, err := backend.DownloadMediaWithMetadataProgressAndStatus(
|
||||||
|
items,
|
||||||
|
outputDir,
|
||||||
|
req.Username,
|
||||||
|
progressCallback,
|
||||||
|
itemStatusCallback,
|
||||||
|
downloadCtx,
|
||||||
|
options,
|
||||||
|
req.Proxy,
|
||||||
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if errors.Is(err, context.Canceled) {
|
if errors.Is(err, context.Canceled) {
|
||||||
return DownloadMediaResponse{
|
return DownloadMediaResponse{
|
||||||
@@ -366,13 +454,39 @@ func (a *App) DownloadMediaWithMetadata(req DownloadMediaWithMetadataRequest) (D
|
|||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a *App) StopDownload() bool {
|
func (a *App) startDownloadOperation() (context.Context, error) {
|
||||||
if a.downloadCancel != nil {
|
a.downloadMu.Lock()
|
||||||
a.downloadCancel()
|
defer a.downloadMu.Unlock()
|
||||||
a.downloadCancel = nil
|
|
||||||
return true
|
if a.downloadActive {
|
||||||
|
return nil, fmt.Errorf("another download is already in progress")
|
||||||
}
|
}
|
||||||
return false
|
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
a.downloadCancel = cancel
|
||||||
|
a.downloadActive = true
|
||||||
|
|
||||||
|
return ctx, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) finishDownloadOperation() {
|
||||||
|
a.downloadMu.Lock()
|
||||||
|
defer a.downloadMu.Unlock()
|
||||||
|
|
||||||
|
a.downloadCancel = nil
|
||||||
|
a.downloadActive = false
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) StopDownload() bool {
|
||||||
|
a.downloadMu.Lock()
|
||||||
|
defer a.downloadMu.Unlock()
|
||||||
|
|
||||||
|
if !a.downloadActive || a.downloadCancel == nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
a.downloadCancel()
|
||||||
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a *App) SaveAccountToDB(username, name, profileImage string, totalMedia int, responseJSON string, mediaType string) error {
|
func (a *App) SaveAccountToDB(username, name, profileImage string, totalMedia int, responseJSON string, mediaType string) error {
|
||||||
|
|||||||
+20
-2
@@ -2,8 +2,26 @@
|
|||||||
|
|
||||||
package backend
|
package backend
|
||||||
|
|
||||||
import "os/exec"
|
import (
|
||||||
|
"errors"
|
||||||
|
"os/exec"
|
||||||
|
"syscall"
|
||||||
|
)
|
||||||
|
|
||||||
func hideWindow(cmd *exec.Cmd) {
|
func hideWindow(cmd *exec.Cmd) {
|
||||||
|
cmd.SysProcAttr = &syscall.SysProcAttr{
|
||||||
|
Setpgid: true,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func terminateCommandProcess(cmd *exec.Cmd) error {
|
||||||
|
if cmd == nil || cmd.Process == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL); err != nil && !errors.Is(err, syscall.ESRCH) {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
@@ -4,6 +4,7 @@ package backend
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"os/exec"
|
"os/exec"
|
||||||
|
"strconv"
|
||||||
"syscall"
|
"syscall"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -13,3 +14,17 @@ func hideWindow(cmd *exec.Cmd) {
|
|||||||
CreationFlags: 0x08000000,
|
CreationFlags: 0x08000000,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func terminateCommandProcess(cmd *exec.Cmd) error {
|
||||||
|
if cmd == nil || cmd.Process == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
taskkill := exec.Command("taskkill", "/T", "/F", "/PID", strconv.Itoa(cmd.Process.Pid))
|
||||||
|
hideWindow(taskkill)
|
||||||
|
if err := taskkill.Run(); err == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
return cmd.Process.Kill()
|
||||||
|
}
|
||||||
+106
-62
@@ -6,6 +6,8 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
_ "modernc.org/sqlite"
|
_ "modernc.org/sqlite"
|
||||||
@@ -41,6 +43,24 @@ type AccountListItem struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
var db *sql.DB
|
var db *sql.DB
|
||||||
|
var dbInitMu sync.Mutex
|
||||||
|
var dbInitialized bool
|
||||||
|
|
||||||
|
func ensureDB() error {
|
||||||
|
dbInitMu.Lock()
|
||||||
|
defer dbInitMu.Unlock()
|
||||||
|
|
||||||
|
if dbInitialized && db != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := initDBInternal(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
dbInitialized = true
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
type accountMetricsPayload struct {
|
type accountMetricsPayload struct {
|
||||||
AccountInfo struct {
|
AccountInfo struct {
|
||||||
@@ -60,6 +80,10 @@ func GetDBPath() string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func InitDB() error {
|
func InitDB() error {
|
||||||
|
return ensureDB()
|
||||||
|
}
|
||||||
|
|
||||||
|
func initDBInternal() error {
|
||||||
dbPath := GetDBPath()
|
dbPath := GetDBPath()
|
||||||
|
|
||||||
dir := filepath.Dir(dbPath)
|
dir := filepath.Dir(dbPath)
|
||||||
@@ -100,16 +124,12 @@ func InitDB() error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
db.Exec("ALTER TABLE accounts ADD COLUMN group_name TEXT DEFAULT ''")
|
|
||||||
db.Exec("ALTER TABLE accounts ADD COLUMN group_color TEXT DEFAULT ''")
|
|
||||||
db.Exec("ALTER TABLE accounts ADD COLUMN media_type TEXT DEFAULT 'all'")
|
|
||||||
db.Exec("ALTER TABLE accounts ADD COLUMN cursor TEXT DEFAULT ''")
|
|
||||||
db.Exec("ALTER TABLE accounts ADD COLUMN completed INTEGER DEFAULT 1")
|
|
||||||
db.Exec("ALTER TABLE accounts ADD COLUMN followers_count INTEGER DEFAULT 0")
|
|
||||||
db.Exec("ALTER TABLE accounts ADD COLUMN statuses_count INTEGER DEFAULT 0")
|
|
||||||
|
|
||||||
db.Exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_username_media_type ON accounts(username, media_type)")
|
db.Exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_username_media_type ON accounts(username, media_type)")
|
||||||
|
|
||||||
|
if err := runMigrations(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
if err := backfillAccountMetrics(); err != nil {
|
if err := backfillAccountMetrics(); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -117,6 +137,37 @@ func InitDB() error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func runMigrations() error {
|
||||||
|
var version int
|
||||||
|
if err := db.QueryRow("PRAGMA user_version").Scan(&version); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
migrations := []string{
|
||||||
|
"ALTER TABLE accounts ADD COLUMN group_name TEXT DEFAULT ''",
|
||||||
|
"ALTER TABLE accounts ADD COLUMN group_color TEXT DEFAULT ''",
|
||||||
|
"ALTER TABLE accounts ADD COLUMN media_type TEXT DEFAULT 'all'",
|
||||||
|
"ALTER TABLE accounts ADD COLUMN cursor TEXT DEFAULT ''",
|
||||||
|
"ALTER TABLE accounts ADD COLUMN completed INTEGER DEFAULT 1",
|
||||||
|
"ALTER TABLE accounts ADD COLUMN followers_count INTEGER DEFAULT 0",
|
||||||
|
"ALTER TABLE accounts ADD COLUMN statuses_count INTEGER DEFAULT 0",
|
||||||
|
}
|
||||||
|
|
||||||
|
for i := version; i < len(migrations); i++ {
|
||||||
|
if _, err := db.Exec(migrations[i]); err != nil {
|
||||||
|
if !strings.Contains(err.Error(), "duplicate column name") {
|
||||||
|
return fmt.Errorf("migration %d failed: %w", i, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := db.Exec(fmt.Sprintf("PRAGMA user_version = %d", len(migrations))); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
func CloseDB() {
|
func CloseDB() {
|
||||||
if db != nil {
|
if db != nil {
|
||||||
db.Close()
|
db.Close()
|
||||||
@@ -128,10 +179,8 @@ func SaveAccount(username, name, profileImage string, totalMedia int, responseJS
|
|||||||
}
|
}
|
||||||
|
|
||||||
func SaveAccountWithStatus(username, name, profileImage string, totalMedia int, responseJSON string, mediaType string, cursor string, completed bool) error {
|
func SaveAccountWithStatus(username, name, profileImage string, totalMedia int, responseJSON string, mediaType string, cursor string, completed bool) error {
|
||||||
if db == nil {
|
if err := ensureDB(); err != nil {
|
||||||
if err := InitDB(); err != nil {
|
return err
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if mediaType == "" {
|
if mediaType == "" {
|
||||||
@@ -164,10 +213,8 @@ func SaveAccountWithStatus(username, name, profileImage string, totalMedia int,
|
|||||||
}
|
}
|
||||||
|
|
||||||
func GetAllAccounts() ([]AccountListItem, error) {
|
func GetAllAccounts() ([]AccountListItem, error) {
|
||||||
if db == nil {
|
if err := ensureDB(); err != nil {
|
||||||
if err := InitDB(); err != nil {
|
return nil, err
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
rows, err := db.Query(`
|
rows, err := db.Query(`
|
||||||
@@ -235,7 +282,31 @@ func backfillAccountMetrics() error {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
defer rows.Close()
|
|
||||||
|
type metricUpdate struct {
|
||||||
|
id int64
|
||||||
|
followersCount int
|
||||||
|
statusesCount int
|
||||||
|
}
|
||||||
|
var updates []metricUpdate
|
||||||
|
for rows.Next() {
|
||||||
|
var id int64
|
||||||
|
var responseJSON string
|
||||||
|
if err := rows.Scan(&id, &responseJSON); err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
followersCount, statusesCount := extractAccountMetrics(responseJSON)
|
||||||
|
updates = append(updates, metricUpdate{id, followersCount, statusesCount})
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
rows.Close()
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
rows.Close()
|
||||||
|
|
||||||
|
if len(updates) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
stmt, err := db.Prepare(`
|
stmt, err := db.Prepare(`
|
||||||
UPDATE accounts
|
UPDATE accounts
|
||||||
@@ -247,27 +318,18 @@ func backfillAccountMetrics() error {
|
|||||||
}
|
}
|
||||||
defer stmt.Close()
|
defer stmt.Close()
|
||||||
|
|
||||||
for rows.Next() {
|
for _, u := range updates {
|
||||||
var id int64
|
if _, err := stmt.Exec(u.followersCount, u.statusesCount, u.id); err != nil {
|
||||||
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 err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return rows.Err()
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func UpdateAccountGroup(id int64, groupName, groupColor string) error {
|
func UpdateAccountGroup(id int64, groupName, groupColor string) error {
|
||||||
if db == nil {
|
if err := ensureDB(); err != nil {
|
||||||
if err := InitDB(); err != nil {
|
return err
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
_, err := db.Exec("UPDATE accounts SET group_name = ?, group_color = ? WHERE id = ?", groupName, groupColor, id)
|
_, err := db.Exec("UPDATE accounts SET group_name = ?, group_color = ? WHERE id = ?", groupName, groupColor, id)
|
||||||
@@ -275,10 +337,8 @@ func UpdateAccountGroup(id int64, groupName, groupColor string) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func GetAllGroups() ([]map[string]string, error) {
|
func GetAllGroups() ([]map[string]string, error) {
|
||||||
if db == nil {
|
if err := ensureDB(); err != nil {
|
||||||
if err := InitDB(); err != nil {
|
return nil, err
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
rows, err := db.Query(`
|
rows, err := db.Query(`
|
||||||
@@ -305,10 +365,8 @@ func GetAllGroups() ([]map[string]string, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func ClearAllAccounts() error {
|
func ClearAllAccounts() error {
|
||||||
if db == nil {
|
if err := ensureDB(); err != nil {
|
||||||
if err := InitDB(); err != nil {
|
return err
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
_, err := db.Exec("DELETE FROM accounts")
|
_, err := db.Exec("DELETE FROM accounts")
|
||||||
@@ -316,10 +374,8 @@ func ClearAllAccounts() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func GetAccountByID(id int64) (*AccountDB, error) {
|
func GetAccountByID(id int64) (*AccountDB, error) {
|
||||||
if db == nil {
|
if err := ensureDB(); err != nil {
|
||||||
if err := InitDB(); err != nil {
|
return nil, err
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
var acc AccountDB
|
var acc AccountDB
|
||||||
@@ -345,10 +401,8 @@ func GetAccountByID(id int64) (*AccountDB, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func GetAccountByUsernameAndMediaType(username, mediaType string) (*AccountDB, error) {
|
func GetAccountByUsernameAndMediaType(username, mediaType string) (*AccountDB, error) {
|
||||||
if db == nil {
|
if err := ensureDB(); err != nil {
|
||||||
if err := InitDB(); err != nil {
|
return nil, err
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if mediaType == "" {
|
if mediaType == "" {
|
||||||
@@ -380,10 +434,8 @@ func GetAccountByUsernameAndMediaType(username, mediaType string) (*AccountDB, e
|
|||||||
}
|
}
|
||||||
|
|
||||||
func DeleteAccount(id int64) error {
|
func DeleteAccount(id int64) error {
|
||||||
if db == nil {
|
if err := ensureDB(); err != nil {
|
||||||
if err := InitDB(); err != nil {
|
return err
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
_, err := db.Exec("DELETE FROM accounts WHERE id = ?", id)
|
_, err := db.Exec("DELETE FROM accounts WHERE id = ?", id)
|
||||||
@@ -523,13 +575,7 @@ func ExportAccountsToTXT(ids []int64, outputDir string) (string, error) {
|
|||||||
return "", fmt.Errorf("no valid usernames found")
|
return "", fmt.Errorf("no valid usernames found")
|
||||||
}
|
}
|
||||||
|
|
||||||
txtContent := ""
|
txtContent := strings.Join(usernames, "\n")
|
||||||
for i, username := range usernames {
|
|
||||||
if i > 0 {
|
|
||||||
txtContent += "\n"
|
|
||||||
}
|
|
||||||
txtContent += username
|
|
||||||
}
|
|
||||||
|
|
||||||
filePath := filepath.Join(exportDir, "twitterxmediabatchdownloader_multiple.txt")
|
filePath := filepath.Join(exportDir, "twitterxmediabatchdownloader_multiple.txt")
|
||||||
|
|
||||||
@@ -541,10 +587,8 @@ func ExportAccountsToTXT(ids []int64, outputDir string) (string, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func ImportAccountFromFile(filePath string) (string, error) {
|
func ImportAccountFromFile(filePath string) (string, error) {
|
||||||
if db == nil {
|
if err := ensureDB(); err != nil {
|
||||||
if err := InitDB(); err != nil {
|
return "", err
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
data, err := os.ReadFile(filePath)
|
data, err := os.ReadFile(filePath)
|
||||||
|
|||||||
+481
-56
@@ -2,6 +2,7 @@ package backend
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
@@ -15,20 +16,63 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
MaxConcurrentDownloads = 10
|
DefaultConcurrentDownloads = 10
|
||||||
|
MaxConcurrentDownloads = 50
|
||||||
|
DefaultRetryAttempts = 2
|
||||||
|
MaxRetryAttempts = 5
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func NormalizeConcurrentDownloads(requested int) int {
|
||||||
|
if requested <= 0 {
|
||||||
|
return DefaultConcurrentDownloads
|
||||||
|
}
|
||||||
|
if requested > MaxConcurrentDownloads {
|
||||||
|
return MaxConcurrentDownloads
|
||||||
|
}
|
||||||
|
return requested
|
||||||
|
}
|
||||||
|
|
||||||
|
func NormalizeRetryAttempts(requested int) int {
|
||||||
|
if requested < 0 {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
if requested > MaxRetryAttempts {
|
||||||
|
return MaxRetryAttempts
|
||||||
|
}
|
||||||
|
return requested
|
||||||
|
}
|
||||||
|
|
||||||
|
type DownloadOptions struct {
|
||||||
|
ConcurrentDownloads int
|
||||||
|
SkipExistingFiles bool
|
||||||
|
DeleteIncompleteFiles bool
|
||||||
|
RetryAttempts int
|
||||||
|
FilenameTemplate string
|
||||||
|
FolderTemplate string
|
||||||
|
AutoConvertGIFs bool
|
||||||
|
GIFQuality string
|
||||||
|
GIFResolution string
|
||||||
|
}
|
||||||
|
|
||||||
|
func NormalizeDownloadOptions(options DownloadOptions) DownloadOptions {
|
||||||
|
options.ConcurrentDownloads = NormalizeConcurrentDownloads(options.ConcurrentDownloads)
|
||||||
|
options.RetryAttempts = NormalizeRetryAttempts(options.RetryAttempts)
|
||||||
|
return options
|
||||||
|
}
|
||||||
|
|
||||||
type MediaItem struct {
|
type MediaItem struct {
|
||||||
URL string `json:"url"`
|
URL string `json:"url"`
|
||||||
Date string `json:"date"`
|
Date string `json:"date"`
|
||||||
TweetID int64 `json:"tweet_id"`
|
TweetID int64 `json:"tweet_id"`
|
||||||
Type string `json:"type"`
|
Type string `json:"type"`
|
||||||
Username string `json:"username"`
|
Username string `json:"username"`
|
||||||
|
AccountName string `json:"account_name,omitempty"`
|
||||||
Content string `json:"content,omitempty"`
|
Content string `json:"content,omitempty"`
|
||||||
OriginalFilename string `json:"original_filename,omitempty"`
|
OriginalFilename string `json:"original_filename,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func DownloadMediaFiles(urls []string, outputDir string, customProxy string) (downloaded int, failed int, err error) {
|
func DownloadMediaFiles(urls []string, outputDir string, options DownloadOptions, customProxy string) (downloaded int, failed int, err error) {
|
||||||
|
options = NormalizeDownloadOptions(options)
|
||||||
|
|
||||||
if err := os.MkdirAll(outputDir, 0755); err != nil {
|
if err := os.MkdirAll(outputDir, 0755); err != nil {
|
||||||
return 0, len(urls), fmt.Errorf("failed to create output directory: %v", err)
|
return 0, len(urls), fmt.Errorf("failed to create output directory: %v", err)
|
||||||
@@ -46,12 +90,14 @@ func DownloadMediaFiles(urls []string, outputDir string, customProxy string) (do
|
|||||||
filename := extractFilename(mediaURL)
|
filename := extractFilename(mediaURL)
|
||||||
outputPath := filepath.Join(outputDir, filename)
|
outputPath := filepath.Join(outputDir, filename)
|
||||||
|
|
||||||
if _, err := os.Stat(outputPath); err == nil {
|
if options.SkipExistingFiles {
|
||||||
downloaded++
|
if _, err := os.Stat(outputPath); err == nil {
|
||||||
continue
|
downloaded++
|
||||||
|
continue
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := downloadFile(client, mediaURL, outputPath); err != nil {
|
if err := downloadFileWithRetry(context.Background(), client, mediaURL, outputPath, options); err != nil {
|
||||||
failed++
|
failed++
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@@ -61,6 +107,140 @@ func DownloadMediaFiles(urls []string, outputDir string, customProxy string) (do
|
|||||||
return downloaded, failed, nil
|
return downloaded, failed, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func fileExists(path string) (bool, error) {
|
||||||
|
_, err := os.Stat(path)
|
||||||
|
if err == nil {
|
||||||
|
return true, nil
|
||||||
|
}
|
||||||
|
if errors.Is(err, os.ErrNotExist) {
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func cleanupIncompleteDownload(outputPath string) {
|
||||||
|
_ = os.Remove(outputPath)
|
||||||
|
}
|
||||||
|
|
||||||
|
func replaceFile(tempPath, outputPath string, allowOverwrite bool) error {
|
||||||
|
if !allowOverwrite {
|
||||||
|
return os.Rename(tempPath, outputPath)
|
||||||
|
}
|
||||||
|
|
||||||
|
exists, err := fileExists(outputPath)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !exists {
|
||||||
|
return os.Rename(tempPath, outputPath)
|
||||||
|
}
|
||||||
|
|
||||||
|
backupPath := fmt.Sprintf("%s.bak.%d", outputPath, time.Now().UnixNano())
|
||||||
|
if err := os.Rename(outputPath, backupPath); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := os.Rename(tempPath, outputPath); err != nil {
|
||||||
|
restoreErr := os.Rename(backupPath, outputPath)
|
||||||
|
if restoreErr != nil {
|
||||||
|
return fmt.Errorf("failed to replace existing file: %v (restore failed: %v)", err, restoreErr)
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
_ = os.Remove(backupPath)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeFileAtomically(outputPath string, data []byte, allowOverwrite bool, keepPartialOnFailure bool) error {
|
||||||
|
out, err := os.CreateTemp(filepath.Dir(outputPath), filepath.Base(outputPath)+".*.part")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
tempPath := out.Name()
|
||||||
|
cleanupTemp := !keepPartialOnFailure
|
||||||
|
defer func() {
|
||||||
|
if out != nil {
|
||||||
|
_ = out.Close()
|
||||||
|
}
|
||||||
|
if cleanupTemp {
|
||||||
|
_ = os.Remove(tempPath)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
if _, err := out.Write(data); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := out.Close(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
out = nil
|
||||||
|
|
||||||
|
if err := replaceFile(tempPath, outputPath, allowOverwrite); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
cleanupTemp = false
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func waitForRetry(ctx context.Context, attempt int) error {
|
||||||
|
timer := time.NewTimer(time.Duration(attempt) * 500 * time.Millisecond)
|
||||||
|
defer timer.Stop()
|
||||||
|
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return ctx.Err()
|
||||||
|
case <-timer.C:
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func downloadFileWithRetry(ctx context.Context, client *http.Client, mediaURL, outputPath string, options DownloadOptions) error {
|
||||||
|
options = NormalizeDownloadOptions(options)
|
||||||
|
|
||||||
|
var lastErr error
|
||||||
|
totalAttempts := options.RetryAttempts + 1
|
||||||
|
for attempt := 1; attempt <= totalAttempts; attempt++ {
|
||||||
|
keepPartialOnFailure := !options.DeleteIncompleteFiles && attempt == totalAttempts
|
||||||
|
lastErr = downloadFileWithContext(ctx, client, mediaURL, outputPath, !options.SkipExistingFiles, keepPartialOnFailure)
|
||||||
|
if lastErr == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if ctx.Err() != nil || errors.Is(lastErr, context.Canceled) {
|
||||||
|
if options.DeleteIncompleteFiles {
|
||||||
|
cleanupIncompleteDownload(outputPath)
|
||||||
|
}
|
||||||
|
return lastErr
|
||||||
|
}
|
||||||
|
if options.DeleteIncompleteFiles {
|
||||||
|
cleanupIncompleteDownload(outputPath)
|
||||||
|
}
|
||||||
|
if attempt < totalAttempts {
|
||||||
|
if err := waitForRetry(ctx, attempt); err != nil {
|
||||||
|
if options.DeleteIncompleteFiles {
|
||||||
|
cleanupIncompleteDownload(outputPath)
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return lastErr
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeTextFileWithOptions(outputPath string, content string, options DownloadOptions) error {
|
||||||
|
keepPartialOnFailure := !options.DeleteIncompleteFiles
|
||||||
|
if err := writeFileAtomically(outputPath, []byte(content), !options.SkipExistingFiles, keepPartialOnFailure); err != nil {
|
||||||
|
if options.DeleteIncompleteFiles {
|
||||||
|
cleanupIncompleteDownload(outputPath)
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
type ProgressCallback func(current, total int)
|
type ProgressCallback func(current, total int)
|
||||||
|
|
||||||
type ItemStatusCallback func(tweetID int64, index int, status string) // status: "success", "failed", "skipped"
|
type ItemStatusCallback func(tweetID int64, index int, status string) // status: "success", "failed", "skipped"
|
||||||
@@ -71,10 +251,18 @@ type downloadTask struct {
|
|||||||
index int
|
index int
|
||||||
}
|
}
|
||||||
|
|
||||||
func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir string, username string, progress ProgressCallback, itemStatus ItemStatusCallback, ctx context.Context, customProxy string) (downloaded int, skipped int, failed int, err error) {
|
type pendingDownloadTask struct {
|
||||||
|
task downloadTask
|
||||||
|
typeDir string
|
||||||
|
baseName string
|
||||||
|
ext string
|
||||||
|
}
|
||||||
|
|
||||||
|
func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir string, username string, progress ProgressCallback, itemStatus ItemStatusCallback, ctx context.Context, options DownloadOptions, customProxy string) (downloaded int, skipped int, failed int, err error) {
|
||||||
if ctx == nil {
|
if ctx == nil {
|
||||||
ctx = context.Background()
|
ctx = context.Background()
|
||||||
}
|
}
|
||||||
|
options = NormalizeDownloadOptions(options)
|
||||||
|
|
||||||
total := len(items)
|
total := len(items)
|
||||||
if total == 0 {
|
if total == 0 {
|
||||||
@@ -82,7 +270,9 @@ func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir str
|
|||||||
}
|
}
|
||||||
|
|
||||||
tweetMediaCount := make(map[string]map[int64]int)
|
tweetMediaCount := make(map[string]map[int64]int)
|
||||||
tasks := make([]downloadTask, 0, total)
|
pendingTasks := make([]pendingDownloadTask, 0, total)
|
||||||
|
filenameCounts := make(map[string]int)
|
||||||
|
downloadDate := time.Now().Format("20060102")
|
||||||
|
|
||||||
for i, item := range items {
|
for i, item := range items {
|
||||||
|
|
||||||
@@ -90,6 +280,10 @@ func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir str
|
|||||||
if itemUsername == "" {
|
if itemUsername == "" {
|
||||||
itemUsername = username
|
itemUsername = username
|
||||||
}
|
}
|
||||||
|
itemAccountName := item.AccountName
|
||||||
|
if itemAccountName == "" {
|
||||||
|
itemAccountName = itemUsername
|
||||||
|
}
|
||||||
|
|
||||||
if tweetMediaCount[itemUsername] == nil {
|
if tweetMediaCount[itemUsername] == nil {
|
||||||
tweetMediaCount[itemUsername] = make(map[int64]int)
|
tweetMediaCount[itemUsername] = make(map[int64]int)
|
||||||
@@ -109,7 +303,7 @@ func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir str
|
|||||||
subfolder = "other"
|
subfolder = "other"
|
||||||
}
|
}
|
||||||
|
|
||||||
baseDir := filepath.Join(outputDir, itemUsername)
|
baseDir := filepath.Join(outputDir, renderFolder(options.FolderTemplate, itemUsername, itemAccountName, downloadDate))
|
||||||
if err := os.MkdirAll(baseDir, 0755); err != nil {
|
if err := os.MkdirAll(baseDir, 0755); err != nil {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@@ -126,25 +320,63 @@ func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir str
|
|||||||
tweetMediaCount[itemUsername][item.TweetID]++
|
tweetMediaCount[itemUsername][item.TweetID]++
|
||||||
mediaIndex := tweetMediaCount[itemUsername][item.TweetID]
|
mediaIndex := tweetMediaCount[itemUsername][item.TweetID]
|
||||||
|
|
||||||
filename := fmt.Sprintf("%s_%s_%d_%02d%s", itemUsername, timestamp, item.TweetID, mediaIndex, ext)
|
mediaID := item.OriginalFilename
|
||||||
outputPath := filepath.Join(typeDir, filename)
|
if mediaID == "" {
|
||||||
|
mediaID = ExtractOriginalFilename(item.URL)
|
||||||
|
}
|
||||||
|
|
||||||
tasks = append(tasks, downloadTask{
|
baseName := renderFilename(options.FilenameTemplate, itemUsername, itemAccountName, timestamp, item.TweetID, item.Type, mediaIndex, mediaID)
|
||||||
item: item,
|
filenameCounts[filenameCollisionKey(typeDir, baseName, ext)]++
|
||||||
outputPath: outputPath,
|
|
||||||
index: i,
|
pendingTasks = append(pendingTasks, pendingDownloadTask{
|
||||||
|
task: downloadTask{
|
||||||
|
item: item,
|
||||||
|
index: i,
|
||||||
|
},
|
||||||
|
typeDir: typeDir,
|
||||||
|
baseName: baseName,
|
||||||
|
ext: ext,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
filenameIndexes := make(map[string]int, len(filenameCounts))
|
||||||
|
tasks := make([]downloadTask, 0, len(pendingTasks))
|
||||||
|
|
||||||
|
for _, pending := range pendingTasks {
|
||||||
|
key := filenameCollisionKey(pending.typeDir, pending.baseName, pending.ext)
|
||||||
|
|
||||||
|
filenameIndexes[key]++
|
||||||
|
|
||||||
|
filename := formatDownloadFilename(
|
||||||
|
pending.baseName,
|
||||||
|
pending.ext,
|
||||||
|
filenameCounts[key],
|
||||||
|
filenameIndexes[key],
|
||||||
|
)
|
||||||
|
|
||||||
|
if options.SkipExistingFiles {
|
||||||
|
canonicalPath := filepath.Join(pending.typeDir, formatDownloadFilename(pending.baseName, pending.ext, 1, 1))
|
||||||
|
if exists, err := fileExists(canonicalPath); err == nil && exists {
|
||||||
|
pending.task.outputPath = canonicalPath
|
||||||
|
tasks = append(tasks, pending.task)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pending.task.outputPath = filepath.Join(pending.typeDir, filename)
|
||||||
|
tasks = append(tasks, pending.task)
|
||||||
|
}
|
||||||
|
|
||||||
var downloadedCount int64
|
var downloadedCount int64
|
||||||
var skippedCount int64
|
var skippedCount int64
|
||||||
var failedCount int64
|
var failedCount int64
|
||||||
var completedCount int64
|
var completedCount int64
|
||||||
|
var conversionWG sync.WaitGroup
|
||||||
|
|
||||||
taskChan := make(chan downloadTask, len(tasks))
|
taskChan := make(chan downloadTask, len(tasks))
|
||||||
var wg sync.WaitGroup
|
var wg sync.WaitGroup
|
||||||
|
|
||||||
numWorkers := MaxConcurrentDownloads
|
numWorkers := options.ConcurrentDownloads
|
||||||
if numWorkers > len(tasks) {
|
if numWorkers > len(tasks) {
|
||||||
numWorkers = len(tasks)
|
numWorkers = len(tasks)
|
||||||
}
|
}
|
||||||
@@ -167,14 +399,6 @@ func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir str
|
|||||||
client := sharedClient
|
client := sharedClient
|
||||||
|
|
||||||
for task := range taskChan {
|
for task := range taskChan {
|
||||||
|
|
||||||
select {
|
|
||||||
case <-ctx.Done():
|
|
||||||
return
|
|
||||||
default:
|
|
||||||
}
|
|
||||||
|
|
||||||
var status string
|
|
||||||
markCompleted := func() {
|
markCompleted := func() {
|
||||||
completed := atomic.AddInt64(&completedCount, 1)
|
completed := atomic.AddInt64(&completedCount, 1)
|
||||||
if progress != nil {
|
if progress != nil {
|
||||||
@@ -182,25 +406,54 @@ func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir str
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if _, err := os.Stat(task.outputPath); err == nil {
|
if ctx.Err() != nil {
|
||||||
status = "skipped"
|
|
||||||
|
|
||||||
if itemStatus != nil {
|
if itemStatus != nil {
|
||||||
itemStatus(task.item.TweetID, task.index, status)
|
itemStatus(task.item.TweetID, task.index, "cancelled")
|
||||||
}
|
}
|
||||||
atomic.AddInt64(&skippedCount, 1)
|
|
||||||
markCompleted()
|
markCompleted()
|
||||||
continue
|
continue
|
||||||
} else if task.item.Type == "text" {
|
}
|
||||||
|
|
||||||
if err := os.WriteFile(task.outputPath, []byte(task.item.Content), 0644); err != nil {
|
var status string
|
||||||
|
|
||||||
|
if options.SkipExistingFiles {
|
||||||
|
exists, err := fileExists(task.outputPath)
|
||||||
|
if err == nil && exists {
|
||||||
|
status = "skipped"
|
||||||
|
|
||||||
|
if itemStatus != nil {
|
||||||
|
itemStatus(task.item.TweetID, task.index, status)
|
||||||
|
}
|
||||||
|
atomic.AddInt64(&skippedCount, 1)
|
||||||
|
markCompleted()
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if task.item.Type == "text" {
|
||||||
|
if ctx.Err() != nil {
|
||||||
|
if itemStatus != nil {
|
||||||
|
itemStatus(task.item.TweetID, task.index, "cancelled")
|
||||||
|
}
|
||||||
|
markCompleted()
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := writeTextFileWithOptions(task.outputPath, task.item.Content, options); err != nil {
|
||||||
atomic.AddInt64(&failedCount, 1)
|
atomic.AddInt64(&failedCount, 1)
|
||||||
status = "failed"
|
status = "failed"
|
||||||
} else {
|
} else {
|
||||||
atomic.AddInt64(&downloadedCount, 1)
|
atomic.AddInt64(&downloadedCount, 1)
|
||||||
status = "success"
|
status = "success"
|
||||||
}
|
}
|
||||||
} else if err := downloadFileWithContext(ctx, client, task.item.URL, task.outputPath); err != nil {
|
} else if err := downloadFileWithRetry(ctx, client, task.item.URL, task.outputPath, options); err != nil {
|
||||||
|
if ctx.Err() != nil || errors.Is(err, context.Canceled) {
|
||||||
|
if itemStatus != nil {
|
||||||
|
itemStatus(task.item.TweetID, task.index, "cancelled")
|
||||||
|
}
|
||||||
|
markCompleted()
|
||||||
|
continue
|
||||||
|
}
|
||||||
atomic.AddInt64(&failedCount, 1)
|
atomic.AddInt64(&failedCount, 1)
|
||||||
status = "failed"
|
status = "failed"
|
||||||
} else {
|
} else {
|
||||||
@@ -209,12 +462,23 @@ func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir str
|
|||||||
|
|
||||||
originalFilename := ExtractOriginalFilename(task.item.URL)
|
originalFilename := ExtractOriginalFilename(task.item.URL)
|
||||||
|
|
||||||
if err := EmbedMetadata(task.outputPath, task.item.Content, tweetURL, originalFilename); err != nil {
|
if ctx.Err() == nil {
|
||||||
|
if err := EmbedMetadata(ctx, task.outputPath, task.item.Content, tweetURL, originalFilename); err != nil && !errors.Is(err, context.Canceled) {
|
||||||
|
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
atomic.AddInt64(&downloadedCount, 1)
|
atomic.AddInt64(&downloadedCount, 1)
|
||||||
status = "success"
|
status = "success"
|
||||||
|
|
||||||
|
if shouldAutoConvertGIF(task.item.Type, options) && ctx.Err() == nil {
|
||||||
|
conversionWG.Add(1)
|
||||||
|
go func(inputPath string) {
|
||||||
|
defer conversionWG.Done()
|
||||||
|
outputPath := strings.TrimSuffix(inputPath, filepath.Ext(inputPath)) + ".gif"
|
||||||
|
_ = ConvertMP4ToGIFWithContext(ctx, inputPath, outputPath, normalizeGIFQuality(options.GIFQuality), normalizeGIFResolution(options.GIFResolution))
|
||||||
|
}(task.outputPath)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if itemStatus != nil {
|
if itemStatus != nil {
|
||||||
@@ -231,18 +495,51 @@ func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir str
|
|||||||
case <-ctx.Done():
|
case <-ctx.Done():
|
||||||
close(taskChan)
|
close(taskChan)
|
||||||
wg.Wait()
|
wg.Wait()
|
||||||
return int(downloadedCount), int(skippedCount), int(failedCount) + (total - int(completedCount)), ctx.Err()
|
return int(downloadedCount), int(skippedCount), int(failedCount), ctx.Err()
|
||||||
case taskChan <- task:
|
case taskChan <- task:
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
close(taskChan)
|
close(taskChan)
|
||||||
|
|
||||||
wg.Wait()
|
wg.Wait()
|
||||||
|
conversionWG.Wait()
|
||||||
|
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return int(downloadedCount), int(skippedCount), int(failedCount), err
|
||||||
|
}
|
||||||
|
|
||||||
return int(downloadedCount), int(skippedCount), int(failedCount), nil
|
return int(downloadedCount), int(skippedCount), int(failedCount), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func downloadFileWithContext(ctx context.Context, client *http.Client, url, outputPath string) error {
|
func shouldAutoConvertGIF(mediaType string, options DownloadOptions) bool {
|
||||||
|
if !options.AutoConvertGIFs || !IsFFmpegInstalled() {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
switch mediaType {
|
||||||
|
case "gif", "animated_gif":
|
||||||
|
return true
|
||||||
|
default:
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func normalizeGIFQuality(quality string) string {
|
||||||
|
if quality == "better" {
|
||||||
|
return quality
|
||||||
|
}
|
||||||
|
return "fast"
|
||||||
|
}
|
||||||
|
|
||||||
|
func normalizeGIFResolution(resolution string) string {
|
||||||
|
switch resolution {
|
||||||
|
case "original", "high", "medium", "low":
|
||||||
|
return resolution
|
||||||
|
default:
|
||||||
|
return "original"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func downloadFileWithContext(ctx context.Context, client *http.Client, url, outputPath string, allowOverwrite bool, keepPartialOnFailure bool) error {
|
||||||
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
|
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -258,14 +555,41 @@ func downloadFileWithContext(ctx context.Context, client *http.Client, url, outp
|
|||||||
return fmt.Errorf("bad status: %s", resp.Status)
|
return fmt.Errorf("bad status: %s", resp.Status)
|
||||||
}
|
}
|
||||||
|
|
||||||
out, err := os.Create(outputPath)
|
out, err := os.CreateTemp(filepath.Dir(outputPath), filepath.Base(outputPath)+".*.part")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
defer out.Close()
|
tempPath := out.Name()
|
||||||
|
cleanupTemp := !keepPartialOnFailure
|
||||||
|
defer func() {
|
||||||
|
if out != nil {
|
||||||
|
_ = out.Close()
|
||||||
|
}
|
||||||
|
if cleanupTemp {
|
||||||
|
_ = os.Remove(tempPath)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
_, err = io.Copy(out, resp.Body)
|
_, err = io.Copy(out, resp.Body)
|
||||||
return err
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := out.Close(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
out = nil
|
||||||
|
|
||||||
|
if ctx.Err() != nil {
|
||||||
|
return ctx.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := replaceFile(tempPath, outputPath, allowOverwrite); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
cleanupTemp = false
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func formatTimestamp(dateStr string) string {
|
func formatTimestamp(dateStr string) string {
|
||||||
@@ -290,6 +614,92 @@ func formatTimestamp(dateStr string) string {
|
|||||||
return "00000000_000000"
|
return "00000000_000000"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func renderFilename(template, username, accountName, timestamp string, tweetID int64, mediaType string, index int, mediaID string) string {
|
||||||
|
if strings.TrimSpace(template) == "" {
|
||||||
|
template = "{handle}_{date}_{tweet_id}"
|
||||||
|
}
|
||||||
|
replacer := strings.NewReplacer(
|
||||||
|
"{handle}", sanitizeFilenamePart(username),
|
||||||
|
"{name}", sanitizeFilenamePart(accountName),
|
||||||
|
"{username}", sanitizeFilenamePart(username),
|
||||||
|
"{account_name}", sanitizeFilenamePart(accountName),
|
||||||
|
"{date}", timestamp,
|
||||||
|
"{tweet_id}", fmt.Sprintf("%d", tweetID),
|
||||||
|
"{index}", fmt.Sprintf("%02d", index),
|
||||||
|
"{media_id}", sanitizeFilenamePart(mediaID),
|
||||||
|
"{type}", sanitizeFilenamePart(mediaType),
|
||||||
|
)
|
||||||
|
name := strings.TrimSpace(replacer.Replace(template))
|
||||||
|
name = sanitizeFilenamePart(name)
|
||||||
|
if name == "" {
|
||||||
|
name = sanitizeFilenamePart(fmt.Sprintf("%s_%s_%d", username, timestamp, tweetID))
|
||||||
|
}
|
||||||
|
return name
|
||||||
|
}
|
||||||
|
|
||||||
|
func filenameCollisionKey(dir, baseName, ext string) string {
|
||||||
|
return dir + "\x00" + baseName + ext
|
||||||
|
}
|
||||||
|
|
||||||
|
func formatDownloadFilename(baseName, ext string, duplicateCount, duplicateIndex int) string {
|
||||||
|
if duplicateCount > 1 {
|
||||||
|
return fmt.Sprintf("%s_%02d%s", baseName, duplicateIndex, ext)
|
||||||
|
}
|
||||||
|
return baseName + ext
|
||||||
|
}
|
||||||
|
|
||||||
|
func renderFolder(template, username, accountName, date string) string {
|
||||||
|
if strings.TrimSpace(template) == "" {
|
||||||
|
template = "{handle}"
|
||||||
|
}
|
||||||
|
replacer := strings.NewReplacer(
|
||||||
|
"{handle}", sanitizeFilenamePart(username),
|
||||||
|
"{name}", sanitizeFilenamePart(accountName),
|
||||||
|
"{username}", sanitizeFilenamePart(username),
|
||||||
|
"{account_name}", sanitizeFilenamePart(accountName),
|
||||||
|
"{date}", date,
|
||||||
|
)
|
||||||
|
name := strings.TrimSpace(replacer.Replace(template))
|
||||||
|
name = sanitizeFilenamePart(name)
|
||||||
|
if name == "" {
|
||||||
|
name = sanitizeFilenamePart(username)
|
||||||
|
}
|
||||||
|
return name
|
||||||
|
}
|
||||||
|
|
||||||
|
func sanitizeFilenamePart(s string) string {
|
||||||
|
cleaned := strings.TrimSpace(strings.Map(func(r rune) rune {
|
||||||
|
switch r {
|
||||||
|
case '\\', '/', ':', '*', '?', '"', '<', '>', '|':
|
||||||
|
return -1
|
||||||
|
}
|
||||||
|
if r >= 0 && r < 32 {
|
||||||
|
return -1
|
||||||
|
}
|
||||||
|
return r
|
||||||
|
}, s))
|
||||||
|
cleaned = strings.TrimRight(cleaned, ". ")
|
||||||
|
if isWindowsReservedName(cleaned) {
|
||||||
|
return cleaned + "_"
|
||||||
|
}
|
||||||
|
return cleaned
|
||||||
|
}
|
||||||
|
|
||||||
|
func isWindowsReservedName(name string) bool {
|
||||||
|
base := name
|
||||||
|
if dotIndex := strings.IndexByte(base, '.'); dotIndex >= 0 {
|
||||||
|
base = base[:dotIndex]
|
||||||
|
}
|
||||||
|
base = strings.ToUpper(strings.TrimSpace(base))
|
||||||
|
switch base {
|
||||||
|
case "CON", "PRN", "AUX", "NUL":
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return len(base) == 4 &&
|
||||||
|
((strings.HasPrefix(base, "COM") && base[3] >= '1' && base[3] <= '9') ||
|
||||||
|
(strings.HasPrefix(base, "LPT") && base[3] >= '1' && base[3] <= '9'))
|
||||||
|
}
|
||||||
|
|
||||||
func getExtension(mediaURL string, mediaType string) string {
|
func getExtension(mediaURL string, mediaType string) string {
|
||||||
parsedURL, err := url.Parse(mediaURL)
|
parsedURL, err := url.Parse(mediaURL)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -354,22 +764,37 @@ func extractFilename(mediaURL string) string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func downloadFile(client *http.Client, url, outputPath string) error {
|
func downloadFile(client *http.Client, url, outputPath string) error {
|
||||||
resp, err := client.Get(url)
|
return downloadFileWithRetry(context.Background(), client, url, outputPath, DownloadOptions{
|
||||||
if err != nil {
|
SkipExistingFiles: false,
|
||||||
return err
|
DeleteIncompleteFiles: true,
|
||||||
}
|
RetryAttempts: 0,
|
||||||
defer resp.Body.Close()
|
})
|
||||||
|
}
|
||||||
if resp.StatusCode != http.StatusOK {
|
|
||||||
return fmt.Errorf("bad status: %s", resp.Status)
|
func DownloadProfileImage(imageURL, outputDir, username, kind, customProxy string) (string, error) {
|
||||||
}
|
if strings.TrimSpace(imageURL) == "" {
|
||||||
|
return "", fmt.Errorf("no %s url available", kind)
|
||||||
out, err := os.Create(outputPath)
|
}
|
||||||
if err != nil {
|
|
||||||
return err
|
baseDir := outputDir
|
||||||
}
|
if username != "" {
|
||||||
defer out.Close()
|
baseDir = filepath.Join(outputDir, username)
|
||||||
|
}
|
||||||
_, err = io.Copy(out, resp.Body)
|
if err := os.MkdirAll(baseDir, 0755); err != nil {
|
||||||
return err
|
return "", fmt.Errorf("failed to create output directory: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
ext := getExtension(imageURL, "photo")
|
||||||
|
filename := fmt.Sprintf("%s_%s%s", sanitizeFilenamePart(username), kind, ext)
|
||||||
|
outputPath := filepath.Join(baseDir, filename)
|
||||||
|
|
||||||
|
client, err := CreateHTTPClient(customProxy, 60*time.Second)
|
||||||
|
if err != nil {
|
||||||
|
client = &http.Client{Timeout: 60 * time.Second}
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := downloadFile(client, imageURL, outputPath); err != nil {
|
||||||
|
return "", fmt.Errorf("failed to download %s: %v", kind, err)
|
||||||
|
}
|
||||||
|
return outputPath, nil
|
||||||
}
|
}
|
||||||
@@ -469,6 +469,10 @@ func extractExifToolFromZip(zipPath, destPath string) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
libDir := filepath.Join(filepath.Dir(destPath), "exiftool_files")
|
libDir := filepath.Join(filepath.Dir(destPath), "exiftool_files")
|
||||||
|
libDirAbs, err := filepath.Abs(libDir)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to resolve libDir: %v", err)
|
||||||
|
}
|
||||||
for _, f := range r.File {
|
for _, f := range r.File {
|
||||||
if strings.Contains(f.Name, "exiftool_files") && !strings.HasSuffix(f.Name, "/") {
|
if strings.Contains(f.Name, "exiftool_files") && !strings.HasSuffix(f.Name, "/") {
|
||||||
parts := strings.Split(f.Name, "exiftool_files/")
|
parts := strings.Split(f.Name, "exiftool_files/")
|
||||||
@@ -482,6 +486,14 @@ func extractExifToolFromZip(zipPath, destPath string) error {
|
|||||||
|
|
||||||
targetPath := filepath.Join(libDir, relPath)
|
targetPath := filepath.Join(libDir, relPath)
|
||||||
|
|
||||||
|
targetAbs, err := filepath.Abs(targetPath)
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if !strings.HasPrefix(targetAbs+string(os.PathSeparator), libDirAbs+string(os.PathSeparator)) && targetAbs != libDirAbs {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
if err := os.MkdirAll(filepath.Dir(targetPath), 0755); err != nil {
|
if err := os.MkdirAll(filepath.Dir(targetPath), 0755); err != nil {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -144,8 +144,11 @@ func getExtractorAssetName() (string, error) {
|
|||||||
return "windows-amd64.zip", nil
|
return "windows-amd64.zip", nil
|
||||||
}
|
}
|
||||||
case "linux":
|
case "linux":
|
||||||
if runtime.GOARCH == "amd64" {
|
switch runtime.GOARCH {
|
||||||
|
case "amd64":
|
||||||
return "linux-amd64.zip", nil
|
return "linux-amd64.zip", nil
|
||||||
|
case "arm64":
|
||||||
|
return "linux-arm64.zip", nil
|
||||||
}
|
}
|
||||||
case "darwin":
|
case "darwin":
|
||||||
switch resolveMacOSExtractorArch(runtime.GOARCH, detectMacOSHardwareArch()) {
|
switch resolveMacOSExtractorArch(runtime.GOARCH, detectMacOSHardwareArch()) {
|
||||||
@@ -172,7 +175,6 @@ func detectMacOSHardwareArch() string {
|
|||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
// On Apple Silicon, this stays "1" even if the app itself runs under Rosetta.
|
|
||||||
cmd := exec.Command("sysctl", "-in", "hw.optional.arm64")
|
cmd := exec.Command("sysctl", "-in", "hw.optional.arm64")
|
||||||
hideWindow(cmd)
|
hideWindow(cmd)
|
||||||
output, err := cmd.Output()
|
output, err := cmd.Output()
|
||||||
|
|||||||
+15
-4
@@ -2,6 +2,7 @@ package backend
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"archive/zip"
|
"archive/zip"
|
||||||
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
@@ -17,9 +18,9 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
ffmpegReleaseAPIURL = "https://api.github.com/repos/afkarxyz/ffmpeg-binaries/releases/latest"
|
ffmpegReleaseAPIURL = "https://api.github.com/repos/spotbye/Dependencies/releases/tags/FFmpeg-8.1"
|
||||||
ffmpegLatestReleaseURL = "https://github.com/afkarxyz/ffmpeg-binaries/releases/latest"
|
ffmpegLatestReleaseURL = "https://github.com/spotbye/Dependencies/releases/tag/FFmpeg-8.1"
|
||||||
ffmpegLatestDownloadBaseURL = "https://github.com/afkarxyz/ffmpeg-binaries/releases/latest/download"
|
ffmpegLatestDownloadBaseURL = "https://github.com/spotbye/Dependencies/releases/download/FFmpeg-8.1"
|
||||||
)
|
)
|
||||||
|
|
||||||
var ffmpegVersionPattern = regexp.MustCompile(`^[0-9]+(?:\.[0-9]+)+`)
|
var ffmpegVersionPattern = regexp.MustCompile(`^[0-9]+(?:\.[0-9]+)+`)
|
||||||
@@ -531,11 +532,18 @@ func normalizeFFmpegVersion(version string) string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func ConvertMP4ToGIF(inputPath, outputPath, quality, resolution string) error {
|
func ConvertMP4ToGIF(inputPath, outputPath, quality, resolution string) error {
|
||||||
|
return ConvertMP4ToGIFWithContext(context.Background(), inputPath, outputPath, quality, resolution)
|
||||||
|
}
|
||||||
|
|
||||||
|
func ConvertMP4ToGIFWithContext(ctx context.Context, inputPath, outputPath, quality, resolution string) error {
|
||||||
ffmpegPath := GetFFmpegPath()
|
ffmpegPath := GetFFmpegPath()
|
||||||
|
|
||||||
if !IsFFmpegInstalled() {
|
if !IsFFmpegInstalled() {
|
||||||
return fmt.Errorf("ffmpeg not installed")
|
return fmt.Errorf("ffmpeg not installed")
|
||||||
}
|
}
|
||||||
|
if ctx == nil {
|
||||||
|
ctx = context.Background()
|
||||||
|
}
|
||||||
|
|
||||||
var args []string
|
var args []string
|
||||||
|
|
||||||
@@ -598,10 +606,13 @@ func ConvertMP4ToGIF(inputPath, outputPath, quality, resolution string) error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
cmd := exec.Command(ffmpegPath, args...)
|
cmd := exec.CommandContext(ctx, ffmpegPath, args...)
|
||||||
hideWindow(cmd)
|
hideWindow(cmd)
|
||||||
output, err := cmd.CombinedOutput()
|
output, err := cmd.CombinedOutput()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
if ctx.Err() != nil {
|
||||||
|
return ctx.Err()
|
||||||
|
}
|
||||||
return fmt.Errorf("ffmpeg error: %v, output: %s", err, string(output))
|
return fmt.Errorf("ffmpeg error: %v, output: %s", err, string(output))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+10
-2
@@ -11,12 +11,20 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func OpenFolderInExplorer(path string) error {
|
func OpenFolderInExplorer(path string) error {
|
||||||
|
os.WriteFile(filepath.Join(os.TempDir(), "openfolder.txt"), []byte(path), 0644)
|
||||||
|
info, err := os.Stat(path)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !info.IsDir() {
|
||||||
|
return os.ErrInvalid
|
||||||
|
}
|
||||||
|
|
||||||
var cmd *exec.Cmd
|
var cmd *exec.Cmd
|
||||||
|
|
||||||
switch runtime.GOOS {
|
switch runtime.GOOS {
|
||||||
case "windows":
|
case "windows":
|
||||||
|
cmd = exec.Command("cmd", "/C", "start", "", path)
|
||||||
cmd = exec.Command("cmd", "/c", "start", "", path)
|
|
||||||
case "darwin":
|
case "darwin":
|
||||||
cmd = exec.Command("open", path)
|
cmd = exec.Command("open", path)
|
||||||
case "linux":
|
case "linux":
|
||||||
|
|||||||
+34
-14
@@ -1,6 +1,7 @@
|
|||||||
package backend
|
package backend
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/url"
|
"net/url"
|
||||||
"os"
|
"os"
|
||||||
@@ -11,6 +12,11 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
filenameSafeRegex = regexp.MustCompile(`^[A-Za-z0-9_]+$`)
|
||||||
|
filenameLetterRegex = regexp.MustCompile(`[A-Za-z]`)
|
||||||
|
)
|
||||||
|
|
||||||
func ExtractOriginalFilename(mediaURL string) string {
|
func ExtractOriginalFilename(mediaURL string) string {
|
||||||
parsedURL, err := url.Parse(mediaURL)
|
parsedURL, err := url.Parse(mediaURL)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -29,7 +35,7 @@ func ExtractOriginalFilename(mediaURL string) string {
|
|||||||
filename = filename[:idx]
|
filename = filename[:idx]
|
||||||
}
|
}
|
||||||
|
|
||||||
if matched, _ := regexp.MatchString(`^[A-Za-z0-9_]+$`, filename); matched && len(filename) > 0 {
|
if filenameSafeRegex.MatchString(filename) && len(filename) > 0 {
|
||||||
return filename
|
return filename
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -44,7 +50,7 @@ func ExtractOriginalFilename(mediaURL string) string {
|
|||||||
filename = filename[:idx]
|
filename = filename[:idx]
|
||||||
}
|
}
|
||||||
|
|
||||||
if matched, _ := regexp.MatchString(`^[A-Za-z0-9_]+$`, filename); matched && len(filename) > 0 {
|
if filenameSafeRegex.MatchString(filename) && len(filename) > 0 {
|
||||||
return filename
|
return filename
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -58,9 +64,8 @@ func ExtractOriginalFilename(mediaURL string) string {
|
|||||||
filename = filename[:idx]
|
filename = filename[:idx]
|
||||||
}
|
}
|
||||||
|
|
||||||
if matched, _ := regexp.MatchString(`^[A-Za-z0-9_]+$`, filename); matched {
|
if filenameSafeRegex.MatchString(filename) {
|
||||||
hasLetter, _ := regexp.MatchString(`[A-Za-z]`, filename)
|
if filenameLetterRegex.MatchString(filename) && len(filename) >= 8 {
|
||||||
if hasLetter && len(filename) >= 8 {
|
|
||||||
return filename
|
return filename
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -70,21 +75,24 @@ func ExtractOriginalFilename(mediaURL string) string {
|
|||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
func EmbedMetadata(filePath string, tweetContent string, tweetURL string, originalFilename string) error {
|
func EmbedMetadata(ctx context.Context, filePath string, tweetContent string, tweetURL string, originalFilename string) error {
|
||||||
ext := strings.ToLower(filepath.Ext(filePath))
|
ext := strings.ToLower(filepath.Ext(filePath))
|
||||||
|
|
||||||
switch ext {
|
switch ext {
|
||||||
case ".jpg", ".jpeg":
|
case ".jpg", ".jpeg":
|
||||||
return embedImageMetadata(filePath, tweetContent, tweetURL, originalFilename)
|
return embedImageMetadata(ctx, filePath, tweetContent, tweetURL, originalFilename)
|
||||||
case ".mp4":
|
case ".mp4":
|
||||||
return embedVideoMetadata(filePath, tweetContent, tweetURL, originalFilename)
|
return embedVideoMetadata(ctx, filePath, tweetContent, tweetURL, originalFilename)
|
||||||
default:
|
default:
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func embedImageMetadata(filePath string, tweetContent string, tweetURL string, originalFilename string) error {
|
func embedImageMetadata(ctx context.Context, filePath string, tweetContent string, tweetURL string, originalFilename string) error {
|
||||||
|
if ctx == nil {
|
||||||
|
ctx = context.Background()
|
||||||
|
}
|
||||||
|
|
||||||
exiftoolPath := findExifTool()
|
exiftoolPath := findExifTool()
|
||||||
if exiftoolPath == "" {
|
if exiftoolPath == "" {
|
||||||
@@ -100,10 +108,13 @@ func embedImageMetadata(filePath string, tweetContent string, tweetURL string, o
|
|||||||
filePath,
|
filePath,
|
||||||
}
|
}
|
||||||
|
|
||||||
cmd := exec.Command(exiftoolPath, args...)
|
cmd := exec.CommandContext(ctx, exiftoolPath, args...)
|
||||||
hideWindow(cmd)
|
hideWindow(cmd)
|
||||||
output, err := cmd.CombinedOutput()
|
output, err := cmd.CombinedOutput()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
if ctx.Err() != nil {
|
||||||
|
return ctx.Err()
|
||||||
|
}
|
||||||
|
|
||||||
return fmt.Errorf("exiftool error (non-fatal): %v, output: %s", err, string(output))
|
return fmt.Errorf("exiftool error (non-fatal): %v, output: %s", err, string(output))
|
||||||
}
|
}
|
||||||
@@ -112,7 +123,10 @@ func embedImageMetadata(filePath string, tweetContent string, tweetURL string, o
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func embedVideoMetadata(filePath string, tweetContent string, tweetURL string, originalFilename string) error {
|
func embedVideoMetadata(ctx context.Context, filePath string, tweetContent string, tweetURL string, originalFilename string) error {
|
||||||
|
if ctx == nil {
|
||||||
|
ctx = context.Background()
|
||||||
|
}
|
||||||
|
|
||||||
exiftoolPath := findExifTool()
|
exiftoolPath := findExifTool()
|
||||||
if exiftoolPath == "" {
|
if exiftoolPath == "" {
|
||||||
@@ -120,10 +134,13 @@ func embedVideoMetadata(filePath string, tweetContent string, tweetURL string, o
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
return embedVideoMetadataWithExifTool(exiftoolPath, filePath, tweetContent, tweetURL, originalFilename)
|
return embedVideoMetadataWithExifTool(ctx, exiftoolPath, filePath, tweetContent, tweetURL, originalFilename)
|
||||||
}
|
}
|
||||||
|
|
||||||
func embedVideoMetadataWithExifTool(exiftoolPath string, filePath string, tweetContent string, tweetURL string, originalFilename string) error {
|
func embedVideoMetadataWithExifTool(ctx context.Context, exiftoolPath string, filePath string, tweetContent string, tweetURL string, originalFilename string) error {
|
||||||
|
if ctx == nil {
|
||||||
|
ctx = context.Background()
|
||||||
|
}
|
||||||
|
|
||||||
metadataComment := buildMetadataComment(tweetContent, tweetURL, originalFilename)
|
metadataComment := buildMetadataComment(tweetContent, tweetURL, originalFilename)
|
||||||
|
|
||||||
@@ -133,10 +150,13 @@ func embedVideoMetadataWithExifTool(exiftoolPath string, filePath string, tweetC
|
|||||||
filePath,
|
filePath,
|
||||||
}
|
}
|
||||||
|
|
||||||
cmd := exec.Command(exiftoolPath, args...)
|
cmd := exec.CommandContext(ctx, exiftoolPath, args...)
|
||||||
hideWindow(cmd)
|
hideWindow(cmd)
|
||||||
output, err := cmd.CombinedOutput()
|
output, err := cmd.CombinedOutput()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
if ctx.Err() != nil {
|
||||||
|
return ctx.Err()
|
||||||
|
}
|
||||||
|
|
||||||
return fmt.Errorf("exiftool error (non-fatal): %v, output: %s", err, string(output))
|
return fmt.Errorf("exiftool error (non-fatal): %v, output: %s", err, string(output))
|
||||||
}
|
}
|
||||||
|
|||||||
+419
-320
@@ -9,6 +9,7 @@ import (
|
|||||||
"os/exec"
|
"os/exec"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"runtime"
|
"runtime"
|
||||||
|
"sort"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
)
|
)
|
||||||
@@ -82,7 +83,7 @@ func KillAllExtractorProcesses() {
|
|||||||
|
|
||||||
for _, cmd := range commands {
|
for _, cmd := range commands {
|
||||||
if cmd != nil && cmd.Process != nil {
|
if cmd != nil && cmd.Process != nil {
|
||||||
_ = cmd.Process.Kill()
|
_ = terminateCommandProcess(cmd)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -110,11 +111,11 @@ func parseExtractorError(output string, username string) string {
|
|||||||
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]"
|
||||||
} else if strings.Contains(outputLower, "rate limit") || strings.Contains(output, "429") {
|
} else if strings.Contains(outputLower, "rate limit") || strings.Contains(outputLower, "rate_limited") || strings.Contains(output, "429") {
|
||||||
hint = " [Hint: Wait 5-15 minutes before retrying]"
|
hint = " [Hint: Wait 5-15 minutes before retrying]"
|
||||||
} else if strings.Contains(output, "401") || strings.Contains(outputLower, "unauthorized") {
|
} else if strings.Contains(output, "401") || strings.Contains(outputLower, "unauthorized") || strings.Contains(outputLower, "auth_invalid") {
|
||||||
hint = " [Hint: Auth token may be invalid or expired]"
|
hint = " [Hint: Auth token may be invalid or expired]"
|
||||||
} else if strings.Contains(output, "404") {
|
} else if strings.Contains(output, "404") || strings.Contains(outputLower, "user_not_found") {
|
||||||
hint = fmt.Sprintf(" [Hint: @%s may not exist or is suspended]", username)
|
hint = fmt.Sprintf(" [Hint: @%s may not exist or is suspended]", username)
|
||||||
} else if strings.Contains(outputLower, "protected") || strings.Contains(output, "403") {
|
} else if strings.Contains(outputLower, "protected") || strings.Contains(output, "403") {
|
||||||
hint = " [Hint: Protected account - need to follow and use auth token]"
|
hint = " [Hint: Protected account - need to follow and use auth token]"
|
||||||
@@ -149,85 +150,103 @@ 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")
|
||||||
}
|
}
|
||||||
|
|
||||||
type Author struct {
|
type richThumb struct {
|
||||||
ID int64 `json:"id"`
|
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
Nick string `json:"nick"`
|
URL string `json:"url"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type UserInfo struct {
|
type richSize struct {
|
||||||
ID int64 `json:"id"`
|
W int `json:"w"`
|
||||||
Name string `json:"name"`
|
H int `json:"h"`
|
||||||
Nick string `json:"nick"`
|
Resize string `json:"resize"`
|
||||||
Location string `json:"location"`
|
URL string `json:"url"`
|
||||||
Date string `json:"date"`
|
|
||||||
Verified bool `json:"verified"`
|
|
||||||
Protected bool `json:"protected"`
|
|
||||||
ProfileBanner string `json:"profile_banner"`
|
|
||||||
ProfileImage string `json:"profile_image"`
|
|
||||||
FavouritesCount int `json:"favourites_count"`
|
|
||||||
FollowersCount int `json:"followers_count"`
|
|
||||||
FriendsCount int `json:"friends_count"`
|
|
||||||
ListedCount int `json:"listed_count"`
|
|
||||||
MediaCount int `json:"media_count"`
|
|
||||||
StatusesCount int `json:"statuses_count"`
|
|
||||||
Description string `json:"description"`
|
|
||||||
URL string `json:"url"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type CLIMediaItem struct {
|
type richVariant struct {
|
||||||
URL string `json:"url"`
|
ContentType string `json:"content_type"`
|
||||||
TweetID TweetIDString `json:"tweet_id"`
|
URL string `json:"url"`
|
||||||
RetweetID TweetIDString `json:"retweet_id"`
|
Bitrate int `json:"bitrate"`
|
||||||
QuoteID TweetIDString `json:"quote_id"`
|
Resolution string `json:"resolution"`
|
||||||
ReplyID TweetIDString `json:"reply_id"`
|
|
||||||
ConversationID TweetIDString `json:"conversation_id"`
|
|
||||||
Date string `json:"date"`
|
|
||||||
Extension string `json:"extension"`
|
|
||||||
Width int `json:"width"`
|
|
||||||
Height int `json:"height"`
|
|
||||||
Type string `json:"type"`
|
|
||||||
Bitrate int `json:"bitrate"`
|
|
||||||
Duration float64 `json:"duration"`
|
|
||||||
Author UserInfo `json:"author"`
|
|
||||||
User UserInfo `json:"user"`
|
|
||||||
Content string `json:"content"`
|
|
||||||
FavoriteCount int `json:"favorite_count"`
|
|
||||||
RetweetCount int `json:"retweet_count"`
|
|
||||||
ReplyCount int `json:"reply_count"`
|
|
||||||
QuoteCount int `json:"quote_count"`
|
|
||||||
BookmarkCount int `json:"bookmark_count"`
|
|
||||||
ViewCount int `json:"view_count"`
|
|
||||||
Source string `json:"source"`
|
|
||||||
Sensitive bool `json:"sensitive"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type TweetMetadata struct {
|
type richMedia struct {
|
||||||
TweetID TweetIDString `json:"tweet_id"`
|
Type string `json:"type"`
|
||||||
RetweetID TweetIDString `json:"retweet_id,omitempty"`
|
MediaID string `json:"media_id"`
|
||||||
QuoteID TweetIDString `json:"quote_id,omitempty"`
|
MediaKey string `json:"media_key"`
|
||||||
ReplyID TweetIDString `json:"reply_id,omitempty"`
|
Thumbnail string `json:"thumbnail"`
|
||||||
ConversationID TweetIDString `json:"conversation_id,omitempty"`
|
ExpandedURL string `json:"expanded_url"`
|
||||||
Date string `json:"date"`
|
Width int `json:"width"`
|
||||||
Author Author `json:"author"`
|
Height int `json:"height"`
|
||||||
Content string `json:"content"`
|
AspectRatio []int `json:"aspect_ratio"`
|
||||||
Lang string `json:"lang,omitempty"`
|
DurationMS int `json:"duration_ms"`
|
||||||
Hashtags []string `json:"hashtags,omitempty"`
|
AltText string `json:"alt_text"`
|
||||||
FavoriteCount int `json:"favorite_count"`
|
Sizes map[string]richSize `json:"sizes"`
|
||||||
RetweetCount int `json:"retweet_count"`
|
Thumbs []richThumb `json:"thumbs"`
|
||||||
QuoteCount int `json:"quote_count,omitempty"`
|
Variants []richVariant `json:"variants"`
|
||||||
ReplyCount int `json:"reply_count,omitempty"`
|
|
||||||
BookmarkCount int `json:"bookmark_count,omitempty"`
|
|
||||||
ViewCount int `json:"view_count,omitempty"`
|
|
||||||
Sensitive bool `json:"sensitive,omitempty"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type CLIResponse struct {
|
type richMiniUser struct {
|
||||||
Media []CLIMediaItem `json:"media"`
|
UserID string `json:"user_id"`
|
||||||
Metadata []TweetMetadata `json:"metadata"`
|
Username string `json:"username"`
|
||||||
Cursor string `json:"cursor,omitempty"`
|
Name string `json:"name"`
|
||||||
Total int `json:"total,omitempty"`
|
Avatar string `json:"avatar"`
|
||||||
Completed bool `json:"completed,omitempty"`
|
Verified bool `json:"verified"`
|
||||||
|
BlueVerified bool `json:"blue_verified"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type richStats struct {
|
||||||
|
Likes int `json:"likes"`
|
||||||
|
Retweets int `json:"retweets"`
|
||||||
|
Replies int `json:"replies"`
|
||||||
|
Quotes int `json:"quotes"`
|
||||||
|
Bookmarks int `json:"bookmarks"`
|
||||||
|
Views int `json:"views"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type richTweet struct {
|
||||||
|
TweetID string `json:"tweet_id"`
|
||||||
|
URL string `json:"url"`
|
||||||
|
Text string `json:"text"`
|
||||||
|
Lang string `json:"lang"`
|
||||||
|
CreatedAt string `json:"created_at"`
|
||||||
|
Source string `json:"source"`
|
||||||
|
Sensitive bool `json:"sensitive"`
|
||||||
|
IsRepost bool `json:"is_repost"`
|
||||||
|
IsReply bool `json:"is_reply"`
|
||||||
|
IsQuote bool `json:"is_quote"`
|
||||||
|
RepostedBy *richMiniUser `json:"reposted_by"`
|
||||||
|
Author richMiniUser `json:"author"`
|
||||||
|
Stats richStats `json:"stats"`
|
||||||
|
Media []richMedia `json:"media"`
|
||||||
|
Hashtags []string `json:"hashtags"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type richAccount struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Username string `json:"username"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Bio string `json:"bio"`
|
||||||
|
Avatar string `json:"avatar"`
|
||||||
|
AvatarVariants []richThumb `json:"avatar_variants"`
|
||||||
|
Banner string `json:"banner"`
|
||||||
|
BannerVariants []richThumb `json:"banner_variants"`
|
||||||
|
Location string `json:"location"`
|
||||||
|
URL string `json:"url"`
|
||||||
|
CreatedAt string `json:"created_at"`
|
||||||
|
Followers int `json:"followers"`
|
||||||
|
Following int `json:"following"`
|
||||||
|
Tweets int `json:"tweets"`
|
||||||
|
MediaCount int `json:"media_count"`
|
||||||
|
Protected bool `json:"protected"`
|
||||||
|
Verified bool `json:"verified"`
|
||||||
|
BlueVerified bool `json:"blue_verified"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type richResponse struct {
|
||||||
|
Account richAccount `json:"account"`
|
||||||
|
Tweets []richTweet `json:"tweets"`
|
||||||
|
NextCursor string `json:"next_cursor"`
|
||||||
|
HasMore bool `json:"has_more"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type TimelineEntry struct {
|
type TimelineEntry struct {
|
||||||
@@ -239,26 +258,41 @@ type TimelineEntry struct {
|
|||||||
Extension string `json:"extension"`
|
Extension string `json:"extension"`
|
||||||
Width int `json:"width"`
|
Width int `json:"width"`
|
||||||
Height int `json:"height"`
|
Height int `json:"height"`
|
||||||
|
Thumbnail string `json:"thumbnail,omitempty"`
|
||||||
|
DurationMS int `json:"duration_ms,omitempty"`
|
||||||
|
AltText string `json:"alt_text,omitempty"`
|
||||||
Content string `json:"content,omitempty"`
|
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"`
|
||||||
|
QuoteCount int `json:"quote_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"`
|
OriginalFilename string `json:"original_filename,omitempty"`
|
||||||
AuthorUsername string `json:"author_username,omitempty"`
|
AuthorUsername string `json:"author_username,omitempty"`
|
||||||
|
AuthorName string `json:"author_name,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type AccountInfo struct {
|
type AccountInfo struct {
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
Nick string `json:"nick"`
|
Nick string `json:"nick"`
|
||||||
Date string `json:"date"`
|
Date string `json:"date"`
|
||||||
FollowersCount int `json:"followers_count"`
|
FollowersCount int `json:"followers_count"`
|
||||||
FriendsCount int `json:"friends_count"`
|
FriendsCount int `json:"friends_count"`
|
||||||
ProfileImage string `json:"profile_image"`
|
ProfileImage string `json:"profile_image"`
|
||||||
StatusesCount int `json:"statuses_count"`
|
StatusesCount int `json:"statuses_count"`
|
||||||
|
Bio string `json:"bio,omitempty"`
|
||||||
|
Banner string `json:"banner,omitempty"`
|
||||||
|
Location string `json:"location,omitempty"`
|
||||||
|
URL string `json:"url,omitempty"`
|
||||||
|
MediaCount int `json:"media_count,omitempty"`
|
||||||
|
Verified bool `json:"verified,omitempty"`
|
||||||
|
BlueVerified bool `json:"blue_verified,omitempty"`
|
||||||
|
Protected bool `json:"protected,omitempty"`
|
||||||
|
AvatarVariants []richThumb `json:"avatar_variants,omitempty"`
|
||||||
|
BannerVariants []richThumb `json:"banner_variants,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type ExtractMetadata struct {
|
type ExtractMetadata struct {
|
||||||
@@ -280,14 +314,20 @@ type TwitterResponse struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type TimelineRequest struct {
|
type TimelineRequest struct {
|
||||||
Username string `json:"username"`
|
Username string `json:"username"`
|
||||||
AuthToken string `json:"auth_token"`
|
AuthToken string `json:"auth_token"`
|
||||||
TimelineType string `json:"timeline_type"`
|
TimelineType string `json:"timeline_type"`
|
||||||
BatchSize int `json:"batch_size"`
|
BatchSize int `json:"batch_size"`
|
||||||
Page int `json:"page"`
|
Page int `json:"page"`
|
||||||
MediaType string `json:"media_type"`
|
MediaType string `json:"media_type"`
|
||||||
Retweets bool `json:"retweets"`
|
Retweets bool `json:"retweets"`
|
||||||
Cursor string `json:"cursor,omitempty"`
|
Cursor string `json:"cursor,omitempty"`
|
||||||
|
IncludePhotos bool `json:"include_photos"`
|
||||||
|
IncludeVideos bool `json:"include_videos"`
|
||||||
|
IncludeGifs bool `json:"include_gifs"`
|
||||||
|
IncludeText bool `json:"include_text"`
|
||||||
|
VideoQuality string `json:"video_quality,omitempty"`
|
||||||
|
ImageSize string `json:"image_size,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type DateRangeRequest struct {
|
type DateRangeRequest struct {
|
||||||
@@ -402,74 +442,252 @@ 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)
|
||||||
}
|
}
|
||||||
|
|
||||||
func convertMetadataToTimelineEntry(meta TweetMetadata) TimelineEntry {
|
func parseTweetID(s string) TweetIDString {
|
||||||
return TimelineEntry{
|
var n int64
|
||||||
URL: "",
|
_, _ = fmt.Sscanf(strings.TrimSpace(s), "%d", &n)
|
||||||
Date: meta.Date,
|
return TweetIDString(n)
|
||||||
TweetID: meta.TweetID,
|
|
||||||
Type: "text",
|
|
||||||
IsRetweet: meta.RetweetID != 0,
|
|
||||||
Extension: "txt",
|
|
||||||
Width: 0,
|
|
||||||
Height: 0,
|
|
||||||
Content: meta.Content,
|
|
||||||
ViewCount: meta.ViewCount,
|
|
||||||
BookmarkCount: meta.BookmarkCount,
|
|
||||||
FavoriteCount: meta.FavoriteCount,
|
|
||||||
RetweetCount: meta.RetweetCount,
|
|
||||||
ReplyCount: meta.ReplyCount,
|
|
||||||
AuthorUsername: meta.Author.Name,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func convertToTimelineEntry(media CLIMediaItem) TimelineEntry {
|
func bestPhotoURL(m richMedia, size string) string {
|
||||||
|
if size == "" {
|
||||||
authorUsername := ""
|
size = "orig"
|
||||||
if media.Author.Name != "" {
|
|
||||||
authorUsername = media.Author.Name
|
|
||||||
} else if media.User.Name != "" {
|
|
||||||
authorUsername = media.User.Name
|
|
||||||
}
|
}
|
||||||
|
if size == "orig" {
|
||||||
entry := TimelineEntry{
|
for _, t := range m.Thumbs {
|
||||||
URL: media.URL,
|
if t.Name == "orig" {
|
||||||
TweetID: media.TweetID,
|
return t.URL
|
||||||
Date: media.Date,
|
}
|
||||||
Extension: media.Extension,
|
}
|
||||||
Width: media.Width,
|
} else if s, ok := m.Sizes[size]; ok && s.URL != "" {
|
||||||
Height: media.Height,
|
return s.URL
|
||||||
IsRetweet: media.RetweetID != 0,
|
|
||||||
Content: media.Content,
|
|
||||||
ViewCount: media.ViewCount,
|
|
||||||
BookmarkCount: media.BookmarkCount,
|
|
||||||
FavoriteCount: media.FavoriteCount,
|
|
||||||
RetweetCount: media.RetweetCount,
|
|
||||||
ReplyCount: media.ReplyCount,
|
|
||||||
Source: media.Source,
|
|
||||||
Verified: media.Author.Verified,
|
|
||||||
AuthorUsername: authorUsername,
|
|
||||||
}
|
}
|
||||||
|
if s, ok := m.Sizes["large"]; ok && s.URL != "" {
|
||||||
|
return s.URL
|
||||||
|
}
|
||||||
|
if s, ok := m.Sizes["medium"]; ok && s.URL != "" {
|
||||||
|
return s.URL
|
||||||
|
}
|
||||||
|
if s, ok := m.Sizes["small"]; ok && s.URL != "" {
|
||||||
|
return s.URL
|
||||||
|
}
|
||||||
|
return m.Thumbnail
|
||||||
|
}
|
||||||
|
|
||||||
if media.Type != "" {
|
func bestVideoURL(m richMedia, quality string) string {
|
||||||
entry.Type = media.Type
|
mp4s := make([]richVariant, 0, len(m.Variants))
|
||||||
} else {
|
for _, v := range m.Variants {
|
||||||
switch strings.ToLower(media.Extension) {
|
if v.ContentType == "video/mp4" && v.URL != "" {
|
||||||
case "mp4", "webm":
|
mp4s = append(mp4s, v)
|
||||||
entry.Type = "video"
|
|
||||||
case "gif":
|
|
||||||
entry.Type = "gif"
|
|
||||||
default:
|
|
||||||
entry.Type = "photo"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if len(mp4s) == 0 {
|
||||||
|
if len(m.Variants) > 0 {
|
||||||
|
return m.Variants[len(m.Variants)-1].URL
|
||||||
|
}
|
||||||
|
return m.Thumbnail
|
||||||
|
}
|
||||||
|
sort.Slice(mp4s, func(i, j int) bool { return mp4s[i].Bitrate < mp4s[j].Bitrate })
|
||||||
|
|
||||||
return entry
|
switch quality {
|
||||||
|
case "lowest":
|
||||||
|
return mp4s[0].URL
|
||||||
|
case "", "highest":
|
||||||
|
return mp4s[len(mp4s)-1].URL
|
||||||
|
}
|
||||||
|
|
||||||
|
target := 0
|
||||||
|
_, _ = fmt.Sscanf(quality, "%d", &target)
|
||||||
|
if target == 0 {
|
||||||
|
return mp4s[len(mp4s)-1].URL
|
||||||
|
}
|
||||||
|
best := mp4s[0]
|
||||||
|
bestDelta := 1 << 30
|
||||||
|
for _, v := range mp4s {
|
||||||
|
h := resolutionHeight(v.Resolution)
|
||||||
|
delta := h - target
|
||||||
|
if delta < 0 {
|
||||||
|
delta = -delta
|
||||||
|
}
|
||||||
|
if delta < bestDelta {
|
||||||
|
bestDelta = delta
|
||||||
|
best = v
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return best.URL
|
||||||
}
|
}
|
||||||
|
|
||||||
func getExtractorPath() string {
|
func resolutionHeight(resolution string) int {
|
||||||
homeDir, _ := os.UserHomeDir()
|
if i := strings.Index(resolution, "x"); i >= 0 {
|
||||||
baseDir := filepath.Join(homeDir, ".twitterxmediabatchdownloader")
|
h := 0
|
||||||
return filepath.Join(baseDir, getExecutableName())
|
_, _ = fmt.Sscanf(resolution[i+1:], "%d", &h)
|
||||||
|
return h
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func previewURL(m richMedia) string {
|
||||||
|
for _, t := range m.Thumbs {
|
||||||
|
if t.Name == "360x360" {
|
||||||
|
return t.URL
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if s, ok := m.Sizes["small"]; ok && s.URL != "" {
|
||||||
|
return s.URL
|
||||||
|
}
|
||||||
|
return m.Thumbnail
|
||||||
|
}
|
||||||
|
|
||||||
|
func extensionFor(downloadURL, mediaType string) string {
|
||||||
|
switch mediaType {
|
||||||
|
case "video", "gif", "animated_gif":
|
||||||
|
return "mp4"
|
||||||
|
}
|
||||||
|
if i := strings.Index(downloadURL, "format="); i >= 0 {
|
||||||
|
rest := downloadURL[i+len("format="):]
|
||||||
|
if amp := strings.IndexByte(rest, '&'); amp >= 0 {
|
||||||
|
rest = rest[:amp]
|
||||||
|
}
|
||||||
|
if rest != "" {
|
||||||
|
return rest
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "jpg"
|
||||||
|
}
|
||||||
|
|
||||||
|
func isVerified(u richMiniUser) bool {
|
||||||
|
return u.Verified || u.BlueVerified
|
||||||
|
}
|
||||||
|
|
||||||
|
func textEntry(t richTweet) TimelineEntry {
|
||||||
|
return TimelineEntry{
|
||||||
|
URL: "",
|
||||||
|
Date: t.CreatedAt,
|
||||||
|
TweetID: parseTweetID(t.TweetID),
|
||||||
|
Type: "text",
|
||||||
|
IsRetweet: t.IsRepost,
|
||||||
|
Extension: "txt",
|
||||||
|
Content: t.Text,
|
||||||
|
ViewCount: t.Stats.Views,
|
||||||
|
BookmarkCount: t.Stats.Bookmarks,
|
||||||
|
FavoriteCount: t.Stats.Likes,
|
||||||
|
RetweetCount: t.Stats.Retweets,
|
||||||
|
ReplyCount: t.Stats.Replies,
|
||||||
|
QuoteCount: t.Stats.Quotes,
|
||||||
|
Source: t.Source,
|
||||||
|
Verified: isVerified(t.Author),
|
||||||
|
AuthorUsername: t.Author.Username,
|
||||||
|
AuthorName: t.Author.Name,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func mediaEntry(t richTweet, m richMedia, videoQuality, imageSize string) TimelineEntry {
|
||||||
|
var downloadURL string
|
||||||
|
switch m.Type {
|
||||||
|
case "video", "animated_gif", "gif":
|
||||||
|
downloadURL = bestVideoURL(m, videoQuality)
|
||||||
|
default:
|
||||||
|
downloadURL = bestPhotoURL(m, imageSize)
|
||||||
|
}
|
||||||
|
return TimelineEntry{
|
||||||
|
URL: downloadURL,
|
||||||
|
Date: t.CreatedAt,
|
||||||
|
TweetID: parseTweetID(t.TweetID),
|
||||||
|
Type: m.Type,
|
||||||
|
IsRetweet: t.IsRepost,
|
||||||
|
Extension: extensionFor(downloadURL, m.Type),
|
||||||
|
Width: m.Width,
|
||||||
|
Height: m.Height,
|
||||||
|
Thumbnail: previewURL(m),
|
||||||
|
DurationMS: m.DurationMS,
|
||||||
|
AltText: m.AltText,
|
||||||
|
Content: t.Text,
|
||||||
|
ViewCount: t.Stats.Views,
|
||||||
|
BookmarkCount: t.Stats.Bookmarks,
|
||||||
|
FavoriteCount: t.Stats.Likes,
|
||||||
|
RetweetCount: t.Stats.Retweets,
|
||||||
|
ReplyCount: t.Stats.Replies,
|
||||||
|
QuoteCount: t.Stats.Quotes,
|
||||||
|
Source: t.Source,
|
||||||
|
Verified: isVerified(t.Author),
|
||||||
|
AuthorUsername: t.Author.Username,
|
||||||
|
AuthorName: t.Author.Name,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type FlattenOptions struct {
|
||||||
|
IncludePhotos bool
|
||||||
|
IncludeVideos bool
|
||||||
|
IncludeGifs bool
|
||||||
|
IncludeText bool
|
||||||
|
VideoQuality string
|
||||||
|
ImageSize string
|
||||||
|
}
|
||||||
|
|
||||||
|
func flattenTweets(tweets []richTweet, opts FlattenOptions) []TimelineEntry {
|
||||||
|
out := make([]TimelineEntry, 0, len(tweets))
|
||||||
|
for _, t := range tweets {
|
||||||
|
if len(t.Media) == 0 {
|
||||||
|
if opts.IncludeText && strings.TrimSpace(t.Text) != "" {
|
||||||
|
out = append(out, textEntry(t))
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for _, m := range t.Media {
|
||||||
|
switch m.Type {
|
||||||
|
case "photo":
|
||||||
|
if !opts.IncludePhotos {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
case "video":
|
||||||
|
if !opts.IncludeVideos {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
case "animated_gif", "gif":
|
||||||
|
if !opts.IncludeGifs {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out = append(out, mediaEntry(t, m, opts.VideoQuality, opts.ImageSize))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func buildAccountInfo(acc richAccount, fallbackUsername string) AccountInfo {
|
||||||
|
info := AccountInfo{
|
||||||
|
Name: fallbackUsername,
|
||||||
|
Nick: fallbackUsername,
|
||||||
|
}
|
||||||
|
if acc.Username != "" {
|
||||||
|
info.Name = acc.Username
|
||||||
|
}
|
||||||
|
if acc.Name != "" {
|
||||||
|
info.Nick = acc.Name
|
||||||
|
}
|
||||||
|
info.Date = acc.CreatedAt
|
||||||
|
info.FollowersCount = acc.Followers
|
||||||
|
info.FriendsCount = acc.Following
|
||||||
|
info.ProfileImage = acc.Avatar
|
||||||
|
info.StatusesCount = acc.Tweets
|
||||||
|
info.Bio = acc.Bio
|
||||||
|
info.Banner = acc.Banner
|
||||||
|
info.Location = acc.Location
|
||||||
|
info.URL = acc.URL
|
||||||
|
info.MediaCount = acc.MediaCount
|
||||||
|
info.Verified = acc.Verified
|
||||||
|
info.BlueVerified = acc.BlueVerified
|
||||||
|
info.Protected = acc.Protected
|
||||||
|
info.AvatarVariants = acc.AvatarVariants
|
||||||
|
info.BannerVariants = acc.BannerVariants
|
||||||
|
return info
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseRichResponse(jsonStr string) (*richResponse, error) {
|
||||||
|
var resp richResponse
|
||||||
|
if err := json.Unmarshal([]byte(jsonStr), &resp); err != nil {
|
||||||
|
return nil, fmt.Errorf("json_error: Failed to parse JSON response: %v", err)
|
||||||
|
}
|
||||||
|
return &resp, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func ExtractTimeline(req TimelineRequest) (*TwitterResponse, error) {
|
func ExtractTimeline(req TimelineRequest) (*TwitterResponse, error) {
|
||||||
@@ -479,26 +697,20 @@ func ExtractTimeline(req TimelineRequest) (*TwitterResponse, error) {
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
isTextOnly := req.MediaType == "text"
|
includeText := req.IncludeText
|
||||||
wantsRetweets := req.Retweets
|
|
||||||
|
|
||||||
timelineType := req.TimelineType
|
timelineType := req.TimelineType
|
||||||
if timelineType == "" {
|
if timelineType == "" {
|
||||||
if isTextOnly {
|
if includeText {
|
||||||
|
|
||||||
timelineType = "tweets"
|
|
||||||
} else if wantsRetweets {
|
|
||||||
|
|
||||||
timelineType = "tweets"
|
timelineType = "tweets"
|
||||||
} else {
|
} else {
|
||||||
|
|
||||||
timelineType = "media"
|
timelineType = "media"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := buildTwitterURL(req.Username, timelineType)
|
targetURL := buildTwitterURL(req.Username, timelineType)
|
||||||
|
|
||||||
args := []string{url}
|
args := []string{targetURL}
|
||||||
|
|
||||||
if req.AuthToken != "" {
|
if req.AuthToken != "" {
|
||||||
args = append(args, "--auth-token", req.AuthToken)
|
args = append(args, "--auth-token", req.AuthToken)
|
||||||
@@ -512,7 +724,7 @@ func ExtractTimeline(req TimelineRequest) (*TwitterResponse, error) {
|
|||||||
args = append(args, "--limit", fmt.Sprintf("%d", req.BatchSize))
|
args = append(args, "--limit", fmt.Sprintf("%d", req.BatchSize))
|
||||||
}
|
}
|
||||||
|
|
||||||
if timelineType == "tweets" || timelineType == "timeline" {
|
if timelineType == "tweets" || timelineType == "timeline" || timelineType == "media" {
|
||||||
if req.Retweets {
|
if req.Retweets {
|
||||||
args = append(args, "--retweets", "include")
|
args = append(args, "--retweets", "include")
|
||||||
} else {
|
} else {
|
||||||
@@ -520,21 +732,10 @@ func ExtractTimeline(req TimelineRequest) (*TwitterResponse, error) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if isTextOnly {
|
if includeText {
|
||||||
args = append(args, "--text-tweets")
|
args = append(args, "--text-tweets")
|
||||||
}
|
}
|
||||||
|
|
||||||
if req.MediaType != "" && req.MediaType != "all" && !isTextOnly {
|
|
||||||
switch req.MediaType {
|
|
||||||
case "image":
|
|
||||||
args = append(args, "--type", "photo")
|
|
||||||
case "video":
|
|
||||||
args = append(args, "--type", "video")
|
|
||||||
case "gif":
|
|
||||||
args = append(args, "--type", "animated_gif")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if req.Cursor != "" {
|
if req.Cursor != "" {
|
||||||
args = append(args, "--cursor", req.Cursor)
|
args = append(args, "--cursor", req.Cursor)
|
||||||
}
|
}
|
||||||
@@ -548,6 +749,9 @@ func ExtractTimeline(req TimelineRequest) (*TwitterResponse, error) {
|
|||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
outputStr := string(output)
|
outputStr := string(output)
|
||||||
|
if strings.TrimSpace(outputStr) == "" {
|
||||||
|
return nil, fmt.Errorf("xtractor process terminated before returning data")
|
||||||
|
}
|
||||||
errorMsg := parseExtractorError(outputStr, req.Username)
|
errorMsg := parseExtractorError(outputStr, req.Username)
|
||||||
return nil, fmt.Errorf("%s", errorMsg)
|
return nil, fmt.Errorf("%s", errorMsg)
|
||||||
}
|
}
|
||||||
@@ -561,21 +765,12 @@ func ExtractTimeline(req TimelineRequest) (*TwitterResponse, error) {
|
|||||||
return nil, fmt.Errorf("parse_error: Could not parse xtractor output. Raw output: %s", outputStr)
|
return nil, fmt.Errorf("parse_error: Could not parse xtractor output. Raw output: %s", outputStr)
|
||||||
}
|
}
|
||||||
|
|
||||||
var cliResponse CLIResponse
|
resp, err := parseRichResponse(jsonStr)
|
||||||
if err := json.Unmarshal([]byte(jsonStr), &cliResponse); err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("json_error: Failed to parse JSON response: %v", err)
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
timeline := make([]TimelineEntry, 0)
|
accountInfo := buildAccountInfo(resp.Account, req.Username)
|
||||||
accountInfo := AccountInfo{
|
|
||||||
Name: req.Username,
|
|
||||||
Nick: req.Username,
|
|
||||||
}
|
|
||||||
|
|
||||||
mediaTweetIDs := make(map[int64]bool)
|
|
||||||
for _, media := range cliResponse.Media {
|
|
||||||
mediaTweetIDs[int64(media.TweetID)] = true
|
|
||||||
}
|
|
||||||
|
|
||||||
isBookmarks := req.TimelineType == "bookmarks"
|
isBookmarks := req.TimelineType == "bookmarks"
|
||||||
isLikes := req.TimelineType == "likes"
|
isLikes := req.TimelineType == "likes"
|
||||||
@@ -587,90 +782,15 @@ func ExtractTimeline(req TimelineRequest) (*TwitterResponse, error) {
|
|||||||
accountInfo.Nick = "My Likes"
|
accountInfo.Nick = "My Likes"
|
||||||
}
|
}
|
||||||
|
|
||||||
if isTextOnly {
|
timeline := flattenTweets(resp.Tweets, FlattenOptions{
|
||||||
|
IncludePhotos: req.IncludePhotos,
|
||||||
for _, meta := range cliResponse.Metadata {
|
IncludeVideos: req.IncludeVideos,
|
||||||
if !mediaTweetIDs[int64(meta.TweetID)] {
|
IncludeGifs: req.IncludeGifs,
|
||||||
timeline = append(timeline, convertMetadataToTimelineEntry(meta))
|
IncludeText: req.IncludeText,
|
||||||
}
|
VideoQuality: req.VideoQuality,
|
||||||
}
|
ImageSize: req.ImageSize,
|
||||||
|
})
|
||||||
if !isBookmarks && !isLikes {
|
completed := !resp.HasMore
|
||||||
if len(cliResponse.Media) > 0 {
|
|
||||||
user := cliResponse.Media[0].User
|
|
||||||
accountInfo.Name = user.Name
|
|
||||||
accountInfo.Nick = user.Nick
|
|
||||||
accountInfo.Date = user.Date
|
|
||||||
accountInfo.FollowersCount = user.FollowersCount
|
|
||||||
accountInfo.FriendsCount = user.FriendsCount
|
|
||||||
accountInfo.ProfileImage = user.ProfileImage
|
|
||||||
accountInfo.StatusesCount = user.StatusesCount
|
|
||||||
} else if len(cliResponse.Metadata) > 0 {
|
|
||||||
firstMeta := cliResponse.Metadata[0]
|
|
||||||
accountInfo.Name = firstMeta.Author.Name
|
|
||||||
accountInfo.Nick = firstMeta.Author.Nick
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
|
|
||||||
if len(cliResponse.Media) > 0 {
|
|
||||||
user := cliResponse.Media[0].User
|
|
||||||
accountInfo.Date = user.Date
|
|
||||||
accountInfo.FollowersCount = user.FollowersCount
|
|
||||||
accountInfo.FriendsCount = user.FriendsCount
|
|
||||||
accountInfo.ProfileImage = user.ProfileImage
|
|
||||||
accountInfo.StatusesCount = user.StatusesCount
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else if len(cliResponse.Media) > 0 {
|
|
||||||
|
|
||||||
timeline = make([]TimelineEntry, 0, len(cliResponse.Media))
|
|
||||||
|
|
||||||
for _, media := range cliResponse.Media {
|
|
||||||
timeline = append(timeline, convertToTimelineEntry(media))
|
|
||||||
}
|
|
||||||
|
|
||||||
user := cliResponse.Media[0].User
|
|
||||||
if !isBookmarks && !isLikes {
|
|
||||||
accountInfo.Name = user.Name
|
|
||||||
accountInfo.Nick = user.Nick
|
|
||||||
}
|
|
||||||
accountInfo.Date = user.Date
|
|
||||||
accountInfo.FollowersCount = user.FollowersCount
|
|
||||||
accountInfo.FriendsCount = user.FriendsCount
|
|
||||||
accountInfo.ProfileImage = user.ProfileImage
|
|
||||||
accountInfo.StatusesCount = user.StatusesCount
|
|
||||||
} else if len(cliResponse.Metadata) > 0 {
|
|
||||||
|
|
||||||
timeline = make([]TimelineEntry, 0, len(cliResponse.Metadata))
|
|
||||||
for _, meta := range cliResponse.Metadata {
|
|
||||||
entry := TimelineEntry{
|
|
||||||
URL: "",
|
|
||||||
TweetID: meta.TweetID,
|
|
||||||
Date: meta.Date,
|
|
||||||
Type: "text",
|
|
||||||
IsRetweet: meta.RetweetID != 0,
|
|
||||||
Extension: "txt",
|
|
||||||
Width: 0,
|
|
||||||
Height: 0,
|
|
||||||
Content: meta.Content,
|
|
||||||
ViewCount: meta.ViewCount,
|
|
||||||
BookmarkCount: meta.BookmarkCount,
|
|
||||||
FavoriteCount: meta.FavoriteCount,
|
|
||||||
RetweetCount: meta.RetweetCount,
|
|
||||||
ReplyCount: meta.ReplyCount,
|
|
||||||
AuthorUsername: meta.Author.Name,
|
|
||||||
}
|
|
||||||
timeline = append(timeline, entry)
|
|
||||||
}
|
|
||||||
|
|
||||||
if !isBookmarks && !isLikes {
|
|
||||||
firstMeta := cliResponse.Metadata[0]
|
|
||||||
accountInfo.Name = firstMeta.Author.Name
|
|
||||||
accountInfo.Nick = firstMeta.Author.Nick
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
hasMore := cliResponse.Cursor != "" && !cliResponse.Completed
|
|
||||||
|
|
||||||
response := &TwitterResponse{
|
response := &TwitterResponse{
|
||||||
AccountInfo: accountInfo,
|
AccountInfo: accountInfo,
|
||||||
@@ -680,12 +800,12 @@ func ExtractTimeline(req TimelineRequest) (*TwitterResponse, error) {
|
|||||||
NewEntries: len(timeline),
|
NewEntries: len(timeline),
|
||||||
Page: req.Page,
|
Page: req.Page,
|
||||||
BatchSize: req.BatchSize,
|
BatchSize: req.BatchSize,
|
||||||
HasMore: hasMore,
|
HasMore: resp.HasMore,
|
||||||
Cursor: cliResponse.Cursor,
|
Cursor: resp.NextCursor,
|
||||||
Completed: cliResponse.Completed,
|
Completed: completed,
|
||||||
},
|
},
|
||||||
Cursor: cliResponse.Cursor,
|
Cursor: resp.NextCursor,
|
||||||
Completed: cliResponse.Completed,
|
Completed: completed,
|
||||||
}
|
}
|
||||||
|
|
||||||
return response, nil
|
return response, nil
|
||||||
@@ -699,9 +819,9 @@ 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)
|
targetURL := buildSearchURL(req.Username, req.StartDate, req.EndDate, mediaFilter, req.Retweets)
|
||||||
|
|
||||||
args := []string{url}
|
args := []string{targetURL}
|
||||||
|
|
||||||
if req.AuthToken != "" {
|
if req.AuthToken != "" {
|
||||||
args = append(args, "--auth-token", req.AuthToken)
|
args = append(args, "--auth-token", req.AuthToken)
|
||||||
@@ -731,6 +851,9 @@ func ExtractDateRange(req DateRangeRequest) (*TwitterResponse, error) {
|
|||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
outputStr := string(output)
|
outputStr := string(output)
|
||||||
|
if strings.TrimSpace(outputStr) == "" {
|
||||||
|
return nil, fmt.Errorf("xtractor process terminated before returning data")
|
||||||
|
}
|
||||||
errorMsg := parseExtractorError(outputStr, req.Username)
|
errorMsg := parseExtractorError(outputStr, req.Username)
|
||||||
return nil, fmt.Errorf("%s", errorMsg)
|
return nil, fmt.Errorf("%s", errorMsg)
|
||||||
}
|
}
|
||||||
@@ -744,49 +867,19 @@ func ExtractDateRange(req DateRangeRequest) (*TwitterResponse, error) {
|
|||||||
return nil, fmt.Errorf("parse_error: Could not parse xtractor output. Raw output: %s", outputStr)
|
return nil, fmt.Errorf("parse_error: Could not parse xtractor output. Raw output: %s", outputStr)
|
||||||
}
|
}
|
||||||
|
|
||||||
var cliResponse CLIResponse
|
resp, err := parseRichResponse(jsonStr)
|
||||||
if err := json.Unmarshal([]byte(jsonStr), &cliResponse); err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("json_error: Failed to parse JSON response: %v", err)
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
mediaTweetIDs := make(map[int64]bool)
|
timeline := flattenTweets(resp.Tweets, FlattenOptions{
|
||||||
for _, media := range cliResponse.Media {
|
IncludePhotos: true,
|
||||||
mediaTweetIDs[int64(media.TweetID)] = true
|
IncludeVideos: true,
|
||||||
}
|
IncludeGifs: true,
|
||||||
|
IncludeText: isTextOnly,
|
||||||
timeline := make([]TimelineEntry, 0, len(cliResponse.Media)+len(cliResponse.Metadata))
|
})
|
||||||
for _, media := range cliResponse.Media {
|
accountInfo := buildAccountInfo(resp.Account, req.Username)
|
||||||
timeline = append(timeline, convertToTimelineEntry(media))
|
completed := !resp.HasMore
|
||||||
}
|
|
||||||
|
|
||||||
if isTextOnly {
|
|
||||||
for _, meta := range cliResponse.Metadata {
|
|
||||||
if !mediaTweetIDs[int64(meta.TweetID)] {
|
|
||||||
timeline = append(timeline, convertMetadataToTimelineEntry(meta))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
accountInfo := AccountInfo{
|
|
||||||
Name: req.Username,
|
|
||||||
Nick: req.Username,
|
|
||||||
}
|
|
||||||
if len(cliResponse.Media) > 0 {
|
|
||||||
user := cliResponse.Media[0].User
|
|
||||||
accountInfo.Name = user.Name
|
|
||||||
accountInfo.Nick = user.Nick
|
|
||||||
accountInfo.Date = user.Date
|
|
||||||
accountInfo.FollowersCount = user.FollowersCount
|
|
||||||
accountInfo.FriendsCount = user.FriendsCount
|
|
||||||
accountInfo.ProfileImage = user.ProfileImage
|
|
||||||
accountInfo.StatusesCount = user.StatusesCount
|
|
||||||
} else if len(cliResponse.Metadata) > 0 {
|
|
||||||
firstMeta := cliResponse.Metadata[0]
|
|
||||||
accountInfo.Name = firstMeta.Author.Name
|
|
||||||
accountInfo.Nick = firstMeta.Author.Nick
|
|
||||||
}
|
|
||||||
|
|
||||||
hasMore := cliResponse.Cursor != "" && !cliResponse.Completed
|
|
||||||
|
|
||||||
response := &TwitterResponse{
|
response := &TwitterResponse{
|
||||||
AccountInfo: accountInfo,
|
AccountInfo: accountInfo,
|
||||||
@@ -796,17 +889,23 @@ func ExtractDateRange(req DateRangeRequest) (*TwitterResponse, error) {
|
|||||||
NewEntries: len(timeline),
|
NewEntries: len(timeline),
|
||||||
Page: 0,
|
Page: 0,
|
||||||
BatchSize: 0,
|
BatchSize: 0,
|
||||||
HasMore: hasMore,
|
HasMore: resp.HasMore,
|
||||||
Cursor: cliResponse.Cursor,
|
Cursor: resp.NextCursor,
|
||||||
Completed: cliResponse.Completed,
|
Completed: completed,
|
||||||
},
|
},
|
||||||
Cursor: cliResponse.Cursor,
|
Cursor: resp.NextCursor,
|
||||||
Completed: cliResponse.Completed,
|
Completed: completed,
|
||||||
}
|
}
|
||||||
|
|
||||||
return response, nil
|
return response, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func getExtractorPath() string {
|
||||||
|
homeDir, _ := os.UserHomeDir()
|
||||||
|
baseDir := filepath.Join(homeDir, ".twitterxmediabatchdownloader")
|
||||||
|
return filepath.Join(baseDir, getExecutableName())
|
||||||
|
}
|
||||||
|
|
||||||
func extractJSON(output string) string {
|
func extractJSON(output string) string {
|
||||||
|
|
||||||
start := strings.Index(output, "{")
|
start := strings.Index(output, "{")
|
||||||
|
|||||||
+28
-28
@@ -12,42 +12,42 @@
|
|||||||
"postinstall": "node scripts/generate-icon.js"
|
"postinstall": "node scripts/generate-icon.js"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@radix-ui/react-checkbox": "^1.3.3",
|
"@radix-ui/react-checkbox": "^1.3.5",
|
||||||
"@radix-ui/react-context-menu": "^2.2.16",
|
"@radix-ui/react-context-menu": "^2.3.1",
|
||||||
"@radix-ui/react-dialog": "^1.1.15",
|
"@radix-ui/react-dialog": "^1.1.17",
|
||||||
"@radix-ui/react-dropdown-menu": "^2.1.16",
|
"@radix-ui/react-dropdown-menu": "^2.1.18",
|
||||||
"@radix-ui/react-label": "^2.1.8",
|
"@radix-ui/react-label": "^2.1.10",
|
||||||
"@radix-ui/react-progress": "^1.1.8",
|
"@radix-ui/react-progress": "^1.1.10",
|
||||||
"@radix-ui/react-select": "^2.2.6",
|
"@radix-ui/react-select": "^2.3.1",
|
||||||
"@radix-ui/react-slot": "^1.2.4",
|
"@radix-ui/react-slot": "^1.3.0",
|
||||||
"@radix-ui/react-switch": "^1.2.6",
|
"@radix-ui/react-switch": "^1.3.1",
|
||||||
"@radix-ui/react-tooltip": "^1.2.8",
|
"@radix-ui/react-tooltip": "^1.2.10",
|
||||||
"@tailwindcss/vite": "^4.1.18",
|
"@tailwindcss/vite": "^4.3.1",
|
||||||
"class-variance-authority": "^0.7.1",
|
"class-variance-authority": "^0.7.1",
|
||||||
"clsx": "^2.1.1",
|
"clsx": "^2.1.1",
|
||||||
"lucide-react": "^0.562.0",
|
"lucide-react": "^0.562.0",
|
||||||
"motion": "^12.23.26",
|
"motion": "^12.40.0",
|
||||||
"next-themes": "^0.4.6",
|
"next-themes": "^0.4.6",
|
||||||
"react": "^19.2.3",
|
"react": "^19.2.7",
|
||||||
"react-dom": "^19.2.3",
|
"react-dom": "^19.2.7",
|
||||||
"sonner": "^2.0.7",
|
"sonner": "^2.0.7",
|
||||||
"tailwind-merge": "^3.4.0",
|
"tailwind-merge": "^3.6.0",
|
||||||
"tailwindcss": "^4.1.18"
|
"tailwindcss": "^4.3.1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@eslint/js": "^9.39.2",
|
"@eslint/js": "^10.0.1",
|
||||||
"@types/node": "^25.0.3",
|
"@types/node": "^26.0.0",
|
||||||
"@types/react": "^19.2.7",
|
"@types/react": "^19.2.17",
|
||||||
"@types/react-dom": "^19.2.3",
|
"@types/react-dom": "^19.2.3",
|
||||||
"@vitejs/plugin-react": "^5.1.2",
|
"@vitejs/plugin-react": "^6.0.2",
|
||||||
"eslint": "^9.39.2",
|
"eslint": "^10.5.0",
|
||||||
"eslint-plugin-react-hooks": "^7.0.1",
|
"eslint-plugin-react-hooks": "^7.1.1",
|
||||||
"eslint-plugin-react-refresh": "^0.4.26",
|
"eslint-plugin-react-refresh": "^0.5.3",
|
||||||
"globals": "^16.5.0",
|
"globals": "^17.6.0",
|
||||||
"sharp": "^0.34.5",
|
"sharp": "^0.35.2",
|
||||||
"tw-animate-css": "^1.4.0",
|
"tw-animate-css": "^1.4.0",
|
||||||
"typescript": "~5.9.3",
|
"typescript": "~6.0.3",
|
||||||
"typescript-eslint": "^8.50.0",
|
"typescript-eslint": "^8.61.1",
|
||||||
"vite": "^7.3.0"
|
"vite": "^8.0.16"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1 +1 @@
|
|||||||
cb4545ab700ecc9d641ab1be76b622f1
|
b9015b5860764ef52b634f74fd0f1180
|
||||||
Generated
+1678
-1858
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,3 @@
|
|||||||
|
allowBuilds:
|
||||||
|
esbuild: true
|
||||||
|
sharp: true
|
||||||
+263
-103
@@ -2,11 +2,14 @@ import { useState, useEffect, useRef, useCallback } from "react";
|
|||||||
import { TooltipProvider } from "@/components/ui/tooltip";
|
import { TooltipProvider } from "@/components/ui/tooltip";
|
||||||
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
|
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { ArrowLeft } from "lucide-react";
|
||||||
import { getSettings, applyThemeMode, applyFont } from "@/lib/settings";
|
import { getSettings, applyThemeMode, applyFont } from "@/lib/settings";
|
||||||
import { applyTheme } from "@/lib/themes";
|
import { applyTheme } from "@/lib/themes";
|
||||||
|
import { openExternal } from "@/lib/utils";
|
||||||
import { compareVersionNumbers } from "@/lib/version";
|
import { compareVersionNumbers } from "@/lib/version";
|
||||||
import { toastWithSound as toast } from "@/lib/toast-with-sound";
|
import { toastWithSound as toast } from "@/lib/toast-with-sound";
|
||||||
import { logger } from "@/lib/logger";
|
import { logger } from "@/lib/logger";
|
||||||
|
import { initDownloadProgressEvents } from "@/lib/download-state";
|
||||||
import { saveFetchState, getFetchState, clearFetchState, getResumableInfo, mergeTimelines, saveCursor, getCursor, clearCursor, type FetchState, } from "@/lib/fetch-state";
|
import { saveFetchState, getFetchState, clearFetchState, getResumableInfo, mergeTimelines, saveCursor, getCursor, clearCursor, type FetchState, } from "@/lib/fetch-state";
|
||||||
import { TitleBar } from "@/components/TitleBar";
|
import { TitleBar } from "@/components/TitleBar";
|
||||||
import { Sidebar, type PageType } from "@/components/Sidebar";
|
import { Sidebar, type PageType } from "@/components/Sidebar";
|
||||||
@@ -24,22 +27,19 @@ import { ExtractTimeline, ExtractDateRange, SaveAccountToDBWithStatus, CleanupEx
|
|||||||
const HISTORY_KEY = "twitter_media_fetch_history";
|
const HISTORY_KEY = "twitter_media_fetch_history";
|
||||||
const MAX_HISTORY = 10;
|
const MAX_HISTORY = 10;
|
||||||
const CURRENT_VERSION = __APP_VERSION__;
|
const CURRENT_VERSION = __APP_VERSION__;
|
||||||
const BATCH_SIZE = 200;
|
const BATCH_SIZE = 100;
|
||||||
function formatNumberWithComma(num: number): string {
|
function formatNumberWithComma(num: number): string {
|
||||||
return num.toLocaleString();
|
return num.toLocaleString();
|
||||||
}
|
}
|
||||||
|
|
||||||
function normalizeTimeline(timeline: TwitterResponse["timeline"] | null | undefined): TwitterResponse["timeline"] {
|
function normalizeTimeline(timeline: TwitterResponse["timeline"] | null | undefined): TwitterResponse["timeline"] {
|
||||||
return Array.isArray(timeline) ? timeline : [];
|
return Array.isArray(timeline) ? timeline : [];
|
||||||
}
|
}
|
||||||
|
|
||||||
function normalizeTwitterResponse(data: TwitterResponse): TwitterResponse {
|
function normalizeTwitterResponse(data: TwitterResponse): TwitterResponse {
|
||||||
return {
|
return {
|
||||||
...data,
|
...data,
|
||||||
timeline: normalizeTimeline(data.timeline),
|
timeline: normalizeTimeline(data.timeline),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async function loadSavedAccountResponse(username: string, mediaType: string): Promise<TwitterResponse | null> {
|
async function loadSavedAccountResponse(username: string, mediaType: string): Promise<TwitterResponse | null> {
|
||||||
try {
|
try {
|
||||||
const savedResponseJSON = await GetSavedAccountFromDB(username, mediaType);
|
const savedResponseJSON = await GetSavedAccountFromDB(username, mediaType);
|
||||||
@@ -49,7 +49,6 @@ async function loadSavedAccountResponse(username: string, mediaType: string): Pr
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function App() {
|
function App() {
|
||||||
const [currentPage, setCurrentPage] = useState<PageType>("main");
|
const [currentPage, setCurrentPage] = useState<PageType>("main");
|
||||||
const [username, setUsername] = useState("");
|
const [username, setUsername] = useState("");
|
||||||
@@ -92,18 +91,62 @@ function App() {
|
|||||||
toast.warning("Fetch completed, but saving to Saved Accounts failed");
|
toast.warning("Fetch completed, but saving to Saved Accounts failed");
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
const restorePartialFetchState = async (cleanUsername: string, mediaType: string, showStoppedToast: boolean) => {
|
||||||
|
const savedState = getFetchState(cleanUsername);
|
||||||
|
if (!savedState || savedState.totalFetched <= 0) {
|
||||||
|
if (showStoppedToast) {
|
||||||
|
toast.info("Fetch stopped");
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const canResume = !!savedState.cursor && !savedState.completed;
|
||||||
|
if (!canResume) {
|
||||||
|
clearFetchState(cleanUsername);
|
||||||
|
clearCursor(cleanUsername);
|
||||||
|
setResumeInfo(null);
|
||||||
|
}
|
||||||
|
const partialResponse = await loadSavedAccountResponse(cleanUsername, savedState.mediaType || mediaType);
|
||||||
|
if (canResume) {
|
||||||
|
setResumeInfo({ canResume: true, mediaCount: savedState.totalFetched });
|
||||||
|
}
|
||||||
|
if (partialResponse) {
|
||||||
|
setResult(partialResponse);
|
||||||
|
try {
|
||||||
|
await SaveAccountToDBWithStatus(partialResponse.account_info.name, partialResponse.account_info.nick, partialResponse.account_info.profile_image, partialResponse.total_urls, JSON.stringify(partialResponse), savedState.mediaType || mediaType, savedState.cursor || "", savedState.completed);
|
||||||
|
}
|
||||||
|
catch (dbErr) {
|
||||||
|
reportDatabaseSaveError("partial fetch data", dbErr);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (showStoppedToast) {
|
||||||
|
toast.info(`Stopped at ${formatNumberWithComma(savedState.totalFetched)} items`);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const stopMultipleFetches = (showToast: boolean) => {
|
||||||
|
stopAllRef.current = true;
|
||||||
|
setIsFetchingAll(false);
|
||||||
|
accountTimersRef.current.forEach((interval) => clearInterval(interval));
|
||||||
|
accountTimersRef.current.clear();
|
||||||
|
accountStartTimesRef.current.clear();
|
||||||
|
accountTimeoutSecondsRef.current.clear();
|
||||||
|
setMultipleAccounts((prev) => prev.map((acc) => {
|
||||||
|
if (acc.status === "fetching") {
|
||||||
|
const mediaCount = accountMediaCountRef.current.get(acc.id) || acc.mediaCount || 0;
|
||||||
|
return { ...acc, status: "incomplete" as const, mediaCount, remainingTime: 0 };
|
||||||
|
}
|
||||||
|
return acc;
|
||||||
|
}));
|
||||||
|
CleanupExtractorProcesses().catch(() => { });
|
||||||
|
if (showToast) {
|
||||||
|
toast.info("Stopped all fetches");
|
||||||
|
}
|
||||||
|
};
|
||||||
const handleFetchTypeChange = (type: FetchType) => {
|
const handleFetchTypeChange = (type: FetchType) => {
|
||||||
setFetchType(type);
|
setFetchType(type);
|
||||||
if (type === "single") {
|
if (type === "single") {
|
||||||
setMultipleAccounts([]);
|
if (isFetchingAll || multipleAccounts.some((acc) => acc.status === "fetching")) {
|
||||||
setIsFetchingAll(false);
|
stopMultipleFetches(false);
|
||||||
stopAllRef.current = true;
|
}
|
||||||
accountTimersRef.current.forEach((interval) => clearInterval(interval));
|
|
||||||
accountTimersRef.current.clear();
|
|
||||||
accountStartTimesRef.current.clear();
|
|
||||||
accountTimeoutSecondsRef.current.clear();
|
|
||||||
accountStopFlagsRef.current.clear();
|
|
||||||
accountMediaCountRef.current.clear();
|
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
setResult(null);
|
setResult(null);
|
||||||
@@ -123,10 +166,45 @@ function App() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
mediaQuery.addEventListener("change", handleChange);
|
mediaQuery.addEventListener("change", handleChange);
|
||||||
|
const cleanupDownloadProgress = initDownloadProgressEvents();
|
||||||
checkForUpdates();
|
checkForUpdates();
|
||||||
loadHistory();
|
loadHistory();
|
||||||
return () => {
|
return () => {
|
||||||
mediaQuery.removeEventListener("change", handleChange);
|
mediaQuery.removeEventListener("change", handleChange);
|
||||||
|
cleanupDownloadProgress();
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
useEffect(() => {
|
||||||
|
const handleDocumentClick = (event: MouseEvent) => {
|
||||||
|
if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const target = event.target;
|
||||||
|
if (!(target instanceof Element)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const anchor = target.closest("a[href]");
|
||||||
|
if (!(anchor instanceof HTMLAnchorElement)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const href = anchor.getAttribute("href");
|
||||||
|
if (!href || href.startsWith("#") || href.startsWith("javascript:")) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const url = new URL(href, window.location.href);
|
||||||
|
if (url.protocol !== "http:" && url.protocol !== "https:") {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
event.preventDefault();
|
||||||
|
openExternal(url.toString());
|
||||||
|
}
|
||||||
|
catch {
|
||||||
|
}
|
||||||
|
};
|
||||||
|
document.addEventListener("click", handleDocumentClick);
|
||||||
|
return () => {
|
||||||
|
document.removeEventListener("click", handleDocumentClick);
|
||||||
};
|
};
|
||||||
}, []);
|
}, []);
|
||||||
const checkForUpdates = async () => {
|
const checkForUpdates = async () => {
|
||||||
@@ -362,10 +440,8 @@ function App() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
const settings = getSettings();
|
const batchSize = BATCH_SIZE;
|
||||||
const isSingleMode = settings.fetchMode === "single";
|
let timelineType = settings.includeText ? "tweets" : "media";
|
||||||
const batchSize = isSingleMode ? 0 : BATCH_SIZE;
|
|
||||||
let timelineType = "timeline";
|
|
||||||
if (isBookmarks) {
|
if (isBookmarks) {
|
||||||
timelineType = "bookmarks";
|
timelineType = "bookmarks";
|
||||||
}
|
}
|
||||||
@@ -374,6 +450,7 @@ function App() {
|
|||||||
}
|
}
|
||||||
let hasMore = true;
|
let hasMore = true;
|
||||||
let page = 0;
|
let page = 0;
|
||||||
|
const seenCursors = new Set<string>();
|
||||||
while (hasMore && !stopFetchRef.current) {
|
while (hasMore && !stopFetchRef.current) {
|
||||||
if (fetchStartTimeRef.current !== null) {
|
if (fetchStartTimeRef.current !== null) {
|
||||||
const settings = getSettings();
|
const settings = getSettings();
|
||||||
@@ -420,7 +497,7 @@ function App() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
const batchNum = page + 1;
|
const batchNum = page + 1;
|
||||||
logger.info(isSingleMode ? "Fetching all media..." : `Fetching batch ${batchNum}${cursor ? " (resuming)" : ""}...`);
|
logger.info(`Fetching batch ${batchNum}${cursor ? " (resuming)" : ""}...`);
|
||||||
const response = await ExtractTimeline({
|
const response = await ExtractTimeline({
|
||||||
username: isBookmarks ? "" : username.trim(),
|
username: isBookmarks ? "" : username.trim(),
|
||||||
auth_token: authToken.trim(),
|
auth_token: authToken.trim(),
|
||||||
@@ -430,6 +507,12 @@ function App() {
|
|||||||
media_type: requestedMediaType,
|
media_type: requestedMediaType,
|
||||||
retweets: retweets || false,
|
retweets: retweets || false,
|
||||||
cursor: cursor,
|
cursor: cursor,
|
||||||
|
include_photos: settings.includePhotos,
|
||||||
|
include_videos: settings.includeVideos,
|
||||||
|
include_gifs: settings.includeGifs,
|
||||||
|
include_text: settings.includeText,
|
||||||
|
video_quality: settings.videoQuality,
|
||||||
|
image_size: settings.imageSize,
|
||||||
});
|
});
|
||||||
const data = normalizeTwitterResponse(JSON.parse(response) as TwitterResponse);
|
const data = normalizeTwitterResponse(JSON.parse(response) as TwitterResponse);
|
||||||
if (!accountInfo && data.account_info) {
|
if (!accountInfo && data.account_info) {
|
||||||
@@ -452,6 +535,14 @@ function App() {
|
|||||||
}
|
}
|
||||||
cursor = data.cursor;
|
cursor = data.cursor;
|
||||||
hasMore = !!data.cursor && !data.completed;
|
hasMore = !!data.cursor && !data.completed;
|
||||||
|
if (hasMore && cursor) {
|
||||||
|
if (seenCursors.has(cursor) || (data.timeline.length > 0 && newCount === 0)) {
|
||||||
|
hasMore = false;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
seenCursors.add(cursor);
|
||||||
|
}
|
||||||
|
}
|
||||||
page++;
|
page++;
|
||||||
if (cursor) {
|
if (cursor) {
|
||||||
saveCursor(cleanUsername, cursor);
|
saveCursor(cleanUsername, cursor);
|
||||||
@@ -507,7 +598,7 @@ function App() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (stopFetchRef.current) {
|
if (stopFetchRef.current && hasMore && cursor) {
|
||||||
const elapsedSecs = fetchStartTimeRef.current ? Math.floor((Date.now() - fetchStartTimeRef.current) / 1000) : 0;
|
const elapsedSecs = fetchStartTimeRef.current ? Math.floor((Date.now() - fetchStartTimeRef.current) / 1000) : 0;
|
||||||
logger.info(`Stopped at ${allTimeline.length} items - can resume later (${elapsedSecs}s)`);
|
logger.info(`Stopped at ${allTimeline.length} items - can resume later (${elapsedSecs}s)`);
|
||||||
toast.info(`Stopped at ${formatNumberWithComma(allTimeline.length)} items`);
|
toast.info(`Stopped at ${formatNumberWithComma(allTimeline.length)} items`);
|
||||||
@@ -559,6 +650,11 @@ function App() {
|
|||||||
catch (error) {
|
catch (error) {
|
||||||
const errorMsg = error instanceof Error ? error.message : String(error);
|
const errorMsg = error instanceof Error ? error.message : String(error);
|
||||||
const elapsedSecs = fetchStartTimeRef.current ? Math.floor((Date.now() - fetchStartTimeRef.current) / 1000) : 0;
|
const elapsedSecs = fetchStartTimeRef.current ? Math.floor((Date.now() - fetchStartTimeRef.current) / 1000) : 0;
|
||||||
|
if (stopFetchRef.current) {
|
||||||
|
logger.info(`Stopped fetch after ${elapsedSecs}s`);
|
||||||
|
await restorePartialFetchState(cleanUsername, requestedMediaType, true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
logger.error(`Failed to fetch: ${errorMsg} (${elapsedSecs}s)`);
|
logger.error(`Failed to fetch: ${errorMsg} (${elapsedSecs}s)`);
|
||||||
if (errorMsg.toLowerCase().includes("xtractor dependency") || errorMsg.toLowerCase().includes("extractor dependency")) {
|
if (errorMsg.toLowerCase().includes("xtractor dependency") || errorMsg.toLowerCase().includes("extractor dependency")) {
|
||||||
toast.error(errorMsg);
|
toast.error(errorMsg);
|
||||||
@@ -568,18 +664,8 @@ function App() {
|
|||||||
}
|
}
|
||||||
const savedState = getFetchState(cleanUsername);
|
const savedState = getFetchState(cleanUsername);
|
||||||
if (savedState && savedState.totalFetched > 0) {
|
if (savedState && savedState.totalFetched > 0) {
|
||||||
const partialResponse = await loadSavedAccountResponse(cleanUsername, savedState.mediaType || requestedMediaType);
|
await restorePartialFetchState(cleanUsername, requestedMediaType, false);
|
||||||
if (partialResponse) {
|
toast.info(`Saved ${formatNumberWithComma(savedState.totalFetched)} items - can resume`);
|
||||||
setResult(partialResponse);
|
|
||||||
setResumeInfo({ canResume: true, mediaCount: savedState.totalFetched });
|
|
||||||
toast.info(`Saved ${formatNumberWithComma(savedState.totalFetched)} items - can resume`);
|
|
||||||
try {
|
|
||||||
await SaveAccountToDBWithStatus(partialResponse.account_info.name, partialResponse.account_info.nick, partialResponse.account_info.profile_image, partialResponse.total_urls, JSON.stringify(partialResponse), savedState.mediaType || requestedMediaType, savedState.cursor || "", false);
|
|
||||||
}
|
|
||||||
catch (dbErr) {
|
|
||||||
reportDatabaseSaveError("partial fetch data", dbErr);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
finally {
|
finally {
|
||||||
@@ -628,6 +714,13 @@ function App() {
|
|||||||
toast.error("Failed to parse saved data");
|
toast.error("Failed to parse saved data");
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
const handleBackToHomeResult = () => {
|
||||||
|
setCurrentPage("main");
|
||||||
|
setResult(null);
|
||||||
|
setNewMediaCount(null);
|
||||||
|
const scrollElement = document.getElementById("app-content-scroll");
|
||||||
|
scrollElement?.scrollTo({ top: 0, behavior: "smooth" });
|
||||||
|
};
|
||||||
const parseUsername = (input: string): string => {
|
const parseUsername = (input: string): string => {
|
||||||
let clean = input.trim();
|
let clean = input.trim();
|
||||||
if (clean.startsWith("@")) {
|
if (clean.startsWith("@")) {
|
||||||
@@ -667,43 +760,59 @@ function App() {
|
|||||||
setCurrentPage("main");
|
setCurrentPage("main");
|
||||||
toast.success(`Added ${formatNumberWithComma(accounts.length)} account(s) to multiple fetch`);
|
toast.success(`Added ${formatNumberWithComma(accounts.length)} account(s) to multiple fetch`);
|
||||||
};
|
};
|
||||||
const handleImportFile = () => {
|
const handleImportAccounts = (entries: string[]) => {
|
||||||
const input = document.createElement("input");
|
const seenUsernames = new Set<string>();
|
||||||
input.type = "file";
|
const uniqueUsernames = entries
|
||||||
input.accept = ".txt";
|
.map((entry) => parseUsername(entry))
|
||||||
input.onchange = async (e) => {
|
.filter((entry) => entry.length > 0)
|
||||||
const file = (e.target as HTMLInputElement).files?.[0];
|
.filter((entry) => {
|
||||||
if (!file)
|
const normalized = entry.toLowerCase();
|
||||||
return;
|
if (seenUsernames.has(normalized)) {
|
||||||
try {
|
return false;
|
||||||
const text = await file.text();
|
|
||||||
const lines = text.split("\n").map((line) => line.trim()).filter((line) => line.length > 0);
|
|
||||||
if (lines.length === 0) {
|
|
||||||
toast.error("File is empty");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const accounts: MultipleAccount[] = lines.map((line) => {
|
|
||||||
const username = parseUsername(line);
|
|
||||||
return {
|
|
||||||
id: crypto.randomUUID(),
|
|
||||||
username,
|
|
||||||
status: "pending",
|
|
||||||
mediaCount: 0,
|
|
||||||
previousMediaCount: 0,
|
|
||||||
elapsedTime: 0,
|
|
||||||
remainingTime: null,
|
|
||||||
showDiff: false,
|
|
||||||
};
|
|
||||||
});
|
|
||||||
setMultipleAccounts(accounts);
|
|
||||||
toast.success(`Imported ${formatNumberWithComma(accounts.length)} account(s)`);
|
|
||||||
}
|
}
|
||||||
catch (error) {
|
seenUsernames.add(normalized);
|
||||||
console.error("Failed to read imported account list:", error);
|
return true;
|
||||||
toast.error("Failed to read file");
|
});
|
||||||
}
|
if (uniqueUsernames.length === 0) {
|
||||||
};
|
toast.error("No valid accounts found");
|
||||||
input.click();
|
return;
|
||||||
|
}
|
||||||
|
const accounts: MultipleAccount[] = uniqueUsernames.map((entry) => ({
|
||||||
|
id: crypto.randomUUID(),
|
||||||
|
username: entry,
|
||||||
|
status: "pending",
|
||||||
|
mediaCount: 0,
|
||||||
|
previousMediaCount: 0,
|
||||||
|
elapsedTime: 0,
|
||||||
|
remainingTime: null,
|
||||||
|
showDiff: false,
|
||||||
|
}));
|
||||||
|
setMultipleAccounts(accounts);
|
||||||
|
toast.success(`Imported ${formatNumberWithComma(accounts.length)} account(s)`);
|
||||||
|
};
|
||||||
|
const handleClearMultipleAccounts = () => {
|
||||||
|
accountTimersRef.current.forEach((interval) => clearInterval(interval));
|
||||||
|
accountTimersRef.current.clear();
|
||||||
|
accountStartTimesRef.current.clear();
|
||||||
|
accountTimeoutSecondsRef.current.clear();
|
||||||
|
accountStopFlagsRef.current.clear();
|
||||||
|
accountMediaCountRef.current.clear();
|
||||||
|
stopAllRef.current = false;
|
||||||
|
setIsFetchingAll(false);
|
||||||
|
setMultipleAccounts([]);
|
||||||
|
toast.info("Multiple fetch list cleared");
|
||||||
|
};
|
||||||
|
const handleRemoveMultipleAccount = (accountId: string) => {
|
||||||
|
const account = multipleAccounts.find((entry) => entry.id === accountId);
|
||||||
|
accountTimersRef.current.delete(accountId);
|
||||||
|
accountStartTimesRef.current.delete(accountId);
|
||||||
|
accountTimeoutSecondsRef.current.delete(accountId);
|
||||||
|
accountStopFlagsRef.current.delete(accountId);
|
||||||
|
accountMediaCountRef.current.delete(accountId);
|
||||||
|
setMultipleAccounts((prev) => prev.filter((entry) => entry.id !== accountId));
|
||||||
|
if (account) {
|
||||||
|
toast.info(`Removed @${account.username} from list`);
|
||||||
|
}
|
||||||
};
|
};
|
||||||
const handleFetchAll = async (authToken: string) => {
|
const handleFetchAll = async (authToken: string) => {
|
||||||
if (multipleAccounts.length === 0) {
|
if (multipleAccounts.length === 0) {
|
||||||
@@ -718,7 +827,7 @@ function App() {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const settings = getSettings();
|
const settings = getSettings();
|
||||||
const selectedMediaType = settings.mediaType || "all";
|
const selectedMediaType = "all";
|
||||||
setFetchedMediaType(selectedMediaType);
|
setFetchedMediaType(selectedMediaType);
|
||||||
const timeoutSeconds = settings.fetchTimeout || 60;
|
const timeoutSeconds = settings.fetchTimeout || 60;
|
||||||
setMultipleAccounts((prev) => prev.map((acc) => ({
|
setMultipleAccounts((prev) => prev.map((acc) => ({
|
||||||
@@ -792,15 +901,14 @@ function App() {
|
|||||||
}));
|
}));
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
const fetchSettings = getSettings();
|
const batchSizeMultiple = BATCH_SIZE;
|
||||||
const isSingleModeMultiple = fetchSettings.fetchMode === "single";
|
|
||||||
const batchSizeMultiple = isSingleModeMultiple ? 0 : BATCH_SIZE;
|
|
||||||
const cleanUsername = account.username.trim();
|
const cleanUsername = account.username.trim();
|
||||||
let allTimeline: TwitterResponse["timeline"] = [];
|
let allTimeline: TwitterResponse["timeline"] = [];
|
||||||
let accountInfo: TwitterResponse["account_info"] | null = null;
|
let accountInfo: TwitterResponse["account_info"] | null = null;
|
||||||
let cursor: string | undefined;
|
let cursor: string | undefined;
|
||||||
let hasMore = true;
|
let hasMore = true;
|
||||||
let page = 0;
|
let page = 0;
|
||||||
|
const seenCursors = new Set<string>();
|
||||||
let previousMediaCount = account.mediaCount || 0;
|
let previousMediaCount = account.mediaCount || 0;
|
||||||
while (hasMore && !stopAllRef.current) {
|
while (hasMore && !stopAllRef.current) {
|
||||||
if (accountStopFlagsRef.current.get(accountId)) {
|
if (accountStopFlagsRef.current.get(accountId)) {
|
||||||
@@ -840,20 +948,35 @@ function App() {
|
|||||||
const response = await ExtractTimeline({
|
const response = await ExtractTimeline({
|
||||||
username: cleanUsername,
|
username: cleanUsername,
|
||||||
auth_token: authToken.trim(),
|
auth_token: authToken.trim(),
|
||||||
timeline_type: "timeline",
|
timeline_type: (settings.includeText || settings.includeRetweets) ? "tweets" : "media",
|
||||||
batch_size: batchSizeMultiple,
|
batch_size: batchSizeMultiple,
|
||||||
page: page,
|
page: page,
|
||||||
media_type: selectedMediaType,
|
media_type: selectedMediaType,
|
||||||
retweets: false,
|
retweets: settings.includeRetweets,
|
||||||
cursor: cursor,
|
cursor: cursor,
|
||||||
|
include_photos: settings.includePhotos,
|
||||||
|
include_videos: settings.includeVideos,
|
||||||
|
include_gifs: settings.includeGifs,
|
||||||
|
include_text: settings.includeText,
|
||||||
|
video_quality: settings.videoQuality,
|
||||||
|
image_size: settings.imageSize,
|
||||||
});
|
});
|
||||||
const data = normalizeTwitterResponse(JSON.parse(response) as TwitterResponse);
|
const data = normalizeTwitterResponse(JSON.parse(response) as TwitterResponse);
|
||||||
if (!accountInfo && data.account_info) {
|
if (!accountInfo && data.account_info) {
|
||||||
accountInfo = data.account_info;
|
accountInfo = data.account_info;
|
||||||
}
|
}
|
||||||
|
const previousMergeCount = allTimeline.length;
|
||||||
allTimeline = mergeTimelines(allTimeline, data.timeline);
|
allTimeline = mergeTimelines(allTimeline, data.timeline);
|
||||||
cursor = data.cursor;
|
cursor = data.cursor;
|
||||||
hasMore = !!data.cursor && !data.completed;
|
hasMore = !!data.cursor && !data.completed;
|
||||||
|
if (hasMore && cursor) {
|
||||||
|
if (seenCursors.has(cursor) || (data.timeline.length > 0 && allTimeline.length === previousMergeCount)) {
|
||||||
|
hasMore = false;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
seenCursors.add(cursor);
|
||||||
|
}
|
||||||
|
}
|
||||||
page++;
|
page++;
|
||||||
if (cursor) {
|
if (cursor) {
|
||||||
saveCursor(cleanUsername, cursor);
|
saveCursor(cleanUsername, cursor);
|
||||||
@@ -907,7 +1030,7 @@ function App() {
|
|||||||
},
|
},
|
||||||
cursor: cursor,
|
cursor: cursor,
|
||||||
completed: !hasMore,
|
completed: !hasMore,
|
||||||
}), selectedMediaType, cursor || "", !hasMore);
|
}), selectedMediaType, cursor || "", !hasMore);
|
||||||
}
|
}
|
||||||
catch (err) {
|
catch (err) {
|
||||||
reportDatabaseSaveError("multi-account progress", err);
|
reportDatabaseSaveError("multi-account progress", err);
|
||||||
@@ -960,6 +1083,19 @@ function App() {
|
|||||||
accountTimeoutSecondsRef.current.delete(accountId);
|
accountTimeoutSecondsRef.current.delete(accountId);
|
||||||
const errorMsg = error instanceof Error ? error.message : String(error);
|
const errorMsg = error instanceof Error ? error.message : String(error);
|
||||||
const mediaCount = accountMediaCountRef.current.get(accountId) || 0;
|
const mediaCount = accountMediaCountRef.current.get(accountId) || 0;
|
||||||
|
if (stopAllRef.current || accountStopFlagsRef.current.get(accountId)) {
|
||||||
|
accountMediaCountRef.current.delete(accountId);
|
||||||
|
setMultipleAccounts((prev) => prev.map((acc) => acc.id === accountId
|
||||||
|
? {
|
||||||
|
...acc,
|
||||||
|
status: "incomplete" as const,
|
||||||
|
error: undefined,
|
||||||
|
mediaCount,
|
||||||
|
}
|
||||||
|
: acc));
|
||||||
|
logger.info(`@${account.username}: stopped - ${mediaCount} items (${elapsedSecs}s)`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
const isAuthError = errorMsg.toLowerCase().includes("401") ||
|
const isAuthError = errorMsg.toLowerCase().includes("401") ||
|
||||||
errorMsg.toLowerCase().includes("unauthorized") ||
|
errorMsg.toLowerCase().includes("unauthorized") ||
|
||||||
errorMsg.toLowerCase().includes("auth token may be invalid") ||
|
errorMsg.toLowerCase().includes("auth token may be invalid") ||
|
||||||
@@ -984,30 +1120,14 @@ function App() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
const handleStopAll = () => {
|
const handleStopAll = () => {
|
||||||
stopAllRef.current = true;
|
stopMultipleFetches(true);
|
||||||
setIsFetchingAll(false);
|
|
||||||
accountTimersRef.current.forEach((interval) => clearInterval(interval));
|
|
||||||
accountTimersRef.current.clear();
|
|
||||||
accountStartTimesRef.current.clear();
|
|
||||||
accountTimeoutSecondsRef.current.clear();
|
|
||||||
setMultipleAccounts((prev) => prev.map((acc) => {
|
|
||||||
if (acc.status === "fetching") {
|
|
||||||
const mediaCount = accountMediaCountRef.current.get(acc.id) || acc.mediaCount || 0;
|
|
||||||
const status = mediaCount === 0 ? ("failed" as const) : ("incomplete" as const);
|
|
||||||
return { ...acc, status, mediaCount };
|
|
||||||
}
|
|
||||||
return acc;
|
|
||||||
}));
|
|
||||||
CleanupExtractorProcesses().catch(() => { });
|
|
||||||
toast.info("Stopped all fetches");
|
|
||||||
};
|
};
|
||||||
const handleStopAccount = (accountId: string) => {
|
const handleStopAccount = (accountId: string) => {
|
||||||
accountStopFlagsRef.current.set(accountId, true);
|
accountStopFlagsRef.current.set(accountId, true);
|
||||||
setMultipleAccounts((prev) => prev.map((acc) => {
|
setMultipleAccounts((prev) => prev.map((acc) => {
|
||||||
if (acc.id === accountId && acc.status === "fetching") {
|
if (acc.id === accountId && acc.status === "fetching") {
|
||||||
const mediaCount = accountMediaCountRef.current.get(accountId) || acc.mediaCount || 0;
|
const mediaCount = accountMediaCountRef.current.get(accountId) || acc.mediaCount || 0;
|
||||||
const status = mediaCount === 0 ? ("failed" as const) : ("incomplete" as const);
|
return { ...acc, status: "incomplete" as const, mediaCount };
|
||||||
return { ...acc, status, mediaCount };
|
|
||||||
}
|
}
|
||||||
return acc;
|
return acc;
|
||||||
}));
|
}));
|
||||||
@@ -1057,10 +1177,9 @@ function App() {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const retrySettings = getSettings();
|
const retrySettings = getSettings();
|
||||||
const selectedMediaType = retrySettings.mediaType || fetchedMediaType || "all";
|
const selectedMediaType = fetchedMediaType || "all";
|
||||||
setFetchedMediaType(selectedMediaType);
|
setFetchedMediaType(selectedMediaType);
|
||||||
const isSingleModeRetry = retrySettings.fetchMode === "single";
|
const batchSizeRetry = BATCH_SIZE;
|
||||||
const batchSizeRetry = isSingleModeRetry ? 0 : BATCH_SIZE;
|
|
||||||
const cleanUsername = account.username.trim();
|
const cleanUsername = account.username.trim();
|
||||||
let existingState: FetchState | null = null;
|
let existingState: FetchState | null = null;
|
||||||
let cursor: string | undefined = account.cursor;
|
let cursor: string | undefined = account.cursor;
|
||||||
@@ -1070,7 +1189,12 @@ function App() {
|
|||||||
existingState = getFetchState(cleanUsername);
|
existingState = getFetchState(cleanUsername);
|
||||||
if (existingState && existingState.cursor && !existingState.completed) {
|
if (existingState && existingState.cursor && !existingState.completed) {
|
||||||
cursor = existingState.cursor;
|
cursor = existingState.cursor;
|
||||||
const savedResponse = await loadSavedAccountResponse(cleanUsername, existingState.mediaType || selectedMediaType);
|
const resumeMediaType = existingState.mediaType || selectedMediaType;
|
||||||
|
const canonicalHandle = account.accountInfo?.name?.trim();
|
||||||
|
let savedResponse = await loadSavedAccountResponse(cleanUsername, resumeMediaType);
|
||||||
|
if (!savedResponse && canonicalHandle && canonicalHandle.toLowerCase() !== cleanUsername.toLowerCase()) {
|
||||||
|
savedResponse = await loadSavedAccountResponse(canonicalHandle, resumeMediaType);
|
||||||
|
}
|
||||||
if (savedResponse) {
|
if (savedResponse) {
|
||||||
allTimeline = savedResponse.timeline;
|
allTimeline = savedResponse.timeline;
|
||||||
accountInfo = savedResponse.account_info;
|
accountInfo = savedResponse.account_info;
|
||||||
@@ -1080,7 +1204,8 @@ function App() {
|
|||||||
else {
|
else {
|
||||||
clearFetchState(cleanUsername);
|
clearFetchState(cleanUsername);
|
||||||
clearCursor(cleanUsername);
|
clearCursor(cleanUsername);
|
||||||
logger.info(`Saved retry state for @${cleanUsername} was missing. Starting from beginning...`);
|
logger.warning(`Saved data for @${cleanUsername} is missing (Saved Accounts entry was cleared). Re-fetching from the beginning...`);
|
||||||
|
toast.warning(`@${cleanUsername}: saved progress was lost, re-fetching from the start`);
|
||||||
cursor = undefined;
|
cursor = undefined;
|
||||||
allTimeline = [];
|
allTimeline = [];
|
||||||
accountInfo = null;
|
accountInfo = null;
|
||||||
@@ -1174,6 +1299,7 @@ function App() {
|
|||||||
try {
|
try {
|
||||||
let hasMore = true;
|
let hasMore = true;
|
||||||
let page = 0;
|
let page = 0;
|
||||||
|
const seenCursors = new Set<string>();
|
||||||
while (hasMore && !stopAllRef.current) {
|
while (hasMore && !stopAllRef.current) {
|
||||||
if (accountStopFlagsRef.current.get(accountId)) {
|
if (accountStopFlagsRef.current.get(accountId)) {
|
||||||
break;
|
break;
|
||||||
@@ -1181,20 +1307,35 @@ function App() {
|
|||||||
const response = await ExtractTimeline({
|
const response = await ExtractTimeline({
|
||||||
username: cleanUsername,
|
username: cleanUsername,
|
||||||
auth_token: authToken.trim(),
|
auth_token: authToken.trim(),
|
||||||
timeline_type: "timeline",
|
timeline_type: (retrySettings.includeText || retrySettings.includeRetweets) ? "tweets" : "media",
|
||||||
batch_size: batchSizeRetry,
|
batch_size: batchSizeRetry,
|
||||||
page: page,
|
page: page,
|
||||||
media_type: selectedMediaType,
|
media_type: selectedMediaType,
|
||||||
retweets: false,
|
retweets: retrySettings.includeRetweets,
|
||||||
cursor: cursor,
|
cursor: cursor,
|
||||||
|
include_photos: retrySettings.includePhotos,
|
||||||
|
include_videos: retrySettings.includeVideos,
|
||||||
|
include_gifs: retrySettings.includeGifs,
|
||||||
|
include_text: retrySettings.includeText,
|
||||||
|
video_quality: retrySettings.videoQuality,
|
||||||
|
image_size: retrySettings.imageSize,
|
||||||
});
|
});
|
||||||
const data = normalizeTwitterResponse(JSON.parse(response) as TwitterResponse);
|
const data = normalizeTwitterResponse(JSON.parse(response) as TwitterResponse);
|
||||||
if (!accountInfo && data.account_info) {
|
if (!accountInfo && data.account_info) {
|
||||||
accountInfo = data.account_info;
|
accountInfo = data.account_info;
|
||||||
}
|
}
|
||||||
|
const previousRetryCount = allTimeline.length;
|
||||||
allTimeline = mergeTimelines(allTimeline, data.timeline);
|
allTimeline = mergeTimelines(allTimeline, data.timeline);
|
||||||
cursor = data.cursor;
|
cursor = data.cursor;
|
||||||
hasMore = !!data.cursor && !data.completed;
|
hasMore = !!data.cursor && !data.completed;
|
||||||
|
if (hasMore && cursor) {
|
||||||
|
if (seenCursors.has(cursor) || (data.timeline.length > 0 && allTimeline.length === previousRetryCount)) {
|
||||||
|
hasMore = false;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
seenCursors.add(cursor);
|
||||||
|
}
|
||||||
|
}
|
||||||
page++;
|
page++;
|
||||||
if (cursor) {
|
if (cursor) {
|
||||||
saveCursor(cleanUsername, cursor);
|
saveCursor(cleanUsername, cursor);
|
||||||
@@ -1301,6 +1442,19 @@ function App() {
|
|||||||
accountTimeoutSecondsRef.current.delete(accountId);
|
accountTimeoutSecondsRef.current.delete(accountId);
|
||||||
const errorMsg = error instanceof Error ? error.message : String(error);
|
const errorMsg = error instanceof Error ? error.message : String(error);
|
||||||
const mediaCount = accountMediaCountRef.current.get(accountId) || 0;
|
const mediaCount = accountMediaCountRef.current.get(accountId) || 0;
|
||||||
|
if (stopAllRef.current || accountStopFlagsRef.current.get(accountId)) {
|
||||||
|
accountMediaCountRef.current.delete(accountId);
|
||||||
|
setMultipleAccounts((prev) => prev.map((acc) => acc.id === accountId
|
||||||
|
? {
|
||||||
|
...acc,
|
||||||
|
status: "incomplete" as const,
|
||||||
|
error: undefined,
|
||||||
|
mediaCount,
|
||||||
|
}
|
||||||
|
: acc));
|
||||||
|
logger.info(`@${account.username}: stopped - ${mediaCount} items (${elapsedSecs}s)`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
const isAuthError = errorMsg.toLowerCase().includes("401") ||
|
const isAuthError = errorMsg.toLowerCase().includes("401") ||
|
||||||
errorMsg.toLowerCase().includes("unauthorized") ||
|
errorMsg.toLowerCase().includes("unauthorized") ||
|
||||||
errorMsg.toLowerCase().includes("auth token may be invalid") ||
|
errorMsg.toLowerCase().includes("auth token may be invalid") ||
|
||||||
@@ -1333,14 +1487,20 @@ function App() {
|
|||||||
return (<>
|
return (<>
|
||||||
<Header version={CURRENT_VERSION} hasUpdate={hasUpdate} releaseDate={releaseDate}/>
|
<Header version={CURRENT_VERSION} hasUpdate={hasUpdate} releaseDate={releaseDate}/>
|
||||||
|
|
||||||
<SearchBar username={username} loading={loading} onUsernameChange={setUsername} onFetch={handleFetch} onStopFetch={handleStopFetch} onResume={handleResume} onClearResume={handleClearResume} resumeInfo={resumeInfo} history={fetchHistory} onHistorySelect={handleHistorySelect} onHistoryRemove={removeFromHistory} hasResult={!!result} elapsedTime={elapsedTime} remainingTime={remainingTime} fetchType={fetchType} onFetchTypeChange={handleFetchTypeChange} multipleAccounts={multipleAccounts} onImportFile={handleImportFile} onFetchAll={handleFetchAll} onStopAll={handleStopAll} onStopAccount={handleStopAccount} onRetryAccount={handleRetryAccount} isFetchingAll={isFetchingAll} mode={searchMode} privateType={searchPrivateType} onModeChange={(mode, privateType) => {
|
<SearchBar username={username} loading={loading} onUsernameChange={setUsername} onFetch={handleFetch} onStopFetch={handleStopFetch} onResume={handleResume} onClearResume={handleClearResume} resumeInfo={resumeInfo} history={fetchHistory} onHistorySelect={handleHistorySelect} onHistoryRemove={removeFromHistory} hasResult={!!result} elapsedTime={elapsedTime} remainingTime={remainingTime} fetchType={fetchType} onFetchTypeChange={handleFetchTypeChange} multipleAccounts={multipleAccounts} onImportAccounts={handleImportAccounts} onFetchAll={handleFetchAll} onStopAll={handleStopAll} onStopAccount={handleStopAccount} onRetryAccount={handleRetryAccount} onClearMultipleAccounts={handleClearMultipleAccounts} onRemoveMultipleAccount={handleRemoveMultipleAccount} onOpenSavedAccounts={() => setCurrentPage("database")} isFetchingAll={isFetchingAll} mode={searchMode} privateType={searchPrivateType} onModeChange={(mode, privateType) => {
|
||||||
setSearchMode(mode);
|
setSearchMode(mode);
|
||||||
if (privateType) {
|
if (privateType) {
|
||||||
setSearchPrivateType(privateType);
|
setSearchPrivateType(privateType);
|
||||||
}
|
}
|
||||||
}}/>
|
}}/>
|
||||||
|
|
||||||
{result && fetchType === "single" && (<div className="mt-4">
|
{result && fetchType === "single" && (<div className="mt-4 space-y-3">
|
||||||
|
<div className="flex justify-start">
|
||||||
|
<Button variant="outline" onClick={handleBackToHomeResult} className="flex items-center gap-2">
|
||||||
|
<ArrowLeft className="h-4 w-4"/>
|
||||||
|
Back to Home
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
<MediaList accountInfo={result.account_info} timeline={result.timeline} totalUrls={result.total_urls} fetchedMediaType={fetchedMediaType} newMediaCount={newMediaCount}/>
|
<MediaList accountInfo={result.account_info} timeline={result.timeline} totalUrls={result.total_urls} fetchedMediaType={fetchedMediaType} newMediaCount={newMediaCount}/>
|
||||||
</div>)}
|
</div>)}
|
||||||
</>);
|
</>);
|
||||||
@@ -1367,7 +1527,7 @@ function App() {
|
|||||||
}
|
}
|
||||||
handleCancelNavigation();
|
handleCancelNavigation();
|
||||||
}}>
|
}}>
|
||||||
<DialogContent className="sm:max-w-[425px] [&>button]:hidden">
|
<DialogContent className="sm:max-w-106.25 [&>button]:hidden">
|
||||||
<DialogHeader>
|
<DialogHeader>
|
||||||
<DialogTitle>Unsaved Changes</DialogTitle>
|
<DialogTitle>Unsaved Changes</DialogTitle>
|
||||||
<DialogDescription>
|
<DialogDescription>
|
||||||
|
|||||||
Binary file not shown.
|
After Width: | Height: | Size: 45 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 44 KiB |
@@ -1,4 +1,4 @@
|
|||||||
import { useState, useEffect, useRef, useCallback, useMemo } from "react";
|
import { useState, useEffect, useRef, useCallback, useMemo, useDeferredValue } from "react";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Badge } from "@/components/ui/badge";
|
import { Badge } from "@/components/ui/badge";
|
||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
@@ -16,7 +16,7 @@ import { toastWithSound as toast } from "@/lib/toast-with-sound";
|
|||||||
import { getSettings } from "@/lib/settings";
|
import { getSettings } from "@/lib/settings";
|
||||||
import { openExternal } from "@/lib/utils";
|
import { openExternal } from "@/lib/utils";
|
||||||
import { GetAllAccountsFromDB, GetAccountFromDB, DeleteAccountFromDB, SaveAccountToDB, ExportAccountJSON, ExportAccountsTXT, UpdateAccountGroup, GetAllGroups, DownloadMediaWithMetadata, StopDownload, CheckFoldersExist, OpenFolder, GetFolderPath, } from "../../wailsjs/go/main/App";
|
import { GetAllAccountsFromDB, GetAccountFromDB, DeleteAccountFromDB, SaveAccountToDB, ExportAccountJSON, ExportAccountsTXT, UpdateAccountGroup, GetAllGroups, DownloadMediaWithMetadata, StopDownload, CheckFoldersExist, OpenFolder, GetFolderPath, } from "../../wailsjs/go/main/App";
|
||||||
import { EventsOn, EventsOff } from "../../wailsjs/runtime/runtime";
|
import { EventsOn } from "../../wailsjs/runtime/runtime";
|
||||||
import { main } from "../../wailsjs/go/models";
|
import { main } from "../../wailsjs/go/models";
|
||||||
interface DownloadProgress {
|
interface DownloadProgress {
|
||||||
current: number;
|
current: number;
|
||||||
@@ -66,11 +66,9 @@ interface DatabaseViewProps {
|
|||||||
}
|
}
|
||||||
const INITIAL_LOAD_COUNT = 12;
|
const INITIAL_LOAD_COUNT = 12;
|
||||||
const LOAD_MORE_COUNT = 12;
|
const LOAD_MORE_COUNT = 12;
|
||||||
|
|
||||||
function getContentScrollElement(): HTMLElement | null {
|
function getContentScrollElement(): HTMLElement | null {
|
||||||
return document.getElementById("app-content-scroll");
|
return document.getElementById("app-content-scroll");
|
||||||
}
|
}
|
||||||
|
|
||||||
export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewProps) {
|
export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewProps) {
|
||||||
const [accounts, setAccounts] = useState<AccountListItem[]>([]);
|
const [accounts, setAccounts] = useState<AccountListItem[]>([]);
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
@@ -82,8 +80,15 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
|
|||||||
const [filterMediaType, setFilterMediaType] = useState<string>("all");
|
const [filterMediaType, setFilterMediaType] = useState<string>("all");
|
||||||
const [accountViewMode, setAccountViewMode] = useState<"public" | "private">("public");
|
const [accountViewMode, setAccountViewMode] = useState<"public" | "private">("public");
|
||||||
const [searchQuery, setSearchQuery] = useState<string>("");
|
const [searchQuery, setSearchQuery] = useState<string>("");
|
||||||
|
const deferredSearchQuery = useDeferredValue(searchQuery);
|
||||||
const [sortOrder, setSortOrder] = useState<"newest" | "oldest" | "username-asc" | "username-desc" | "followers-high" | "followers-low" | "posts-high" | "posts-low" | "media-high" | "media-low">("newest");
|
const [sortOrder, setSortOrder] = useState<"newest" | "oldest" | "username-asc" | "username-desc" | "followers-high" | "followers-low" | "posts-high" | "posts-low" | "media-high" | "media-low">("newest");
|
||||||
const [gridView, setGridView] = useState<"large" | "small" | "list">("list");
|
const [gridView, setGridView] = useState<"large" | "small" | "list">(() => {
|
||||||
|
const stored = localStorage.getItem("savedAccountsViewMode");
|
||||||
|
return stored === "large" || stored === "small" || stored === "list" ? stored : "list";
|
||||||
|
});
|
||||||
|
useEffect(() => {
|
||||||
|
localStorage.setItem("savedAccountsViewMode", gridView);
|
||||||
|
}, [gridView]);
|
||||||
const [editingAccount, setEditingAccount] = useState<AccountListItem | null>(null);
|
const [editingAccount, setEditingAccount] = useState<AccountListItem | null>(null);
|
||||||
const [editGroupName, setEditGroupName] = useState("");
|
const [editGroupName, setEditGroupName] = useState("");
|
||||||
const [editGroupColor, setEditGroupColor] = useState("");
|
const [editGroupColor, setEditGroupColor] = useState("");
|
||||||
@@ -147,7 +152,6 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
|
|||||||
setDownloadProgress(progress);
|
setDownloadProgress(progress);
|
||||||
});
|
});
|
||||||
return () => {
|
return () => {
|
||||||
EventsOff("download-progress");
|
|
||||||
unsubscribe();
|
unsubscribe();
|
||||||
};
|
};
|
||||||
}, []);
|
}, []);
|
||||||
@@ -162,8 +166,8 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
|
|||||||
const baseAccounts = accountViewMode === "public" ? publicAccounts : privateAccounts;
|
const baseAccounts = accountViewMode === "public" ? publicAccounts : privateAccounts;
|
||||||
return baseAccounts
|
return baseAccounts
|
||||||
.filter((acc) => {
|
.filter((acc) => {
|
||||||
if (searchQuery) {
|
if (deferredSearchQuery) {
|
||||||
const query = searchQuery.toLowerCase();
|
const query = deferredSearchQuery.toLowerCase();
|
||||||
const matchesUsername = acc.username.toLowerCase().includes(query);
|
const matchesUsername = acc.username.toLowerCase().includes(query);
|
||||||
const matchesName = acc.name.toLowerCase().includes(query);
|
const matchesName = acc.name.toLowerCase().includes(query);
|
||||||
if (!matchesUsername && !matchesName)
|
if (!matchesUsername && !matchesName)
|
||||||
@@ -219,7 +223,7 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
|
|||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}, [accountViewMode, filterGroup, filterMediaType, privateAccounts, publicAccounts, searchQuery, sortOrder]);
|
}, [accountViewMode, filterGroup, filterMediaType, privateAccounts, publicAccounts, deferredSearchQuery, sortOrder]);
|
||||||
const visibleAccounts = useMemo(() => filteredAccounts.slice(0, visibleCount), [filteredAccounts, visibleCount]);
|
const visibleAccounts = useMemo(() => filteredAccounts.slice(0, visibleCount), [filteredAccounts, visibleCount]);
|
||||||
const visibleAccountsKey = visibleAccounts
|
const visibleAccountsKey = visibleAccounts
|
||||||
.map((account) => `${account.id}:${account.username}`)
|
.map((account) => `${account.id}:${account.username}`)
|
||||||
@@ -230,11 +234,9 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
|
|||||||
setFolderExistence(new Map());
|
setFolderExistence(new Map());
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (visibleAccounts.length === 0) {
|
if (visibleAccounts.length === 0) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
let active = true;
|
let active = true;
|
||||||
const loadVisibleFolderExistence = async () => {
|
const loadVisibleFolderExistence = async () => {
|
||||||
try {
|
try {
|
||||||
@@ -243,7 +245,6 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
|
|||||||
if (!active) {
|
if (!active) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
setFolderExistence((prev) => {
|
setFolderExistence((prev) => {
|
||||||
const next = new Map(prev);
|
const next = new Map(prev);
|
||||||
for (const account of visibleAccounts) {
|
for (const account of visibleAccounts) {
|
||||||
@@ -256,7 +257,6 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
|
|||||||
console.error("Failed to check visible folders:", error);
|
console.error("Failed to check visible folders:", error);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
void loadVisibleFolderExistence();
|
void loadVisibleFolderExistence();
|
||||||
return () => {
|
return () => {
|
||||||
active = false;
|
active = false;
|
||||||
@@ -316,17 +316,24 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
|
|||||||
toast.error("Failed to load account data");
|
toast.error("Failed to load account data");
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
const handleOpenFolder = async (username: string) => {
|
const handleOpenFolder = async (account: AccountListItem) => {
|
||||||
const settings = getSettings();
|
const settings = getSettings();
|
||||||
let folderName = username;
|
const basePath = settings.downloadPath || "";
|
||||||
if (username === "bookmarks") {
|
if (!basePath) {
|
||||||
folderName = "My Bookmarks";
|
toast.error("Download folder is not set");
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
else if (username === "likes") {
|
let username = account.username || account.name || "";
|
||||||
folderName = "My Likes";
|
|
||||||
}
|
|
||||||
const folderPath = await GetFolderPath(settings.downloadPath, folderName);
|
|
||||||
try {
|
try {
|
||||||
|
const responseJSON = await GetAccountFromDB(account.id);
|
||||||
|
const data = JSON.parse(responseJSON);
|
||||||
|
username = data.account_info?.name || username;
|
||||||
|
}
|
||||||
|
catch {
|
||||||
|
}
|
||||||
|
const folderName = getFolderNameForAccount(username);
|
||||||
|
try {
|
||||||
|
const folderPath = await GetFolderPath(basePath, folderName);
|
||||||
await OpenFolder(folderPath);
|
await OpenFolder(folderPath);
|
||||||
}
|
}
|
||||||
catch (error) {
|
catch (error) {
|
||||||
@@ -377,7 +384,13 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
|
|||||||
})),
|
})),
|
||||||
output_dir: outputDir,
|
output_dir: outputDir,
|
||||||
username: actualUsername,
|
username: actualUsername,
|
||||||
|
concurrent_downloads: settings.concurrentDownloads || 10,
|
||||||
|
skip_existing: settings.skipExistingFiles,
|
||||||
|
delete_incomplete_files: settings.deleteIncompleteFiles,
|
||||||
|
retry_attempts: settings.retryAttempts,
|
||||||
proxy: settings.proxy || "",
|
proxy: settings.proxy || "",
|
||||||
|
filename_template: settings.filenameTemplate || "",
|
||||||
|
folder_template: settings.folderTemplate || "",
|
||||||
});
|
});
|
||||||
const response = await DownloadMediaWithMetadata(request);
|
const response = await DownloadMediaWithMetadata(request);
|
||||||
if (response.cancelled) {
|
if (response.cancelled) {
|
||||||
@@ -496,7 +509,13 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
|
|||||||
})),
|
})),
|
||||||
output_dir: outputDir,
|
output_dir: outputDir,
|
||||||
username: actualUsername,
|
username: actualUsername,
|
||||||
|
concurrent_downloads: settings.concurrentDownloads || 10,
|
||||||
|
skip_existing: settings.skipExistingFiles,
|
||||||
|
delete_incomplete_files: settings.deleteIncompleteFiles,
|
||||||
|
retry_attempts: settings.retryAttempts,
|
||||||
proxy: settings.proxy || "",
|
proxy: settings.proxy || "",
|
||||||
|
filename_template: settings.filenameTemplate || "",
|
||||||
|
folder_template: settings.folderTemplate || "",
|
||||||
});
|
});
|
||||||
const response = await DownloadMediaWithMetadata(request);
|
const response = await DownloadMediaWithMetadata(request);
|
||||||
if (response.cancelled) {
|
if (response.cancelled) {
|
||||||
@@ -611,104 +630,116 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
|
|||||||
input.type = "file";
|
input.type = "file";
|
||||||
input.accept = ".json";
|
input.accept = ".json";
|
||||||
input.multiple = true;
|
input.multiple = true;
|
||||||
|
input.style.display = "none";
|
||||||
|
document.body.appendChild(input);
|
||||||
|
const cleanup = () => {
|
||||||
|
if (input.parentNode) {
|
||||||
|
input.parentNode.removeChild(input);
|
||||||
|
}
|
||||||
|
};
|
||||||
input.onchange = async (e) => {
|
input.onchange = async (e) => {
|
||||||
const files = (e.target as HTMLInputElement).files;
|
try {
|
||||||
if (!files || files.length === 0)
|
const files = (e.target as HTMLInputElement).files;
|
||||||
return;
|
if (!files || files.length === 0)
|
||||||
let imported = 0;
|
return;
|
||||||
for (const file of Array.from(files)) {
|
let imported = 0;
|
||||||
try {
|
for (const file of Array.from(files)) {
|
||||||
const text = await file.text();
|
try {
|
||||||
const data = JSON.parse(text);
|
const text = await file.text();
|
||||||
let detectedMediaType = "all";
|
const data = JSON.parse(text);
|
||||||
if (data.media_type) {
|
let detectedMediaType = "all";
|
||||||
detectedMediaType = data.media_type;
|
if (data.media_type) {
|
||||||
}
|
detectedMediaType = data.media_type;
|
||||||
else if (data.media_list && Array.isArray(data.media_list)) {
|
|
||||||
const types = new Set(data.media_list.map((item: {
|
|
||||||
media_type?: string;
|
|
||||||
type?: string;
|
|
||||||
}) => item.media_type || item.type).filter(Boolean));
|
|
||||||
if (types.size === 1) {
|
|
||||||
const singleType = Array.from(types)[0] as string;
|
|
||||||
if (singleType === "photo")
|
|
||||||
detectedMediaType = "image";
|
|
||||||
else if (singleType === "video")
|
|
||||||
detectedMediaType = "video";
|
|
||||||
else if (singleType === "animated_gif")
|
|
||||||
detectedMediaType = "gif";
|
|
||||||
else
|
|
||||||
detectedMediaType = singleType;
|
|
||||||
}
|
}
|
||||||
}
|
else if (data.media_list && Array.isArray(data.media_list)) {
|
||||||
else if (data.timeline && Array.isArray(data.timeline)) {
|
const types = new Set(data.media_list.map((item: {
|
||||||
const types = new Set(data.timeline.map((item: {
|
|
||||||
type?: string;
|
|
||||||
}) => item.type).filter(Boolean));
|
|
||||||
if (types.size === 1) {
|
|
||||||
const singleType = Array.from(types)[0] as string;
|
|
||||||
if (singleType === "photo")
|
|
||||||
detectedMediaType = "image";
|
|
||||||
else if (singleType === "video")
|
|
||||||
detectedMediaType = "video";
|
|
||||||
else if (singleType === "animated_gif")
|
|
||||||
detectedMediaType = "gif";
|
|
||||||
else if (singleType === "text")
|
|
||||||
detectedMediaType = "text";
|
|
||||||
else
|
|
||||||
detectedMediaType = singleType;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (data.account_info && data.timeline) {
|
|
||||||
await SaveAccountToDB(data.account_info.name, data.account_info.nick, data.account_info.profile_image, data.total_urls || data.timeline.length, text, detectedMediaType);
|
|
||||||
imported++;
|
|
||||||
}
|
|
||||||
else if (data.username && data.media_list) {
|
|
||||||
const convertedData = {
|
|
||||||
account_info: {
|
|
||||||
name: data.username,
|
|
||||||
nick: data.nick || data.username,
|
|
||||||
date: "",
|
|
||||||
followers_count: data.followers || 0,
|
|
||||||
friends_count: data.following || 0,
|
|
||||||
profile_image: data.profile_image || "",
|
|
||||||
statuses_count: data.posts || 0,
|
|
||||||
},
|
|
||||||
total_urls: data.media_list.length,
|
|
||||||
timeline: data.media_list.map((item: {
|
|
||||||
url: string;
|
|
||||||
date: string;
|
|
||||||
tweet_id: string;
|
|
||||||
type: string;
|
|
||||||
media_type?: string;
|
media_type?: string;
|
||||||
}) => ({
|
type?: string;
|
||||||
url: item.url,
|
}) => item.media_type || item.type).filter(Boolean));
|
||||||
date: item.date,
|
if (types.size === 1) {
|
||||||
tweet_id: item.tweet_id,
|
const singleType = Array.from(types)[0] as string;
|
||||||
type: item.media_type || item.type,
|
if (singleType === "photo")
|
||||||
is_retweet: false,
|
detectedMediaType = "image";
|
||||||
})),
|
else if (singleType === "video")
|
||||||
metadata: {
|
detectedMediaType = "video";
|
||||||
new_entries: data.media_list.length,
|
else if (singleType === "animated_gif")
|
||||||
page: 0,
|
detectedMediaType = "gif";
|
||||||
batch_size: 0,
|
else
|
||||||
has_more: false,
|
detectedMediaType = singleType;
|
||||||
},
|
}
|
||||||
};
|
}
|
||||||
await SaveAccountToDB(convertedData.account_info.name, convertedData.account_info.nick, convertedData.account_info.profile_image, convertedData.total_urls, JSON.stringify(convertedData), detectedMediaType);
|
else if (data.timeline && Array.isArray(data.timeline)) {
|
||||||
imported++;
|
const types = new Set(data.timeline.map((item: {
|
||||||
|
type?: string;
|
||||||
|
}) => item.type).filter(Boolean));
|
||||||
|
if (types.size === 1) {
|
||||||
|
const singleType = Array.from(types)[0] as string;
|
||||||
|
if (singleType === "photo")
|
||||||
|
detectedMediaType = "image";
|
||||||
|
else if (singleType === "video")
|
||||||
|
detectedMediaType = "video";
|
||||||
|
else if (singleType === "animated_gif")
|
||||||
|
detectedMediaType = "gif";
|
||||||
|
else if (singleType === "text")
|
||||||
|
detectedMediaType = "text";
|
||||||
|
else
|
||||||
|
detectedMediaType = singleType;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (data.account_info && data.timeline) {
|
||||||
|
await SaveAccountToDB(data.account_info.name, data.account_info.nick, data.account_info.profile_image, data.total_urls || data.timeline.length, text, detectedMediaType);
|
||||||
|
imported++;
|
||||||
|
}
|
||||||
|
else if (data.username && data.media_list) {
|
||||||
|
const convertedData = {
|
||||||
|
account_info: {
|
||||||
|
name: data.username,
|
||||||
|
nick: data.nick || data.username,
|
||||||
|
date: "",
|
||||||
|
followers_count: data.followers || 0,
|
||||||
|
friends_count: data.following || 0,
|
||||||
|
profile_image: data.profile_image || "",
|
||||||
|
statuses_count: data.posts || 0,
|
||||||
|
},
|
||||||
|
total_urls: data.media_list.length,
|
||||||
|
timeline: data.media_list.map((item: {
|
||||||
|
url: string;
|
||||||
|
date: string;
|
||||||
|
tweet_id: string;
|
||||||
|
type: string;
|
||||||
|
media_type?: string;
|
||||||
|
}) => ({
|
||||||
|
url: item.url,
|
||||||
|
date: item.date,
|
||||||
|
tweet_id: item.tweet_id,
|
||||||
|
type: item.media_type || item.type,
|
||||||
|
is_retweet: false,
|
||||||
|
})),
|
||||||
|
metadata: {
|
||||||
|
new_entries: data.media_list.length,
|
||||||
|
page: 0,
|
||||||
|
batch_size: 0,
|
||||||
|
has_more: false,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
await SaveAccountToDB(convertedData.account_info.name, convertedData.account_info.nick, convertedData.account_info.profile_image, convertedData.total_urls, JSON.stringify(convertedData), detectedMediaType);
|
||||||
|
imported++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (err) {
|
||||||
|
console.error(`Failed to import ${file.name}:`, err);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
catch (err) {
|
if (imported > 0) {
|
||||||
console.error(`Failed to import ${file.name}:`, err);
|
toast.success(`Imported ${imported} account(s)`);
|
||||||
|
loadAccounts();
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
toast.error("No valid files imported");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (imported > 0) {
|
finally {
|
||||||
toast.success(`Imported ${imported} account(s)`);
|
cleanup();
|
||||||
loadAccounts();
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
toast.error("No valid files imported");
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
input.click();
|
input.click();
|
||||||
@@ -995,9 +1026,9 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
|
|||||||
{gridView === "large" && (<div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
|
{gridView === "large" && (<div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
|
||||||
{filteredAccounts
|
{filteredAccounts
|
||||||
.slice(0, visibleCount)
|
.slice(0, visibleCount)
|
||||||
.map((account) => (<div key={account.id} className={`relative rounded-lg border transition-colors p-4 ${selectedIds.has(account.id) ? "border-primary bg-primary/5" : "bg-card hover:bg-muted/50"}`}>
|
.map((account, index) => (<div key={account.id} onClick={() => handleView(account.id, account.username)} className={`relative rounded-lg border transition-colors p-4 cursor-pointer ${selectedIds.has(account.id) ? "border-primary bg-primary/5" : "bg-card hover:bg-muted/50"}`}>
|
||||||
|
|
||||||
<Checkbox checked={selectedIds.has(account.id)} onCheckedChange={() => toggleSelect(account.id)} className="absolute top-2 left-2 z-10"/>
|
<Checkbox checked={selectedIds.has(account.id)} onCheckedChange={() => toggleSelect(account.id)} onClick={(e) => e.stopPropagation()} className="absolute top-2 left-2 z-10"/>
|
||||||
|
|
||||||
<div className="absolute top-2 right-2 z-10 flex gap-1">
|
<div className="absolute top-2 right-2 z-10 flex gap-1">
|
||||||
<Badge variant="secondary" className={cn("text-xs flex items-center gap-1", account.media_type === "text" && "bg-orange-500/20 text-orange-600 dark:text-orange-400", account.media_type === "image" && "bg-blue-500/20 text-blue-600 dark:text-blue-400", account.media_type === "video" && "bg-purple-500/20 text-purple-600 dark:text-purple-400", account.media_type === "gif" && "bg-green-500/20 text-green-600 dark:text-green-400", (!account.media_type || account.media_type === "all") && "bg-indigo-500/20 text-indigo-600 dark:text-indigo-400")}>
|
<Badge variant="secondary" className={cn("text-xs flex items-center gap-1", account.media_type === "text" && "bg-orange-500/20 text-orange-600 dark:text-orange-400", account.media_type === "image" && "bg-blue-500/20 text-blue-600 dark:text-blue-400", account.media_type === "video" && "bg-purple-500/20 text-purple-600 dark:text-purple-400", account.media_type === "gif" && "bg-green-500/20 text-green-600 dark:text-green-400", (!account.media_type || account.media_type === "all") && "bg-indigo-500/20 text-indigo-600 dark:text-indigo-400")}>
|
||||||
@@ -1012,9 +1043,14 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
|
|||||||
</Badge>)}
|
</Badge>)}
|
||||||
</div>
|
</div>
|
||||||
<div className="flex flex-col items-center text-center gap-3 pt-4">
|
<div className="flex flex-col items-center text-center gap-3 pt-4">
|
||||||
{isPrivateAccount(account.username) ? (<div className="w-20 h-20 rounded-full bg-primary/10 flex items-center justify-center cursor-pointer hover:bg-primary/20 transition-colors" onClick={() => handleView(account.id, account.username)}>
|
<div className="relative">
|
||||||
{account.username === "bookmarks" ? (<Bookmark className="h-10 w-10 text-primary"/>) : (<Heart className="h-10 w-10 text-primary"/>)}
|
<span className="absolute -top-1.5 -left-1.5 z-10 flex h-5 min-w-5 items-center justify-center rounded-full bg-primary px-1 text-xs font-medium text-primary-foreground">
|
||||||
</div>) : (<img src={account.profile_image} alt={account.name} className="w-20 h-20 rounded-full cursor-pointer hover:opacity-80 transition-opacity" onClick={() => handleView(account.id, account.username)}/>)}
|
{index + 1}
|
||||||
|
</span>
|
||||||
|
{isPrivateAccount(account.username) ? (<div className="w-20 h-20 rounded-full bg-primary/10 flex items-center justify-center">
|
||||||
|
{account.username === "bookmarks" ? (<Bookmark className="h-10 w-10 text-primary"/>) : (<Heart className="h-10 w-10 text-primary"/>)}
|
||||||
|
</div>) : (<img src={account.profile_image} alt={account.name} className="w-20 h-20 rounded-full"/>)}
|
||||||
|
</div>
|
||||||
<div className="w-full min-w-0">
|
<div className="w-full min-w-0">
|
||||||
<div className="font-medium truncate">{account.name}</div>
|
<div className="font-medium truncate">{account.name}</div>
|
||||||
{!isPrivateAccount(account.username) && (<button type="button" onClick={() => openExternal(`https://x.com/${account.username}`)} className="text-sm text-muted-foreground hover:text-primary hover:underline">
|
{!isPrivateAccount(account.username) && (<button type="button" onClick={() => openExternal(`https://x.com/${account.username}`)} className="text-sm text-muted-foreground hover:text-primary hover:underline">
|
||||||
@@ -1024,13 +1060,13 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
|
|||||||
{formatNumberWithComma(account.total_media)} media
|
{formatNumberWithComma(account.total_media)} media
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex gap-1">
|
<div className="flex gap-1" onClick={(e) => e.stopPropagation()}>
|
||||||
{downloadingAccountId === account.id ? (<Button variant="outline" size="icon" className="h-8 w-8" onClick={handleStopDownload}>
|
{downloadingAccountId === account.id ? (<Button variant="outline" size="icon" className="h-8 w-8" onClick={handleStopDownload}>
|
||||||
<StopCircle className="h-4 w-4 text-destructive"/>
|
<StopCircle className="h-4 w-4 text-destructive"/>
|
||||||
</Button>) : (<Button variant="default" size="icon" className="h-8 w-8" onClick={() => handleDownload(account.id, account.username)} disabled={isDownloading}>
|
</Button>) : (<Button variant="default" size="icon" className="h-8 w-8" onClick={() => handleDownload(account.id, account.username)} disabled={isDownloading}>
|
||||||
<Download className="h-4 w-4"/>
|
<Download className="h-4 w-4"/>
|
||||||
</Button>)}
|
</Button>)}
|
||||||
<Button variant="outline" size="icon" className="h-8 w-8" onClick={() => handleOpenFolder(account.username)} disabled={!folderExistence.get(account.id)}>
|
<Button variant="outline" size="icon" className="h-8 w-8" onClick={() => handleOpenFolder(account)} disabled={!folderExistence.get(account.id)}>
|
||||||
<FolderOpen className="h-4 w-4"/>
|
<FolderOpen className="h-4 w-4"/>
|
||||||
</Button>
|
</Button>
|
||||||
<DropdownMenu>
|
<DropdownMenu>
|
||||||
@@ -1040,7 +1076,10 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
|
|||||||
</Button>
|
</Button>
|
||||||
</DropdownMenuTrigger>
|
</DropdownMenuTrigger>
|
||||||
<DropdownMenuContent align="end">
|
<DropdownMenuContent align="end">
|
||||||
{!isPrivateAccount(account.username) && (<DropdownMenuItem onClick={() => handleEditGroup(account)}>
|
{!isPrivateAccount(account.username) && (<DropdownMenuItem onSelect={(event) => {
|
||||||
|
event.preventDefault();
|
||||||
|
handleEditGroup(account);
|
||||||
|
}}>
|
||||||
<Pencil className="h-4 w-4 mr-2"/>
|
<Pencil className="h-4 w-4 mr-2"/>
|
||||||
Edit Group
|
Edit Group
|
||||||
</DropdownMenuItem>)}
|
</DropdownMenuItem>)}
|
||||||
@@ -1084,9 +1123,9 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
|
|||||||
{gridView === "small" && (<div className="grid grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-3">
|
{gridView === "small" && (<div className="grid grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-3">
|
||||||
{filteredAccounts
|
{filteredAccounts
|
||||||
.slice(0, visibleCount)
|
.slice(0, visibleCount)
|
||||||
.map((account) => (<div key={account.id} className={`relative rounded-lg border transition-colors p-3 ${selectedIds.has(account.id) ? "border-primary bg-primary/5" : "bg-card hover:bg-muted/50"}`}>
|
.map((account, index) => (<div key={account.id} onClick={() => handleView(account.id, account.username)} className={`relative rounded-lg border transition-colors p-3 cursor-pointer ${selectedIds.has(account.id) ? "border-primary bg-primary/5" : "bg-card hover:bg-muted/50"}`}>
|
||||||
|
|
||||||
<Checkbox checked={selectedIds.has(account.id)} onCheckedChange={() => toggleSelect(account.id)} className="absolute top-1.5 left-1.5 z-10"/>
|
<Checkbox checked={selectedIds.has(account.id)} onCheckedChange={() => toggleSelect(account.id)} onClick={(e) => e.stopPropagation()} className="absolute top-1.5 left-1.5 z-10"/>
|
||||||
|
|
||||||
<div className="absolute top-1.5 right-1.5 z-10 flex gap-1">
|
<div className="absolute top-1.5 right-1.5 z-10 flex gap-1">
|
||||||
<Badge variant="secondary" className={cn("text-xs p-1", account.media_type === "text" && "bg-orange-500/20 text-orange-600 dark:text-orange-400", account.media_type === "image" && "bg-blue-500/20 text-blue-600 dark:text-blue-400", account.media_type === "video" && "bg-purple-500/20 text-purple-600 dark:text-purple-400", account.media_type === "gif" && "bg-green-500/20 text-green-600 dark:text-green-400", (!account.media_type || account.media_type === "all") && "bg-indigo-500/20 text-indigo-600 dark:text-indigo-400")}>
|
<Badge variant="secondary" className={cn("text-xs p-1", account.media_type === "text" && "bg-orange-500/20 text-orange-600 dark:text-orange-400", account.media_type === "image" && "bg-blue-500/20 text-blue-600 dark:text-blue-400", account.media_type === "video" && "bg-purple-500/20 text-purple-600 dark:text-purple-400", account.media_type === "gif" && "bg-green-500/20 text-green-600 dark:text-green-400", (!account.media_type || account.media_type === "all") && "bg-indigo-500/20 text-indigo-600 dark:text-indigo-400")}>
|
||||||
@@ -1101,9 +1140,14 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
|
|||||||
</Badge>)}
|
</Badge>)}
|
||||||
</div>
|
</div>
|
||||||
<div className="flex flex-col items-center text-center gap-2 pt-4">
|
<div className="flex flex-col items-center text-center gap-2 pt-4">
|
||||||
{isPrivateAccount(account.username) ? (<div className="w-14 h-14 rounded-full bg-primary/10 flex items-center justify-center cursor-pointer hover:bg-primary/20 transition-colors" onClick={() => handleView(account.id, account.username)}>
|
<div className="relative">
|
||||||
{account.username === "bookmarks" ? (<Bookmark className="h-7 w-7 text-primary"/>) : (<Heart className="h-7 w-7 text-primary"/>)}
|
<span className="absolute -top-1.5 -left-1.5 z-10 flex h-5 min-w-5 items-center justify-center rounded-full bg-primary px-1 text-xs font-medium text-primary-foreground">
|
||||||
</div>) : (<img src={account.profile_image} alt={account.name} className="w-14 h-14 rounded-full cursor-pointer hover:opacity-80 transition-opacity" onClick={() => handleView(account.id, account.username)}/>)}
|
{index + 1}
|
||||||
|
</span>
|
||||||
|
{isPrivateAccount(account.username) ? (<div className="w-14 h-14 rounded-full bg-primary/10 flex items-center justify-center">
|
||||||
|
{account.username === "bookmarks" ? (<Bookmark className="h-7 w-7 text-primary"/>) : (<Heart className="h-7 w-7 text-primary"/>)}
|
||||||
|
</div>) : (<img src={account.profile_image} alt={account.name} className="w-14 h-14 rounded-full"/>)}
|
||||||
|
</div>
|
||||||
<div className="w-full min-w-0">
|
<div className="w-full min-w-0">
|
||||||
<div className="text-xs font-medium truncate">{account.name}</div>
|
<div className="text-xs font-medium truncate">{account.name}</div>
|
||||||
{!isPrivateAccount(account.username) && (<button type="button" onClick={() => openExternal(`https://x.com/${account.username}`)} className="text-xs text-muted-foreground hover:text-primary hover:underline truncate block w-full">
|
{!isPrivateAccount(account.username) && (<button type="button" onClick={() => openExternal(`https://x.com/${account.username}`)} className="text-xs text-muted-foreground hover:text-primary hover:underline truncate block w-full">
|
||||||
@@ -1113,13 +1157,13 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
|
|||||||
{formatNumberWithComma(account.total_media)} media
|
{formatNumberWithComma(account.total_media)} media
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex gap-1">
|
<div className="flex gap-1" onClick={(e) => e.stopPropagation()}>
|
||||||
{downloadingAccountId === account.id ? (<Button variant="outline" size="icon" className="h-7 w-7" onClick={handleStopDownload}>
|
{downloadingAccountId === account.id ? (<Button variant="outline" size="icon" className="h-7 w-7" onClick={handleStopDownload}>
|
||||||
<StopCircle className="h-3 w-3 text-destructive"/>
|
<StopCircle className="h-3 w-3 text-destructive"/>
|
||||||
</Button>) : (<Button variant="default" size="icon" className="h-7 w-7" onClick={() => handleDownload(account.id, account.username)} disabled={isDownloading}>
|
</Button>) : (<Button variant="default" size="icon" className="h-7 w-7" onClick={() => handleDownload(account.id, account.username)} disabled={isDownloading}>
|
||||||
<Download className="h-3 w-3"/>
|
<Download className="h-3 w-3"/>
|
||||||
</Button>)}
|
</Button>)}
|
||||||
<Button variant="outline" size="icon" className="h-7 w-7" onClick={() => handleOpenFolder(account.username)} disabled={!folderExistence.get(account.id)}>
|
<Button variant="outline" size="icon" className="h-7 w-7" onClick={() => handleOpenFolder(account)} disabled={!folderExistence.get(account.id)}>
|
||||||
<FolderOpen className="h-3 w-3"/>
|
<FolderOpen className="h-3 w-3"/>
|
||||||
</Button>
|
</Button>
|
||||||
<DropdownMenu>
|
<DropdownMenu>
|
||||||
@@ -1129,7 +1173,10 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
|
|||||||
</Button>
|
</Button>
|
||||||
</DropdownMenuTrigger>
|
</DropdownMenuTrigger>
|
||||||
<DropdownMenuContent align="end">
|
<DropdownMenuContent align="end">
|
||||||
{!isPrivateAccount(account.username) && (<DropdownMenuItem onClick={() => handleEditGroup(account)}>
|
{!isPrivateAccount(account.username) && (<DropdownMenuItem onSelect={(event) => {
|
||||||
|
event.preventDefault();
|
||||||
|
handleEditGroup(account);
|
||||||
|
}}>
|
||||||
<Pencil className="h-4 w-4 mr-2"/>
|
<Pencil className="h-4 w-4 mr-2"/>
|
||||||
Edit Group
|
Edit Group
|
||||||
</DropdownMenuItem>)}
|
</DropdownMenuItem>)}
|
||||||
@@ -1173,14 +1220,16 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
|
|||||||
{gridView === "list" && filteredAccounts
|
{gridView === "list" && filteredAccounts
|
||||||
.slice(0, visibleCount)
|
.slice(0, visibleCount)
|
||||||
.map((account, index) => (<div key={account.id} className={`rounded-lg border transition-colors ${selectedIds.has(account.id) ? "border-primary bg-primary/5" : "bg-card hover:bg-muted/50"}`}>
|
.map((account, index) => (<div key={account.id} className={`rounded-lg border transition-colors ${selectedIds.has(account.id) ? "border-primary bg-primary/5" : "bg-card hover:bg-muted/50"}`}>
|
||||||
<div className="flex items-center gap-4 p-4">
|
<div className="flex items-center gap-4 p-4 cursor-pointer" onClick={() => handleView(account.id, account.username)}>
|
||||||
<Checkbox checked={selectedIds.has(account.id)} onCheckedChange={() => toggleSelect(account.id)}/>
|
<Checkbox checked={selectedIds.has(account.id)} onCheckedChange={() => toggleSelect(account.id)} onClick={(e) => e.stopPropagation()}/>
|
||||||
<span className="text-sm text-muted-foreground w-8 text-center shrink-0">
|
<div className="relative shrink-0">
|
||||||
{index + 1}
|
<span className="absolute -top-1.5 -left-1.5 z-10 flex h-5 min-w-5 items-center justify-center rounded-full bg-primary px-1 text-xs font-medium text-primary-foreground">
|
||||||
</span>
|
{index + 1}
|
||||||
{isPrivateAccount(account.username) ? (<div className="w-12 h-12 rounded-full bg-primary/10 flex items-center justify-center cursor-pointer hover:bg-primary/20 transition-colors" onClick={() => handleView(account.id, account.username)}>
|
</span>
|
||||||
{account.username === "bookmarks" ? (<Bookmark className="h-6 w-6 text-primary"/>) : (<Heart className="h-6 w-6 text-primary"/>)}
|
{isPrivateAccount(account.username) ? (<div className="w-12 h-12 rounded-full bg-primary/10 flex items-center justify-center">
|
||||||
</div>) : (<img src={account.profile_image} alt={account.name} className="w-12 h-12 rounded-full cursor-pointer hover:opacity-80 transition-opacity" onClick={() => handleView(account.id, account.username)}/>)}
|
{account.username === "bookmarks" ? (<Bookmark className="h-6 w-6 text-primary"/>) : (<Heart className="h-6 w-6 text-primary"/>)}
|
||||||
|
</div>) : (<img src={account.profile_image} alt={account.name} className="w-12 h-12 rounded-full"/>)}
|
||||||
|
</div>
|
||||||
<div className="flex-1 min-w-0">
|
<div className="flex-1 min-w-0">
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<span className="truncate">{account.name}</span>
|
<span className="truncate">{account.name}</span>
|
||||||
@@ -1222,7 +1271,7 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
|
|||||||
{account.last_fetched} {getRelativeTime(account.last_fetched)}
|
{account.last_fetched} {getRelativeTime(account.last_fetched)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2" onClick={(e) => e.stopPropagation()}>
|
||||||
{downloadingAccountId === account.id ? (<Tooltip>
|
{downloadingAccountId === account.id ? (<Tooltip>
|
||||||
<TooltipTrigger asChild>
|
<TooltipTrigger asChild>
|
||||||
<Button variant="outline" size="icon" onClick={handleStopDownload}>
|
<Button variant="outline" size="icon" onClick={handleStopDownload}>
|
||||||
@@ -1240,7 +1289,7 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
|
|||||||
</Tooltip>)}
|
</Tooltip>)}
|
||||||
<Tooltip>
|
<Tooltip>
|
||||||
<TooltipTrigger asChild>
|
<TooltipTrigger asChild>
|
||||||
<Button variant="outline" size="icon" onClick={() => handleOpenFolder(account.username)} disabled={!folderExistence.get(account.id)}>
|
<Button variant="outline" size="icon" onClick={() => handleOpenFolder(account)} disabled={!folderExistence.get(account.id)}>
|
||||||
<FolderOpen className="h-4 w-4"/>
|
<FolderOpen className="h-4 w-4"/>
|
||||||
</Button>
|
</Button>
|
||||||
</TooltipTrigger>
|
</TooltipTrigger>
|
||||||
@@ -1258,7 +1307,10 @@ export function DatabaseView({ onLoadAccount, onUpdateSelected }: DatabaseViewPr
|
|||||||
<TooltipContent>More Options</TooltipContent>
|
<TooltipContent>More Options</TooltipContent>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
<DropdownMenuContent align="end">
|
<DropdownMenuContent align="end">
|
||||||
{!isPrivateAccount(account.username) && (<DropdownMenuItem onClick={() => handleEditGroup(account)}>
|
{!isPrivateAccount(account.username) && (<DropdownMenuItem onSelect={(event) => {
|
||||||
|
event.preventDefault();
|
||||||
|
handleEditGroup(account);
|
||||||
|
}}>
|
||||||
<Pencil className="h-4 w-4 mr-2"/>
|
<Pencil className="h-4 w-4 mr-2"/>
|
||||||
Edit Group
|
Edit Group
|
||||||
</DropdownMenuItem>)}
|
</DropdownMenuItem>)}
|
||||||
|
|||||||
@@ -4,36 +4,40 @@ import { Button } from "@/components/ui/button";
|
|||||||
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from "@/components/ui/dialog";
|
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from "@/components/ui/dialog";
|
||||||
import { Spinner } from "@/components/ui/spinner";
|
import { Spinner } from "@/components/ui/spinner";
|
||||||
import { toastWithSound as toast } from "@/lib/toast-with-sound";
|
import { toastWithSound as toast } from "@/lib/toast-with-sound";
|
||||||
|
import { compareVersionNumbers } from "@/lib/version";
|
||||||
import { Quit } from "../../wailsjs/runtime/runtime";
|
import { Quit } from "../../wailsjs/runtime/runtime";
|
||||||
import { DownloadExtractor, IsExtractorInstalled } from "../../wailsjs/go/main/App";
|
import { DownloadExtractor, GetExtractorVersionStatus } from "../../wailsjs/go/main/App";
|
||||||
|
|
||||||
interface DependencySetupDialogProps {
|
interface DependencySetupDialogProps {
|
||||||
onInstalled?: () => void;
|
onInstalled?: () => void;
|
||||||
}
|
}
|
||||||
|
interface ExtractorVersionStatus {
|
||||||
interface GithubReleaseResponse {
|
installed: boolean;
|
||||||
tag_name?: string;
|
installed_version?: string;
|
||||||
|
latest_version?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
const extractorReleaseAPIURL = "https://api.github.com/repos/afkarxyz/xtractor-binaries/releases/latest";
|
|
||||||
|
|
||||||
export function DependencySetupDialog({ onInstalled }: DependencySetupDialogProps) {
|
export function DependencySetupDialog({ onInstalled }: DependencySetupDialogProps) {
|
||||||
const [open, setOpen] = useState(false);
|
const [open, setOpen] = useState(false);
|
||||||
const [checking, setChecking] = useState(true);
|
const [checking, setChecking] = useState(true);
|
||||||
const [downloading, setDownloading] = useState(false);
|
const [downloading, setDownloading] = useState(false);
|
||||||
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
||||||
|
const [updateRequired, setUpdateRequired] = useState(false);
|
||||||
|
const [installedVersion, setInstalledVersion] = useState<string | null>(null);
|
||||||
const [releaseVersion, setReleaseVersion] = useState<string | null>(null);
|
const [releaseVersion, setReleaseVersion] = useState<string | null>(null);
|
||||||
const [releaseStatusMessage, setReleaseStatusMessage] = useState("Checking latest GitHub release...");
|
const [releaseStatusMessage, setReleaseStatusMessage] = useState("Checking latest GitHub release...");
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
let cancelled = false;
|
let cancelled = false;
|
||||||
const abortController = new AbortController();
|
|
||||||
|
|
||||||
const checkDependency = async () => {
|
const checkDependency = async () => {
|
||||||
try {
|
try {
|
||||||
const installed = await IsExtractorInstalled();
|
const status = await GetExtractorVersionStatus() as ExtractorVersionStatus;
|
||||||
|
const nextInstalledVersion = status.installed_version?.trim() || null;
|
||||||
|
const nextLatestVersion = status.latest_version?.trim() || null;
|
||||||
|
const nextUpdateRequired = !!(status.installed && nextLatestVersion && (!nextInstalledVersion || compareVersionNumbers(nextLatestVersion, nextInstalledVersion) > 0));
|
||||||
if (!cancelled) {
|
if (!cancelled) {
|
||||||
setOpen(!installed);
|
setUpdateRequired(nextUpdateRequired);
|
||||||
|
setInstalledVersion(nextInstalledVersion);
|
||||||
|
setReleaseVersion(nextLatestVersion);
|
||||||
|
setReleaseStatusMessage(nextLatestVersion ? `Latest GitHub release: ${nextLatestVersion}` : "Latest GitHub release unavailable.");
|
||||||
|
setOpen(!status.installed || nextUpdateRequired);
|
||||||
setErrorMessage(null);
|
setErrorMessage(null);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -49,56 +53,18 @@ export function DependencySetupDialog({ onInstalled }: DependencySetupDialogProp
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const loadReleaseInfo = async () => {
|
|
||||||
try {
|
|
||||||
const response = await fetch(extractorReleaseAPIURL, {
|
|
||||||
headers: {
|
|
||||||
Accept: "application/vnd.github+json",
|
|
||||||
},
|
|
||||||
signal: abortController.signal,
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
throw new Error(`GitHub release status ${response.status}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
const release = (await response.json()) as GithubReleaseResponse;
|
|
||||||
const version = release.tag_name?.trim();
|
|
||||||
|
|
||||||
if (!version) {
|
|
||||||
throw new Error("Missing GitHub release tag");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!cancelled) {
|
|
||||||
setReleaseVersion(version);
|
|
||||||
setReleaseStatusMessage(`Latest GitHub release: ${version}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
catch {
|
|
||||||
if (!cancelled && !abortController.signal.aborted) {
|
|
||||||
setReleaseVersion(null);
|
|
||||||
setReleaseStatusMessage("Latest GitHub release unavailable.");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
void checkDependency();
|
void checkDependency();
|
||||||
void loadReleaseInfo();
|
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
cancelled = true;
|
cancelled = true;
|
||||||
abortController.abort();
|
|
||||||
};
|
};
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const handleDownload = async () => {
|
const handleDownload = async () => {
|
||||||
setDownloading(true);
|
setDownloading(true);
|
||||||
setErrorMessage(null);
|
setErrorMessage(null);
|
||||||
try {
|
try {
|
||||||
await DownloadExtractor();
|
await DownloadExtractor();
|
||||||
setOpen(false);
|
setOpen(false);
|
||||||
toast.success("Xtractor installed");
|
toast.success(updateRequired ? "Xtractor updated" : "Xtractor installed");
|
||||||
onInstalled?.();
|
onInstalled?.();
|
||||||
}
|
}
|
||||||
catch (error) {
|
catch (error) {
|
||||||
@@ -110,17 +76,14 @@ export function DependencySetupDialog({ onInstalled }: DependencySetupDialogProp
|
|||||||
setDownloading(false);
|
setDownloading(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleExit = () => {
|
const handleExit = () => {
|
||||||
if (!downloading) {
|
if (!downloading) {
|
||||||
void Quit();
|
void Quit();
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
if (checking && !open) {
|
if (checking && !open) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
return (<Dialog open={open} onOpenChange={(nextOpen) => {
|
return (<Dialog open={open} onOpenChange={(nextOpen) => {
|
||||||
if (nextOpen) {
|
if (nextOpen) {
|
||||||
setOpen(true);
|
setOpen(true);
|
||||||
@@ -131,11 +94,16 @@ export function DependencySetupDialog({ onInstalled }: DependencySetupDialogProp
|
|||||||
<div className="mb-2 flex h-12 w-12 items-center justify-center rounded-2xl border bg-muted/50">
|
<div className="mb-2 flex h-12 w-12 items-center justify-center rounded-2xl border bg-muted/50">
|
||||||
<Package className="h-6 w-6"/>
|
<Package className="h-6 w-6"/>
|
||||||
</div>
|
</div>
|
||||||
<DialogTitle>Download Xtractor</DialogTitle>
|
<DialogTitle>{updateRequired ? "Update Xtractor" : "Download Xtractor"}</DialogTitle>
|
||||||
<DialogDescription>Xtractor is required before you can use this app.</DialogDescription>
|
<DialogDescription>
|
||||||
|
{updateRequired ? "A newer Xtractor binary is available or the installed version could not be verified." : "Xtractor is required before you can use this app."}
|
||||||
|
</DialogDescription>
|
||||||
</DialogHeader>
|
</DialogHeader>
|
||||||
|
|
||||||
<div className="space-y-3">
|
<div className="space-y-3">
|
||||||
|
{updateRequired && releaseVersion && (<p className="text-sm text-amber-600 dark:text-amber-400">
|
||||||
|
Installed: {installedVersion || "unknown"} - Latest: {releaseVersion}
|
||||||
|
</p>)}
|
||||||
<p className="text-sm text-muted-foreground">{releaseVersion ? `Latest GitHub release: ${releaseVersion}` : releaseStatusMessage}</p>
|
<p className="text-sm text-muted-foreground">{releaseVersion ? `Latest GitHub release: ${releaseVersion}` : releaseStatusMessage}</p>
|
||||||
|
|
||||||
{errorMessage && (<div className="flex items-start gap-2 rounded-lg border border-destructive/40 bg-destructive/10 p-3 text-sm text-destructive">
|
{errorMessage && (<div className="flex items-start gap-2 rounded-lg border border-destructive/40 bg-destructive/10 p-3 text-sm text-destructive">
|
||||||
@@ -151,10 +119,10 @@ export function DependencySetupDialog({ onInstalled }: DependencySetupDialogProp
|
|||||||
<Button onClick={handleDownload} disabled={downloading}>
|
<Button onClick={handleDownload} disabled={downloading}>
|
||||||
{downloading ? (<>
|
{downloading ? (<>
|
||||||
<Spinner />
|
<Spinner />
|
||||||
Downloading Xtractor...
|
{updateRequired ? "Updating Xtractor..." : "Downloading Xtractor..."}
|
||||||
</>) : (<>
|
</>) : (<>
|
||||||
<Download className="h-4 w-4"/>
|
<Download className="h-4 w-4"/>
|
||||||
Download Xtractor
|
{updateRequired ? "Update Xtractor" : "Download Xtractor"}
|
||||||
</>)}
|
</>)}
|
||||||
</Button>
|
</Button>
|
||||||
</DialogFooter>
|
</DialogFooter>
|
||||||
|
|||||||
@@ -0,0 +1,66 @@
|
|||||||
|
import { useRef } from "react";
|
||||||
|
import { Label } from "@/components/ui/label";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { RefreshCw } from "lucide-react";
|
||||||
|
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
||||||
|
import { type TemplateToken } from "@/lib/settings";
|
||||||
|
export function FormatEditor({ title, value, defaultValue, tokens, suffix, placeholder, render, onChange }: {
|
||||||
|
title: string;
|
||||||
|
value: string;
|
||||||
|
defaultValue: string;
|
||||||
|
tokens: TemplateToken[];
|
||||||
|
suffix?: string;
|
||||||
|
placeholder?: string;
|
||||||
|
render: (template: string) => string;
|
||||||
|
onChange: (next: string) => void;
|
||||||
|
}) {
|
||||||
|
const inputRef = useRef<HTMLInputElement | null>(null);
|
||||||
|
const insertToken = (token: string) => {
|
||||||
|
const input = inputRef.current;
|
||||||
|
let next: string;
|
||||||
|
let caret: number;
|
||||||
|
if (input && input.selectionStart !== null && input.selectionEnd !== null) {
|
||||||
|
const start = input.selectionStart;
|
||||||
|
const end = input.selectionEnd;
|
||||||
|
next = value.slice(0, start) + token + value.slice(end);
|
||||||
|
caret = start + token.length;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
next = value + token;
|
||||||
|
caret = next.length;
|
||||||
|
}
|
||||||
|
onChange(next);
|
||||||
|
requestAnimationFrame(() => {
|
||||||
|
if (input) {
|
||||||
|
input.focus();
|
||||||
|
input.setSelectionRange(caret, caret);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
|
const preview = render(value) + (suffix ?? "");
|
||||||
|
return (<div className="space-y-3">
|
||||||
|
<Label className="text-sm font-semibold">{title}</Label>
|
||||||
|
<div className="relative">
|
||||||
|
<Input ref={inputRef} value={value} placeholder={placeholder} onChange={(e) => onChange(e.target.value)} className="font-mono text-sm pr-9"/>
|
||||||
|
<button type="button" onClick={() => onChange(defaultValue)} className="absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground transition-colors">
|
||||||
|
<RefreshCw className="h-4 w-4"/>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div className="rounded-lg border bg-muted/40 px-3 py-2">
|
||||||
|
<div className="text-[10px] font-semibold uppercase tracking-wide text-muted-foreground">Preview</div>
|
||||||
|
<div className="font-mono text-sm break-all">{preview || <span className="text-muted-foreground italic">empty</span>}</div>
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-wrap gap-2">
|
||||||
|
{tokens.map((token) => (<Tooltip key={token.key}>
|
||||||
|
<TooltipTrigger asChild>
|
||||||
|
<button type="button" onMouseDown={(e) => e.preventDefault()} onClick={() => insertToken(token.key)} className="rounded-md border bg-background px-2.5 py-1 text-xs font-mono text-muted-foreground transition-colors hover:text-foreground hover:border-primary/50">
|
||||||
|
{token.key}
|
||||||
|
</button>
|
||||||
|
</TooltipTrigger>
|
||||||
|
<TooltipContent side="top">
|
||||||
|
<span className="font-mono">{token.example || "—"}</span>
|
||||||
|
</TooltipContent>
|
||||||
|
</Tooltip>))}
|
||||||
|
</div>
|
||||||
|
</div>);
|
||||||
|
}
|
||||||
@@ -11,8 +11,8 @@ export function Header({ version, hasUpdate, releaseDate }: HeaderProps) {
|
|||||||
return (<div className="relative">
|
return (<div className="relative">
|
||||||
<div className="text-center space-y-2">
|
<div className="text-center space-y-2">
|
||||||
<div className="flex items-center justify-center gap-3">
|
<div className="flex items-center justify-center gap-3">
|
||||||
<img src="/icon.svg" alt="Twitter/X Media Batch Downloader" className="w-12 h-12 cursor-pointer" onClick={() => window.location.reload()}/>
|
<img src="/icon.svg" alt="Twitter/X Media Batch Downloader" className="w-12 h-12"/>
|
||||||
<h1 className="text-3xl font-bold cursor-pointer" onClick={() => window.location.reload()}>
|
<h1 className="text-3xl font-bold">
|
||||||
Twitter/X Media Batch Downloader
|
Twitter/X Media Batch Downloader
|
||||||
</h1>
|
</h1>
|
||||||
<div className="relative">
|
<div className="relative">
|
||||||
|
|||||||
@@ -5,27 +5,17 @@ import { Badge } from "@/components/ui/badge";
|
|||||||
import { Progress } from "@/components/ui/progress";
|
import { Progress } from "@/components/ui/progress";
|
||||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select";
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select";
|
||||||
import { Tooltip, TooltipContent, TooltipTrigger, } from "@/components/ui/tooltip";
|
import { Tooltip, TooltipContent, TooltipTrigger, } from "@/components/ui/tooltip";
|
||||||
import { Image, Video, Film, FileText, ExternalLink, Repeat2, Download, FolderOpen, LayoutGrid, Grid3X3, List, StopCircle, Users, UserPlus, MessageSquare, Calendar, ArrowUp, ChevronLeft, ChevronRight, Eye, Heart, Bookmark, BadgeCheck, Maximize2, CheckCircle, XCircle, FileCheck, } from "lucide-react";
|
import { Image, Video, Film, FileText, ExternalLink, Repeat2, Download, FolderOpen, LayoutGrid, Grid3X3, List, StopCircle, MapPin, Link2, Lock, Calendar, ArrowUp, ChevronLeft, ChevronRight, Eye, Heart, Bookmark, BadgeCheck, Maximize2, CheckCircle, XCircle, FileCheck, } from "lucide-react";
|
||||||
import { Spinner } from "@/components/ui/spinner";
|
import { Spinner } from "@/components/ui/spinner";
|
||||||
import type { TimelineEntry, AccountInfo } from "@/types/api";
|
import type { TimelineEntry, AccountInfo } from "@/types/api";
|
||||||
import { logger } from "@/lib/logger";
|
import { logger } from "@/lib/logger";
|
||||||
import { toastWithSound as toast } from "@/lib/toast-with-sound";
|
import { toastWithSound as toast } from "@/lib/toast-with-sound";
|
||||||
import { getSettings } from "@/lib/settings";
|
import { getSettings, renderFolderTemplate } from "@/lib/settings";
|
||||||
import { getCachedDependencyStatus, getCachedMediaFolderStatus, setCachedDependencyStatus, setCachedMediaFolderStatus } from "@/lib/runtime-cache";
|
import { beginDownload, finishDownload, setDownloadItemStatus, useDownloadState } from "@/lib/download-state";
|
||||||
|
import { getCachedMediaFolderStatus, setCachedMediaFolderStatus } from "@/lib/runtime-cache";
|
||||||
import { openExternal } from "@/lib/utils";
|
import { openExternal } from "@/lib/utils";
|
||||||
import { DownloadMediaWithMetadata, OpenFolder, IsFFmpegInstalled, ConvertGIFs, StopDownload, CheckFolderExists, CheckGifsFolderHasMP4 } from "../../wailsjs/go/main/App";
|
import { DownloadMediaWithMetadata, DownloadProfileImage, OpenFolder, StopDownload, CheckFolderExists } from "../../wailsjs/go/main/App";
|
||||||
import { EventsOn, EventsOff } from "../../wailsjs/runtime/runtime";
|
|
||||||
import { main } from "../../wailsjs/go/models";
|
import { main } from "../../wailsjs/go/models";
|
||||||
interface DownloadProgress {
|
|
||||||
current: number;
|
|
||||||
total: number;
|
|
||||||
percent: number;
|
|
||||||
}
|
|
||||||
interface DownloadItemStatus {
|
|
||||||
tweet_id: number;
|
|
||||||
index: number;
|
|
||||||
status: "success" | "failed" | "skipped";
|
|
||||||
}
|
|
||||||
interface MediaListProps {
|
interface MediaListProps {
|
||||||
accountInfo: AccountInfo;
|
accountInfo: AccountInfo;
|
||||||
timeline: TimelineEntry[];
|
timeline: TimelineEntry[];
|
||||||
@@ -34,11 +24,9 @@ interface MediaListProps {
|
|||||||
newMediaCount?: number | null;
|
newMediaCount?: number | null;
|
||||||
}
|
}
|
||||||
const MEDIA_LIST_PAGE_SIZE = 30;
|
const MEDIA_LIST_PAGE_SIZE = 30;
|
||||||
|
|
||||||
function getContentScrollElement(): HTMLElement | null {
|
function getContentScrollElement(): HTMLElement | null {
|
||||||
return document.getElementById("app-content-scroll");
|
return document.getElementById("app-content-scroll");
|
||||||
}
|
}
|
||||||
|
|
||||||
function getThumbnailUrl(url: string): string {
|
function getThumbnailUrl(url: string): string {
|
||||||
if (url.includes("video.twimg.com/tweet_video/")) {
|
if (url.includes("video.twimg.com/tweet_video/")) {
|
||||||
const match = url.match(/tweet_video\/([^/]+)\.mp4/);
|
const match = url.match(/tweet_video\/([^/]+)\.mp4/);
|
||||||
@@ -78,6 +66,12 @@ function getPreviewUrl(url: string): string {
|
|||||||
}
|
}
|
||||||
return url;
|
return url;
|
||||||
}
|
}
|
||||||
|
function getEntryThumbnail(item: TimelineEntry): string {
|
||||||
|
if (item.thumbnail) {
|
||||||
|
return item.thumbnail;
|
||||||
|
}
|
||||||
|
return getThumbnailUrl(item.url);
|
||||||
|
}
|
||||||
function getMediaIcon(type: string) {
|
function getMediaIcon(type: string) {
|
||||||
switch (type) {
|
switch (type) {
|
||||||
case "photo":
|
case "photo":
|
||||||
@@ -95,10 +89,14 @@ function getMediaIcon(type: string) {
|
|||||||
}
|
}
|
||||||
function formatDate(dateStr: string): string {
|
function formatDate(dateStr: string): string {
|
||||||
try {
|
try {
|
||||||
if (dateStr.includes("T")) {
|
const d = new Date(dateStr);
|
||||||
const [datePart, timePart] = dateStr.split("T");
|
if (!Number.isNaN(d.getTime())) {
|
||||||
const timeClean = timePart.split("+")[0].split("Z")[0];
|
const year = d.getFullYear();
|
||||||
return `${datePart} • ${timeClean}`;
|
const month = String(d.getMonth() + 1).padStart(2, "0");
|
||||||
|
const day = String(d.getDate()).padStart(2, "0");
|
||||||
|
const hours = String(d.getHours()).padStart(2, "0");
|
||||||
|
const minutes = String(d.getMinutes()).padStart(2, "0");
|
||||||
|
return `${year}-${month}-${day} ${hours}:${minutes}`;
|
||||||
}
|
}
|
||||||
return dateStr;
|
return dateStr;
|
||||||
}
|
}
|
||||||
@@ -168,7 +166,6 @@ function formatJoinDate(dateStr: string): string {
|
|||||||
return dateStr;
|
return dateStr;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function getAccountFolderName(accountInfo: AccountInfo): string {
|
function getAccountFolderName(accountInfo: AccountInfo): string {
|
||||||
if (accountInfo.nick === "My Bookmarks" || accountInfo.name === "bookmarks") {
|
if (accountInfo.nick === "My Bookmarks" || accountInfo.name === "bookmarks") {
|
||||||
return "My Bookmarks";
|
return "My Bookmarks";
|
||||||
@@ -176,32 +173,53 @@ function getAccountFolderName(accountInfo: AccountInfo): string {
|
|||||||
if (accountInfo.nick === "My Likes" || accountInfo.name === "likes") {
|
if (accountInfo.nick === "My Likes" || accountInfo.name === "likes") {
|
||||||
return "My Likes";
|
return "My Likes";
|
||||||
}
|
}
|
||||||
return accountInfo.name;
|
const template = getSettings().folderTemplate;
|
||||||
|
const pad = (n: number) => String(n).padStart(2, "0");
|
||||||
|
const now = new Date();
|
||||||
|
const rendered = renderFolderTemplate(template, {
|
||||||
|
username: accountInfo.name,
|
||||||
|
accountName: accountInfo.nick,
|
||||||
|
date: `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}`,
|
||||||
|
});
|
||||||
|
return rendered || accountInfo.name;
|
||||||
|
}
|
||||||
|
function pickVariantUrl(variants: {
|
||||||
|
name: string;
|
||||||
|
url: string;
|
||||||
|
}[] | undefined, size: string, fallback: string): string {
|
||||||
|
if (variants && variants.length > 0) {
|
||||||
|
const match = variants.find((v) => v.name === size);
|
||||||
|
if (match?.url)
|
||||||
|
return match.url;
|
||||||
|
}
|
||||||
|
return fallback;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType = "all", newMediaCount = null, }: MediaListProps) {
|
export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType = "all", newMediaCount = null, }: MediaListProps) {
|
||||||
const settings = getSettings();
|
const settings = getSettings();
|
||||||
const folderName = getAccountFolderName(accountInfo);
|
const folderName = getAccountFolderName(accountInfo);
|
||||||
|
const downloadState = useDownloadState();
|
||||||
|
const anyDownloadActive = downloadState.active;
|
||||||
|
const isDownloading = downloadState.active && downloadState.scope === "media";
|
||||||
|
const downloadProgress = isDownloading ? downloadState.progress : null;
|
||||||
|
const downloadingItem = isDownloading ? downloadState.currentItemKey : null;
|
||||||
|
const itemStatusByKey = downloadState.itemStatusByKey;
|
||||||
const cachedMediaFolderStatus = settings.downloadPath
|
const cachedMediaFolderStatus = settings.downloadPath
|
||||||
? getCachedMediaFolderStatus(settings.downloadPath, folderName)
|
? getCachedMediaFolderStatus(settings.downloadPath, folderName)
|
||||||
: null;
|
: null;
|
||||||
const [selectedItems, setSelectedItems] = useState<Set<number>>(new Set());
|
const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set());
|
||||||
const [sortBy, setSortBy] = useState<string>("date-desc");
|
const [sortBy, setSortBy] = useState<string>("date-desc");
|
||||||
const [filterType, setFilterType] = useState<string>("all");
|
const [filterType, setFilterType] = useState<string>("all");
|
||||||
const [viewMode, setViewMode] = useState<"large" | "small" | "list">("list");
|
const [viewMode, setViewMode] = useState<"large" | "small" | "list">(() => {
|
||||||
const [isDownloading, setIsDownloading] = useState(false);
|
const stored = localStorage.getItem("resultViewMode");
|
||||||
const [downloadProgress, setDownloadProgress] = useState<DownloadProgress | null>(null);
|
return stored === "large" || stored === "small" || stored === "list" ? stored : "list";
|
||||||
|
});
|
||||||
|
useEffect(() => {
|
||||||
|
localStorage.setItem("resultViewMode", viewMode);
|
||||||
|
}, [viewMode]);
|
||||||
const [hasDownloaded, setHasDownloaded] = useState(false);
|
const [hasDownloaded, setHasDownloaded] = useState(false);
|
||||||
const [isConverting, setIsConverting] = useState(false);
|
|
||||||
const [ffmpegInstalled, setFfmpegInstalled] = useState(() => getCachedDependencyStatus("ffmpeg").installed ?? false);
|
|
||||||
const [showScrollTop, setShowScrollTop] = useState(false);
|
const [showScrollTop, setShowScrollTop] = useState(false);
|
||||||
const [folderExists, setFolderExists] = useState(cachedMediaFolderStatus?.folderExists ?? false);
|
const [folderExists, setFolderExists] = useState(cachedMediaFolderStatus?.folderExists ?? false);
|
||||||
const [gifsFolderHasMP4, setGifsFolderHasMP4] = useState(cachedMediaFolderStatus?.gifsFolderHasMP4 ?? false);
|
|
||||||
const [previewIndex, setPreviewIndex] = useState<number | null>(null);
|
const [previewIndex, setPreviewIndex] = useState<number | null>(null);
|
||||||
const [downloadedItems, setDownloadedItems] = useState<Set<string>>(new Set());
|
|
||||||
const [failedItems, setFailedItems] = useState<Set<string>>(new Set());
|
|
||||||
const [skippedItems, setSkippedItems] = useState<Set<string>>(new Set());
|
|
||||||
const [downloadingItem, setDownloadingItem] = useState<string | null>(null);
|
|
||||||
const [visibleCount, setVisibleCount] = useState<number>(MEDIA_LIST_PAGE_SIZE);
|
const [visibleCount, setVisibleCount] = useState<number>(MEDIA_LIST_PAGE_SIZE);
|
||||||
const loadMoreRef = useRef<HTMLDivElement>(null);
|
const loadMoreRef = useRef<HTMLDivElement>(null);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -252,24 +270,19 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
|
|||||||
setVisibleCount(MEDIA_LIST_PAGE_SIZE);
|
setVisibleCount(MEDIA_LIST_PAGE_SIZE);
|
||||||
}, [filteredTimeline.length]);
|
}, [filteredTimeline.length]);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const checkFoldersAndFFmpeg = async () => {
|
const checkFolders = async () => {
|
||||||
const settings = getSettings();
|
const settings = getSettings();
|
||||||
const basePath = settings.downloadPath;
|
const basePath = settings.downloadPath;
|
||||||
const installed = await IsFFmpegInstalled();
|
|
||||||
setCachedDependencyStatus("ffmpeg", { installed });
|
|
||||||
setFfmpegInstalled(installed);
|
|
||||||
if (!basePath || !accountInfo.name)
|
if (!basePath || !accountInfo.name)
|
||||||
return;
|
return;
|
||||||
const exists = await CheckFolderExists(basePath, folderName);
|
const exists = await CheckFolderExists(basePath, folderName);
|
||||||
const hasMP4 = exists ? await CheckGifsFolderHasMP4(basePath, folderName) : false;
|
|
||||||
setCachedMediaFolderStatus(basePath, folderName, {
|
setCachedMediaFolderStatus(basePath, folderName, {
|
||||||
folderExists: exists,
|
folderExists: exists,
|
||||||
gifsFolderHasMP4: hasMP4,
|
gifsFolderHasMP4: false,
|
||||||
});
|
});
|
||||||
setFolderExists(exists);
|
setFolderExists(exists);
|
||||||
setGifsFolderHasMP4(hasMP4);
|
|
||||||
};
|
};
|
||||||
checkFoldersAndFFmpeg();
|
checkFolders();
|
||||||
}, [accountInfo.name, accountInfo.nick, folderName, hasDownloaded]);
|
}, [accountInfo.name, accountInfo.nick, folderName, hasDownloaded]);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const sentinel = loadMoreRef.current;
|
const sentinel = loadMoreRef.current;
|
||||||
@@ -301,70 +314,15 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
|
|||||||
setPreviewIndex(null);
|
setPreviewIndex(null);
|
||||||
};
|
};
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (previewIndex !== null) {
|
if (previewIndex === null) {
|
||||||
document.body.style.overflow = "hidden";
|
return;
|
||||||
}
|
|
||||||
else {
|
|
||||||
document.body.style.overflow = "";
|
|
||||||
}
|
}
|
||||||
|
const previousOverflow = document.body.style.overflow;
|
||||||
|
document.body.style.overflow = "hidden";
|
||||||
return () => {
|
return () => {
|
||||||
document.body.style.overflow = "";
|
document.body.style.overflow = previousOverflow;
|
||||||
};
|
};
|
||||||
}, [previewIndex]);
|
}, [previewIndex]);
|
||||||
useEffect(() => {
|
|
||||||
const unsubscribe = EventsOn("download-progress", (progress: DownloadProgress) => {
|
|
||||||
setDownloadProgress(progress);
|
|
||||||
});
|
|
||||||
return () => {
|
|
||||||
EventsOff("download-progress");
|
|
||||||
unsubscribe();
|
|
||||||
};
|
|
||||||
}, []);
|
|
||||||
const currentDownloadingItemKeyRef = useRef<string | null>(null);
|
|
||||||
const bulkDownloadKeyMapRef = useRef<Map<number, string>>(new Map());
|
|
||||||
useEffect(() => {
|
|
||||||
const unsubscribe = EventsOn("download-item-status", (status: DownloadItemStatus) => {
|
|
||||||
const currentKey = currentDownloadingItemKeyRef.current;
|
|
||||||
const keyMap = bulkDownloadKeyMapRef.current;
|
|
||||||
let itemKey: string;
|
|
||||||
if (currentKey) {
|
|
||||||
itemKey = currentKey;
|
|
||||||
}
|
|
||||||
else if (keyMap.size > 0) {
|
|
||||||
itemKey = keyMap.get(status.index) ?? `${String(status.tweet_id)}-${status.index}`;
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
itemKey = `${String(status.tweet_id)}-${status.index}`;
|
|
||||||
}
|
|
||||||
if (status.status === "success") {
|
|
||||||
setDownloadedItems((prev) => new Set(prev).add(itemKey));
|
|
||||||
if (currentKey) {
|
|
||||||
toast.success("Downloaded");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else if (status.status === "failed") {
|
|
||||||
setFailedItems((prev) => new Set(prev).add(itemKey));
|
|
||||||
if (currentKey) {
|
|
||||||
toast.error("Download failed");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else if (status.status === "skipped") {
|
|
||||||
setDownloadedItems((prev) => {
|
|
||||||
const newSet = new Set(prev);
|
|
||||||
newSet.delete(itemKey);
|
|
||||||
return newSet;
|
|
||||||
});
|
|
||||||
setSkippedItems((prev) => new Set(prev).add(itemKey));
|
|
||||||
if (currentKey) {
|
|
||||||
toast.info("Already exists");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
return () => {
|
|
||||||
EventsOff("download-item-status");
|
|
||||||
unsubscribe();
|
|
||||||
};
|
|
||||||
}, []);
|
|
||||||
const goToPrevious = () => {
|
const goToPrevious = () => {
|
||||||
if (previewIndex !== null && previewIndex > 0) {
|
if (previewIndex !== null && previewIndex > 0) {
|
||||||
setPreviewIndex(previewIndex - 1);
|
setPreviewIndex(previewIndex - 1);
|
||||||
@@ -408,16 +366,16 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
|
|||||||
setSelectedItems(new Set());
|
setSelectedItems(new Set());
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
setSelectedItems(new Set(filteredTimeline.map((_, i) => i)));
|
setSelectedItems(new Set(filteredTimeline.map((item) => getItemKey(item))));
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
const toggleItem = (index: number) => {
|
const toggleItem = (key: string) => {
|
||||||
const newSelected = new Set(selectedItems);
|
const newSelected = new Set(selectedItems);
|
||||||
if (newSelected.has(index)) {
|
if (newSelected.has(key)) {
|
||||||
newSelected.delete(index);
|
newSelected.delete(key);
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
newSelected.add(index);
|
newSelected.add(key);
|
||||||
}
|
}
|
||||||
setSelectedItems(newSelected);
|
setSelectedItems(newSelected);
|
||||||
};
|
};
|
||||||
@@ -432,37 +390,105 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
|
|||||||
}
|
}
|
||||||
return settings.downloadPath;
|
return settings.downloadPath;
|
||||||
};
|
};
|
||||||
|
const createMediaItemRequest = (item: TimelineEntry) => new main.MediaItemRequest({
|
||||||
|
url: item.url,
|
||||||
|
date: item.date,
|
||||||
|
tweet_id: item.tweet_id,
|
||||||
|
type: item.type,
|
||||||
|
content: item.content || "",
|
||||||
|
original_filename: item.original_filename || "",
|
||||||
|
author_username: item.author_username || "",
|
||||||
|
account_name: item.author_name || accountInfo.nick || accountInfo.name,
|
||||||
|
});
|
||||||
|
const getItemStatusFlags = (itemKey: string) => {
|
||||||
|
const status = itemStatusByKey[itemKey];
|
||||||
|
return {
|
||||||
|
isItemDownloaded: status === "success",
|
||||||
|
isItemFailed: status === "failed",
|
||||||
|
isItemSkipped: status === "skipped",
|
||||||
|
isItemDownloading: downloadingItem === itemKey,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
const handleDownloadItem = async (item: TimelineEntry, itemKey: string) => {
|
||||||
|
beginDownload({ current: 0, total: 1, percent: 0 }, { scope: "media", currentItemKey: itemKey, itemKeyByIndex: { 0: itemKey } });
|
||||||
|
try {
|
||||||
|
const settings = getSettings();
|
||||||
|
const request = new main.DownloadMediaWithMetadataRequest({
|
||||||
|
items: [createMediaItemRequest(item)],
|
||||||
|
output_dir: getOutputDir(),
|
||||||
|
username: accountInfo.name,
|
||||||
|
concurrent_downloads: settings.concurrentDownloads || 10,
|
||||||
|
skip_existing: settings.skipExistingFiles,
|
||||||
|
delete_incomplete_files: settings.deleteIncompleteFiles,
|
||||||
|
retry_attempts: settings.retryAttempts,
|
||||||
|
proxy: settings.proxy || "",
|
||||||
|
filename_template: settings.filenameTemplate || "",
|
||||||
|
folder_template: settings.folderTemplate || "",
|
||||||
|
auto_convert_gifs: settings.autoConvertGifs,
|
||||||
|
gif_quality: settings.gifQuality || "fast",
|
||||||
|
gif_resolution: settings.gifResolution || "original",
|
||||||
|
});
|
||||||
|
const response = await DownloadMediaWithMetadata(request);
|
||||||
|
if (response.cancelled) {
|
||||||
|
toast.info(response.message || "Download stopped");
|
||||||
|
}
|
||||||
|
else if (response.success) {
|
||||||
|
if (response.skipped > 0) {
|
||||||
|
setDownloadItemStatus(itemKey, "skipped");
|
||||||
|
toast.info("Already exists");
|
||||||
|
}
|
||||||
|
else if (response.downloaded > 0) {
|
||||||
|
setDownloadItemStatus(itemKey, "success");
|
||||||
|
toast.success("Downloaded");
|
||||||
|
}
|
||||||
|
setHasDownloaded(true);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
setDownloadItemStatus(itemKey, "failed");
|
||||||
|
toast.error(response.message || "Download failed");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (error) {
|
||||||
|
setDownloadItemStatus(itemKey, "failed");
|
||||||
|
const errorMsg = error instanceof Error ? error.message : String(error);
|
||||||
|
toast.error(`Download failed: ${errorMsg}`);
|
||||||
|
}
|
||||||
|
finally {
|
||||||
|
finishDownload();
|
||||||
|
}
|
||||||
|
};
|
||||||
const handleDownload = async () => {
|
const handleDownload = async () => {
|
||||||
const itemsWithIndices = selectedItems.size > 0
|
const itemsWithIndices = selectedItems.size > 0
|
||||||
? Array.from(selectedItems).map((i) => ({ item: filteredTimeline[i], originalIndex: i }))
|
? filteredTimeline
|
||||||
|
.map((item, i) => ({ item, originalIndex: i }))
|
||||||
|
.filter((entry) => selectedItems.has(getItemKey(entry.item)))
|
||||||
: filteredTimeline.map((item, i) => ({ item, originalIndex: i }));
|
: filteredTimeline.map((item, i) => ({ item, originalIndex: i }));
|
||||||
if (itemsWithIndices.length === 0) {
|
if (itemsWithIndices.length === 0) {
|
||||||
toast.error("No media to download");
|
toast.error("No media to download");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const keyMap = new Map<number, string>();
|
const keyMap: Record<number, string> = {};
|
||||||
itemsWithIndices.forEach((entry, backendIndex) => {
|
itemsWithIndices.forEach((entry, backendIndex) => {
|
||||||
keyMap.set(backendIndex, getItemKey(entry.item));
|
keyMap[backendIndex] = getItemKey(entry.item);
|
||||||
});
|
});
|
||||||
bulkDownloadKeyMapRef.current = keyMap;
|
beginDownload({ current: 0, total: itemsWithIndices.length, percent: 0 }, { scope: "media", itemKeyByIndex: keyMap });
|
||||||
setIsDownloading(true);
|
|
||||||
setDownloadProgress({ current: 0, total: itemsWithIndices.length, percent: 0 });
|
|
||||||
logger.info(`Starting download of ${itemsWithIndices.length} files...`);
|
logger.info(`Starting download of ${itemsWithIndices.length} files...`);
|
||||||
try {
|
try {
|
||||||
const settings = getSettings();
|
const settings = getSettings();
|
||||||
const request = new main.DownloadMediaWithMetadataRequest({
|
const request = new main.DownloadMediaWithMetadataRequest({
|
||||||
items: itemsWithIndices.map(({ item }) => new main.MediaItemRequest({
|
items: itemsWithIndices.map(({ item }) => createMediaItemRequest(item)),
|
||||||
url: item.url,
|
|
||||||
date: item.date,
|
|
||||||
tweet_id: item.tweet_id,
|
|
||||||
type: item.type,
|
|
||||||
content: item.content || "",
|
|
||||||
original_filename: item.original_filename || "",
|
|
||||||
author_username: item.author_username || "",
|
|
||||||
})),
|
|
||||||
output_dir: getOutputDir(),
|
output_dir: getOutputDir(),
|
||||||
username: accountInfo.name,
|
username: accountInfo.name,
|
||||||
|
concurrent_downloads: settings.concurrentDownloads || 10,
|
||||||
|
skip_existing: settings.skipExistingFiles,
|
||||||
|
delete_incomplete_files: settings.deleteIncompleteFiles,
|
||||||
|
retry_attempts: settings.retryAttempts,
|
||||||
proxy: settings.proxy || "",
|
proxy: settings.proxy || "",
|
||||||
|
filename_template: settings.filenameTemplate || "",
|
||||||
|
folder_template: settings.folderTemplate || "",
|
||||||
|
auto_convert_gifs: settings.autoConvertGifs,
|
||||||
|
gif_quality: settings.gifQuality || "fast",
|
||||||
|
gif_resolution: settings.gifResolution || "original",
|
||||||
});
|
});
|
||||||
const response = await DownloadMediaWithMetadata(request);
|
const response = await DownloadMediaWithMetadata(request);
|
||||||
if (response.cancelled) {
|
if (response.cancelled) {
|
||||||
@@ -493,17 +519,12 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
|
|||||||
toast.success(message);
|
toast.success(message);
|
||||||
}
|
}
|
||||||
setHasDownloaded(true);
|
setHasDownloaded(true);
|
||||||
const installed = await IsFFmpegInstalled();
|
|
||||||
setCachedDependencyStatus("ffmpeg", { installed });
|
|
||||||
setFfmpegInstalled(installed);
|
|
||||||
if (settings.downloadPath) {
|
if (settings.downloadPath) {
|
||||||
const hasMP4 = await CheckGifsFolderHasMP4(settings.downloadPath, folderName);
|
|
||||||
setCachedMediaFolderStatus(settings.downloadPath, folderName, {
|
setCachedMediaFolderStatus(settings.downloadPath, folderName, {
|
||||||
folderExists: true,
|
folderExists: true,
|
||||||
gifsFolderHasMP4: hasMP4,
|
gifsFolderHasMP4: false,
|
||||||
});
|
});
|
||||||
setFolderExists(true);
|
setFolderExists(true);
|
||||||
setGifsFolderHasMP4(hasMP4);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
@@ -517,15 +538,14 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
|
|||||||
toast.error("Download failed");
|
toast.error("Download failed");
|
||||||
}
|
}
|
||||||
finally {
|
finally {
|
||||||
setIsDownloading(false);
|
finishDownload();
|
||||||
setDownloadProgress(null);
|
|
||||||
bulkDownloadKeyMapRef.current = new Map();
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
const handleStopDownload = async () => {
|
const handleStopDownload = async () => {
|
||||||
try {
|
try {
|
||||||
const stopped = await StopDownload();
|
const stopped = await StopDownload();
|
||||||
if (stopped) {
|
if (stopped) {
|
||||||
|
finishDownload();
|
||||||
logger.info("Download stopped by user");
|
logger.info("Download stopped by user");
|
||||||
toast.info("Stopped");
|
toast.info("Stopped");
|
||||||
}
|
}
|
||||||
@@ -534,6 +554,30 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
|
|||||||
console.error("Failed to stop download:", error);
|
console.error("Failed to stop download:", error);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
const handleDownloadProfileImage = async (kind: "avatar" | "banner") => {
|
||||||
|
const settings = getSettings();
|
||||||
|
const url = kind === "avatar"
|
||||||
|
? pickVariantUrl(accountInfo.avatar_variants, settings.avatarSize, accountInfo.profile_image)
|
||||||
|
: pickVariantUrl(accountInfo.banner_variants, settings.bannerSize, accountInfo.banner || "");
|
||||||
|
if (!url) {
|
||||||
|
toast.error(`No ${kind} available`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await DownloadProfileImage(new main.DownloadProfileImageRequest({
|
||||||
|
url,
|
||||||
|
output_dir: settings.downloadPath,
|
||||||
|
username: folderName,
|
||||||
|
kind,
|
||||||
|
proxy: settings.proxy || "",
|
||||||
|
}));
|
||||||
|
toast.success(`${kind === "avatar" ? "Avatar" : "Banner"} downloaded`);
|
||||||
|
}
|
||||||
|
catch (error) {
|
||||||
|
logger.error(`Failed to download ${kind}: ${error}`);
|
||||||
|
toast.error(`Failed to download ${kind}`);
|
||||||
|
}
|
||||||
|
};
|
||||||
const handleOpenFolder = async () => {
|
const handleOpenFolder = async () => {
|
||||||
const settings = getSettings();
|
const settings = getSettings();
|
||||||
const isBookmarks = accountInfo.nick === "My Bookmarks";
|
const isBookmarks = accountInfo.nick === "My Bookmarks";
|
||||||
@@ -548,8 +592,8 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
|
|||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
folderPath = settings.downloadPath
|
folderPath = settings.downloadPath
|
||||||
? `${settings.downloadPath}/${accountInfo.name}`
|
? `${settings.downloadPath}/${folderName}`
|
||||||
: accountInfo.name;
|
: folderName;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
await OpenFolder(folderPath);
|
await OpenFolder(folderPath);
|
||||||
@@ -566,52 +610,6 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
|
|||||||
const handleOpenTweet = (tweetId: string) => {
|
const handleOpenTweet = (tweetId: string) => {
|
||||||
openExternal(`https://x.com/${accountInfo.name}/status/${tweetId}`);
|
openExternal(`https://x.com/${accountInfo.name}/status/${tweetId}`);
|
||||||
};
|
};
|
||||||
const handleConvertGifs = async () => {
|
|
||||||
const settings = getSettings();
|
|
||||||
const isBookmarks = accountInfo.nick === "My Bookmarks";
|
|
||||||
const isLikes = accountInfo.nick === "My Likes";
|
|
||||||
let folderPath: string;
|
|
||||||
if (isBookmarks || isLikes) {
|
|
||||||
const separator = settings.downloadPath.includes("/") ? "/" : "\\";
|
|
||||||
const folderName = isBookmarks ? "My Bookmarks" : "My Likes";
|
|
||||||
folderPath = `${settings.downloadPath}${separator}${folderName}`;
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
folderPath = `${settings.downloadPath}/${accountInfo.name}`;
|
|
||||||
}
|
|
||||||
setIsConverting(true);
|
|
||||||
logger.info("Converting GIFs...");
|
|
||||||
try {
|
|
||||||
const response = await ConvertGIFs({
|
|
||||||
folder_path: folderPath,
|
|
||||||
quality: settings.gifQuality || "fast",
|
|
||||||
resolution: settings.gifResolution || "high",
|
|
||||||
delete_original: false,
|
|
||||||
});
|
|
||||||
if (response.success) {
|
|
||||||
logger.success(`Converted ${response.converted} GIFs`);
|
|
||||||
toast.success(`${response.converted} GIFs converted`);
|
|
||||||
const hasMP4 = await CheckGifsFolderHasMP4(settings.downloadPath, folderName);
|
|
||||||
setCachedMediaFolderStatus(settings.downloadPath, folderName, {
|
|
||||||
folderExists: true,
|
|
||||||
gifsFolderHasMP4: hasMP4,
|
|
||||||
});
|
|
||||||
setGifsFolderHasMP4(hasMP4);
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
logger.error(response.message);
|
|
||||||
toast.error("Convert failed");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
catch (error) {
|
|
||||||
const errorMsg = error instanceof Error ? error.message : String(error);
|
|
||||||
logger.error(`Convert failed: ${errorMsg}`);
|
|
||||||
toast.error("Convert failed");
|
|
||||||
}
|
|
||||||
finally {
|
|
||||||
setIsConverting(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
return (<div className="space-y-4">
|
return (<div className="space-y-4">
|
||||||
|
|
||||||
{accountInfo.name === "bookmarks" || accountInfo.name === "likes" ? (<div className="flex items-center gap-4 p-4 bg-muted/50 rounded-lg">
|
{accountInfo.name === "bookmarks" || accountInfo.name === "likes" ? (<div className="flex items-center gap-4 p-4 bg-muted/50 rounded-lg">
|
||||||
@@ -630,40 +628,69 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
|
|||||||
</div>
|
</div>
|
||||||
<div className="text-sm text-muted-foreground">items found</div>
|
<div className="text-sm text-muted-foreground">items found</div>
|
||||||
</div>
|
</div>
|
||||||
</div>) : (<div className="flex items-center gap-4 p-4 bg-muted/50 rounded-lg">
|
</div>) : (<div className="rounded-lg overflow-hidden bg-muted/50 border">
|
||||||
<img src={accountInfo.profile_image} alt={accountInfo.nick} className="w-16 h-16 rounded-full"/>
|
{accountInfo.banner && (<div className="group/banner relative h-24 w-full bg-cover bg-center" style={{ backgroundImage: `url("${accountInfo.banner}")` }}>
|
||||||
<div className="flex-1">
|
<button type="button" aria-label="Download banner" onClick={() => void handleDownloadProfileImage("banner")} className="absolute top-2 right-2 flex h-9 w-9 items-center justify-center rounded-full bg-black/60 text-white opacity-0 transition-all hover:scale-105 hover:bg-primary hover:text-primary-foreground group-hover/banner:opacity-100">
|
||||||
<div className="flex items-center gap-2">
|
<Download className="h-4 w-4"/>
|
||||||
<h2 className="text-xl">{accountInfo.nick}</h2>
|
</button>
|
||||||
<span className="text-muted-foreground">@{accountInfo.name}</span>
|
</div>)}
|
||||||
|
<div className="p-4">
|
||||||
|
<div className="flex items-end justify-between gap-4">
|
||||||
|
<div className="flex items-end gap-3 min-w-0">
|
||||||
|
<div className={`group/avatar relative shrink-0 ${accountInfo.banner ? "-mt-14" : ""}`}>
|
||||||
|
<img src={accountInfo.profile_image} alt={accountInfo.nick} className={`w-20 h-20 rounded-full object-cover bg-muted ${accountInfo.banner ? "ring-4 ring-background" : ""}`}/>
|
||||||
|
<button type="button" aria-label="Download avatar" onClick={() => void handleDownloadProfileImage("avatar")} className="absolute inset-0 flex items-center justify-center rounded-full bg-black/50 text-white opacity-0 transition-opacity hover:bg-black/62 group-hover/avatar:opacity-100">
|
||||||
|
<Download className="h-5 w-5"/>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div className="min-w-0">
|
||||||
|
<div className="flex items-center gap-1.5">
|
||||||
|
<h2 className="text-xl font-bold truncate">{accountInfo.nick}</h2>
|
||||||
|
{(accountInfo.verified || accountInfo.blue_verified) && (<BadgeCheck className="h-4 w-4 text-blue-500 shrink-0"/>)}
|
||||||
|
{accountInfo.protected && (<Lock className="h-3.5 w-3.5 text-muted-foreground shrink-0"/>)}
|
||||||
|
</div>
|
||||||
|
<div className="text-sm text-muted-foreground truncate">@{accountInfo.name}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="text-right shrink-0">
|
||||||
|
<div className="flex items-center justify-end gap-2">
|
||||||
|
{newMediaCount !== null && newMediaCount > 0 && (<div className="text-lg font-semibold text-green-600 dark:text-green-400 animate-in fade-in slide-in-from-left-2 duration-300">
|
||||||
|
{formatNumberWithComma(newMediaCount)}+
|
||||||
|
</div>)}
|
||||||
|
<div className="text-2xl font-bold text-primary">{formatNumberWithComma(totalUrls)}</div>
|
||||||
|
</div>
|
||||||
|
<div className="text-sm text-muted-foreground">items found</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-center gap-4 text-sm text-muted-foreground mt-1">
|
|
||||||
<span className="flex items-center gap-1">
|
{accountInfo.bio && (<p className="text-sm mt-3 whitespace-pre-wrap wrap-break-word">{accountInfo.bio}</p>)}
|
||||||
<Users className="h-3.5 w-3.5"/>
|
|
||||||
{formatNumber(accountInfo.followers_count)} followers
|
<div className="flex flex-wrap items-center gap-x-4 gap-y-1 text-sm text-muted-foreground mt-3">
|
||||||
</span>
|
{accountInfo.location && (<span className="flex items-center gap-1">
|
||||||
<span className="flex items-center gap-1">
|
<MapPin className="h-3.5 w-3.5"/>
|
||||||
<UserPlus className="h-3.5 w-3.5"/>
|
{accountInfo.location}
|
||||||
{formatNumber(accountInfo.friends_count)} following
|
</span>)}
|
||||||
</span>
|
{accountInfo.url && (<button type="button" onClick={() => openExternal(accountInfo.url!)} className="flex items-center gap-1 hover:underline">
|
||||||
<span className="flex items-center gap-1">
|
<Link2 className="h-3.5 w-3.5"/>
|
||||||
<MessageSquare className="h-3.5 w-3.5"/>
|
{accountInfo.url.replace(/^https?:\/\//, "").replace(/\/+$/, "")}
|
||||||
{formatNumber(accountInfo.statuses_count)} posts
|
</button>)}
|
||||||
</span>
|
|
||||||
{accountInfo.date && (<span className="flex items-center gap-1">
|
{accountInfo.date && (<span className="flex items-center gap-1">
|
||||||
<Calendar className="h-3.5 w-3.5"/>
|
<Calendar className="h-3.5 w-3.5"/>
|
||||||
Joined {formatJoinDate(accountInfo.date)}
|
Joined {formatJoinDate(accountInfo.date)}
|
||||||
</span>)}
|
</span>)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
|
||||||
<div className="text-right">
|
<div className="flex flex-wrap items-center gap-x-2 gap-y-1 text-sm mt-3">
|
||||||
<div className="flex items-center justify-end gap-2">
|
<span><strong className="text-foreground">{formatNumber(accountInfo.statuses_count)}</strong> <span className="text-muted-foreground">posts</span></span>
|
||||||
{newMediaCount !== null && newMediaCount > 0 && (<div className="text-lg font-semibold text-green-600 dark:text-green-400 animate-in fade-in slide-in-from-left-2 duration-300">
|
<span className="text-muted-foreground">·</span>
|
||||||
{formatNumberWithComma(newMediaCount)}+
|
<span><strong className="text-foreground">{formatNumber(accountInfo.friends_count)}</strong> <span className="text-muted-foreground">following</span></span>
|
||||||
</div>)}
|
<span className="text-muted-foreground">·</span>
|
||||||
<div className="text-2xl font-bold text-primary">{formatNumberWithComma(totalUrls)}</div>
|
<span><strong className="text-foreground">{formatNumber(accountInfo.followers_count)}</strong> <span className="text-muted-foreground">followers</span></span>
|
||||||
|
{accountInfo.media_count ? (<>
|
||||||
|
<span className="text-muted-foreground">·</span>
|
||||||
|
<span><strong className="text-foreground">{formatNumber(accountInfo.media_count)}</strong> <span className="text-muted-foreground">media</span></span>
|
||||||
|
</>) : null}
|
||||||
</div>
|
</div>
|
||||||
<div className="text-sm text-muted-foreground">items found</div>
|
|
||||||
</div>
|
</div>
|
||||||
</div>)}
|
</div>)}
|
||||||
|
|
||||||
@@ -704,6 +731,12 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
|
|||||||
GIFs ({formatNumberWithComma(mediaCounts.gif)})
|
GIFs ({formatNumberWithComma(mediaCounts.gif)})
|
||||||
</span>
|
</span>
|
||||||
</SelectItem>)}
|
</SelectItem>)}
|
||||||
|
{mediaCounts.text > 0 && (<SelectItem value="text">
|
||||||
|
<span className="flex items-center gap-2">
|
||||||
|
<FileText className="h-4 w-4 text-orange-500"/>
|
||||||
|
Text ({formatNumberWithComma(mediaCounts.text)})
|
||||||
|
</span>
|
||||||
|
</SelectItem>)}
|
||||||
</SelectContent>
|
</SelectContent>
|
||||||
</Select>)}
|
</Select>)}
|
||||||
|
|
||||||
@@ -725,21 +758,12 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
|
|||||||
<FolderOpen className="h-4 w-4"/>
|
<FolderOpen className="h-4 w-4"/>
|
||||||
Open Folder
|
Open Folder
|
||||||
</Button>
|
</Button>
|
||||||
<Button variant="outline" onClick={handleConvertGifs} disabled={isConverting || !gifsFolderHasMP4 || !ffmpegInstalled}>
|
|
||||||
{isConverting ? (<>
|
|
||||||
<Spinner />
|
|
||||||
Converting...
|
|
||||||
</>) : (<>
|
|
||||||
<Film className="h-4 w-4"/>
|
|
||||||
Convert GIFs
|
|
||||||
</>)}
|
|
||||||
</Button>
|
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
{isDownloading && (<Button variant="destructive" onClick={handleStopDownload}>
|
{isDownloading && (<Button variant="destructive" onClick={handleStopDownload}>
|
||||||
<StopCircle className="h-4 w-4"/>
|
<StopCircle className="h-4 w-4"/>
|
||||||
Stop
|
Stop
|
||||||
</Button>)}
|
</Button>)}
|
||||||
<Button onClick={handleDownload} disabled={isDownloading}>
|
<Button onClick={handleDownload} disabled={anyDownloadActive}>
|
||||||
{isDownloading ? (<>
|
{isDownloading ? (<>
|
||||||
<Spinner />
|
<Spinner />
|
||||||
Downloading...
|
Downloading...
|
||||||
@@ -774,21 +798,20 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
|
|||||||
|
|
||||||
{viewMode === "list" ? (<div className="space-y-2">
|
{viewMode === "list" ? (<div className="space-y-2">
|
||||||
{filteredTimeline.slice(0, visibleCount).map((item, index) => {
|
{filteredTimeline.slice(0, visibleCount).map((item, index) => {
|
||||||
const isSelected = selectedItems.has(index);
|
|
||||||
const itemKey = getItemKey(item);
|
const itemKey = getItemKey(item);
|
||||||
const isItemDownloaded = downloadedItems.has(itemKey);
|
const isSelected = selectedItems.has(itemKey);
|
||||||
const isItemFailed = failedItems.has(itemKey);
|
const { isItemDownloaded, isItemFailed, isItemSkipped, isItemDownloading } = getItemStatusFlags(itemKey);
|
||||||
const isItemSkipped = skippedItems.has(itemKey);
|
return (<div key={itemKey} onClick={() => openPreview(index)} className={`flex items-center gap-4 p-3 rounded-lg border-2 transition-all cursor-pointer ${isSelected ? "border-primary bg-primary/5" : "border-transparent hover:bg-muted/50"}`}>
|
||||||
const isItemDownloading = downloadingItem === itemKey;
|
<Checkbox checked={isSelected} onCheckedChange={() => toggleItem(itemKey)} onClick={(e) => e.stopPropagation()}/>
|
||||||
return (<div key={itemKey} className={`flex items-center gap-4 p-3 rounded-lg border-2 transition-all ${isSelected ? "border-primary bg-primary/5" : "border-transparent hover:bg-muted/50"}`}>
|
<div className="relative shrink-0">
|
||||||
<Checkbox checked={isSelected} onCheckedChange={() => toggleItem(index)}/>
|
<span className="absolute -top-1.5 -left-1.5 z-10 flex h-5 min-w-5 items-center justify-center rounded-full bg-primary px-1 text-xs font-medium text-primary-foreground">
|
||||||
<span className="text-sm text-muted-foreground w-8 text-center shrink-0">
|
{index + 1}
|
||||||
{index + 1}
|
</span>
|
||||||
</span>
|
<div className="w-16 h-16 rounded overflow-hidden bg-muted">
|
||||||
<div className="w-16 h-16 rounded overflow-hidden bg-muted shrink-0 cursor-pointer hover:opacity-80 transition-opacity" onClick={() => openPreview(index)}>
|
{item.type !== "text" && getEntryThumbnail(item) ? (<img src={getEntryThumbnail(item)} alt="" className="w-full h-full object-cover" loading="lazy"/>) : (<div className="w-full h-full flex items-center justify-center">
|
||||||
{item.type === "photo" || item.type === "animated_gif" || item.type === "gif" ? (<img src={getThumbnailUrl(item.url)} alt="" className="w-full h-full object-cover" loading="lazy"/>) : (<div className="w-full h-full flex items-center justify-center">
|
{getMediaIcon(item.type)}
|
||||||
{getMediaIcon(item.type)}
|
</div>)}
|
||||||
</div>)}
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex-1 min-w-0">
|
<div className="flex-1 min-w-0">
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
@@ -816,47 +839,7 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
|
|||||||
<div className="flex items-center gap-2 shrink-0">
|
<div className="flex items-center gap-2 shrink-0">
|
||||||
<Tooltip>
|
<Tooltip>
|
||||||
<TooltipTrigger asChild>
|
<TooltipTrigger asChild>
|
||||||
<Button size="icon" variant="default" onClick={async () => {
|
<Button size="icon" variant="default" onClick={() => void handleDownloadItem(item, itemKey)} disabled={anyDownloadActive}>
|
||||||
setDownloadingItem(itemKey);
|
|
||||||
currentDownloadingItemKeyRef.current = itemKey;
|
|
||||||
try {
|
|
||||||
const settings = getSettings();
|
|
||||||
const request = new main.DownloadMediaWithMetadataRequest({
|
|
||||||
items: [new main.MediaItemRequest({
|
|
||||||
url: item.url,
|
|
||||||
date: item.date,
|
|
||||||
tweet_id: item.tweet_id,
|
|
||||||
type: item.type,
|
|
||||||
content: item.content || "",
|
|
||||||
original_filename: item.original_filename || "",
|
|
||||||
author_username: item.author_username || "",
|
|
||||||
})],
|
|
||||||
output_dir: getOutputDir(),
|
|
||||||
username: accountInfo.name,
|
|
||||||
proxy: settings.proxy || "",
|
|
||||||
});
|
|
||||||
const response = await DownloadMediaWithMetadata(request);
|
|
||||||
if (response.cancelled) {
|
|
||||||
toast.info(response.message || "Download stopped");
|
|
||||||
}
|
|
||||||
else if (response.success) {
|
|
||||||
setHasDownloaded(true);
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
setFailedItems((prev) => new Set(prev).add(itemKey));
|
|
||||||
toast.error(response.message || "Download failed");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
catch (error) {
|
|
||||||
setFailedItems((prev) => new Set(prev).add(itemKey));
|
|
||||||
const errorMsg = error instanceof Error ? error.message : String(error);
|
|
||||||
toast.error(`Download failed: ${errorMsg}`);
|
|
||||||
}
|
|
||||||
finally {
|
|
||||||
setDownloadingItem(null);
|
|
||||||
setTimeout(() => { currentDownloadingItemKeyRef.current = null; }, 1000);
|
|
||||||
}
|
|
||||||
}} disabled={downloadingItem !== null}>
|
|
||||||
{isItemDownloading ? (<Spinner />) : isItemSkipped ? (<FileCheck className="h-4 w-4"/>) : isItemDownloaded ? (<CheckCircle className="h-4 w-4"/>) : isItemFailed ? (<XCircle className="h-4 w-4"/>) : (<Download className="h-4 w-4"/>)}
|
{isItemDownloading ? (<Spinner />) : isItemSkipped ? (<FileCheck className="h-4 w-4"/>) : isItemDownloaded ? (<CheckCircle className="h-4 w-4"/>) : isItemFailed ? (<XCircle className="h-4 w-4"/>) : (<Download className="h-4 w-4"/>)}
|
||||||
</Button>
|
</Button>
|
||||||
</TooltipTrigger>
|
</TooltipTrigger>
|
||||||
@@ -872,16 +855,16 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
|
|||||||
})}
|
})}
|
||||||
</div>) : (<div className={`grid gap-3 ${viewMode === "large" ? "grid-cols-4" : "grid-cols-6"}`}>
|
</div>) : (<div className={`grid gap-3 ${viewMode === "large" ? "grid-cols-4" : "grid-cols-6"}`}>
|
||||||
{filteredTimeline.slice(0, visibleCount).map((item, index) => {
|
{filteredTimeline.slice(0, visibleCount).map((item, index) => {
|
||||||
const isSelected = selectedItems.has(index);
|
|
||||||
const itemKey = getItemKey(item);
|
const itemKey = getItemKey(item);
|
||||||
const isItemDownloaded = downloadedItems.has(itemKey);
|
const isSelected = selectedItems.has(itemKey);
|
||||||
const isItemFailed = failedItems.has(itemKey);
|
const { isItemDownloaded, isItemFailed, isItemSkipped, isItemDownloading } = getItemStatusFlags(itemKey);
|
||||||
const isItemSkipped = skippedItems.has(itemKey);
|
|
||||||
const isItemDownloading = downloadingItem === itemKey;
|
|
||||||
return (<div key={itemKey} className={`relative group rounded-lg overflow-hidden border-2 transition-all ${isSelected ? "border-primary" : "border-transparent hover:border-muted-foreground/30"}`}>
|
return (<div key={itemKey} className={`relative group rounded-lg overflow-hidden border-2 transition-all ${isSelected ? "border-primary" : "border-transparent hover:border-muted-foreground/30"}`}>
|
||||||
|
|
||||||
<div className="aspect-square bg-muted relative cursor-pointer" onClick={() => openPreview(index)}>
|
<div className="aspect-square bg-muted relative cursor-pointer" onClick={() => openPreview(index)}>
|
||||||
{item.type === "photo" || item.type === "animated_gif" || item.type === "gif" ? (<img src={getThumbnailUrl(item.url)} alt="" className="w-full h-full object-cover" loading="lazy"/>) : (<div className="w-full h-full flex items-center justify-center bg-muted">
|
<span className="absolute top-1.5 left-1.5 z-20 flex h-5 min-w-5 items-center justify-center rounded-full bg-primary px-1 text-xs font-medium text-primary-foreground">
|
||||||
|
{index + 1}
|
||||||
|
</span>
|
||||||
|
{item.type !== "text" && getEntryThumbnail(item) ? (<img src={getEntryThumbnail(item)} alt="" className="w-full h-full object-cover" loading="lazy"/>) : (<div className="w-full h-full flex items-center justify-center bg-muted">
|
||||||
{getMediaIcon(item.type)}
|
{getMediaIcon(item.type)}
|
||||||
</div>)}
|
</div>)}
|
||||||
|
|
||||||
@@ -891,45 +874,8 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
|
|||||||
<TooltipTrigger asChild>
|
<TooltipTrigger asChild>
|
||||||
<Button size="icon" variant="default" className="h-8 w-8" onClick={async (e) => {
|
<Button size="icon" variant="default" className="h-8 w-8" onClick={async (e) => {
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
setDownloadingItem(itemKey);
|
await handleDownloadItem(item, itemKey);
|
||||||
currentDownloadingItemKeyRef.current = itemKey;
|
}} disabled={anyDownloadActive}>
|
||||||
try {
|
|
||||||
const settings = getSettings();
|
|
||||||
const request = new main.DownloadMediaWithMetadataRequest({
|
|
||||||
items: [new main.MediaItemRequest({
|
|
||||||
url: item.url,
|
|
||||||
date: item.date,
|
|
||||||
tweet_id: item.tweet_id,
|
|
||||||
type: item.type,
|
|
||||||
content: item.content || "",
|
|
||||||
author_username: item.author_username || "",
|
|
||||||
})],
|
|
||||||
output_dir: getOutputDir(),
|
|
||||||
username: accountInfo.name,
|
|
||||||
proxy: settings.proxy || "",
|
|
||||||
});
|
|
||||||
const response = await DownloadMediaWithMetadata(request);
|
|
||||||
if (response.cancelled) {
|
|
||||||
toast.info(response.message || "Download stopped");
|
|
||||||
}
|
|
||||||
else if (response.success) {
|
|
||||||
setHasDownloaded(true);
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
setFailedItems((prev) => new Set(prev).add(itemKey));
|
|
||||||
toast.error(response.message || "Download failed");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
catch (error) {
|
|
||||||
setFailedItems((prev) => new Set(prev).add(itemKey));
|
|
||||||
const errorMsg = error instanceof Error ? error.message : String(error);
|
|
||||||
toast.error(`Download failed: ${errorMsg}`);
|
|
||||||
}
|
|
||||||
finally {
|
|
||||||
setDownloadingItem(null);
|
|
||||||
setTimeout(() => { currentDownloadingItemKeyRef.current = null; }, 1000);
|
|
||||||
}
|
|
||||||
}} disabled={downloadingItem !== null}>
|
|
||||||
{isItemDownloading ? (<Spinner />) : isItemSkipped ? (<FileCheck className="h-4 w-4"/>) : isItemDownloaded ? (<CheckCircle className="h-4 w-4"/>) : isItemFailed ? (<XCircle className="h-4 w-4"/>) : (<Download className="h-4 w-4"/>)}
|
{isItemDownloading ? (<Spinner />) : isItemSkipped ? (<FileCheck className="h-4 w-4"/>) : isItemDownloaded ? (<CheckCircle className="h-4 w-4"/>) : isItemFailed ? (<XCircle className="h-4 w-4"/>) : (<Download className="h-4 w-4"/>)}
|
||||||
</Button>
|
</Button>
|
||||||
</TooltipTrigger>
|
</TooltipTrigger>
|
||||||
@@ -947,7 +893,7 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
|
|||||||
|
|
||||||
|
|
||||||
<div className="absolute top-2 left-2" onClick={(e) => e.stopPropagation()}>
|
<div className="absolute top-2 left-2" onClick={(e) => e.stopPropagation()}>
|
||||||
<Checkbox checked={isSelected} onCheckedChange={() => toggleItem(index)} className="bg-background/80"/>
|
<Checkbox checked={isSelected} onCheckedChange={() => toggleItem(itemKey)} className="bg-background/80"/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|
||||||
@@ -1058,50 +1004,10 @@ export function MediaList({ accountInfo, timeline, totalUrls, fetchedMediaType =
|
|||||||
{(() => {
|
{(() => {
|
||||||
const item = filteredTimeline[previewIndex];
|
const item = filteredTimeline[previewIndex];
|
||||||
const itemKey = getItemKey(item);
|
const itemKey = getItemKey(item);
|
||||||
const isItemDownloaded = downloadedItems.has(itemKey);
|
const { isItemDownloaded, isItemFailed, isItemSkipped, isItemDownloading } = getItemStatusFlags(itemKey);
|
||||||
const isItemFailed = failedItems.has(itemKey);
|
|
||||||
const isItemSkipped = skippedItems.has(itemKey);
|
|
||||||
const isItemDownloading = downloadingItem === itemKey;
|
|
||||||
return (<Button variant="default" size="sm" className="h-9" onClick={async () => {
|
return (<Button variant="default" size="sm" className="h-9" onClick={async () => {
|
||||||
setDownloadingItem(itemKey);
|
await handleDownloadItem(item, itemKey);
|
||||||
currentDownloadingItemKeyRef.current = itemKey;
|
}} disabled={anyDownloadActive}>
|
||||||
try {
|
|
||||||
const settings = getSettings();
|
|
||||||
const request = new main.DownloadMediaWithMetadataRequest({
|
|
||||||
items: [new main.MediaItemRequest({
|
|
||||||
url: item.url,
|
|
||||||
date: item.date,
|
|
||||||
tweet_id: item.tweet_id,
|
|
||||||
type: item.type,
|
|
||||||
content: item.content || "",
|
|
||||||
original_filename: item.original_filename || "",
|
|
||||||
author_username: item.author_username || "",
|
|
||||||
})],
|
|
||||||
output_dir: getOutputDir(),
|
|
||||||
username: accountInfo.name,
|
|
||||||
proxy: settings.proxy || "",
|
|
||||||
});
|
|
||||||
const response = await DownloadMediaWithMetadata(request);
|
|
||||||
if (response.cancelled) {
|
|
||||||
toast.info(response.message || "Download stopped");
|
|
||||||
}
|
|
||||||
else if (response.success) {
|
|
||||||
setHasDownloaded(true);
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
setFailedItems((prev) => new Set(prev).add(itemKey));
|
|
||||||
toast.error("Download failed");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
catch {
|
|
||||||
setFailedItems((prev) => new Set(prev).add(itemKey));
|
|
||||||
toast.error("Download failed");
|
|
||||||
}
|
|
||||||
finally {
|
|
||||||
setDownloadingItem(null);
|
|
||||||
setTimeout(() => { currentDownloadingItemKeyRef.current = null; }, 1000);
|
|
||||||
}
|
|
||||||
}} disabled={downloadingItem !== null}>
|
|
||||||
{isItemDownloading ? (<Spinner className="mr-1"/>) : isItemSkipped ? (<FileCheck className="h-4 w-4 mr-1"/>) : isItemDownloaded ? (<CheckCircle className="h-4 w-4 mr-1"/>) : isItemFailed ? (<XCircle className="h-4 w-4 mr-1"/>) : (<Download className="h-4 w-4 mr-1"/>)}
|
{isItemDownloading ? (<Spinner className="mr-1"/>) : isItemSkipped ? (<FileCheck className="h-4 w-4 mr-1"/>) : isItemDownloaded ? (<CheckCircle className="h-4 w-4 mr-1"/>) : isItemFailed ? (<XCircle className="h-4 w-4 mr-1"/>) : (<Download className="h-4 w-4 mr-1"/>)}
|
||||||
{isItemDownloading ? "Downloading..." : isItemSkipped ? "Already exists" : isItemDownloaded ? "Downloaded" : isItemFailed ? "Failed" : "Download"}
|
{isItemDownloading ? "Downloading..." : isItemSkipped ? "Already exists" : isItemDownloaded ? "Downloaded" : isItemFailed ? "Failed" : "Download"}
|
||||||
</Button>);
|
</Button>);
|
||||||
|
|||||||
@@ -1,27 +1,32 @@
|
|||||||
import { useState, useEffect } from "react";
|
import { useEffect, useRef, useState } from "react";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Checkbox } from "@/components/ui/checkbox";
|
||||||
|
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
|
||||||
import { InputWithContext } from "@/components/ui/input-with-context";
|
import { InputWithContext } from "@/components/ui/input-with-context";
|
||||||
import { Label } from "@/components/ui/label";
|
import { Label } from "@/components/ui/label";
|
||||||
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";
|
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
||||||
|
import { FetchHistory } from "@/components/FetchHistory";
|
||||||
|
import type { HistoryItem } from "@/components/FetchHistory";
|
||||||
|
import { toastWithSound as toast } from "@/lib/toast-with-sound";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
import { getSettings, updateSettings, VIDEO_QUALITIES, IMAGE_SIZES, AVATAR_SIZES, BANNER_SIZES, type VideoQuality, type ImageSize, type AvatarSize, type BannerSize } from "@/lib/settings";
|
||||||
|
import { GetStoredAuthToken, SetStoredAuthToken } from "../../wailsjs/go/main/App";
|
||||||
|
import { AlertCircle, Bookmark, CheckCircle, Clipboard, CloudDownload, Clock, Database, Eye, EyeOff, Globe, Heart, Hourglass, Info, Lock, RotateCcw, SlidersHorizontal, StopCircle, Trash2, User, Users, XCircle } from "lucide-react";
|
||||||
import { Spinner } from "@/components/ui/spinner";
|
import { Spinner } from "@/components/ui/spinner";
|
||||||
function formatNumberWithComma(num: number): string {
|
function formatNumberWithComma(num: number): string {
|
||||||
return num.toLocaleString();
|
return num.toLocaleString();
|
||||||
}
|
}
|
||||||
import { Checkbox } from "@/components/ui/checkbox";
|
function pillClass(active: boolean): string {
|
||||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select";
|
return cn("rounded-md px-3 py-1.5 text-sm font-medium transition-colors cursor-pointer", active
|
||||||
import { Tooltip, TooltipContent, TooltipTrigger, } from "@/components/ui/tooltip";
|
? "bg-primary text-primary-foreground"
|
||||||
import { FetchHistory } from "@/components/FetchHistory";
|
: "bg-muted text-muted-foreground hover:text-foreground");
|
||||||
import type { HistoryItem } from "@/components/FetchHistory";
|
}
|
||||||
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";
|
export type FetchType = "single" | "multiple";
|
||||||
const LEGACY_PUBLIC_AUTH_TOKEN_KEY = "twitter_public_auth_token";
|
const LEGACY_PUBLIC_AUTH_TOKEN_KEY = "twitter_public_auth_token";
|
||||||
const LEGACY_PRIVATE_AUTH_TOKEN_KEY = "twitter_private_auth_token";
|
const LEGACY_PRIVATE_AUTH_TOKEN_KEY = "twitter_private_auth_token";
|
||||||
let sessionPublicAuthToken = "";
|
let sessionAuthToken = "";
|
||||||
let sessionPrivateAuthToken = "";
|
|
||||||
export interface MultipleAccount {
|
export interface MultipleAccount {
|
||||||
id: string;
|
id: string;
|
||||||
username: string;
|
username: string;
|
||||||
@@ -60,42 +65,67 @@ interface SearchBarProps {
|
|||||||
fetchType?: FetchType;
|
fetchType?: FetchType;
|
||||||
onFetchTypeChange?: (type: FetchType) => void;
|
onFetchTypeChange?: (type: FetchType) => void;
|
||||||
multipleAccounts?: MultipleAccount[];
|
multipleAccounts?: MultipleAccount[];
|
||||||
onImportFile?: () => void;
|
onImportAccounts?: (accounts: string[]) => void;
|
||||||
onFetchAll?: (authToken: string) => void;
|
onFetchAll?: (authToken: string) => void;
|
||||||
onStopAll?: () => void;
|
onStopAll?: () => void;
|
||||||
onStopAccount?: (accountId: string) => void;
|
onStopAccount?: (accountId: string) => void;
|
||||||
onRetryAccount?: (accountId: string, authToken: string) => void;
|
onRetryAccount?: (accountId: string, authToken: string) => void;
|
||||||
|
onClearMultipleAccounts?: () => void;
|
||||||
|
onRemoveMultipleAccount?: (accountId: string) => void;
|
||||||
|
onOpenSavedAccounts?: () => void;
|
||||||
isFetchingAll?: boolean;
|
isFetchingAll?: boolean;
|
||||||
mode?: FetchMode;
|
mode?: FetchMode;
|
||||||
privateType?: PrivateType;
|
privateType?: PrivateType;
|
||||||
onModeChange?: (mode: FetchMode, privateType?: PrivateType) => void;
|
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) {
|
export function SearchBar({ username, loading, onUsernameChange, onFetch, onStopFetch, onResume, onClearResume, resumeInfo, history, onHistorySelect, onHistoryRemove, hasResult, elapsedTime = 0, remainingTime = null, fetchType = "single", onFetchTypeChange, multipleAccounts = [], onImportAccounts, onFetchAll, onStopAll, onStopAccount, onRetryAccount, onClearMultipleAccounts, onRemoveMultipleAccount, onOpenSavedAccounts, isFetchingAll = false, mode: externalMode, privateType: externalPrivateType, onModeChange, }: SearchBarProps) {
|
||||||
const [useDateRange, setUseDateRange] = useState(false);
|
const [includePhotos, setIncludePhotos] = useState(getSettings().includePhotos);
|
||||||
const [startDate, setStartDate] = useState("");
|
const [includeVideos, setIncludeVideos] = useState(getSettings().includeVideos);
|
||||||
const [endDate, setEndDate] = useState("");
|
const [includeGifs, setIncludeGifs] = useState(getSettings().includeGifs);
|
||||||
const [mediaType, setMediaType] = useState<SettingsMediaType>(getSettings().mediaType);
|
const [includeText, setIncludeText] = useState(getSettings().includeText);
|
||||||
const [retweets, setRetweets] = useState(getSettings().includeRetweets);
|
const [retweets, setRetweets] = useState(getSettings().includeRetweets);
|
||||||
|
const [videoQuality, setVideoQuality] = useState<VideoQuality>(getSettings().videoQuality);
|
||||||
|
const [imageSize, setImageSize] = useState<ImageSize>(getSettings().imageSize);
|
||||||
|
const [avatarSize, setAvatarSize] = useState<AvatarSize>(getSettings().avatarSize);
|
||||||
|
const [bannerSize, setBannerSize] = useState<BannerSize>(getSettings().bannerSize);
|
||||||
|
const [sharedAuthToken, setSharedAuthToken] = useState(() => sessionAuthToken || localStorage.getItem(LEGACY_PUBLIC_AUTH_TOKEN_KEY) || localStorage.getItem(LEGACY_PRIVATE_AUTH_TOKEN_KEY) || "");
|
||||||
|
const [showAuthToken, setShowAuthToken] = useState(false);
|
||||||
|
const [showAuthRequiredDialog, setShowAuthRequiredDialog] = useState(false);
|
||||||
|
const [showSettingsDialog, setShowSettingsDialog] = useState(false);
|
||||||
|
useEffect(() => {
|
||||||
|
if (showSettingsDialog) {
|
||||||
|
const fresh = getSettings();
|
||||||
|
setIncludePhotos(fresh.includePhotos);
|
||||||
|
setIncludeVideos(fresh.includeVideos);
|
||||||
|
setIncludeGifs(fresh.includeGifs);
|
||||||
|
setIncludeText(fresh.includeText);
|
||||||
|
setRetweets(fresh.includeRetweets);
|
||||||
|
setVideoQuality(fresh.videoQuality);
|
||||||
|
setImageSize(fresh.imageSize);
|
||||||
|
setAvatarSize(fresh.avatarSize);
|
||||||
|
setBannerSize(fresh.bannerSize);
|
||||||
|
}
|
||||||
|
}, [showSettingsDialog]);
|
||||||
|
const [showImportDialog, setShowImportDialog] = useState(false);
|
||||||
|
const [importAccountsText, setImportAccountsText] = useState("");
|
||||||
|
const [authPromptToken, setAuthPromptToken] = useState("");
|
||||||
const mode = externalMode || "public";
|
const mode = externalMode || "public";
|
||||||
const privateType = externalPrivateType || "bookmarks";
|
const privateType = externalPrivateType || "bookmarks";
|
||||||
const [showAuthInput, setShowAuthInput] = useState(false);
|
const isLikesMode = mode === "private" && privateType === "likes";
|
||||||
const [showAdvanced, setShowAdvanced] = useState(false);
|
const isBookmarksMode = mode === "private" && privateType === "bookmarks";
|
||||||
const [currentFetchMode, setCurrentFetchMode] = useState<SettingsFetchMode>(getSettings().fetchMode);
|
const isAnyMultipleAccountFetching = multipleAccounts.some((account) => account.status === "fetching");
|
||||||
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(() => {
|
useEffect(() => {
|
||||||
let active = true;
|
let active = true;
|
||||||
const syncStoredTokens = async () => {
|
const syncStoredTokens = async () => {
|
||||||
const legacyPublicToken = localStorage.getItem(LEGACY_PUBLIC_AUTH_TOKEN_KEY) || "";
|
const legacyPublicToken = localStorage.getItem(LEGACY_PUBLIC_AUTH_TOKEN_KEY) || "";
|
||||||
const legacyPrivateToken = localStorage.getItem(LEGACY_PRIVATE_AUTH_TOKEN_KEY) || "";
|
const legacyPrivateToken = localStorage.getItem(LEGACY_PRIVATE_AUTH_TOKEN_KEY) || "";
|
||||||
|
const legacyUnifiedToken = legacyPublicToken || legacyPrivateToken;
|
||||||
try {
|
try {
|
||||||
if (legacyPublicToken) {
|
if (legacyUnifiedToken) {
|
||||||
await SetStoredAuthToken("public", legacyPublicToken);
|
await Promise.all([
|
||||||
}
|
SetStoredAuthToken("public", legacyUnifiedToken),
|
||||||
if (legacyPrivateToken) {
|
SetStoredAuthToken("private", legacyUnifiedToken),
|
||||||
await SetStoredAuthToken("private", legacyPrivateToken);
|
]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
catch (error) {
|
catch (error) {
|
||||||
@@ -105,7 +135,6 @@ export function SearchBar({ username, loading, onUsernameChange, onFetch, onStop
|
|||||||
localStorage.removeItem(LEGACY_PUBLIC_AUTH_TOKEN_KEY);
|
localStorage.removeItem(LEGACY_PUBLIC_AUTH_TOKEN_KEY);
|
||||||
localStorage.removeItem(LEGACY_PRIVATE_AUTH_TOKEN_KEY);
|
localStorage.removeItem(LEGACY_PRIVATE_AUTH_TOKEN_KEY);
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const [storedPublicToken, storedPrivateToken] = await Promise.all([
|
const [storedPublicToken, storedPrivateToken] = await Promise.all([
|
||||||
GetStoredAuthToken("public"),
|
GetStoredAuthToken("public"),
|
||||||
@@ -114,10 +143,15 @@ export function SearchBar({ username, loading, onUsernameChange, onFetch, onStop
|
|||||||
if (!active) {
|
if (!active) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
sessionPublicAuthToken = storedPublicToken || "";
|
const unifiedToken = storedPublicToken || storedPrivateToken || "";
|
||||||
setPublicAuthToken(storedPublicToken || "");
|
sessionAuthToken = unifiedToken;
|
||||||
sessionPrivateAuthToken = storedPrivateToken || "";
|
setSharedAuthToken(unifiedToken);
|
||||||
setPrivateAuthToken(storedPrivateToken || "");
|
if (unifiedToken && (storedPublicToken !== unifiedToken || storedPrivateToken !== unifiedToken)) {
|
||||||
|
await Promise.all([
|
||||||
|
SetStoredAuthToken("public", unifiedToken),
|
||||||
|
SetStoredAuthToken("private", unifiedToken),
|
||||||
|
]);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
catch (error) {
|
catch (error) {
|
||||||
console.error("Failed to load auth token from secure storage:", error);
|
console.error("Failed to load auth token from secure storage:", error);
|
||||||
@@ -128,66 +162,148 @@ export function SearchBar({ username, loading, onUsernameChange, onFetch, onStop
|
|||||||
active = false;
|
active = false;
|
||||||
};
|
};
|
||||||
}, []);
|
}, []);
|
||||||
const handlePublicTokenChange = async (value: string) => {
|
const tokenWriteTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||||
sessionPublicAuthToken = value;
|
const pendingAuthActionRef = useRef<((authToken: string) => void) | null>(null);
|
||||||
setPublicAuthToken(value);
|
useEffect(() => {
|
||||||
try {
|
return () => {
|
||||||
await SetStoredAuthToken("public", value);
|
if (tokenWriteTimerRef.current) {
|
||||||
|
clearTimeout(tokenWriteTimerRef.current);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
const handleSharedTokenChange = (value: string) => {
|
||||||
|
sessionAuthToken = value;
|
||||||
|
setSharedAuthToken(value);
|
||||||
|
if (tokenWriteTimerRef.current) {
|
||||||
|
clearTimeout(tokenWriteTimerRef.current);
|
||||||
}
|
}
|
||||||
catch (error) {
|
tokenWriteTimerRef.current = setTimeout(() => {
|
||||||
console.error("Failed to store public auth token securely:", error);
|
void Promise.all([
|
||||||
|
SetStoredAuthToken("public", value),
|
||||||
|
SetStoredAuthToken("private", value),
|
||||||
|
]).catch((error) => {
|
||||||
|
console.error("Failed to store auth token securely:", error);
|
||||||
|
});
|
||||||
|
}, 400);
|
||||||
|
};
|
||||||
|
const closeAuthRequiredDialog = (open: boolean) => {
|
||||||
|
setShowAuthRequiredDialog(open);
|
||||||
|
if (!open) {
|
||||||
|
pendingAuthActionRef.current = null;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
const handlePrivateTokenChange = async (value: string) => {
|
const requireAuthToken = (onAuthorized: (authToken: string) => void) => {
|
||||||
sessionPrivateAuthToken = value;
|
const token = sharedAuthToken.trim();
|
||||||
setPrivateAuthToken(value);
|
if (token) {
|
||||||
try {
|
onAuthorized(token);
|
||||||
await SetStoredAuthToken("private", value);
|
return;
|
||||||
}
|
|
||||||
catch (error) {
|
|
||||||
console.error("Failed to store private auth token securely:", error);
|
|
||||||
}
|
}
|
||||||
|
pendingAuthActionRef.current = onAuthorized;
|
||||||
|
setAuthPromptToken(sharedAuthToken);
|
||||||
|
setShowAuthRequiredDialog(true);
|
||||||
};
|
};
|
||||||
const handleFetch = () => {
|
const handleFetch = () => {
|
||||||
const authToken = mode === "public" ? publicAuthToken : privateAuthToken;
|
requireAuthToken((authToken) => {
|
||||||
onFetch(useDateRange, startDate, endDate, mediaType, retweets, mode, privateType, authToken, false);
|
onFetch(false, undefined, undefined, undefined, retweets, mode, privateType, authToken, false);
|
||||||
|
});
|
||||||
};
|
};
|
||||||
const handleResume = () => {
|
const handleClipboardPaste = async () => {
|
||||||
const authToken = mode === "public" ? publicAuthToken : privateAuthToken;
|
try {
|
||||||
if (onResume) {
|
const clipboardText = (await navigator.clipboard.readText()).trim();
|
||||||
onResume(authToken, mediaType, retweets);
|
if (clipboardText) {
|
||||||
|
onUsernameChange(clipboardText);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (error) {
|
||||||
|
console.error("Failed to read clipboard:", error);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
const currentAuthToken = mode === "public" ? publicAuthToken : privateAuthToken;
|
const handleResume = () => {
|
||||||
const hasAuthToken = currentAuthToken.trim().length > 0;
|
if (onResume) {
|
||||||
const isLikesMode = mode === "private" && privateType === "likes";
|
requireAuthToken((authToken) => {
|
||||||
const isBookmarksMode = mode === "private" && privateType === "bookmarks";
|
onResume(authToken, undefined, retweets);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const handleFetchAll = () => {
|
||||||
|
requireAuthToken((authToken) => {
|
||||||
|
onFetchAll?.(authToken);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
const handleRetry = (accountId: string) => {
|
||||||
|
requireAuthToken((authToken) => {
|
||||||
|
onRetryAccount?.(accountId, authToken);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
const handleAuthPromptSubmit = () => {
|
||||||
|
const token = authPromptToken.trim();
|
||||||
|
if (!token) {
|
||||||
|
toast.error("Please enter your auth token");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
handleSharedTokenChange(token);
|
||||||
|
const pendingAction = pendingAuthActionRef.current;
|
||||||
|
pendingAuthActionRef.current = null;
|
||||||
|
setShowAuthRequiredDialog(false);
|
||||||
|
pendingAction?.(token);
|
||||||
|
};
|
||||||
|
const handleOpenFetchSettings = () => {
|
||||||
|
pendingAuthActionRef.current = null;
|
||||||
|
setShowAuthRequiredDialog(false);
|
||||||
|
setShowSettingsDialog(true);
|
||||||
|
};
|
||||||
|
const openImportDialog = () => {
|
||||||
|
setImportAccountsText(multipleAccounts.map((account) => account.username).join("\n"));
|
||||||
|
setShowImportDialog(true);
|
||||||
|
};
|
||||||
|
const handleImportSubmit = () => {
|
||||||
|
const accounts = importAccountsText
|
||||||
|
.split(/[\n,;]+/)
|
||||||
|
.map((entry) => entry.trim())
|
||||||
|
.filter((entry) => entry.length > 0);
|
||||||
|
if (accounts.length === 0) {
|
||||||
|
toast.error("Please enter at least one account");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
onImportAccounts?.(accounts);
|
||||||
|
setShowImportDialog(false);
|
||||||
|
};
|
||||||
const formatTime = (seconds: number): string => {
|
const formatTime = (seconds: number): string => {
|
||||||
const mins = Math.floor(seconds / 60);
|
const mins = Math.floor(seconds / 60);
|
||||||
const secs = seconds % 60;
|
const secs = seconds % 60;
|
||||||
return `${mins}:${String(secs).padStart(2, "0")}`;
|
return `${mins}:${String(secs).padStart(2, "0")}`;
|
||||||
};
|
};
|
||||||
|
const activeCountdown = remainingTime !== null && remainingTime >= 0
|
||||||
|
? formatTime(remainingTime)
|
||||||
|
: elapsedTime > 0
|
||||||
|
? formatTime(elapsedTime)
|
||||||
|
: null;
|
||||||
|
const fetchingLabel = activeCountdown ? `Fetching... (${activeCountdown})` : "Fetching...";
|
||||||
|
const authTokenHelpText = mode === "private"
|
||||||
|
? "Use auth token from the account whose bookmarks or likes you want to fetch."
|
||||||
|
: "Recommended to use a dummy account, not your main account. Excessive usage may cause suspension.";
|
||||||
return (<div className="space-y-3">
|
return (<div className="space-y-3">
|
||||||
|
|
||||||
<div className="flex justify-center gap-2">
|
<div className="flex justify-center gap-2">
|
||||||
<div className="flex gap-0.5 p-0.5 bg-muted rounded-lg w-fit">
|
<div className="flex w-fit gap-0.5 rounded-lg bg-muted p-0.5">
|
||||||
<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"
|
<button type="button" onClick={() => onFetchTypeChange?.("single")} className={cn("flex cursor-pointer items-center gap-1 rounded-md px-2 py-1 text-xs font-medium transition-all", fetchType === "single"
|
||||||
? "bg-background text-foreground shadow-sm"
|
? "bg-background text-foreground shadow-sm"
|
||||||
: "text-muted-foreground hover:text-foreground")}>
|
: "text-muted-foreground hover:text-foreground")}>
|
||||||
<User className="h-3 w-3"/>
|
<User className="h-3 w-3"/>
|
||||||
Single
|
Single
|
||||||
</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"
|
<button type="button" onClick={() => onFetchTypeChange?.("multiple")} className={cn("flex cursor-pointer items-center gap-1 rounded-md px-2 py-1 text-xs font-medium transition-all", fetchType === "multiple"
|
||||||
? "bg-background text-foreground shadow-sm"
|
? "bg-background text-foreground shadow-sm"
|
||||||
: "text-muted-foreground hover:text-foreground")}>
|
: "text-muted-foreground hover:text-foreground")}>
|
||||||
<Users className="h-3 w-3"/>
|
<Users className="h-3 w-3"/>
|
||||||
Multiple
|
Multiple
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
{fetchType === "single" && (<div className="flex gap-0.5 p-0.5 bg-muted rounded-lg w-fit">
|
|
||||||
|
{fetchType === "single" && (<div className="flex w-fit gap-0.5 rounded-lg bg-muted p-0.5">
|
||||||
<button type="button" onClick={() => {
|
<button type="button" onClick={() => {
|
||||||
onModeChange?.("public");
|
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"
|
}} className={cn("flex cursor-pointer items-center gap-1 rounded-md px-2 py-1 text-xs font-medium transition-all", mode === "public"
|
||||||
? "bg-background text-foreground shadow-sm"
|
? "bg-background text-foreground shadow-sm"
|
||||||
: "text-muted-foreground hover:text-foreground")}>
|
: "text-muted-foreground hover:text-foreground")}>
|
||||||
<Globe className="h-3 w-3"/>
|
<Globe className="h-3 w-3"/>
|
||||||
@@ -195,7 +311,7 @@ export function SearchBar({ username, loading, onUsernameChange, onFetch, onStop
|
|||||||
</button>
|
</button>
|
||||||
<button type="button" onClick={() => {
|
<button type="button" onClick={() => {
|
||||||
onModeChange?.("private");
|
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"
|
}} className={cn("flex cursor-pointer items-center gap-1 rounded-md px-2 py-1 text-xs font-medium transition-all", mode === "private"
|
||||||
? "bg-background text-foreground shadow-sm"
|
? "bg-background text-foreground shadow-sm"
|
||||||
: "text-muted-foreground hover:text-foreground")}>
|
: "text-muted-foreground hover:text-foreground")}>
|
||||||
<Lock className="h-3 w-3"/>
|
<Lock className="h-3 w-3"/>
|
||||||
@@ -204,81 +320,77 @@ export function SearchBar({ username, loading, onUsernameChange, onFetch, onStop
|
|||||||
</div>)}
|
</div>)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|
||||||
{fetchType === "multiple" && (<div className="space-y-2">
|
{fetchType === "multiple" && (<div className="space-y-2">
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<Label htmlFor="import-txt" className="text-sm">
|
<Label className="text-sm">Account List</Label>
|
||||||
Import Accounts
|
|
||||||
</Label>
|
|
||||||
<Tooltip>
|
<Tooltip>
|
||||||
<TooltipTrigger asChild>
|
<TooltipTrigger asChild>
|
||||||
<Info className="h-4 w-4 text-muted-foreground cursor-help"/>
|
<Info className="h-4 w-4 cursor-help text-muted-foreground"/>
|
||||||
</TooltipTrigger>
|
</TooltipTrigger>
|
||||||
<TooltipContent className="max-w-xs">
|
<TooltipContent className="max-w-xs">
|
||||||
<p className="text-sm">
|
<p className="text-sm">
|
||||||
One username per line, example:
|
One username or URL per line. Commas and semicolons are supported too.
|
||||||
<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>
|
</p>
|
||||||
</TooltipContent>
|
</TooltipContent>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<Button id="import-txt" variant="outline" onClick={onImportFile} className="flex items-center gap-2 flex-1">
|
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||||
<FileText className="h-4 w-4"/>
|
<Button variant="outline" onClick={openImportDialog} disabled={isFetchingAll} className="flex w-64 items-center justify-center gap-2">
|
||||||
Import TXT File
|
<Users className="h-4 w-4"/>
|
||||||
|
Input Account List
|
||||||
</Button>
|
</Button>
|
||||||
<Button variant="default" onClick={() => onFetchAll?.(publicAuthToken)} disabled={multipleAccounts.length === 0 || isFetchingAll} className="flex items-center gap-2 flex-1">
|
|
||||||
{isFetchingAll ? (<>
|
<div className="ml-auto flex items-center gap-2">
|
||||||
<Spinner />
|
{isFetchingAll && (<Button variant="destructive" onClick={onStopAll} className="w-28">
|
||||||
Fetching All...
|
<StopCircle className="h-4 w-4"/>
|
||||||
</>) : (<>
|
Stop All
|
||||||
<CloudDownload className="h-4 w-4"/>
|
</Button>)}
|
||||||
Fetch All
|
|
||||||
</>)}
|
<Tooltip>
|
||||||
</Button>
|
<TooltipTrigger asChild>
|
||||||
{isFetchingAll && (<Button variant="destructive" onClick={onStopAll} className="flex items-center gap-2">
|
<Button variant="outline" size="icon" onClick={() => setShowSettingsDialog(true)} disabled={loading || isFetchingAll} aria-label="Fetch settings">
|
||||||
<StopCircle className="h-4 w-4"/>
|
<SlidersHorizontal className="h-4 w-4"/>
|
||||||
Stop All
|
</Button>
|
||||||
</Button>)}
|
</TooltipTrigger>
|
||||||
|
<TooltipContent>Fetch Settings</TooltipContent>
|
||||||
|
</Tooltip>
|
||||||
|
|
||||||
|
<Button variant="default" onClick={handleFetchAll} disabled={multipleAccounts.length === 0 || isFetchingAll} className="flex w-36 items-center justify-center gap-2">
|
||||||
|
{isFetchingAll ? (<>
|
||||||
|
<Spinner />
|
||||||
|
Fetching All...
|
||||||
|
</>) : (<>
|
||||||
|
<CloudDownload className="h-4 w-4"/>
|
||||||
|
Fetch All
|
||||||
|
</>)}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>)}
|
</div>)}
|
||||||
|
|
||||||
|
|
||||||
{fetchType === "single" && (mode === "public" || isLikesMode) && (<div className="space-y-2">
|
{fetchType === "single" && (mode === "public" || isLikesMode) && (<div className="space-y-2">
|
||||||
<Label htmlFor="username">
|
<Label htmlFor="username">X/Twitter URL or Username</Label>
|
||||||
X/Twitter URL or Username
|
|
||||||
</Label>
|
|
||||||
|
|
||||||
<div className="flex gap-2">
|
<div className="flex gap-2">
|
||||||
<div className="relative flex-1">
|
<div className="relative flex-1">
|
||||||
<InputWithContext id="username" placeholder={isLikesMode
|
<InputWithContext id="username" placeholder={isLikesMode
|
||||||
? "your_username or @your_username or https://x.com/your_username"
|
? "your_username or @your_username or https://x.com/your_username"
|
||||||
: "masteraoko or @masteraoko or https://x.com/masteraoko"} value={username} onChange={(e) => onUsernameChange(e.target.value)} onKeyDown={(e) => e.key === "Enter" && handleFetch()} className="pr-8"/>
|
: "masteraoko or @masteraoko or https://x.com/masteraoko"} value={username} onChange={(e) => onUsernameChange(e.target.value)} onKeyDown={(e) => e.key === "Enter" && handleFetch()} className="pr-8"/>
|
||||||
{username && (<button type="button" className="absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground transition-colors cursor-pointer" onClick={() => onUsernameChange("")}>
|
{username && (<button type="button" className="absolute top-1/2 right-2 -translate-y-1/2 cursor-pointer text-muted-foreground transition-colors hover:text-foreground" onClick={() => onUsernameChange("")}>
|
||||||
<XCircle className="h-4 w-4"/>
|
<XCircle className="h-4 w-4"/>
|
||||||
</button>)}
|
</button>)}
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
{loading && (<>
|
|
||||||
|
|
||||||
{(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">
|
<Button variant="outline" size="icon" className="shrink-0" aria-label="Paste from clipboard" onClick={() => void handleClipboardPaste()}>
|
||||||
<Clock className="h-3.5 w-3.5 text-muted-foreground shrink-0"/>
|
<Clipboard className="h-4 w-4"/>
|
||||||
<span className="font-mono">
|
</Button>
|
||||||
{remainingTime !== null && remainingTime >= 0
|
|
||||||
? `${Math.floor(remainingTime / 60)}:${String(remainingTime % 60).padStart(2, "0")}`
|
<div className="flex items-center gap-2">
|
||||||
: `${Math.floor(elapsedTime / 60)}:${String(elapsedTime % 60).padStart(2, "0")}`}
|
{loading && (<Button variant="destructive" onClick={onStopFetch}>
|
||||||
</span>
|
<StopCircle className="h-4 w-4"/>
|
||||||
</div>)}
|
Stop
|
||||||
<Button variant="destructive" onClick={onStopFetch}>
|
</Button>)}
|
||||||
<StopCircle className="h-4 w-4"/>
|
|
||||||
Stop
|
|
||||||
</Button>
|
|
||||||
</>)}
|
|
||||||
|
|
||||||
{!loading && resumeInfo?.canResume && mode === "public" && (<>
|
{!loading && resumeInfo?.canResume && mode === "public" && (<>
|
||||||
<Tooltip>
|
<Tooltip>
|
||||||
@@ -289,15 +401,26 @@ export function SearchBar({ username, loading, onUsernameChange, onFetch, onStop
|
|||||||
</TooltipTrigger>
|
</TooltipTrigger>
|
||||||
<TooltipContent>Clear Resume</TooltipContent>
|
<TooltipContent>Clear Resume</TooltipContent>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
<Button variant="secondary" onClick={handleResume} disabled={!hasAuthToken}>
|
|
||||||
|
<Button variant="secondary" onClick={handleResume}>
|
||||||
<RotateCcw className="h-4 w-4"/>
|
<RotateCcw className="h-4 w-4"/>
|
||||||
Resume ({resumeInfo.mediaCount.toLocaleString()})
|
Resume ({resumeInfo.mediaCount.toLocaleString()})
|
||||||
</Button>
|
</Button>
|
||||||
</>)}
|
</>)}
|
||||||
<Button onClick={handleFetch} disabled={loading || !hasAuthToken}>
|
|
||||||
|
<Tooltip>
|
||||||
|
<TooltipTrigger asChild>
|
||||||
|
<Button variant="outline" size="icon" onClick={() => setShowSettingsDialog(true)} disabled={loading} aria-label="Fetch settings">
|
||||||
|
<SlidersHorizontal className="h-4 w-4"/>
|
||||||
|
</Button>
|
||||||
|
</TooltipTrigger>
|
||||||
|
<TooltipContent>Fetch Settings</TooltipContent>
|
||||||
|
</Tooltip>
|
||||||
|
|
||||||
|
<Button onClick={handleFetch} disabled={loading}>
|
||||||
{loading ? (<>
|
{loading ? (<>
|
||||||
<Spinner />
|
<Spinner />
|
||||||
Fetching...
|
{fetchingLabel}
|
||||||
</>) : (<>
|
</>) : (<>
|
||||||
{isLikesMode ? <Heart className="h-4 w-4"/> : <CloudDownload className="h-4 w-4"/>}
|
{isLikesMode ? <Heart className="h-4 w-4"/> : <CloudDownload className="h-4 w-4"/>}
|
||||||
{isLikesMode ? "Fetch Likes" : "Fetch"}
|
{isLikesMode ? "Fetch Likes" : "Fetch"}
|
||||||
@@ -307,35 +430,20 @@ export function SearchBar({ username, loading, onUsernameChange, onFetch, onStop
|
|||||||
</div>
|
</div>
|
||||||
</div>)}
|
</div>)}
|
||||||
|
|
||||||
|
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
|
|
||||||
<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">
|
|
||||||
<Cookie className={cn("h-4 w-4", hasAuthToken ? "text-green-500" : "text-destructive")}/>
|
|
||||||
Auth Token
|
|
||||||
{showAuthInput ? <ChevronUp className="h-4 w-4"/> : <ChevronDown className="h-4 w-4"/>}
|
|
||||||
</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">
|
|
||||||
<SlidersHorizontal className="h-4 w-4"/>
|
|
||||||
Advanced Settings
|
|
||||||
{showAdvanced ? <ChevronUp className="h-4 w-4"/> : <ChevronDown className="h-4 w-4"/>}
|
|
||||||
</button>
|
|
||||||
|
|
||||||
|
|
||||||
{mode === "private" && fetchType === "single" && (<>
|
{mode === "private" && fetchType === "single" && (<>
|
||||||
<button type="button" onClick={() => {
|
<button type="button" onClick={() => {
|
||||||
onModeChange?.("private", "bookmarks");
|
onModeChange?.("private", "bookmarks");
|
||||||
}} className={cn("flex items-center gap-2 px-4 py-2 rounded-lg border text-sm font-medium transition-all cursor-pointer", privateType === "bookmarks"
|
}} className={cn("flex cursor-pointer items-center gap-2 rounded-lg border px-4 py-2 text-sm font-medium transition-all", privateType === "bookmarks"
|
||||||
? "border-primary bg-primary/10 text-primary"
|
? "border-primary bg-primary/10 text-primary"
|
||||||
: "border-border hover:border-primary/50")}>
|
: "border-border hover:border-primary/50")}>
|
||||||
<Bookmark className="h-4 w-4"/>
|
<Bookmark className="h-4 w-4"/>
|
||||||
My Bookmarks
|
My Bookmarks
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
<button type="button" onClick={() => {
|
<button type="button" onClick={() => {
|
||||||
onModeChange?.("private", "likes");
|
onModeChange?.("private", "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("flex cursor-pointer items-center gap-2 rounded-lg border px-4 py-2 text-sm font-medium transition-all", privateType === "likes"
|
||||||
? "border-primary bg-primary/10 text-primary"
|
? "border-primary bg-primary/10 text-primary"
|
||||||
: "border-border hover:border-primary/50")}>
|
: "border-border hover:border-primary/50")}>
|
||||||
<Heart className="h-4 w-4"/>
|
<Heart className="h-4 w-4"/>
|
||||||
@@ -343,27 +451,25 @@ export function SearchBar({ username, loading, onUsernameChange, onFetch, onStop
|
|||||||
</button>
|
</button>
|
||||||
</>)}
|
</>)}
|
||||||
|
|
||||||
|
{fetchType === "single" && isBookmarksMode && (<div className="ml-auto flex items-center gap-2">
|
||||||
|
{loading && (<Button variant="destructive" onClick={onStopFetch}>
|
||||||
|
<StopCircle className="h-4 w-4"/>
|
||||||
|
Stop
|
||||||
|
</Button>)}
|
||||||
|
|
||||||
{isBookmarksMode && (<div className="flex items-center gap-2 ml-auto">
|
<Tooltip>
|
||||||
{loading && (<>
|
<TooltipTrigger asChild>
|
||||||
|
<Button variant="outline" size="icon" onClick={() => setShowSettingsDialog(true)} disabled={loading} aria-label="Fetch settings">
|
||||||
{(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">
|
<SlidersHorizontal className="h-4 w-4"/>
|
||||||
<Clock className="h-3.5 w-3.5 text-muted-foreground shrink-0"/>
|
|
||||||
<span className="font-mono">
|
|
||||||
{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>
|
||||||
</>)}
|
</TooltipTrigger>
|
||||||
<Button onClick={handleFetch} disabled={loading || !hasAuthToken}>
|
<TooltipContent>Fetch Settings</TooltipContent>
|
||||||
|
</Tooltip>
|
||||||
|
|
||||||
|
<Button onClick={handleFetch} disabled={loading}>
|
||||||
{loading ? (<>
|
{loading ? (<>
|
||||||
<Spinner />
|
<Spinner />
|
||||||
Fetching...
|
{fetchingLabel}
|
||||||
</>) : (<>
|
</>) : (<>
|
||||||
<Bookmark className="h-4 w-4"/>
|
<Bookmark className="h-4 w-4"/>
|
||||||
Fetch Bookmarks
|
Fetch Bookmarks
|
||||||
@@ -372,120 +478,7 @@ export function SearchBar({ username, loading, onUsernameChange, onFetch, onStop
|
|||||||
</div>)}
|
</div>)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{fetchType === "multiple" && multipleAccounts.length > 0 && (<div className="rounded-lg border bg-muted/30 p-3">
|
||||||
{showAuthInput && (<div className="p-3 border rounded-lg bg-muted/30">
|
|
||||||
<div className="flex items-center gap-3">
|
|
||||||
<div className="flex items-center gap-1.5">
|
|
||||||
<Label htmlFor="auth-token" className="text-sm whitespace-nowrap">
|
|
||||||
Auth Token
|
|
||||||
</Label>
|
|
||||||
<Tooltip>
|
|
||||||
<TooltipTrigger asChild>
|
|
||||||
<Info className="h-4 w-4 text-muted-foreground cursor-help"/>
|
|
||||||
</TooltipTrigger>
|
|
||||||
<TooltipContent className="text-center">
|
|
||||||
{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>)}
|
|
||||||
</TooltipContent>
|
|
||||||
</Tooltip>
|
|
||||||
</div>
|
|
||||||
<div className="relative flex-1">
|
|
||||||
<InputWithContext id="auth-token" type={mode === "public"
|
|
||||||
? showPublicToken
|
|
||||||
? "text"
|
|
||||||
: "password"
|
|
||||||
: showPrivateToken
|
|
||||||
? "text"
|
|
||||||
: "password"} placeholder="Enter your auth_token cookie value" value={currentAuthToken} 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>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>)}
|
|
||||||
|
|
||||||
|
|
||||||
{showAdvanced && (<div className="p-3 border rounded-lg bg-muted/30 space-y-3">
|
|
||||||
|
|
||||||
<div className="flex items-center gap-4 flex-wrap">
|
|
||||||
|
|
||||||
<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">
|
|
||||||
<Label htmlFor="media-type" className="text-sm">
|
|
||||||
Media Type
|
|
||||||
</Label>
|
|
||||||
<Select value={mediaType} onValueChange={(value: SettingsMediaType) => {
|
|
||||||
updateSettings({ mediaType: value });
|
|
||||||
setMediaType(value);
|
|
||||||
}}>
|
|
||||||
<SelectTrigger id="media-type" className="w-auto h-8 bg-background">
|
|
||||||
<SelectValue />
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
<SelectItem value="all">All Media</SelectItem>
|
|
||||||
<SelectItem value="image">Images</SelectItem>
|
|
||||||
<SelectItem value="video">Videos</SelectItem>
|
|
||||||
<SelectItem value="gif">GIFs</SelectItem>
|
|
||||||
<SelectItem value="text">Text (No Media)</SelectItem>
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<Checkbox id="retweets" checked={retweets} onCheckedChange={(checked) => {
|
|
||||||
const value = checked as boolean;
|
|
||||||
updateSettings({ includeRetweets: value });
|
|
||||||
setRetweets(value);
|
|
||||||
}} className="bg-background"/>
|
|
||||||
<Label htmlFor="retweets" className="text-sm cursor-pointer">
|
|
||||||
Include Retweets
|
|
||||||
</Label>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
|
|
||||||
{mode === "public" && (<>
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<Checkbox id="date-range" checked={useDateRange} 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
|
|
||||||
</Label>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
|
|
||||||
{useDateRange && (<>
|
|
||||||
<InputWithContext id="start-date" type="date" value={startDate} onChange={(e) => setStartDate(e.target.value)} className="w-35 h-8 bg-background"/>
|
|
||||||
<span className="text-sm text-muted-foreground">-</span>
|
|
||||||
<InputWithContext id="end-date" type="date" value={endDate} onChange={(e) => setEndDate(e.target.value)} className="w-35 h-8 bg-background"/>
|
|
||||||
</>)}
|
|
||||||
</>)}
|
|
||||||
</div>
|
|
||||||
</div>)}
|
|
||||||
|
|
||||||
|
|
||||||
{fetchType === "multiple" && multipleAccounts.length > 0 && (<div className="p-3 border rounded-lg bg-muted/30">
|
|
||||||
<div className="flex items-center gap-6 text-sm">
|
<div className="flex items-center gap-6 text-sm">
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<CheckCircle className="h-4 w-4 text-green-600 dark:text-green-400"/>
|
<CheckCircle className="h-4 w-4 text-green-600 dark:text-green-400"/>
|
||||||
@@ -494,6 +487,7 @@ export function SearchBar({ username, loading, onUsernameChange, onFetch, onStop
|
|||||||
{formatNumberWithComma(multipleAccounts.filter((acc) => acc.status === "completed").length)}
|
{formatNumberWithComma(multipleAccounts.filter((acc) => acc.status === "completed").length)}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<AlertCircle className="h-4 w-4 text-yellow-600 dark:text-yellow-400"/>
|
<AlertCircle className="h-4 w-4 text-yellow-600 dark:text-yellow-400"/>
|
||||||
<span className="text-muted-foreground">Incomplete:</span>
|
<span className="text-muted-foreground">Incomplete:</span>
|
||||||
@@ -501,6 +495,7 @@ export function SearchBar({ username, loading, onUsernameChange, onFetch, onStop
|
|||||||
{formatNumberWithComma(multipleAccounts.filter((acc) => acc.status === "incomplete").length)}
|
{formatNumberWithComma(multipleAccounts.filter((acc) => acc.status === "incomplete").length)}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<XCircle className="h-4 w-4 text-red-600 dark:text-red-400"/>
|
<XCircle className="h-4 w-4 text-red-600 dark:text-red-400"/>
|
||||||
<span className="text-muted-foreground">Failed:</span>
|
<span className="text-muted-foreground">Failed:</span>
|
||||||
@@ -508,35 +503,48 @@ export function SearchBar({ username, loading, onUsernameChange, onFetch, onStop
|
|||||||
{formatNumberWithComma(multipleAccounts.filter((acc) => acc.status === "failed").length)}
|
{formatNumberWithComma(multipleAccounts.filter((acc) => acc.status === "failed").length)}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-center gap-2 ml-auto">
|
|
||||||
<span className="text-muted-foreground">Total:</span>
|
<div className="ml-auto flex items-center gap-3">
|
||||||
<span className="font-medium">
|
<div className="flex items-center gap-2">
|
||||||
{formatNumberWithComma(multipleAccounts.filter((acc) => acc.status === "completed" || acc.status === "incomplete" || acc.status === "failed").length)}/{formatNumberWithComma(multipleAccounts.length)}
|
<span className="text-muted-foreground">Total:</span>
|
||||||
</span>
|
<span className="font-medium">
|
||||||
|
{formatNumberWithComma(multipleAccounts.filter((acc) => acc.status === "completed" || acc.status === "incomplete" || acc.status === "failed").length)}/{formatNumberWithComma(multipleAccounts.length)}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
{!isFetchingAll && onOpenSavedAccounts && multipleAccounts.some((acc) => acc.status === "completed" || acc.status === "incomplete") && (<Button variant="secondary" size="sm" onClick={onOpenSavedAccounts} className="flex items-center gap-2">
|
||||||
|
<Database className="h-3.5 w-3.5"/>
|
||||||
|
Open Saved Accounts to Download
|
||||||
|
</Button>)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>)}
|
</div>)}
|
||||||
|
|
||||||
|
|
||||||
{fetchType === "multiple" && multipleAccounts.length > 0 && (<div className="space-y-2">
|
{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="flex items-center justify-between gap-2">
|
||||||
<div className="space-y-2 max-h-100 overflow-y-auto">
|
<p className="text-sm text-muted-foreground">Accounts to Fetch ({formatNumberWithComma(multipleAccounts.length)})</p>
|
||||||
{multipleAccounts.map((account) => (<div key={account.id} className="p-3 border rounded-lg bg-card">
|
<Button variant="outline" size="sm" onClick={onClearMultipleAccounts} disabled={isFetchingAll || isAnyMultipleAccountFetching} className="flex items-center gap-2">
|
||||||
|
<Trash2 className="h-4 w-4"/>
|
||||||
|
Clear List
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
<div className="max-h-100 space-y-2 overflow-y-auto">
|
||||||
|
{multipleAccounts.map((account) => (<div key={account.id} className="rounded-lg border bg-card p-3">
|
||||||
<div className="flex items-center gap-3">
|
<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">
|
{account.accountInfo ? (<img src={account.accountInfo.profile_image} alt={account.accountInfo.nick} className="h-10 w-10 rounded-full"/>) : (<div className="flex h-10 w-10 items-center justify-center rounded-full bg-muted">
|
||||||
<User className="h-5 w-5 text-muted-foreground"/>
|
<User className="h-5 w-5 text-muted-foreground"/>
|
||||||
</div>)}
|
</div>)}
|
||||||
<div className="flex-1 min-w-0">
|
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
{account.accountInfo ? (<>
|
{account.accountInfo ? (<>
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<span className="font-medium">{account.accountInfo.nick}</span>
|
<span className="font-medium">{account.accountInfo.nick}</span>
|
||||||
<span className="text-sm text-muted-foreground">@{account.accountInfo.name}</span>
|
<span className="text-sm text-muted-foreground">@{account.accountInfo.name}</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-center gap-2 mt-1">
|
<div className="mt-1 flex items-center gap-2">
|
||||||
<span className="text-sm text-muted-foreground">
|
<span className="text-sm text-muted-foreground">
|
||||||
<span className="text-primary">{account.mediaCount.toLocaleString()}</span> items found
|
<span className="text-primary">{account.mediaCount.toLocaleString()}</span> items found
|
||||||
</span>
|
</span>
|
||||||
{account.showDiff && account.previousMediaCount > 0 && account.mediaCount > account.previousMediaCount && (<span className="text-sm text-green-600 dark:text-green-400 font-medium">
|
{account.showDiff && account.previousMediaCount > 0 && account.mediaCount > account.previousMediaCount && (<span className="text-sm font-medium text-green-600 dark:text-green-400">
|
||||||
+{account.mediaCount - account.previousMediaCount}
|
+{account.mediaCount - account.previousMediaCount}
|
||||||
</span>)}
|
</span>)}
|
||||||
</div>
|
</div>
|
||||||
@@ -544,10 +552,11 @@ export function SearchBar({ username, loading, onUsernameChange, onFetch, onStop
|
|||||||
<span className="font-medium">@{account.username}</span>
|
<span className="font-medium">@{account.username}</span>
|
||||||
</div>)}
|
</div>)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
{account.status === "fetching" && (<>
|
{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">
|
<div className="flex w-21.25 items-center gap-1.5 rounded-md border bg-muted/50 px-3 py-1.5 text-sm">
|
||||||
<Clock className="h-3.5 w-3.5 text-muted-foreground shrink-0"/>
|
<Clock className="h-3.5 w-3.5 shrink-0 text-muted-foreground"/>
|
||||||
<span className="font-mono">
|
<span className="font-mono">
|
||||||
{account.remainingTime !== null && account.remainingTime >= 0
|
{account.remainingTime !== null && account.remainingTime >= 0
|
||||||
? formatTime(account.remainingTime)
|
? formatTime(account.remainingTime)
|
||||||
@@ -559,34 +568,43 @@ export function SearchBar({ username, loading, onUsernameChange, onFetch, onStop
|
|||||||
Stop
|
Stop
|
||||||
</Button>
|
</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">
|
|
||||||
|
{account.status === "pending" && (<span className="flex items-center gap-1.5 rounded bg-gray-500/20 px-2 py-1 text-xs text-gray-600 dark:text-gray-400">
|
||||||
<Hourglass className="h-3 w-3"/>
|
<Hourglass className="h-3 w-3"/>
|
||||||
Pending
|
Pending
|
||||||
</span>)}
|
</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">
|
|
||||||
|
{account.status === "completed" && (<span className="flex items-center gap-1.5 rounded bg-green-500/20 px-2 py-1 text-xs text-green-600 dark:text-green-400">
|
||||||
<CheckCircle className="h-3 w-3"/>
|
<CheckCircle className="h-3 w-3"/>
|
||||||
Completed
|
Completed
|
||||||
</span>)}
|
</span>)}
|
||||||
|
|
||||||
{account.status === "incomplete" && (<>
|
{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">
|
<span className="flex items-center gap-1.5 rounded bg-yellow-500/20 px-2 py-1 text-xs text-yellow-600 dark:text-yellow-400">
|
||||||
<AlertCircle className="h-3 w-3"/>
|
<AlertCircle className="h-3 w-3"/>
|
||||||
Incomplete
|
Incomplete
|
||||||
</span>
|
</span>
|
||||||
<Button variant="outline" size="sm" onClick={() => onRetryAccount?.(account.id, publicAuthToken)} disabled={isFetchingAll} className="flex items-center gap-2">
|
<Button variant="outline" size="sm" onClick={() => handleRetry(account.id)} disabled={isFetchingAll} className="flex items-center gap-2">
|
||||||
<RotateCcw className="h-3.5 w-3.5"/>
|
<RotateCcw className="h-3.5 w-3.5"/>
|
||||||
Retry
|
Retry
|
||||||
</Button>
|
</Button>
|
||||||
</>)}
|
</>)}
|
||||||
|
|
||||||
{account.status === "failed" && (<>
|
{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">
|
<span className="flex items-center gap-1.5 rounded bg-red-500/20 px-2 py-1 text-xs text-red-600 dark:text-red-400">
|
||||||
<XCircle className="h-3 w-3"/>
|
<XCircle className="h-3 w-3"/>
|
||||||
Failed
|
Failed
|
||||||
</span>
|
</span>
|
||||||
<Button variant="outline" size="sm" onClick={() => onRetryAccount?.(account.id, publicAuthToken)} disabled={isFetchingAll} className="flex items-center gap-2">
|
<Button variant="outline" size="sm" onClick={() => handleRetry(account.id)} disabled={isFetchingAll} className="flex items-center gap-2">
|
||||||
<RotateCcw className="h-3.5 w-3.5"/>
|
<RotateCcw className="h-3.5 w-3.5"/>
|
||||||
Retry
|
Retry
|
||||||
</Button>
|
</Button>
|
||||||
</>)}
|
</>)}
|
||||||
|
|
||||||
|
<Button variant="outline" size="sm" onClick={() => onRemoveMultipleAccount?.(account.id)} disabled={isFetchingAll || account.status === "fetching"} className="flex items-center gap-2">
|
||||||
|
<Trash2 className="h-3.5 w-3.5"/>
|
||||||
|
Delete
|
||||||
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>))}
|
</div>))}
|
||||||
@@ -594,5 +612,161 @@ export function SearchBar({ username, loading, onUsernameChange, onFetch, onStop
|
|||||||
</div>)}
|
</div>)}
|
||||||
|
|
||||||
{!hasResult && mode === "public" && fetchType === "single" && (<FetchHistory history={history} onSelect={onHistorySelect} onRemove={onHistoryRemove}/>)}
|
{!hasResult && mode === "public" && fetchType === "single" && (<FetchHistory history={history} onSelect={onHistorySelect} onRemove={onHistoryRemove}/>)}
|
||||||
|
|
||||||
|
<Dialog open={showImportDialog} onOpenChange={setShowImportDialog}>
|
||||||
|
<DialogContent className="sm:max-w-xl">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>Input Account List</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
Enter one username or URL per line. Commas and semicolons also work.
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
|
||||||
|
<textarea value={importAccountsText} onChange={(e) => setImportAccountsText(e.target.value)} placeholder={"masteraoko\nxbatchdemo\nhttps://x.com/takomayuyi"} className="border-input placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 min-h-64 w-full rounded-md border bg-transparent px-3 py-2 text-sm shadow-xs outline-none focus-visible:ring-[3px]"/>
|
||||||
|
|
||||||
|
<DialogFooter>
|
||||||
|
<Button variant="outline" onClick={() => setShowImportDialog(false)}>Cancel</Button>
|
||||||
|
<Button onClick={handleImportSubmit}>Import Accounts</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
|
||||||
|
<Dialog open={showAuthRequiredDialog} onOpenChange={closeAuthRequiredDialog}>
|
||||||
|
<DialogContent className="sm:max-w-xl">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>Cookie Required</DialogTitle>
|
||||||
|
</DialogHeader>
|
||||||
|
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="required-auth-token">Auth Token</Label>
|
||||||
|
<div className="relative">
|
||||||
|
<InputWithContext id="required-auth-token" type={showAuthToken ? "text" : "password"} placeholder="Enter your auth_token cookie value" value={authPromptToken} onChange={(e) => setAuthPromptToken(e.target.value)} onKeyDown={(e) => {
|
||||||
|
if (e.key === "Enter") {
|
||||||
|
handleAuthPromptSubmit();
|
||||||
|
}
|
||||||
|
}} className="pr-10"/>
|
||||||
|
<button type="button" aria-label={showAuthToken ? "Hide auth token" : "Show auth token"} className="absolute top-1/2 right-2 -translate-y-1/2 text-muted-foreground transition-colors hover:text-foreground" onClick={() => setShowAuthToken((prev) => !prev)}>
|
||||||
|
{showAuthToken ? <EyeOff className="h-4 w-4"/> : <Eye className="h-4 w-4"/>}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-3 rounded-lg border bg-muted/30 p-4 text-sm">
|
||||||
|
<p>
|
||||||
|
Tutorial:
|
||||||
|
{" "}
|
||||||
|
<a href="https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader#how-to-obtain-auth-token" target="_blank" rel="noreferrer" className="font-medium underline underline-offset-4">
|
||||||
|
afkarxyz/Twitter-X-Media-Batch-Downloader
|
||||||
|
</a>
|
||||||
|
</p>
|
||||||
|
<ol className="list-decimal space-y-1 pl-5 text-muted-foreground">
|
||||||
|
<li>
|
||||||
|
Go to
|
||||||
|
{" "}
|
||||||
|
<a href="https://www.x.com/" target="_blank" rel="noreferrer" className="underline underline-offset-4">
|
||||||
|
Twitter's website
|
||||||
|
</a>
|
||||||
|
</li>
|
||||||
|
<li>Log into your account</li>
|
||||||
|
<li>
|
||||||
|
Open the Developer Tools by pressing
|
||||||
|
{" "}
|
||||||
|
<kbd className="rounded border bg-background px-1.5 py-0.5 font-mono text-xs">F12</kbd>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
Navigate to the Application tab, then select Storage {"->"} Cookies
|
||||||
|
</li>
|
||||||
|
<li>Find and copy the <code>auth_token</code> value</li>
|
||||||
|
<li>Do not log out of your account, as a new <code>auth_token</code> will be generated by Twitter</li>
|
||||||
|
</ol>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<DialogFooter>
|
||||||
|
<Button variant="outline" onClick={handleOpenFetchSettings}>Open Fetch Settings</Button>
|
||||||
|
<Button variant="outline" onClick={() => closeAuthRequiredDialog(false)}>Cancel</Button>
|
||||||
|
<Button onClick={handleAuthPromptSubmit}>Save and Continue</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
|
||||||
|
<Dialog open={showSettingsDialog} onOpenChange={setShowSettingsDialog}>
|
||||||
|
<DialogContent className="sm:max-w-xl max-h-[85vh] flex flex-col overflow-hidden">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>Fetch Settings</DialogTitle>
|
||||||
|
</DialogHeader>
|
||||||
|
|
||||||
|
<div className="space-y-4 overflow-y-auto flex-1 min-h-0 -mx-2 px-2">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Label htmlFor="shared-auth-token" className="text-sm">Auth Token</Label>
|
||||||
|
<Tooltip>
|
||||||
|
<TooltipTrigger asChild>
|
||||||
|
<Info className="h-4 w-4 cursor-help text-muted-foreground"/>
|
||||||
|
</TooltipTrigger>
|
||||||
|
<TooltipContent className="max-w-sm">
|
||||||
|
<p className="text-sm">{authTokenHelpText}</p>
|
||||||
|
</TooltipContent>
|
||||||
|
</Tooltip>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<InputWithContext id="shared-auth-token" type="text" placeholder="Enter your auth_token cookie value" value={sharedAuthToken} onChange={(e) => void handleSharedTokenChange(e.target.value)}/>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{fetchType === "single" && (<div className="flex items-center justify-between gap-4">
|
||||||
|
<Label htmlFor="retweets" className="cursor-pointer text-sm">Include Reposts</Label>
|
||||||
|
<Checkbox id="retweets" checked={retweets} onCheckedChange={(checked) => {
|
||||||
|
const value = checked as boolean;
|
||||||
|
updateSettings({ includeRetweets: value });
|
||||||
|
setRetweets(value);
|
||||||
|
}}/>
|
||||||
|
</div>)}
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label className="text-sm">Include Media</Label>
|
||||||
|
<div className="grid grid-cols-4 gap-2">
|
||||||
|
<button type="button" className={pillClass(includePhotos)} onClick={() => { updateSettings({ includePhotos: !includePhotos }); setIncludePhotos((v) => !v); }}>Photos</button>
|
||||||
|
<button type="button" className={pillClass(includeVideos)} onClick={() => { updateSettings({ includeVideos: !includeVideos }); setIncludeVideos((v) => !v); }}>Videos</button>
|
||||||
|
<button type="button" className={pillClass(includeGifs)} onClick={() => { updateSettings({ includeGifs: !includeGifs }); setIncludeGifs((v) => !v); }}>GIFs</button>
|
||||||
|
<button type="button" className={pillClass(includeText)} onClick={() => { updateSettings({ includeText: !includeText }); setIncludeText((v) => !v); }}>Text</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label className="text-sm">Video Quality</Label>
|
||||||
|
<div className="grid grid-cols-5 gap-2">
|
||||||
|
{VIDEO_QUALITIES.map((q) => (<button key={q.value} type="button" className={pillClass(videoQuality === q.value)} onClick={() => { updateSettings({ videoQuality: q.value }); setVideoQuality(q.value); }}>{q.label}</button>))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label className="text-sm">Image Size</Label>
|
||||||
|
<div className="grid grid-cols-4 gap-2">
|
||||||
|
{IMAGE_SIZES.map((s) => (<button key={s.value} type="button" className={pillClass(imageSize === s.value)} onClick={() => { updateSettings({ imageSize: s.value }); setImageSize(s.value); }}>{s.label}</button>))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label className="text-sm">Avatar Size</Label>
|
||||||
|
<div className="grid grid-cols-5 gap-2">
|
||||||
|
{AVATAR_SIZES.map((s) => (<button key={s.value} type="button" className={pillClass(avatarSize === s.value)} onClick={() => { updateSettings({ avatarSize: s.value }); setAvatarSize(s.value); }}>{s.label}</button>))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label className="text-sm">Banner Size</Label>
|
||||||
|
<div className="grid grid-cols-4 gap-2">
|
||||||
|
{BANNER_SIZES.map((s) => (<button key={s.value} type="button" className={pillClass(bannerSize === s.value)} onClick={() => { updateSettings({ bannerSize: s.value }); setBannerSize(s.value); }}>{s.label}</button>))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<DialogFooter>
|
||||||
|
<Button onClick={() => setShowSettingsDialog(false)}>Done</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
</div>);
|
</div>);
|
||||||
}
|
}
|
||||||
@@ -6,31 +6,28 @@ import { InputWithContext } from "@/components/ui/input-with-context";
|
|||||||
import { Label } from "@/components/ui/label";
|
import { Label } from "@/components/ui/label";
|
||||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select";
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select";
|
||||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
||||||
import { Check, Download, ExternalLink, FolderOpen, Info, MonitorCog, PackageSearch, Plus, RotateCcw, Save, Trash2 } from "lucide-react";
|
import { Check, Download, ExternalLink, FolderOpen, Info, MonitorCog, PackageSearch, Plus, RotateCcw, Save, Trash2, FileSignature } from "lucide-react";
|
||||||
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from "@/components/ui/dialog";
|
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from "@/components/ui/dialog";
|
||||||
import { Spinner } from "@/components/ui/spinner";
|
import { Spinner } from "@/components/ui/spinner";
|
||||||
import { Switch } from "@/components/ui/switch";
|
import { Switch } from "@/components/ui/switch";
|
||||||
import { getSettings, getSettingsWithDefaults, saveSettings, resetToDefaultSettings, applyThemeMode, applyFont, getFontOptions, parseGoogleFontUrl, loadGoogleFontUrl, loadCustomFonts, saveCustomFonts, type Settings as SettingsType, type FontFamily, type GifQuality, type GifResolution, type CustomFontFamily } from "@/lib/settings";
|
import { getSettings, getSettingsWithDefaults, saveSettings, resetToDefaultSettings, applyThemeMode, applyFont, getFontOptions, parseGoogleFontUrl, loadGoogleFontUrl, loadCustomFonts, saveCustomFonts, DEFAULT_FILENAME_TEMPLATE, FILENAME_TEMPLATE_VARIABLES, renderFilenameTemplate, SAMPLE_FILENAME_DATA, DEFAULT_FOLDER_TEMPLATE, FOLDER_TEMPLATE_VARIABLES, renderFolderTemplate, SAMPLE_FOLDER_DATA, type Settings as SettingsType, type FontFamily, type GifQuality, type GifResolution, type CustomFontFamily } from "@/lib/settings";
|
||||||
|
import { FormatEditor } from "@/components/FormatEditor";
|
||||||
import { getCachedDependencyStatus, setCachedDependencyStatus } from "@/lib/runtime-cache";
|
import { getCachedDependencyStatus, setCachedDependencyStatus } from "@/lib/runtime-cache";
|
||||||
import { themes, applyTheme } from "@/lib/themes";
|
import { themes, applyTheme } from "@/lib/themes";
|
||||||
import { compareVersionNumbers } from "@/lib/version";
|
import { compareVersionNumbers } from "@/lib/version";
|
||||||
import { SelectFolder, IsExtractorInstalled, DownloadExtractor, IsFFmpegInstalled, DownloadFFmpeg, IsExifToolInstalled, DownloadExifTool } from "../../wailsjs/go/main/App";
|
import { SelectFolder, IsExtractorInstalled, DownloadExtractor, IsFFmpegInstalled, DownloadFFmpeg, IsExifToolInstalled, DownloadExifTool } from "../../wailsjs/go/main/App";
|
||||||
import { toastWithSound as toast } from "@/lib/toast-with-sound";
|
import { toastWithSound as toast } from "@/lib/toast-with-sound";
|
||||||
|
|
||||||
interface DependencyVersionStatus {
|
interface DependencyVersionStatus {
|
||||||
installed: boolean;
|
installed: boolean;
|
||||||
installed_version?: string;
|
installed_version?: string;
|
||||||
latest_version?: string;
|
latest_version?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
type DependencyVersionMethod = "GetExtractorVersionStatus" | "GetFFmpegVersionStatus" | "GetExifToolVersionStatus";
|
type DependencyVersionMethod = "GetExtractorVersionStatus" | "GetFFmpegVersionStatus" | "GetExifToolVersionStatus";
|
||||||
type SettingsTab = "general" | "dependencies";
|
type SettingsTab = "general" | "downloads" | "naming" | "dependencies";
|
||||||
|
|
||||||
interface SettingsPageProps {
|
interface SettingsPageProps {
|
||||||
onUnsavedChangesChange?: (hasUnsavedChanges: boolean) => void;
|
onUnsavedChangesChange?: (hasUnsavedChanges: boolean) => void;
|
||||||
onResetRequest?: (resetFn: () => void) => void;
|
onResetRequest?: (resetFn: () => void) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
function getDependencyVersionStatus(methodName: DependencyVersionMethod) {
|
function getDependencyVersionStatus(methodName: DependencyVersionMethod) {
|
||||||
const app = (window as Window & {
|
const app = (window as Window & {
|
||||||
go?: {
|
go?: {
|
||||||
@@ -42,14 +39,12 @@ function getDependencyVersionStatus(methodName: DependencyVersionMethod) {
|
|||||||
const method = app?.[methodName];
|
const method = app?.[methodName];
|
||||||
return method ? method() : Promise.resolve(null);
|
return method ? method() : Promise.resolve(null);
|
||||||
}
|
}
|
||||||
|
|
||||||
function hasNewDependencyVersion(installedVersion: string | null, latestVersion: string | null) {
|
function hasNewDependencyVersion(installedVersion: string | null, latestVersion: string | null) {
|
||||||
if (!installedVersion || !latestVersion) {
|
if (!installedVersion || !latestVersion) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
return compareVersionNumbers(latestVersion, installedVersion) > 0;
|
return compareVersionNumbers(latestVersion, installedVersion) > 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
function buildDependencyVersionText(name: string, installed: boolean, installedVersion: string | null, latestVersion: string | null, updateAvailable: boolean) {
|
function buildDependencyVersionText(name: string, installed: boolean, installedVersion: string | null, latestVersion: string | null, updateAvailable: boolean) {
|
||||||
if (installed) {
|
if (installed) {
|
||||||
if (!installedVersion) {
|
if (!installedVersion) {
|
||||||
@@ -61,7 +56,6 @@ function buildDependencyVersionText(name: string, installed: boolean, installedV
|
|||||||
}
|
}
|
||||||
return latestVersion ? `Latest ${name}: ${latestVersion}` : null;
|
return latestVersion ? `Latest ${name}: ${latestVersion}` : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function SettingsPage({ onUnsavedChangesChange, onResetRequest }: SettingsPageProps) {
|
export function SettingsPage({ onUnsavedChangesChange, onResetRequest }: SettingsPageProps) {
|
||||||
const cachedExtractorStatus = getCachedDependencyStatus("extractor");
|
const cachedExtractorStatus = getCachedDependencyStatus("extractor");
|
||||||
const cachedFfmpegStatus = getCachedDependencyStatus("ffmpeg");
|
const cachedFfmpegStatus = getCachedDependencyStatus("ffmpeg");
|
||||||
@@ -85,14 +79,12 @@ export function SettingsPage({ onUnsavedChangesChange, onResetRequest }: Setting
|
|||||||
const [exiftoolLatestVersion, setExiftoolLatestVersion] = useState<string | null>(cachedExiftoolStatus.latestVersion);
|
const [exiftoolLatestVersion, setExiftoolLatestVersion] = useState<string | null>(cachedExiftoolStatus.latestVersion);
|
||||||
const [downloadingExifTool, setDownloadingExifTool] = useState(false);
|
const [downloadingExifTool, setDownloadingExifTool] = useState(false);
|
||||||
const [showResetConfirm, setShowResetConfirm] = useState(false);
|
const [showResetConfirm, setShowResetConfirm] = useState(false);
|
||||||
|
|
||||||
const extractorUpdateAvailable = hasNewDependencyVersion(extractorInstalledVersion, extractorLatestVersion);
|
const extractorUpdateAvailable = hasNewDependencyVersion(extractorInstalledVersion, extractorLatestVersion);
|
||||||
const ffmpegUpdateAvailable = hasNewDependencyVersion(ffmpegInstalledVersion, ffmpegLatestVersion);
|
const ffmpegUpdateAvailable = hasNewDependencyVersion(ffmpegInstalledVersion, ffmpegLatestVersion);
|
||||||
const exiftoolUpdateAvailable = hasNewDependencyVersion(exiftoolInstalledVersion, exiftoolLatestVersion);
|
const exiftoolUpdateAvailable = hasNewDependencyVersion(exiftoolInstalledVersion, exiftoolLatestVersion);
|
||||||
const parsedAddFont = parseGoogleFontUrl(addFontUrl);
|
const parsedAddFont = parseGoogleFontUrl(addFontUrl);
|
||||||
const fontOptions = getFontOptions(tempSettings.customFonts);
|
const fontOptions = getFontOptions(tempSettings.customFonts);
|
||||||
const hasUnsavedChanges = JSON.stringify(savedSettings) !== JSON.stringify(tempSettings);
|
const hasUnsavedChanges = JSON.stringify(savedSettings) !== JSON.stringify(tempSettings);
|
||||||
|
|
||||||
const resetToSaved = useCallback(() => {
|
const resetToSaved = useCallback(() => {
|
||||||
const freshSavedSettings = getSettings();
|
const freshSavedSettings = getSettings();
|
||||||
flushSync(() => {
|
flushSync(() => {
|
||||||
@@ -100,17 +92,14 @@ export function SettingsPage({ onUnsavedChangesChange, onResetRequest }: Setting
|
|||||||
setIsDark(document.documentElement.classList.contains("dark"));
|
setIsDark(document.documentElement.classList.contains("dark"));
|
||||||
});
|
});
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (onResetRequest) {
|
if (onResetRequest) {
|
||||||
onResetRequest(resetToSaved);
|
onResetRequest(resetToSaved);
|
||||||
}
|
}
|
||||||
}, [onResetRequest, resetToSaved]);
|
}, [onResetRequest, resetToSaved]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
onUnsavedChangesChange?.(hasUnsavedChanges);
|
onUnsavedChangesChange?.(hasUnsavedChanges);
|
||||||
}, [hasUnsavedChanges, onUnsavedChangesChange]);
|
}, [hasUnsavedChanges, onUnsavedChangesChange]);
|
||||||
|
|
||||||
const extractorVersionText = extractorInstalled
|
const extractorVersionText = extractorInstalled
|
||||||
? extractorInstalledVersion
|
? extractorInstalledVersion
|
||||||
? extractorUpdateAvailable && extractorLatestVersion
|
? extractorUpdateAvailable && extractorLatestVersion
|
||||||
@@ -120,10 +109,8 @@ export function SettingsPage({ onUnsavedChangesChange, onResetRequest }: Setting
|
|||||||
: extractorLatestVersion
|
: extractorLatestVersion
|
||||||
? `Latest: ${extractorLatestVersion}`
|
? `Latest: ${extractorLatestVersion}`
|
||||||
: null;
|
: null;
|
||||||
|
|
||||||
const ffmpegVersionText = buildDependencyVersionText("FFmpeg", ffmpegInstalled, ffmpegInstalledVersion, ffmpegLatestVersion, ffmpegUpdateAvailable);
|
const ffmpegVersionText = buildDependencyVersionText("FFmpeg", ffmpegInstalled, ffmpegInstalledVersion, ffmpegLatestVersion, ffmpegUpdateAvailable);
|
||||||
const exiftoolVersionText = buildDependencyVersionText("ExifTool", exiftoolInstalled, exiftoolInstalledVersion, exiftoolLatestVersion, exiftoolUpdateAvailable);
|
const exiftoolVersionText = buildDependencyVersionText("ExifTool", exiftoolInstalled, exiftoolInstalledVersion, exiftoolLatestVersion, exiftoolUpdateAvailable);
|
||||||
|
|
||||||
const loadDependencyStatus = async () => {
|
const loadDependencyStatus = async () => {
|
||||||
try {
|
try {
|
||||||
const [extractorVersionStatus, ffmpegVersionStatus, exiftoolVersionStatus, extractor, ffmpeg, exiftool] = await Promise.all([
|
const [extractorVersionStatus, ffmpegVersionStatus, exiftoolVersionStatus, extractor, ffmpeg, exiftool] = await Promise.all([
|
||||||
@@ -143,7 +130,6 @@ export function SettingsPage({ onUnsavedChangesChange, onResetRequest }: Setting
|
|||||||
const nextExiftoolInstalled = exiftoolVersionStatus?.installed ?? exiftool;
|
const nextExiftoolInstalled = exiftoolVersionStatus?.installed ?? exiftool;
|
||||||
const nextExiftoolInstalledVersion = exiftoolVersionStatus?.installed_version?.trim() || null;
|
const nextExiftoolInstalledVersion = exiftoolVersionStatus?.installed_version?.trim() || null;
|
||||||
const nextExiftoolLatestVersion = exiftoolVersionStatus?.latest_version?.trim() || null;
|
const nextExiftoolLatestVersion = exiftoolVersionStatus?.latest_version?.trim() || null;
|
||||||
|
|
||||||
setCachedDependencyStatus("extractor", {
|
setCachedDependencyStatus("extractor", {
|
||||||
installed: nextExtractorInstalled,
|
installed: nextExtractorInstalled,
|
||||||
installedVersion: nextExtractorInstalledVersion,
|
installedVersion: nextExtractorInstalledVersion,
|
||||||
@@ -159,7 +145,6 @@ export function SettingsPage({ onUnsavedChangesChange, onResetRequest }: Setting
|
|||||||
installedVersion: nextExiftoolInstalledVersion,
|
installedVersion: nextExiftoolInstalledVersion,
|
||||||
latestVersion: nextExiftoolLatestVersion,
|
latestVersion: nextExiftoolLatestVersion,
|
||||||
});
|
});
|
||||||
|
|
||||||
setExtractorInstalled(nextExtractorInstalled);
|
setExtractorInstalled(nextExtractorInstalled);
|
||||||
setExtractorInstalledVersion(nextExtractorInstalledVersion);
|
setExtractorInstalledVersion(nextExtractorInstalledVersion);
|
||||||
setExtractorLatestVersion(nextExtractorLatestVersion);
|
setExtractorLatestVersion(nextExtractorLatestVersion);
|
||||||
@@ -174,7 +159,6 @@ export function SettingsPage({ onUnsavedChangesChange, onResetRequest }: Setting
|
|||||||
console.error("Failed to check dependency status:", error);
|
console.error("Failed to check dependency status:", error);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
applyThemeMode(savedSettings.themeMode);
|
applyThemeMode(savedSettings.themeMode);
|
||||||
applyTheme(savedSettings.theme);
|
applyTheme(savedSettings.theme);
|
||||||
@@ -188,7 +172,6 @@ export function SettingsPage({ onUnsavedChangesChange, onResetRequest }: Setting
|
|||||||
mediaQuery.addEventListener("change", handleChange);
|
mediaQuery.addEventListener("change", handleChange);
|
||||||
return () => mediaQuery.removeEventListener("change", handleChange);
|
return () => mediaQuery.removeEventListener("change", handleChange);
|
||||||
}, [savedSettings.themeMode, savedSettings.theme]);
|
}, [savedSettings.themeMode, savedSettings.theme]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
applyThemeMode(tempSettings.themeMode);
|
applyThemeMode(tempSettings.themeMode);
|
||||||
applyTheme(tempSettings.theme);
|
applyTheme(tempSettings.theme);
|
||||||
@@ -197,13 +180,11 @@ export function SettingsPage({ onUnsavedChangesChange, onResetRequest }: Setting
|
|||||||
setIsDark(document.documentElement.classList.contains("dark"));
|
setIsDark(document.documentElement.classList.contains("dark"));
|
||||||
}, 0);
|
}, 0);
|
||||||
}, [tempSettings.themeMode, tempSettings.theme, tempSettings.fontFamily, tempSettings.customFonts]);
|
}, [tempSettings.themeMode, tempSettings.theme, tempSettings.fontFamily, tempSettings.customFonts]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (showAddFontDialog && parsedAddFont) {
|
if (showAddFontDialog && parsedAddFont) {
|
||||||
loadGoogleFontUrl(parsedAddFont.url, "twitter-media-add-font-preview");
|
loadGoogleFontUrl(parsedAddFont.url, "twitter-media-add-font-preview");
|
||||||
}
|
}
|
||||||
}, [showAddFontDialog, parsedAddFont]);
|
}, [showAddFontDialog, parsedAddFont]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const loadDefaults = async () => {
|
const loadDefaults = async () => {
|
||||||
if (!savedSettings.downloadPath) {
|
if (!savedSettings.downloadPath) {
|
||||||
@@ -215,7 +196,6 @@ export function SettingsPage({ onUnsavedChangesChange, onResetRequest }: Setting
|
|||||||
void loadDefaults();
|
void loadDefaults();
|
||||||
void loadDependencyStatus();
|
void loadDependencyStatus();
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const syncCustomFonts = async () => {
|
const syncCustomFonts = async () => {
|
||||||
const customFonts = await loadCustomFonts();
|
const customFonts = await loadCustomFonts();
|
||||||
@@ -224,14 +204,12 @@ export function SettingsPage({ onUnsavedChangesChange, onResetRequest }: Setting
|
|||||||
};
|
};
|
||||||
void syncCustomFonts();
|
void syncCustomFonts();
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const handleSave = () => {
|
const handleSave = () => {
|
||||||
saveSettings(tempSettings);
|
saveSettings(tempSettings);
|
||||||
setSavedSettings(tempSettings);
|
setSavedSettings(tempSettings);
|
||||||
toast.success("Settings saved");
|
toast.success("Settings saved");
|
||||||
onUnsavedChangesChange?.(false);
|
onUnsavedChangesChange?.(false);
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleReset = async () => {
|
const handleReset = async () => {
|
||||||
const defaultSettings = await resetToDefaultSettings();
|
const defaultSettings = await resetToDefaultSettings();
|
||||||
setTempSettings(defaultSettings);
|
setTempSettings(defaultSettings);
|
||||||
@@ -242,7 +220,6 @@ export function SettingsPage({ onUnsavedChangesChange, onResetRequest }: Setting
|
|||||||
setShowResetConfirm(false);
|
setShowResetConfirm(false);
|
||||||
toast.success("Settings reset to default");
|
toast.success("Settings reset to default");
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleBrowseFolder = async () => {
|
const handleBrowseFolder = async () => {
|
||||||
try {
|
try {
|
||||||
const selectedPath = await SelectFolder(tempSettings.downloadPath || "");
|
const selectedPath = await SelectFolder(tempSettings.downloadPath || "");
|
||||||
@@ -255,12 +232,10 @@ export function SettingsPage({ onUnsavedChangesChange, onResetRequest }: Setting
|
|||||||
toast.error(`Error selecting folder: ${error}`);
|
toast.error(`Error selecting folder: ${error}`);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const closeAddFontDialog = () => {
|
const closeAddFontDialog = () => {
|
||||||
setShowAddFontDialog(false);
|
setShowAddFontDialog(false);
|
||||||
setAddFontUrl("");
|
setAddFontUrl("");
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleAddFont = async () => {
|
const handleAddFont = async () => {
|
||||||
if (!parsedAddFont) {
|
if (!parsedAddFont) {
|
||||||
toast.error("Enter a valid Google Fonts URL");
|
toast.error("Enter a valid Google Fonts URL");
|
||||||
@@ -281,7 +256,6 @@ export function SettingsPage({ onUnsavedChangesChange, onResetRequest }: Setting
|
|||||||
closeAddFontDialog();
|
closeAddFontDialog();
|
||||||
toast.success(`${parsedAddFont.label} added`);
|
toast.success(`${parsedAddFont.label} added`);
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleDeleteCustomFont = async (fontValue: CustomFontFamily) => {
|
const handleDeleteCustomFont = async (fontValue: CustomFontFamily) => {
|
||||||
const customFonts = (tempSettings.customFonts || []).filter((font) => font.value !== fontValue);
|
const customFonts = (tempSettings.customFonts || []).filter((font) => font.value !== fontValue);
|
||||||
const savedCustomFonts = await saveCustomFonts(customFonts);
|
const savedCustomFonts = await saveCustomFonts(customFonts);
|
||||||
@@ -303,7 +277,6 @@ export function SettingsPage({ onUnsavedChangesChange, onResetRequest }: Setting
|
|||||||
}
|
}
|
||||||
toast.success("Font deleted");
|
toast.success("Font deleted");
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleDownloadExtractor = async () => {
|
const handleDownloadExtractor = async () => {
|
||||||
setDownloadingExtractor(true);
|
setDownloadingExtractor(true);
|
||||||
try {
|
try {
|
||||||
@@ -324,7 +297,6 @@ export function SettingsPage({ onUnsavedChangesChange, onResetRequest }: Setting
|
|||||||
setDownloadingExtractor(false);
|
setDownloadingExtractor(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleDownloadFFmpeg = async () => {
|
const handleDownloadFFmpeg = async () => {
|
||||||
setDownloadingFFmpeg(true);
|
setDownloadingFFmpeg(true);
|
||||||
try {
|
try {
|
||||||
@@ -345,7 +317,6 @@ export function SettingsPage({ onUnsavedChangesChange, onResetRequest }: Setting
|
|||||||
setDownloadingFFmpeg(false);
|
setDownloadingFFmpeg(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleDownloadExifTool = async () => {
|
const handleDownloadExifTool = async () => {
|
||||||
setDownloadingExifTool(true);
|
setDownloadingExifTool(true);
|
||||||
try {
|
try {
|
||||||
@@ -366,7 +337,6 @@ export function SettingsPage({ onUnsavedChangesChange, onResetRequest }: Setting
|
|||||||
setDownloadingExifTool(false);
|
setDownloadingExifTool(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
return (<div className="space-y-4">
|
return (<div className="space-y-4">
|
||||||
<div className="flex items-center justify-between">
|
<div className="flex items-center justify-between">
|
||||||
<h1 className="text-2xl font-bold">Settings</h1>
|
<h1 className="text-2xl font-bold">Settings</h1>
|
||||||
@@ -387,6 +357,14 @@ export function SettingsPage({ onUnsavedChangesChange, onResetRequest }: Setting
|
|||||||
<MonitorCog className="h-4 w-4"/>
|
<MonitorCog className="h-4 w-4"/>
|
||||||
General
|
General
|
||||||
</Button>
|
</Button>
|
||||||
|
<Button variant={activeTab === "downloads" ? "default" : "ghost"} size="sm" onClick={() => setActiveTab("downloads")} className="rounded-b-none gap-2">
|
||||||
|
<Download className="h-4 w-4"/>
|
||||||
|
Downloads
|
||||||
|
</Button>
|
||||||
|
<Button variant={activeTab === "naming" ? "default" : "ghost"} size="sm" onClick={() => setActiveTab("naming")} className="rounded-b-none gap-2">
|
||||||
|
<FileSignature className="h-4 w-4"/>
|
||||||
|
Naming
|
||||||
|
</Button>
|
||||||
<Button variant={activeTab === "dependencies" ? "default" : "ghost"} size="sm" onClick={() => setActiveTab("dependencies")} className="rounded-b-none gap-2">
|
<Button variant={activeTab === "dependencies" ? "default" : "ghost"} size="sm" onClick={() => setActiveTab("dependencies")} className="rounded-b-none gap-2">
|
||||||
<PackageSearch className="h-4 w-4"/>
|
<PackageSearch className="h-4 w-4"/>
|
||||||
Dependencies
|
Dependencies
|
||||||
@@ -394,19 +372,8 @@ export function SettingsPage({ onUnsavedChangesChange, onResetRequest }: Setting
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="pt-4">
|
<div className="pt-4">
|
||||||
{activeTab === "general" && (<div className="grid grid-cols-1 gap-4 md:grid-cols-2">
|
{activeTab === "general" && (<div className="max-w-3xl space-y-4">
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
<div className="space-y-2">
|
|
||||||
<Label htmlFor="download-path">Download Path</Label>
|
|
||||||
<div className="flex gap-2">
|
|
||||||
<InputWithContext id="download-path" value={tempSettings.downloadPath} onChange={(e) => setTempSettings((prev) => ({ ...prev, downloadPath: e.target.value }))} placeholder="C:\Users\YourUsername\Pictures"/>
|
|
||||||
<Button type="button" onClick={handleBrowseFolder} className="gap-1.5">
|
|
||||||
<FolderOpen className="h-4 w-4"/>
|
|
||||||
Browse
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="theme-mode">Mode</Label>
|
<Label htmlFor="theme-mode">Mode</Label>
|
||||||
<Select value={tempSettings.themeMode} onValueChange={(value: "auto" | "light" | "dark") => setTempSettings((prev) => ({ ...prev, themeMode: value }))}>
|
<Select value={tempSettings.themeMode} onValueChange={(value: "auto" | "light" | "dark") => setTempSettings((prev) => ({ ...prev, themeMode: value }))}>
|
||||||
@@ -481,128 +448,204 @@ export function SettingsPage({ onUnsavedChangesChange, onResetRequest }: Setting
|
|||||||
<Switch id="sfx-enabled" checked={tempSettings.sfxEnabled} onCheckedChange={(checked) => setTempSettings((prev) => ({ ...prev, sfxEnabled: checked }))}/>
|
<Switch id="sfx-enabled" checked={tempSettings.sfxEnabled} onCheckedChange={(checked) => setTempSettings((prev) => ({ ...prev, sfxEnabled: checked }))}/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
</div>)}
|
||||||
|
|
||||||
|
{activeTab === "downloads" && (<div className="grid grid-cols-1 gap-4 md:grid-cols-[minmax(0,1fr)_1px_minmax(0,1fr)] md:gap-6">
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="download-path">Download Path</Label>
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<InputWithContext id="download-path" value={tempSettings.downloadPath} onChange={(e) => setTempSettings((prev) => ({ ...prev, downloadPath: e.target.value }))} placeholder="C:\Users\YourUsername\Pictures"/>
|
||||||
|
<Button type="button" onClick={handleBrowseFolder} className="gap-1.5">
|
||||||
|
<FolderOpen className="h-4 w-4"/>
|
||||||
|
Browse
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div className="flex flex-wrap gap-6">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="concurrent-downloads" className="flex items-center gap-2">
|
||||||
|
Concurrent Downloads
|
||||||
|
<Tooltip>
|
||||||
|
<TooltipTrigger asChild>
|
||||||
|
<Info className="h-3.5 w-3.5 cursor-help text-muted-foreground"/>
|
||||||
|
</TooltipTrigger>
|
||||||
|
<TooltipContent side="top">
|
||||||
|
<p>How many media files can download at the same time.</p>
|
||||||
|
</TooltipContent>
|
||||||
|
</Tooltip>
|
||||||
|
</Label>
|
||||||
|
<Select value={String(tempSettings.concurrentDownloads || 10)} onValueChange={(value) => setTempSettings((prev) => ({ ...prev, concurrentDownloads: parseInt(value, 10) }))}>
|
||||||
|
<SelectTrigger id="concurrent-downloads" className="w-fit">
|
||||||
|
<SelectValue placeholder="10"/>
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
{[1, 2, 3, 5, 8, 10, 15, 20, 25, 30, 40, 50].map((value) => (<SelectItem key={value} value={String(value)}>
|
||||||
|
{value}
|
||||||
|
</SelectItem>))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="retry-attempts" className="flex items-center gap-2">
|
||||||
|
Retry Attempts
|
||||||
|
<Tooltip>
|
||||||
|
<TooltipTrigger asChild>
|
||||||
|
<Info className="h-3.5 w-3.5 cursor-help text-muted-foreground"/>
|
||||||
|
</TooltipTrigger>
|
||||||
|
<TooltipContent side="top">
|
||||||
|
<p>How many times to retry a failed download before giving up.</p>
|
||||||
|
</TooltipContent>
|
||||||
|
</Tooltip>
|
||||||
|
</Label>
|
||||||
|
<Select value={String(tempSettings.retryAttempts)} onValueChange={(value) => setTempSettings((prev) => ({ ...prev, retryAttempts: parseInt(value, 10) }))}>
|
||||||
|
<SelectTrigger id="retry-attempts" className="w-fit">
|
||||||
|
<SelectValue placeholder="1"/>
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
{[1, 2, 3, 4, 5].map((value) => (<SelectItem key={value} value={String(value)}>
|
||||||
|
{value}
|
||||||
|
</SelectItem>))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center justify-between gap-4">
|
||||||
|
<Label htmlFor="skip-existing-files" className="cursor-pointer">Skip Existing Files</Label>
|
||||||
|
<Switch id="skip-existing-files" checked={tempSettings.skipExistingFiles} onCheckedChange={(checked) => setTempSettings((prev) => ({ ...prev, skipExistingFiles: checked }))}/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center justify-between gap-4">
|
||||||
|
<Label htmlFor="delete-incomplete-files" className="cursor-pointer">Delete Incomplete Files</Label>
|
||||||
|
<Switch id="delete-incomplete-files" checked={tempSettings.deleteIncompleteFiles} onCheckedChange={(checked) => setTempSettings((prev) => ({ ...prev, deleteIncompleteFiles: checked }))}/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div aria-hidden="true" className="hidden bg-border md:block"/>
|
||||||
|
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
<div className="space-y-4">
|
<div className="space-y-2">
|
||||||
<Label className="flex items-center gap-2">
|
<Label htmlFor="proxy" className="flex items-center gap-2">
|
||||||
GIF Conversion
|
Proxy
|
||||||
<Tooltip>
|
<Tooltip>
|
||||||
<TooltipTrigger asChild>
|
<TooltipTrigger asChild>
|
||||||
<Info className="h-3.5 w-3.5 cursor-help text-muted-foreground"/>
|
<Info className="h-3.5 w-3.5 cursor-help text-muted-foreground"/>
|
||||||
</TooltipTrigger>
|
</TooltipTrigger>
|
||||||
<TooltipContent side="top">
|
<TooltipContent side="top">
|
||||||
<p>Quality settings for converting Twitter's MP4 into actual GIF files.</p>
|
<p>Supports one proxy or multiple proxies separated by commas. Requests will rotate through them.</p>
|
||||||
</TooltipContent>
|
</TooltipContent>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
</Label>
|
</Label>
|
||||||
|
<InputWithContext id="proxy" value={tempSettings.proxy || ""} onChange={(e) => setTempSettings((prev) => ({ ...prev, proxy: e.target.value }))} placeholder="http://proxy1:port, socks5://proxy2:port (optional)" className="max-w-md"/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="fetch-timeout" className="flex items-center gap-2">
|
||||||
|
Fetch Timeout
|
||||||
|
<Tooltip>
|
||||||
|
<TooltipTrigger asChild>
|
||||||
|
<Info className="h-3.5 w-3.5 cursor-help text-muted-foreground"/>
|
||||||
|
</TooltipTrigger>
|
||||||
|
<TooltipContent side="top">
|
||||||
|
<p>Timeout in seconds. Fetch stops automatically when reached</p>
|
||||||
|
</TooltipContent>
|
||||||
|
</Tooltip>
|
||||||
|
</Label>
|
||||||
|
<InputWithContext id="fetch-timeout" type="number" value={tempSettings.fetchTimeout || 60} onChange={(e) => {
|
||||||
|
const inputValue = e.target.value;
|
||||||
|
if (inputValue === "") {
|
||||||
|
setTempSettings((prev) => ({ ...prev, fetchTimeout: 60 }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const value = parseInt(inputValue, 10);
|
||||||
|
if (!isNaN(value)) {
|
||||||
|
setTempSettings((prev) => ({ ...prev, fetchTimeout: value }));
|
||||||
|
}
|
||||||
|
}} onBlur={(e) => {
|
||||||
|
const value = parseInt(e.target.value, 10);
|
||||||
|
if (isNaN(value) || value < 30) {
|
||||||
|
setTempSettings((prev) => ({ ...prev, fetchTimeout: 30 }));
|
||||||
|
}
|
||||||
|
else if (value > 900) {
|
||||||
|
setTempSettings((prev) => ({ ...prev, fetchTimeout: 900 }));
|
||||||
|
}
|
||||||
|
}} placeholder="60" className="w-24"/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-4">
|
||||||
<div className="space-y-3">
|
<div className="space-y-3">
|
||||||
<div className="space-y-2">
|
<Label className="flex items-center gap-2">
|
||||||
<Label htmlFor="gif-quality" className={!ffmpegInstalled ? "text-muted-foreground" : undefined}>GIF Quality</Label>
|
GIF Conversion
|
||||||
<Select value={tempSettings.gifQuality} onValueChange={(value: GifQuality) => {
|
<Tooltip>
|
||||||
setTempSettings((prev) => ({
|
<TooltipTrigger asChild>
|
||||||
...prev,
|
<Info className="h-3.5 w-3.5 cursor-help text-muted-foreground"/>
|
||||||
gifQuality: value,
|
</TooltipTrigger>
|
||||||
}));
|
<TooltipContent side="top">
|
||||||
}} disabled={!ffmpegInstalled}>
|
<p>Quality settings for converting Twitter's MP4 into actual GIF files.</p>
|
||||||
<SelectTrigger id="gif-quality" className="w-fit">
|
</TooltipContent>
|
||||||
<SelectValue placeholder="Select quality"/>
|
</Tooltip>
|
||||||
</SelectTrigger>
|
</Label>
|
||||||
<SelectContent>
|
<div className="flex items-center justify-between gap-4">
|
||||||
<SelectItem value="fast">Fast</SelectItem>
|
<Label htmlFor="auto-convert-gifs" className={!ffmpegInstalled ? "text-muted-foreground" : undefined}>Auto Convert GIFs</Label>
|
||||||
<SelectItem value="better">Better</SelectItem>
|
<Switch id="auto-convert-gifs" checked={tempSettings.autoConvertGifs} onCheckedChange={(checked) => setTempSettings((prev) => ({ ...prev, autoConvertGifs: checked }))} disabled={!ffmpegInstalled}/>
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
</div>
|
</div>
|
||||||
|
<div className="flex items-center justify-between gap-4">
|
||||||
<div className="space-y-2">
|
<Label htmlFor="gif-quality" className={!ffmpegInstalled || !tempSettings.autoConvertGifs ? "text-muted-foreground" : undefined}>GIF Quality</Label>
|
||||||
<Label htmlFor="gif-resolution" className={!ffmpegInstalled ? "text-muted-foreground" : undefined}>Resolution</Label>
|
<div className="flex items-center gap-2">
|
||||||
<Select value={tempSettings.gifResolution} onValueChange={(value: GifResolution) => setTempSettings((prev) => ({ ...prev, gifResolution: value }))} disabled={!ffmpegInstalled}>
|
<Select value={tempSettings.gifQuality} onValueChange={(value: GifQuality) => {
|
||||||
<SelectTrigger id="gif-resolution" className="w-fit">
|
setTempSettings((prev) => ({
|
||||||
<SelectValue placeholder="Resolution"/>
|
...prev,
|
||||||
</SelectTrigger>
|
gifQuality: value,
|
||||||
<SelectContent>
|
}));
|
||||||
<SelectItem value="original">Original</SelectItem>
|
}} disabled={!ffmpegInstalled || !tempSettings.autoConvertGifs}>
|
||||||
<SelectItem value="high">High (800px)</SelectItem>
|
<SelectTrigger id="gif-quality" className="w-fit">
|
||||||
<SelectItem value="medium">Medium (600px)</SelectItem>
|
<SelectValue placeholder="Select quality"/>
|
||||||
<SelectItem value="low">Low (400px)</SelectItem>
|
</SelectTrigger>
|
||||||
</SelectContent>
|
<SelectContent>
|
||||||
</Select>
|
<SelectItem value="fast">Fast</SelectItem>
|
||||||
</div>
|
<SelectItem value="better">Better</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
<div className="space-y-2">
|
</Select>
|
||||||
<Label className="flex items-center gap-2">
|
<Select value={tempSettings.gifResolution} onValueChange={(value: GifResolution) => setTempSettings((prev) => ({ ...prev, gifResolution: value }))} disabled={!ffmpegInstalled || !tempSettings.autoConvertGifs}>
|
||||||
Network
|
<SelectTrigger id="gif-resolution" className="w-fit">
|
||||||
<Tooltip>
|
<SelectValue placeholder="Resolution"/>
|
||||||
<TooltipTrigger asChild>
|
</SelectTrigger>
|
||||||
<Info className="h-3.5 w-3.5 cursor-help text-muted-foreground"/>
|
<SelectContent>
|
||||||
</TooltipTrigger>
|
<SelectItem value="original">Original</SelectItem>
|
||||||
<TooltipContent side="top">
|
<SelectItem value="high">High (800px)</SelectItem>
|
||||||
<p>Connection settings used while fetching data and downloading media.</p>
|
<SelectItem value="medium">Medium (600px)</SelectItem>
|
||||||
</TooltipContent>
|
<SelectItem value="low">Low (400px)</SelectItem>
|
||||||
</Tooltip>
|
</SelectContent>
|
||||||
</Label>
|
</Select>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label htmlFor="proxy" className="flex items-center gap-2">
|
|
||||||
Proxy
|
|
||||||
<Tooltip>
|
|
||||||
<TooltipTrigger asChild>
|
|
||||||
<Info className="h-3.5 w-3.5 cursor-help text-muted-foreground"/>
|
|
||||||
</TooltipTrigger>
|
|
||||||
<TooltipContent side="top">
|
|
||||||
<p>Supports one proxy or multiple proxies separated by commas. Requests will rotate through them.</p>
|
|
||||||
</TooltipContent>
|
|
||||||
</Tooltip>
|
|
||||||
</Label>
|
|
||||||
<InputWithContext id="proxy" value={tempSettings.proxy || ""} onChange={(e) => setTempSettings((prev) => ({ ...prev, proxy: e.target.value }))} placeholder="http://proxy1:port, socks5://proxy2:port (optional)" className="max-w-md"/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label htmlFor="fetch-timeout" className="flex items-center gap-2">
|
|
||||||
Fetch Timeout
|
|
||||||
<Tooltip>
|
|
||||||
<TooltipTrigger asChild>
|
|
||||||
<Info className="h-3.5 w-3.5 cursor-help text-muted-foreground"/>
|
|
||||||
</TooltipTrigger>
|
|
||||||
<TooltipContent side="top">
|
|
||||||
<p>Timeout in seconds. Fetch stops automatically when reached</p>
|
|
||||||
</TooltipContent>
|
|
||||||
</Tooltip>
|
|
||||||
</Label>
|
|
||||||
<InputWithContext id="fetch-timeout" type="number" value={tempSettings.fetchTimeout || 60} onChange={(e) => {
|
|
||||||
const inputValue = e.target.value;
|
|
||||||
if (inputValue === "") {
|
|
||||||
setTempSettings((prev) => ({ ...prev, fetchTimeout: 60 }));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const value = parseInt(inputValue, 10);
|
|
||||||
if (!isNaN(value)) {
|
|
||||||
setTempSettings((prev) => ({ ...prev, fetchTimeout: value }));
|
|
||||||
}
|
|
||||||
}} onBlur={(e) => {
|
|
||||||
const value = parseInt(e.target.value, 10);
|
|
||||||
if (isNaN(value) || value < 30) {
|
|
||||||
setTempSettings((prev) => ({ ...prev, fetchTimeout: 30 }));
|
|
||||||
}
|
|
||||||
else if (value > 900) {
|
|
||||||
setTempSettings((prev) => ({ ...prev, fetchTimeout: 900 }));
|
|
||||||
}
|
|
||||||
}} placeholder="60" className="w-24"/>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>)}
|
</div>)}
|
||||||
|
|
||||||
|
{activeTab === "naming" && (<div className="grid grid-cols-1 gap-6 md:grid-cols-2 md:gap-8 items-start">
|
||||||
|
<div className="md:pr-8 md:border-r border-border">
|
||||||
|
<FormatEditor title="Folder" value={tempSettings.folderTemplate} defaultValue={DEFAULT_FOLDER_TEMPLATE} tokens={FOLDER_TEMPLATE_VARIABLES} placeholder={DEFAULT_FOLDER_TEMPLATE} render={(t) => renderFolderTemplate(t, SAMPLE_FOLDER_DATA)} onChange={(next) => setTempSettings((prev) => ({ ...prev, folderTemplate: next }))}/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<FormatEditor title="Filename" value={tempSettings.filenameTemplate} defaultValue={DEFAULT_FILENAME_TEMPLATE} tokens={FILENAME_TEMPLATE_VARIABLES} placeholder={DEFAULT_FILENAME_TEMPLATE} suffix=".jpg" render={(t) => renderFilenameTemplate(t, SAMPLE_FILENAME_DATA)} onChange={(next) => setTempSettings((prev) => ({ ...prev, filenameTemplate: next }))}/>
|
||||||
|
</div>
|
||||||
|
</div>)}
|
||||||
|
|
||||||
{activeTab === "dependencies" && (<div className="grid grid-cols-1 gap-4 md:grid-cols-2">
|
{activeTab === "dependencies" && (<div className="grid grid-cols-1 gap-4 md:grid-cols-2">
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label className="flex flex-wrap items-center gap-2">
|
<Label className="flex flex-wrap items-center gap-2">
|
||||||
<span>Core Xtractor</span>
|
<span>Core Xtractor</span>
|
||||||
{extractorVersionText && (<span className={extractorUpdateAvailable
|
{extractorVersionText && (<span className={extractorUpdateAvailable
|
||||||
? "text-xs font-normal text-amber-600 dark:text-amber-400"
|
? "text-xs font-normal text-amber-600 dark:text-amber-400"
|
||||||
: "text-xs font-normal text-muted-foreground"}>
|
: "text-xs font-normal text-muted-foreground"}>
|
||||||
{extractorVersionText}
|
{extractorVersionText}
|
||||||
</span>)}
|
</span>)}
|
||||||
<Tooltip>
|
<Tooltip>
|
||||||
@@ -635,8 +678,8 @@ export function SettingsPage({ onUnsavedChangesChange, onResetRequest }: Setting
|
|||||||
<Label className="flex flex-wrap items-center gap-2">
|
<Label className="flex flex-wrap items-center gap-2">
|
||||||
<span>GIF Conversion</span>
|
<span>GIF Conversion</span>
|
||||||
{ffmpegVersionText && (<span className={ffmpegUpdateAvailable
|
{ffmpegVersionText && (<span className={ffmpegUpdateAvailable
|
||||||
? "text-xs font-normal text-amber-600 dark:text-amber-400"
|
? "text-xs font-normal text-amber-600 dark:text-amber-400"
|
||||||
: "text-xs font-normal text-muted-foreground"}>
|
: "text-xs font-normal text-muted-foreground"}>
|
||||||
{ffmpegVersionText}
|
{ffmpegVersionText}
|
||||||
</span>)}
|
</span>)}
|
||||||
<Tooltip>
|
<Tooltip>
|
||||||
@@ -669,8 +712,8 @@ export function SettingsPage({ onUnsavedChangesChange, onResetRequest }: Setting
|
|||||||
<Label className="flex flex-wrap items-center gap-2">
|
<Label className="flex flex-wrap items-center gap-2">
|
||||||
<span>Metadata Embedding</span>
|
<span>Metadata Embedding</span>
|
||||||
{exiftoolVersionText && (<span className={exiftoolUpdateAvailable
|
{exiftoolVersionText && (<span className={exiftoolUpdateAvailable
|
||||||
? "text-xs font-normal text-amber-600 dark:text-amber-400"
|
? "text-xs font-normal text-amber-600 dark:text-amber-400"
|
||||||
: "text-xs font-normal text-muted-foreground"}>
|
: "text-xs font-normal text-muted-foreground"}>
|
||||||
{exiftoolVersionText}
|
{exiftoolVersionText}
|
||||||
</span>)}
|
</span>)}
|
||||||
<Tooltip>
|
<Tooltip>
|
||||||
|
|||||||
@@ -1,19 +1,57 @@
|
|||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||||
import { CircleCheck, Copy } from "lucide-react";
|
import { CircleCheck, Copy } from "lucide-react";
|
||||||
import { openExternal } from "@/lib/utils";
|
import { openExternal } from "@/lib/utils";
|
||||||
import KofiLogo from "@/assets/ko-fi.gif";
|
import KofiLogo from "@/assets/ko-fi.gif";
|
||||||
import KofiSvg from "@/assets/kofi_symbol.svg";
|
import KofiSvg from "@/assets/kofi_symbol.svg";
|
||||||
import UsdtBarcode from "@/assets/usdt.jpg";
|
import UsdtTronQr from "@/assets/usdt.jpg";
|
||||||
|
import UsdtEvmQr from "@/assets/usdt_evm.jpg";
|
||||||
const USDT_ADDRESS = "THnzAAwZgp2Sq5CAXLP2njQDhTvgZG9EWs";
|
import UsdcEvmQr from "@/assets/usdc.jpg";
|
||||||
|
type CryptoCoin = "usdt" | "usdc";
|
||||||
|
type CryptoNetwork = "ethereum" | "bsc" | "polygon" | "base" | "tron";
|
||||||
|
const EVM_ADDRESS = "0xB563a7F39770C151e2FacE26926081a00c5EF349";
|
||||||
|
const TRON_ADDRESS = "THnzAAwZgp2Sq5CAXLP2njQDhTvgZG9EWs";
|
||||||
|
const EVM_NETWORKS: Array<{
|
||||||
|
value: CryptoNetwork;
|
||||||
|
label: string;
|
||||||
|
shortLabel: string;
|
||||||
|
}> = [
|
||||||
|
{ value: "bsc", label: "BNB Smart Chain (BEP20)", shortLabel: "BEP20" },
|
||||||
|
{ value: "polygon", label: "Polygon", shortLabel: "Polygon" },
|
||||||
|
{ value: "ethereum", label: "Ethereum (ERC20)", shortLabel: "ERC20" },
|
||||||
|
{ value: "base", label: "Base", shortLabel: "Base" },
|
||||||
|
];
|
||||||
|
const USDT_NETWORKS: Array<{
|
||||||
|
value: CryptoNetwork;
|
||||||
|
label: string;
|
||||||
|
shortLabel: string;
|
||||||
|
}> = [
|
||||||
|
{ value: "ethereum", label: "Ethereum (ERC20)", shortLabel: "ERC20" },
|
||||||
|
{ value: "bsc", label: "BNB Smart Chain (BEP20)", shortLabel: "BEP20" },
|
||||||
|
{ value: "tron", label: "Tron (TRC20)", shortLabel: "TRC20" },
|
||||||
|
{ value: "polygon", label: "Polygon", shortLabel: "Polygon" },
|
||||||
|
];
|
||||||
export function SupportPage() {
|
export function SupportPage() {
|
||||||
const [copiedUsdt, setCopiedUsdt] = useState(false);
|
const [selectedCoin, setSelectedCoin] = useState<CryptoCoin>("usdt");
|
||||||
|
const [selectedNetwork, setSelectedNetwork] = useState<CryptoNetwork>("tron");
|
||||||
|
const [copiedAddress, setCopiedAddress] = useState(false);
|
||||||
|
const networkOptions = selectedCoin === "usdt" ? USDT_NETWORKS : EVM_NETWORKS;
|
||||||
|
const activeNetwork = networkOptions.find((network) => network.value === selectedNetwork) || EVM_NETWORKS[0];
|
||||||
|
const isTron = selectedNetwork === "tron";
|
||||||
|
const cryptoAddress = isTron ? TRON_ADDRESS : EVM_ADDRESS;
|
||||||
|
const cryptoQr = isTron ? UsdtTronQr : selectedCoin === "usdt" ? UsdtEvmQr : UsdcEvmQr;
|
||||||
|
const handleCoinChange = (coin: CryptoCoin) => {
|
||||||
|
setSelectedCoin(coin);
|
||||||
|
setCopiedAddress(false);
|
||||||
|
const nextNetworks = coin === "usdt" ? USDT_NETWORKS : EVM_NETWORKS;
|
||||||
|
if (!nextNetworks.some((network) => network.value === selectedNetwork)) {
|
||||||
|
setSelectedNetwork("ethereum");
|
||||||
|
}
|
||||||
|
};
|
||||||
return (<div className="flex min-h-[70vh] items-center justify-center p-4">
|
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 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 min-w-0 flex-1 basis-0 flex-col items-center justify-between space-y-6 border-b p-6 md:border-r md:border-b-0">
|
||||||
<div className="flex flex-col items-center space-y-4">
|
<div className="flex flex-col items-center space-y-4">
|
||||||
<div className="relative flex h-32 w-full items-center justify-center">
|
<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"/>
|
<img src={KofiLogo} className="pointer-events-none absolute w-72" alt="Ko-fi"/>
|
||||||
@@ -23,35 +61,59 @@ export function SupportPage() {
|
|||||||
Enjoying the project? You can support ongoing development by buying me a coffee.
|
Enjoying the project? You can support ongoing development by buying me a coffee.
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</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")}>
|
<Button className="h-9 w-4/5 gap-2 bg-[#72a4f2] text-sm font-semibold text-white hover:bg-[#5f8cd6]" onClick={() => openExternal("https://ko-fi.com/afkarxyz")}>
|
||||||
<img src={KofiSvg} className="h-5 w-5 shrink-0" alt="" aria-hidden="true"/>
|
<img src={KofiSvg} className="h-6 w-6 shrink-0" alt="" aria-hidden="true"/>
|
||||||
Support me on Ko-fi
|
Support me on Ko-fi
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex flex-1 flex-col items-center justify-between space-y-6 p-6">
|
<div className="flex min-w-0 flex-1 basis-0 flex-col items-center justify-between space-y-4 p-6">
|
||||||
<div className="flex w-full flex-col items-center space-y-4">
|
<div className="flex w-full flex-col items-center space-y-3">
|
||||||
<div className="flex h-32 items-center justify-center">
|
<div className="flex h-32 items-center justify-center">
|
||||||
<div className="rounded-xl border bg-white p-2 shadow-sm">
|
<div className="rounded-xl border bg-white p-2 shadow-sm">
|
||||||
<img src={UsdtBarcode} className="h-24 w-24 object-contain" alt="USDT Barcode"/>
|
<img src={cryptoQr} className="h-24 w-24 object-contain" alt={`${selectedCoin.toUpperCase()} ${activeNetwork.label} QR code`}/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<h4 className="font-semibold text-foreground">USDT (TRC20)</h4>
|
<h4 className="font-semibold text-foreground">Support via Crypto</h4>
|
||||||
<p className="px-4 text-center text-sm text-muted-foreground">
|
<p className="px-4 text-center text-sm text-muted-foreground">
|
||||||
Crypto donations are also accepted. Scan the QR code or copy the address.
|
Crypto donations are also accepted. Scan the QR code or copy the address.
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</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">
|
<div className="w-full space-y-2">
|
||||||
<code className="truncate text-xs font-mono text-muted-foreground" title={USDT_ADDRESS}>
|
<div className="grid grid-cols-2 gap-2">
|
||||||
{USDT_ADDRESS}
|
<Select value={selectedCoin} onValueChange={(value: CryptoCoin) => handleCoinChange(value)}>
|
||||||
</code>
|
<SelectTrigger size="sm" className="w-full" aria-label="Coin">
|
||||||
<Button variant="ghost" size="icon" className="h-7 w-7 shrink-0 hover:bg-background" onClick={() => {
|
<SelectValue />
|
||||||
navigator.clipboard.writeText(USDT_ADDRESS);
|
</SelectTrigger>
|
||||||
setCopiedUsdt(true);
|
<SelectContent>
|
||||||
setTimeout(() => setCopiedUsdt(false), 500);
|
<SelectItem value="usdt">USDT</SelectItem>
|
||||||
|
<SelectItem value="usdc">USDC</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
<Select value={selectedNetwork} onValueChange={(value: CryptoNetwork) => {
|
||||||
|
setSelectedNetwork(value);
|
||||||
|
setCopiedAddress(false);
|
||||||
}}>
|
}}>
|
||||||
{copiedUsdt ? <CircleCheck className="h-3.5 w-3.5 text-green-500"/> : <Copy className="h-3.5 w-3.5"/>}
|
<SelectTrigger size="sm" className="w-full" aria-label="Network">
|
||||||
</Button>
|
<SelectValue>{activeNetwork.shortLabel}</SelectValue>
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
{networkOptions.map((network) => (<SelectItem key={network.value} value={network.value}>{network.label}</SelectItem>))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
<div className="flex h-10 w-full items-center justify-between gap-2 rounded-lg border bg-muted/50 py-1.5 pr-1.5 pl-3">
|
||||||
|
<code className="min-w-0 flex-1 truncate text-xs font-mono text-muted-foreground" title={cryptoAddress}>
|
||||||
|
{cryptoAddress}
|
||||||
|
</code>
|
||||||
|
<Button variant="ghost" size="icon" className="h-7 w-7 shrink-0 hover:bg-background" aria-label="Copy wallet address" onClick={() => {
|
||||||
|
navigator.clipboard.writeText(cryptoAddress);
|
||||||
|
setCopiedAddress(true);
|
||||||
|
setTimeout(() => setCopiedAddress(false), 500);
|
||||||
|
}}>
|
||||||
|
{copiedAddress ? <CircleCheck className="h-3.5 w-3.5 text-green-500"/> : <Copy className="h-3.5 w-3.5"/>}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,5 +1,12 @@
|
|||||||
import { X, Minus, Maximize } from "lucide-react";
|
import { X, Minus, Maximize, Info, Puzzle, FileCode2, Globe } from "lucide-react";
|
||||||
import { WindowMinimise, WindowToggleMaximise, Quit } from "../../wailsjs/runtime/runtime";
|
import { WindowMinimise, WindowToggleMaximise, Quit } from "../../wailsjs/runtime/runtime";
|
||||||
|
import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem } from "@/components/ui/dropdown-menu";
|
||||||
|
import { openExternal } from "@/lib/utils";
|
||||||
|
const INFO_LINKS = [
|
||||||
|
{ label: "Chrome Extension", icon: Puzzle, url: "https://chromewebstore.google.com/detail/cboceolmgkoobpfjiojkigmihijfgmdo" },
|
||||||
|
{ label: "Userscript", icon: FileCode2, url: "https://greasyfork.org/en/scripts/523157" },
|
||||||
|
{ label: "Website", icon: Globe, url: "https://twitterdl.app" },
|
||||||
|
];
|
||||||
export function TitleBar() {
|
export function TitleBar() {
|
||||||
const handleMinimize = () => {
|
const handleMinimize = () => {
|
||||||
WindowMinimise();
|
WindowMinimise();
|
||||||
@@ -15,14 +22,27 @@ export function TitleBar() {
|
|||||||
<div className="fixed top-0 left-14 right-0 h-10 z-40 bg-background/80 backdrop-blur-sm" style={{ "--wails-draggable": "drag" } as React.CSSProperties} onDoubleClick={handleMaximize}/>
|
<div className="fixed top-0 left-14 right-0 h-10 z-40 bg-background/80 backdrop-blur-sm" style={{ "--wails-draggable": "drag" } as React.CSSProperties} onDoubleClick={handleMaximize}/>
|
||||||
|
|
||||||
|
|
||||||
<div className="fixed top-1.5 right-2 z-50 flex h-7 gap-0.5">
|
<div className="fixed top-1.5 right-2 z-50 flex h-7 gap-0.5" style={{ "--wails-draggable": "no-drag" } as React.CSSProperties}>
|
||||||
<button onClick={handleMinimize} className="w-8 h-7 flex items-center justify-center hover:bg-muted transition-colors rounded" style={{ "--wails-draggable": "no-drag" } as React.CSSProperties} aria-label="Minimize">
|
<DropdownMenu>
|
||||||
|
<DropdownMenuTrigger asChild>
|
||||||
|
<button className="w-8 h-7 flex items-center justify-center hover:bg-muted transition-colors rounded" aria-label="Info">
|
||||||
|
<Info className="w-3.5 h-3.5"/>
|
||||||
|
</button>
|
||||||
|
</DropdownMenuTrigger>
|
||||||
|
<DropdownMenuContent align="end">
|
||||||
|
{INFO_LINKS.map(({ label, icon: Icon, url }) => (<DropdownMenuItem key={label} onClick={() => openExternal(url)} className="gap-2 cursor-pointer">
|
||||||
|
<Icon className="w-4 h-4 text-muted-foreground"/>
|
||||||
|
{label}
|
||||||
|
</DropdownMenuItem>))}
|
||||||
|
</DropdownMenuContent>
|
||||||
|
</DropdownMenu>
|
||||||
|
<button onClick={handleMinimize} className="w-8 h-7 flex items-center justify-center hover:bg-muted transition-colors rounded" aria-label="Minimize">
|
||||||
<Minus className="w-3.5 h-3.5"/>
|
<Minus className="w-3.5 h-3.5"/>
|
||||||
</button>
|
</button>
|
||||||
<button onClick={handleMaximize} className="w-8 h-7 flex items-center justify-center hover:bg-muted transition-colors rounded" style={{ "--wails-draggable": "no-drag" } as React.CSSProperties} aria-label="Maximize">
|
<button onClick={handleMaximize} className="w-8 h-7 flex items-center justify-center hover:bg-muted transition-colors rounded" aria-label="Maximize">
|
||||||
<Maximize className="w-3.5 h-3.5"/>
|
<Maximize className="w-3.5 h-3.5"/>
|
||||||
</button>
|
</button>
|
||||||
<button onClick={handleClose} className="w-8 h-7 flex items-center justify-center hover:bg-destructive hover:text-white transition-colors rounded" style={{ "--wails-draggable": "no-drag" } as React.CSSProperties} aria-label="Close">
|
<button onClick={handleClose} className="w-8 h-7 flex items-center justify-center hover:bg-destructive hover:text-white transition-colors rounded" aria-label="Close">
|
||||||
<X className="w-3.5 h-3.5"/>
|
<X className="w-3.5 h-3.5"/>
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,19 +1,14 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import type { Transition, Variants } from "motion/react";
|
import type { Transition, Variants } from "motion/react";
|
||||||
import { AnimatePresence, motion } from "motion/react";
|
import { AnimatePresence, motion } from "motion/react";
|
||||||
import { useEffect, useState, type HTMLAttributes } from "react";
|
import { useEffect, useState, type HTMLAttributes } from "react";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
type ReportIconMode = "bug" | "bulb";
|
type ReportIconMode = "bug" | "bulb";
|
||||||
|
|
||||||
interface BugReportIconProps extends HTMLAttributes<HTMLDivElement> {
|
interface BugReportIconProps extends HTMLAttributes<HTMLDivElement> {
|
||||||
size?: number;
|
size?: number;
|
||||||
loop?: boolean;
|
loop?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
const LOOP_INTERVAL_MS = 2200;
|
const LOOP_INTERVAL_MS = 2200;
|
||||||
|
|
||||||
const GROUP_VARIANTS: Variants = {
|
const GROUP_VARIANTS: Variants = {
|
||||||
hidden: {
|
hidden: {
|
||||||
opacity: 0,
|
opacity: 0,
|
||||||
@@ -33,7 +28,6 @@ const GROUP_VARIANTS: Variants = {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
const DRAW_VARIANTS: Variants = {
|
const DRAW_VARIANTS: Variants = {
|
||||||
hidden: {
|
hidden: {
|
||||||
pathLength: 0,
|
pathLength: 0,
|
||||||
@@ -48,7 +42,6 @@ const DRAW_VARIANTS: Variants = {
|
|||||||
opacity: 0,
|
opacity: 0,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
function createDrawTransition(delay = 0, duration = 0.36): Transition {
|
function createDrawTransition(delay = 0, duration = 0.36): Transition {
|
||||||
return {
|
return {
|
||||||
duration,
|
duration,
|
||||||
@@ -57,7 +50,6 @@ function createDrawTransition(delay = 0, duration = 0.36): Transition {
|
|||||||
opacity: { delay },
|
opacity: { delay },
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function BugPaths() {
|
function BugPaths() {
|
||||||
return (<>
|
return (<>
|
||||||
<motion.path d="m8 2 1.88 1.88" transition={createDrawTransition(0)} variants={DRAW_VARIANTS}/>
|
<motion.path d="m8 2 1.88 1.88" transition={createDrawTransition(0)} variants={DRAW_VARIANTS}/>
|
||||||
@@ -73,7 +65,6 @@ function BugPaths() {
|
|||||||
<motion.path d="M3 21a4 4 0 0 1 3.81-4" transition={createDrawTransition(0.56)} variants={DRAW_VARIANTS}/>
|
<motion.path d="M3 21a4 4 0 0 1 3.81-4" transition={createDrawTransition(0.56)} variants={DRAW_VARIANTS}/>
|
||||||
</>);
|
</>);
|
||||||
}
|
}
|
||||||
|
|
||||||
function BulbPaths() {
|
function BulbPaths() {
|
||||||
return (<>
|
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="M15 14c.2-1 .7-1.7 1.5-2.5 1-.9 1.5-2.2 1.5-3.5A6 6 0 0 0 6 8c0 1 .2 2.2 1.5 3.5.7.7 1.3 1.5 1.5 2.5" transition={createDrawTransition(0, 0.46)} variants={DRAW_VARIANTS}/>
|
||||||
@@ -81,13 +72,13 @@ function BulbPaths() {
|
|||||||
<motion.path d="M10 22h4" transition={createDrawTransition(0.24)} variants={DRAW_VARIANTS}/>
|
<motion.path d="M10 22h4" transition={createDrawTransition(0.24)} variants={DRAW_VARIANTS}/>
|
||||||
</>);
|
</>);
|
||||||
}
|
}
|
||||||
|
function ReportIconGroup({ mode }: {
|
||||||
function ReportIconGroup({ mode }: { mode: ReportIconMode; }) {
|
mode: ReportIconMode;
|
||||||
|
}) {
|
||||||
return (<motion.g animate="visible" exit="exit" initial="hidden" variants={GROUP_VARIANTS}>
|
return (<motion.g animate="visible" exit="exit" initial="hidden" variants={GROUP_VARIANTS}>
|
||||||
{mode === "bug" ? <BugPaths /> : <BulbPaths />}
|
{mode === "bug" ? <BugPaths /> : <BulbPaths />}
|
||||||
</motion.g>);
|
</motion.g>);
|
||||||
}
|
}
|
||||||
|
|
||||||
function StaticBugIcon() {
|
function StaticBugIcon() {
|
||||||
return (<g>
|
return (<g>
|
||||||
<path d="m8 2 1.88 1.88"/>
|
<path d="m8 2 1.88 1.88"/>
|
||||||
@@ -103,29 +94,23 @@ function StaticBugIcon() {
|
|||||||
<path d="M3 21a4 4 0 0 1 3.81-4"/>
|
<path d="M3 21a4 4 0 0 1 3.81-4"/>
|
||||||
</g>);
|
</g>);
|
||||||
}
|
}
|
||||||
|
|
||||||
function BugReportIcon({ className, size = 28, loop = false, ...props }: BugReportIconProps) {
|
function BugReportIcon({ className, size = 28, loop = false, ...props }: BugReportIconProps) {
|
||||||
const [mode, setMode] = useState<ReportIconMode>("bug");
|
const [mode, setMode] = useState<ReportIconMode>("bug");
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!loop) {
|
if (!loop) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const intervalId = window.setInterval(() => {
|
const intervalId = window.setInterval(() => {
|
||||||
setMode((currentMode) => currentMode === "bug" ? "bulb" : "bug");
|
setMode((currentMode) => currentMode === "bug" ? "bulb" : "bug");
|
||||||
}, LOOP_INTERVAL_MS);
|
}, LOOP_INTERVAL_MS);
|
||||||
|
|
||||||
return () => window.clearInterval(intervalId);
|
return () => window.clearInterval(intervalId);
|
||||||
}, [loop]);
|
}, [loop]);
|
||||||
|
|
||||||
return (<div className={cn("flex items-center justify-center", className)} {...props}>
|
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">
|
<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>
|
{loop ? (<AnimatePresence>
|
||||||
<ReportIconGroup key={mode} mode={mode} />
|
<ReportIconGroup key={mode} mode={mode}/>
|
||||||
</AnimatePresence>) : (<StaticBugIcon />)}
|
</AnimatePresence>) : (<StaticBugIcon />)}
|
||||||
</svg>
|
</svg>
|
||||||
</div>);
|
</div>);
|
||||||
}
|
}
|
||||||
|
|
||||||
export { BugReportIcon };
|
export { BugReportIcon };
|
||||||
+12
-2
@@ -246,11 +246,21 @@ input::-ms-clear {
|
|||||||
display: none;
|
display: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
input[type="number"] {
|
input[type="number"],
|
||||||
|
input[type="date"],
|
||||||
|
input[type="datetime-local"],
|
||||||
|
input[type="time"],
|
||||||
|
input[type="month"],
|
||||||
|
input[type="week"] {
|
||||||
color-scheme: light;
|
color-scheme: light;
|
||||||
}
|
}
|
||||||
|
|
||||||
.dark input[type="number"] {
|
.dark input[type="number"],
|
||||||
|
.dark input[type="date"],
|
||||||
|
.dark input[type="datetime-local"],
|
||||||
|
.dark input[type="time"],
|
||||||
|
.dark input[type="month"],
|
||||||
|
.dark input[type="week"] {
|
||||||
color-scheme: dark;
|
color-scheme: dark;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,112 @@
|
|||||||
|
import { useSyncExternalStore } from "react";
|
||||||
|
import { EventsOn } from "../../wailsjs/runtime/runtime";
|
||||||
|
export interface DownloadProgress {
|
||||||
|
current: number;
|
||||||
|
total: number;
|
||||||
|
percent: number;
|
||||||
|
}
|
||||||
|
export interface DownloadItemStatus {
|
||||||
|
tweet_id: number;
|
||||||
|
index: number;
|
||||||
|
status: "success" | "failed" | "skipped" | "cancelled";
|
||||||
|
}
|
||||||
|
export type DownloadScope = "media" | "database" | "database-bulk";
|
||||||
|
export type DownloadItemResult = "success" | "failed" | "skipped";
|
||||||
|
export interface DownloadState {
|
||||||
|
active: boolean;
|
||||||
|
scope: DownloadScope | null;
|
||||||
|
accountId: number | null;
|
||||||
|
progress: DownloadProgress | null;
|
||||||
|
currentItemKey: string | null;
|
||||||
|
itemKeyByIndex: Record<number, string>;
|
||||||
|
itemStatusByKey: Record<string, DownloadItemResult>;
|
||||||
|
}
|
||||||
|
const listeners = new Set<() => void>();
|
||||||
|
let state: DownloadState = {
|
||||||
|
active: false,
|
||||||
|
scope: null,
|
||||||
|
accountId: null,
|
||||||
|
progress: null,
|
||||||
|
currentItemKey: null,
|
||||||
|
itemKeyByIndex: {},
|
||||||
|
itemStatusByKey: {},
|
||||||
|
};
|
||||||
|
let unsubscribeEvents: (() => void) | null = null;
|
||||||
|
function emit() {
|
||||||
|
for (const listener of listeners) {
|
||||||
|
listener();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function setState(next: Partial<DownloadState>) {
|
||||||
|
state = { ...state, ...next };
|
||||||
|
emit();
|
||||||
|
}
|
||||||
|
export function initDownloadProgressEvents() {
|
||||||
|
if (unsubscribeEvents) {
|
||||||
|
return unsubscribeEvents;
|
||||||
|
}
|
||||||
|
const unsubscribeProgress = EventsOn("download-progress", (progress: DownloadProgress) => {
|
||||||
|
if (!state.scope) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setState({ progress });
|
||||||
|
});
|
||||||
|
const unsubscribeItemStatus = EventsOn("download-item-status", (status: DownloadItemStatus) => {
|
||||||
|
if (status.status === "cancelled") {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const itemKey = state.currentItemKey || state.itemKeyByIndex[status.index] || `${String(status.tweet_id)}-${status.index}`;
|
||||||
|
setState({
|
||||||
|
itemStatusByKey: {
|
||||||
|
...state.itemStatusByKey,
|
||||||
|
[itemKey]: status.status,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
});
|
||||||
|
unsubscribeEvents = () => {
|
||||||
|
unsubscribeProgress();
|
||||||
|
unsubscribeItemStatus();
|
||||||
|
unsubscribeEvents = null;
|
||||||
|
};
|
||||||
|
return unsubscribeEvents;
|
||||||
|
}
|
||||||
|
export function beginDownload(progress: DownloadProgress, meta: Pick<DownloadState, "scope"> & Partial<Pick<DownloadState, "accountId" | "currentItemKey" | "itemKeyByIndex">>) {
|
||||||
|
setState({
|
||||||
|
active: true,
|
||||||
|
scope: meta.scope,
|
||||||
|
accountId: meta.accountId ?? null,
|
||||||
|
progress,
|
||||||
|
currentItemKey: meta.currentItemKey ?? null,
|
||||||
|
itemKeyByIndex: meta.itemKeyByIndex ?? {},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
export function finishDownload() {
|
||||||
|
setState({
|
||||||
|
active: false,
|
||||||
|
scope: null,
|
||||||
|
accountId: null,
|
||||||
|
progress: null,
|
||||||
|
currentItemKey: null,
|
||||||
|
itemKeyByIndex: {},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
export function setDownloadItemStatus(itemKey: string, status: DownloadItemResult) {
|
||||||
|
setState({
|
||||||
|
itemStatusByKey: {
|
||||||
|
...state.itemStatusByKey,
|
||||||
|
[itemKey]: status,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
export function subscribeDownloadState(listener: () => void) {
|
||||||
|
listeners.add(listener);
|
||||||
|
return () => {
|
||||||
|
listeners.delete(listener);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
export function getDownloadState() {
|
||||||
|
return state;
|
||||||
|
}
|
||||||
|
export function useDownloadState() {
|
||||||
|
return useSyncExternalStore(subscribeDownloadState, getDownloadState, getDownloadState);
|
||||||
|
}
|
||||||
@@ -11,12 +11,10 @@ export interface FetchState {
|
|||||||
retweets: boolean;
|
retweets: boolean;
|
||||||
timelineType: string;
|
timelineType: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
function normalizeFetchState(state: FetchState | null | undefined): FetchState | null {
|
function normalizeFetchState(state: FetchState | null | undefined): FetchState | null {
|
||||||
if (!state) {
|
if (!state) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
...state,
|
...state,
|
||||||
cursor: state.cursor || "",
|
cursor: state.cursor || "",
|
||||||
@@ -26,7 +24,6 @@ function normalizeFetchState(state: FetchState | null | undefined): FetchState |
|
|||||||
timelineType: state.timelineType || "timeline",
|
timelineType: state.timelineType || "timeline",
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export function saveFetchState(state: Partial<FetchState> & {
|
export function saveFetchState(state: Partial<FetchState> & {
|
||||||
username: string;
|
username: string;
|
||||||
}): void {
|
}): void {
|
||||||
|
|||||||
@@ -1,16 +1,13 @@
|
|||||||
export type DependencyName = "extractor" | "ffmpeg" | "exiftool";
|
export type DependencyName = "extractor" | "ffmpeg" | "exiftool";
|
||||||
|
|
||||||
export interface CachedDependencyStatus {
|
export interface CachedDependencyStatus {
|
||||||
installed: boolean | null;
|
installed: boolean | null;
|
||||||
installedVersion: string | null;
|
installedVersion: string | null;
|
||||||
latestVersion: string | null;
|
latestVersion: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface CachedMediaFolderStatus {
|
export interface CachedMediaFolderStatus {
|
||||||
folderExists: boolean;
|
folderExists: boolean;
|
||||||
gifsFolderHasMP4: boolean;
|
gifsFolderHasMP4: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
const dependencyStatusCache: Record<DependencyName, CachedDependencyStatus> = {
|
const dependencyStatusCache: Record<DependencyName, CachedDependencyStatus> = {
|
||||||
extractor: {
|
extractor: {
|
||||||
installed: null,
|
installed: null,
|
||||||
@@ -28,28 +25,22 @@ const dependencyStatusCache: Record<DependencyName, CachedDependencyStatus> = {
|
|||||||
latestVersion: null,
|
latestVersion: null,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
const mediaFolderStatusCache = new Map<string, CachedMediaFolderStatus>();
|
const mediaFolderStatusCache = new Map<string, CachedMediaFolderStatus>();
|
||||||
|
|
||||||
function getMediaFolderStatusKey(downloadPath: string, folderName: string): string {
|
function getMediaFolderStatusKey(downloadPath: string, folderName: string): string {
|
||||||
return `${downloadPath}::${folderName}`;
|
return `${downloadPath}::${folderName}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getCachedDependencyStatus(name: DependencyName): CachedDependencyStatus {
|
export function getCachedDependencyStatus(name: DependencyName): CachedDependencyStatus {
|
||||||
return { ...dependencyStatusCache[name] };
|
return { ...dependencyStatusCache[name] };
|
||||||
}
|
}
|
||||||
|
|
||||||
export function setCachedDependencyStatus(name: DependencyName, status: Partial<CachedDependencyStatus>): void {
|
export function setCachedDependencyStatus(name: DependencyName, status: Partial<CachedDependencyStatus>): void {
|
||||||
dependencyStatusCache[name] = {
|
dependencyStatusCache[name] = {
|
||||||
...dependencyStatusCache[name],
|
...dependencyStatusCache[name],
|
||||||
...status,
|
...status,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getCachedMediaFolderStatus(downloadPath: string, folderName: string): CachedMediaFolderStatus | null {
|
export function getCachedMediaFolderStatus(downloadPath: string, folderName: string): CachedMediaFolderStatus | null {
|
||||||
return mediaFolderStatusCache.get(getMediaFolderStatusKey(downloadPath, folderName)) ?? null;
|
return mediaFolderStatusCache.get(getMediaFolderStatusKey(downloadPath, folderName)) ?? null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function setCachedMediaFolderStatus(downloadPath: string, folderName: string, status: CachedMediaFolderStatus): void {
|
export function setCachedMediaFolderStatus(downloadPath: string, folderName: string, status: CachedMediaFolderStatus): void {
|
||||||
mediaFolderStatusCache.set(getMediaFolderStatusKey(downloadPath, folderName), status);
|
mediaFolderStatusCache.set(getMediaFolderStatusKey(downloadPath, folderName), status);
|
||||||
}
|
}
|
||||||
+217
-59
@@ -1,78 +1,206 @@
|
|||||||
import { GetDefaults } from "../../wailsjs/go/main/App";
|
import { GetDefaults } from "../../wailsjs/go/main/App";
|
||||||
|
export type BuiltInFontFamily = "google-sans" | "inter" | "poppins" | "roboto" | "dm-sans" | "plus-jakarta-sans" | "manrope" | "space-grotesk" | "noto-sans" | "nunito-sans" | "figtree" | "raleway" | "public-sans" | "outfit" | "jetbrains-mono" | "geist-sans" | "bricolage-grotesque";
|
||||||
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 CustomFontFamily = `custom-${string}`;
|
||||||
export type FontFamily = BuiltInFontFamily | CustomFontFamily;
|
export type FontFamily = BuiltInFontFamily | CustomFontFamily;
|
||||||
|
|
||||||
export interface CustomFontOption {
|
export interface CustomFontOption {
|
||||||
value: CustomFontFamily;
|
value: CustomFontFamily;
|
||||||
label: string;
|
label: string;
|
||||||
fontFamily: string;
|
fontFamily: string;
|
||||||
url: string;
|
url: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface FontOption {
|
export interface FontOption {
|
||||||
value: FontFamily;
|
value: FontFamily;
|
||||||
label: string;
|
label: string;
|
||||||
fontFamily: string;
|
fontFamily: string;
|
||||||
url?: string;
|
url?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export type GifQuality = "fast" | "better";
|
export type GifQuality = "fast" | "better";
|
||||||
export type GifResolution = "original" | "high" | "medium" | "low";
|
export type GifResolution = "original" | "high" | "medium" | "low";
|
||||||
export type FetchMode = "single" | "batch";
|
export type VideoQuality = "highest" | "720" | "480" | "360" | "lowest";
|
||||||
export type MediaType = "all" | "image" | "video" | "gif" | "text";
|
export type ImageSize = "orig" | "large" | "medium" | "small";
|
||||||
|
export type AvatarSize = "orig" | "400x400" | "200x200" | "bigger" | "normal";
|
||||||
|
export type BannerSize = "orig" | "1500x500" | "600x200" | "300x100";
|
||||||
|
export const VIDEO_QUALITIES: {
|
||||||
|
value: VideoQuality;
|
||||||
|
label: string;
|
||||||
|
}[] = [
|
||||||
|
{ value: "highest", label: "Highest" },
|
||||||
|
{ value: "720", label: "720p" },
|
||||||
|
{ value: "480", label: "480p" },
|
||||||
|
{ value: "360", label: "360p" },
|
||||||
|
{ value: "lowest", label: "Lowest" },
|
||||||
|
];
|
||||||
|
export const IMAGE_SIZES: {
|
||||||
|
value: ImageSize;
|
||||||
|
label: string;
|
||||||
|
}[] = [
|
||||||
|
{ value: "orig", label: "Original" },
|
||||||
|
{ value: "large", label: "Large" },
|
||||||
|
{ value: "medium", label: "Medium" },
|
||||||
|
{ value: "small", label: "Small" },
|
||||||
|
];
|
||||||
|
export const AVATAR_SIZES: {
|
||||||
|
value: AvatarSize;
|
||||||
|
label: string;
|
||||||
|
}[] = [
|
||||||
|
{ value: "orig", label: "Original" },
|
||||||
|
{ value: "400x400", label: "400px" },
|
||||||
|
{ value: "200x200", label: "200px" },
|
||||||
|
{ value: "bigger", label: "Bigger" },
|
||||||
|
{ value: "normal", label: "Normal" },
|
||||||
|
];
|
||||||
|
export const BANNER_SIZES: {
|
||||||
|
value: BannerSize;
|
||||||
|
label: string;
|
||||||
|
}[] = [
|
||||||
|
{ value: "orig", label: "Original" },
|
||||||
|
{ value: "1500x500", label: "1500×500" },
|
||||||
|
{ value: "600x200", label: "600×200" },
|
||||||
|
{ value: "300x100", label: "300×100" },
|
||||||
|
];
|
||||||
|
export const DEFAULT_FILENAME_TEMPLATE = "{handle}_{date}_{tweet_id}";
|
||||||
|
export interface TemplateToken {
|
||||||
|
key: string;
|
||||||
|
description: string;
|
||||||
|
example: string;
|
||||||
|
}
|
||||||
|
export const FILENAME_TEMPLATE_VARIABLES: TemplateToken[] = [
|
||||||
|
{ key: "{handle}", description: "Author handle", example: "elonmusk" },
|
||||||
|
{ key: "{name}", description: "Author display name", example: "Elon Musk" },
|
||||||
|
{ key: "{date}", description: "Tweet date & time", example: "20250620_104556" },
|
||||||
|
{ key: "{tweet_id}", description: "Tweet ID", example: "1989033613824815258" },
|
||||||
|
{ key: "{media_id}", description: "Unique media ID (prevents overwrites)", example: "Gx1aB2cXkAA7Yz9" },
|
||||||
|
{ key: "{type}", description: "Media type", example: "photo" },
|
||||||
|
];
|
||||||
|
export interface FilenameTemplateData {
|
||||||
|
username?: string;
|
||||||
|
accountName?: string;
|
||||||
|
date?: string;
|
||||||
|
tweetId?: string;
|
||||||
|
index?: number;
|
||||||
|
mediaID?: string;
|
||||||
|
type?: string;
|
||||||
|
}
|
||||||
|
export const SAMPLE_FILENAME_DATA: FilenameTemplateData = {
|
||||||
|
username: "elonmusk",
|
||||||
|
accountName: "Elon Musk",
|
||||||
|
date: "20250620_104556",
|
||||||
|
tweetId: "1989033613824815258",
|
||||||
|
index: 1,
|
||||||
|
mediaID: "Gx1aB2cXkAA7Yz9",
|
||||||
|
type: "photo",
|
||||||
|
};
|
||||||
|
function sanitizeTemplatePart(input: string): string {
|
||||||
|
const cleaned = input
|
||||||
|
.replace(/[\u0000-\u001f\\/:*?"<>|]/g, "")
|
||||||
|
.trim()
|
||||||
|
.replace(/[. ]+$/g, "");
|
||||||
|
return /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i.test(cleaned) ? `${cleaned}_` : cleaned;
|
||||||
|
}
|
||||||
|
export function renderFilenameTemplate(template: string, data: FilenameTemplateData): string {
|
||||||
|
if (!template)
|
||||||
|
return "";
|
||||||
|
return sanitizeTemplatePart(template
|
||||||
|
.replace(/\{handle\}/g, sanitizeTemplatePart(data.username ?? ""))
|
||||||
|
.replace(/\{name\}/g, sanitizeTemplatePart(data.accountName ?? ""))
|
||||||
|
.replace(/\{username\}/g, sanitizeTemplatePart(data.username ?? ""))
|
||||||
|
.replace(/\{account_name\}/g, sanitizeTemplatePart(data.accountName ?? ""))
|
||||||
|
.replace(/\{date\}/g, sanitizeTemplatePart(data.date ?? ""))
|
||||||
|
.replace(/\{tweet_id\}/g, sanitizeTemplatePart(data.tweetId ?? ""))
|
||||||
|
.replace(/\{index\}/g, String(data.index ?? 1).padStart(2, "0"))
|
||||||
|
.replace(/\{media_id\}/g, sanitizeTemplatePart(data.mediaID ?? ""))
|
||||||
|
.replace(/\{type\}/g, sanitizeTemplatePart(data.type ?? ""))
|
||||||
|
.trim());
|
||||||
|
}
|
||||||
|
export const DEFAULT_FOLDER_TEMPLATE = "{handle}";
|
||||||
|
export const FOLDER_TEMPLATE_VARIABLES: TemplateToken[] = [
|
||||||
|
{ key: "{handle}", description: "Author handle", example: "elonmusk" },
|
||||||
|
{ key: "{name}", description: "Author display name", example: "Elon Musk" },
|
||||||
|
{ key: "{date}", description: "Download date", example: "20250620" },
|
||||||
|
];
|
||||||
|
export interface FolderTemplateData {
|
||||||
|
username?: string;
|
||||||
|
accountName?: string;
|
||||||
|
date?: string;
|
||||||
|
}
|
||||||
|
export const SAMPLE_FOLDER_DATA: FolderTemplateData = {
|
||||||
|
username: "elonmusk",
|
||||||
|
accountName: "Elon Musk",
|
||||||
|
date: "20250620",
|
||||||
|
};
|
||||||
|
export function renderFolderTemplate(template: string, data: FolderTemplateData): string {
|
||||||
|
if (!template)
|
||||||
|
return "";
|
||||||
|
return sanitizeTemplatePart(template
|
||||||
|
.replace(/\{handle\}/g, sanitizeTemplatePart(data.username ?? ""))
|
||||||
|
.replace(/\{name\}/g, sanitizeTemplatePart(data.accountName ?? ""))
|
||||||
|
.replace(/\{username\}/g, sanitizeTemplatePart(data.username ?? ""))
|
||||||
|
.replace(/\{account_name\}/g, sanitizeTemplatePart(data.accountName ?? ""))
|
||||||
|
.replace(/\{date\}/g, sanitizeTemplatePart(data.date ?? ""))
|
||||||
|
.trim());
|
||||||
|
}
|
||||||
|
const DEFAULT_CONCURRENT_DOWNLOADS = 10;
|
||||||
|
const MIN_CONCURRENT_DOWNLOADS = 1;
|
||||||
|
const MAX_CONCURRENT_DOWNLOADS = 50;
|
||||||
|
const DEFAULT_RETRY_ATTEMPTS = 1;
|
||||||
|
const MIN_RETRY_ATTEMPTS = 1;
|
||||||
|
const MAX_RETRY_ATTEMPTS = 5;
|
||||||
export interface Settings {
|
export interface Settings {
|
||||||
downloadPath: string;
|
downloadPath: string;
|
||||||
|
concurrentDownloads: number;
|
||||||
|
skipExistingFiles: boolean;
|
||||||
|
deleteIncompleteFiles: boolean;
|
||||||
|
retryAttempts: number;
|
||||||
theme: string;
|
theme: string;
|
||||||
themeMode: "auto" | "light" | "dark";
|
themeMode: "auto" | "light" | "dark";
|
||||||
fontFamily: FontFamily;
|
fontFamily: FontFamily;
|
||||||
customFonts: CustomFontOption[];
|
customFonts: CustomFontOption[];
|
||||||
sfxEnabled: boolean;
|
sfxEnabled: boolean;
|
||||||
|
autoConvertGifs: boolean;
|
||||||
gifQuality: GifQuality;
|
gifQuality: GifQuality;
|
||||||
gifResolution: GifResolution;
|
gifResolution: GifResolution;
|
||||||
proxy: string;
|
proxy: string;
|
||||||
fetchTimeout: number;
|
fetchTimeout: number;
|
||||||
fetchMode: FetchMode;
|
includePhotos: boolean;
|
||||||
mediaType: MediaType;
|
includeVideos: boolean;
|
||||||
|
includeGifs: boolean;
|
||||||
|
includeText: boolean;
|
||||||
includeRetweets: boolean;
|
includeRetweets: boolean;
|
||||||
|
videoQuality: VideoQuality;
|
||||||
|
imageSize: ImageSize;
|
||||||
|
avatarSize: AvatarSize;
|
||||||
|
bannerSize: BannerSize;
|
||||||
|
filenameTemplate: string;
|
||||||
|
folderTemplate: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const DEFAULT_SETTINGS: Settings = {
|
export const DEFAULT_SETTINGS: Settings = {
|
||||||
downloadPath: "",
|
downloadPath: "",
|
||||||
|
concurrentDownloads: DEFAULT_CONCURRENT_DOWNLOADS,
|
||||||
|
skipExistingFiles: true,
|
||||||
|
deleteIncompleteFiles: true,
|
||||||
|
retryAttempts: DEFAULT_RETRY_ATTEMPTS,
|
||||||
theme: "yellow",
|
theme: "yellow",
|
||||||
themeMode: "auto",
|
themeMode: "auto",
|
||||||
fontFamily: "google-sans",
|
fontFamily: "google-sans",
|
||||||
customFonts: [],
|
customFonts: [],
|
||||||
sfxEnabled: true,
|
sfxEnabled: true,
|
||||||
|
autoConvertGifs: false,
|
||||||
gifQuality: "fast",
|
gifQuality: "fast",
|
||||||
gifResolution: "original",
|
gifResolution: "original",
|
||||||
proxy: "",
|
proxy: "",
|
||||||
fetchTimeout: 60,
|
fetchTimeout: 60,
|
||||||
fetchMode: "batch",
|
includePhotos: true,
|
||||||
mediaType: "all",
|
includeVideos: true,
|
||||||
|
includeGifs: true,
|
||||||
|
includeText: false,
|
||||||
includeRetweets: false,
|
includeRetweets: false,
|
||||||
|
videoQuality: "highest",
|
||||||
|
imageSize: "orig",
|
||||||
|
avatarSize: "orig",
|
||||||
|
bannerSize: "orig",
|
||||||
|
filenameTemplate: DEFAULT_FILENAME_TEMPLATE,
|
||||||
|
folderTemplate: DEFAULT_FOLDER_TEMPLATE,
|
||||||
};
|
};
|
||||||
|
|
||||||
export const FONT_OPTIONS: FontOption[] = [
|
export const FONT_OPTIONS: FontOption[] = [
|
||||||
{
|
{
|
||||||
value: "bricolage-grotesque",
|
value: "bricolage-grotesque",
|
||||||
@@ -160,13 +288,11 @@ export const FONT_OPTIONS: FontOption[] = [
|
|||||||
fontFamily: '"Space Grotesk", system-ui, sans-serif',
|
fontFamily: '"Space Grotesk", system-ui, sans-serif',
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
const BUILT_IN_FONT_VALUES = new Set(FONT_OPTIONS.map((font) => font.value));
|
const BUILT_IN_FONT_VALUES = new Set(FONT_OPTIONS.map((font) => font.value));
|
||||||
const SETTINGS_KEY = "twitter-media-downloader-settings";
|
const SETTINGS_KEY = "twitter-media-downloader-settings";
|
||||||
const GOOGLE_FONT_LINK_ID_PREFIX = "twitter-media-custom-font-";
|
const GOOGLE_FONT_LINK_ID_PREFIX = "twitter-media-custom-font-";
|
||||||
const GOOGLE_FONTS_CSS_HOST = "fonts.googleapis.com";
|
const GOOGLE_FONTS_CSS_HOST = "fonts.googleapis.com";
|
||||||
const GOOGLE_FONTS_SPECIMEN_HOST = "fonts.google.com";
|
const GOOGLE_FONTS_SPECIMEN_HOST = "fonts.google.com";
|
||||||
|
|
||||||
function extractGoogleFontInputUrl(input: string): string {
|
function extractGoogleFontInputUrl(input: string): string {
|
||||||
const trimmed = input.trim();
|
const trimmed = input.trim();
|
||||||
const hrefMatch = trimmed.match(/\bhref=["']([^"']+)["']/i);
|
const hrefMatch = trimmed.match(/\bhref=["']([^"']+)["']/i);
|
||||||
@@ -179,7 +305,6 @@ function extractGoogleFontInputUrl(input: string): string {
|
|||||||
}
|
}
|
||||||
return trimmed;
|
return trimmed;
|
||||||
}
|
}
|
||||||
|
|
||||||
function coerceGoogleFontUrl(rawUrl: string): string {
|
function coerceGoogleFontUrl(rawUrl: string): string {
|
||||||
const trimmed = rawUrl.trim();
|
const trimmed = rawUrl.trim();
|
||||||
if (/^https?:\/\//i.test(trimmed)) {
|
if (/^https?:\/\//i.test(trimmed)) {
|
||||||
@@ -190,34 +315,28 @@ function coerceGoogleFontUrl(rawUrl: string): string {
|
|||||||
}
|
}
|
||||||
return trimmed;
|
return trimmed;
|
||||||
}
|
}
|
||||||
|
|
||||||
function normalizeFontLabel(label: string): string {
|
function normalizeFontLabel(label: string): string {
|
||||||
return label.replace(/\+/g, " ").replace(/\s+/g, " ").trim();
|
return label.replace(/\+/g, " ").replace(/\s+/g, " ").trim();
|
||||||
}
|
}
|
||||||
|
|
||||||
function slugifyFontLabel(label: string): string {
|
function slugifyFontLabel(label: string): string {
|
||||||
return label.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "font";
|
return label.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "font";
|
||||||
}
|
}
|
||||||
|
|
||||||
function toFontFamilyCss(label: string): string {
|
function toFontFamilyCss(label: string): string {
|
||||||
const escapedLabel = label.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
|
const escapedLabel = label.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
|
||||||
return `"${escapedLabel}", system-ui, sans-serif`;
|
return `"${escapedLabel}", system-ui, sans-serif`;
|
||||||
}
|
}
|
||||||
|
|
||||||
function buildGoogleFontsCssUrl(label: string): string {
|
function buildGoogleFontsCssUrl(label: string): string {
|
||||||
const url = new URL("https://fonts.googleapis.com/css2");
|
const url = new URL("https://fonts.googleapis.com/css2");
|
||||||
url.searchParams.set("family", label);
|
url.searchParams.set("family", label);
|
||||||
url.searchParams.set("display", "swap");
|
url.searchParams.set("display", "swap");
|
||||||
return url.toString();
|
return url.toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
function extractSpecimenFontLabel(parsed: URL): string {
|
function extractSpecimenFontLabel(parsed: URL): string {
|
||||||
const segments = parsed.pathname.split("/").filter(Boolean);
|
const segments = parsed.pathname.split("/").filter(Boolean);
|
||||||
const specimenIndex = segments.findIndex((segment) => segment.toLowerCase() === "specimen");
|
const specimenIndex = segments.findIndex((segment) => segment.toLowerCase() === "specimen");
|
||||||
const specimenName = specimenIndex >= 0 ? segments[specimenIndex + 1] : "";
|
const specimenName = specimenIndex >= 0 ? segments[specimenIndex + 1] : "";
|
||||||
return normalizeFontLabel(decodeURIComponent(specimenName || ""));
|
return normalizeFontLabel(decodeURIComponent(specimenName || ""));
|
||||||
}
|
}
|
||||||
|
|
||||||
function normalizeGoogleFontCssUrl(rawUrl: string): string | null {
|
function normalizeGoogleFontCssUrl(rawUrl: string): string | null {
|
||||||
try {
|
try {
|
||||||
const parsed = new URL(coerceGoogleFontUrl(extractGoogleFontInputUrl(rawUrl)));
|
const parsed = new URL(coerceGoogleFontUrl(extractGoogleFontInputUrl(rawUrl)));
|
||||||
@@ -243,7 +362,6 @@ function normalizeGoogleFontCssUrl(rawUrl: string): string | null {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function parseGoogleFontUrl(rawUrl: string): CustomFontOption | null {
|
export function parseGoogleFontUrl(rawUrl: string): CustomFontOption | null {
|
||||||
const normalizedUrl = normalizeGoogleFontCssUrl(rawUrl);
|
const normalizedUrl = normalizeGoogleFontCssUrl(rawUrl);
|
||||||
if (!normalizedUrl) {
|
if (!normalizedUrl) {
|
||||||
@@ -262,7 +380,6 @@ export function parseGoogleFontUrl(rawUrl: string): CustomFontOption | null {
|
|||||||
url: normalizedUrl,
|
url: normalizedUrl,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function normalizeCustomFonts(customFonts: unknown): CustomFontOption[] {
|
function normalizeCustomFonts(customFonts: unknown): CustomFontOption[] {
|
||||||
if (!Array.isArray(customFonts)) {
|
if (!Array.isArray(customFonts)) {
|
||||||
return [];
|
return [];
|
||||||
@@ -274,7 +391,9 @@ function normalizeCustomFonts(customFonts: unknown): CustomFontOption[] {
|
|||||||
if (!item || typeof item !== "object") {
|
if (!item || typeof item !== "object") {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
const rawUrl = (item as { url?: unknown }).url;
|
const rawUrl = (item as {
|
||||||
|
url?: unknown;
|
||||||
|
}).url;
|
||||||
if (typeof rawUrl !== "string") {
|
if (typeof rawUrl !== "string") {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -288,7 +407,6 @@ function normalizeCustomFonts(customFonts: unknown): CustomFontOption[] {
|
|||||||
}
|
}
|
||||||
return normalizedFonts;
|
return normalizedFonts;
|
||||||
}
|
}
|
||||||
|
|
||||||
function normalizeFontFamily(fontFamily: unknown, customFonts: CustomFontOption[]): FontFamily {
|
function normalizeFontFamily(fontFamily: unknown, customFonts: CustomFontOption[]): FontFamily {
|
||||||
if (typeof fontFamily !== "string") {
|
if (typeof fontFamily !== "string") {
|
||||||
return DEFAULT_SETTINGS.fontFamily;
|
return DEFAULT_SETTINGS.fontFamily;
|
||||||
@@ -299,11 +417,56 @@ function normalizeFontFamily(fontFamily: unknown, customFonts: CustomFontOption[
|
|||||||
const customFont = customFonts.find((font) => font.value === fontFamily);
|
const customFont = customFonts.find((font) => font.value === fontFamily);
|
||||||
return customFont ? customFont.value : DEFAULT_SETTINGS.fontFamily;
|
return customFont ? customFont.value : DEFAULT_SETTINGS.fontFamily;
|
||||||
}
|
}
|
||||||
|
function normalizeConcurrentDownloads(value: unknown): number {
|
||||||
|
if (typeof value !== "number" || !Number.isFinite(value)) {
|
||||||
|
return DEFAULT_CONCURRENT_DOWNLOADS;
|
||||||
|
}
|
||||||
|
const rounded = Math.round(value);
|
||||||
|
if (rounded < MIN_CONCURRENT_DOWNLOADS) {
|
||||||
|
return MIN_CONCURRENT_DOWNLOADS;
|
||||||
|
}
|
||||||
|
if (rounded > MAX_CONCURRENT_DOWNLOADS) {
|
||||||
|
return MAX_CONCURRENT_DOWNLOADS;
|
||||||
|
}
|
||||||
|
return rounded;
|
||||||
|
}
|
||||||
|
function normalizeBoolean(value: unknown, fallback: boolean): boolean {
|
||||||
|
if (typeof value === "boolean") {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
return fallback;
|
||||||
|
}
|
||||||
|
function normalizeRetryAttempts(value: unknown): number {
|
||||||
|
if (typeof value !== "number" || !Number.isFinite(value)) {
|
||||||
|
return DEFAULT_RETRY_ATTEMPTS;
|
||||||
|
}
|
||||||
|
const rounded = Math.round(value);
|
||||||
|
if (rounded < MIN_RETRY_ATTEMPTS) {
|
||||||
|
return MIN_RETRY_ATTEMPTS;
|
||||||
|
}
|
||||||
|
if (rounded > MAX_RETRY_ATTEMPTS) {
|
||||||
|
return MAX_RETRY_ATTEMPTS;
|
||||||
|
}
|
||||||
|
return rounded;
|
||||||
|
}
|
||||||
|
function normalizeTemplateTokens(value: unknown, fallback: string): string {
|
||||||
|
if (typeof value !== "string") {
|
||||||
|
return fallback;
|
||||||
|
}
|
||||||
|
return value
|
||||||
|
.replace(/\{username\}/g, "{handle}")
|
||||||
|
.replace(/\{account_name\}/g, "{name}");
|
||||||
|
}
|
||||||
|
function normalizeFilenameTemplate(value: unknown): string {
|
||||||
|
const template = normalizeTemplateTokens(value, DEFAULT_FILENAME_TEMPLATE);
|
||||||
|
return template === "{handle}_{date}_{tweet_id}_{index}" ? DEFAULT_FILENAME_TEMPLATE : template;
|
||||||
|
}
|
||||||
|
function normalizeFolderTemplate(value: unknown): string {
|
||||||
|
return normalizeTemplateTokens(value, DEFAULT_FOLDER_TEMPLATE);
|
||||||
|
}
|
||||||
export function getFontOptions(customFonts: CustomFontOption[] = []): FontOption[] {
|
export function getFontOptions(customFonts: CustomFontOption[] = []): FontOption[] {
|
||||||
return [...FONT_OPTIONS, ...normalizeCustomFonts(customFonts)];
|
return [...FONT_OPTIONS, ...normalizeCustomFonts(customFonts)];
|
||||||
}
|
}
|
||||||
|
|
||||||
export function loadGoogleFontUrl(url: string, id = `${GOOGLE_FONT_LINK_ID_PREFIX}preview`): void {
|
export function loadGoogleFontUrl(url: string, id = `${GOOGLE_FONT_LINK_ID_PREFIX}preview`): void {
|
||||||
const normalizedUrl = normalizeGoogleFontCssUrl(url);
|
const normalizedUrl = normalizeGoogleFontCssUrl(url);
|
||||||
if (!normalizedUrl) {
|
if (!normalizedUrl) {
|
||||||
@@ -320,13 +483,11 @@ export function loadGoogleFontUrl(url: string, id = `${GOOGLE_FONT_LINK_ID_PREFI
|
|||||||
link.href = normalizedUrl;
|
link.href = normalizedUrl;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function loadCustomFontStylesheets(customFonts: CustomFontOption[]): void {
|
function loadCustomFontStylesheets(customFonts: CustomFontOption[]): void {
|
||||||
for (const font of normalizeCustomFonts(customFonts)) {
|
for (const font of normalizeCustomFonts(customFonts)) {
|
||||||
loadGoogleFontUrl(font.url, `${GOOGLE_FONT_LINK_ID_PREFIX}${font.value}`);
|
loadGoogleFontUrl(font.url, `${GOOGLE_FONT_LINK_ID_PREFIX}${font.value}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function applyFont(fontFamily: FontFamily, customFonts: CustomFontOption[] = []): void {
|
export function applyFont(fontFamily: FontFamily, customFonts: CustomFontOption[] = []): void {
|
||||||
const fontOptions = getFontOptions(customFonts);
|
const fontOptions = getFontOptions(customFonts);
|
||||||
loadCustomFontStylesheets(customFonts);
|
loadCustomFontStylesheets(customFonts);
|
||||||
@@ -336,7 +497,6 @@ export function applyFont(fontFamily: FontFamily, customFonts: CustomFontOption[
|
|||||||
document.body.style.fontFamily = font.fontFamily;
|
document.body.style.fontFamily = font.fontFamily;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function fetchDefaultPath(): Promise<string> {
|
async function fetchDefaultPath(): Promise<string> {
|
||||||
try {
|
try {
|
||||||
const data = await GetDefaults();
|
const data = await GetDefaults();
|
||||||
@@ -347,17 +507,22 @@ async function fetchDefaultPath(): Promise<string> {
|
|||||||
return "";
|
return "";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function toNormalizedSettings(settings: Partial<Settings>): Settings {
|
function toNormalizedSettings(settings: Partial<Settings>): Settings {
|
||||||
const customFonts = normalizeCustomFonts(settings.customFonts);
|
const customFonts = normalizeCustomFonts(settings.customFonts);
|
||||||
return {
|
return {
|
||||||
...DEFAULT_SETTINGS,
|
...DEFAULT_SETTINGS,
|
||||||
...settings,
|
...settings,
|
||||||
|
concurrentDownloads: normalizeConcurrentDownloads(settings.concurrentDownloads),
|
||||||
|
skipExistingFiles: normalizeBoolean(settings.skipExistingFiles, DEFAULT_SETTINGS.skipExistingFiles),
|
||||||
|
deleteIncompleteFiles: normalizeBoolean(settings.deleteIncompleteFiles, DEFAULT_SETTINGS.deleteIncompleteFiles),
|
||||||
|
retryAttempts: normalizeRetryAttempts(settings.retryAttempts),
|
||||||
|
autoConvertGifs: normalizeBoolean(settings.autoConvertGifs, DEFAULT_SETTINGS.autoConvertGifs),
|
||||||
|
filenameTemplate: normalizeFilenameTemplate(settings.filenameTemplate),
|
||||||
|
folderTemplate: normalizeFolderTemplate(settings.folderTemplate),
|
||||||
customFonts,
|
customFonts,
|
||||||
fontFamily: normalizeFontFamily(settings.fontFamily, 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);
|
||||||
@@ -370,7 +535,6 @@ export function getSettings(): Settings {
|
|||||||
}
|
}
|
||||||
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 (!settings.downloadPath) {
|
||||||
@@ -378,7 +542,6 @@ export async function getSettingsWithDefaults(): Promise<Settings> {
|
|||||||
}
|
}
|
||||||
return toNormalizedSettings(settings);
|
return toNormalizedSettings(settings);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function saveSettings(settings: Settings): void {
|
export function saveSettings(settings: Settings): void {
|
||||||
try {
|
try {
|
||||||
const normalizedSettings = toNormalizedSettings(settings);
|
const normalizedSettings = toNormalizedSettings(settings);
|
||||||
@@ -388,14 +551,12 @@ export function saveSettings(settings: Settings): void {
|
|||||||
console.error("Failed to save settings:", 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 = toNormalizedSettings({ ...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 = toNormalizedSettings({
|
const defaultSettings = toNormalizedSettings({
|
||||||
@@ -405,11 +566,9 @@ export async function resetToDefaultSettings(): Promise<Settings> {
|
|||||||
saveSettings(defaultSettings);
|
saveSettings(defaultSettings);
|
||||||
return defaultSettings;
|
return defaultSettings;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function loadCustomFonts(): Promise<CustomFontOption[]> {
|
export async function loadCustomFonts(): Promise<CustomFontOption[]> {
|
||||||
return normalizeCustomFonts(getSettings().customFonts);
|
return normalizeCustomFonts(getSettings().customFonts);
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function saveCustomFonts(customFonts: CustomFontOption[]): Promise<CustomFontOption[]> {
|
export async function saveCustomFonts(customFonts: CustomFontOption[]): Promise<CustomFontOption[]> {
|
||||||
const normalizedFonts = normalizeCustomFonts(customFonts);
|
const normalizedFonts = normalizeCustomFonts(customFonts);
|
||||||
const settings = getSettings();
|
const settings = getSettings();
|
||||||
@@ -420,7 +579,6 @@ export async function saveCustomFonts(customFonts: CustomFontOption[]): Promise<
|
|||||||
});
|
});
|
||||||
return 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;
|
||||||
|
|||||||
@@ -1,3 +1,7 @@
|
|||||||
|
export interface Thumb {
|
||||||
|
name: string;
|
||||||
|
url: string;
|
||||||
|
}
|
||||||
export interface AccountInfo {
|
export interface AccountInfo {
|
||||||
name: string;
|
name: string;
|
||||||
nick: string;
|
nick: string;
|
||||||
@@ -6,6 +10,16 @@ export interface AccountInfo {
|
|||||||
friends_count: number;
|
friends_count: number;
|
||||||
profile_image: string;
|
profile_image: string;
|
||||||
statuses_count: number;
|
statuses_count: number;
|
||||||
|
bio?: string;
|
||||||
|
banner?: string;
|
||||||
|
location?: string;
|
||||||
|
url?: string;
|
||||||
|
media_count?: number;
|
||||||
|
verified?: boolean;
|
||||||
|
blue_verified?: boolean;
|
||||||
|
protected?: boolean;
|
||||||
|
avatar_variants?: Thumb[];
|
||||||
|
banner_variants?: Thumb[];
|
||||||
}
|
}
|
||||||
export interface TimelineEntry {
|
export interface TimelineEntry {
|
||||||
url: string;
|
url: string;
|
||||||
@@ -16,16 +30,21 @@ export interface TimelineEntry {
|
|||||||
extension: string;
|
extension: string;
|
||||||
width: number;
|
width: number;
|
||||||
height: number;
|
height: number;
|
||||||
|
thumbnail?: string;
|
||||||
|
duration_ms?: number;
|
||||||
|
alt_text?: string;
|
||||||
content?: string;
|
content?: string;
|
||||||
view_count?: number;
|
view_count?: number;
|
||||||
bookmark_count?: number;
|
bookmark_count?: number;
|
||||||
favorite_count?: number;
|
favorite_count?: number;
|
||||||
retweet_count?: number;
|
retweet_count?: number;
|
||||||
reply_count?: number;
|
reply_count?: number;
|
||||||
|
quote_count?: number;
|
||||||
source?: string;
|
source?: string;
|
||||||
verified?: boolean;
|
verified?: boolean;
|
||||||
original_filename?: string;
|
original_filename?: string;
|
||||||
author_username?: string;
|
author_username?: string;
|
||||||
|
author_name?: string;
|
||||||
}
|
}
|
||||||
export interface ExtractMetadata {
|
export interface ExtractMetadata {
|
||||||
new_entries: number;
|
new_entries: number;
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
{
|
{
|
||||||
"compilerOptions": {
|
"compilerOptions": {
|
||||||
|
"ignoreDeprecations": "6.0",
|
||||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
|
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
|
||||||
"target": "ES2022",
|
"target": "ES2022",
|
||||||
"useDefineForClassFields": true,
|
"useDefineForClassFields": true,
|
||||||
|
|||||||
Vendored
+2
@@ -31,6 +31,8 @@ export function DownloadMedia(arg1:main.DownloadMediaRequest):Promise<main.Downl
|
|||||||
|
|
||||||
export function DownloadMediaWithMetadata(arg1:main.DownloadMediaWithMetadataRequest):Promise<main.DownloadMediaResponse>;
|
export function DownloadMediaWithMetadata(arg1:main.DownloadMediaWithMetadataRequest):Promise<main.DownloadMediaResponse>;
|
||||||
|
|
||||||
|
export function DownloadProfileImage(arg1:main.DownloadProfileImageRequest):Promise<string>;
|
||||||
|
|
||||||
export function ExportAccountJSON(arg1:number,arg2:string):Promise<string>;
|
export function ExportAccountJSON(arg1:number,arg2:string):Promise<string>;
|
||||||
|
|
||||||
export function ExportAccountsTXT(arg1:Array<number>,arg2:string):Promise<string>;
|
export function ExportAccountsTXT(arg1:Array<number>,arg2:string):Promise<string>;
|
||||||
|
|||||||
@@ -58,6 +58,10 @@ export function DownloadMediaWithMetadata(arg1) {
|
|||||||
return window['go']['main']['App']['DownloadMediaWithMetadata'](arg1);
|
return window['go']['main']['App']['DownloadMediaWithMetadata'](arg1);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function DownloadProfileImage(arg1) {
|
||||||
|
return window['go']['main']['App']['DownloadProfileImage'](arg1);
|
||||||
|
}
|
||||||
|
|
||||||
export function ExportAccountJSON(arg1, arg2) {
|
export function ExportAccountJSON(arg1, arg2) {
|
||||||
return window['go']['main']['App']['ExportAccountJSON'](arg1, arg2);
|
return window['go']['main']['App']['ExportAccountJSON'](arg1, arg2);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -135,6 +135,10 @@ export namespace main {
|
|||||||
urls: string[];
|
urls: string[];
|
||||||
output_dir: string;
|
output_dir: string;
|
||||||
username: string;
|
username: string;
|
||||||
|
concurrent_downloads?: number;
|
||||||
|
skip_existing: boolean;
|
||||||
|
delete_incomplete_files: boolean;
|
||||||
|
retry_attempts?: number;
|
||||||
proxy?: string;
|
proxy?: string;
|
||||||
|
|
||||||
static createFrom(source: any = {}) {
|
static createFrom(source: any = {}) {
|
||||||
@@ -146,6 +150,10 @@ export namespace main {
|
|||||||
this.urls = source["urls"];
|
this.urls = source["urls"];
|
||||||
this.output_dir = source["output_dir"];
|
this.output_dir = source["output_dir"];
|
||||||
this.username = source["username"];
|
this.username = source["username"];
|
||||||
|
this.concurrent_downloads = source["concurrent_downloads"];
|
||||||
|
this.skip_existing = source["skip_existing"];
|
||||||
|
this.delete_incomplete_files = source["delete_incomplete_files"];
|
||||||
|
this.retry_attempts = source["retry_attempts"];
|
||||||
this.proxy = source["proxy"];
|
this.proxy = source["proxy"];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -179,6 +187,7 @@ export namespace main {
|
|||||||
content?: string;
|
content?: string;
|
||||||
original_filename?: string;
|
original_filename?: string;
|
||||||
author_username?: string;
|
author_username?: string;
|
||||||
|
account_name?: string;
|
||||||
|
|
||||||
static createFrom(source: any = {}) {
|
static createFrom(source: any = {}) {
|
||||||
return new MediaItemRequest(source);
|
return new MediaItemRequest(source);
|
||||||
@@ -193,13 +202,23 @@ export namespace main {
|
|||||||
this.content = source["content"];
|
this.content = source["content"];
|
||||||
this.original_filename = source["original_filename"];
|
this.original_filename = source["original_filename"];
|
||||||
this.author_username = source["author_username"];
|
this.author_username = source["author_username"];
|
||||||
|
this.account_name = source["account_name"];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
export class DownloadMediaWithMetadataRequest {
|
export class DownloadMediaWithMetadataRequest {
|
||||||
items: MediaItemRequest[];
|
items: MediaItemRequest[];
|
||||||
output_dir: string;
|
output_dir: string;
|
||||||
username: string;
|
username: string;
|
||||||
|
concurrent_downloads?: number;
|
||||||
|
skip_existing: boolean;
|
||||||
|
delete_incomplete_files: boolean;
|
||||||
|
retry_attempts?: number;
|
||||||
proxy?: string;
|
proxy?: string;
|
||||||
|
filename_template?: string;
|
||||||
|
folder_template?: string;
|
||||||
|
auto_convert_gifs?: boolean;
|
||||||
|
gif_quality?: string;
|
||||||
|
gif_resolution?: string;
|
||||||
|
|
||||||
static createFrom(source: any = {}) {
|
static createFrom(source: any = {}) {
|
||||||
return new DownloadMediaWithMetadataRequest(source);
|
return new DownloadMediaWithMetadataRequest(source);
|
||||||
@@ -210,7 +229,16 @@ export namespace main {
|
|||||||
this.items = this.convertValues(source["items"], MediaItemRequest);
|
this.items = this.convertValues(source["items"], MediaItemRequest);
|
||||||
this.output_dir = source["output_dir"];
|
this.output_dir = source["output_dir"];
|
||||||
this.username = source["username"];
|
this.username = source["username"];
|
||||||
|
this.concurrent_downloads = source["concurrent_downloads"];
|
||||||
|
this.skip_existing = source["skip_existing"];
|
||||||
|
this.delete_incomplete_files = source["delete_incomplete_files"];
|
||||||
|
this.retry_attempts = source["retry_attempts"];
|
||||||
this.proxy = source["proxy"];
|
this.proxy = source["proxy"];
|
||||||
|
this.filename_template = source["filename_template"];
|
||||||
|
this.folder_template = source["folder_template"];
|
||||||
|
this.auto_convert_gifs = source["auto_convert_gifs"];
|
||||||
|
this.gif_quality = source["gif_quality"];
|
||||||
|
this.gif_resolution = source["gif_resolution"];
|
||||||
}
|
}
|
||||||
|
|
||||||
convertValues(a: any, classs: any, asMap: boolean = false): any {
|
convertValues(a: any, classs: any, asMap: boolean = false): any {
|
||||||
@@ -231,6 +259,26 @@ export namespace main {
|
|||||||
return a;
|
return a;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
export class DownloadProfileImageRequest {
|
||||||
|
url: string;
|
||||||
|
output_dir: string;
|
||||||
|
username: string;
|
||||||
|
kind: string;
|
||||||
|
proxy?: string;
|
||||||
|
|
||||||
|
static createFrom(source: any = {}) {
|
||||||
|
return new DownloadProfileImageRequest(source);
|
||||||
|
}
|
||||||
|
|
||||||
|
constructor(source: any = {}) {
|
||||||
|
if ('string' === typeof source) source = JSON.parse(source);
|
||||||
|
this.url = source["url"];
|
||||||
|
this.output_dir = source["output_dir"];
|
||||||
|
this.username = source["username"];
|
||||||
|
this.kind = source["kind"];
|
||||||
|
this.proxy = source["proxy"];
|
||||||
|
}
|
||||||
|
}
|
||||||
export class ImportAccountResponse {
|
export class ImportAccountResponse {
|
||||||
success: boolean;
|
success: boolean;
|
||||||
username: string;
|
username: string;
|
||||||
@@ -257,6 +305,12 @@ export namespace main {
|
|||||||
media_type: string;
|
media_type: string;
|
||||||
retweets: boolean;
|
retweets: boolean;
|
||||||
cursor?: string;
|
cursor?: string;
|
||||||
|
include_photos: boolean;
|
||||||
|
include_videos: boolean;
|
||||||
|
include_gifs: boolean;
|
||||||
|
include_text: boolean;
|
||||||
|
video_quality?: string;
|
||||||
|
image_size?: string;
|
||||||
|
|
||||||
static createFrom(source: any = {}) {
|
static createFrom(source: any = {}) {
|
||||||
return new TimelineRequest(source);
|
return new TimelineRequest(source);
|
||||||
@@ -272,6 +326,12 @@ export namespace main {
|
|||||||
this.media_type = source["media_type"];
|
this.media_type = source["media_type"];
|
||||||
this.retweets = source["retweets"];
|
this.retweets = source["retweets"];
|
||||||
this.cursor = source["cursor"];
|
this.cursor = source["cursor"];
|
||||||
|
this.include_photos = source["include_photos"];
|
||||||
|
this.include_videos = source["include_videos"];
|
||||||
|
this.include_gifs = source["include_gifs"];
|
||||||
|
this.include_text = source["include_text"];
|
||||||
|
this.video_quality = source["video_quality"];
|
||||||
|
this.image_size = source["image_size"];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -11,7 +11,7 @@
|
|||||||
},
|
},
|
||||||
"info": {
|
"info": {
|
||||||
"productName": "Twitter/X Media Batch Downloader",
|
"productName": "Twitter/X Media Batch Downloader",
|
||||||
"productVersion": "4.5"
|
"productVersion": "4.9"
|
||||||
},
|
},
|
||||||
"wailsjsdir": "./frontend",
|
"wailsjsdir": "./frontend",
|
||||||
"assetdir": "./frontend/dist",
|
"assetdir": "./frontend/dist",
|
||||||
|
|||||||
Reference in new issue
Block a user