mirror of
https://github.com/Alvin-Zilverstand/Twitter-X-Media-Batch-Downloader.git
synced 2026-11-24 07:13:11 +01:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
30bcf3db9f | ||
|
|
ada11f086e | ||
|
|
b4266cb7fa | ||
|
|
aa87cce538 | ||
|
|
2d913d987f | ||
|
|
3abba4cc59 | ||
|
|
6417e73da4 | ||
|
|
280133649d | ||
|
|
8e5f18c6cc | ||
|
|
312b6b2c50 | ||
|
|
671209714b | ||
|
|
bc450ff204 | ||
|
|
1ace435160 | ||
|
|
df0de054c8 | ||
|
|
f2a3810c8c | ||
|
|
549d8fde60 | ||
|
|
64bd8b4b2d | ||
|
|
0f2427ad2b | ||
|
|
05e8230063 | ||
|
|
83672f42b6 | ||
|
|
affd36c968 | ||
|
|
281ea82656 | ||
|
|
aa003fab4c | ||
|
|
805fade0fb | ||
|
|
dacf6f5a01 | ||
|
|
fe095afb38 | ||
|
|
e769ea8d20 | ||
|
|
befe838e79 | ||
|
|
b534bc278e | ||
|
|
2e882635eb | ||
|
|
5d5b778c8e | ||
|
|
7cf134f681 | ||
|
|
7d90eb7cb2 | ||
|
|
3d1fd7d1fb | ||
|
|
c0885b1812 | ||
|
|
1ca5c613ae | ||
|
|
596ba9bb3c | ||
|
|
a1cbb04402 | ||
|
|
ddf6439893 | ||
|
|
fed2bf7b0c | ||
|
|
241884de89 | ||
|
|
77b443ace0 | ||
|
|
cd48b6f9bc | ||
|
|
6f45b48047 | ||
|
|
7083c56c8b | ||
|
|
60cb3cbabd | ||
|
|
b38bff238a | ||
|
|
d4d216ed6b | ||
|
|
129c007f6f | ||
|
|
d78ad32c09 | ||
|
|
3975e5dd0e | ||
|
|
37f1d910cb | ||
|
|
74ed38cc31 | ||
|
|
2e326c39a0 | ||
|
|
39c37d4776 | ||
|
|
5709d76ceb | ||
|
|
75b3549653 | ||
|
|
ebe739e612 | ||
|
|
d423f20bad | ||
|
|
fba8a8ac45 | ||
|
|
a36c7613d2 | ||
|
|
c7615ed2f6 | ||
|
|
0c17f1b419 | ||
|
|
dd38880366 | ||
|
|
306d2c3c95 | ||
|
|
1caa59bbcf | ||
|
|
4d0021092c | ||
|
|
981bc8d9ec | ||
|
|
c894bfd4d2 | ||
|
|
61e50b8121 | ||
|
|
ba69dd7cf4 | ||
|
|
bcc332d0d7 | ||
|
|
82184aef33 | ||
|
|
357ad0f020 | ||
|
|
43f4d84593 | ||
|
|
4cecb6b14e | ||
|
|
eb712d5d8d | ||
|
|
46c178fec0 | ||
|
|
8ce5f1f833 | ||
|
|
0a80a3d331 | ||
|
|
f8b27ecb5a | ||
|
|
70e79af700 | ||
|
|
4fb60840a0 | ||
|
|
5613c152f8 | ||
|
|
ad5d7727eb | ||
|
|
ed1f0fce06 | ||
|
|
ee92174773 | ||
|
|
f08ce57feb | ||
|
|
4f21321e42 | ||
|
|
c8b7a5365a | ||
|
|
1049b544c5 | ||
|
|
e7db97a936 | ||
|
|
af1280b798 | ||
|
|
4f6004a501 | ||
|
|
e7141cd8d1 | ||
|
|
4d6f4d904a | ||
|
|
4081e6aacf | ||
|
|
2b405a16a7 | ||
|
|
5e658c05d4 | ||
|
|
b26dd0b2af | ||
|
|
28422dcf1d | ||
|
|
46e09532fc | ||
|
|
967d91d370 | ||
|
|
2ff0242e32 | ||
|
|
1e1d612807 | ||
|
|
9821dd8c65 | ||
|
|
46bb7d38f7 | ||
|
|
112f5992c4 | ||
|
|
178b3c490f |
No files matched your search
+62
@@ -0,0 +1,62 @@
|
||||
# Wails Build
|
||||
build/
|
||||
backend/bin/
|
||||
*.exe
|
||||
*.dll
|
||||
*.dylib
|
||||
*.so
|
||||
|
||||
# Wails Generated Files
|
||||
frontend/wailsjs/
|
||||
|
||||
# Go
|
||||
*.test
|
||||
*.out
|
||||
go.work
|
||||
go.work.sum
|
||||
|
||||
# Node / Frontend
|
||||
node_modules/
|
||||
frontend/node_modules/
|
||||
frontend/dist/
|
||||
frontend/.vite/
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
.pnpm-store/
|
||||
.npm
|
||||
.yarn
|
||||
*.tsbuildinfo
|
||||
|
||||
# IDE / Editors
|
||||
.vscode/
|
||||
.idea/
|
||||
*.swp
|
||||
*.swo
|
||||
*~
|
||||
.DS_Store
|
||||
|
||||
# OS
|
||||
Thumbs.db
|
||||
desktop.ini
|
||||
|
||||
# Environment
|
||||
.env
|
||||
.env.local
|
||||
.env.*.local
|
||||
|
||||
# Logs
|
||||
*.log
|
||||
logs/
|
||||
|
||||
# Temporary files
|
||||
tmp/
|
||||
temp/
|
||||
*.tmp
|
||||
*.bak
|
||||
*.old
|
||||
|
||||
# Build notes (optional - uncomment if you don't want to commit)
|
||||
# BUILD_NOTES.md
|
||||
build.txt
|
||||
@@ -1,79 +0,0 @@
|
||||
import json
|
||||
import re
|
||||
import os
|
||||
from datetime import datetime
|
||||
from gallery_dl.extractor import twitter
|
||||
|
||||
def get_metadata(username, auth_token):
|
||||
url = f"https://x.com/{username}/timeline"
|
||||
|
||||
match = re.match(twitter.TwitterTimelineExtractor.pattern, url)
|
||||
if not match:
|
||||
raise ValueError(f"Invalid URL: {url}")
|
||||
|
||||
extractor = twitter.TwitterTimelineExtractor(match)
|
||||
|
||||
extractor.config = lambda key, default=None: {
|
||||
"cookies": {
|
||||
"auth_token": auth_token
|
||||
}
|
||||
}.get(key, default)
|
||||
|
||||
extractor.initialize()
|
||||
|
||||
output = {
|
||||
'account_info': {},
|
||||
'total_urls': 0,
|
||||
'timeline': []
|
||||
}
|
||||
|
||||
for item in extractor:
|
||||
if isinstance(item, tuple) and len(item) >= 3:
|
||||
media_url = item[1]
|
||||
tweet_data = item[2]
|
||||
|
||||
if not output['account_info']:
|
||||
if 'user' in tweet_data:
|
||||
user = tweet_data['user']
|
||||
user_date = user.get('date', '')
|
||||
if isinstance(user_date, datetime):
|
||||
user_date = user_date.strftime("%Y-%m-%d %H:%M:%S")
|
||||
|
||||
output['account_info'] = {
|
||||
'name': user.get('name', ''),
|
||||
'nick': user.get('nick', ''),
|
||||
'date': user_date,
|
||||
'followers_count': user.get('followers_count', 0),
|
||||
'friends_count': user.get('friends_count', 0),
|
||||
'profile_image': user.get('profile_image', ''),
|
||||
'statuses_count': user.get('statuses_count', 0)
|
||||
}
|
||||
|
||||
if 'pbs.twimg.com' in media_url or 'video.twimg.com' in media_url:
|
||||
tweet_date = tweet_data.get('date', datetime.now())
|
||||
if isinstance(tweet_date, datetime):
|
||||
tweet_date = tweet_date.strftime("%Y-%m-%d %H:%M:%S")
|
||||
|
||||
timeline_entry = {
|
||||
'url': media_url,
|
||||
'date': tweet_date,
|
||||
'tweet_id': tweet_data.get('tweet_id', 0),
|
||||
}
|
||||
|
||||
if 'type' in tweet_data:
|
||||
timeline_entry['type'] = tweet_data['type']
|
||||
|
||||
output['timeline'].append(timeline_entry)
|
||||
output['total_urls'] += 1
|
||||
|
||||
current_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
output_file = os.path.join(current_dir, f"{username}.json")
|
||||
|
||||
with open(output_file, 'w', encoding='utf-8') as f:
|
||||
json.dump(output, f, ensure_ascii=False, indent=2)
|
||||
|
||||
return output
|
||||
|
||||
username = ""
|
||||
auth_token = ""
|
||||
get_metadata(username, auth_token)
|
||||
@@ -1,35 +0,0 @@
|
||||
import json
|
||||
import re
|
||||
import os
|
||||
from gallery_dl.extractor import twitter
|
||||
|
||||
def get_metadata(username, auth_token):
|
||||
url = f"https://x.com/{username}/timeline"
|
||||
|
||||
match = re.match(twitter.TwitterTimelineExtractor.pattern, url)
|
||||
if not match:
|
||||
raise ValueError(f"Invalid URL: {url}")
|
||||
|
||||
extractor = twitter.TwitterTimelineExtractor(match)
|
||||
|
||||
extractor.config = lambda key, default=None: {
|
||||
"cookies": {
|
||||
"auth_token": auth_token
|
||||
}
|
||||
}.get(key, default)
|
||||
|
||||
extractor.initialize()
|
||||
|
||||
all_items = []
|
||||
for item in extractor:
|
||||
all_items.append(item)
|
||||
|
||||
current_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
output_file = os.path.join(current_dir, f"{username}.json")
|
||||
|
||||
with open(output_file, 'w', encoding='utf-8') as f:
|
||||
json.dump(all_items, f, indent=2, default=str)
|
||||
|
||||
username = ""
|
||||
auth_token = ""
|
||||
get_metadata(username, auth_token)
|
||||
@@ -3,55 +3,42 @@
|
||||

|
||||
|
||||
<div align="center">
|
||||
<b>Twitter/X Media Batch Downloader</b> is a GUI tool that allows users to download all media, including images and videos, in their original quality from Twitter/X accounts, even withheld account, using <code>gallery-dl</code>
|
||||
|
||||
A GUI tool to download original-quality images and videos from Twitter/X accounts, powered by gallery-dl by @mikf
|
||||
|
||||

|
||||

|
||||

|
||||
|
||||
</div>
|
||||
|
||||
## 📥 Download
|
||||
### [Download](https://github.com/afkarxyz/SpotiFLAC/releases)
|
||||
|
||||
- Download the latest version of [TwitterXMediaBatchDownloader](https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases/download/v1.9/TwitterXMediaBatchDownloader.exe)
|
||||
- If you're familiar with **userscripts**, please install it [here](https://greasyfork.org/en/scripts/523157-twitter-x-media-batch-downloader)
|
||||
- If you're familiar with userscripts, install it [**here**](https://greasyfork.org/en/scripts/551198)
|
||||
|
||||
## ✨ Features
|
||||
- To install the Chrome extension version, click [**here**](https://www.patreon.com/posts/chrome-extension-139296789)
|
||||
|
||||
- Powered by `gallery-dl`, similar to `yt-dlp`
|
||||
- Supports downloading from **Withheld Accounts**
|
||||
- **Choose media type**: All (Image + GIF + Video) or specific (Image/GIF/Video)
|
||||
- Downloads in original quality
|
||||
|
||||
## 🖼️ Screenshots
|
||||
## Screenshot
|
||||
|
||||

|
||||

|
||||
|
||||

|
||||
|
||||

|
||||
|
||||
> [!Important]
|
||||
> It is highly recommended to use the local `gallery-dl` **(by unchecking "Use API").** Use the API only for withheld accounts, as it has a 60-second timeout limit.
|
||||
|
||||

|
||||
|
||||

|
||||
|
||||
## 🔑 How to Obtain Auth Token
|
||||
## How to Obtain Auth Token
|
||||
|
||||
> [!Warning]
|
||||
> - I suggest not using the **main account** to obtain the token.
|
||||
> - You can use https://temp-mail.io to register a Twitter account.
|
||||
> - Using an auth token or cookies has the potential to get the **account suspended.**
|
||||
> - If too many media files are fetched, it will 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/)
|
||||
2. Log into your account
|
||||
3. Open the Developer Tools by pressing `F12`
|
||||
4. Navigate to the **Application** tab, then select **Storage** > **Cookies**
|
||||
5. Find and copy the `auth_token` value or use the browser extension [X.com Auth Token Grabber](https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases/download/v1.0/X.com.Auth.Token.Grabber.zip)
|
||||
3. Open the Developer Tools by pressing <kbd>F12</kbd>
|
||||
4. Navigate to the **Application** tab, then select **Storage → Cookies**
|
||||
5. Find and copy the `auth_token` value
|
||||
6. Do not log out of your account, as a new `auth_token` will be generated by Twitter
|
||||
|
||||
> X.com Auth Token Grabber
|
||||
|
||||

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

|
||||
|
||||
[](https://ko-fi.com/afkarxyz)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,554 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"twitterxmediabatchdownloader/backend"
|
||||
|
||||
"github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
)
|
||||
|
||||
// App struct
|
||||
type App struct {
|
||||
ctx context.Context
|
||||
downloadCtx context.Context
|
||||
downloadCancel context.CancelFunc
|
||||
}
|
||||
|
||||
// NewApp creates a new App application struct
|
||||
func NewApp() *App {
|
||||
return &App{}
|
||||
}
|
||||
|
||||
// startup is called when the app starts. The context is saved
|
||||
// so we can call the runtime methods
|
||||
func (a *App) startup(ctx context.Context) {
|
||||
a.ctx = ctx
|
||||
// Initialize database
|
||||
backend.InitDB()
|
||||
// Kill any leftover extractor processes from previous session
|
||||
backend.KillAllExtractorProcesses()
|
||||
}
|
||||
|
||||
// shutdown is called when the app is closing
|
||||
func (a *App) shutdown(ctx context.Context) {
|
||||
backend.CloseDB()
|
||||
// Kill any running extractor processes
|
||||
backend.KillAllExtractorProcesses()
|
||||
}
|
||||
|
||||
// CleanupExtractorProcesses kills all running extractor processes
|
||||
// Can be called from frontend when user wants to stop/reset
|
||||
func (a *App) CleanupExtractorProcesses() {
|
||||
backend.KillAllExtractorProcesses()
|
||||
}
|
||||
|
||||
// TimelineRequest represents the request structure for timeline extraction
|
||||
type TimelineRequest struct {
|
||||
Username string `json:"username"`
|
||||
AuthToken string `json:"auth_token"`
|
||||
TimelineType string `json:"timeline_type"`
|
||||
BatchSize int `json:"batch_size"`
|
||||
Page int `json:"page"`
|
||||
MediaType string `json:"media_type"`
|
||||
Retweets bool `json:"retweets"`
|
||||
Cursor string `json:"cursor,omitempty"` // Resume from this cursor position
|
||||
}
|
||||
|
||||
// DateRangeRequest represents the request structure for date range extraction
|
||||
type DateRangeRequest struct {
|
||||
Username string `json:"username"`
|
||||
AuthToken string `json:"auth_token"`
|
||||
StartDate string `json:"start_date"`
|
||||
EndDate string `json:"end_date"`
|
||||
MediaFilter string `json:"media_filter"`
|
||||
Retweets bool `json:"retweets"`
|
||||
}
|
||||
|
||||
// ExtractTimeline extracts media from user timeline
|
||||
func (a *App) ExtractTimeline(req TimelineRequest) (string, error) {
|
||||
// Username not required for bookmarks only
|
||||
if req.Username == "" && req.TimelineType != "bookmarks" {
|
||||
return "", fmt.Errorf("username is required")
|
||||
}
|
||||
if req.AuthToken == "" {
|
||||
return "", fmt.Errorf("auth token is required")
|
||||
}
|
||||
|
||||
backendReq := backend.TimelineRequest{
|
||||
Username: req.Username,
|
||||
AuthToken: req.AuthToken,
|
||||
TimelineType: req.TimelineType,
|
||||
BatchSize: req.BatchSize,
|
||||
Page: req.Page,
|
||||
MediaType: req.MediaType,
|
||||
Retweets: req.Retweets,
|
||||
Cursor: req.Cursor,
|
||||
}
|
||||
|
||||
response, err := backend.ExtractTimeline(backendReq)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to extract timeline: %v", err)
|
||||
}
|
||||
|
||||
jsonData, err := json.MarshalIndent(response, "", " ")
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to encode response: %v", err)
|
||||
}
|
||||
|
||||
return string(jsonData), nil
|
||||
}
|
||||
|
||||
// ExtractDateRange extracts media based on date range
|
||||
func (a *App) ExtractDateRange(req DateRangeRequest) (string, error) {
|
||||
if req.Username == "" {
|
||||
return "", fmt.Errorf("username is required")
|
||||
}
|
||||
if req.AuthToken == "" {
|
||||
return "", fmt.Errorf("auth token is required")
|
||||
}
|
||||
if req.StartDate == "" {
|
||||
return "", fmt.Errorf("start date is required")
|
||||
}
|
||||
if req.EndDate == "" {
|
||||
return "", fmt.Errorf("end date is required")
|
||||
}
|
||||
|
||||
backendReq := backend.DateRangeRequest{
|
||||
Username: req.Username,
|
||||
AuthToken: req.AuthToken,
|
||||
StartDate: req.StartDate,
|
||||
EndDate: req.EndDate,
|
||||
MediaFilter: req.MediaFilter,
|
||||
Retweets: req.Retweets,
|
||||
}
|
||||
|
||||
response, err := backend.ExtractDateRange(backendReq)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to extract date range: %v", err)
|
||||
}
|
||||
|
||||
jsonData, err := json.MarshalIndent(response, "", " ")
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to encode response: %v", err)
|
||||
}
|
||||
|
||||
return string(jsonData), nil
|
||||
}
|
||||
|
||||
// OpenFolder opens a folder in the file explorer
|
||||
func (a *App) OpenFolder(path string) error {
|
||||
if path == "" {
|
||||
return fmt.Errorf("path is required")
|
||||
}
|
||||
|
||||
// Clean the path to use correct separators for the OS
|
||||
cleanPath := filepath.Clean(path)
|
||||
|
||||
err := backend.OpenFolderInExplorer(cleanPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to open folder: %v", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// SelectFolder opens a folder selection dialog and returns the selected path
|
||||
func (a *App) SelectFolder(defaultPath string) (string, error) {
|
||||
return backend.SelectFolderDialog(a.ctx, defaultPath)
|
||||
}
|
||||
|
||||
// GetDefaults returns the default configuration
|
||||
func (a *App) GetDefaults() map[string]string {
|
||||
return map[string]string{
|
||||
"downloadPath": backend.GetDefaultDownloadPath(),
|
||||
}
|
||||
}
|
||||
|
||||
// Quit closes the application
|
||||
func (a *App) Quit() {
|
||||
panic("quit")
|
||||
}
|
||||
|
||||
// DownloadMediaRequest represents the request for downloading media (legacy)
|
||||
type DownloadMediaRequest struct {
|
||||
URLs []string `json:"urls"`
|
||||
OutputDir string `json:"output_dir"`
|
||||
Username string `json:"username"`
|
||||
Proxy string `json:"proxy,omitempty"` // Optional proxy URL (e.g., http://proxy:port or socks5://proxy:port)
|
||||
}
|
||||
|
||||
// MediaItemRequest represents a media item with metadata
|
||||
type MediaItemRequest struct {
|
||||
URL string `json:"url"`
|
||||
Date string `json:"date"`
|
||||
TweetID backend.TweetIDString `json:"tweet_id"`
|
||||
Type string `json:"type"`
|
||||
Content string `json:"content,omitempty"` // Tweet text content (for text-only tweets)
|
||||
OriginalFilename string `json:"original_filename,omitempty"` // Original filename from API
|
||||
AuthorUsername string `json:"author_username,omitempty"` // Username of tweet author (for bookmarks and likes)
|
||||
}
|
||||
|
||||
// DownloadMediaWithMetadataRequest represents the request for downloading media with metadata
|
||||
type DownloadMediaWithMetadataRequest struct {
|
||||
Items []MediaItemRequest `json:"items"`
|
||||
OutputDir string `json:"output_dir"`
|
||||
Username string `json:"username"`
|
||||
Proxy string `json:"proxy,omitempty"` // Optional proxy URL (e.g., http://proxy:port or socks5://proxy:port)
|
||||
}
|
||||
|
||||
// DownloadMediaResponse represents the response for download operation
|
||||
type DownloadMediaResponse struct {
|
||||
Success bool `json:"success"`
|
||||
Downloaded int `json:"downloaded"`
|
||||
Skipped int `json:"skipped"`
|
||||
Failed int `json:"failed"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
// DownloadMedia downloads media files from URLs (legacy)
|
||||
func (a *App) DownloadMedia(req DownloadMediaRequest) (DownloadMediaResponse, error) {
|
||||
if len(req.URLs) == 0 {
|
||||
return DownloadMediaResponse{
|
||||
Success: false,
|
||||
Message: "No URLs provided",
|
||||
}, fmt.Errorf("no URLs provided")
|
||||
}
|
||||
|
||||
outputDir := req.OutputDir
|
||||
if outputDir == "" {
|
||||
outputDir = backend.GetDefaultDownloadPath()
|
||||
}
|
||||
|
||||
// Create subfolder for username if provided
|
||||
if req.Username != "" {
|
||||
outputDir = filepath.Join(outputDir, req.Username)
|
||||
}
|
||||
|
||||
downloaded, failed, err := backend.DownloadMediaFiles(req.URLs, outputDir, req.Proxy)
|
||||
if err != nil {
|
||||
return DownloadMediaResponse{
|
||||
Success: false,
|
||||
Downloaded: downloaded,
|
||||
Skipped: 0,
|
||||
Failed: failed,
|
||||
Message: err.Error(),
|
||||
}, err
|
||||
}
|
||||
|
||||
return DownloadMediaResponse{
|
||||
Success: true,
|
||||
Downloaded: downloaded,
|
||||
Skipped: 0,
|
||||
Failed: failed,
|
||||
Message: fmt.Sprintf("Downloaded %d files, %d failed", downloaded, failed),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// DownloadProgress represents download progress event data
|
||||
type DownloadProgress struct {
|
||||
Current int `json:"current"`
|
||||
Total int `json:"total"`
|
||||
Percent int `json:"percent"`
|
||||
}
|
||||
|
||||
// DownloadItemStatus represents per-item download status event data
|
||||
type DownloadItemStatus struct {
|
||||
TweetID int64 `json:"tweet_id"`
|
||||
Index int `json:"index"`
|
||||
Status string `json:"status"` // "success", "failed", "skipped"
|
||||
}
|
||||
|
||||
// DownloadMediaWithMetadata downloads media files with proper naming and categorization
|
||||
func (a *App) DownloadMediaWithMetadata(req DownloadMediaWithMetadataRequest) (DownloadMediaResponse, error) {
|
||||
if len(req.Items) == 0 {
|
||||
return DownloadMediaResponse{
|
||||
Success: false,
|
||||
Message: "No items provided",
|
||||
}, fmt.Errorf("no items provided")
|
||||
}
|
||||
|
||||
outputDir := req.OutputDir
|
||||
if outputDir == "" {
|
||||
outputDir = backend.GetDefaultDownloadPath()
|
||||
}
|
||||
|
||||
// Convert request items to backend items
|
||||
// For bookmarks and likes, use author_username from each item if available
|
||||
items := make([]backend.MediaItem, len(req.Items))
|
||||
for i, item := range req.Items {
|
||||
// Use original filename from API if available, otherwise extract from URL
|
||||
originalFilename := item.OriginalFilename
|
||||
if originalFilename == "" {
|
||||
// Fallback: extract from URL if not provided in API response
|
||||
originalFilename = backend.ExtractOriginalFilename(item.URL)
|
||||
}
|
||||
|
||||
// For bookmarks and likes, use author_username from item, otherwise use req.Username
|
||||
username := req.Username
|
||||
if item.AuthorUsername != "" {
|
||||
username = item.AuthorUsername
|
||||
}
|
||||
|
||||
items[i] = backend.MediaItem{
|
||||
URL: item.URL,
|
||||
Date: item.Date,
|
||||
TweetID: int64(item.TweetID),
|
||||
Type: item.Type,
|
||||
Username: username,
|
||||
Content: item.Content,
|
||||
OriginalFilename: originalFilename,
|
||||
}
|
||||
}
|
||||
|
||||
// Create cancellable context
|
||||
a.downloadCtx, a.downloadCancel = context.WithCancel(context.Background())
|
||||
|
||||
// Progress callback
|
||||
progressCallback := func(current, total int) {
|
||||
percent := 0
|
||||
if total > 0 {
|
||||
percent = (current * 100) / total
|
||||
}
|
||||
runtime.EventsEmit(a.ctx, "download-progress", DownloadProgress{
|
||||
Current: current,
|
||||
Total: total,
|
||||
Percent: percent,
|
||||
})
|
||||
}
|
||||
|
||||
// Per-item status callback
|
||||
itemStatusCallback := func(tweetID int64, index int, status string) {
|
||||
runtime.EventsEmit(a.ctx, "download-item-status", DownloadItemStatus{
|
||||
TweetID: tweetID,
|
||||
Index: index,
|
||||
Status: status,
|
||||
})
|
||||
}
|
||||
|
||||
downloaded, skipped, failed, err := backend.DownloadMediaWithMetadataProgressAndStatus(items, outputDir, req.Username, progressCallback, itemStatusCallback, a.downloadCtx, req.Proxy)
|
||||
if err != nil {
|
||||
return DownloadMediaResponse{
|
||||
Success: false,
|
||||
Downloaded: downloaded,
|
||||
Skipped: skipped,
|
||||
Failed: failed,
|
||||
Message: err.Error(),
|
||||
}, err
|
||||
}
|
||||
|
||||
// Clear cancel function
|
||||
a.downloadCancel = nil
|
||||
|
||||
return DownloadMediaResponse{
|
||||
Success: true,
|
||||
Downloaded: downloaded,
|
||||
Skipped: skipped,
|
||||
Failed: failed,
|
||||
Message: fmt.Sprintf("Downloaded %d files, %d skipped, %d failed", downloaded, skipped, failed),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// StopDownload cancels the current download operation
|
||||
func (a *App) StopDownload() bool {
|
||||
if a.downloadCancel != nil {
|
||||
a.downloadCancel()
|
||||
a.downloadCancel = nil
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Database functions
|
||||
|
||||
// SaveAccountToDB saves account data to database
|
||||
func (a *App) SaveAccountToDB(username, name, profileImage string, totalMedia int, responseJSON string, mediaType string) error {
|
||||
return backend.SaveAccount(username, name, profileImage, totalMedia, responseJSON, mediaType)
|
||||
}
|
||||
|
||||
// SaveAccountToDBWithStatus saves account data with cursor and completion status for resume capability
|
||||
func (a *App) SaveAccountToDBWithStatus(username, name, profileImage string, totalMedia int, responseJSON string, mediaType string, cursor string, completed bool) error {
|
||||
return backend.SaveAccountWithStatus(username, name, profileImage, totalMedia, responseJSON, mediaType, cursor, completed)
|
||||
}
|
||||
|
||||
// GetAllAccountsFromDB returns all saved accounts
|
||||
func (a *App) GetAllAccountsFromDB() ([]backend.AccountListItem, error) {
|
||||
return backend.GetAllAccounts()
|
||||
}
|
||||
|
||||
// GetAccountFromDB returns account data by ID
|
||||
func (a *App) GetAccountFromDB(id int64) (string, error) {
|
||||
acc, err := backend.GetAccountByID(id)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return acc.ResponseJSON, nil
|
||||
}
|
||||
|
||||
// DeleteAccountFromDB deletes an account from database
|
||||
func (a *App) DeleteAccountFromDB(id int64) error {
|
||||
return backend.DeleteAccount(id)
|
||||
}
|
||||
|
||||
// ClearAllAccountsFromDB deletes all accounts from database
|
||||
func (a *App) ClearAllAccountsFromDB() error {
|
||||
return backend.ClearAllAccounts()
|
||||
}
|
||||
|
||||
// ExportAccountJSON exports account to JSON file in specified directory
|
||||
func (a *App) ExportAccountJSON(id int64, outputDir string) (string, error) {
|
||||
return backend.ExportAccountToFile(id, outputDir)
|
||||
}
|
||||
|
||||
// ExportAccountsTXT exports selected accounts to TXT file in specified directory
|
||||
func (a *App) ExportAccountsTXT(ids []int64, outputDir string) (string, error) {
|
||||
return backend.ExportAccountsToTXT(ids, outputDir)
|
||||
}
|
||||
|
||||
// UpdateAccountGroup updates the group for an account
|
||||
func (a *App) UpdateAccountGroup(id int64, groupName, groupColor string) error {
|
||||
return backend.UpdateAccountGroup(id, groupName, groupColor)
|
||||
}
|
||||
|
||||
// GetAllGroups returns all unique groups
|
||||
func (a *App) GetAllGroups() ([]map[string]string, error) {
|
||||
return backend.GetAllGroups()
|
||||
}
|
||||
|
||||
// FFmpeg functions
|
||||
|
||||
// IsFFmpegInstalled checks if ffmpeg is available
|
||||
func (a *App) IsFFmpegInstalled() bool {
|
||||
return backend.IsFFmpegInstalled()
|
||||
}
|
||||
|
||||
// DownloadFFmpeg downloads ffmpeg binary
|
||||
func (a *App) DownloadFFmpeg() error {
|
||||
return backend.DownloadFFmpeg(nil)
|
||||
}
|
||||
|
||||
// IsExifToolInstalled checks if exiftool is available
|
||||
func (a *App) IsExifToolInstalled() bool {
|
||||
return backend.IsExifToolInstalled()
|
||||
}
|
||||
|
||||
// DownloadExifTool downloads exiftool binary
|
||||
func (a *App) DownloadExifTool() error {
|
||||
return backend.DownloadExifTool(nil)
|
||||
}
|
||||
|
||||
// ConvertGIFsRequest represents request for converting GIFs
|
||||
type ConvertGIFsRequest struct {
|
||||
FolderPath string `json:"folder_path"`
|
||||
Quality string `json:"quality"` // "fast" or "better"
|
||||
Resolution string `json:"resolution"` // "original", "high", "medium", "low"
|
||||
DeleteOriginal bool `json:"delete_original"`
|
||||
}
|
||||
|
||||
// ConvertGIFsResponse represents response for GIF conversion
|
||||
type ConvertGIFsResponse struct {
|
||||
Success bool `json:"success"`
|
||||
Converted int `json:"converted"`
|
||||
Failed int `json:"failed"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
// ConvertGIFs converts MP4 files in gifs folder to actual GIF format
|
||||
func (a *App) ConvertGIFs(req ConvertGIFsRequest) (ConvertGIFsResponse, error) {
|
||||
if !backend.IsFFmpegInstalled() {
|
||||
return ConvertGIFsResponse{
|
||||
Success: false,
|
||||
Message: "FFmpeg not installed. Please download it first.",
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Default values if not provided
|
||||
quality := req.Quality
|
||||
if quality == "" {
|
||||
quality = "fast"
|
||||
}
|
||||
resolution := req.Resolution
|
||||
if resolution == "" {
|
||||
resolution = "high"
|
||||
}
|
||||
|
||||
converted, failed, err := backend.ConvertGIFsInFolder(req.FolderPath, quality, resolution, req.DeleteOriginal)
|
||||
if err != nil {
|
||||
return ConvertGIFsResponse{
|
||||
Success: false,
|
||||
Message: err.Error(),
|
||||
}, err
|
||||
}
|
||||
|
||||
return ConvertGIFsResponse{
|
||||
Success: true,
|
||||
Converted: converted,
|
||||
Failed: failed,
|
||||
Message: fmt.Sprintf("Converted %d GIFs, %d failed", converted, failed),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ImportAccountResponse represents the response for import operation
|
||||
type ImportAccountResponse struct {
|
||||
Success bool `json:"success"`
|
||||
Username string `json:"username"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
// CheckFolderExists checks if a folder exists for the given username
|
||||
func (a *App) CheckFolderExists(basePath, username string) bool {
|
||||
return backend.CheckFolderExists(basePath, username)
|
||||
}
|
||||
|
||||
// CheckGifsFolderExists checks if a gifs subfolder exists for the given username
|
||||
func (a *App) CheckGifsFolderExists(basePath, username string) bool {
|
||||
return backend.CheckGifsFolderExists(basePath, username)
|
||||
}
|
||||
|
||||
// CheckGifsFolderHasMP4 checks if the gifs folder has any MP4 files to convert
|
||||
func (a *App) CheckGifsFolderHasMP4(basePath, username string) bool {
|
||||
return backend.CheckGifsFolderHasMP4(basePath, username)
|
||||
}
|
||||
|
||||
// GetFolderPath returns the full path for a username folder
|
||||
func (a *App) GetFolderPath(basePath, username string) string {
|
||||
return backend.GetFolderPath(basePath, username)
|
||||
}
|
||||
|
||||
// GetGifsFolderPath returns the full path for a username's gifs folder
|
||||
func (a *App) GetGifsFolderPath(basePath, username string) string {
|
||||
return backend.GetGifsFolderPath(basePath, username)
|
||||
}
|
||||
|
||||
// ImportAccountFromJSON imports account from JSON file (supports both old and new format)
|
||||
func (a *App) ImportAccountFromJSON() (ImportAccountResponse, error) {
|
||||
// Open file dialog
|
||||
filePath, err := runtime.OpenFileDialog(a.ctx, runtime.OpenDialogOptions{
|
||||
Title: "Import Account JSON",
|
||||
Filters: []runtime.FileFilter{
|
||||
{DisplayName: "JSON Files", Pattern: "*.json"},
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
return ImportAccountResponse{Success: false, Message: err.Error()}, err
|
||||
}
|
||||
|
||||
// User cancelled
|
||||
if filePath == "" {
|
||||
return ImportAccountResponse{Success: false, Message: "Cancelled"}, nil
|
||||
}
|
||||
|
||||
// Import the file
|
||||
username, err := backend.ImportAccountFromFile(filePath)
|
||||
if err != nil {
|
||||
return ImportAccountResponse{Success: false, Message: err.Error()}, err
|
||||
}
|
||||
|
||||
return ImportAccountResponse{
|
||||
Success: true,
|
||||
Username: username,
|
||||
Message: fmt.Sprintf("Successfully imported @%s", username),
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
//go:build !windows
|
||||
|
||||
package backend
|
||||
|
||||
import "os/exec"
|
||||
|
||||
// hideWindow is a no-op on non-Windows platforms
|
||||
func hideWindow(cmd *exec.Cmd) {
|
||||
// No action needed on Unix-like systems
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
//go:build windows
|
||||
|
||||
package backend
|
||||
|
||||
import (
|
||||
"os/exec"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
// hideWindow sets the command to run without showing a console window on Windows
|
||||
func hideWindow(cmd *exec.Cmd) {
|
||||
cmd.SysProcAttr = &syscall.SysProcAttr{
|
||||
HideWindow: true,
|
||||
CreationFlags: 0x08000000, // CREATE_NO_WINDOW
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package backend
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
)
|
||||
|
||||
func GetDefaultDownloadPath() string {
|
||||
// Get user's home directory
|
||||
homeDir, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
// Fallback to Public Pictures if can't get home dir
|
||||
return "C:\\Users\\Public\\Pictures"
|
||||
}
|
||||
|
||||
// Return path to user's Pictures folder
|
||||
return filepath.Join(homeDir, "Pictures")
|
||||
}
|
||||
|
||||
// GetProxyURL gets proxy URL from environment variables or custom proxy setting
|
||||
// Priority: customProxy > HTTP_PROXY/HTTPS_PROXY > http_proxy/https_proxy
|
||||
func GetProxyURL(customProxy string) (*url.URL, error) {
|
||||
// First, check custom proxy setting
|
||||
if customProxy != "" {
|
||||
proxyURL, err := url.Parse(customProxy)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid custom proxy URL: %v", err)
|
||||
}
|
||||
return proxyURL, nil
|
||||
}
|
||||
|
||||
// Check environment variables (case-insensitive on Windows)
|
||||
proxyEnv := os.Getenv("HTTPS_PROXY")
|
||||
if proxyEnv == "" {
|
||||
proxyEnv = os.Getenv("https_proxy")
|
||||
}
|
||||
if proxyEnv == "" {
|
||||
proxyEnv = os.Getenv("HTTP_PROXY")
|
||||
}
|
||||
if proxyEnv == "" {
|
||||
proxyEnv = os.Getenv("http_proxy")
|
||||
}
|
||||
|
||||
if proxyEnv != "" {
|
||||
proxyURL, err := url.Parse(proxyEnv)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid proxy URL from environment: %v", err)
|
||||
}
|
||||
return proxyURL, nil
|
||||
}
|
||||
|
||||
return nil, nil // No proxy
|
||||
}
|
||||
|
||||
// CreateHTTPClient creates an HTTP client with proxy support
|
||||
func CreateHTTPClient(customProxy string, timeout time.Duration) (*http.Client, error) {
|
||||
proxyURL, err := GetProxyURL(customProxy)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
transport := &http.Transport{
|
||||
Proxy: http.ProxyURL(proxyURL),
|
||||
}
|
||||
|
||||
client := &http.Client{
|
||||
Transport: transport,
|
||||
Timeout: timeout,
|
||||
}
|
||||
|
||||
return client, nil
|
||||
}
|
||||
@@ -0,0 +1,508 @@
|
||||
package backend
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
_ "github.com/mattn/go-sqlite3"
|
||||
)
|
||||
|
||||
// AccountDB represents a saved account in the database
|
||||
type AccountDB struct {
|
||||
ID int64 `json:"id"`
|
||||
Username string `json:"username"`
|
||||
Name string `json:"name"`
|
||||
ProfileImage string `json:"profile_image"`
|
||||
TotalMedia int `json:"total_media"`
|
||||
LastFetched time.Time `json:"last_fetched"`
|
||||
ResponseJSON string `json:"response_json"`
|
||||
MediaType string `json:"media_type"`
|
||||
Cursor string `json:"cursor"`
|
||||
Completed bool `json:"completed"`
|
||||
}
|
||||
|
||||
// AccountListItem represents a simplified account for listing
|
||||
type AccountListItem struct {
|
||||
ID int64 `json:"id"`
|
||||
Username string `json:"username"`
|
||||
Name string `json:"name"`
|
||||
ProfileImage string `json:"profile_image"`
|
||||
TotalMedia int `json:"total_media"`
|
||||
LastFetched string `json:"last_fetched"`
|
||||
GroupName string `json:"group_name"`
|
||||
GroupColor string `json:"group_color"`
|
||||
MediaType string `json:"media_type"`
|
||||
Cursor string `json:"cursor"`
|
||||
Completed bool `json:"completed"`
|
||||
}
|
||||
|
||||
var db *sql.DB
|
||||
|
||||
// GetDBPath returns the database file path
|
||||
func GetDBPath() string {
|
||||
homeDir, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
homeDir = "."
|
||||
}
|
||||
return filepath.Join(homeDir, ".twitterxmediabatchdownloader", "accounts.db")
|
||||
}
|
||||
|
||||
// InitDB initializes the database connection
|
||||
func InitDB() error {
|
||||
dbPath := GetDBPath()
|
||||
|
||||
// Create directory if not exists
|
||||
dir := filepath.Dir(dbPath)
|
||||
if err := os.MkdirAll(dir, 0755); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var err error
|
||||
db, err = sql.Open("sqlite3", dbPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Create tables
|
||||
_, err = db.Exec(`
|
||||
CREATE TABLE IF NOT EXISTS accounts (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
username TEXT NOT NULL,
|
||||
name TEXT,
|
||||
profile_image TEXT,
|
||||
total_media INTEGER DEFAULT 0,
|
||||
last_fetched DATETIME,
|
||||
response_json TEXT,
|
||||
group_name TEXT DEFAULT '',
|
||||
group_color TEXT DEFAULT '',
|
||||
media_type TEXT DEFAULT 'all',
|
||||
cursor TEXT DEFAULT '',
|
||||
completed INTEGER DEFAULT 1,
|
||||
UNIQUE(username, media_type)
|
||||
)
|
||||
`)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Add group columns if they don't exist (migration for existing databases)
|
||||
db.Exec("ALTER TABLE accounts ADD COLUMN group_name TEXT DEFAULT ''")
|
||||
db.Exec("ALTER TABLE accounts ADD COLUMN group_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")
|
||||
|
||||
// Migration: Update unique constraint for existing databases
|
||||
// This allows same username with different media types
|
||||
db.Exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_username_media_type ON accounts(username, media_type)")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// CloseDB closes the database connection
|
||||
func CloseDB() {
|
||||
if db != nil {
|
||||
db.Close()
|
||||
}
|
||||
}
|
||||
|
||||
// SaveAccount saves or updates an account in the database
|
||||
func SaveAccount(username, name, profileImage string, totalMedia int, responseJSON string, mediaType string) error {
|
||||
return SaveAccountWithStatus(username, name, profileImage, totalMedia, responseJSON, mediaType, "", true)
|
||||
}
|
||||
|
||||
// SaveAccountWithStatus saves or updates an account with cursor and completion status
|
||||
func SaveAccountWithStatus(username, name, profileImage string, totalMedia int, responseJSON string, mediaType string, cursor string, completed bool) error {
|
||||
if db == nil {
|
||||
if err := InitDB(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// Default to "all" if not specified
|
||||
if mediaType == "" {
|
||||
mediaType = "all"
|
||||
}
|
||||
|
||||
completedInt := 0
|
||||
if completed {
|
||||
completedInt = 1
|
||||
}
|
||||
|
||||
_, err := db.Exec(`
|
||||
INSERT INTO accounts (username, name, profile_image, total_media, last_fetched, response_json, media_type, cursor, completed)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(username, media_type) DO UPDATE SET
|
||||
name = excluded.name,
|
||||
profile_image = excluded.profile_image,
|
||||
total_media = excluded.total_media,
|
||||
last_fetched = excluded.last_fetched,
|
||||
response_json = excluded.response_json,
|
||||
cursor = excluded.cursor,
|
||||
completed = excluded.completed
|
||||
`, username, name, profileImage, totalMedia, time.Now(), responseJSON, mediaType, cursor, completedInt)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// GetAllAccounts returns all saved accounts
|
||||
func GetAllAccounts() ([]AccountListItem, error) {
|
||||
if db == nil {
|
||||
if err := InitDB(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
rows, err := db.Query(`
|
||||
SELECT id, username, name, profile_image, total_media, last_fetched,
|
||||
COALESCE(group_name, '') as group_name, COALESCE(group_color, '') as group_color,
|
||||
COALESCE(media_type, 'all') as media_type,
|
||||
COALESCE(cursor, '') as cursor, COALESCE(completed, 1) as completed
|
||||
FROM accounts
|
||||
ORDER BY group_name ASC, last_fetched DESC
|
||||
`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var accounts []AccountListItem
|
||||
for rows.Next() {
|
||||
var acc AccountListItem
|
||||
var lastFetched time.Time
|
||||
var completedInt int
|
||||
if err := rows.Scan(&acc.ID, &acc.Username, &acc.Name, &acc.ProfileImage, &acc.TotalMedia, &lastFetched, &acc.GroupName, &acc.GroupColor, &acc.MediaType, &acc.Cursor, &completedInt); err != nil {
|
||||
continue
|
||||
}
|
||||
acc.LastFetched = lastFetched.Format("2006-01-02 15:04")
|
||||
acc.Completed = completedInt == 1
|
||||
accounts = append(accounts, acc)
|
||||
}
|
||||
|
||||
return accounts, nil
|
||||
}
|
||||
|
||||
// UpdateAccountGroup updates the group for an account
|
||||
func UpdateAccountGroup(id int64, groupName, groupColor string) error {
|
||||
if db == nil {
|
||||
if err := InitDB(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
_, err := db.Exec("UPDATE accounts SET group_name = ?, group_color = ? WHERE id = ?", groupName, groupColor, id)
|
||||
return err
|
||||
}
|
||||
|
||||
// GetAllGroups returns all unique groups
|
||||
func GetAllGroups() ([]map[string]string, error) {
|
||||
if db == nil {
|
||||
if err := InitDB(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
rows, err := db.Query(`
|
||||
SELECT DISTINCT group_name, group_color
|
||||
FROM accounts
|
||||
WHERE group_name != ''
|
||||
ORDER BY group_name
|
||||
`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var groups []map[string]string
|
||||
for rows.Next() {
|
||||
var name, color string
|
||||
if err := rows.Scan(&name, &color); err != nil {
|
||||
continue
|
||||
}
|
||||
groups = append(groups, map[string]string{"name": name, "color": color})
|
||||
}
|
||||
|
||||
return groups, nil
|
||||
}
|
||||
|
||||
// ClearAllAccounts deletes all accounts from the database
|
||||
func ClearAllAccounts() error {
|
||||
if db == nil {
|
||||
if err := InitDB(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
_, err := db.Exec("DELETE FROM accounts")
|
||||
return err
|
||||
}
|
||||
|
||||
|
||||
// GetAccountByID returns a specific account by ID
|
||||
func GetAccountByID(id int64) (*AccountDB, error) {
|
||||
if db == nil {
|
||||
if err := InitDB(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
var acc AccountDB
|
||||
var lastFetched time.Time
|
||||
var completedInt int
|
||||
err := db.QueryRow(`
|
||||
SELECT id, username, name, profile_image, total_media, last_fetched, response_json,
|
||||
COALESCE(cursor, '') as cursor, COALESCE(completed, 1) as completed
|
||||
FROM accounts WHERE id = ?
|
||||
`, id).Scan(&acc.ID, &acc.Username, &acc.Name, &acc.ProfileImage, &acc.TotalMedia, &lastFetched, &acc.ResponseJSON, &acc.Cursor, &completedInt)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
acc.LastFetched = lastFetched
|
||||
acc.Completed = completedInt == 1
|
||||
|
||||
// Convert legacy format if needed
|
||||
if converted, err := ConvertLegacyToNewFormat(acc.ResponseJSON); err == nil {
|
||||
acc.ResponseJSON = converted
|
||||
}
|
||||
|
||||
return &acc, nil
|
||||
}
|
||||
|
||||
// DeleteAccount deletes an account from the database
|
||||
func DeleteAccount(id int64) error {
|
||||
if db == nil {
|
||||
if err := InitDB(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
_, err := db.Exec("DELETE FROM accounts WHERE id = ?", id)
|
||||
return err
|
||||
}
|
||||
// LegacyMediaEntry represents media entry in old format
|
||||
type LegacyMediaEntry struct {
|
||||
TweetID string `json:"tweet_id"`
|
||||
URL string `json:"url"`
|
||||
Date string `json:"date"`
|
||||
Type string `json:"type"`
|
||||
}
|
||||
|
||||
// LegacyAccountFormat represents the old saved account format
|
||||
type LegacyAccountFormat struct {
|
||||
Username string `json:"username"`
|
||||
Nick string `json:"nick"`
|
||||
Followers int `json:"followers"`
|
||||
Following int `json:"following"`
|
||||
Posts int `json:"posts"`
|
||||
MediaType string `json:"media_type"`
|
||||
ProfileImage string `json:"profile_image"`
|
||||
FetchMode string `json:"fetch_mode"`
|
||||
FetchTimestamp string `json:"fetch_timestamp"`
|
||||
GroupID interface{} `json:"group_id"`
|
||||
MediaList []LegacyMediaEntry `json:"media_list"`
|
||||
}
|
||||
|
||||
// ConvertLegacyToNewFormat converts old format to new TwitterResponse format
|
||||
func ConvertLegacyToNewFormat(jsonStr string) (string, error) {
|
||||
// First check if it's already in new format (has account_info key)
|
||||
var check map[string]interface{}
|
||||
if err := json.Unmarshal([]byte(jsonStr), &check); err != nil {
|
||||
return jsonStr, err
|
||||
}
|
||||
|
||||
// If already has account_info, it's new format - return as is
|
||||
if _, hasAccountInfo := check["account_info"]; hasAccountInfo {
|
||||
return jsonStr, nil
|
||||
}
|
||||
|
||||
// Check if it's legacy format (has username and media_list)
|
||||
if _, hasUsername := check["username"]; !hasUsername {
|
||||
return jsonStr, nil
|
||||
}
|
||||
if _, hasMediaList := check["media_list"]; !hasMediaList {
|
||||
return jsonStr, nil
|
||||
}
|
||||
|
||||
// Parse as legacy format
|
||||
var legacy LegacyAccountFormat
|
||||
if err := json.Unmarshal([]byte(jsonStr), &legacy); err != nil {
|
||||
return jsonStr, err
|
||||
}
|
||||
|
||||
// Convert timeline entries
|
||||
timeline := make([]map[string]interface{}, len(legacy.MediaList))
|
||||
for i, media := range legacy.MediaList {
|
||||
timeline[i] = map[string]interface{}{
|
||||
"url": media.URL,
|
||||
"date": media.Date,
|
||||
"tweet_id": media.TweetID,
|
||||
"type": media.Type,
|
||||
"is_retweet": false,
|
||||
}
|
||||
}
|
||||
|
||||
// Build new format
|
||||
newFormat := map[string]interface{}{
|
||||
"account_info": map[string]interface{}{
|
||||
"name": legacy.Username,
|
||||
"nick": legacy.Nick,
|
||||
"date": "",
|
||||
"followers_count": legacy.Followers,
|
||||
"friends_count": legacy.Following,
|
||||
"profile_image": legacy.ProfileImage,
|
||||
"statuses_count": legacy.Posts,
|
||||
},
|
||||
"total_urls": len(legacy.MediaList),
|
||||
"timeline": timeline,
|
||||
"metadata": map[string]interface{}{
|
||||
"new_entries": len(legacy.MediaList),
|
||||
"page": 0,
|
||||
"batch_size": 0,
|
||||
"has_more": false,
|
||||
},
|
||||
}
|
||||
|
||||
// Convert back to JSON
|
||||
newJSON, err := json.Marshal(newFormat)
|
||||
if err != nil {
|
||||
return jsonStr, err
|
||||
}
|
||||
|
||||
return string(newJSON), nil
|
||||
}
|
||||
|
||||
// ExportAccountToFile exports account JSON to a file
|
||||
func ExportAccountToFile(id int64, outputDir string) (string, error) {
|
||||
acc, err := GetAccountByID(id)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// Create export directory if not exists
|
||||
exportDir := filepath.Join(outputDir, "twitterxmediabatchdownloader_backups")
|
||||
if err := os.MkdirAll(exportDir, 0755); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// Use username (nick) for filename
|
||||
filename := acc.Username
|
||||
if filename == "" {
|
||||
filename = acc.Name
|
||||
}
|
||||
|
||||
filePath := filepath.Join(exportDir, filename+".json")
|
||||
|
||||
if err := os.WriteFile(filePath, []byte(acc.ResponseJSON), 0644); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return filePath, nil
|
||||
}
|
||||
|
||||
// ExportAccountsToTXT exports selected accounts to TXT file (one username per line)
|
||||
func ExportAccountsToTXT(ids []int64, outputDir string) (string, error) {
|
||||
if len(ids) == 0 {
|
||||
return "", fmt.Errorf("no accounts to export")
|
||||
}
|
||||
|
||||
// Create export directory if not exists
|
||||
exportDir := filepath.Join(outputDir, "twitterxmediabatchdownloader_backups")
|
||||
if err := os.MkdirAll(exportDir, 0755); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// Get all accounts by IDs
|
||||
var usernames []string
|
||||
for _, id := range ids {
|
||||
acc, err := GetAccountByID(id)
|
||||
if err != nil {
|
||||
continue // Skip if account not found
|
||||
}
|
||||
if acc.Username != "" {
|
||||
usernames = append(usernames, acc.Username)
|
||||
}
|
||||
}
|
||||
|
||||
if len(usernames) == 0 {
|
||||
return "", fmt.Errorf("no valid usernames found")
|
||||
}
|
||||
|
||||
// Create TXT content (one username per line)
|
||||
txtContent := ""
|
||||
for i, username := range usernames {
|
||||
if i > 0 {
|
||||
txtContent += "\n"
|
||||
}
|
||||
txtContent += username
|
||||
}
|
||||
|
||||
// Filename: twitterxmediabatchdownloader_multiple.txt
|
||||
filePath := filepath.Join(exportDir, "twitterxmediabatchdownloader_multiple.txt")
|
||||
|
||||
if err := os.WriteFile(filePath, []byte(txtContent), 0644); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return filePath, nil
|
||||
}
|
||||
|
||||
// ImportAccountFromFile imports account from JSON file (supports both old and new format)
|
||||
func ImportAccountFromFile(filePath string) (string, error) {
|
||||
if db == nil {
|
||||
if err := InitDB(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
|
||||
// Read file
|
||||
data, err := os.ReadFile(filePath)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
jsonStr := string(data)
|
||||
|
||||
// Convert legacy format if needed
|
||||
convertedJSON, err := ConvertLegacyToNewFormat(jsonStr)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// Parse the converted JSON to extract account info
|
||||
var parsed map[string]interface{}
|
||||
if err := json.Unmarshal([]byte(convertedJSON), &parsed); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// Extract account info
|
||||
accountInfo, ok := parsed["account_info"].(map[string]interface{})
|
||||
if !ok {
|
||||
return "", fmt.Errorf("invalid JSON format: missing account_info")
|
||||
}
|
||||
|
||||
username, _ := accountInfo["name"].(string)
|
||||
name, _ := accountInfo["nick"].(string)
|
||||
profileImage, _ := accountInfo["profile_image"].(string)
|
||||
|
||||
totalURLs := 0
|
||||
if total, ok := parsed["total_urls"].(float64); ok {
|
||||
totalURLs = int(total)
|
||||
}
|
||||
|
||||
if username == "" {
|
||||
return "", fmt.Errorf("invalid JSON format: missing username")
|
||||
}
|
||||
|
||||
// Save to database with default media type "all" for imported files
|
||||
err = SaveAccount(username, name, profileImage, totalURLs, convertedJSON, "all")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return username, nil
|
||||
}
|
||||
@@ -0,0 +1,419 @@
|
||||
package backend
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
// MaxConcurrentDownloads is the number of parallel downloads
|
||||
MaxConcurrentDownloads = 10
|
||||
)
|
||||
|
||||
// MediaItem represents a media item with metadata for download
|
||||
type MediaItem struct {
|
||||
URL string `json:"url"`
|
||||
Date string `json:"date"`
|
||||
TweetID int64 `json:"tweet_id"`
|
||||
Type string `json:"type"`
|
||||
Username string `json:"username"`
|
||||
Content string `json:"content,omitempty"` // Tweet text content (for text-only tweets)
|
||||
OriginalFilename string `json:"original_filename,omitempty"` // Original Twitter media filename (15 char alphanumeric)
|
||||
}
|
||||
|
||||
// DownloadMediaFiles downloads media files from URLs to the output directory (legacy)
|
||||
func DownloadMediaFiles(urls []string, outputDir string, customProxy string) (downloaded int, failed int, err error) {
|
||||
// Create output directory if it doesn't exist
|
||||
if err := os.MkdirAll(outputDir, 0755); err != nil {
|
||||
return 0, len(urls), fmt.Errorf("failed to create output directory: %v", err)
|
||||
}
|
||||
|
||||
// Create HTTP client with proxy support
|
||||
client, err := CreateHTTPClient(customProxy, 60*time.Second)
|
||||
if err != nil {
|
||||
// If proxy setup fails, use default client without proxy
|
||||
client = &http.Client{
|
||||
Timeout: 60 * time.Second,
|
||||
}
|
||||
}
|
||||
|
||||
for _, mediaURL := range urls {
|
||||
filename := extractFilename(mediaURL)
|
||||
outputPath := filepath.Join(outputDir, filename)
|
||||
|
||||
// Skip if file already exists
|
||||
if _, err := os.Stat(outputPath); err == nil {
|
||||
downloaded++
|
||||
continue
|
||||
}
|
||||
|
||||
if err := downloadFile(client, mediaURL, outputPath); err != nil {
|
||||
failed++
|
||||
continue
|
||||
}
|
||||
downloaded++
|
||||
}
|
||||
|
||||
return downloaded, failed, nil
|
||||
}
|
||||
|
||||
// ProgressCallback is a function type for progress updates
|
||||
type ProgressCallback func(current, total int)
|
||||
|
||||
// ItemStatusCallback is a function type for per-item status updates
|
||||
type ItemStatusCallback func(tweetID int64, index int, status string) // status: "success", "failed", "skipped"
|
||||
|
||||
// downloadTask represents a single download task
|
||||
type downloadTask struct {
|
||||
item MediaItem
|
||||
outputPath string
|
||||
index int
|
||||
}
|
||||
|
||||
// DownloadMediaWithMetadataProgressAndStatus downloads media files with progress and per-item status callbacks
|
||||
// Returns: downloaded count, skipped count, failed count, error
|
||||
func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir string, username string, progress ProgressCallback, itemStatus ItemStatusCallback, ctx context.Context, customProxy string) (downloaded int, skipped int, failed int, err error) {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
|
||||
total := len(items)
|
||||
if total == 0 {
|
||||
return 0, 0, 0, nil
|
||||
}
|
||||
|
||||
// Prepare all tasks first (sequential to handle tweet media count)
|
||||
// For bookmarks and likes, each item may have different username, so we track per username
|
||||
tweetMediaCount := make(map[string]map[int64]int) // username -> tweet_id -> count
|
||||
tasks := make([]downloadTask, 0, total)
|
||||
|
||||
for i, item := range items {
|
||||
// Use item.Username if available (for bookmarks/likes with different authors), otherwise use provided username
|
||||
itemUsername := item.Username
|
||||
if itemUsername == "" {
|
||||
itemUsername = username
|
||||
}
|
||||
|
||||
// Initialize tweet media count for this username if needed
|
||||
if tweetMediaCount[itemUsername] == nil {
|
||||
tweetMediaCount[itemUsername] = make(map[int64]int)
|
||||
}
|
||||
|
||||
// Determine subfolder based on type
|
||||
var subfolder string
|
||||
switch item.Type {
|
||||
case "photo":
|
||||
subfolder = "images"
|
||||
case "video":
|
||||
subfolder = "videos"
|
||||
case "gif", "animated_gif":
|
||||
subfolder = "gifs"
|
||||
case "text":
|
||||
subfolder = "texts"
|
||||
default:
|
||||
subfolder = "other"
|
||||
}
|
||||
|
||||
// Create base directory for this username
|
||||
baseDir := filepath.Join(outputDir, itemUsername)
|
||||
if err := os.MkdirAll(baseDir, 0755); err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
// Create type subfolder
|
||||
typeDir := filepath.Join(baseDir, subfolder)
|
||||
if err := os.MkdirAll(typeDir, 0755); err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
// Format timestamp from date
|
||||
timestamp := formatTimestamp(item.Date)
|
||||
|
||||
// Get file extension
|
||||
ext := getExtension(item.URL, item.Type)
|
||||
|
||||
// Increment counter for this username and tweet_id
|
||||
tweetMediaCount[itemUsername][item.TweetID]++
|
||||
mediaIndex := tweetMediaCount[itemUsername][item.TweetID]
|
||||
|
||||
// Create filename: {username}_{timestamp}_{tweet_id}_{index}.{ext}
|
||||
filename := fmt.Sprintf("%s_%s_%d_%02d%s", itemUsername, timestamp, item.TweetID, mediaIndex, ext)
|
||||
outputPath := filepath.Join(typeDir, filename)
|
||||
|
||||
tasks = append(tasks, downloadTask{
|
||||
item: item,
|
||||
outputPath: outputPath,
|
||||
index: i,
|
||||
})
|
||||
}
|
||||
|
||||
// Counters for parallel downloads
|
||||
var downloadedCount int64
|
||||
var skippedCount int64
|
||||
var failedCount int64
|
||||
var completedCount int64
|
||||
|
||||
// Create worker pool
|
||||
taskChan := make(chan downloadTask, len(tasks))
|
||||
var wg sync.WaitGroup
|
||||
|
||||
// Start workers
|
||||
numWorkers := MaxConcurrentDownloads
|
||||
if numWorkers > len(tasks) {
|
||||
numWorkers = len(tasks)
|
||||
}
|
||||
|
||||
// Create HTTP client once for all workers (shared client is more efficient)
|
||||
var sharedClient *http.Client
|
||||
client, err := CreateHTTPClient(customProxy, 60*time.Second)
|
||||
if err != nil {
|
||||
// If proxy setup fails, use default client without proxy
|
||||
sharedClient = &http.Client{
|
||||
Timeout: 60 * time.Second,
|
||||
}
|
||||
} else {
|
||||
sharedClient = client
|
||||
}
|
||||
|
||||
for i := 0; i < numWorkers; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
client := sharedClient
|
||||
|
||||
for task := range taskChan {
|
||||
// Check for cancellation
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
default:
|
||||
}
|
||||
|
||||
var status string
|
||||
// Skip if file already exists
|
||||
if _, err := os.Stat(task.outputPath); err == nil {
|
||||
status = "skipped"
|
||||
// Emit status immediately for skipped files
|
||||
if itemStatus != nil {
|
||||
itemStatus(task.item.TweetID, task.index, status)
|
||||
}
|
||||
atomic.AddInt64(&skippedCount, 1)
|
||||
continue // Skip to next task
|
||||
} else if task.item.Type == "text" {
|
||||
// For text tweets, write content to file
|
||||
if err := os.WriteFile(task.outputPath, []byte(task.item.Content), 0644); err != nil {
|
||||
atomic.AddInt64(&failedCount, 1)
|
||||
status = "failed"
|
||||
} else {
|
||||
atomic.AddInt64(&downloadedCount, 1)
|
||||
status = "success"
|
||||
}
|
||||
} else if err := downloadFileWithContext(ctx, client, task.item.URL, task.outputPath); err != nil {
|
||||
atomic.AddInt64(&failedCount, 1)
|
||||
status = "failed"
|
||||
} else {
|
||||
// Embed metadata after successful download
|
||||
tweetURL := fmt.Sprintf("https://x.com/i/status/%d", task.item.TweetID)
|
||||
// Always extract original filename from URL (simpler approach)
|
||||
originalFilename := ExtractOriginalFilename(task.item.URL)
|
||||
|
||||
// For debugging: if original filename is still empty for video, it means it's not in the URL
|
||||
// This is acceptable - video URLs from Twitter may not contain original filename
|
||||
|
||||
// Embed metadata (non-fatal: if it fails, file is still downloaded)
|
||||
if err := EmbedMetadata(task.outputPath, task.item.Content, tweetURL, originalFilename); err != nil {
|
||||
// Log error but don't fail the download
|
||||
// Metadata embedding is optional
|
||||
}
|
||||
|
||||
atomic.AddInt64(&downloadedCount, 1)
|
||||
status = "success"
|
||||
}
|
||||
|
||||
// Emit per-item status
|
||||
if itemStatus != nil {
|
||||
itemStatus(task.item.TweetID, task.index, status)
|
||||
}
|
||||
|
||||
// Update progress
|
||||
completed := atomic.AddInt64(&completedCount, 1)
|
||||
if progress != nil {
|
||||
progress(int(completed), total)
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// Send tasks to workers
|
||||
for _, task := range tasks {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
close(taskChan)
|
||||
wg.Wait()
|
||||
return int(downloadedCount), int(skippedCount), int(failedCount) + (total - int(completedCount)), ctx.Err()
|
||||
case taskChan <- task:
|
||||
}
|
||||
}
|
||||
close(taskChan)
|
||||
|
||||
// Wait for all workers to finish
|
||||
wg.Wait()
|
||||
|
||||
return int(downloadedCount), int(skippedCount), int(failedCount), nil
|
||||
}
|
||||
|
||||
// downloadFileWithContext downloads a single file with context support for cancellation
|
||||
func downloadFileWithContext(ctx context.Context, client *http.Client, url, outputPath string) error {
|
||||
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("bad status: %s", resp.Status)
|
||||
}
|
||||
|
||||
out, err := os.Create(outputPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer out.Close()
|
||||
|
||||
_, err = io.Copy(out, resp.Body)
|
||||
return err
|
||||
}
|
||||
|
||||
// formatTimestamp converts date string to timestamp format
|
||||
func formatTimestamp(dateStr string) string {
|
||||
// Try parsing various date formats
|
||||
formats := []string{
|
||||
"2006-01-02T15:04:05", // ISO 8601 without timezone (from extractor)
|
||||
"2006-01-02T15:04:05+00:00", // ISO 8601 with timezone
|
||||
"2006-01-02T15:04:05-07:00", // ISO 8601 with timezone offset
|
||||
time.RFC3339, // Standard RFC3339
|
||||
"2006-01-02T15:04:05.000Z",
|
||||
"2006-01-02T15:04:05Z",
|
||||
"2006-01-02 15:04:05",
|
||||
"Mon Jan 02 15:04:05 -0700 2006",
|
||||
}
|
||||
|
||||
for _, format := range formats {
|
||||
if t, err := time.Parse(format, dateStr); err == nil {
|
||||
return t.Format("20060102_150405")
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: use empty string to indicate parsing failed
|
||||
return "00000000_000000"
|
||||
}
|
||||
|
||||
// getExtension determines file extension from URL and type
|
||||
func getExtension(mediaURL string, mediaType string) string {
|
||||
parsedURL, err := url.Parse(mediaURL)
|
||||
if err != nil {
|
||||
return ".jpg"
|
||||
}
|
||||
|
||||
// Check format query param for Twitter images
|
||||
if format := parsedURL.Query().Get("format"); format != "" {
|
||||
return "." + format
|
||||
}
|
||||
|
||||
// Get extension from path
|
||||
path := parsedURL.Path
|
||||
ext := filepath.Ext(path)
|
||||
if ext != "" {
|
||||
return ext
|
||||
}
|
||||
|
||||
// Default based on type
|
||||
switch mediaType {
|
||||
case "video":
|
||||
return ".mp4"
|
||||
case "gif", "animated_gif":
|
||||
return ".mp4" // Twitter GIFs are actually MP4
|
||||
case "text":
|
||||
return ".txt"
|
||||
default:
|
||||
return ".jpg"
|
||||
}
|
||||
}
|
||||
|
||||
// extractFilename extracts filename from URL (legacy)
|
||||
func extractFilename(mediaURL string) string {
|
||||
parsedURL, err := url.Parse(mediaURL)
|
||||
if err != nil {
|
||||
return fmt.Sprintf("media_%d", time.Now().UnixNano())
|
||||
}
|
||||
|
||||
// Get the path part
|
||||
path := parsedURL.Path
|
||||
|
||||
// Extract base filename
|
||||
base := filepath.Base(path)
|
||||
|
||||
// Handle Twitter image URLs: /media/XXX -> XXX.jpg
|
||||
if strings.Contains(mediaURL, "pbs.twimg.com/media/") {
|
||||
// Get format from query params
|
||||
format := parsedURL.Query().Get("format")
|
||||
if format == "" {
|
||||
format = "jpg"
|
||||
}
|
||||
|
||||
// Remove any existing extension
|
||||
if idx := strings.LastIndex(base, "."); idx > 0 {
|
||||
base = base[:idx]
|
||||
}
|
||||
|
||||
return base + "." + format
|
||||
}
|
||||
|
||||
// Handle Twitter video URLs
|
||||
if strings.Contains(mediaURL, "video.twimg.com") {
|
||||
return base
|
||||
}
|
||||
|
||||
// Default: use base name or generate one
|
||||
if base == "" || base == "." {
|
||||
return fmt.Sprintf("media_%d", time.Now().UnixNano())
|
||||
}
|
||||
|
||||
return base
|
||||
}
|
||||
|
||||
// downloadFile downloads a single file from URL
|
||||
func downloadFile(client *http.Client, url, outputPath string) error {
|
||||
resp, err := client.Get(url)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("bad status: %s", resp.Status)
|
||||
}
|
||||
|
||||
out, err := os.Create(outputPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer out.Close()
|
||||
|
||||
_, err = io.Copy(out, resp.Body)
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
//go:build linux || darwin
|
||||
|
||||
package backend
|
||||
|
||||
import _ "embed"
|
||||
|
||||
//go:embed bin/extractor
|
||||
var extractorBin []byte
|
||||
@@ -0,0 +1,8 @@
|
||||
//go:build windows
|
||||
|
||||
package backend
|
||||
|
||||
import _ "embed"
|
||||
|
||||
//go:embed bin/extractor.exe
|
||||
var extractorBin []byte
|
||||
@@ -0,0 +1,348 @@
|
||||
package backend
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// ExifTool download URLs (SourceForge)
|
||||
const (
|
||||
// Windows 64-bit
|
||||
exiftoolWindows64URL = "https://sourceforge.net/projects/exiftool/files/exiftool-13.43_64.zip/download"
|
||||
// Windows 32-bit
|
||||
exiftoolWindows32URL = "https://sourceforge.net/projects/exiftool/files/exiftool-13.43_32.zip/download"
|
||||
// Unix (Linux/macOS): tar.gz
|
||||
exiftoolUnixURL = "https://sourceforge.net/projects/exiftool/files/Image-ExifTool-13.43.tar.gz/download"
|
||||
)
|
||||
|
||||
// ExifTool SHA256 hashes for verification
|
||||
// Note: Hashes will be calculated during download if not provided
|
||||
// For now, we'll skip hash verification for version 13.43 (can be added later if needed)
|
||||
const (
|
||||
exiftoolWindows64Hash = "" // Hash not provided, will skip verification
|
||||
exiftoolWindows32Hash = "" // Hash not provided, will skip verification
|
||||
exiftoolUnixHash = "" // Hash not provided, will skip verification
|
||||
)
|
||||
|
||||
// GetExifToolPath returns the path to exiftool binary
|
||||
func GetExifToolPath() string {
|
||||
homeDir, _ := os.UserHomeDir()
|
||||
baseDir := filepath.Join(homeDir, ".twitterxmediabatchdownloader")
|
||||
|
||||
switch runtime.GOOS {
|
||||
case "windows":
|
||||
return filepath.Join(baseDir, "exiftool.exe")
|
||||
default:
|
||||
// For Unix (Linux/macOS), exiftool is in Image-ExifTool-VERSION/exiftool
|
||||
// We need to find the folder dynamically since version may vary
|
||||
pattern := filepath.Join(baseDir, "Image-ExifTool-*")
|
||||
matches, err := filepath.Glob(pattern)
|
||||
if err == nil && len(matches) > 0 {
|
||||
// Use the first match (should only be one)
|
||||
exiftoolPath := filepath.Join(matches[0], "exiftool")
|
||||
if _, err := os.Stat(exiftoolPath); err == nil {
|
||||
return exiftoolPath
|
||||
}
|
||||
}
|
||||
// Fallback: return path that will be created after extraction
|
||||
return filepath.Join(baseDir, "exiftool")
|
||||
}
|
||||
}
|
||||
|
||||
// IsExifToolInstalled checks if exiftool is available
|
||||
func IsExifToolInstalled() bool {
|
||||
exiftoolPath := GetExifToolPath()
|
||||
if _, err := os.Stat(exiftoolPath); err == nil {
|
||||
// Test if it's executable by running version command
|
||||
cmd := exec.Command(exiftoolPath, "-ver")
|
||||
hideWindow(cmd)
|
||||
if err := cmd.Run(); err == nil {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// calculateSHA256 calculates SHA256 hash of a file
|
||||
func calculateSHA256(filePath string) (string, error) {
|
||||
file, err := os.Open(filePath)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
hash := sha256.New()
|
||||
if _, err := io.Copy(hash, file); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return hex.EncodeToString(hash.Sum(nil)), nil
|
||||
}
|
||||
|
||||
// verifyHash verifies the SHA256 hash of a downloaded file
|
||||
func verifyHash(filePath, expectedHash string) error {
|
||||
actualHash, err := calculateSHA256(filePath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to calculate hash: %v", err)
|
||||
}
|
||||
|
||||
if !strings.EqualFold(actualHash, expectedHash) {
|
||||
return fmt.Errorf("hash verification failed: expected %s, got %s", expectedHash, actualHash)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// is64Bit checks if the system is 64-bit
|
||||
func is64Bit() bool {
|
||||
return runtime.GOARCH == "amd64" || runtime.GOARCH == "arm64"
|
||||
}
|
||||
|
||||
// DownloadExifTool downloads exiftool binary for current platform
|
||||
func DownloadExifTool(progressCallback func(downloaded, total int64)) error {
|
||||
var downloadURL string
|
||||
var expectedHash string
|
||||
|
||||
switch runtime.GOOS {
|
||||
case "windows":
|
||||
if is64Bit() {
|
||||
downloadURL = exiftoolWindows64URL
|
||||
expectedHash = exiftoolWindows64Hash
|
||||
} else {
|
||||
downloadURL = exiftoolWindows32URL
|
||||
expectedHash = exiftoolWindows32Hash
|
||||
}
|
||||
case "linux", "darwin":
|
||||
// Linux and macOS use the same tar.gz archive
|
||||
downloadURL = exiftoolUnixURL
|
||||
expectedHash = exiftoolUnixHash
|
||||
default:
|
||||
return fmt.Errorf("unsupported platform: %s", runtime.GOOS)
|
||||
}
|
||||
|
||||
// Create temp file for download
|
||||
tempFile, err := os.CreateTemp("", "exiftool-*")
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create temp file: %v", err)
|
||||
}
|
||||
tempPath := tempFile.Name()
|
||||
defer os.Remove(tempPath)
|
||||
defer tempFile.Close()
|
||||
|
||||
// Download file
|
||||
resp, err := http.Get(downloadURL)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to download exiftool: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("failed to download exiftool: status %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
// Copy with progress
|
||||
total := resp.ContentLength
|
||||
var downloaded int64
|
||||
buf := make([]byte, 32*1024)
|
||||
|
||||
for {
|
||||
n, err := resp.Body.Read(buf)
|
||||
if n > 0 {
|
||||
_, writeErr := tempFile.Write(buf[:n])
|
||||
if writeErr != nil {
|
||||
return fmt.Errorf("failed to write temp file: %v", writeErr)
|
||||
}
|
||||
downloaded += int64(n)
|
||||
if progressCallback != nil {
|
||||
progressCallback(downloaded, total)
|
||||
}
|
||||
}
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to download: %v", err)
|
||||
}
|
||||
}
|
||||
tempFile.Close()
|
||||
|
||||
// Verify hash before extraction
|
||||
if expectedHash != "" {
|
||||
if err := verifyHash(tempPath, expectedHash); err != nil {
|
||||
return fmt.Errorf("hash verification failed: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Extract exiftool binary
|
||||
exiftoolPath := GetExifToolPath()
|
||||
baseDir := filepath.Dir(exiftoolPath)
|
||||
if err := os.MkdirAll(baseDir, 0755); err != nil {
|
||||
return fmt.Errorf("failed to create directory: %v", err)
|
||||
}
|
||||
|
||||
switch runtime.GOOS {
|
||||
case "windows":
|
||||
return extractExifToolFromZip(tempPath, exiftoolPath)
|
||||
case "linux", "darwin":
|
||||
// For Linux/macOS, we need to extract and build
|
||||
// For simplicity, we'll extract the exiftool script from tar.gz
|
||||
return extractExifToolFromTarGz(tempPath, exiftoolPath)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// extractExifToolFromZip extracts exiftool from Windows zip archive
|
||||
func extractExifToolFromZip(zipPath, destPath string) error {
|
||||
r, err := zip.OpenReader(zipPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to open zip: %v", err)
|
||||
}
|
||||
defer r.Close()
|
||||
|
||||
// Look for exiftool(-k).exe or exiftool.exe in the zip
|
||||
var exiftoolFile *zip.File
|
||||
for _, f := range r.File {
|
||||
name := filepath.Base(f.Name)
|
||||
// ExifTool Windows zip contains exiftool(-k).exe
|
||||
if name == "exiftool(-k).exe" || name == "exiftool.exe" {
|
||||
exiftoolFile = f
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if exiftoolFile == nil {
|
||||
return fmt.Errorf("exiftool.exe not found in archive")
|
||||
}
|
||||
|
||||
rc, err := exiftoolFile.Open()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to open file in zip: %v", err)
|
||||
}
|
||||
defer rc.Close()
|
||||
|
||||
out, err := os.Create(destPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create output file: %v", err)
|
||||
}
|
||||
defer out.Close()
|
||||
|
||||
if _, err := io.Copy(out, rc); err != nil {
|
||||
return fmt.Errorf("failed to extract file: %v", err)
|
||||
}
|
||||
|
||||
// Also need to extract the lib directory for Windows (exiftool_files folder)
|
||||
libDir := filepath.Join(filepath.Dir(destPath), "exiftool_files")
|
||||
for _, f := range r.File {
|
||||
// Check if file is in exiftool_files directory
|
||||
if strings.Contains(f.Name, "exiftool_files") && !strings.HasSuffix(f.Name, "/") {
|
||||
// Extract relative path from exiftool_files
|
||||
parts := strings.Split(f.Name, "exiftool_files/")
|
||||
if len(parts) < 2 {
|
||||
continue
|
||||
}
|
||||
relPath := parts[1]
|
||||
if relPath == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
targetPath := filepath.Join(libDir, relPath)
|
||||
|
||||
// Create directory structure
|
||||
if err := os.MkdirAll(filepath.Dir(targetPath), 0755); err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
// Skip if it's a directory entry
|
||||
if f.FileInfo().IsDir() {
|
||||
os.MkdirAll(targetPath, 0755)
|
||||
continue
|
||||
}
|
||||
|
||||
// Extract file
|
||||
rc, err := f.Open()
|
||||
if err != nil {
|
||||
continue // Skip on error
|
||||
}
|
||||
|
||||
outFile, err := os.Create(targetPath)
|
||||
if err != nil {
|
||||
rc.Close()
|
||||
continue
|
||||
}
|
||||
|
||||
io.Copy(outFile, rc)
|
||||
outFile.Close()
|
||||
rc.Close()
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// extractExifToolFromTarGz extracts exiftool from tar.gz archive (Linux/macOS)
|
||||
func extractExifToolFromTarGz(tarGzPath, destPath string) error {
|
||||
// For Linux/macOS, ExifTool is a Perl script that requires the lib directory
|
||||
// We'll extract the entire folder and use exiftool directly from Image-ExifTool-VERSION/exiftool
|
||||
// This is simpler than implementing tar.gz extraction in Go
|
||||
|
||||
baseDir := filepath.Dir(destPath)
|
||||
|
||||
// Use system tar command to extract
|
||||
cmd := exec.Command("tar", "-xzf", tarGzPath, "-C", baseDir)
|
||||
hideWindow(cmd)
|
||||
output, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to extract tar.gz: %v, output: %s", err, string(output))
|
||||
}
|
||||
|
||||
// Find the extracted exiftool script
|
||||
// The archive extracts to Image-ExifTool-VERSION/exiftool
|
||||
// We need to find the folder dynamically since version may vary
|
||||
var extractedDir string
|
||||
var exiftoolScript string
|
||||
|
||||
// Use glob pattern to find Image-ExifTool-* directories
|
||||
pattern := filepath.Join(baseDir, "Image-ExifTool-*")
|
||||
matches, err := filepath.Glob(pattern)
|
||||
if err == nil && len(matches) > 0 {
|
||||
// Use the first match (should only be one)
|
||||
extractedDir = matches[0]
|
||||
exiftoolScript = filepath.Join(extractedDir, "exiftool")
|
||||
} else {
|
||||
// Fallback: try common version or alternative location
|
||||
extractedDir = filepath.Join(baseDir, "Image-ExifTool-13.43")
|
||||
exiftoolScript = filepath.Join(extractedDir, "exiftool")
|
||||
}
|
||||
|
||||
// Check if exiftool script exists
|
||||
if _, err := os.Stat(exiftoolScript); err != nil {
|
||||
// Try alternative location
|
||||
extractedDir = filepath.Join(baseDir, "exiftool")
|
||||
exiftoolScript = filepath.Join(extractedDir, "exiftool")
|
||||
if _, err := os.Stat(exiftoolScript); err != nil {
|
||||
return fmt.Errorf("exiftool script not found in extracted archive (searched in: %s and %s)", pattern, extractedDir)
|
||||
}
|
||||
}
|
||||
|
||||
// Make exiftool executable (required for Unix systems)
|
||||
if err := os.Chmod(exiftoolScript, 0755); err != nil {
|
||||
return fmt.Errorf("failed to make exiftool executable: %v", err)
|
||||
}
|
||||
|
||||
// For Unix, we keep the entire folder structure and use exiftool directly from it
|
||||
// The folder will remain in baseDir and GetExifToolPath() will find it via glob pattern
|
||||
// No need to copy or remove anything
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,338 @@
|
||||
package backend
|
||||
|
||||
import (
|
||||
"archive/tar"
|
||||
"archive/zip"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
|
||||
"github.com/ulikunitz/xz"
|
||||
)
|
||||
|
||||
// FFmpeg download URLs
|
||||
const (
|
||||
ffmpegWindowsURL = "https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/ffmpeg-master-latest-win64-gpl.zip"
|
||||
ffmpegLinuxURL = "https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/ffmpeg-master-latest-linux64-gpl.tar.xz"
|
||||
ffmpegMacOSURL = "https://evermeet.cx/ffmpeg/getrelease/ffmpeg/zip"
|
||||
)
|
||||
|
||||
// GetFFmpegPath returns the path to ffmpeg binary
|
||||
func GetFFmpegPath() string {
|
||||
homeDir, _ := os.UserHomeDir()
|
||||
baseDir := filepath.Join(homeDir, ".twitterxmediabatchdownloader")
|
||||
|
||||
switch runtime.GOOS {
|
||||
case "windows":
|
||||
return filepath.Join(baseDir, "ffmpeg.exe")
|
||||
default:
|
||||
return filepath.Join(baseDir, "ffmpeg")
|
||||
}
|
||||
}
|
||||
|
||||
// IsFFmpegInstalled checks if ffmpeg is available
|
||||
func IsFFmpegInstalled() bool {
|
||||
ffmpegPath := GetFFmpegPath()
|
||||
if _, err := os.Stat(ffmpegPath); err == nil {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// DownloadFFmpeg downloads ffmpeg binary for current platform
|
||||
func DownloadFFmpeg(progressCallback func(downloaded, total int64)) error {
|
||||
var downloadURL string
|
||||
|
||||
switch runtime.GOOS {
|
||||
case "windows":
|
||||
downloadURL = ffmpegWindowsURL
|
||||
case "linux":
|
||||
downloadURL = ffmpegLinuxURL
|
||||
case "darwin":
|
||||
downloadURL = ffmpegMacOSURL
|
||||
default:
|
||||
return fmt.Errorf("unsupported platform: %s", runtime.GOOS)
|
||||
}
|
||||
|
||||
// Create temp file for download
|
||||
tempFile, err := os.CreateTemp("", "ffmpeg-*")
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create temp file: %v", err)
|
||||
}
|
||||
tempPath := tempFile.Name()
|
||||
defer os.Remove(tempPath)
|
||||
defer tempFile.Close()
|
||||
|
||||
// Download file
|
||||
resp, err := http.Get(downloadURL)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to download ffmpeg: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("failed to download ffmpeg: status %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
// Copy with progress
|
||||
total := resp.ContentLength
|
||||
var downloaded int64
|
||||
buf := make([]byte, 32*1024)
|
||||
|
||||
for {
|
||||
n, err := resp.Body.Read(buf)
|
||||
if n > 0 {
|
||||
_, writeErr := tempFile.Write(buf[:n])
|
||||
if writeErr != nil {
|
||||
return fmt.Errorf("failed to write temp file: %v", writeErr)
|
||||
}
|
||||
downloaded += int64(n)
|
||||
if progressCallback != nil {
|
||||
progressCallback(downloaded, total)
|
||||
}
|
||||
}
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to download: %v", err)
|
||||
}
|
||||
}
|
||||
tempFile.Close()
|
||||
|
||||
// Extract ffmpeg binary
|
||||
ffmpegPath := GetFFmpegPath()
|
||||
baseDir := filepath.Dir(ffmpegPath)
|
||||
if err := os.MkdirAll(baseDir, 0755); err != nil {
|
||||
return fmt.Errorf("failed to create directory: %v", err)
|
||||
}
|
||||
|
||||
switch runtime.GOOS {
|
||||
case "windows", "darwin":
|
||||
return extractFromZip(tempPath, ffmpegPath)
|
||||
case "linux":
|
||||
return extractFromTarXz(tempPath, ffmpegPath)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// extractFromZip extracts ffmpeg from zip archive
|
||||
func extractFromZip(zipPath, destPath string) error {
|
||||
r, err := zip.OpenReader(zipPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to open zip: %v", err)
|
||||
}
|
||||
defer r.Close()
|
||||
|
||||
for _, f := range r.File {
|
||||
// Look for ffmpeg binary
|
||||
name := filepath.Base(f.Name)
|
||||
if name == "ffmpeg" || name == "ffmpeg.exe" {
|
||||
rc, err := f.Open()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to open file in zip: %v", err)
|
||||
}
|
||||
defer rc.Close()
|
||||
|
||||
out, err := os.Create(destPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create output file: %v", err)
|
||||
}
|
||||
defer out.Close()
|
||||
|
||||
if _, err := io.Copy(out, rc); err != nil {
|
||||
return fmt.Errorf("failed to extract file: %v", err)
|
||||
}
|
||||
|
||||
// Make executable on Unix
|
||||
if runtime.GOOS != "windows" {
|
||||
os.Chmod(destPath, 0755)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
return fmt.Errorf("ffmpeg binary not found in archive")
|
||||
}
|
||||
|
||||
// extractFromTarXz extracts ffmpeg from tar.xz archive
|
||||
func extractFromTarXz(tarXzPath, destPath string) error {
|
||||
file, err := os.Open(tarXzPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to open tar.xz: %v", err)
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
xzReader, err := xz.NewReader(file)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create xz reader: %v", err)
|
||||
}
|
||||
|
||||
tarReader := tar.NewReader(xzReader)
|
||||
|
||||
for {
|
||||
header, err := tarReader.Next()
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read tar: %v", err)
|
||||
}
|
||||
|
||||
// Look for ffmpeg binary
|
||||
name := filepath.Base(header.Name)
|
||||
if name == "ffmpeg" && header.Typeflag == tar.TypeReg {
|
||||
out, err := os.Create(destPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create output file: %v", err)
|
||||
}
|
||||
defer out.Close()
|
||||
|
||||
if _, err := io.Copy(out, tarReader); err != nil {
|
||||
return fmt.Errorf("failed to extract file: %v", err)
|
||||
}
|
||||
|
||||
os.Chmod(destPath, 0755)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
return fmt.Errorf("ffmpeg binary not found in archive")
|
||||
}
|
||||
|
||||
// ConvertMP4ToGIF converts an MP4 file to GIF using ffmpeg
|
||||
// quality: "fast" for simple conversion, "better" for optimized palette
|
||||
// resolution: "original", "high" (800px), "medium" (600px), "low" (400px)
|
||||
func ConvertMP4ToGIF(inputPath, outputPath, quality, resolution string) error {
|
||||
ffmpegPath := GetFFmpegPath()
|
||||
|
||||
if !IsFFmpegInstalled() {
|
||||
return fmt.Errorf("ffmpeg not installed")
|
||||
}
|
||||
|
||||
var args []string
|
||||
|
||||
if quality == "fast" {
|
||||
// Fast mode: simple conversion with resolution scaling
|
||||
var scaleFilter string
|
||||
switch resolution {
|
||||
case "high":
|
||||
scaleFilter = "scale=800:-1"
|
||||
case "medium":
|
||||
scaleFilter = "scale=600:-1"
|
||||
case "low":
|
||||
scaleFilter = "scale=400:-1"
|
||||
default: // original - no scaling
|
||||
scaleFilter = ""
|
||||
}
|
||||
|
||||
if scaleFilter != "" {
|
||||
args = []string{
|
||||
"-i", inputPath,
|
||||
"-vf", scaleFilter,
|
||||
"-loop", "0",
|
||||
"-y",
|
||||
outputPath,
|
||||
}
|
||||
} else {
|
||||
args = []string{
|
||||
"-i", inputPath,
|
||||
"-loop", "0",
|
||||
"-y",
|
||||
outputPath,
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Better mode: optimized palette with dithering
|
||||
var filter string
|
||||
|
||||
switch resolution {
|
||||
case "high":
|
||||
filter = "scale=800:-1:flags=lanczos,palettegen=stats_mode=full[palette];[0:v]scale=800:-1:flags=lanczos[scaled];[scaled][palette]paletteuse=dither=sierra2_4a"
|
||||
case "medium":
|
||||
filter = "scale=600:-1:flags=lanczos,palettegen=stats_mode=full[palette];[0:v]scale=600:-1:flags=lanczos[scaled];[scaled][palette]paletteuse=dither=sierra2_4a"
|
||||
case "low":
|
||||
filter = "scale=400:-1:flags=lanczos,palettegen=stats_mode=full[palette];[0:v]scale=400:-1:flags=lanczos[scaled];[scaled][palette]paletteuse=dither=sierra2_4a"
|
||||
default: // original
|
||||
filter = "palettegen=stats_mode=full[palette];[0:v][palette]paletteuse=dither=sierra2_4a"
|
||||
}
|
||||
|
||||
// Set FPS based on resolution
|
||||
fps := "15"
|
||||
if resolution == "medium" {
|
||||
fps = "10"
|
||||
} else if resolution == "low" {
|
||||
fps = "8"
|
||||
}
|
||||
|
||||
args = []string{
|
||||
"-i", inputPath,
|
||||
"-lavfi", filter,
|
||||
"-r", fps,
|
||||
"-y",
|
||||
outputPath,
|
||||
}
|
||||
}
|
||||
|
||||
cmd := exec.Command(ffmpegPath, args...)
|
||||
hideWindow(cmd) // Hide console window on Windows
|
||||
output, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
return fmt.Errorf("ffmpeg error: %v, output: %s", err, string(output))
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// ConvertGIFsInFolder converts all MP4 files in gifs folder to actual GIF format
|
||||
func ConvertGIFsInFolder(folderPath, quality, resolution string, deleteOriginal bool) (converted int, failed int, err error) {
|
||||
if !IsFFmpegInstalled() {
|
||||
return 0, 0, fmt.Errorf("ffmpeg not installed")
|
||||
}
|
||||
|
||||
// Clean the path to handle cross-platform path separators
|
||||
cleanPath := filepath.Clean(folderPath)
|
||||
gifsFolder := filepath.Join(cleanPath, "gifs")
|
||||
if _, err := os.Stat(gifsFolder); os.IsNotExist(err) {
|
||||
return 0, 0, fmt.Errorf("gifs folder not found: %s", gifsFolder)
|
||||
}
|
||||
|
||||
files, err := os.ReadDir(gifsFolder)
|
||||
if err != nil {
|
||||
return 0, 0, fmt.Errorf("failed to read gifs folder: %v", err)
|
||||
}
|
||||
|
||||
for _, file := range files {
|
||||
if file.IsDir() {
|
||||
continue
|
||||
}
|
||||
|
||||
name := file.Name()
|
||||
if !strings.HasSuffix(strings.ToLower(name), ".mp4") {
|
||||
continue
|
||||
}
|
||||
|
||||
inputPath := filepath.Join(gifsFolder, name)
|
||||
outputPath := filepath.Join(gifsFolder, strings.TrimSuffix(name, filepath.Ext(name))+".gif")
|
||||
|
||||
if err := ConvertMP4ToGIF(inputPath, outputPath, quality, resolution); err != nil {
|
||||
failed++
|
||||
continue
|
||||
}
|
||||
|
||||
if deleteOriginal {
|
||||
os.Remove(inputPath)
|
||||
}
|
||||
|
||||
converted++
|
||||
}
|
||||
|
||||
return converted, failed, nil
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package backend
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
)
|
||||
|
||||
func OpenFolderInExplorer(path string) error {
|
||||
var cmd *exec.Cmd
|
||||
|
||||
switch runtime.GOOS {
|
||||
case "windows":
|
||||
// Use cmd /c start to open explorer - more reliable
|
||||
cmd = exec.Command("cmd", "/c", "start", "", path)
|
||||
case "darwin": // macOS
|
||||
cmd = exec.Command("open", path)
|
||||
case "linux":
|
||||
cmd = exec.Command("xdg-open", path)
|
||||
default:
|
||||
cmd = exec.Command("xdg-open", path)
|
||||
}
|
||||
|
||||
hideWindow(cmd) // Hide console window on Windows
|
||||
return cmd.Run()
|
||||
}
|
||||
|
||||
func SelectFolderDialog(ctx context.Context, defaultPath string) (string, error) {
|
||||
// If defaultPath is empty, use default download path
|
||||
if defaultPath == "" {
|
||||
defaultPath = GetDefaultDownloadPath()
|
||||
}
|
||||
|
||||
options := wailsRuntime.OpenDialogOptions{
|
||||
Title: "Select Download Folder",
|
||||
DefaultDirectory: defaultPath,
|
||||
}
|
||||
|
||||
selectedPath, err := wailsRuntime.OpenDirectoryDialog(ctx, options)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// If user cancelled, selectedPath will be empty
|
||||
if selectedPath == "" {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
return selectedPath, nil
|
||||
}
|
||||
|
||||
// CheckFolderExists checks if a folder exists at the given path
|
||||
func CheckFolderExists(basePath, username string) bool {
|
||||
folderPath := filepath.Join(basePath, username)
|
||||
info, err := os.Stat(folderPath)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return info.IsDir()
|
||||
}
|
||||
|
||||
// CheckGifsFolderExists checks if a gifs subfolder exists for the given username
|
||||
func CheckGifsFolderExists(basePath, username string) bool {
|
||||
gifsPath := filepath.Join(basePath, username, "gifs")
|
||||
info, err := os.Stat(gifsPath)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return info.IsDir()
|
||||
}
|
||||
|
||||
// CheckGifsFolderHasMP4 checks if the gifs folder has any MP4 files to convert
|
||||
func CheckGifsFolderHasMP4(basePath, username string) bool {
|
||||
gifsPath := filepath.Join(basePath, username, "gifs")
|
||||
|
||||
entries, err := os.ReadDir(gifsPath)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
for _, entry := range entries {
|
||||
if !entry.IsDir() {
|
||||
ext := filepath.Ext(entry.Name())
|
||||
if ext == ".mp4" || ext == ".MP4" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// GetFolderPath returns the full path for a username folder
|
||||
func GetFolderPath(basePath, username string) string {
|
||||
return filepath.Join(basePath, username)
|
||||
}
|
||||
|
||||
// GetGifsFolderPath returns the full path for a username's gifs folder
|
||||
func GetGifsFolderPath(basePath, username string) string {
|
||||
return filepath.Join(basePath, username, "gifs")
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
package backend
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"runtime"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// ExtractOriginalFilename extracts the original filename from Twitter media URL
|
||||
// Supports 3 formats:
|
||||
// 1. animated_gif: https://video.twimg.com/tweet_video/GzstJyDbIAAPuX9.mp4 -> GzstJyDbIAAPuX9
|
||||
// 2. photo: https://pbs.twimg.com/media/GynjhU0bYAAA_I4?format=jpg -> GynjhU0bYAAA_I4
|
||||
// 3. video: https://video.twimg.com/amplify_video/.../Jpo0cDa7aNtjSv7o.mp4 -> Jpo0cDa7aNtjSv7o
|
||||
func ExtractOriginalFilename(mediaURL string) string {
|
||||
parsedURL, err := url.Parse(mediaURL)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
path := parsedURL.Path
|
||||
parts := strings.Split(path, "/")
|
||||
|
||||
// 1. animated_gif: video.twimg.com/tweet_video/XXX.mp4
|
||||
if strings.Contains(mediaURL, "/tweet_video/") {
|
||||
for i, part := range parts {
|
||||
if part == "tweet_video" && i+1 < len(parts) {
|
||||
filename := parts[i+1]
|
||||
// Remove extension
|
||||
if idx := strings.LastIndex(filename, "."); idx > 0 {
|
||||
filename = filename[:idx]
|
||||
}
|
||||
// Validate alphanumeric + underscore (Twitter filenames can contain _)
|
||||
if matched, _ := regexp.MatchString(`^[A-Za-z0-9_]+$`, filename); matched && len(filename) > 0 {
|
||||
return filename
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2. photo: pbs.twimg.com/media/XXX
|
||||
if strings.Contains(mediaURL, "pbs.twimg.com/media/") {
|
||||
if len(parts) > 0 {
|
||||
filename := parts[len(parts)-1]
|
||||
// Remove extension if present
|
||||
if idx := strings.LastIndex(filename, "."); idx > 0 {
|
||||
filename = filename[:idx]
|
||||
}
|
||||
// Validate alphanumeric + underscore (Twitter filenames can contain _)
|
||||
if matched, _ := regexp.MatchString(`^[A-Za-z0-9_]+$`, filename); matched && len(filename) > 0 {
|
||||
return filename
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. video: video.twimg.com/amplify_video/.../XXX.mp4 or video.twimg.com/ext_tw_video/.../XXX.mp4
|
||||
// Filename is the last segment (before extension)
|
||||
// Note: Skip if already handled by tweet_video above
|
||||
if strings.Contains(mediaURL, "video.twimg.com") && !strings.Contains(mediaURL, "/tweet_video/") {
|
||||
if len(parts) > 0 {
|
||||
filename := parts[len(parts)-1]
|
||||
// Remove extension
|
||||
if idx := strings.LastIndex(filename, "."); idx > 0 {
|
||||
filename = filename[:idx]
|
||||
}
|
||||
// Validate: alphanumeric + underscore with at least one letter (to exclude pure numeric IDs)
|
||||
if matched, _ := regexp.MatchString(`^[A-Za-z0-9_]+$`, filename); matched {
|
||||
hasLetter, _ := regexp.MatchString(`[A-Za-z]`, filename)
|
||||
if hasLetter && len(filename) >= 8 {
|
||||
return filename
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
// EmbedMetadata embeds metadata into a media file
|
||||
// Only supports JPG (images) and MP4 (videos)
|
||||
func EmbedMetadata(filePath string, tweetContent string, tweetURL string, originalFilename string) error {
|
||||
ext := strings.ToLower(filepath.Ext(filePath))
|
||||
|
||||
switch ext {
|
||||
case ".jpg", ".jpeg":
|
||||
return embedImageMetadata(filePath, tweetContent, tweetURL, originalFilename)
|
||||
case ".mp4":
|
||||
return embedVideoMetadata(filePath, tweetContent, tweetURL, originalFilename)
|
||||
default:
|
||||
// For unsupported formats, skip metadata embedding
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// embedImageMetadata embeds metadata into image files using exiftool or similar
|
||||
// Since we don't want to add heavy dependencies, we'll use a simple approach:
|
||||
// For JPEG: We can use exiftool if available, or skip if not
|
||||
// For PNG: Limited support, skip for now
|
||||
func embedImageMetadata(filePath string, tweetContent string, tweetURL string, originalFilename string) error {
|
||||
// Try to use exiftool if available (common tool for metadata)
|
||||
exiftoolPath := findExifTool()
|
||||
if exiftoolPath == "" {
|
||||
// exiftool not found, skip metadata embedding for images
|
||||
// This is acceptable as it's an optional feature
|
||||
return nil
|
||||
}
|
||||
|
||||
// Build metadata comment
|
||||
metadataComment := buildMetadataComment(tweetContent, tweetURL, originalFilename)
|
||||
|
||||
// Use exiftool to add comment only (URL | filename)
|
||||
args := []string{
|
||||
"-overwrite_original",
|
||||
"-Comment=" + metadataComment,
|
||||
filePath,
|
||||
}
|
||||
|
||||
cmd := exec.Command(exiftoolPath, args...)
|
||||
hideWindow(cmd)
|
||||
output, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
// Non-fatal: if exiftool fails, just skip metadata
|
||||
return fmt.Errorf("exiftool error (non-fatal): %v, output: %s", err, string(output))
|
||||
}
|
||||
|
||||
_ = output // Suppress unused variable warning
|
||||
return nil
|
||||
}
|
||||
|
||||
// embedVideoMetadata embeds metadata into video/GIF files using ExifTool
|
||||
func embedVideoMetadata(filePath string, tweetContent string, tweetURL string, originalFilename string) error {
|
||||
// Use ExifTool for video metadata (works well for MP4)
|
||||
exiftoolPath := findExifTool()
|
||||
if exiftoolPath == "" {
|
||||
// ExifTool not available, skip metadata embedding (non-fatal)
|
||||
return nil
|
||||
}
|
||||
|
||||
return embedVideoMetadataWithExifTool(exiftoolPath, filePath, tweetContent, tweetURL, originalFilename)
|
||||
}
|
||||
|
||||
// embedVideoMetadataWithExifTool embeds metadata using ExifTool (preferred for MP4)
|
||||
func embedVideoMetadataWithExifTool(exiftoolPath string, filePath string, tweetContent string, tweetURL string, originalFilename string) error {
|
||||
// Build metadata comment
|
||||
metadataComment := buildMetadataComment(tweetContent, tweetURL, originalFilename)
|
||||
|
||||
// Use exiftool to add comment only (URL | filename)
|
||||
args := []string{
|
||||
"-overwrite_original",
|
||||
"-Comment=" + metadataComment,
|
||||
filePath,
|
||||
}
|
||||
|
||||
cmd := exec.Command(exiftoolPath, args...)
|
||||
hideWindow(cmd)
|
||||
output, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
// Non-fatal: if exiftool fails, skip metadata (file still downloaded)
|
||||
return fmt.Errorf("exiftool error (non-fatal): %v, output: %s", err, string(output))
|
||||
}
|
||||
|
||||
_ = output // Suppress unused variable warning
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
// buildMetadataComment builds a formatted metadata comment string
|
||||
func buildMetadataComment(tweetContent string, tweetURL string, originalFilename string) string {
|
||||
var parts []string
|
||||
|
||||
if tweetURL != "" {
|
||||
parts = append(parts, tweetURL)
|
||||
}
|
||||
if originalFilename != "" {
|
||||
parts = append(parts, originalFilename)
|
||||
}
|
||||
|
||||
// If no original filename, just return URL (don't add empty part)
|
||||
if len(parts) == 0 {
|
||||
return ""
|
||||
}
|
||||
|
||||
return strings.Join(parts, " | ")
|
||||
}
|
||||
|
||||
// findExifTool searches for exiftool, prioritizing the installed version in .twitterxmediabatchdownloader
|
||||
func findExifTool() string {
|
||||
// First, check if exiftool is installed in .twitterxmediabatchdownloader
|
||||
if IsExifToolInstalled() {
|
||||
return GetExifToolPath()
|
||||
}
|
||||
|
||||
// Fallback: check common system locations
|
||||
commonPaths := []string{
|
||||
"exiftool",
|
||||
"/usr/bin/exiftool",
|
||||
"/usr/local/bin/exiftool",
|
||||
"C:\\Program Files\\exiftool\\exiftool.exe",
|
||||
"C:\\exiftool\\exiftool.exe",
|
||||
}
|
||||
|
||||
for _, path := range commonPaths {
|
||||
if runtime.GOOS == "windows" {
|
||||
// On Windows, try .exe extension
|
||||
if _, err := exec.LookPath(path); err == nil {
|
||||
return path
|
||||
}
|
||||
} else {
|
||||
// On Unix, check if executable
|
||||
if _, err := os.Stat(path); err == nil {
|
||||
return path
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Try to find in PATH
|
||||
if path, err := exec.LookPath("exiftool"); err == nil {
|
||||
return path
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
@@ -0,0 +1,918 @@
|
||||
package backend
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// getExecutableName returns the appropriate executable name for the current OS
|
||||
func getExecutableName() string {
|
||||
if runtime.GOOS == "windows" {
|
||||
return "extractor.exe"
|
||||
}
|
||||
return "extractor"
|
||||
}
|
||||
|
||||
// KillAllExtractorProcesses kills all running extractor processes
|
||||
// This is useful for cleanup when starting fresh or when user stops fetch
|
||||
func KillAllExtractorProcesses() {
|
||||
exeName := getExecutableName()
|
||||
|
||||
var cmd *exec.Cmd
|
||||
if runtime.GOOS == "windows" {
|
||||
// Use taskkill on Windows
|
||||
cmd = exec.Command("taskkill", "/F", "/IM", exeName)
|
||||
} else {
|
||||
// Use pkill on Unix
|
||||
cmd = exec.Command("pkill", "-f", exeName)
|
||||
}
|
||||
|
||||
hideWindow(cmd)
|
||||
cmd.CombinedOutput() // Ignore errors - it's okay if no processes found
|
||||
}
|
||||
|
||||
// parseExtractorError parses the extractor output and returns a user-friendly error message
|
||||
// while preserving the original error from gallery-dl
|
||||
func parseExtractorError(output string, username string) string {
|
||||
outputLower := strings.ToLower(output)
|
||||
|
||||
// Extract the actual error line from gallery-dl output
|
||||
lines := strings.Split(output, "\n")
|
||||
var errorLine string
|
||||
for _, line := range lines {
|
||||
lineLower := strings.ToLower(line)
|
||||
if strings.Contains(lineLower, "error:") || strings.Contains(lineLower, "exception") {
|
||||
errorLine = strings.TrimSpace(line)
|
||||
break
|
||||
}
|
||||
}
|
||||
if errorLine == "" {
|
||||
errorLine = strings.TrimSpace(output)
|
||||
}
|
||||
|
||||
// Truncate if too long
|
||||
if len(errorLine) > 300 {
|
||||
errorLine = errorLine[:300] + "..."
|
||||
}
|
||||
|
||||
// Add context hint based on error type, but keep original message
|
||||
var hint string
|
||||
if strings.Contains(outputLower, "unable to retrieve tweets from this timeline") {
|
||||
hint = " [Hint: End of timeline reached or rate limited - data already fetched has been saved]"
|
||||
} else if strings.Contains(outputLower, "rate limit") || strings.Contains(output, "429") {
|
||||
hint = " [Hint: Wait 5-15 minutes before retrying]"
|
||||
} else if strings.Contains(output, "401") || strings.Contains(outputLower, "unauthorized") {
|
||||
hint = " [Hint: Auth token may be invalid or expired]"
|
||||
} else if strings.Contains(output, "404") {
|
||||
hint = fmt.Sprintf(" [Hint: @%s may not exist or is suspended]", username)
|
||||
} else if strings.Contains(outputLower, "protected") || strings.Contains(output, "403") {
|
||||
hint = " [Hint: Protected account - need to follow and use auth token]"
|
||||
}
|
||||
|
||||
return errorLine + hint
|
||||
}
|
||||
|
||||
// TweetIDString is a custom type that unmarshals int64 but marshals as string
|
||||
type TweetIDString int64
|
||||
|
||||
// MarshalJSON converts TweetIDString to JSON string to preserve precision in JavaScript
|
||||
func (t TweetIDString) MarshalJSON() ([]byte, error) {
|
||||
return []byte(fmt.Sprintf(`"%d"`, t)), nil
|
||||
}
|
||||
|
||||
// UnmarshalJSON accepts both number and string from JSON
|
||||
func (t *TweetIDString) UnmarshalJSON(data []byte) error {
|
||||
// Try to unmarshal as number first (from extractor)
|
||||
var num int64
|
||||
if err := json.Unmarshal(data, &num); err == nil {
|
||||
*t = TweetIDString(num)
|
||||
return nil
|
||||
}
|
||||
// Try as string (for future compatibility)
|
||||
var str string
|
||||
if err := json.Unmarshal(data, &str); err == nil {
|
||||
parsed, err := fmt.Sscanf(str, "%d", &num)
|
||||
if err != nil || parsed != 1 {
|
||||
return fmt.Errorf("invalid tweet_id string: %s", str)
|
||||
}
|
||||
*t = TweetIDString(num)
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("tweet_id must be number or string")
|
||||
}
|
||||
|
||||
// Author represents tweet author information from extractor
|
||||
type Author struct {
|
||||
ID int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Nick string `json:"nick"`
|
||||
}
|
||||
|
||||
// UserInfo represents full user information from extractor
|
||||
type UserInfo struct {
|
||||
ID int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Nick string `json:"nick"`
|
||||
Location string `json:"location"`
|
||||
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"`
|
||||
}
|
||||
|
||||
// CLIMediaItem represents a single media entry from extractor CLI
|
||||
type CLIMediaItem struct {
|
||||
URL string `json:"url"`
|
||||
TweetID TweetIDString `json:"tweet_id"`
|
||||
RetweetID TweetIDString `json:"retweet_id"`
|
||||
QuoteID TweetIDString `json:"quote_id"`
|
||||
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"`
|
||||
}
|
||||
|
||||
// TweetMetadata represents tweet metadata from extractor
|
||||
type TweetMetadata struct {
|
||||
TweetID TweetIDString `json:"tweet_id"`
|
||||
RetweetID TweetIDString `json:"retweet_id,omitempty"`
|
||||
QuoteID TweetIDString `json:"quote_id,omitempty"`
|
||||
ReplyID TweetIDString `json:"reply_id,omitempty"`
|
||||
ConversationID TweetIDString `json:"conversation_id,omitempty"`
|
||||
Date string `json:"date"`
|
||||
Author Author `json:"author"`
|
||||
Content string `json:"content"`
|
||||
Lang string `json:"lang,omitempty"`
|
||||
Hashtags []string `json:"hashtags,omitempty"`
|
||||
FavoriteCount int `json:"favorite_count"`
|
||||
RetweetCount int `json:"retweet_count"`
|
||||
QuoteCount int `json:"quote_count,omitempty"`
|
||||
ReplyCount int `json:"reply_count,omitempty"`
|
||||
BookmarkCount int `json:"bookmark_count,omitempty"`
|
||||
ViewCount int `json:"view_count,omitempty"`
|
||||
Sensitive bool `json:"sensitive,omitempty"`
|
||||
}
|
||||
|
||||
// CLIResponse represents the raw response from extractor CLI
|
||||
type CLIResponse struct {
|
||||
Media []CLIMediaItem `json:"media"`
|
||||
Metadata []TweetMetadata `json:"metadata"`
|
||||
Cursor string `json:"cursor,omitempty"` // Cursor for resume
|
||||
Total int `json:"total,omitempty"` // Total items fetched
|
||||
Completed bool `json:"completed,omitempty"` // True if all fetched
|
||||
}
|
||||
|
||||
// TimelineEntry represents a single media entry for frontend (converted from MediaItem)
|
||||
type TimelineEntry struct {
|
||||
URL string `json:"url"`
|
||||
Date string `json:"date"`
|
||||
TweetID TweetIDString `json:"tweet_id"`
|
||||
Type string `json:"type"`
|
||||
IsRetweet bool `json:"is_retweet"`
|
||||
Extension string `json:"extension"`
|
||||
Width int `json:"width"`
|
||||
Height int `json:"height"`
|
||||
Content string `json:"content,omitempty"`
|
||||
ViewCount int `json:"view_count,omitempty"`
|
||||
BookmarkCount int `json:"bookmark_count,omitempty"`
|
||||
FavoriteCount int `json:"favorite_count,omitempty"`
|
||||
RetweetCount int `json:"retweet_count,omitempty"`
|
||||
ReplyCount int `json:"reply_count,omitempty"`
|
||||
Source string `json:"source,omitempty"`
|
||||
Verified bool `json:"verified,omitempty"`
|
||||
OriginalFilename string `json:"original_filename,omitempty"` // Original filename from API
|
||||
AuthorUsername string `json:"author_username,omitempty"` // Username of tweet author (for bookmarks and likes)
|
||||
}
|
||||
|
||||
// AccountInfo represents Twitter account information (derived from metadata)
|
||||
type AccountInfo struct {
|
||||
Name string `json:"name"`
|
||||
Nick string `json:"nick"`
|
||||
Date string `json:"date"`
|
||||
FollowersCount int `json:"followers_count"`
|
||||
FriendsCount int `json:"friends_count"`
|
||||
ProfileImage string `json:"profile_image"`
|
||||
StatusesCount int `json:"statuses_count"`
|
||||
}
|
||||
|
||||
// ExtractMetadata represents extraction metadata
|
||||
type ExtractMetadata struct {
|
||||
NewEntries int `json:"new_entries"`
|
||||
Page int `json:"page"`
|
||||
BatchSize int `json:"batch_size"`
|
||||
HasMore bool `json:"has_more"`
|
||||
Cursor string `json:"cursor,omitempty"` // Cursor for resume capability
|
||||
Completed bool `json:"completed,omitempty"` // True if all media fetched
|
||||
}
|
||||
|
||||
// TwitterResponse represents the full response for frontend
|
||||
type TwitterResponse struct {
|
||||
AccountInfo AccountInfo `json:"account_info"`
|
||||
TotalURLs int `json:"total_urls"`
|
||||
Timeline []TimelineEntry `json:"timeline"`
|
||||
Metadata ExtractMetadata `json:"metadata"`
|
||||
Cursor string `json:"cursor,omitempty"` // Cursor for next fetch
|
||||
Completed bool `json:"completed,omitempty"` // True if fetch completed
|
||||
}
|
||||
|
||||
// TimelineRequest represents request parameters for timeline extraction
|
||||
type TimelineRequest struct {
|
||||
Username string `json:"username"`
|
||||
AuthToken string `json:"auth_token"`
|
||||
TimelineType string `json:"timeline_type"` // media, timeline, tweets, with_replies, likes, bookmarks
|
||||
BatchSize int `json:"batch_size"` // 0 = all
|
||||
Page int `json:"page"`
|
||||
MediaType string `json:"media_type"` // all, image, video, gif
|
||||
Retweets bool `json:"retweets"`
|
||||
Cursor string `json:"cursor,omitempty"` // Resume from this cursor position
|
||||
}
|
||||
|
||||
// DateRangeRequest represents request parameters for date range extraction
|
||||
type DateRangeRequest struct {
|
||||
Username string `json:"username"`
|
||||
AuthToken string `json:"auth_token"`
|
||||
StartDate string `json:"start_date"` // YYYY-MM-DD
|
||||
EndDate string `json:"end_date"` // YYYY-MM-DD
|
||||
MediaFilter string `json:"media_filter"`
|
||||
Retweets bool `json:"retweets"`
|
||||
}
|
||||
|
||||
// buildTwitterURL constructs the Twitter URL based on username and timeline type
|
||||
func buildTwitterURL(username, timelineType string) string {
|
||||
// Special case: bookmarks don't need username
|
||||
if timelineType == "bookmarks" {
|
||||
return "https://x.com/i/bookmarks"
|
||||
}
|
||||
|
||||
// Clean username - extract handle from URL if needed
|
||||
username = cleanUsername(username)
|
||||
|
||||
// Build URL based on timeline type
|
||||
baseURL := "https://x.com/" + username
|
||||
switch timelineType {
|
||||
case "media":
|
||||
return baseURL + "/media"
|
||||
case "timeline":
|
||||
return baseURL + "/timeline" // Best for cursor support
|
||||
case "tweets":
|
||||
return baseURL + "/tweets"
|
||||
case "with_replies":
|
||||
return baseURL + "/with_replies"
|
||||
case "likes":
|
||||
return baseURL + "/likes"
|
||||
default:
|
||||
return baseURL + "/timeline" // Default to timeline for reliable cursor
|
||||
}
|
||||
}
|
||||
|
||||
// cleanUsername extracts the handle from different input formats
|
||||
// Handles: @username, username, https://x.com/username, https://x.com/username/media, etc.
|
||||
func cleanUsername(username string) string {
|
||||
username = strings.TrimSpace(username)
|
||||
username = strings.TrimPrefix(username, "@")
|
||||
|
||||
if strings.Contains(username, "x.com/") || strings.Contains(username, "twitter.com/") {
|
||||
parsed := username
|
||||
if !strings.HasPrefix(parsed, "http://") && !strings.HasPrefix(parsed, "https://") {
|
||||
parsed = "https://" + strings.TrimPrefix(parsed, "//")
|
||||
}
|
||||
if u, err := url.Parse(parsed); err == nil {
|
||||
segments := strings.Split(strings.Trim(u.Path, "/"), "/")
|
||||
// Skip special paths like /i/bookmarks, /search, /home, /explore
|
||||
if len(segments) > 0 && segments[0] != "" {
|
||||
firstSegment := strings.ToLower(segments[0])
|
||||
// These are not usernames
|
||||
if firstSegment == "i" || firstSegment == "search" || firstSegment == "home" || firstSegment == "explore" || firstSegment == "settings" || firstSegment == "messages" || firstSegment == "notifications" {
|
||||
return username // Return as-is, let caller handle
|
||||
}
|
||||
return segments[0]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return username
|
||||
}
|
||||
|
||||
// ensureURLScheme normalises URLs so the CLI accepts them
|
||||
func ensureURLScheme(raw string) string {
|
||||
raw = strings.TrimSpace(raw)
|
||||
if raw == "" {
|
||||
return raw
|
||||
}
|
||||
if strings.HasPrefix(raw, "http://") || strings.HasPrefix(raw, "https://") {
|
||||
return raw
|
||||
}
|
||||
if strings.HasPrefix(raw, "//") {
|
||||
return "https:" + raw
|
||||
}
|
||||
return "https://" + strings.TrimPrefix(raw, "//")
|
||||
}
|
||||
|
||||
// buildSearchURL assembles an X.com search URL for date range queries
|
||||
func buildSearchURL(username, startDate, endDate, mediaFilter string, includeRetweets bool) string {
|
||||
trimmed := strings.TrimSpace(username)
|
||||
lower := strings.ToLower(trimmed)
|
||||
if strings.Contains(lower, "search?q=") {
|
||||
return ensureURLScheme(trimmed)
|
||||
}
|
||||
|
||||
handle := cleanUsername(trimmed)
|
||||
var parts []string
|
||||
if handle != "" {
|
||||
parts = append(parts, fmt.Sprintf("from:%s", handle))
|
||||
}
|
||||
if startDate != "" {
|
||||
parts = append(parts, fmt.Sprintf("since:%s", startDate))
|
||||
}
|
||||
if endDate != "" {
|
||||
parts = append(parts, fmt.Sprintf("until:%s", endDate))
|
||||
}
|
||||
|
||||
switch strings.ToLower(strings.TrimSpace(mediaFilter)) {
|
||||
case "image", "images", "photo", "photos":
|
||||
parts = append(parts, "filter:images")
|
||||
case "video", "videos", "gif", "gifs":
|
||||
parts = append(parts, "filter:videos")
|
||||
case "text":
|
||||
parts = append(parts, "-filter:media")
|
||||
default:
|
||||
parts = append(parts, "filter:media")
|
||||
}
|
||||
|
||||
if !includeRetweets {
|
||||
parts = append(parts, "-filter:retweets")
|
||||
}
|
||||
|
||||
query := url.QueryEscape(strings.Join(parts, " "))
|
||||
return fmt.Sprintf("https://x.com/search?q=%s&src=typed_query&f=live", query)
|
||||
}
|
||||
|
||||
// convertMetadataToTimelineEntry converts metadata-only tweets to timeline entries
|
||||
func convertMetadataToTimelineEntry(meta TweetMetadata) TimelineEntry {
|
||||
return TimelineEntry{
|
||||
URL: "",
|
||||
Date: meta.Date,
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
// convertToTimelineEntry converts CLIMediaItem to TimelineEntry
|
||||
func convertToTimelineEntry(media CLIMediaItem) TimelineEntry {
|
||||
// Get username from Author field (preferred for bookmarks/likes) or User field
|
||||
// Author field always contains the tweet author, while User might be the account fetching for likes
|
||||
authorUsername := ""
|
||||
if media.Author.Name != "" {
|
||||
authorUsername = media.Author.Name
|
||||
} else if media.User.Name != "" {
|
||||
authorUsername = media.User.Name
|
||||
}
|
||||
|
||||
entry := TimelineEntry{
|
||||
URL: media.URL,
|
||||
TweetID: media.TweetID,
|
||||
Date: media.Date,
|
||||
Extension: media.Extension,
|
||||
Width: media.Width,
|
||||
Height: media.Height,
|
||||
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,
|
||||
// OriginalFilename will be extracted from URL in download.go
|
||||
}
|
||||
|
||||
// Determine type - media item already has type from CLI
|
||||
if media.Type != "" {
|
||||
entry.Type = media.Type
|
||||
} else {
|
||||
switch strings.ToLower(media.Extension) {
|
||||
case "mp4", "webm":
|
||||
entry.Type = "video"
|
||||
case "gif":
|
||||
entry.Type = "gif"
|
||||
default:
|
||||
entry.Type = "photo"
|
||||
}
|
||||
}
|
||||
|
||||
return entry
|
||||
}
|
||||
|
||||
// getExtractorPath returns the path to extractor binary
|
||||
// Binary is stored in ~/.twitterxmediabatchdownloader/ (same as ffmpeg and database)
|
||||
func getExtractorPath() string {
|
||||
homeDir, _ := os.UserHomeDir()
|
||||
baseDir := filepath.Join(homeDir, ".twitterxmediabatchdownloader")
|
||||
return filepath.Join(baseDir, getExecutableName())
|
||||
}
|
||||
|
||||
// getHashFilePath returns the path to the hash file for version checking
|
||||
func getHashFilePath() string {
|
||||
homeDir, _ := os.UserHomeDir()
|
||||
baseDir := filepath.Join(homeDir, ".twitterxmediabatchdownloader")
|
||||
return filepath.Join(baseDir, "extractor.sha256")
|
||||
}
|
||||
|
||||
// calculateHash calculates SHA256 hash of data
|
||||
func calculateHash(data []byte) string {
|
||||
hash := sha256.Sum256(data)
|
||||
return hex.EncodeToString(hash[:])
|
||||
}
|
||||
|
||||
// ensureExtractor ensures the extractor binary exists
|
||||
// Extracts from embedded binary if not present or if hash differs (update)
|
||||
func ensureExtractor() (string, error) {
|
||||
exePath := getExtractorPath()
|
||||
hashPath := getHashFilePath()
|
||||
baseDir := filepath.Dir(exePath)
|
||||
|
||||
// Create directory if not exists
|
||||
if err := os.MkdirAll(baseDir, 0755); err != nil {
|
||||
return "", fmt.Errorf("failed to create directory: %v", err)
|
||||
}
|
||||
|
||||
// Calculate hash of embedded binary
|
||||
embeddedHash := calculateHash(extractorBin)
|
||||
|
||||
// Check if binary and hash file exist
|
||||
if _, err := os.Stat(exePath); err == nil {
|
||||
// Binary exists - check hash
|
||||
if storedHash, err := os.ReadFile(hashPath); err == nil {
|
||||
if string(storedHash) == embeddedHash {
|
||||
return exePath, nil // Already extracted and up to date
|
||||
}
|
||||
}
|
||||
// Hash differs or missing - need to update
|
||||
os.Remove(exePath)
|
||||
}
|
||||
|
||||
// Extract binary
|
||||
if err := os.WriteFile(exePath, extractorBin, 0755); err != nil {
|
||||
return "", fmt.Errorf("failed to write extractor: %v", err)
|
||||
}
|
||||
|
||||
// Save hash for future comparison
|
||||
if err := os.WriteFile(hashPath, []byte(embeddedHash), 0644); err != nil {
|
||||
// Non-fatal - binary still works, just won't skip next time
|
||||
fmt.Printf("Warning: failed to save hash file: %v\n", err)
|
||||
}
|
||||
|
||||
return exePath, nil
|
||||
}
|
||||
|
||||
// ExtractTimeline extracts media from user timeline using the new CLI
|
||||
func ExtractTimeline(req TimelineRequest) (*TwitterResponse, error) {
|
||||
// Get or extract extractor binary (persistent, not temp)
|
||||
exePath, err := ensureExtractor()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Determine the right endpoint based on what user wants:
|
||||
// - Media (all/image/video/gif): Use /media endpoint - fastest and most reliable
|
||||
// - Text tweets: Use /tweets endpoint with --text-tweets
|
||||
// - With retweets: Use /tweets endpoint (retweets not available on /media)
|
||||
isTextOnly := req.MediaType == "text"
|
||||
wantsRetweets := req.Retweets
|
||||
|
||||
timelineType := req.TimelineType
|
||||
if timelineType == "" {
|
||||
if isTextOnly {
|
||||
// Text-only tweets need /tweets endpoint
|
||||
timelineType = "tweets"
|
||||
} else if wantsRetweets {
|
||||
// Retweets need /tweets endpoint (not available on /media)
|
||||
timelineType = "tweets"
|
||||
} else {
|
||||
// Default: /media endpoint - fastest for media-only fetch
|
||||
timelineType = "media"
|
||||
}
|
||||
}
|
||||
|
||||
url := buildTwitterURL(req.Username, timelineType)
|
||||
|
||||
// Build command arguments for new CLI format
|
||||
// Format: extractor.exe URL --auth-token TOKEN --json [options]
|
||||
args := []string{url}
|
||||
|
||||
// Add auth token
|
||||
if req.AuthToken != "" {
|
||||
args = append(args, "--auth-token", req.AuthToken)
|
||||
} else {
|
||||
args = append(args, "--guest")
|
||||
}
|
||||
|
||||
// Always request JSON output with metadata
|
||||
args = append(args, "--json", "--metadata")
|
||||
|
||||
// Add limit if specified
|
||||
if req.BatchSize > 0 {
|
||||
args = append(args, "--limit", fmt.Sprintf("%d", req.BatchSize))
|
||||
}
|
||||
|
||||
// Handle retweets - only relevant when using /tweets endpoint
|
||||
if timelineType == "tweets" || timelineType == "timeline" {
|
||||
if req.Retweets {
|
||||
args = append(args, "--retweets", "include")
|
||||
} else {
|
||||
args = append(args, "--retweets", "skip")
|
||||
}
|
||||
}
|
||||
|
||||
// Only add --text-tweets when explicitly requesting text content
|
||||
if isTextOnly {
|
||||
args = append(args, "--text-tweets")
|
||||
}
|
||||
|
||||
// Handle media type filter using --type parameter
|
||||
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")
|
||||
}
|
||||
}
|
||||
|
||||
// Add cursor for resume capability
|
||||
if req.Cursor != "" {
|
||||
args = append(args, "--cursor", req.Cursor)
|
||||
}
|
||||
|
||||
// Execute command with UTF-8 encoding
|
||||
cmd := exec.Command(exePath, args...)
|
||||
cmd.Env = append(os.Environ(),
|
||||
"PYTHONIOENCODING=utf-8",
|
||||
"PYTHONUTF8=1",
|
||||
)
|
||||
hideWindow(cmd) // Hide console window on Windows
|
||||
output, err := cmd.CombinedOutput()
|
||||
|
||||
// Ensure process is killed after completion
|
||||
if cmd.Process != nil {
|
||||
cmd.Process.Kill()
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
outputStr := string(output)
|
||||
errorMsg := parseExtractorError(outputStr, req.Username)
|
||||
return nil, fmt.Errorf("%s", errorMsg)
|
||||
}
|
||||
|
||||
// Find JSON in output (skip any info messages)
|
||||
jsonStr := extractJSON(string(output))
|
||||
if jsonStr == "" {
|
||||
outputStr := string(output)
|
||||
if strings.TrimSpace(outputStr) == "" {
|
||||
return nil, fmt.Errorf("empty_response: Extractor returned no data. The timeline may be empty or inaccessible")
|
||||
}
|
||||
return nil, fmt.Errorf("parse_error: Could not parse extractor output. Raw output: %s", outputStr)
|
||||
}
|
||||
|
||||
// Parse CLI response
|
||||
var cliResponse CLIResponse
|
||||
if err := json.Unmarshal([]byte(jsonStr), &cliResponse); err != nil {
|
||||
return nil, fmt.Errorf("json_error: Failed to parse JSON response: %v", err)
|
||||
}
|
||||
|
||||
// Convert to frontend format
|
||||
var timeline []TimelineEntry
|
||||
accountInfo := AccountInfo{
|
||||
Name: req.Username,
|
||||
Nick: req.Username,
|
||||
}
|
||||
|
||||
// Build a set of tweet IDs that have media
|
||||
mediaTweetIDs := make(map[int64]bool)
|
||||
for _, media := range cliResponse.Media {
|
||||
mediaTweetIDs[int64(media.TweetID)] = true
|
||||
}
|
||||
|
||||
// For bookmarks and likes, keep name as "bookmarks"/"likes" (not from author tweet)
|
||||
isBookmarks := req.TimelineType == "bookmarks"
|
||||
isLikes := req.TimelineType == "likes"
|
||||
if isBookmarks {
|
||||
accountInfo.Name = "bookmarks"
|
||||
accountInfo.Nick = "My Bookmarks"
|
||||
} else if isLikes {
|
||||
accountInfo.Name = "likes"
|
||||
accountInfo.Nick = "My Likes"
|
||||
}
|
||||
|
||||
if isTextOnly {
|
||||
// Text-only mode: get tweets from metadata that don't have media
|
||||
timeline = make([]TimelineEntry, 0)
|
||||
for _, meta := range cliResponse.Metadata {
|
||||
if !mediaTweetIDs[int64(meta.TweetID)] {
|
||||
timeline = append(timeline, convertMetadataToTimelineEntry(meta))
|
||||
}
|
||||
}
|
||||
|
||||
// Get account info from first media item if available, otherwise from metadata
|
||||
if !isBookmarks && !isLikes {
|
||||
if len(cliResponse.Media) > 0 {
|
||||
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 {
|
||||
// For bookmarks and likes, get other info from first media item if available
|
||||
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 {
|
||||
// Normal media items only (text tweets handled separately with "text" media type)
|
||||
timeline = make([]TimelineEntry, 0, len(cliResponse.Media))
|
||||
|
||||
// Add media items
|
||||
for _, media := range cliResponse.Media {
|
||||
timeline = append(timeline, convertToTimelineEntry(media))
|
||||
}
|
||||
|
||||
// Get account info from first media item
|
||||
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 {
|
||||
// Fallback: Text-only tweets (no media) - convert metadata to timeline entries
|
||||
timeline = make([]TimelineEntry, 0, len(cliResponse.Metadata))
|
||||
for _, meta := range cliResponse.Metadata {
|
||||
entry := TimelineEntry{
|
||||
URL: "", // No media URL for text tweets
|
||||
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)
|
||||
}
|
||||
// Get account info from first metadata
|
||||
if !isBookmarks && !isLikes {
|
||||
firstMeta := cliResponse.Metadata[0]
|
||||
accountInfo.Name = firstMeta.Author.Name
|
||||
accountInfo.Nick = firstMeta.Author.Nick
|
||||
}
|
||||
}
|
||||
|
||||
// Determine if there's more data to fetch
|
||||
hasMore := cliResponse.Cursor != "" && !cliResponse.Completed
|
||||
|
||||
response := &TwitterResponse{
|
||||
AccountInfo: accountInfo,
|
||||
TotalURLs: len(timeline),
|
||||
Timeline: timeline,
|
||||
Metadata: ExtractMetadata{
|
||||
NewEntries: len(timeline),
|
||||
Page: req.Page,
|
||||
BatchSize: req.BatchSize,
|
||||
HasMore: hasMore,
|
||||
Cursor: cliResponse.Cursor,
|
||||
Completed: cliResponse.Completed,
|
||||
},
|
||||
Cursor: cliResponse.Cursor,
|
||||
Completed: cliResponse.Completed,
|
||||
}
|
||||
|
||||
return response, nil
|
||||
}
|
||||
|
||||
// ExtractDateRange extracts media based on date range using the new CLI
|
||||
func ExtractDateRange(req DateRangeRequest) (*TwitterResponse, error) {
|
||||
// Get or extract extractor binary (persistent, not temp)
|
||||
exePath, err := ensureExtractor()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
mediaFilter := strings.ToLower(strings.TrimSpace(req.MediaFilter))
|
||||
url := buildSearchURL(req.Username, req.StartDate, req.EndDate, mediaFilter, req.Retweets)
|
||||
|
||||
// Build command arguments
|
||||
args := []string{url}
|
||||
|
||||
// Add auth token
|
||||
if req.AuthToken != "" {
|
||||
args = append(args, "--auth-token", req.AuthToken)
|
||||
} else {
|
||||
args = append(args, "--guest")
|
||||
}
|
||||
|
||||
// Always request JSON output with metadata
|
||||
args = append(args, "--json", "--metadata")
|
||||
|
||||
if req.Retweets {
|
||||
args = append(args, "--retweets", "include")
|
||||
} else {
|
||||
args = append(args, "--retweets", "skip")
|
||||
}
|
||||
|
||||
isTextOnly := mediaFilter == "text"
|
||||
if isTextOnly {
|
||||
args = append(args, "--text-tweets")
|
||||
}
|
||||
|
||||
// Execute command with UTF-8 encoding
|
||||
cmd := exec.Command(exePath, args...)
|
||||
cmd.Env = append(os.Environ(),
|
||||
"PYTHONIOENCODING=utf-8",
|
||||
"PYTHONUTF8=1",
|
||||
)
|
||||
hideWindow(cmd)
|
||||
output, err := cmd.CombinedOutput()
|
||||
|
||||
// Ensure process is killed after completion
|
||||
if cmd.Process != nil {
|
||||
cmd.Process.Kill()
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
outputStr := string(output)
|
||||
errorMsg := parseExtractorError(outputStr, req.Username)
|
||||
return nil, fmt.Errorf("%s", errorMsg)
|
||||
}
|
||||
|
||||
// Find JSON in output (skip any info messages)
|
||||
jsonStr := extractJSON(string(output))
|
||||
if jsonStr == "" {
|
||||
outputStr := string(output)
|
||||
if strings.TrimSpace(outputStr) == "" {
|
||||
return nil, fmt.Errorf("empty_response: Extractor returned no data. The timeline may be empty or inaccessible")
|
||||
}
|
||||
return nil, fmt.Errorf("parse_error: Could not parse extractor output. Raw output: %s", outputStr)
|
||||
}
|
||||
|
||||
// Parse CLI response
|
||||
var cliResponse CLIResponse
|
||||
if err := json.Unmarshal([]byte(jsonStr), &cliResponse); err != nil {
|
||||
return nil, fmt.Errorf("json_error: Failed to parse JSON response: %v", err)
|
||||
}
|
||||
|
||||
// Convert to frontend format
|
||||
mediaTweetIDs := make(map[int64]bool)
|
||||
for _, media := range cliResponse.Media {
|
||||
mediaTweetIDs[int64(media.TweetID)] = true
|
||||
}
|
||||
|
||||
timeline := make([]TimelineEntry, 0, len(cliResponse.Media)+len(cliResponse.Metadata))
|
||||
for _, media := range cliResponse.Media {
|
||||
timeline = append(timeline, convertToTimelineEntry(media))
|
||||
}
|
||||
|
||||
if isTextOnly {
|
||||
for _, meta := range cliResponse.Metadata {
|
||||
if !mediaTweetIDs[int64(meta.TweetID)] {
|
||||
timeline = append(timeline, convertMetadataToTimelineEntry(meta))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Build account info from first media item (has full user info)
|
||||
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
|
||||
}
|
||||
|
||||
// Determine if there's more data to fetch
|
||||
hasMore := cliResponse.Cursor != "" && !cliResponse.Completed
|
||||
|
||||
response := &TwitterResponse{
|
||||
AccountInfo: accountInfo,
|
||||
TotalURLs: len(timeline),
|
||||
Timeline: timeline,
|
||||
Metadata: ExtractMetadata{
|
||||
NewEntries: len(timeline),
|
||||
Page: 0,
|
||||
BatchSize: 0,
|
||||
HasMore: hasMore,
|
||||
Cursor: cliResponse.Cursor,
|
||||
Completed: cliResponse.Completed,
|
||||
},
|
||||
Cursor: cliResponse.Cursor,
|
||||
Completed: cliResponse.Completed,
|
||||
}
|
||||
|
||||
return response, nil
|
||||
}
|
||||
|
||||
// extractJSON finds and extracts JSON object from output string
|
||||
func extractJSON(output string) string {
|
||||
// Find the start of JSON object
|
||||
start := strings.Index(output, "{")
|
||||
if start == -1 {
|
||||
return ""
|
||||
}
|
||||
|
||||
// Find the matching closing brace
|
||||
depth := 0
|
||||
for i := start; i < len(output); i++ {
|
||||
if output[i] == '{' {
|
||||
depth++
|
||||
} else if output[i] == '}' {
|
||||
depth--
|
||||
if depth == 0 {
|
||||
return output[start : i+1]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
.DS_Store
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"$schema": "https://ui.shadcn.com/schema.json",
|
||||
"style": "new-york",
|
||||
"rsc": false,
|
||||
"tsx": true,
|
||||
"tailwind": {
|
||||
"config": "",
|
||||
"css": "src/index.css",
|
||||
"baseColor": "neutral",
|
||||
"cssVariables": true,
|
||||
"prefix": ""
|
||||
},
|
||||
"iconLibrary": "lucide",
|
||||
"aliases": {
|
||||
"components": "@/components",
|
||||
"utils": "@/lib/utils",
|
||||
"ui": "@/components/ui",
|
||||
"lib": "@/lib",
|
||||
"hooks": "@/hooks"
|
||||
},
|
||||
"registries": {}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import js from '@eslint/js'
|
||||
import globals from 'globals'
|
||||
import reactHooks from 'eslint-plugin-react-hooks'
|
||||
import reactRefresh from 'eslint-plugin-react-refresh'
|
||||
import tseslint from 'typescript-eslint'
|
||||
import { defineConfig, globalIgnores } from 'eslint/config'
|
||||
|
||||
export default defineConfig([
|
||||
globalIgnores(['dist']),
|
||||
{
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
extends: [
|
||||
js.configs.recommended,
|
||||
tseslint.configs.recommended,
|
||||
reactHooks.configs.flat.recommended,
|
||||
reactRefresh.configs.vite,
|
||||
],
|
||||
languageOptions: {
|
||||
ecmaVersion: 2020,
|
||||
globals: globals.browser,
|
||||
},
|
||||
},
|
||||
])
|
||||
@@ -0,0 +1,16 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/icon.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@300..800&family=Figtree:wght@300..900&family=Geist:wght@100..900&family=Google+Sans+Code:ital,wght@0,300..800;1,300..800&family=Google+Sans+Flex:opsz,wght@6..144,1..1000&family=Inter:wght@300..800&family=JetBrains+Mono:ital,wght@0,100..800;1,100..800&family=Manrope:wght@300..800&family=Noto+Sans:wght@100..900&family=Nunito+Sans:opsz,wght@6..12,200..1000&family=Outfit:wght@100..900&family=Plus+Jakarta+Sans:wght@300..800&family=Poppins:wght@300;400;500;600;700;800&family=Public+Sans:ital,wght@0,100..900;1,100..900&family=Raleway:wght@100..900&family=Roboto:wght@300;400;500;700;900&family=Space+Grotesk:wght@300..700&display=swap" rel="stylesheet">
|
||||
<title>Twitter/X Media Batch Downloader</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,55 @@
|
||||
{
|
||||
"name": "frontend",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc -b && vite build",
|
||||
"lint": "eslint .",
|
||||
"preview": "vite preview",
|
||||
"generate-icon": "node scripts/generate-icon.js",
|
||||
"postinstall": "node scripts/generate-icon.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"@radix-ui/react-accordion": "^1.2.12",
|
||||
"@radix-ui/react-checkbox": "^1.3.3",
|
||||
"@radix-ui/react-context-menu": "^2.2.16",
|
||||
"@radix-ui/react-dialog": "^1.1.15",
|
||||
"@radix-ui/react-dropdown-menu": "^2.1.16",
|
||||
"@radix-ui/react-label": "^2.1.8",
|
||||
"@radix-ui/react-progress": "^1.1.8",
|
||||
"@radix-ui/react-radio-group": "^1.3.8",
|
||||
"@radix-ui/react-select": "^2.2.6",
|
||||
"@radix-ui/react-slot": "^1.2.4",
|
||||
"@radix-ui/react-switch": "^1.2.6",
|
||||
"@radix-ui/react-tabs": "^1.1.13",
|
||||
"@radix-ui/react-tooltip": "^1.2.8",
|
||||
"@tailwindcss/vite": "^4.1.18",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"lucide-react": "^0.561.0",
|
||||
"next-themes": "^0.4.6",
|
||||
"react": "^19.2.3",
|
||||
"react-dom": "^19.2.3",
|
||||
"sonner": "^2.0.7",
|
||||
"tailwind-merge": "^3.4.0",
|
||||
"tailwindcss": "^4.1.18"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.39.2",
|
||||
"@types/node": "^25.0.2",
|
||||
"@types/react": "^19.2.7",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@vitejs/plugin-react": "^5.1.2",
|
||||
"eslint": "^9.39.2",
|
||||
"eslint-plugin-react-hooks": "^7.0.1",
|
||||
"eslint-plugin-react-refresh": "^0.4.25",
|
||||
"globals": "^16.5.0",
|
||||
"sharp": "^0.34.5",
|
||||
"tw-animate-css": "^1.4.0",
|
||||
"typescript": "~5.9.3",
|
||||
"typescript-eslint": "^8.50.0",
|
||||
"vite": "^7.3.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
fac81d3fc08563d82c20da44a49a8efa
|
||||
Generated
+3853
File diff suppressed because it is too large.
Load diff
@@ -1,11 +1,11 @@
|
||||
<?xml version="1.0" ?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1"
|
||||
id="Layer_1" width="512px" height="512px" viewBox="0 0 24 24" style="enable-background:new 0 0 24 24;"
|
||||
xml:space="preserve">
|
||||
<g fill="#1da0f1">
|
||||
<polygon
|
||||
points="12.153992,10.729553 8.088684,5.041199 5.92041,5.041199 10.956299,12.087097 11.59021,12.97345 15.900635,19.009583 18.068909,19.009583 12.785217,11.615906 " />
|
||||
<path
|
||||
d="M21.15979,1H2.84021C1.823853,1,1,1.823853,1,2.84021v18.31958C1,22.176147,1.823853,23,2.84021,23h18.31958 C22.176147,23,23,22.176147,23,21.15979V2.84021C23,1.823853,22.176147,1,21.15979,1z M15.235352,20l-4.362549-6.213013 L5.411438,20H4l6.246887-7.104675L4,4h4.764648l4.130127,5.881958L18.06958,4h1.411377l-5.95697,6.775635L20,20H15.235352z" />
|
||||
</g>
|
||||
</svg>
|
||||
<?xml version="1.0" ?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1"
|
||||
id="Layer_1" width="512px" height="512px" viewBox="0 0 24 24" style="enable-background:new 0 0 24 24;"
|
||||
xml:space="preserve">
|
||||
<g fill="#1da0f1">
|
||||
<polygon
|
||||
points="12.153992,10.729553 8.088684,5.041199 5.92041,5.041199 10.956299,12.087097 11.59021,12.97345 15.900635,19.009583 18.068909,19.009583 12.785217,11.615906 " />
|
||||
<path
|
||||
d="M21.15979,1H2.84021C1.823853,1,1,1.823853,1,2.84021v18.31958C1,22.176147,1.823853,23,2.84021,23h18.31958 C22.176147,23,23,22.176147,23,21.15979V2.84021C23,1.823853,22.176147,1,21.15979,1z M15.235352,20l-4.362549-6.213013 L5.411438,20H4l6.246887-7.104675L4,4h4.764648l4.130127,5.881958L18.06958,4h1.411377l-5.95697,6.775635L20,20H15.235352z" />
|
||||
</g>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 876 B After Width: | Height: | Size: 865 B |
@@ -0,0 +1,33 @@
|
||||
import sharp from 'sharp';
|
||||
import { readFileSync, mkdirSync } from 'fs';
|
||||
import { dirname, join } from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
const rootDir = join(__dirname, '..', '..');
|
||||
|
||||
const svgPath = join(rootDir, 'frontend', 'public', 'icon.svg');
|
||||
const outputPath = join(rootDir, 'build', 'appicon.png');
|
||||
|
||||
async function generateIcon() {
|
||||
try {
|
||||
// Ensure build directory exists
|
||||
mkdirSync(join(rootDir, 'build'), { recursive: true });
|
||||
|
||||
// Read SVG
|
||||
const svgBuffer = readFileSync(svgPath);
|
||||
|
||||
// Convert SVG to PNG (1024x1024 for Wails)
|
||||
await sharp(svgBuffer)
|
||||
.resize(1024, 1024)
|
||||
.png()
|
||||
.toFile(outputPath);
|
||||
|
||||
console.log('✓ Icon generated:', outputPath);
|
||||
} catch (error) {
|
||||
console.error('✗ Failed to generate icon:', error.message);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
generateIcon();
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,111 @@
|
||||
import { useState, useEffect, useRef } from "react";
|
||||
import { Trash2, Copy, Check } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { logger, type LogEntry } from "@/lib/logger";
|
||||
|
||||
const levelColors: Record<string, string> = {
|
||||
info: "text-blue-500",
|
||||
success: "text-green-500",
|
||||
warning: "text-yellow-500",
|
||||
error: "text-red-500",
|
||||
debug: "text-gray-500",
|
||||
};
|
||||
|
||||
function formatTime(date: Date): string {
|
||||
return date.toLocaleTimeString("en-US", {
|
||||
hour12: false,
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
second: "2-digit",
|
||||
});
|
||||
}
|
||||
|
||||
export function DebugLoggerPage() {
|
||||
const [logs, setLogs] = useState<LogEntry[]>([]);
|
||||
const [copied, setCopied] = useState(false);
|
||||
const scrollRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const unsubscribe = logger.subscribe(() => {
|
||||
setLogs(logger.getLogs());
|
||||
});
|
||||
setLogs(logger.getLogs());
|
||||
return () => {
|
||||
unsubscribe();
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (scrollRef.current) {
|
||||
scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
|
||||
}
|
||||
}, [logs]);
|
||||
|
||||
const handleClear = () => {
|
||||
logger.clear();
|
||||
};
|
||||
|
||||
const handleCopy = async () => {
|
||||
const logText = logs
|
||||
.map((log) => `[${formatTime(log.timestamp)}] [${log.level}] ${log.message}`)
|
||||
.join("\n");
|
||||
|
||||
try {
|
||||
await navigator.clipboard.writeText(logText);
|
||||
setCopied(true);
|
||||
setTimeout(() => setCopied(false), 500);
|
||||
} catch (err) {
|
||||
console.error("Failed to copy logs:", err);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<h1 className="text-2xl font-bold">Debug Logs</h1>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleCopy}
|
||||
disabled={logs.length === 0}
|
||||
className="gap-1.5"
|
||||
>
|
||||
{copied ? <Check className="h-4 w-4" /> : <Copy className="h-4 w-4" />}
|
||||
Copy
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleClear}
|
||||
className="gap-1.5"
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
Clear
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
ref={scrollRef}
|
||||
className="h-[calc(100vh-220px)] overflow-y-auto bg-muted/50 rounded-md p-3 font-mono text-xs"
|
||||
>
|
||||
{logs.length === 0 ? (
|
||||
<p className="text-muted-foreground lowercase">no logs yet...</p>
|
||||
) : (
|
||||
logs.map((log, i) => (
|
||||
<div key={i} className="flex gap-2 py-0.5">
|
||||
<span className="text-muted-foreground shrink-0">
|
||||
[{formatTime(log.timestamp)}]
|
||||
</span>
|
||||
<span className={`shrink-0 w-16 ${levelColors[log.level]}`}>
|
||||
[{log.level}]
|
||||
</span>
|
||||
<span className="break-all">{log.message}</span>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { X, User } from "lucide-react";
|
||||
|
||||
export interface HistoryItem {
|
||||
id: string;
|
||||
username: string;
|
||||
name: string;
|
||||
image: string;
|
||||
mediaCount: number;
|
||||
timestamp: number;
|
||||
}
|
||||
|
||||
interface FetchHistoryProps {
|
||||
history: HistoryItem[];
|
||||
onSelect: (item: HistoryItem) => void;
|
||||
onRemove: (id: string) => void;
|
||||
}
|
||||
|
||||
export function FetchHistory({ history, onSelect, onRemove }: FetchHistoryProps) {
|
||||
if (history.length === 0) return null;
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<p className="text-sm text-muted-foreground">Recent Fetches</p>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{history.map((item) => (
|
||||
<div
|
||||
key={item.id}
|
||||
className="flex items-center gap-2 px-3 py-1.5 bg-muted/50 rounded-full hover:bg-muted transition-colors group cursor-pointer"
|
||||
onClick={() => onSelect(item)}
|
||||
>
|
||||
{item.image ? (
|
||||
<img
|
||||
src={item.image}
|
||||
alt={item.name}
|
||||
className="w-5 h-5 rounded-full"
|
||||
/>
|
||||
) : (
|
||||
<User className="w-5 h-5 text-muted-foreground" />
|
||||
)}
|
||||
<span className="text-sm">@{item.username}</span>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-4 w-4 opacity-0 group-hover:opacity-100 transition-opacity"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onRemove(item.id);
|
||||
}}
|
||||
>
|
||||
<X className="h-3 w-3" />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipTrigger,
|
||||
} from "@/components/ui/tooltip";
|
||||
import { openExternal } from "@/lib/utils";
|
||||
import { formatRelativeTime } from "@/lib/relative-time";
|
||||
|
||||
interface HeaderProps {
|
||||
version: string;
|
||||
hasUpdate: boolean;
|
||||
releaseDate?: string | null;
|
||||
}
|
||||
|
||||
export function Header({ version, hasUpdate, releaseDate }: HeaderProps) {
|
||||
return (
|
||||
<div className="relative">
|
||||
<div className="text-center space-y-2">
|
||||
<div className="flex items-center justify-center gap-3">
|
||||
<img
|
||||
src="/icon.svg"
|
||||
alt="Twitter/X Media Batch Downloader"
|
||||
className="w-12 h-12 cursor-pointer"
|
||||
onClick={() => window.location.reload()}
|
||||
/>
|
||||
<h1
|
||||
className="text-3xl font-bold cursor-pointer"
|
||||
onClick={() => window.location.reload()}
|
||||
>
|
||||
Twitter/X Media Batch Downloader
|
||||
</h1>
|
||||
<div className="relative">
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Badge variant="default" asChild>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => openExternal("https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases")}
|
||||
className="cursor-pointer hover:opacity-80 transition-opacity"
|
||||
>
|
||||
v{version}
|
||||
</button>
|
||||
</Badge>
|
||||
</TooltipTrigger>
|
||||
{hasUpdate && releaseDate && (
|
||||
<TooltipContent>
|
||||
<p>{formatRelativeTime(releaseDate)}</p>
|
||||
</TooltipContent>
|
||||
)}
|
||||
</Tooltip>
|
||||
{hasUpdate && (
|
||||
<span className="absolute -top-1 -right-1 flex h-3 w-3">
|
||||
<span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-green-400 opacity-75"></span>
|
||||
<span className="relative inline-flex rounded-full h-3 w-3 bg-green-500"></span>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,856 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { InputWithContext } from "@/components/ui/input-with-context";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import {
|
||||
XCircle,
|
||||
Calendar,
|
||||
StopCircle,
|
||||
Globe,
|
||||
Lock,
|
||||
Bookmark,
|
||||
Heart,
|
||||
Key,
|
||||
Eye,
|
||||
EyeOff,
|
||||
ChevronDown,
|
||||
ChevronUp,
|
||||
Info,
|
||||
RotateCcw,
|
||||
Trash2,
|
||||
Clock,
|
||||
CloudDownload,
|
||||
User,
|
||||
Users,
|
||||
FileText,
|
||||
Hourglass,
|
||||
CheckCircle,
|
||||
AlertCircle,
|
||||
} from "lucide-react";
|
||||
import { Spinner } from "@/components/ui/spinner";
|
||||
|
||||
function formatNumberWithComma(num: number): string {
|
||||
return num.toLocaleString();
|
||||
}
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipTrigger,
|
||||
} from "@/components/ui/tooltip";
|
||||
import { Settings as SettingsIcon } from "lucide-react";
|
||||
import { FetchHistory } from "@/components/FetchHistory";
|
||||
import type { HistoryItem } from "@/components/FetchHistory";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export type FetchMode = "public" | "private";
|
||||
export type PrivateType = "bookmarks" | "likes";
|
||||
export type FetchType = "single" | "multiple";
|
||||
|
||||
// Local storage keys for auth tokens
|
||||
const PUBLIC_AUTH_TOKEN_KEY = "twitter_public_auth_token";
|
||||
const PRIVATE_AUTH_TOKEN_KEY = "twitter_private_auth_token";
|
||||
|
||||
export interface MultipleAccount {
|
||||
id: string;
|
||||
username: string;
|
||||
status: "pending" | "fetching" | "completed" | "incomplete" | "failed";
|
||||
accountInfo?: {
|
||||
name: string;
|
||||
nick: string;
|
||||
profile_image: string;
|
||||
};
|
||||
mediaCount: number;
|
||||
previousMediaCount: number;
|
||||
elapsedTime: number;
|
||||
remainingTime: number | null;
|
||||
error?: string;
|
||||
showDiff?: boolean;
|
||||
cursor?: string;
|
||||
}
|
||||
|
||||
interface SearchBarProps {
|
||||
username: string;
|
||||
loading: boolean;
|
||||
onUsernameChange: (username: string) => void;
|
||||
onFetch: (
|
||||
useDateRange: boolean,
|
||||
startDate?: string,
|
||||
endDate?: string,
|
||||
mediaType?: string,
|
||||
retweets?: boolean,
|
||||
mode?: FetchMode,
|
||||
privateType?: PrivateType,
|
||||
authToken?: string,
|
||||
isResume?: boolean
|
||||
) => void;
|
||||
onStopFetch: () => void;
|
||||
onResume?: (authToken: string, mediaType?: string, retweets?: boolean) => void;
|
||||
onClearResume?: () => void;
|
||||
resumeInfo?: { canResume: boolean; mediaCount: number } | null;
|
||||
history: HistoryItem[];
|
||||
onHistorySelect: (item: HistoryItem) => void;
|
||||
onHistoryRemove: (id: string) => void;
|
||||
hasResult: boolean;
|
||||
elapsedTime?: number;
|
||||
remainingTime?: number | null;
|
||||
// Multiple mode props
|
||||
fetchType?: FetchType;
|
||||
onFetchTypeChange?: (type: FetchType) => void;
|
||||
multipleAccounts?: MultipleAccount[];
|
||||
onImportFile?: () => void;
|
||||
onFetchAll?: () => void;
|
||||
onStopAll?: () => void;
|
||||
onStopAccount?: (accountId: string) => void;
|
||||
onRetryAccount?: (accountId: string) => void;
|
||||
isFetchingAll?: boolean;
|
||||
// Mode control
|
||||
mode?: FetchMode;
|
||||
privateType?: PrivateType;
|
||||
onModeChange?: (mode: FetchMode, privateType?: PrivateType) => void;
|
||||
}
|
||||
|
||||
export function SearchBar({
|
||||
username,
|
||||
loading,
|
||||
onUsernameChange,
|
||||
onFetch,
|
||||
onStopFetch,
|
||||
onResume,
|
||||
onClearResume,
|
||||
resumeInfo,
|
||||
history,
|
||||
onHistorySelect,
|
||||
onHistoryRemove,
|
||||
hasResult,
|
||||
elapsedTime = 0,
|
||||
remainingTime = null,
|
||||
fetchType = "single",
|
||||
onFetchTypeChange,
|
||||
multipleAccounts = [],
|
||||
onImportFile,
|
||||
onFetchAll,
|
||||
onStopAll,
|
||||
onStopAccount,
|
||||
onRetryAccount,
|
||||
isFetchingAll = false,
|
||||
mode: externalMode,
|
||||
privateType: externalPrivateType,
|
||||
onModeChange,
|
||||
}: SearchBarProps) {
|
||||
const [useDateRange, setUseDateRange] = useState(false);
|
||||
const [startDate, setStartDate] = useState("");
|
||||
const [endDate, setEndDate] = useState("");
|
||||
const [mediaType, setMediaType] = useState("all");
|
||||
const [retweets, setRetweets] = useState(false);
|
||||
const [mode, setMode] = useState<FetchMode>(externalMode || "public");
|
||||
const [privateType, setPrivateType] = useState<PrivateType>(externalPrivateType || "bookmarks");
|
||||
|
||||
// Sync with external mode if provided
|
||||
useEffect(() => {
|
||||
if (externalMode !== undefined) {
|
||||
setMode(externalMode);
|
||||
}
|
||||
}, [externalMode]);
|
||||
|
||||
useEffect(() => {
|
||||
if (externalPrivateType !== undefined) {
|
||||
setPrivateType(externalPrivateType);
|
||||
}
|
||||
}, [externalPrivateType]);
|
||||
const [showAuthInput, setShowAuthInput] = useState(false);
|
||||
const [showAdvanced, setShowAdvanced] = useState(false);
|
||||
|
||||
// Separate auth tokens for public and private modes
|
||||
const [publicAuthToken, setPublicAuthToken] = useState("");
|
||||
const [privateAuthToken, setPrivateAuthToken] = useState("");
|
||||
const [showPublicToken, setShowPublicToken] = useState(false);
|
||||
const [showPrivateToken, setShowPrivateToken] = useState(false);
|
||||
|
||||
// Load saved auth tokens on mount
|
||||
useEffect(() => {
|
||||
const savedPublicToken = localStorage.getItem(PUBLIC_AUTH_TOKEN_KEY) || "";
|
||||
const savedPrivateToken = localStorage.getItem(PRIVATE_AUTH_TOKEN_KEY) || "";
|
||||
setPublicAuthToken(savedPublicToken);
|
||||
setPrivateAuthToken(savedPrivateToken);
|
||||
}, []);
|
||||
|
||||
// Save auth tokens when they change
|
||||
const handlePublicTokenChange = (value: string) => {
|
||||
setPublicAuthToken(value);
|
||||
localStorage.setItem(PUBLIC_AUTH_TOKEN_KEY, value);
|
||||
};
|
||||
|
||||
const handlePrivateTokenChange = (value: string) => {
|
||||
setPrivateAuthToken(value);
|
||||
localStorage.setItem(PRIVATE_AUTH_TOKEN_KEY, value);
|
||||
};
|
||||
|
||||
const handleFetch = () => {
|
||||
const authToken = mode === "public" ? publicAuthToken : privateAuthToken;
|
||||
onFetch(useDateRange, startDate, endDate, mediaType, retweets, mode, privateType, authToken, false);
|
||||
};
|
||||
|
||||
const handleResume = () => {
|
||||
const authToken = mode === "public" ? publicAuthToken : privateAuthToken;
|
||||
if (onResume) {
|
||||
onResume(authToken, mediaType, retweets);
|
||||
}
|
||||
};
|
||||
|
||||
const currentAuthToken = mode === "public" ? publicAuthToken : privateAuthToken;
|
||||
const hasAuthToken = currentAuthToken.trim().length > 0;
|
||||
// Likes needs username (URL is /username/likes), bookmarks doesn't
|
||||
const isLikesMode = mode === "private" && privateType === "likes";
|
||||
const isBookmarksMode = mode === "private" && privateType === "bookmarks";
|
||||
|
||||
const formatTime = (seconds: number): string => {
|
||||
const mins = Math.floor(seconds / 60);
|
||||
const secs = seconds % 60;
|
||||
return `${mins}:${String(secs).padStart(2, "0")}`;
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
{/* Fetch Type and Mode Toggle (Single/Multiple and Public/Private in one line) */}
|
||||
<div className="flex justify-center gap-2">
|
||||
<div className="flex gap-0.5 p-0.5 bg-muted rounded-lg w-fit">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onFetchTypeChange?.("single")}
|
||||
className={cn(
|
||||
"flex items-center gap-1 px-2 py-1 rounded-md text-xs font-medium transition-all cursor-pointer",
|
||||
fetchType === "single"
|
||||
? "bg-background text-foreground shadow-sm"
|
||||
: "text-muted-foreground hover:text-foreground"
|
||||
)}
|
||||
>
|
||||
<User className="h-3 w-3" />
|
||||
Single
|
||||
</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"
|
||||
? "bg-background text-foreground shadow-sm"
|
||||
: "text-muted-foreground hover:text-foreground"
|
||||
)}
|
||||
>
|
||||
<Users className="h-3 w-3" />
|
||||
Multiple
|
||||
</button>
|
||||
</div>
|
||||
{fetchType === "single" && (
|
||||
<div className="flex gap-0.5 p-0.5 bg-muted rounded-lg w-fit">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setMode("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"
|
||||
? "bg-background text-foreground shadow-sm"
|
||||
: "text-muted-foreground hover:text-foreground"
|
||||
)}
|
||||
>
|
||||
<Globe className="h-3 w-3" />
|
||||
Public
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setMode("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"
|
||||
? "bg-background text-foreground shadow-sm"
|
||||
: "text-muted-foreground hover:text-foreground"
|
||||
)}
|
||||
>
|
||||
<Lock className="h-3 w-3" />
|
||||
Private
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Multiple Mode UI - Import and Fetch All Buttons */}
|
||||
{fetchType === "multiple" && (
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Label htmlFor="import-txt" className="text-sm">
|
||||
Import Accounts
|
||||
</Label>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Info className="h-4 w-4 text-muted-foreground cursor-help" />
|
||||
</TooltipTrigger>
|
||||
<TooltipContent className="max-w-xs">
|
||||
<p className="text-sm">
|
||||
One username per line, example:
|
||||
<br />
|
||||
<span className="font-mono text-xs">masteraoko</span>
|
||||
<br />
|
||||
<span className="font-mono text-xs">xbatchdemo</span>
|
||||
<br />
|
||||
<span className="font-mono text-xs">takomayuyi</span>
|
||||
</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
id="import-txt"
|
||||
variant="outline"
|
||||
onClick={onImportFile}
|
||||
className="flex items-center gap-2 flex-1"
|
||||
>
|
||||
<FileText className="h-4 w-4" />
|
||||
Import TXT File
|
||||
</Button>
|
||||
<Button
|
||||
variant="default"
|
||||
onClick={onFetchAll}
|
||||
disabled={multipleAccounts.length === 0 || isFetchingAll}
|
||||
className="flex items-center gap-2 flex-1"
|
||||
>
|
||||
{isFetchingAll ? (
|
||||
<>
|
||||
<Spinner />
|
||||
Fetching All...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<CloudDownload className="h-4 w-4" />
|
||||
Fetch All
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
{isFetchingAll && (
|
||||
<Button
|
||||
variant="destructive"
|
||||
onClick={onStopAll}
|
||||
className="flex items-center gap-2"
|
||||
>
|
||||
<StopCircle className="h-4 w-4" />
|
||||
Stop All
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Username Input - for public mode and likes mode, only in single mode */}
|
||||
{fetchType === "single" && (mode === "public" || isLikesMode) && (
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="username">
|
||||
{isLikesMode ? "Your Username" : "Username"}
|
||||
</Label>
|
||||
|
||||
<div className="flex gap-2">
|
||||
<div className="relative flex-1">
|
||||
<InputWithContext
|
||||
id="username"
|
||||
placeholder={
|
||||
isLikesMode
|
||||
? "your_username or @your_username or https://x.com/your_username"
|
||||
: "masteraoko or @masteraoko or https://x.com/masteraoko"
|
||||
}
|
||||
value={username}
|
||||
onChange={(e) => onUsernameChange(e.target.value)}
|
||||
onKeyDown={(e) => e.key === "Enter" && handleFetch()}
|
||||
className="pr-8"
|
||||
/>
|
||||
{username && (
|
||||
<button
|
||||
type="button"
|
||||
className="absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground transition-colors cursor-pointer"
|
||||
onClick={() => onUsernameChange("")}
|
||||
>
|
||||
<XCircle className="h-4 w-4" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{loading && (
|
||||
<>
|
||||
{/* Timer Display */}
|
||||
{(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-[85px]">
|
||||
<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>
|
||||
</>
|
||||
)}
|
||||
{/* Resume button - show when there's resumable data */}
|
||||
{!loading && resumeInfo?.canResume && mode === "public" && (
|
||||
<>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button variant="outline" size="icon" onClick={onClearResume}>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>Clear resume data</TooltipContent>
|
||||
</Tooltip>
|
||||
<Button variant="secondary" onClick={handleResume} disabled={!hasAuthToken}>
|
||||
<RotateCcw className="h-4 w-4" />
|
||||
Resume ({resumeInfo.mediaCount})
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
<Button onClick={handleFetch} disabled={loading || !hasAuthToken}>
|
||||
{loading ? (
|
||||
<>
|
||||
<Spinner />
|
||||
Fetching...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
{isLikesMode ? <Heart className="h-4 w-4" /> : <CloudDownload className="h-4 w-4" />}
|
||||
{isLikesMode ? "Fetch Likes" : "Fetch"}
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Auth Token & Advanced Settings Row */}
|
||||
<div className="flex items-center gap-2">
|
||||
{/* Auth Token Button */}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowAuthInput(!showAuthInput)}
|
||||
className="flex items-center gap-2 px-4 py-2 border rounded-lg text-sm font-medium hover:bg-muted/50 transition-colors cursor-pointer"
|
||||
>
|
||||
<Key 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>
|
||||
|
||||
{/* Advanced Settings 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"
|
||||
>
|
||||
<SettingsIcon className="h-4 w-4" />
|
||||
Advanced Settings
|
||||
{showAdvanced ? <ChevronUp className="h-4 w-4" /> : <ChevronDown className="h-4 w-4" />}
|
||||
</button>
|
||||
|
||||
{/* Private Mode Options - My Bookmarks / My Likes */}
|
||||
{mode === "private" && fetchType === "single" && (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setPrivateType("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"
|
||||
? "border-primary bg-primary/10 text-primary"
|
||||
: "border-border hover:border-primary/50"
|
||||
)}
|
||||
>
|
||||
<Bookmark className="h-4 w-4" />
|
||||
My Bookmarks
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setPrivateType("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"
|
||||
? "border-primary bg-primary/10 text-primary"
|
||||
: "border-border hover:border-primary/50"
|
||||
)}
|
||||
>
|
||||
<Heart className="h-4 w-4" />
|
||||
My Likes
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Bookmarks Mode - Fetch button inline */}
|
||||
{isBookmarksMode && (
|
||||
<div className="flex items-center gap-2 ml-auto">
|
||||
{loading && (
|
||||
<>
|
||||
{/* Timer Display */}
|
||||
{(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-[85px]">
|
||||
<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 onClick={handleFetch} disabled={loading || !hasAuthToken}>
|
||||
{loading ? (
|
||||
<>
|
||||
<Spinner />
|
||||
Fetching...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Bookmark className="h-4 w-4" />
|
||||
Fetch Bookmarks
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Auth Token Input (collapsible) */}
|
||||
{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>
|
||||
)}
|
||||
|
||||
{/* Advanced Settings (collapsible) */}
|
||||
{showAdvanced && (
|
||||
<div className="p-3 border rounded-lg bg-muted/30 space-y-3">
|
||||
{/* Options Row */}
|
||||
<div className="flex items-center gap-4">
|
||||
{/* Media Type */}
|
||||
<div className="flex items-center gap-2">
|
||||
<Label htmlFor="media-type" className="text-sm">
|
||||
Media Type
|
||||
</Label>
|
||||
<Select value={mediaType} onValueChange={setMediaType}>
|
||||
<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>
|
||||
|
||||
{/* Include Retweets */}
|
||||
<div className="flex items-center gap-2">
|
||||
<Checkbox
|
||||
id="retweets"
|
||||
checked={retweets}
|
||||
onCheckedChange={(checked) => setRetweets(checked as boolean)}
|
||||
className="bg-background"
|
||||
/>
|
||||
<Label htmlFor="retweets" className="text-sm cursor-pointer">
|
||||
Include Retweets
|
||||
</Label>
|
||||
</div>
|
||||
|
||||
{/* Date Range Toggle - only for public mode */}
|
||||
{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>
|
||||
|
||||
{/* Date Range Inputs - inline */}
|
||||
{useDateRange && (
|
||||
<>
|
||||
<InputWithContext
|
||||
id="start-date"
|
||||
type="date"
|
||||
value={startDate}
|
||||
onChange={(e) => setStartDate(e.target.value)}
|
||||
className="w-[140px] h-8 bg-background"
|
||||
/>
|
||||
<span className="text-sm text-muted-foreground">-</span>
|
||||
<InputWithContext
|
||||
id="end-date"
|
||||
type="date"
|
||||
value={endDate}
|
||||
onChange={(e) => setEndDate(e.target.value)}
|
||||
className="w-[140px] h-8 bg-background"
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Statistics for Multiple Fetch - below auth token and advanced settings */}
|
||||
{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-2">
|
||||
<CheckCircle className="h-4 w-4 text-green-600 dark:text-green-400" />
|
||||
<span className="text-muted-foreground">Completed:</span>
|
||||
<span className="font-medium">
|
||||
{formatNumberWithComma(multipleAccounts.filter((acc) => acc.status === "completed").length)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<AlertCircle className="h-4 w-4 text-yellow-600 dark:text-yellow-400" />
|
||||
<span className="text-muted-foreground">Incomplete:</span>
|
||||
<span className="font-medium">
|
||||
{formatNumberWithComma(multipleAccounts.filter((acc) => acc.status === "incomplete").length)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<XCircle className="h-4 w-4 text-red-600 dark:text-red-400" />
|
||||
<span className="text-muted-foreground">Failed:</span>
|
||||
<span className="font-medium">
|
||||
{formatNumberWithComma(multipleAccounts.filter((acc) => acc.status === "failed").length)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 ml-auto">
|
||||
<span className="text-muted-foreground">Total:</span>
|
||||
<span className="font-medium">
|
||||
{formatNumberWithComma(multipleAccounts.filter((acc) =>
|
||||
acc.status === "completed" || acc.status === "incomplete" || acc.status === "failed"
|
||||
).length)}/{formatNumberWithComma(multipleAccounts.length)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Account List - below auth token and advanced settings */}
|
||||
{fetchType === "multiple" && multipleAccounts.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
<p className="text-sm text-muted-foreground">Accounts to Fetch ({formatNumberWithComma(multipleAccounts.length)})</p>
|
||||
<div className="space-y-2 max-h-[400px] overflow-y-auto">
|
||||
{multipleAccounts.map((account) => (
|
||||
<div
|
||||
key={account.id}
|
||||
className="p-3 border rounded-lg bg-card"
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
{account.accountInfo ? (
|
||||
<img
|
||||
src={account.accountInfo.profile_image}
|
||||
alt={account.accountInfo.nick}
|
||||
className="w-10 h-10 rounded-full"
|
||||
/>
|
||||
) : (
|
||||
<div className="w-10 h-10 rounded-full bg-muted flex items-center justify-center">
|
||||
<User className="h-5 w-5 text-muted-foreground" />
|
||||
</div>
|
||||
)}
|
||||
<div className="flex-1 min-w-0">
|
||||
{account.accountInfo ? (
|
||||
<>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="font-medium">{account.accountInfo.nick}</span>
|
||||
<span className="text-sm text-muted-foreground">@{account.accountInfo.name}</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 mt-1">
|
||||
<span className="text-sm text-muted-foreground">
|
||||
<span className="text-primary">{account.mediaCount.toLocaleString()}</span> items found
|
||||
</span>
|
||||
{account.showDiff && account.previousMediaCount > 0 && account.mediaCount > account.previousMediaCount && (
|
||||
<span className="text-sm text-green-600 dark:text-green-400 font-medium">
|
||||
+{account.mediaCount - account.previousMediaCount}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="font-medium">@{account.username}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{account.status === "fetching" && (
|
||||
<>
|
||||
<div className="flex items-center gap-1.5 px-3 py-1.5 border rounded-md bg-muted/50 text-sm w-[85px]">
|
||||
<Clock className="h-3.5 w-3.5 text-muted-foreground shrink-0" />
|
||||
<span className="font-mono">
|
||||
{account.remainingTime !== null && account.remainingTime >= 0
|
||||
? formatTime(account.remainingTime)
|
||||
: formatTime(account.elapsedTime)}
|
||||
</span>
|
||||
</div>
|
||||
<Button
|
||||
variant="destructive"
|
||||
onClick={() => onStopAccount?.(account.id)}
|
||||
className="flex items-center gap-2"
|
||||
>
|
||||
<StopCircle className="h-4 w-4" />
|
||||
Stop
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
{account.status === "pending" && (
|
||||
<span className="text-xs px-2 py-1 bg-gray-500/20 text-gray-600 dark:text-gray-400 rounded flex items-center gap-1.5">
|
||||
<Hourglass className="h-3 w-3" />
|
||||
Pending
|
||||
</span>
|
||||
)}
|
||||
{account.status === "completed" && (
|
||||
<span className="text-xs px-2 py-1 bg-green-500/20 text-green-600 dark:text-green-400 rounded flex items-center gap-1.5">
|
||||
<CheckCircle className="h-3 w-3" />
|
||||
Completed
|
||||
</span>
|
||||
)}
|
||||
{account.status === "incomplete" && (
|
||||
<>
|
||||
<span className="text-xs px-2 py-1 bg-yellow-500/20 text-yellow-600 dark:text-yellow-400 rounded flex items-center gap-1.5">
|
||||
<AlertCircle className="h-3 w-3" />
|
||||
Incomplete
|
||||
</span>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => onRetryAccount?.(account.id)}
|
||||
disabled={isFetchingAll}
|
||||
className="flex items-center gap-2"
|
||||
>
|
||||
<RotateCcw className="h-3.5 w-3.5" />
|
||||
Retry
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
{account.status === "failed" && (
|
||||
<>
|
||||
<span className="text-xs px-2 py-1 bg-red-500/20 text-red-600 dark:text-red-400 rounded flex items-center gap-1.5">
|
||||
<XCircle className="h-3 w-3" />
|
||||
Failed
|
||||
</span>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => onRetryAccount?.(account.id)}
|
||||
disabled={isFetchingAll}
|
||||
className="flex items-center gap-2"
|
||||
>
|
||||
<RotateCcw className="h-3.5 w-3.5" />
|
||||
Retry
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!hasResult && mode === "public" && fetchType === "single" && (
|
||||
<FetchHistory
|
||||
history={history}
|
||||
onSelect={onHistorySelect}
|
||||
onRemove={onHistoryRemove}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,437 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { InputWithContext } from "@/components/ui/input-with-context";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import { FolderOpen, Save, RotateCcw, Info, Download, Check } from "lucide-react";
|
||||
import { Spinner } from "@/components/ui/spinner";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { getSettings, getSettingsWithDefaults, saveSettings, resetToDefaultSettings, applyThemeMode, applyFont, FONT_OPTIONS, type Settings as SettingsType, type FontFamily, type GifQuality, type GifResolution } from "@/lib/settings";
|
||||
import { themes, applyTheme } from "@/lib/themes";
|
||||
import { SelectFolder, IsFFmpegInstalled, DownloadFFmpeg, IsExifToolInstalled, DownloadExifTool } from "../../wailsjs/go/main/App";
|
||||
import { toastWithSound as toast } from "@/lib/toast-with-sound";
|
||||
|
||||
export function SettingsPage() {
|
||||
const [savedSettings, setSavedSettings] = useState<SettingsType>(getSettings());
|
||||
const [tempSettings, setTempSettings] = useState<SettingsType>(savedSettings);
|
||||
const [isDark, setIsDark] = useState(document.documentElement.classList.contains('dark'));
|
||||
const [ffmpegInstalled, setFfmpegInstalled] = useState(false);
|
||||
const [downloadingFFmpeg, setDownloadingFFmpeg] = useState(false);
|
||||
const [exiftoolInstalled, setExiftoolInstalled] = useState(false);
|
||||
const [downloadingExifTool, setDownloadingExifTool] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
applyThemeMode(savedSettings.themeMode);
|
||||
applyTheme(savedSettings.theme);
|
||||
|
||||
const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");
|
||||
const handleChange = () => {
|
||||
if (savedSettings.themeMode === "auto") {
|
||||
applyThemeMode("auto");
|
||||
applyTheme(savedSettings.theme);
|
||||
}
|
||||
};
|
||||
|
||||
mediaQuery.addEventListener("change", handleChange);
|
||||
return () => mediaQuery.removeEventListener("change", handleChange);
|
||||
}, [savedSettings.themeMode, savedSettings.theme]);
|
||||
|
||||
useEffect(() => {
|
||||
applyThemeMode(tempSettings.themeMode);
|
||||
applyTheme(tempSettings.theme);
|
||||
applyFont(tempSettings.fontFamily);
|
||||
setTimeout(() => {
|
||||
setIsDark(document.documentElement.classList.contains('dark'));
|
||||
}, 0);
|
||||
}, [tempSettings.themeMode, tempSettings.theme, tempSettings.fontFamily]);
|
||||
|
||||
useEffect(() => {
|
||||
const loadDefaults = async () => {
|
||||
if (!savedSettings.downloadPath) {
|
||||
const settingsWithDefaults = await getSettingsWithDefaults();
|
||||
setSavedSettings(settingsWithDefaults);
|
||||
setTempSettings(settingsWithDefaults);
|
||||
}
|
||||
};
|
||||
loadDefaults();
|
||||
|
||||
// Check FFmpeg and ExifTool status
|
||||
IsFFmpegInstalled().then(setFfmpegInstalled);
|
||||
IsExifToolInstalled().then(setExiftoolInstalled);
|
||||
}, []);
|
||||
|
||||
const handleSave = () => {
|
||||
saveSettings(tempSettings);
|
||||
setSavedSettings(tempSettings);
|
||||
toast.success("Settings saved");
|
||||
};
|
||||
|
||||
const handleReset = async () => {
|
||||
const defaultSettings = await resetToDefaultSettings();
|
||||
setTempSettings(defaultSettings);
|
||||
setSavedSettings(defaultSettings);
|
||||
applyThemeMode(defaultSettings.themeMode);
|
||||
applyTheme(defaultSettings.theme);
|
||||
applyFont(defaultSettings.fontFamily);
|
||||
toast.success("Settings reset to default");
|
||||
};
|
||||
|
||||
const handleBrowseFolder = async () => {
|
||||
try {
|
||||
const selectedPath = await SelectFolder(tempSettings.downloadPath || "");
|
||||
if (selectedPath && selectedPath.trim() !== "") {
|
||||
setTempSettings((prev) => ({ ...prev, downloadPath: selectedPath }));
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error selecting folder:", error);
|
||||
toast.error(`Error selecting folder: ${error}`);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDownloadFFmpeg = async () => {
|
||||
setDownloadingFFmpeg(true);
|
||||
try {
|
||||
await DownloadFFmpeg();
|
||||
setFfmpegInstalled(true);
|
||||
toast.success("FFmpeg downloaded successfully");
|
||||
} catch (error) {
|
||||
toast.error("Failed to download FFmpeg");
|
||||
console.error("Error downloading FFmpeg:", error);
|
||||
} finally {
|
||||
setDownloadingFFmpeg(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDownloadExifTool = async () => {
|
||||
setDownloadingExifTool(true);
|
||||
try {
|
||||
await DownloadExifTool();
|
||||
setExiftoolInstalled(true);
|
||||
toast.success("ExifTool downloaded successfully");
|
||||
} catch (error) {
|
||||
toast.error("Failed to download ExifTool");
|
||||
console.error("Error downloading ExifTool:", error);
|
||||
} finally {
|
||||
setDownloadingExifTool(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<h1 className="text-2xl font-bold">Settings</h1>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
{/* Left Column */}
|
||||
<div className="space-y-4">
|
||||
{/* Download Path */}
|
||||
<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>
|
||||
|
||||
{/* Theme Mode */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="theme-mode">Mode</Label>
|
||||
<Select
|
||||
value={tempSettings.themeMode}
|
||||
onValueChange={(value: "auto" | "light" | "dark") => setTempSettings((prev) => ({ ...prev, themeMode: value }))}
|
||||
>
|
||||
<SelectTrigger id="theme-mode">
|
||||
<SelectValue placeholder="Select theme mode" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="auto">Auto</SelectItem>
|
||||
<SelectItem value="light">Light</SelectItem>
|
||||
<SelectItem value="dark">Dark</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{/* Accent */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="theme">Accent</Label>
|
||||
<Select
|
||||
value={tempSettings.theme}
|
||||
onValueChange={(value) => setTempSettings((prev) => ({ ...prev, theme: value }))}
|
||||
>
|
||||
<SelectTrigger id="theme">
|
||||
<SelectValue placeholder="Select a theme" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{themes.map((theme) => (
|
||||
<SelectItem key={theme.name} value={theme.name}>
|
||||
<span className="flex items-center gap-2">
|
||||
<span
|
||||
className="w-3 h-3 rounded-full border border-border"
|
||||
style={{
|
||||
backgroundColor: isDark ? theme.cssVars.dark.primary : theme.cssVars.light.primary
|
||||
}}
|
||||
/>
|
||||
{theme.label}
|
||||
</span>
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{/* Font */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="font">Font</Label>
|
||||
<Select
|
||||
value={tempSettings.fontFamily}
|
||||
onValueChange={(value: FontFamily) => setTempSettings((prev) => ({ ...prev, fontFamily: value }))}
|
||||
>
|
||||
<SelectTrigger id="font">
|
||||
<SelectValue placeholder="Select a font" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{FONT_OPTIONS.map((font) => (
|
||||
<SelectItem key={font.value} value={font.value}>
|
||||
<span style={{ fontFamily: font.fontFamily }}>{font.label}</span>
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{/* Sound Effects */}
|
||||
<div className="flex items-center gap-3 pt-2">
|
||||
<Label htmlFor="sfx-enabled" className="cursor-pointer text-sm">Sound Effects</Label>
|
||||
<Switch
|
||||
id="sfx-enabled"
|
||||
checked={tempSettings.sfxEnabled}
|
||||
onCheckedChange={(checked) => setTempSettings(prev => ({ ...prev, sfxEnabled: checked }))}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Right Column */}
|
||||
<div className="space-y-4">
|
||||
{/* Metadata Embedding */}
|
||||
<div className="space-y-2">
|
||||
<Label className="flex items-center gap-2">
|
||||
Metadata Embedding
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Info className="h-3.5 w-3.5 text-muted-foreground cursor-help" />
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="top">
|
||||
<p>ExifTool is required to embed tweet URL and original filename into media file metadata</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</Label>
|
||||
<div className="h-9 flex items-center">
|
||||
{exiftoolInstalled ? (
|
||||
<div className="flex items-center gap-2 text-sm text-green-600 dark:text-green-400">
|
||||
<Check className="h-4 w-4" />
|
||||
Installed
|
||||
</div>
|
||||
) : (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-9"
|
||||
onClick={handleDownloadExifTool}
|
||||
disabled={downloadingExifTool}
|
||||
>
|
||||
{downloadingExifTool ? (
|
||||
<>
|
||||
<Spinner />
|
||||
Downloading...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Download className="h-4 w-4" />
|
||||
Download ExifTool
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* GIF Conversion */}
|
||||
<div className="space-y-2">
|
||||
<Label className="flex items-center gap-2">
|
||||
GIF Conversion
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Info className="h-3.5 w-3.5 text-muted-foreground cursor-help" />
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="top">
|
||||
<p>FFmpeg is required to convert Twitter's MP4 to actual GIF format</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</Label>
|
||||
<div className="h-9 flex items-center">
|
||||
{ffmpegInstalled ? (
|
||||
<div className="flex items-center gap-2 text-sm text-green-600 dark:text-green-400">
|
||||
<Check className="h-4 w-4" />
|
||||
Installed
|
||||
</div>
|
||||
) : (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-9"
|
||||
onClick={handleDownloadFFmpeg}
|
||||
disabled={downloadingFFmpeg}
|
||||
>
|
||||
{downloadingFFmpeg ? (
|
||||
<>
|
||||
<Spinner />
|
||||
Downloading...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Download className="h-4 w-4" />
|
||||
Download FFmpeg
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* GIF Quality - only show if FFmpeg installed */}
|
||||
{ffmpegInstalled && (
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="gif-quality">GIF Quality</Label>
|
||||
<div className="flex items-center gap-2">
|
||||
<Select
|
||||
value={tempSettings.gifQuality}
|
||||
onValueChange={(value: GifQuality) => {
|
||||
setTempSettings((prev) => ({
|
||||
...prev,
|
||||
gifQuality: value,
|
||||
}));
|
||||
}}
|
||||
>
|
||||
<SelectTrigger id="gif-quality" className="w-auto">
|
||||
<SelectValue placeholder="Select quality" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="fast">Fast</SelectItem>
|
||||
<SelectItem value="better">Better</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Select
|
||||
value={tempSettings.gifResolution}
|
||||
onValueChange={(value: GifResolution) => setTempSettings((prev) => ({ ...prev, gifResolution: value }))}
|
||||
>
|
||||
<SelectTrigger id="gif-resolution" className="w-auto">
|
||||
<SelectValue placeholder="Resolution" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="original">Original</SelectItem>
|
||||
<SelectItem value="high">High (800px)</SelectItem>
|
||||
<SelectItem value="medium">Medium (600px)</SelectItem>
|
||||
<SelectItem value="low">Low (400px)</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Proxy */}
|
||||
<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 text-muted-foreground cursor-help" />
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="top">
|
||||
<p>If download fails, try using a proxy server</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</Label>
|
||||
<InputWithContext
|
||||
id="proxy"
|
||||
value={tempSettings.proxy || ""}
|
||||
onChange={(e) => setTempSettings((prev) => ({ ...prev, proxy: e.target.value }))}
|
||||
placeholder="http://proxy:port or socks5://proxy:port (optional)"
|
||||
className="w-[90%]"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Fetch Timeout */}
|
||||
<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 text-muted-foreground cursor-help" />
|
||||
</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;
|
||||
// Allow empty input for user to type freely
|
||||
if (inputValue === "") {
|
||||
setTempSettings((prev) => ({ ...prev, fetchTimeout: 60 }));
|
||||
return;
|
||||
}
|
||||
const value = parseInt(inputValue, 10);
|
||||
// Allow any number while typing (including values less than min during typing)
|
||||
// Validation will happen on blur
|
||||
if (!isNaN(value)) {
|
||||
setTempSettings((prev) => ({ ...prev, fetchTimeout: value }));
|
||||
}
|
||||
}}
|
||||
onBlur={(e) => {
|
||||
// Validate and clamp value on blur
|
||||
const value = parseInt(e.target.value, 10);
|
||||
if (isNaN(value) || value < 30) {
|
||||
setTempSettings((prev) => ({ ...prev, fetchTimeout: 30 }));
|
||||
} else if (value > 900) {
|
||||
setTempSettings((prev) => ({ ...prev, fetchTimeout: 900 }));
|
||||
}
|
||||
}}
|
||||
placeholder="60"
|
||||
className="w-[20%]"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Actions */}
|
||||
<div className="flex gap-2 justify-between pt-4 border-t">
|
||||
<Button variant="outline" onClick={handleReset} className="gap-1.5">
|
||||
<RotateCcw className="h-4 w-4" />
|
||||
Reset to Default
|
||||
</Button>
|
||||
<Button onClick={handleSave} className="gap-1.5">
|
||||
<Save className="h-4 w-4" />
|
||||
Save Changes
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
import { Home, Settings, Bug, Database, LayoutGrid, Coffee, Github } from "lucide-react";
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipTrigger,
|
||||
} from "@/components/ui/tooltip";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { openExternal } from "@/lib/utils";
|
||||
|
||||
export type PageType = "main" | "settings" | "debug" | "database";
|
||||
|
||||
interface SidebarProps {
|
||||
currentPage: PageType;
|
||||
onPageChange: (page: PageType) => void;
|
||||
}
|
||||
|
||||
export function Sidebar({ currentPage, onPageChange }: SidebarProps) {
|
||||
const navItems = [
|
||||
{ id: "main" as PageType, icon: Home, label: "Home" },
|
||||
{ id: "settings" as PageType, icon: Settings, label: "Settings" },
|
||||
{ id: "database" as PageType, icon: Database, label: "Saved Accounts" },
|
||||
{ id: "debug" as PageType, icon: Bug, label: "Debug Logs" },
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="fixed left-0 top-0 h-full w-14 bg-card border-r border-border flex flex-col items-center py-14 z-30">
|
||||
<div className="flex flex-col gap-2 flex-1">
|
||||
{navItems.map((item) => (
|
||||
<Tooltip key={item.id} delayDuration={0}>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant={currentPage === item.id ? "secondary" : "ghost"}
|
||||
size="icon"
|
||||
className="h-10 w-10"
|
||||
onClick={() => onPageChange(item.id)}
|
||||
>
|
||||
<item.icon className="h-5 w-5" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="right">
|
||||
<p>{item.label}</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Bottom icons */}
|
||||
<div className="mt-auto flex flex-col gap-2">
|
||||
<Tooltip delayDuration={0}>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-10 w-10"
|
||||
onClick={() => openExternal("https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/issues")}
|
||||
>
|
||||
<Github className="h-5 w-5" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="right">
|
||||
<p>Report Bug</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
<Tooltip delayDuration={0}>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-10 w-10"
|
||||
onClick={() => openExternal("https://exyezed.cc/")}
|
||||
>
|
||||
<LayoutGrid className="h-5 w-5" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="right">
|
||||
<p>Other Projects</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
<Tooltip delayDuration={0}>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-10 w-10"
|
||||
onClick={() => openExternal("https://ko-fi.com/afkarxyz")}
|
||||
>
|
||||
<Coffee className="h-5 w-5" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="right">
|
||||
<p>Support me on Ko-fi</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import { X, Minus, Maximize } from "lucide-react";
|
||||
import { WindowMinimise, WindowToggleMaximise, Quit } from "../../wailsjs/runtime/runtime";
|
||||
|
||||
export function TitleBar() {
|
||||
const handleMinimize = () => {
|
||||
WindowMinimise();
|
||||
};
|
||||
|
||||
const handleMaximize = () => {
|
||||
WindowToggleMaximise();
|
||||
};
|
||||
|
||||
const handleClose = () => {
|
||||
Quit();
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* Draggable area */}
|
||||
<div
|
||||
className="fixed top-0 left-14 right-0 h-10 z-40 bg-background/80 backdrop-blur-sm"
|
||||
style={{ "--wails-draggable": "drag" } as React.CSSProperties}
|
||||
onDoubleClick={handleMaximize}
|
||||
/>
|
||||
|
||||
{/* Window control buttons - Windows style, right side */}
|
||||
<div className="fixed top-1.5 right-2 z-50 flex h-7 gap-0.5">
|
||||
<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"
|
||||
>
|
||||
<Minus className="w-3.5 h-3.5" />
|
||||
</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"
|
||||
>
|
||||
<Maximize className="w-3.5 h-3.5" />
|
||||
</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"
|
||||
>
|
||||
<X className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import * as React from "react"
|
||||
import { Slot } from "@radix-ui/react-slot"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const badgeVariants = cva(
|
||||
"inline-flex items-center justify-center rounded-full border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default:
|
||||
"border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",
|
||||
secondary:
|
||||
"border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",
|
||||
destructive:
|
||||
"border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
|
||||
outline:
|
||||
"text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
function Badge({
|
||||
className,
|
||||
variant,
|
||||
asChild = false,
|
||||
...props
|
||||
}: React.ComponentProps<"span"> &
|
||||
VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
|
||||
const Comp = asChild ? Slot : "span"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="badge"
|
||||
className={cn(badgeVariants({ variant }), className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Badge, badgeVariants }
|
||||
@@ -0,0 +1,60 @@
|
||||
import * as React from "react"
|
||||
import { Slot } from "@radix-ui/react-slot"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const buttonVariants = cva(
|
||||
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all cursor-pointer disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-primary text-primary-foreground hover:bg-primary/90",
|
||||
destructive:
|
||||
"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
|
||||
outline:
|
||||
"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",
|
||||
secondary:
|
||||
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
|
||||
ghost:
|
||||
"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
|
||||
link: "text-primary underline-offset-4 hover:underline",
|
||||
},
|
||||
size: {
|
||||
default: "h-9 px-4 py-2 has-[>svg]:px-3",
|
||||
sm: "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",
|
||||
lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
|
||||
icon: "size-9",
|
||||
"icon-sm": "size-8",
|
||||
"icon-lg": "size-10",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
function Button({
|
||||
className,
|
||||
variant,
|
||||
size,
|
||||
asChild = false,
|
||||
...props
|
||||
}: React.ComponentProps<"button"> &
|
||||
VariantProps<typeof buttonVariants> & {
|
||||
asChild?: boolean
|
||||
}) {
|
||||
const Comp = asChild ? Slot : "button"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="button"
|
||||
className={cn(buttonVariants({ variant, size, className }))}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Button, buttonVariants }
|
||||
@@ -0,0 +1,32 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as CheckboxPrimitive from "@radix-ui/react-checkbox"
|
||||
import { CheckIcon } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Checkbox({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof CheckboxPrimitive.Root>) {
|
||||
return (
|
||||
<CheckboxPrimitive.Root
|
||||
data-slot="checkbox"
|
||||
className={cn(
|
||||
"peer border-input dark:bg-input/30 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:data-[state=checked]:bg-primary data-[state=checked]:border-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive size-4 shrink-0 rounded-[4px] border shadow-xs transition-shadow outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<CheckboxPrimitive.Indicator
|
||||
data-slot="checkbox-indicator"
|
||||
className="grid place-content-center text-current transition-none"
|
||||
>
|
||||
<CheckIcon className="size-3.5" />
|
||||
</CheckboxPrimitive.Indicator>
|
||||
</CheckboxPrimitive.Root>
|
||||
)
|
||||
}
|
||||
|
||||
export { Checkbox }
|
||||
@@ -0,0 +1,252 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as ContextMenuPrimitive from "@radix-ui/react-context-menu"
|
||||
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function ContextMenu({
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Root>) {
|
||||
return <ContextMenuPrimitive.Root data-slot="context-menu" {...props} />
|
||||
}
|
||||
|
||||
function ContextMenuTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Trigger>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Trigger data-slot="context-menu-trigger" {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuGroup({
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Group>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Group data-slot="context-menu-group" {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuPortal({
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Portal>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Portal data-slot="context-menu-portal" {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuSub({
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Sub>) {
|
||||
return <ContextMenuPrimitive.Sub data-slot="context-menu-sub" {...props} />
|
||||
}
|
||||
|
||||
function ContextMenuRadioGroup({
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.RadioGroup>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.RadioGroup
|
||||
data-slot="context-menu-radio-group"
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuSubTrigger({
|
||||
className,
|
||||
inset,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.SubTrigger> & {
|
||||
inset?: boolean
|
||||
}) {
|
||||
return (
|
||||
<ContextMenuPrimitive.SubTrigger
|
||||
data-slot="context-menu-sub-trigger"
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground flex cursor-default items-center rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-inset:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<ChevronRightIcon className="ml-auto" />
|
||||
</ContextMenuPrimitive.SubTrigger>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuSubContent({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.SubContent>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.SubContent
|
||||
data-slot="context-menu-sub-content"
|
||||
className={cn(
|
||||
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-32 origin-(--radix-context-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuContent({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Content>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Portal>
|
||||
<ContextMenuPrimitive.Content
|
||||
data-slot="context-menu-content"
|
||||
className={cn(
|
||||
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-context-menu-content-available-height) min-w-32 origin-(--radix-context-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</ContextMenuPrimitive.Portal>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuItem({
|
||||
className,
|
||||
inset,
|
||||
variant = "default",
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Item> & {
|
||||
inset?: boolean
|
||||
variant?: "default" | "destructive"
|
||||
}) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Item
|
||||
data-slot="context-menu-item"
|
||||
data-inset={inset}
|
||||
data-variant={variant}
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:text-destructive! [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-disabled:pointer-events-none data-disabled:opacity-50 data-inset:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuCheckboxItem({
|
||||
className,
|
||||
children,
|
||||
checked,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.CheckboxItem>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.CheckboxItem
|
||||
data-slot="context-menu-checkbox-item"
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
checked={checked}
|
||||
{...props}
|
||||
>
|
||||
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||
<ContextMenuPrimitive.ItemIndicator>
|
||||
<CheckIcon className="size-4" />
|
||||
</ContextMenuPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</ContextMenuPrimitive.CheckboxItem>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuRadioItem({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.RadioItem>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.RadioItem
|
||||
data-slot="context-menu-radio-item"
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||
<ContextMenuPrimitive.ItemIndicator>
|
||||
<CircleIcon className="size-2 fill-current" />
|
||||
</ContextMenuPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</ContextMenuPrimitive.RadioItem>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuLabel({
|
||||
className,
|
||||
inset,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Label> & {
|
||||
inset?: boolean
|
||||
}) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Label
|
||||
data-slot="context-menu-label"
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
"text-foreground px-2 py-1.5 text-sm font-medium data-inset:pl-8",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuSeparator({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Separator>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Separator
|
||||
data-slot="context-menu-separator"
|
||||
className={cn("bg-border -mx-1 my-1 h-px", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuShortcut({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"span">) {
|
||||
return (
|
||||
<span
|
||||
data-slot="context-menu-shortcut"
|
||||
className={cn(
|
||||
"text-muted-foreground ml-auto text-xs tracking-widest",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
ContextMenu,
|
||||
ContextMenuTrigger,
|
||||
ContextMenuContent,
|
||||
ContextMenuItem,
|
||||
ContextMenuCheckboxItem,
|
||||
ContextMenuRadioItem,
|
||||
ContextMenuLabel,
|
||||
ContextMenuSeparator,
|
||||
ContextMenuShortcut,
|
||||
ContextMenuGroup,
|
||||
ContextMenuPortal,
|
||||
ContextMenuSub,
|
||||
ContextMenuSubContent,
|
||||
ContextMenuSubTrigger,
|
||||
ContextMenuRadioGroup,
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as DialogPrimitive from "@radix-ui/react-dialog"
|
||||
import { XIcon } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Dialog({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Root>) {
|
||||
return <DialogPrimitive.Root data-slot="dialog" {...props} />
|
||||
}
|
||||
|
||||
function DialogTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
|
||||
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
|
||||
}
|
||||
|
||||
function DialogPortal({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Portal>) {
|
||||
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
|
||||
}
|
||||
|
||||
function DialogClose({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Close>) {
|
||||
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
|
||||
}
|
||||
|
||||
function DialogOverlay({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
|
||||
return (
|
||||
<DialogPrimitive.Overlay
|
||||
data-slot="dialog-overlay"
|
||||
className={cn(
|
||||
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogContent({
|
||||
className,
|
||||
children,
|
||||
showCloseButton = true,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Content> & {
|
||||
showCloseButton?: boolean
|
||||
}) {
|
||||
return (
|
||||
<DialogPortal data-slot="dialog-portal">
|
||||
<DialogOverlay />
|
||||
<DialogPrimitive.Content
|
||||
data-slot="dialog-content"
|
||||
className={cn(
|
||||
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
{showCloseButton && (
|
||||
<DialogPrimitive.Close
|
||||
data-slot="dialog-close"
|
||||
className="ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"
|
||||
>
|
||||
<XIcon />
|
||||
<span className="sr-only">Close</span>
|
||||
</DialogPrimitive.Close>
|
||||
)}
|
||||
</DialogPrimitive.Content>
|
||||
</DialogPortal>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="dialog-header"
|
||||
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="dialog-footer"
|
||||
className={cn(
|
||||
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogTitle({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Title>) {
|
||||
return (
|
||||
<DialogPrimitive.Title
|
||||
data-slot="dialog-title"
|
||||
className={cn("text-lg leading-none font-semibold", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogDescription({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Description>) {
|
||||
return (
|
||||
<DialogPrimitive.Description
|
||||
data-slot="dialog-description"
|
||||
className={cn("text-muted-foreground text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Dialog,
|
||||
DialogClose,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogOverlay,
|
||||
DialogPortal,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
import * as React from "react"
|
||||
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu"
|
||||
import { CheckIcon, ChevronRightIcon } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const DropdownMenu = DropdownMenuPrimitive.Root
|
||||
|
||||
const DropdownMenuTrigger = DropdownMenuPrimitive.Trigger
|
||||
|
||||
const DropdownMenuGroup = DropdownMenuPrimitive.Group
|
||||
|
||||
const DropdownMenuPortal = DropdownMenuPrimitive.Portal
|
||||
|
||||
const DropdownMenuSub = DropdownMenuPrimitive.Sub
|
||||
|
||||
const DropdownMenuRadioGroup = DropdownMenuPrimitive.RadioGroup
|
||||
|
||||
const DropdownMenuSubTrigger = React.forwardRef<
|
||||
React.ElementRef<typeof DropdownMenuPrimitive.SubTrigger>,
|
||||
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubTrigger> & {
|
||||
inset?: boolean
|
||||
}
|
||||
>(({ className, inset, children, ...props }, ref) => (
|
||||
<DropdownMenuPrimitive.SubTrigger
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent",
|
||||
inset && "pl-8",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<ChevronRightIcon className="ml-auto h-4 w-4" />
|
||||
</DropdownMenuPrimitive.SubTrigger>
|
||||
))
|
||||
DropdownMenuSubTrigger.displayName =
|
||||
DropdownMenuPrimitive.SubTrigger.displayName
|
||||
|
||||
const DropdownMenuSubContent = React.forwardRef<
|
||||
React.ElementRef<typeof DropdownMenuPrimitive.SubContent>,
|
||||
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubContent>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<DropdownMenuPrimitive.SubContent
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"z-50 min-w-32 overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
DropdownMenuSubContent.displayName =
|
||||
DropdownMenuPrimitive.SubContent.displayName
|
||||
|
||||
const DropdownMenuContent = React.forwardRef<
|
||||
React.ElementRef<typeof DropdownMenuPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Content>
|
||||
>(({ className, sideOffset = 4, ...props }, ref) => (
|
||||
<DropdownMenuPrimitive.Portal>
|
||||
<DropdownMenuPrimitive.Content
|
||||
ref={ref}
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
"z-50 min-w-32 overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</DropdownMenuPrimitive.Portal>
|
||||
))
|
||||
DropdownMenuContent.displayName = DropdownMenuPrimitive.Content.displayName
|
||||
|
||||
const DropdownMenuItem = React.forwardRef<
|
||||
React.ElementRef<typeof DropdownMenuPrimitive.Item>,
|
||||
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Item> & {
|
||||
inset?: boolean
|
||||
}
|
||||
>(({ className, inset, ...props }, ref) => (
|
||||
<DropdownMenuPrimitive.Item
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50",
|
||||
inset && "pl-8",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
DropdownMenuItem.displayName = DropdownMenuPrimitive.Item.displayName
|
||||
|
||||
const DropdownMenuCheckboxItem = React.forwardRef<
|
||||
React.ElementRef<typeof DropdownMenuPrimitive.CheckboxItem>,
|
||||
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.CheckboxItem>
|
||||
>(({ className, children, checked, ...props }, ref) => (
|
||||
<DropdownMenuPrimitive.CheckboxItem
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50",
|
||||
className
|
||||
)}
|
||||
checked={checked}
|
||||
{...props}
|
||||
>
|
||||
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
|
||||
<DropdownMenuPrimitive.ItemIndicator>
|
||||
<CheckIcon className="h-4 w-4" />
|
||||
</DropdownMenuPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</DropdownMenuPrimitive.CheckboxItem>
|
||||
))
|
||||
DropdownMenuCheckboxItem.displayName =
|
||||
DropdownMenuPrimitive.CheckboxItem.displayName
|
||||
|
||||
const DropdownMenuRadioItem = React.forwardRef<
|
||||
React.ElementRef<typeof DropdownMenuPrimitive.RadioItem>,
|
||||
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.RadioItem>
|
||||
>(({ className, children, ...props }, ref) => (
|
||||
<DropdownMenuPrimitive.RadioItem
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
|
||||
<DropdownMenuPrimitive.ItemIndicator>
|
||||
<CheckIcon className="h-4 w-4" />
|
||||
</DropdownMenuPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</DropdownMenuPrimitive.RadioItem>
|
||||
))
|
||||
DropdownMenuRadioItem.displayName = DropdownMenuPrimitive.RadioItem.displayName
|
||||
|
||||
const DropdownMenuLabel = React.forwardRef<
|
||||
React.ElementRef<typeof DropdownMenuPrimitive.Label>,
|
||||
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Label> & {
|
||||
inset?: boolean
|
||||
}
|
||||
>(({ className, inset, ...props }, ref) => (
|
||||
<DropdownMenuPrimitive.Label
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"px-2 py-1.5 text-sm font-semibold",
|
||||
inset && "pl-8",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
DropdownMenuLabel.displayName = DropdownMenuPrimitive.Label.displayName
|
||||
|
||||
const DropdownMenuSeparator = React.forwardRef<
|
||||
React.ElementRef<typeof DropdownMenuPrimitive.Separator>,
|
||||
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Separator>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<DropdownMenuPrimitive.Separator
|
||||
ref={ref}
|
||||
className={cn("-mx-1 my-1 h-px bg-muted", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
DropdownMenuSeparator.displayName = DropdownMenuPrimitive.Separator.displayName
|
||||
|
||||
const DropdownMenuShortcut = ({
|
||||
className,
|
||||
...props
|
||||
}: React.HTMLAttributes<HTMLSpanElement>) => {
|
||||
return (
|
||||
<span
|
||||
className={cn("ml-auto text-xs tracking-widest opacity-60", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
DropdownMenuShortcut.displayName = "DropdownMenuShortcut"
|
||||
|
||||
export {
|
||||
DropdownMenu,
|
||||
DropdownMenuTrigger,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuCheckboxItem,
|
||||
DropdownMenuRadioItem,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuShortcut,
|
||||
DropdownMenuGroup,
|
||||
DropdownMenuPortal,
|
||||
DropdownMenuSub,
|
||||
DropdownMenuSubContent,
|
||||
DropdownMenuSubTrigger,
|
||||
DropdownMenuRadioGroup,
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,216 @@
|
||||
import * as React from "react";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import {
|
||||
ContextMenu,
|
||||
ContextMenuContent,
|
||||
ContextMenuItem,
|
||||
ContextMenuSeparator,
|
||||
ContextMenuTrigger,
|
||||
} from "@/components/ui/context-menu";
|
||||
import { Scissors, Copy, Clipboard, Type } from "lucide-react";
|
||||
|
||||
export interface InputWithContextProps
|
||||
extends React.InputHTMLAttributes<HTMLInputElement> {
|
||||
onValueChange?: (value: string) => void;
|
||||
}
|
||||
|
||||
const InputWithContext = React.forwardRef<HTMLInputElement, InputWithContextProps>(
|
||||
({ className, type, onValueChange, onChange, ...props }, ref) => {
|
||||
const inputRef = React.useRef<HTMLInputElement>(null);
|
||||
const [hasSelection, setHasSelection] = React.useState(false);
|
||||
const [canPaste, setCanPaste] = React.useState(false);
|
||||
|
||||
// Combine refs
|
||||
React.useImperativeHandle(ref, () => inputRef.current as HTMLInputElement);
|
||||
|
||||
// Check selection state
|
||||
const updateSelectionState = () => {
|
||||
const input = inputRef.current;
|
||||
if (!input) return;
|
||||
const start = input.selectionStart ?? 0;
|
||||
const end = input.selectionEnd ?? 0;
|
||||
setHasSelection(start !== end);
|
||||
};
|
||||
|
||||
// Check clipboard permission when user explicitly opens the context menu.
|
||||
const checkClipboard = async () => {
|
||||
try {
|
||||
const text = await navigator.clipboard.readText();
|
||||
setCanPaste(text.length > 0);
|
||||
} catch {
|
||||
setCanPaste(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleCut = async () => {
|
||||
const input = inputRef.current;
|
||||
if (!input) return;
|
||||
|
||||
const start = input.selectionStart ?? 0;
|
||||
const end = input.selectionEnd ?? 0;
|
||||
const selectedText = input.value.substring(start, end);
|
||||
|
||||
if (selectedText) {
|
||||
try {
|
||||
await navigator.clipboard.writeText(selectedText);
|
||||
const newValue = input.value.substring(0, start) + input.value.substring(end);
|
||||
|
||||
// Update value and trigger change
|
||||
input.value = newValue;
|
||||
input.setSelectionRange(start, start);
|
||||
|
||||
// Trigger React onChange
|
||||
if (onChange) {
|
||||
const event = {
|
||||
target: input,
|
||||
currentTarget: input,
|
||||
} as React.ChangeEvent<HTMLInputElement>;
|
||||
onChange(event);
|
||||
}
|
||||
|
||||
if (onValueChange) {
|
||||
onValueChange(newValue);
|
||||
}
|
||||
|
||||
input.focus();
|
||||
} catch (err) {
|
||||
console.error("Failed to cut:", err);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleCopy = async () => {
|
||||
const input = inputRef.current;
|
||||
if (!input) return;
|
||||
|
||||
const start = input.selectionStart ?? 0;
|
||||
const end = input.selectionEnd ?? 0;
|
||||
const selectedText = input.value.substring(start, end);
|
||||
|
||||
if (selectedText) {
|
||||
try {
|
||||
await navigator.clipboard.writeText(selectedText);
|
||||
input.focus();
|
||||
} catch (err) {
|
||||
console.error("Failed to copy:", err);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handlePaste = async () => {
|
||||
const input = inputRef.current;
|
||||
if (!input) return;
|
||||
|
||||
try {
|
||||
const text = await navigator.clipboard.readText();
|
||||
const start = input.selectionStart ?? 0;
|
||||
const end = input.selectionEnd ?? 0;
|
||||
|
||||
const newValue =
|
||||
input.value.substring(0, start) + text + input.value.substring(end);
|
||||
|
||||
// Update value and trigger change
|
||||
input.value = newValue;
|
||||
const newPosition = start + text.length;
|
||||
input.setSelectionRange(newPosition, newPosition);
|
||||
|
||||
// Trigger React onChange
|
||||
if (onChange) {
|
||||
const event = {
|
||||
target: input,
|
||||
currentTarget: input,
|
||||
} as React.ChangeEvent<HTMLInputElement>;
|
||||
onChange(event);
|
||||
}
|
||||
|
||||
if (onValueChange) {
|
||||
onValueChange(newValue);
|
||||
}
|
||||
|
||||
input.focus();
|
||||
await checkClipboard();
|
||||
} catch (err) {
|
||||
console.error("Failed to paste:", err);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSelectAll = () => {
|
||||
const input = inputRef.current;
|
||||
if (!input) return;
|
||||
input.select();
|
||||
input.focus();
|
||||
updateSelectionState();
|
||||
};
|
||||
|
||||
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
if (onChange) {
|
||||
onChange(e);
|
||||
}
|
||||
if (onValueChange) {
|
||||
onValueChange(e.target.value);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<ContextMenu
|
||||
onOpenChange={(open) => {
|
||||
if (open) {
|
||||
checkClipboard();
|
||||
}
|
||||
}}
|
||||
>
|
||||
<ContextMenuTrigger asChild>
|
||||
<Input
|
||||
ref={inputRef}
|
||||
type={type}
|
||||
className={className}
|
||||
onChange={handleInputChange}
|
||||
onSelect={updateSelectionState}
|
||||
onMouseUp={updateSelectionState}
|
||||
onKeyUp={updateSelectionState}
|
||||
{...props}
|
||||
/>
|
||||
</ContextMenuTrigger>
|
||||
<ContextMenuContent className="w-48">
|
||||
<ContextMenuItem
|
||||
onSelect={handleCut}
|
||||
disabled={!hasSelection || props.disabled || props.readOnly}
|
||||
>
|
||||
<Scissors className="mr-2 h-4 w-4" />
|
||||
Cut
|
||||
<span className="ml-auto text-xs text-muted-foreground">Ctrl+X</span>
|
||||
</ContextMenuItem>
|
||||
<ContextMenuItem
|
||||
onSelect={handleCopy}
|
||||
disabled={!hasSelection || props.disabled}
|
||||
>
|
||||
<Copy className="mr-2 h-4 w-4" />
|
||||
Copy
|
||||
<span className="ml-auto text-xs text-muted-foreground">Ctrl+C</span>
|
||||
</ContextMenuItem>
|
||||
<ContextMenuItem
|
||||
onSelect={handlePaste}
|
||||
disabled={!canPaste || props.disabled || props.readOnly}
|
||||
>
|
||||
<Clipboard className="mr-2 h-4 w-4" />
|
||||
Paste
|
||||
<span className="ml-auto text-xs text-muted-foreground">Ctrl+V</span>
|
||||
</ContextMenuItem>
|
||||
<ContextMenuSeparator />
|
||||
<ContextMenuItem
|
||||
onSelect={handleSelectAll}
|
||||
disabled={!inputRef.current?.value || props.disabled}
|
||||
>
|
||||
<Type className="mr-2 h-4 w-4" />
|
||||
Select All
|
||||
<span className="ml-auto text-xs text-muted-foreground">Ctrl+A</span>
|
||||
</ContextMenuItem>
|
||||
</ContextMenuContent>
|
||||
</ContextMenu>
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
InputWithContext.displayName = "InputWithContext";
|
||||
|
||||
export { InputWithContext };
|
||||
@@ -0,0 +1,21 @@
|
||||
import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
|
||||
return (
|
||||
<input
|
||||
type={type}
|
||||
data-slot="input"
|
||||
className={cn(
|
||||
"file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
||||
"focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
|
||||
"aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Input }
|
||||
@@ -0,0 +1,24 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as LabelPrimitive from "@radix-ui/react-label"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Label({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
|
||||
return (
|
||||
<LabelPrimitive.Root
|
||||
data-slot="label"
|
||||
className={cn(
|
||||
"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Label }
|
||||
@@ -0,0 +1,31 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as ProgressPrimitive from "@radix-ui/react-progress"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Progress({
|
||||
className,
|
||||
value,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ProgressPrimitive.Root>) {
|
||||
return (
|
||||
<ProgressPrimitive.Root
|
||||
data-slot="progress"
|
||||
className={cn(
|
||||
"bg-primary/20 relative h-2 w-full overflow-hidden rounded-full",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ProgressPrimitive.Indicator
|
||||
data-slot="progress-indicator"
|
||||
className="bg-primary h-full w-full flex-1 transition-all"
|
||||
style={{ transform: `translateX(-${100 - (value || 0)}%)` }}
|
||||
/>
|
||||
</ProgressPrimitive.Root>
|
||||
)
|
||||
}
|
||||
|
||||
export { Progress }
|
||||
@@ -0,0 +1,185 @@
|
||||
import * as React from "react"
|
||||
import * as SelectPrimitive from "@radix-ui/react-select"
|
||||
import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Select({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Root>) {
|
||||
return <SelectPrimitive.Root data-slot="select" {...props} />
|
||||
}
|
||||
|
||||
function SelectGroup({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Group>) {
|
||||
return <SelectPrimitive.Group data-slot="select-group" {...props} />
|
||||
}
|
||||
|
||||
function SelectValue({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Value>) {
|
||||
return <SelectPrimitive.Value data-slot="select-value" {...props} />
|
||||
}
|
||||
|
||||
function SelectTrigger({
|
||||
className,
|
||||
size = "default",
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Trigger> & {
|
||||
size?: "sm" | "default"
|
||||
}) {
|
||||
return (
|
||||
<SelectPrimitive.Trigger
|
||||
data-slot="select-trigger"
|
||||
data-size={size}
|
||||
className={cn(
|
||||
"border-input data-placeholder:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-fit items-center justify-between gap-2 rounded-md border bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<SelectPrimitive.Icon asChild>
|
||||
<ChevronDownIcon className="size-4 opacity-50" />
|
||||
</SelectPrimitive.Icon>
|
||||
</SelectPrimitive.Trigger>
|
||||
)
|
||||
}
|
||||
|
||||
function SelectContent({
|
||||
className,
|
||||
children,
|
||||
position = "popper",
|
||||
align = "center",
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Content>) {
|
||||
return (
|
||||
<SelectPrimitive.Portal>
|
||||
<SelectPrimitive.Content
|
||||
data-slot="select-content"
|
||||
className={cn(
|
||||
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-32 origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border shadow-md",
|
||||
position === "popper" &&
|
||||
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
|
||||
className
|
||||
)}
|
||||
position={position}
|
||||
align={align}
|
||||
{...props}
|
||||
>
|
||||
<SelectScrollUpButton />
|
||||
<SelectPrimitive.Viewport
|
||||
className={cn(
|
||||
"p-1",
|
||||
position === "popper" &&
|
||||
"h-(--radix-select-trigger-height) w-full min-w-(--radix-select-trigger-width) scroll-my-1"
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</SelectPrimitive.Viewport>
|
||||
<SelectScrollDownButton />
|
||||
</SelectPrimitive.Content>
|
||||
</SelectPrimitive.Portal>
|
||||
)
|
||||
}
|
||||
|
||||
function SelectLabel({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Label>) {
|
||||
return (
|
||||
<SelectPrimitive.Label
|
||||
data-slot="select-label"
|
||||
className={cn("text-muted-foreground px-2 py-1.5 text-xs", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SelectItem({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Item>) {
|
||||
return (
|
||||
<SelectPrimitive.Item
|
||||
data-slot="select-item"
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span className="absolute right-2 flex size-3.5 items-center justify-center">
|
||||
<SelectPrimitive.ItemIndicator>
|
||||
<CheckIcon className="size-4" />
|
||||
</SelectPrimitive.ItemIndicator>
|
||||
</span>
|
||||
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
|
||||
</SelectPrimitive.Item>
|
||||
)
|
||||
}
|
||||
|
||||
function SelectSeparator({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Separator>) {
|
||||
return (
|
||||
<SelectPrimitive.Separator
|
||||
data-slot="select-separator"
|
||||
className={cn("bg-border pointer-events-none -mx-1 my-1 h-px", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SelectScrollUpButton({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.ScrollUpButton>) {
|
||||
return (
|
||||
<SelectPrimitive.ScrollUpButton
|
||||
data-slot="select-scroll-up-button"
|
||||
className={cn(
|
||||
"flex cursor-default items-center justify-center py-1",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ChevronUpIcon className="size-4" />
|
||||
</SelectPrimitive.ScrollUpButton>
|
||||
)
|
||||
}
|
||||
|
||||
function SelectScrollDownButton({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.ScrollDownButton>) {
|
||||
return (
|
||||
<SelectPrimitive.ScrollDownButton
|
||||
data-slot="select-scroll-down-button"
|
||||
className={cn(
|
||||
"flex cursor-default items-center justify-center py-1",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ChevronDownIcon className="size-4" />
|
||||
</SelectPrimitive.ScrollDownButton>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectGroup,
|
||||
SelectItem,
|
||||
SelectLabel,
|
||||
SelectScrollDownButton,
|
||||
SelectScrollUpButton,
|
||||
SelectSeparator,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import {
|
||||
CircleCheckIcon,
|
||||
InfoIcon,
|
||||
Loader2Icon,
|
||||
OctagonXIcon,
|
||||
TriangleAlertIcon,
|
||||
} from "lucide-react"
|
||||
import { useTheme } from "next-themes"
|
||||
import { Toaster as Sonner, type ToasterProps } from "sonner"
|
||||
|
||||
const Toaster = ({ ...props }: ToasterProps) => {
|
||||
const { theme = "system" } = useTheme()
|
||||
|
||||
return (
|
||||
<Sonner
|
||||
theme={theme as ToasterProps["theme"]}
|
||||
className="toaster group"
|
||||
icons={{
|
||||
success: <CircleCheckIcon className="size-4" />,
|
||||
info: <InfoIcon className="size-4" />,
|
||||
warning: <TriangleAlertIcon className="size-4" />,
|
||||
error: <OctagonXIcon className="size-4" />,
|
||||
loading: <Loader2Icon className="size-4 animate-spin" />,
|
||||
}}
|
||||
toastOptions={{
|
||||
classNames: {
|
||||
success: "border-green-500 bg-green-50 text-green-900 dark:bg-green-950 dark:text-green-100 [&>svg]:text-green-500",
|
||||
error: "border-red-500 bg-red-50 text-red-900 dark:bg-red-950 dark:text-red-100 [&>svg]:text-red-500",
|
||||
warning: "border-yellow-500 bg-yellow-50 text-yellow-900 dark:bg-yellow-950 dark:text-yellow-100 [&>svg]:text-yellow-500",
|
||||
info: "border-blue-500 bg-blue-50 text-blue-900 dark:bg-blue-950 dark:text-blue-100 [&>svg]:text-blue-500",
|
||||
},
|
||||
}}
|
||||
style={
|
||||
{
|
||||
"--normal-bg": "var(--popover)",
|
||||
"--normal-text": "var(--popover-foreground)",
|
||||
"--normal-border": "var(--border)",
|
||||
"--border-radius": "var(--radius)",
|
||||
left: "calc(56px + 1rem)",
|
||||
} as React.CSSProperties
|
||||
}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Toaster }
|
||||
@@ -0,0 +1,15 @@
|
||||
import { Loader2 } from "lucide-react"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Spinner({ className, ...props }: React.ComponentProps<"svg">) {
|
||||
return (
|
||||
<Loader2
|
||||
role="status"
|
||||
aria-label="Loading"
|
||||
className={cn("size-4 animate-spin", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Spinner }
|
||||
@@ -0,0 +1,31 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as SwitchPrimitive from "@radix-ui/react-switch"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Switch({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SwitchPrimitive.Root>) {
|
||||
return (
|
||||
<SwitchPrimitive.Root
|
||||
data-slot="switch"
|
||||
className={cn(
|
||||
"peer data-[state=checked]:bg-primary data-[state=unchecked]:bg-input focus-visible:border-ring focus-visible:ring-ring/50 inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border border-transparent shadow-xs transition-all outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<SwitchPrimitive.Thumb
|
||||
data-slot="switch-thumb"
|
||||
className={cn(
|
||||
"pointer-events-none block size-4 rounded-full shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0 data-[state=checked]:bg-primary-foreground data-[state=unchecked]:bg-background"
|
||||
)}
|
||||
/>
|
||||
</SwitchPrimitive.Root>
|
||||
)
|
||||
}
|
||||
|
||||
export { Switch }
|
||||
@@ -0,0 +1,61 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as TooltipPrimitive from "@radix-ui/react-tooltip"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function TooltipProvider({
|
||||
delayDuration = 0,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TooltipPrimitive.Provider>) {
|
||||
return (
|
||||
<TooltipPrimitive.Provider
|
||||
data-slot="tooltip-provider"
|
||||
delayDuration={delayDuration}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function Tooltip({
|
||||
...props
|
||||
}: React.ComponentProps<typeof TooltipPrimitive.Root>) {
|
||||
return (
|
||||
<TooltipProvider>
|
||||
<TooltipPrimitive.Root data-slot="tooltip" {...props} />
|
||||
</TooltipProvider>
|
||||
)
|
||||
}
|
||||
|
||||
function TooltipTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof TooltipPrimitive.Trigger>) {
|
||||
return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props} />
|
||||
}
|
||||
|
||||
function TooltipContent({
|
||||
className,
|
||||
sideOffset = 0,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TooltipPrimitive.Content>) {
|
||||
return (
|
||||
<TooltipPrimitive.Portal>
|
||||
<TooltipPrimitive.Content
|
||||
data-slot="tooltip-content"
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
"bg-foreground text-background animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<TooltipPrimitive.Arrow className="bg-foreground fill-foreground z-50 size-2.5 translate-y-[calc(-50%-2px)] rotate-45 rounded-[2px]" />
|
||||
</TooltipPrimitive.Content>
|
||||
</TooltipPrimitive.Portal>
|
||||
)
|
||||
}
|
||||
|
||||
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }
|
||||
@@ -0,0 +1,255 @@
|
||||
@import "tailwindcss";
|
||||
@import "tw-animate-css";
|
||||
|
||||
@custom-variant dark (&:is(.dark *));
|
||||
|
||||
@theme inline {
|
||||
--radius-sm: calc(var(--radius) - 4px);
|
||||
--radius-md: calc(var(--radius) - 2px);
|
||||
--radius-lg: var(--radius);
|
||||
--radius-xl: calc(var(--radius) + 4px);
|
||||
--color-background: var(--background);
|
||||
--color-foreground: var(--foreground);
|
||||
--color-card: var(--card);
|
||||
--color-card-foreground: var(--card-foreground);
|
||||
--color-popover: var(--popover);
|
||||
--color-popover-foreground: var(--popover-foreground);
|
||||
--color-primary: var(--primary);
|
||||
--color-primary-foreground: var(--primary-foreground);
|
||||
--color-secondary: var(--secondary);
|
||||
--color-secondary-foreground: var(--secondary-foreground);
|
||||
--color-muted: var(--muted);
|
||||
--color-muted-foreground: var(--muted-foreground);
|
||||
--color-accent: var(--accent);
|
||||
--color-accent-foreground: var(--accent-foreground);
|
||||
--color-destructive: var(--destructive);
|
||||
--color-border: var(--border);
|
||||
--color-input: var(--input);
|
||||
--color-ring: var(--ring);
|
||||
}
|
||||
|
||||
:root {
|
||||
--radius: 0.625rem;
|
||||
--background: oklch(1 0 0);
|
||||
--foreground: oklch(0.145 0 0);
|
||||
--card: oklch(1 0 0);
|
||||
--card-foreground: oklch(0.145 0 0);
|
||||
--popover: oklch(1 0 0);
|
||||
--popover-foreground: oklch(0.145 0 0);
|
||||
--primary: oklch(0.205 0 0);
|
||||
--primary-foreground: oklch(0.985 0 0);
|
||||
--secondary: oklch(0.97 0 0);
|
||||
--secondary-foreground: oklch(0.205 0 0);
|
||||
--muted: oklch(0.97 0 0);
|
||||
--muted-foreground: oklch(0.556 0 0);
|
||||
--accent: oklch(0.97 0 0);
|
||||
--accent-foreground: oklch(0.205 0 0);
|
||||
--destructive: oklch(0.577 0.245 27.325);
|
||||
--border: oklch(0.922 0 0);
|
||||
--input: oklch(0.922 0 0);
|
||||
--ring: oklch(0.708 0 0);
|
||||
}
|
||||
|
||||
.dark {
|
||||
--background: oklch(0.145 0 0);
|
||||
--foreground: oklch(0.985 0 0);
|
||||
--card: oklch(0.205 0 0);
|
||||
--card-foreground: oklch(0.985 0 0);
|
||||
--popover: oklch(0.205 0 0);
|
||||
--popover-foreground: oklch(0.985 0 0);
|
||||
--primary: oklch(0.922 0 0);
|
||||
--primary-foreground: oklch(0.205 0 0);
|
||||
--secondary: oklch(0.269 0 0);
|
||||
--secondary-foreground: oklch(0.985 0 0);
|
||||
--muted: oklch(0.269 0 0);
|
||||
--muted-foreground: oklch(0.708 0 0);
|
||||
--accent: oklch(0.269 0 0);
|
||||
--accent-foreground: oklch(0.985 0 0);
|
||||
--destructive: oklch(0.704 0.191 22.216);
|
||||
--border: oklch(1 0 0 / 10%);
|
||||
--input: oklch(1 0 0 / 15%);
|
||||
--ring: oklch(0.556 0 0);
|
||||
}
|
||||
|
||||
@layer base {
|
||||
* {
|
||||
@apply border-border outline-ring/50;
|
||||
}
|
||||
body {
|
||||
@apply bg-background text-foreground;
|
||||
font-family: "Google Sans Flex", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
|
||||
}
|
||||
code, pre, .font-mono {
|
||||
font-family: "Google Sans Code", ui-monospace, SFMono-Regular, "SF Mono", Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace !important;
|
||||
}
|
||||
}
|
||||
|
||||
@theme inline {
|
||||
--font-mono: "Google Sans Code", ui-monospace, SFMono-Regular, "SF Mono", Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
|
||||
}
|
||||
|
||||
/* Sonner Toast Styling */
|
||||
[data-sonner-toast] {
|
||||
@apply rounded-lg shadow-lg border;
|
||||
}
|
||||
|
||||
[data-sonner-toast][data-type="success"] {
|
||||
@apply bg-green-50 border-green-200 text-green-900;
|
||||
}
|
||||
|
||||
[data-sonner-toast][data-type="success"] [data-icon] {
|
||||
@apply text-green-600;
|
||||
}
|
||||
|
||||
[data-sonner-toast][data-type="error"] {
|
||||
@apply bg-red-50 border-red-200 text-red-900;
|
||||
}
|
||||
|
||||
[data-sonner-toast][data-type="error"] [data-icon] {
|
||||
@apply text-red-600;
|
||||
}
|
||||
|
||||
[data-sonner-toast][data-type="warning"] {
|
||||
@apply bg-yellow-50 border-yellow-200 text-yellow-900;
|
||||
}
|
||||
|
||||
[data-sonner-toast][data-type="warning"] [data-icon] {
|
||||
@apply text-yellow-600;
|
||||
}
|
||||
|
||||
[data-sonner-toast][data-type="info"] {
|
||||
@apply bg-blue-50 border-blue-200 text-blue-900;
|
||||
}
|
||||
|
||||
[data-sonner-toast][data-type="info"] [data-icon] {
|
||||
@apply text-blue-600;
|
||||
}
|
||||
|
||||
/* Ensure description text uses same color as title */
|
||||
[data-sonner-toast] [data-description],
|
||||
[data-sonner-toast] [data-description] * {
|
||||
opacity: 1 !important;
|
||||
}
|
||||
|
||||
/* Specific color for each toast type - match icon color */
|
||||
[data-sonner-toast][data-type="success"] [data-description],
|
||||
[data-sonner-toast][data-type="success"] [data-description] * {
|
||||
color: rgb(22 163 74) !important; /* green-600 - same as icon */
|
||||
}
|
||||
|
||||
[data-sonner-toast][data-type="error"] [data-description],
|
||||
[data-sonner-toast][data-type="error"] [data-description] * {
|
||||
color: rgb(220 38 38) !important; /* red-600 - same as icon */
|
||||
}
|
||||
|
||||
[data-sonner-toast][data-type="warning"] [data-description],
|
||||
[data-sonner-toast][data-type="warning"] [data-description] * {
|
||||
color: rgb(202 138 4) !important; /* yellow-600 - same as icon */
|
||||
}
|
||||
|
||||
[data-sonner-toast][data-type="info"] [data-description],
|
||||
[data-sonner-toast][data-type="info"] [data-description] * {
|
||||
color: rgb(37 99 235) !important; /* blue-600 - same as icon */
|
||||
}
|
||||
|
||||
/* Dark mode - use same icon colors */
|
||||
.dark [data-sonner-toast][data-type="success"] [data-description],
|
||||
.dark [data-sonner-toast][data-type="success"] [data-description] * {
|
||||
color: rgb(22 163 74) !important; /* green-600 */
|
||||
}
|
||||
|
||||
.dark [data-sonner-toast][data-type="error"] [data-description],
|
||||
.dark [data-sonner-toast][data-type="error"] [data-description] * {
|
||||
color: rgb(220 38 38) !important; /* red-600 */
|
||||
}
|
||||
|
||||
.dark [data-sonner-toast][data-type="warning"] [data-description],
|
||||
.dark [data-sonner-toast][data-type="warning"] [data-description] * {
|
||||
color: rgb(202 138 4) !important; /* yellow-600 */
|
||||
}
|
||||
|
||||
.dark [data-sonner-toast][data-type="info"] [data-description],
|
||||
.dark [data-sonner-toast][data-type="info"] [data-description] * {
|
||||
color: rgb(37 99 235) !important; /* blue-600 */
|
||||
}
|
||||
|
||||
/* Dark mode toast styling */
|
||||
.dark [data-sonner-toast][data-type="success"] {
|
||||
@apply bg-green-950 border-green-800 text-green-100;
|
||||
}
|
||||
|
||||
.dark [data-sonner-toast][data-type="success"] [data-icon] {
|
||||
@apply text-green-400;
|
||||
}
|
||||
|
||||
.dark [data-sonner-toast][data-type="error"] {
|
||||
@apply bg-red-950 border-red-800 text-red-100;
|
||||
}
|
||||
|
||||
.dark [data-sonner-toast][data-type="error"] [data-icon] {
|
||||
@apply text-red-400;
|
||||
}
|
||||
|
||||
.dark [data-sonner-toast][data-type="warning"] {
|
||||
@apply bg-yellow-950 border-yellow-800 text-yellow-100;
|
||||
}
|
||||
|
||||
.dark [data-sonner-toast][data-type="warning"] [data-icon] {
|
||||
@apply text-yellow-400;
|
||||
}
|
||||
|
||||
.dark [data-sonner-toast][data-type="info"] {
|
||||
@apply bg-blue-950 border-blue-800 text-blue-100;
|
||||
}
|
||||
|
||||
.dark [data-sonner-toast][data-type="info"] [data-icon] {
|
||||
@apply text-blue-400;
|
||||
}
|
||||
|
||||
/* Custom Scrollbar - mengikuti primary color theme */
|
||||
::-webkit-scrollbar {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-track {
|
||||
background: var(--secondary);
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-thumb {
|
||||
background: var(--primary);
|
||||
border-radius: 4px;
|
||||
opacity: 0.7;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-thumb:hover {
|
||||
background: var(--primary);
|
||||
filter: brightness(1.2);
|
||||
}
|
||||
|
||||
/* Firefox scrollbar support */
|
||||
* {
|
||||
scrollbar-width: thin;
|
||||
scrollbar-color: var(--primary) var(--secondary);
|
||||
}
|
||||
|
||||
/* Custom scrollbar class untuk komponen tertentu */
|
||||
.custom-scrollbar::-webkit-scrollbar {
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
}
|
||||
|
||||
.custom-scrollbar::-webkit-scrollbar-track {
|
||||
background: var(--muted);
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
.custom-scrollbar::-webkit-scrollbar-thumb {
|
||||
background: var(--primary);
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
.custom-scrollbar::-webkit-scrollbar-thumb:hover {
|
||||
filter: brightness(1.2);
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
// Audio utility for toast notifications using Web Audio API
|
||||
|
||||
class AudioManager {
|
||||
private audioContext: AudioContext | null = null;
|
||||
|
||||
private getAudioContext(): AudioContext {
|
||||
if (!this.audioContext) {
|
||||
this.audioContext = new (window.AudioContext || (window as any).webkitAudioContext)();
|
||||
}
|
||||
return this.audioContext;
|
||||
}
|
||||
|
||||
// Generate a simple tone using oscillator
|
||||
private playTone(frequency: number, duration: number, type: OscillatorType = 'sine', volume: number = 0.3) {
|
||||
try {
|
||||
const ctx = this.getAudioContext();
|
||||
const oscillator = ctx.createOscillator();
|
||||
const gainNode = ctx.createGain();
|
||||
|
||||
oscillator.connect(gainNode);
|
||||
gainNode.connect(ctx.destination);
|
||||
|
||||
oscillator.frequency.value = frequency;
|
||||
oscillator.type = type;
|
||||
|
||||
gainNode.gain.setValueAtTime(volume, ctx.currentTime);
|
||||
gainNode.gain.exponentialRampToValueAtTime(0.01, ctx.currentTime + duration);
|
||||
|
||||
oscillator.start(ctx.currentTime);
|
||||
oscillator.stop(ctx.currentTime + duration);
|
||||
} catch (error) {
|
||||
console.error('Error playing audio:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// Success sound - pleasant ascending tones
|
||||
playSuccess() {
|
||||
const ctx = this.getAudioContext();
|
||||
const now = ctx.currentTime;
|
||||
|
||||
// First tone
|
||||
this.playToneAt(523.25, 0.08, 'sine', 0.2, now); // C5
|
||||
// Second tone
|
||||
this.playToneAt(659.25, 0.08, 'sine', 0.2, now + 0.08); // E5
|
||||
// Third tone
|
||||
this.playToneAt(783.99, 0.15, 'sine', 0.25, now + 0.16); // G5
|
||||
}
|
||||
|
||||
// Error sound - descending tones
|
||||
playError() {
|
||||
const ctx = this.getAudioContext();
|
||||
const now = ctx.currentTime;
|
||||
|
||||
// First tone
|
||||
this.playToneAt(392.00, 0.1, 'square', 0.15, now); // G4
|
||||
// Second tone
|
||||
this.playToneAt(329.63, 0.2, 'square', 0.2, now + 0.1); // E4
|
||||
}
|
||||
|
||||
// Warning sound - alternating tones
|
||||
playWarning() {
|
||||
const ctx = this.getAudioContext();
|
||||
const now = ctx.currentTime;
|
||||
|
||||
// First tone
|
||||
this.playToneAt(440.00, 0.1, 'triangle', 0.2, now); // A4
|
||||
// Second tone
|
||||
this.playToneAt(493.88, 0.1, 'triangle', 0.2, now + 0.12); // B4
|
||||
}
|
||||
|
||||
// Info sound - single soft tone
|
||||
playInfo() {
|
||||
this.playTone(523.25, 0.15, 'sine', 0.15); // C5
|
||||
}
|
||||
|
||||
// Helper method to play tone at specific time
|
||||
private playToneAt(frequency: number, duration: number, type: OscillatorType, volume: number, startTime: number) {
|
||||
try {
|
||||
const ctx = this.getAudioContext();
|
||||
const oscillator = ctx.createOscillator();
|
||||
const gainNode = ctx.createGain();
|
||||
|
||||
oscillator.connect(gainNode);
|
||||
gainNode.connect(ctx.destination);
|
||||
|
||||
oscillator.frequency.value = frequency;
|
||||
oscillator.type = type;
|
||||
|
||||
gainNode.gain.setValueAtTime(volume, startTime);
|
||||
gainNode.gain.exponentialRampToValueAtTime(0.01, startTime + duration);
|
||||
|
||||
oscillator.start(startTime);
|
||||
oscillator.stop(startTime + duration);
|
||||
} catch (error) {
|
||||
console.error('Error playing audio:', error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Export singleton instance
|
||||
export const audioManager = new AudioManager();
|
||||
|
||||
// Helper functions for easy use
|
||||
export const playSuccessSound = () => audioManager.playSuccess();
|
||||
export const playErrorSound = () => audioManager.playError();
|
||||
export const playWarningSound = () => audioManager.playWarning();
|
||||
export const playInfoSound = () => audioManager.playInfo();
|
||||
@@ -0,0 +1,237 @@
|
||||
/**
|
||||
* Fetch State Manager
|
||||
* Manages resumable fetch state for large accounts
|
||||
*/
|
||||
|
||||
import type { TwitterResponse, TimelineEntry, AccountInfo } from "@/types/api";
|
||||
|
||||
const FETCH_STATE_KEY = "twitter_fetch_state";
|
||||
const CURSOR_STATE_KEY = "twitter_cursor_state"; // Lightweight cursor-only storage
|
||||
|
||||
export interface FetchState {
|
||||
username: string;
|
||||
cursor: string;
|
||||
timeline: TimelineEntry[];
|
||||
accountInfo: AccountInfo | null;
|
||||
totalFetched: number;
|
||||
completed: boolean;
|
||||
lastUpdated: number;
|
||||
authToken: string; // Encrypted/hashed for security
|
||||
mediaType: string;
|
||||
retweets: boolean;
|
||||
timelineType: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Save current fetch state for resume capability
|
||||
*/
|
||||
export function saveFetchState(state: Partial<FetchState> & { username: string }): void {
|
||||
try {
|
||||
const existing = getFetchState(state.username);
|
||||
const updated: FetchState = {
|
||||
username: state.username,
|
||||
cursor: state.cursor || "",
|
||||
timeline: state.timeline || existing?.timeline || [],
|
||||
accountInfo: state.accountInfo || existing?.accountInfo || null,
|
||||
totalFetched: state.totalFetched ?? existing?.totalFetched ?? 0,
|
||||
completed: state.completed ?? false,
|
||||
lastUpdated: Date.now(),
|
||||
authToken: state.authToken || existing?.authToken || "",
|
||||
mediaType: state.mediaType || existing?.mediaType || "all",
|
||||
retweets: state.retweets ?? existing?.retweets ?? false,
|
||||
timelineType: state.timelineType || existing?.timelineType || "timeline",
|
||||
};
|
||||
|
||||
// Get all states
|
||||
const allStates = getAllFetchStates();
|
||||
allStates[state.username.toLowerCase()] = updated;
|
||||
|
||||
localStorage.setItem(FETCH_STATE_KEY, JSON.stringify(allStates));
|
||||
} catch (error) {
|
||||
console.error("Failed to save fetch state:", error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get fetch state for a specific username
|
||||
*/
|
||||
export function getFetchState(username: string): FetchState | null {
|
||||
try {
|
||||
const allStates = getAllFetchStates();
|
||||
return allStates[username.toLowerCase()] || null;
|
||||
} catch (error) {
|
||||
console.error("Failed to get fetch state:", error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all fetch states
|
||||
*/
|
||||
export function getAllFetchStates(): Record<string, FetchState> {
|
||||
try {
|
||||
const stored = localStorage.getItem(FETCH_STATE_KEY);
|
||||
if (stored) {
|
||||
return JSON.parse(stored);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to parse fetch states:", error);
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if there's a resumable fetch for username
|
||||
*/
|
||||
export function hasResumableFetch(username: string): boolean {
|
||||
const state = getFetchState(username);
|
||||
if (!state) return false;
|
||||
|
||||
// Has cursor and not completed
|
||||
return !!state.cursor && !state.completed && state.timeline.length > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get resumable fetch info for display
|
||||
*/
|
||||
export function getResumableInfo(username: string): {
|
||||
canResume: boolean;
|
||||
mediaCount: number;
|
||||
lastUpdated: Date | null;
|
||||
} {
|
||||
const state = getFetchState(username);
|
||||
if (!state || state.completed || !state.cursor) {
|
||||
return { canResume: false, mediaCount: 0, lastUpdated: null };
|
||||
}
|
||||
|
||||
return {
|
||||
canResume: true,
|
||||
mediaCount: state.timeline.length,
|
||||
lastUpdated: new Date(state.lastUpdated),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear fetch state for username
|
||||
*/
|
||||
export function clearFetchState(username: string): void {
|
||||
try {
|
||||
const allStates = getAllFetchStates();
|
||||
delete allStates[username.toLowerCase()];
|
||||
localStorage.setItem(FETCH_STATE_KEY, JSON.stringify(allStates));
|
||||
} catch (error) {
|
||||
console.error("Failed to clear fetch state:", error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear all incomplete fetch states (cleanup)
|
||||
*/
|
||||
export function clearAllIncompleteFetchStates(): void {
|
||||
try {
|
||||
const allStates = getAllFetchStates();
|
||||
const completed: Record<string, FetchState> = {};
|
||||
|
||||
for (const [key, state] of Object.entries(allStates)) {
|
||||
if (state.completed) {
|
||||
completed[key] = state;
|
||||
}
|
||||
}
|
||||
|
||||
localStorage.setItem(FETCH_STATE_KEY, JSON.stringify(completed));
|
||||
} catch (error) {
|
||||
console.error("Failed to clear fetch states:", error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert fetch state to TwitterResponse format
|
||||
*/
|
||||
export function stateToResponse(state: FetchState): TwitterResponse | null {
|
||||
if (!state.accountInfo) return null;
|
||||
|
||||
return {
|
||||
account_info: state.accountInfo,
|
||||
total_urls: state.timeline.length,
|
||||
timeline: state.timeline,
|
||||
metadata: {
|
||||
new_entries: state.timeline.length,
|
||||
page: 0,
|
||||
batch_size: 0,
|
||||
has_more: !state.completed,
|
||||
cursor: state.cursor,
|
||||
completed: state.completed,
|
||||
},
|
||||
cursor: state.cursor,
|
||||
completed: state.completed,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Save cursor only (lightweight, can be called every batch)
|
||||
*/
|
||||
export function saveCursor(username: string, cursor: string): void {
|
||||
try {
|
||||
const allCursors = getAllCursors();
|
||||
allCursors[username.toLowerCase()] = {
|
||||
cursor,
|
||||
lastUpdated: Date.now(),
|
||||
};
|
||||
localStorage.setItem(CURSOR_STATE_KEY, JSON.stringify(allCursors));
|
||||
} catch (error) {
|
||||
console.error("Failed to save cursor:", error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get cursor for username from localStorage (lightweight, synchronous)
|
||||
*/
|
||||
export function getCursor(username: string): string | null {
|
||||
try {
|
||||
const allCursors = getAllCursors();
|
||||
return allCursors[username.toLowerCase()]?.cursor || null;
|
||||
} catch (error) {
|
||||
console.error("Failed to get cursor:", error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all cursors
|
||||
*/
|
||||
function getAllCursors(): Record<string, { cursor: string; lastUpdated: number }> {
|
||||
try {
|
||||
const stored = localStorage.getItem(CURSOR_STATE_KEY);
|
||||
if (stored) {
|
||||
return JSON.parse(stored);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to parse cursors:", error);
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear cursor for username
|
||||
*/
|
||||
export function clearCursor(username: string): void {
|
||||
try {
|
||||
const allCursors = getAllCursors();
|
||||
delete allCursors[username.toLowerCase()];
|
||||
localStorage.setItem(CURSOR_STATE_KEY, JSON.stringify(allCursors));
|
||||
} catch (error) {
|
||||
console.error("Failed to clear cursor:", error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge new timeline entries with existing (deduplicate by tweet_id)
|
||||
*/
|
||||
export function mergeTimelines(
|
||||
existing: TimelineEntry[],
|
||||
newEntries: TimelineEntry[]
|
||||
): TimelineEntry[] {
|
||||
const seenIds = new Set(existing.map((e) => e.tweet_id));
|
||||
const unique = newEntries.filter((e) => !seenIds.has(e.tweet_id));
|
||||
return [...existing, ...unique];
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
export type LogLevel = "info" | "success" | "warning" | "error" | "debug";
|
||||
|
||||
export interface LogEntry {
|
||||
timestamp: Date;
|
||||
level: LogLevel;
|
||||
message: string;
|
||||
}
|
||||
|
||||
class Logger {
|
||||
private logs: LogEntry[] = [];
|
||||
private maxLogs = 500;
|
||||
private listeners: Set<() => void> = new Set();
|
||||
|
||||
private addLog(level: LogLevel, message: string) {
|
||||
const entry: LogEntry = {
|
||||
timestamp: new Date(),
|
||||
level,
|
||||
message: message.toLowerCase(),
|
||||
};
|
||||
this.logs.push(entry);
|
||||
if (this.logs.length > this.maxLogs) {
|
||||
this.logs.shift();
|
||||
}
|
||||
this.notifyListeners();
|
||||
}
|
||||
|
||||
info(message: string) {
|
||||
this.addLog("info", message);
|
||||
}
|
||||
|
||||
success(message: string) {
|
||||
this.addLog("success", message);
|
||||
}
|
||||
|
||||
warning(message: string) {
|
||||
this.addLog("warning", message);
|
||||
}
|
||||
|
||||
error(message: string) {
|
||||
this.addLog("error", message);
|
||||
}
|
||||
|
||||
debug(message: string) {
|
||||
this.addLog("debug", message);
|
||||
}
|
||||
|
||||
getLogs(): LogEntry[] {
|
||||
return [...this.logs];
|
||||
}
|
||||
|
||||
clear() {
|
||||
this.logs = [];
|
||||
this.notifyListeners();
|
||||
}
|
||||
|
||||
subscribe(listener: () => void) {
|
||||
this.listeners.add(listener);
|
||||
return () => this.listeners.delete(listener);
|
||||
}
|
||||
|
||||
private notifyListeners() {
|
||||
this.listeners.forEach((listener) => listener());
|
||||
}
|
||||
}
|
||||
|
||||
export const logger = new Logger();
|
||||
@@ -0,0 +1,59 @@
|
||||
/**
|
||||
* Format a date to relative time string with max 2 units
|
||||
* e.g., "23 hours 32 minutes ago", "1 day 14 hours ago"
|
||||
*/
|
||||
export function formatRelativeTime(date: Date | string | number): string {
|
||||
const now = new Date();
|
||||
const target = new Date(date);
|
||||
const diffMs = now.getTime() - target.getTime();
|
||||
|
||||
if (diffMs < 0) return "just now";
|
||||
|
||||
const seconds = Math.floor(diffMs / 1000);
|
||||
const minutes = Math.floor(seconds / 60);
|
||||
const hours = Math.floor(minutes / 60);
|
||||
const days = Math.floor(hours / 24);
|
||||
const weeks = Math.floor(days / 7);
|
||||
const months = Math.floor(days / 30);
|
||||
const years = Math.floor(days / 365);
|
||||
|
||||
const parts: string[] = [];
|
||||
|
||||
if (years > 0) {
|
||||
parts.push(`${years} ${years === 1 ? "year" : "years"}`);
|
||||
const remainingMonths = Math.floor((days % 365) / 30);
|
||||
if (remainingMonths > 0) {
|
||||
parts.push(`${remainingMonths} ${remainingMonths === 1 ? "month" : "months"}`);
|
||||
}
|
||||
} else if (months > 0) {
|
||||
parts.push(`${months} ${months === 1 ? "month" : "months"}`);
|
||||
const remainingDays = days % 30;
|
||||
if (remainingDays > 0) {
|
||||
parts.push(`${remainingDays} ${remainingDays === 1 ? "day" : "days"}`);
|
||||
}
|
||||
} else if (weeks > 0) {
|
||||
parts.push(`${weeks} ${weeks === 1 ? "week" : "weeks"}`);
|
||||
const remainingDays = days % 7;
|
||||
if (remainingDays > 0) {
|
||||
parts.push(`${remainingDays} ${remainingDays === 1 ? "day" : "days"}`);
|
||||
}
|
||||
} else if (days > 0) {
|
||||
parts.push(`${days} ${days === 1 ? "day" : "days"}`);
|
||||
const remainingHours = hours % 24;
|
||||
if (remainingHours > 0) {
|
||||
parts.push(`${remainingHours} ${remainingHours === 1 ? "hour" : "hours"}`);
|
||||
}
|
||||
} else if (hours > 0) {
|
||||
parts.push(`${hours} ${hours === 1 ? "hour" : "hours"}`);
|
||||
const remainingMinutes = minutes % 60;
|
||||
if (remainingMinutes > 0) {
|
||||
parts.push(`${remainingMinutes} ${remainingMinutes === 1 ? "minute" : "minutes"}`);
|
||||
}
|
||||
} else if (minutes > 0) {
|
||||
parts.push(`${minutes} ${minutes === 1 ? "minute" : "minutes"}`);
|
||||
} else {
|
||||
return "just now";
|
||||
}
|
||||
|
||||
return "Released " + parts.slice(0, 2).join(" ") + " ago";
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
import { GetDefaults } from "../../wailsjs/go/main/App";
|
||||
|
||||
export type FontFamily = "google-sans" | "inter" | "poppins" | "roboto" | "dm-sans" | "plus-jakarta-sans" | "manrope" | "space-grotesk" | "noto-sans" | "nunito-sans" | "figtree" | "raleway" | "public-sans" | "outfit" | "jetbrains-mono" | "geist-sans";
|
||||
export type GifQuality = "fast" | "better";
|
||||
export type GifResolution = "original" | "high" | "medium" | "low";
|
||||
|
||||
export interface Settings {
|
||||
downloadPath: string;
|
||||
theme: string;
|
||||
themeMode: "auto" | "light" | "dark";
|
||||
fontFamily: FontFamily;
|
||||
sfxEnabled: boolean;
|
||||
gifQuality: GifQuality;
|
||||
gifResolution: GifResolution;
|
||||
proxy: string; // Proxy URL (e.g., http://proxy:port or socks5://proxy:port). Empty to use system proxy or no proxy.
|
||||
fetchTimeout: number; // Fetch timeout in seconds. Default: 60 seconds.
|
||||
}
|
||||
|
||||
export const DEFAULT_SETTINGS: Settings = {
|
||||
downloadPath: "",
|
||||
theme: "yellow",
|
||||
themeMode: "auto",
|
||||
fontFamily: "google-sans",
|
||||
sfxEnabled: true,
|
||||
gifQuality: "fast",
|
||||
gifResolution: "original",
|
||||
proxy: "",
|
||||
fetchTimeout: 60, // Default: 60 seconds
|
||||
};
|
||||
|
||||
export const FONT_OPTIONS: { value: FontFamily; label: string; fontFamily: string }[] = [
|
||||
{ value: "dm-sans", label: "DM Sans", fontFamily: '"DM Sans", system-ui, sans-serif' },
|
||||
{ value: "figtree", label: "Figtree", fontFamily: '"Figtree", system-ui, sans-serif' },
|
||||
{ value: "geist-sans", label: "Geist Sans", fontFamily: '"Geist", system-ui, sans-serif' },
|
||||
{ value: "google-sans", label: "Google Sans Flex", fontFamily: '"Google Sans Flex", system-ui, sans-serif' },
|
||||
{ value: "inter", label: "Inter", fontFamily: '"Inter", system-ui, sans-serif' },
|
||||
{ value: "jetbrains-mono", label: "JetBrains Mono", fontFamily: '"JetBrains Mono", ui-monospace, monospace' },
|
||||
{ value: "manrope", label: "Manrope", fontFamily: '"Manrope", system-ui, sans-serif' },
|
||||
{ value: "noto-sans", label: "Noto Sans", fontFamily: '"Noto Sans", system-ui, sans-serif' },
|
||||
{ value: "nunito-sans", label: "Nunito Sans", fontFamily: '"Nunito Sans", system-ui, sans-serif' },
|
||||
{ value: "outfit", label: "Outfit", fontFamily: '"Outfit", system-ui, sans-serif' },
|
||||
{ value: "plus-jakarta-sans", label: "Plus Jakarta Sans", fontFamily: '"Plus Jakarta Sans", system-ui, sans-serif' },
|
||||
{ value: "poppins", label: "Poppins", fontFamily: '"Poppins", system-ui, sans-serif' },
|
||||
{ value: "public-sans", label: "Public Sans", fontFamily: '"Public Sans", system-ui, sans-serif' },
|
||||
{ value: "raleway", label: "Raleway", fontFamily: '"Raleway", system-ui, sans-serif' },
|
||||
{ value: "roboto", label: "Roboto", fontFamily: '"Roboto", system-ui, sans-serif' },
|
||||
{ value: "space-grotesk", label: "Space Grotesk", fontFamily: '"Space Grotesk", system-ui, sans-serif' },
|
||||
];
|
||||
|
||||
export function applyFont(fontFamily: FontFamily): void {
|
||||
const font = FONT_OPTIONS.find(f => f.value === fontFamily);
|
||||
if (font) {
|
||||
document.documentElement.style.setProperty('--font-sans', font.fontFamily);
|
||||
document.body.style.fontFamily = font.fontFamily;
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchDefaultPath(): Promise<string> {
|
||||
try {
|
||||
const data = await GetDefaults();
|
||||
return data.downloadPath || "";
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch default path:", error);
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
const SETTINGS_KEY = "twitter-media-downloader-settings";
|
||||
|
||||
export function getSettings(): Settings {
|
||||
try {
|
||||
const stored = localStorage.getItem(SETTINGS_KEY);
|
||||
if (stored) {
|
||||
const parsed = JSON.parse(stored);
|
||||
return { ...DEFAULT_SETTINGS, ...parsed };
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to load settings:", error);
|
||||
}
|
||||
return DEFAULT_SETTINGS;
|
||||
}
|
||||
|
||||
export async function getSettingsWithDefaults(): Promise<Settings> {
|
||||
const settings = getSettings();
|
||||
|
||||
// If downloadPath is empty, fetch from backend
|
||||
if (!settings.downloadPath) {
|
||||
settings.downloadPath = await fetchDefaultPath();
|
||||
}
|
||||
|
||||
return settings;
|
||||
}
|
||||
|
||||
export function saveSettings(settings: Settings): void {
|
||||
try {
|
||||
localStorage.setItem(SETTINGS_KEY, JSON.stringify(settings));
|
||||
} catch (error) {
|
||||
console.error("Failed to save settings:", error);
|
||||
}
|
||||
}
|
||||
|
||||
export function updateSettings(partial: Partial<Settings>): Settings {
|
||||
const current = getSettings();
|
||||
const updated = { ...current, ...partial };
|
||||
saveSettings(updated);
|
||||
return updated;
|
||||
}
|
||||
|
||||
export async function resetToDefaultSettings(): Promise<Settings> {
|
||||
const defaultPath = await fetchDefaultPath();
|
||||
const defaultSettings = {
|
||||
...DEFAULT_SETTINGS,
|
||||
downloadPath: defaultPath,
|
||||
};
|
||||
saveSettings(defaultSettings);
|
||||
return defaultSettings;
|
||||
}
|
||||
|
||||
export function applyThemeMode(mode: "auto" | "light" | "dark"): void {
|
||||
if (mode === "auto") {
|
||||
const prefersDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
|
||||
if (prefersDark) {
|
||||
document.documentElement.classList.add("dark");
|
||||
} else {
|
||||
document.documentElement.classList.remove("dark");
|
||||
}
|
||||
} else if (mode === "dark") {
|
||||
document.documentElement.classList.add("dark");
|
||||
} else {
|
||||
document.documentElement.classList.remove("dark");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,290 @@
|
||||
export interface Theme {
|
||||
name: string;
|
||||
label: string;
|
||||
cssVars: {
|
||||
light: Record<string, string>;
|
||||
dark: Record<string, string>;
|
||||
};
|
||||
}
|
||||
|
||||
// Base colors yang sama untuk semua tema (kecuali primary dan primary-foreground)
|
||||
const baseLightColors: Record<string, string> = {
|
||||
background: "oklch(1 0 0)",
|
||||
foreground: "oklch(0.145 0 0)",
|
||||
card: "oklch(1 0 0)",
|
||||
"card-foreground": "oklch(0.145 0 0)",
|
||||
popover: "oklch(1 0 0)",
|
||||
"popover-foreground": "oklch(0.145 0 0)",
|
||||
secondary: "oklch(0.967 0.001 286.375)",
|
||||
"secondary-foreground": "oklch(0.21 0.006 285.885)",
|
||||
muted: "oklch(0.97 0 0)",
|
||||
"muted-foreground": "oklch(0.556 0 0)",
|
||||
accent: "oklch(0.97 0 0)",
|
||||
"accent-foreground": "oklch(0.205 0 0)",
|
||||
destructive: "oklch(0.58 0.22 27)",
|
||||
border: "oklch(0.922 0 0)",
|
||||
input: "oklch(0.922 0 0)",
|
||||
ring: "oklch(0.708 0 0)",
|
||||
};
|
||||
|
||||
const baseDarkColors: Record<string, string> = {
|
||||
background: "oklch(0.145 0 0)",
|
||||
foreground: "oklch(0.985 0 0)",
|
||||
card: "oklch(0.205 0 0)",
|
||||
"card-foreground": "oklch(0.985 0 0)",
|
||||
popover: "oklch(0.205 0 0)",
|
||||
"popover-foreground": "oklch(0.985 0 0)",
|
||||
secondary: "oklch(0.274 0.006 286.033)",
|
||||
"secondary-foreground": "oklch(0.985 0 0)",
|
||||
muted: "oklch(0.269 0 0)",
|
||||
"muted-foreground": "oklch(0.708 0 0)",
|
||||
accent: "oklch(0.371 0 0)",
|
||||
"accent-foreground": "oklch(0.985 0 0)",
|
||||
destructive: "oklch(0.704 0.191 22.216)",
|
||||
border: "oklch(1 0 0 / 10%)",
|
||||
input: "oklch(1 0 0 / 15%)",
|
||||
ring: "oklch(0.556 0 0)",
|
||||
};
|
||||
|
||||
// Primary colors yang berbeda untuk setiap tema
|
||||
interface PrimaryColors {
|
||||
light: {
|
||||
primary: string;
|
||||
"primary-foreground": string;
|
||||
};
|
||||
dark: {
|
||||
primary: string;
|
||||
"primary-foreground": string;
|
||||
};
|
||||
}
|
||||
|
||||
const primaryColors: Record<string, PrimaryColors> = {
|
||||
amber: {
|
||||
light: {
|
||||
primary: "oklch(0.67 0.16 58)",
|
||||
"primary-foreground": "oklch(0.99 0.02 95)",
|
||||
},
|
||||
dark: {
|
||||
primary: "oklch(0.77 0.16 70)",
|
||||
"primary-foreground": "oklch(0.28 0.07 46)",
|
||||
},
|
||||
},
|
||||
blue: {
|
||||
light: {
|
||||
primary: "oklch(0.488 0.243 264.376)",
|
||||
"primary-foreground": "oklch(0.97 0.014 254.604)",
|
||||
},
|
||||
dark: {
|
||||
primary: "oklch(0.42 0.18 266)",
|
||||
"primary-foreground": "oklch(0.97 0.014 254.604)",
|
||||
},
|
||||
},
|
||||
cyan: {
|
||||
light: {
|
||||
primary: "oklch(0.61 0.11 222)",
|
||||
"primary-foreground": "oklch(0.98 0.02 201)",
|
||||
},
|
||||
dark: {
|
||||
primary: "oklch(0.71 0.13 215)",
|
||||
"primary-foreground": "oklch(0.30 0.05 230)",
|
||||
},
|
||||
},
|
||||
emerald: {
|
||||
light: {
|
||||
primary: "oklch(0.60 0.13 163)",
|
||||
"primary-foreground": "oklch(0.98 0.02 166)",
|
||||
},
|
||||
dark: {
|
||||
primary: "oklch(0.70 0.15 162)",
|
||||
"primary-foreground": "oklch(0.26 0.05 173)",
|
||||
},
|
||||
},
|
||||
fuchsia: {
|
||||
light: {
|
||||
primary: "oklch(0.59 0.26 323)",
|
||||
"primary-foreground": "oklch(0.98 0.02 320)",
|
||||
},
|
||||
dark: {
|
||||
primary: "oklch(0.67 0.26 322)",
|
||||
"primary-foreground": "oklch(0.98 0.02 320)",
|
||||
},
|
||||
},
|
||||
green: {
|
||||
light: {
|
||||
primary: "oklch(0.648 0.2 131.684)",
|
||||
"primary-foreground": "oklch(0.986 0.031 120.757)",
|
||||
},
|
||||
dark: {
|
||||
primary: "oklch(0.648 0.2 131.684)",
|
||||
"primary-foreground": "oklch(0.986 0.031 120.757)",
|
||||
},
|
||||
},
|
||||
indigo: {
|
||||
light: {
|
||||
primary: "oklch(0.51 0.23 277)",
|
||||
"primary-foreground": "oklch(0.96 0.02 272)",
|
||||
},
|
||||
dark: {
|
||||
primary: "oklch(0.59 0.20 277)",
|
||||
"primary-foreground": "oklch(0.96 0.02 272)",
|
||||
},
|
||||
},
|
||||
lime: {
|
||||
light: {
|
||||
primary: "oklch(0.65 0.18 132)",
|
||||
"primary-foreground": "oklch(0.99 0.03 121)",
|
||||
},
|
||||
dark: {
|
||||
primary: "oklch(0.77 0.20 131)",
|
||||
"primary-foreground": "oklch(0.27 0.07 132)",
|
||||
},
|
||||
},
|
||||
neutral: {
|
||||
light: {
|
||||
primary: "oklch(0.205 0 0)",
|
||||
"primary-foreground": "oklch(0.985 0 0)",
|
||||
},
|
||||
dark: {
|
||||
primary: "oklch(0.922 0 0)",
|
||||
"primary-foreground": "oklch(0.205 0 0)",
|
||||
},
|
||||
},
|
||||
orange: {
|
||||
light: {
|
||||
primary: "oklch(0.646 0.222 41.116)",
|
||||
"primary-foreground": "oklch(0.98 0.016 73.684)",
|
||||
},
|
||||
dark: {
|
||||
primary: "oklch(0.705 0.213 47.604)",
|
||||
"primary-foreground": "oklch(0.98 0.016 73.684)",
|
||||
},
|
||||
},
|
||||
pink: {
|
||||
light: {
|
||||
primary: "oklch(0.59 0.22 1)",
|
||||
"primary-foreground": "oklch(0.97 0.01 343)",
|
||||
},
|
||||
dark: {
|
||||
primary: "oklch(0.66 0.21 354)",
|
||||
"primary-foreground": "oklch(0.97 0.01 343)",
|
||||
},
|
||||
},
|
||||
purple: {
|
||||
light: {
|
||||
primary: "oklch(0.56 0.25 302)",
|
||||
"primary-foreground": "oklch(0.98 0.01 308)",
|
||||
},
|
||||
dark: {
|
||||
primary: "oklch(0.63 0.23 304)",
|
||||
"primary-foreground": "oklch(0.98 0.01 308)",
|
||||
},
|
||||
},
|
||||
red: {
|
||||
light: {
|
||||
primary: "oklch(0.577 0.245 27.325)",
|
||||
"primary-foreground": "oklch(0.971 0.013 17.38)",
|
||||
},
|
||||
dark: {
|
||||
primary: "oklch(0.637 0.237 25.331)",
|
||||
"primary-foreground": "oklch(0.971 0.013 17.38)",
|
||||
},
|
||||
},
|
||||
rose: {
|
||||
light: {
|
||||
primary: "oklch(0.586 0.253 17.585)",
|
||||
"primary-foreground": "oklch(0.969 0.015 12.422)",
|
||||
},
|
||||
dark: {
|
||||
primary: "oklch(0.645 0.246 16.439)",
|
||||
"primary-foreground": "oklch(0.969 0.015 12.422)",
|
||||
},
|
||||
},
|
||||
sky: {
|
||||
light: {
|
||||
primary: "oklch(0.59 0.14 242)",
|
||||
"primary-foreground": "oklch(0.98 0.01 237)",
|
||||
},
|
||||
dark: {
|
||||
primary: "oklch(0.68 0.15 237)",
|
||||
"primary-foreground": "oklch(0.29 0.06 243)",
|
||||
},
|
||||
},
|
||||
teal: {
|
||||
light: {
|
||||
primary: "oklch(0.60 0.10 185)",
|
||||
"primary-foreground": "oklch(0.98 0.01 181)",
|
||||
},
|
||||
dark: {
|
||||
primary: "oklch(0.70 0.12 183)",
|
||||
"primary-foreground": "oklch(0.28 0.04 193)",
|
||||
},
|
||||
},
|
||||
violet: {
|
||||
light: {
|
||||
primary: "oklch(0.541 0.281 293.009)",
|
||||
"primary-foreground": "oklch(0.969 0.016 293.756)",
|
||||
},
|
||||
dark: {
|
||||
primary: "oklch(0.606 0.25 292.717)",
|
||||
"primary-foreground": "oklch(0.969 0.016 293.756)",
|
||||
},
|
||||
},
|
||||
yellow: {
|
||||
light: {
|
||||
primary: "oklch(0.852 0.199 91.936)",
|
||||
"primary-foreground": "oklch(0.421 0.095 57.708)",
|
||||
},
|
||||
dark: {
|
||||
primary: "oklch(0.795 0.184 86.047)",
|
||||
"primary-foreground": "oklch(0.421 0.095 57.708)",
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
// Helper function untuk menggabungkan base colors dengan primary colors
|
||||
function createTheme(
|
||||
name: string,
|
||||
label: string,
|
||||
primary: PrimaryColors
|
||||
): Theme {
|
||||
return {
|
||||
name,
|
||||
label,
|
||||
cssVars: {
|
||||
light: { ...baseLightColors, ...primary.light },
|
||||
dark: { ...baseDarkColors, ...primary.dark },
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export const themes: Theme[] = [
|
||||
createTheme("amber", "Amber", primaryColors.amber),
|
||||
createTheme("blue", "Blue", primaryColors.blue),
|
||||
createTheme("cyan", "Cyan", primaryColors.cyan),
|
||||
createTheme("emerald", "Emerald", primaryColors.emerald),
|
||||
createTheme("fuchsia", "Fuchsia", primaryColors.fuchsia),
|
||||
createTheme("green", "Green", primaryColors.green),
|
||||
createTheme("indigo", "Indigo", primaryColors.indigo),
|
||||
createTheme("lime", "Lime", primaryColors.lime),
|
||||
createTheme("neutral", "Neutral", primaryColors.neutral),
|
||||
createTheme("orange", "Orange", primaryColors.orange),
|
||||
createTheme("pink", "Pink", primaryColors.pink),
|
||||
createTheme("purple", "Purple", primaryColors.purple),
|
||||
createTheme("red", "Red", primaryColors.red),
|
||||
createTheme("rose", "Rose", primaryColors.rose),
|
||||
createTheme("sky", "Sky", primaryColors.sky),
|
||||
createTheme("teal", "Teal", primaryColors.teal),
|
||||
createTheme("violet", "Violet", primaryColors.violet),
|
||||
createTheme("yellow", "Yellow", primaryColors.yellow),
|
||||
].sort((a, b) => a.name.localeCompare(b.name));
|
||||
|
||||
export function applyTheme(themeName: string) {
|
||||
const theme = themes.find((t) => t.name === themeName) || themes[0];
|
||||
const root = document.documentElement;
|
||||
const isDark = root.classList.contains("dark");
|
||||
const vars = isDark ? theme.cssVars.dark : theme.cssVars.light;
|
||||
|
||||
Object.entries(vars).forEach(([key, value]) => {
|
||||
root.style.setProperty(`--${key}`, value);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import { toast } from "sonner";
|
||||
import {
|
||||
playSuccessSound,
|
||||
playErrorSound,
|
||||
playWarningSound,
|
||||
playInfoSound,
|
||||
} from "./audio";
|
||||
import { logger } from "./logger";
|
||||
import { getSettings } from "./settings";
|
||||
|
||||
const toastStyle = {
|
||||
className: "font-mono lowercase",
|
||||
};
|
||||
|
||||
// Helper to check if SFX is enabled
|
||||
const isSfxEnabled = () => getSettings().sfxEnabled;
|
||||
|
||||
// Wrapper functions for toast with sound effects
|
||||
export const toastWithSound = {
|
||||
success: (message: string, data?: any) => {
|
||||
const msg = message.toLowerCase();
|
||||
logger.success(msg);
|
||||
if (isSfxEnabled()) playSuccessSound();
|
||||
return toast.success(msg, { ...toastStyle, ...data });
|
||||
},
|
||||
|
||||
error: (message: string, data?: any) => {
|
||||
const msg = message.toLowerCase();
|
||||
logger.error(msg);
|
||||
if (isSfxEnabled()) playErrorSound();
|
||||
return toast.error(msg, { ...toastStyle, ...data });
|
||||
},
|
||||
|
||||
warning: (message: string, data?: any) => {
|
||||
const msg = message.toLowerCase();
|
||||
logger.warning(msg);
|
||||
if (isSfxEnabled()) playWarningSound();
|
||||
return toast.warning(msg, { ...toastStyle, ...data });
|
||||
},
|
||||
|
||||
info: (message: string, data?: any) => {
|
||||
const msg = message.toLowerCase();
|
||||
logger.info(msg);
|
||||
if (isSfxEnabled()) playInfoSound();
|
||||
return toast.info(msg, { ...toastStyle, ...data });
|
||||
},
|
||||
|
||||
// Default toast without specific type
|
||||
message: (message: string, data?: any) => {
|
||||
const msg = message.toLowerCase();
|
||||
logger.info(msg);
|
||||
if (isSfxEnabled()) playInfoSound();
|
||||
return toast(msg, { ...toastStyle, ...data });
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,44 @@
|
||||
import { clsx, type ClassValue } from "clsx"
|
||||
import { twMerge } from "tailwind-merge"
|
||||
import { BrowserOpenURL } from "../../wailsjs/runtime/runtime"
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs))
|
||||
}
|
||||
|
||||
export function sanitizePath(input: string, os: string): string {
|
||||
if (os === "Windows") {
|
||||
return input.replace(/[<>:"/\\|?*]/g, "_");
|
||||
}
|
||||
return input.replace(/\//g, "_");
|
||||
}
|
||||
|
||||
export function joinPath(os: string, ...parts: string[]): string {
|
||||
const sep = os === "Windows" ? "\\" : "/";
|
||||
|
||||
const filtered = parts.filter(Boolean);
|
||||
if (filtered.length === 0) return "";
|
||||
|
||||
const joined = filtered
|
||||
.map((p, i) => {
|
||||
if (i === 0) {
|
||||
return p.replace(/[/\\]+$/g, "");
|
||||
}
|
||||
return p.replace(/^[/\\]+|[/\\]+$/g, "");
|
||||
})
|
||||
.filter(Boolean)
|
||||
.join(sep);
|
||||
|
||||
return joined;
|
||||
}
|
||||
|
||||
export function openExternal(url: string) {
|
||||
if (!url) return;
|
||||
try {
|
||||
BrowserOpenURL(url);
|
||||
} catch (error) {
|
||||
if (typeof window !== "undefined") {
|
||||
window.open(url, "_blank", "noopener,noreferrer");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { StrictMode } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import "./index.css";
|
||||
import App from "./App.tsx";
|
||||
import { Toaster } from "@/components/ui/sonner";
|
||||
|
||||
createRoot(document.getElementById("root")!).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
<Toaster position="bottom-left" duration={1000} />
|
||||
</StrictMode>
|
||||
);
|
||||
@@ -0,0 +1,78 @@
|
||||
// Twitter/X Media Batch Downloader Types
|
||||
|
||||
export interface AccountInfo {
|
||||
name: string; // username/handle from extractor
|
||||
nick: string; // display name from extractor
|
||||
date: string;
|
||||
followers_count: number;
|
||||
friends_count: number;
|
||||
profile_image: string;
|
||||
statuses_count: number;
|
||||
}
|
||||
|
||||
export interface TimelineEntry {
|
||||
url: string;
|
||||
date: string;
|
||||
tweet_id: string;
|
||||
type: string; // photo, video, gif, text
|
||||
is_retweet: boolean;
|
||||
extension: string;
|
||||
width: number;
|
||||
height: number;
|
||||
content?: string;
|
||||
view_count?: number;
|
||||
bookmark_count?: number;
|
||||
favorite_count?: number;
|
||||
retweet_count?: number;
|
||||
reply_count?: number;
|
||||
source?: string;
|
||||
verified?: boolean;
|
||||
original_filename?: string; // Original filename from API
|
||||
author_username?: string; // Username of tweet author (for bookmarks and likes)
|
||||
}
|
||||
|
||||
export interface ExtractMetadata {
|
||||
new_entries: number;
|
||||
page: number;
|
||||
batch_size: number;
|
||||
has_more: boolean;
|
||||
cursor?: string; // Cursor for resume capability
|
||||
completed?: boolean; // True if all media fetched
|
||||
}
|
||||
|
||||
export interface TwitterResponse {
|
||||
account_info: AccountInfo;
|
||||
total_urls: number;
|
||||
timeline: TimelineEntry[];
|
||||
metadata: ExtractMetadata;
|
||||
cursor?: string; // Cursor for next fetch (from CLI)
|
||||
completed?: boolean; // True if fetch completed
|
||||
}
|
||||
|
||||
export interface TimelineRequest {
|
||||
username: string;
|
||||
auth_token: string;
|
||||
timeline_type: string; // media, timeline, tweets, with_replies, likes
|
||||
batch_size: number;
|
||||
page: number;
|
||||
media_type: string; // all, image, video, gif
|
||||
retweets: boolean;
|
||||
cursor?: string; // Resume from this cursor position
|
||||
}
|
||||
|
||||
export interface DateRangeRequest {
|
||||
username: string;
|
||||
auth_token: string;
|
||||
start_date: string; // YYYY-MM-DD
|
||||
end_date: string; // YYYY-MM-DD
|
||||
media_filter: string;
|
||||
retweets: boolean;
|
||||
}
|
||||
|
||||
// Settings types
|
||||
export interface Settings {
|
||||
downloadPath: string;
|
||||
theme: string;
|
||||
themeMode: "auto" | "light" | "dark";
|
||||
sfxEnabled: boolean;
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
|
||||
"target": "ES2022",
|
||||
"useDefineForClassFields": true,
|
||||
"lib": ["ES2022", "DOM", "DOM.Iterable"],
|
||||
"module": "ESNext",
|
||||
"types": ["vite/client"],
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx",
|
||||
|
||||
/* Linting */
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"erasableSyntaxOnly": false,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"noUncheckedSideEffectImports": true,
|
||||
|
||||
/* Path Mapping */
|
||||
"baseUrl": ".",
|
||||
"paths": {
|
||||
"@/*": [
|
||||
"./src/*"
|
||||
]
|
||||
}
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"files": [],
|
||||
"references": [
|
||||
{ "path": "./tsconfig.app.json" },
|
||||
{ "path": "./tsconfig.node.json" }
|
||||
],
|
||||
"compilerOptions": {
|
||||
"baseUrl": ".",
|
||||
"paths": {
|
||||
"@/*": ["./src/*"]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
|
||||
"target": "ES2023",
|
||||
"lib": ["ES2023"],
|
||||
"module": "ESNext",
|
||||
"types": ["node"],
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
|
||||
/* Linting */
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"noUncheckedSideEffectImports": true
|
||||
},
|
||||
"include": ["vite.config.ts"]
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import path from "path"
|
||||
import tailwindcss from "@tailwindcss/vite"
|
||||
import react from "@vitejs/plugin-react"
|
||||
import { defineConfig } from "vite"
|
||||
|
||||
// https://vite.dev/config/
|
||||
export default defineConfig({
|
||||
plugins: [react(), tailwindcss()],
|
||||
resolve: {
|
||||
alias: {
|
||||
"@": path.resolve(__dirname, "./src"),
|
||||
},
|
||||
},
|
||||
})
|
||||
-154
@@ -1,154 +0,0 @@
|
||||
import re
|
||||
import json
|
||||
from datetime import datetime
|
||||
from gallery_dl.extractor import twitter
|
||||
|
||||
def get_metadata(username, auth_token, timeline_type="timeline", batch_size=0, page=0, media_type="all"):
|
||||
url = f"https://x.com/{username}/{timeline_type}"
|
||||
|
||||
if timeline_type == "media":
|
||||
extractor_class = twitter.TwitterMediaExtractor
|
||||
elif timeline_type == "tweets":
|
||||
extractor_class = twitter.TwitterTweetsExtractor
|
||||
elif timeline_type == "with_replies":
|
||||
extractor_class = twitter.TwitterRepliesExtractor
|
||||
else:
|
||||
extractor_class = twitter.TwitterTimelineExtractor
|
||||
|
||||
match = re.match(extractor_class.pattern, url)
|
||||
if not match:
|
||||
raise ValueError(f"Invalid URL for {timeline_type}: {url}")
|
||||
|
||||
extractor = extractor_class(match)
|
||||
|
||||
config_dict = {
|
||||
"cookies": {
|
||||
"auth_token": auth_token
|
||||
}
|
||||
}
|
||||
|
||||
if batch_size > 0:
|
||||
config_dict["count"] = batch_size
|
||||
|
||||
extractor.config = lambda key, default=None: config_dict.get(key, default)
|
||||
|
||||
extractor.initialize()
|
||||
|
||||
structured_output = {
|
||||
'account_info': {},
|
||||
'total_urls': 0,
|
||||
'timeline': []
|
||||
}
|
||||
|
||||
iterator = iter(extractor)
|
||||
|
||||
if batch_size > 0 and page > 0:
|
||||
items_to_skip = page * batch_size
|
||||
|
||||
if hasattr(extractor, '_cursor') and extractor._cursor:
|
||||
pass
|
||||
else:
|
||||
skipped = 0
|
||||
try:
|
||||
for _ in range(items_to_skip):
|
||||
next(iterator)
|
||||
skipped += 1
|
||||
except StopIteration:
|
||||
pass
|
||||
|
||||
new_timeline_entries = []
|
||||
|
||||
items_to_fetch = batch_size if batch_size > 0 else float('inf')
|
||||
items_fetched = 0
|
||||
|
||||
try:
|
||||
while items_fetched < items_to_fetch:
|
||||
item = next(iterator)
|
||||
items_fetched += 1
|
||||
|
||||
if isinstance(item, tuple) and len(item) >= 3:
|
||||
media_url = item[1]
|
||||
tweet_data = item[2]
|
||||
|
||||
if not structured_output['account_info'] and 'user' in tweet_data:
|
||||
user = tweet_data['user']
|
||||
user_date = user.get('date', '')
|
||||
if isinstance(user_date, datetime):
|
||||
user_date = user_date.strftime("%Y-%m-%d %H:%M:%S")
|
||||
|
||||
structured_output['account_info'] = {
|
||||
'name': user.get('name', ''),
|
||||
'nick': user.get('nick', ''),
|
||||
'date': user_date,
|
||||
'followers_count': user.get('followers_count', 0),
|
||||
'friends_count': user.get('friends_count', 0),
|
||||
'profile_image': user.get('profile_image', ''),
|
||||
'statuses_count': user.get('statuses_count', 0)
|
||||
}
|
||||
|
||||
if 'pbs.twimg.com' in media_url or 'video.twimg.com' in media_url:
|
||||
tweet_date = tweet_data.get('date', datetime.now())
|
||||
if isinstance(tweet_date, datetime):
|
||||
tweet_date = tweet_date.strftime("%Y-%m-%d %H:%M:%S")
|
||||
|
||||
timeline_entry = {
|
||||
'url': media_url,
|
||||
'date': tweet_date,
|
||||
'tweet_id': tweet_data.get('tweet_id', 0),
|
||||
}
|
||||
|
||||
if 'type' in tweet_data:
|
||||
timeline_entry['type'] = tweet_data['type']
|
||||
|
||||
if media_type == 'all' or (
|
||||
(media_type == 'image' and 'pbs.twimg.com' in media_url and tweet_data.get('type') == 'photo') or
|
||||
(media_type == 'video' and 'video.twimg.com' in media_url and tweet_data.get('type') == 'video') or
|
||||
(media_type == 'gif' and 'video.twimg.com' in media_url and tweet_data.get('type') == 'animated_gif')
|
||||
):
|
||||
new_timeline_entries.append(timeline_entry)
|
||||
structured_output['total_urls'] += 1
|
||||
except StopIteration:
|
||||
pass
|
||||
|
||||
structured_output['timeline'].extend(new_timeline_entries)
|
||||
|
||||
cursor_info = None
|
||||
if hasattr(extractor, '_cursor') and extractor._cursor:
|
||||
cursor_info = extractor._cursor
|
||||
|
||||
structured_output['metadata'] = {
|
||||
"new_entries": len(new_timeline_entries),
|
||||
"page": page,
|
||||
"batch_size": batch_size,
|
||||
"has_more": batch_size > 0 and items_fetched == batch_size,
|
||||
"cursor": cursor_info
|
||||
}
|
||||
|
||||
if not structured_output['account_info']:
|
||||
raise ValueError("Failed to fetch account information. Please check the username and auth token.")
|
||||
|
||||
return structured_output
|
||||
|
||||
def main():
|
||||
username = ""
|
||||
auth_token = ""
|
||||
timeline_type = "media"
|
||||
batch_size = 100
|
||||
page = 0
|
||||
media_type = "all"
|
||||
|
||||
try:
|
||||
data = get_metadata(
|
||||
username=username,
|
||||
auth_token=auth_token,
|
||||
timeline_type=timeline_type,
|
||||
batch_size=batch_size,
|
||||
page=page,
|
||||
media_type=media_type
|
||||
)
|
||||
print(json.dumps(data, ensure_ascii=False, indent=2))
|
||||
except Exception as e:
|
||||
print(json.dumps({"error": str(e)}, ensure_ascii=False))
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,39 @@
|
||||
module twitterxmediabatchdownloader
|
||||
|
||||
go 1.25.4
|
||||
|
||||
require (
|
||||
github.com/mattn/go-sqlite3 v1.14.32
|
||||
github.com/ulikunitz/xz v0.5.15
|
||||
github.com/wailsapp/wails/v2 v2.11.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/bep/debounce v1.2.1 // indirect
|
||||
github.com/go-ole/go-ole v1.3.0 // indirect
|
||||
github.com/godbus/dbus/v5 v5.2.0 // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/gorilla/websocket v1.5.3 // indirect
|
||||
github.com/jchv/go-winloader v0.0.0-20250406163304-c1995be93bd1 // indirect
|
||||
github.com/labstack/echo/v4 v4.13.4 // indirect
|
||||
github.com/labstack/gommon v0.4.2 // indirect
|
||||
github.com/leaanthony/go-ansi-parser v1.6.1 // indirect
|
||||
github.com/leaanthony/gosod v1.0.4 // indirect
|
||||
github.com/leaanthony/slicer v1.6.0 // indirect
|
||||
github.com/leaanthony/u v1.1.1 // indirect
|
||||
github.com/mattn/go-colorable v0.1.14 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect
|
||||
github.com/pkg/errors v0.9.1 // indirect
|
||||
github.com/rivo/uniseg v0.4.7 // indirect
|
||||
github.com/samber/lo v1.52.0 // indirect
|
||||
github.com/tkrajina/go-reflector v0.5.8 // indirect
|
||||
github.com/valyala/bytebufferpool v1.0.0 // indirect
|
||||
github.com/valyala/fasttemplate v1.2.2 // indirect
|
||||
github.com/wailsapp/go-webview2 v1.0.23 // indirect
|
||||
github.com/wailsapp/mimetype v1.4.1 // indirect
|
||||
golang.org/x/crypto v0.45.0 // indirect
|
||||
golang.org/x/net v0.47.0 // indirect
|
||||
golang.org/x/sys v0.38.0 // indirect
|
||||
golang.org/x/text v0.31.0 // indirect
|
||||
)
|
||||
@@ -0,0 +1,83 @@
|
||||
github.com/bep/debounce v1.2.1 h1:v67fRdBA9UQu2NhLFXrSg0Brw7CexQekrBwDMM8bzeY=
|
||||
github.com/bep/debounce v1.2.1/go.mod h1:H8yggRPQKLUhUoqrJC1bO2xNya7vanpDl7xR3ISbCJ0=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE=
|
||||
github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78=
|
||||
github.com/godbus/dbus/v5 v5.2.0 h1:3WexO+U+yg9T70v9FdHr9kCxYlazaAXUhx2VMkbfax8=
|
||||
github.com/godbus/dbus/v5 v5.2.0/go.mod h1:3AAv2+hPq5rdnr5txxxRwiGjPXamgoIHgz9FPBfOp3c=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
||||
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||
github.com/jchv/go-winloader v0.0.0-20250406163304-c1995be93bd1 h1:njuLRcjAuMKr7kI3D85AXWkw6/+v9PwtV6M6o11sWHQ=
|
||||
github.com/jchv/go-winloader v0.0.0-20250406163304-c1995be93bd1/go.mod h1:alcuEEnZsY1WQsagKhZDsoPCRoOijYqhZvPwLG0kzVs=
|
||||
github.com/labstack/echo/v4 v4.13.4 h1:oTZZW+T3s9gAu5L8vmzihV7/lkXGZuITzTQkTEhcXEA=
|
||||
github.com/labstack/echo/v4 v4.13.4/go.mod h1:g63b33BZ5vZzcIUF8AtRH40DrTlXnx4UMC8rBdndmjQ=
|
||||
github.com/labstack/gommon v0.4.2 h1:F8qTUNXgG1+6WQmqoUWnz8WiEU60mXVVw0P4ht1WRA0=
|
||||
github.com/labstack/gommon v0.4.2/go.mod h1:QlUFxVM+SNXhDL/Z7YhocGIBYOiwB0mXm1+1bAPHPyU=
|
||||
github.com/leaanthony/debme v1.2.1 h1:9Tgwf+kjcrbMQ4WnPcEIUcQuIZYqdWftzZkBr+i/oOc=
|
||||
github.com/leaanthony/debme v1.2.1/go.mod h1:3V+sCm5tYAgQymvSOfYQ5Xx2JCr+OXiD9Jkw3otUjiA=
|
||||
github.com/leaanthony/go-ansi-parser v1.6.1 h1:xd8bzARK3dErqkPFtoF9F3/HgN8UQk0ed1YDKpEz01A=
|
||||
github.com/leaanthony/go-ansi-parser v1.6.1/go.mod h1:+vva/2y4alzVmmIEpk9QDhA7vLC5zKDTRwfZGOp3IWU=
|
||||
github.com/leaanthony/gosod v1.0.4 h1:YLAbVyd591MRffDgxUOU1NwLhT9T1/YiwjKZpkNFeaI=
|
||||
github.com/leaanthony/gosod v1.0.4/go.mod h1:GKuIL0zzPj3O1SdWQOdgURSuhkF+Urizzxh26t9f1cw=
|
||||
github.com/leaanthony/slicer v1.6.0 h1:1RFP5uiPJvT93TAHi+ipd3NACobkW53yUiBqZheE/Js=
|
||||
github.com/leaanthony/slicer v1.6.0/go.mod h1:o/Iz29g7LN0GqH3aMjWAe90381nyZlDNquK+mtH2Fj8=
|
||||
github.com/leaanthony/u v1.1.1 h1:TUFjwDGlNX+WuwVEzDqQwC2lOv0P4uhTQw7CMFdiK7M=
|
||||
github.com/leaanthony/u v1.1.1/go.mod h1:9+o6hejoRljvZ3BzdYlVL0JYCwtnAsVuN9pVTQcaRfI=
|
||||
github.com/matryer/is v1.4.0/go.mod h1:8I/i5uYgLzgsgEloJE1U6xx5HkBQpAZvepWuujKwMRU=
|
||||
github.com/matryer/is v1.4.1 h1:55ehd8zaGABKLXQUe2awZ99BD/PTc2ls+KV/dXphgEQ=
|
||||
github.com/matryer/is v1.4.1/go.mod h1:8I/i5uYgLzgsgEloJE1U6xx5HkBQpAZvepWuujKwMRU=
|
||||
github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=
|
||||
github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/mattn/go-sqlite3 v1.14.32 h1:JD12Ag3oLy1zQA+BNn74xRgaBbdhbNIDYvQUEuuErjs=
|
||||
github.com/mattn/go-sqlite3 v1.14.32/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
|
||||
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ=
|
||||
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU=
|
||||
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
|
||||
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
|
||||
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
|
||||
github.com/samber/lo v1.52.0 h1:Rvi+3BFHES3A8meP33VPAxiBZX/Aws5RxrschYGjomw=
|
||||
github.com/samber/lo v1.52.0/go.mod h1:4+MXEGsJzbKGaUEQFKBq2xtfuznW9oz/WrgyzMzRoM0=
|
||||
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
|
||||
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||
github.com/tkrajina/go-reflector v0.5.8 h1:yPADHrwmUbMq4RGEyaOUpz2H90sRsETNVpjzo3DLVQQ=
|
||||
github.com/tkrajina/go-reflector v0.5.8/go.mod h1:ECbqLgccecY5kPmPmXg1MrHW585yMcDkVl6IvJe64T4=
|
||||
github.com/ulikunitz/xz v0.5.15 h1:9DNdB5s+SgV3bQ2ApL10xRc35ck0DuIX/isZvIk+ubY=
|
||||
github.com/ulikunitz/xz v0.5.15/go.mod h1:nbz6k7qbPmH4IRqmfOplQw/tblSgqTqBwxkY0oWt/14=
|
||||
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
|
||||
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
|
||||
github.com/valyala/fasttemplate v1.2.2 h1:lxLXG0uE3Qnshl9QyaK6XJxMXlQZELvChBOCmQD0Loo=
|
||||
github.com/valyala/fasttemplate v1.2.2/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ=
|
||||
github.com/wailsapp/go-webview2 v1.0.23 h1:jmv8qhz1lHibCc79bMM/a/FqOnnzOGEisLav+a0b9P0=
|
||||
github.com/wailsapp/go-webview2 v1.0.23/go.mod h1:qJmWAmAmaniuKGZPWwne+uor3AHMB5PFhqiK0Bbj8kc=
|
||||
github.com/wailsapp/mimetype v1.4.1 h1:pQN9ycO7uo4vsUUuPeHEYoUkLVkaRntMnHJxVwYhwHs=
|
||||
github.com/wailsapp/mimetype v1.4.1/go.mod h1:9aV5k31bBOv5z6u+QP8TltzvNGJPmNJD4XlAL3U+j3o=
|
||||
github.com/wailsapp/wails/v2 v2.11.0 h1:seLacV8pqupq32IjS4Y7V8ucab0WZwtK6VvUVxSBtqQ=
|
||||
github.com/wailsapp/wails/v2 v2.11.0/go.mod h1:jrf0ZaM6+GBc1wRmXsM8cIvzlg0karYin3erahI4+0k=
|
||||
golang.org/x/crypto v0.45.0 h1:jMBrvKuj23MTlT0bQEOBcAE0mjg8mK9RXFhRH6nyF3Q=
|
||||
golang.org/x/crypto v0.45.0/go.mod h1:XTGrrkGJve7CYK7J8PEww4aY7gM3qMCElcJQ8n8JdX4=
|
||||
golang.org/x/net v0.0.0-20210505024714-0287a6fb4125/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
||||
golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY=
|
||||
golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU=
|
||||
golang.org/x/sys v0.0.0-20200810151505-1b9f1253b3ed/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc=
|
||||
golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.31.0 h1:aC8ghyu4JhP8VojJ2lEHBnochRno1sgL6nEi9WGFGMM=
|
||||
golang.org/x/text v0.31.0/go.mod h1:tKRAlv61yKIjGGHX/4tP1LTbc13YSec1pxVEWXzfoeM=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
@@ -0,0 +1,54 @@
|
||||
# Building Extractor Binary
|
||||
|
||||
This guide explains how to build the `extractor` binary from `twitter_cli.py`.
|
||||
|
||||
## Quick Start - Use Pre-built Binary
|
||||
|
||||
**You don't need to build the binary yourself!** After running the main application once, the pre-built binary is automatically extracted to:
|
||||
|
||||
```
|
||||
Windows: C:\Users\YourUsername\.twitterxmediabatchdownloader\extractor.exe
|
||||
Linux: ~/.twitterxmediabatchdownloader/extractor
|
||||
macOS: ~/.twitterxmediabatchdownloader/extractor
|
||||
```
|
||||
|
||||
You can use this binary directly for CLI operations without rebuilding.
|
||||
|
||||
### Using the Pre-built Binary
|
||||
|
||||
```powershell
|
||||
# Windows
|
||||
C:\Users\YourUsername\.twitterxmediabatchdownloader\extractor.exe https://x.com/username/media --limit 10 --json --guest
|
||||
|
||||
# Linux/macOS
|
||||
~/.twitterxmediabatchdownloader/extractor https://x.com/username/media --limit 10 --json --guest
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Building from Source (Optional)
|
||||
|
||||
If you need to rebuild the binary (e.g., after modifying `twitter_cli.py`):
|
||||
|
||||
### Prerequisites
|
||||
|
||||
```bash
|
||||
pip install pyinstaller
|
||||
# or
|
||||
pip install nuitka
|
||||
```
|
||||
|
||||
### Build Commands
|
||||
|
||||
```bash
|
||||
# PyInstaller (faster build, larger file)
|
||||
pyinstaller --onefile --name extractor --collect-all gallery_dl twitter_cli.py
|
||||
|
||||
# Nuitka (slower build, better performance, smaller file)
|
||||
python -m nuitka --onefile --output-filename=extractor.exe --include-package=gallery_dl --include-package-data=gallery_dl twitter_cli.py
|
||||
```
|
||||
|
||||
### Output Location
|
||||
|
||||
- PyInstaller: `dist/extractor` or `dist/extractor.exe`
|
||||
- Nuitka: `extractor` or `extractor.exe` (in current directory)
|
||||
+275
@@ -0,0 +1,275 @@
|
||||
# Usage Guide
|
||||
|
||||
CLI tool for extracting media and metadata from Twitter/X using gallery-dl extractor.
|
||||
|
||||
## Command Line Arguments
|
||||
|
||||
### Required
|
||||
- `url` — Twitter/X URL (timeline, media, likes, search, etc.)
|
||||
- `--auth-token TOKEN` — Your auth_token cookie value (required)
|
||||
|
||||
### Content Options
|
||||
- `--retweets {skip|include|original}` — Control retweets (default: skip)
|
||||
- `--no-videos` — Skip video downloads
|
||||
- `--text-tweets` — Include tweets without media
|
||||
- `--type {photo|video|animated_gif|all}` — Filter by media type (default: all)
|
||||
|
||||
### Quality & Format
|
||||
- `--size SIZE` — Image size: `orig`, `4096x4096`, `large`, `medium`, `small` (default: orig)
|
||||
|
||||
### Fetch Control
|
||||
- `--limit N` — Maximum media items to fetch (0 = unlimited)
|
||||
- `--cursor CURSOR` — Resume from specific cursor position
|
||||
|
||||
### Output Options
|
||||
- `--json` — Output results as JSON
|
||||
- `--metadata` — Include tweet metadata (author, counts, etc.)
|
||||
- `--output FILE` / `-o FILE` — Save to JSON file with resume capability
|
||||
- `--resume FILE` / `-r FILE` — Resume from previous JSON file
|
||||
- `--progress` — Show progress during fetch
|
||||
|
||||
### Advanced
|
||||
- `--set KEY=VALUE` — Set gallery-dl extractor options (repeatable)
|
||||
- `-v` / `--verbose` — Show detailed metadata during fetch
|
||||
|
||||
---
|
||||
|
||||
## Usage Examples
|
||||
|
||||
### Basic Fetch
|
||||
|
||||
```powershell
|
||||
# Fetch media with authentication
|
||||
python twitter_cli.py https://x.com/username/media --limit 10 --json --auth-token YOUR_TOKEN
|
||||
```
|
||||
|
||||
### Media Type Filtering
|
||||
|
||||
```powershell
|
||||
# Photos only
|
||||
python twitter_cli.py https://x.com/username/media --type photo --json --auth-token YOUR_TOKEN
|
||||
|
||||
# Videos only
|
||||
python twitter_cli.py https://x.com/username/media --type video --json --auth-token YOUR_TOKEN
|
||||
|
||||
# Animated GIFs only
|
||||
python twitter_cli.py https://x.com/username/media --type animated_gif --json --auth-token YOUR_TOKEN
|
||||
```
|
||||
|
||||
### With Metadata
|
||||
|
||||
```powershell
|
||||
# Include tweet metadata (author, date, counts)
|
||||
python twitter_cli.py https://x.com/username/media --limit 5 --json --metadata --auth-token YOUR_TOKEN
|
||||
```
|
||||
|
||||
### Retweets Control
|
||||
|
||||
```powershell
|
||||
# Skip retweets (default)
|
||||
python twitter_cli.py https://x.com/username/timeline --retweets skip --json --auth-token YOUR_TOKEN
|
||||
|
||||
# Include retweets
|
||||
python twitter_cli.py https://x.com/username/timeline --retweets include --json --auth-token YOUR_TOKEN
|
||||
|
||||
# Get original tweet from retweets
|
||||
python twitter_cli.py https://x.com/username/timeline --retweets original --json --auth-token YOUR_TOKEN
|
||||
```
|
||||
|
||||
### Save & Resume
|
||||
|
||||
```powershell
|
||||
# Save to file (with resume capability)
|
||||
python twitter_cli.py https://x.com/username/media --limit 100 --output results.json --progress --auth-token YOUR_TOKEN
|
||||
|
||||
# Resume from saved file
|
||||
python twitter_cli.py https://x.com/username/media --resume results.json --limit 100 --output results.json --auth-token YOUR_TOKEN
|
||||
|
||||
# Fetch all remaining
|
||||
python twitter_cli.py https://x.com/username/media --resume results.json --limit 0 --output results.json --auth-token YOUR_TOKEN
|
||||
```
|
||||
|
||||
### Private Content
|
||||
|
||||
```powershell
|
||||
# Your likes
|
||||
python twitter_cli.py https://x.com/username/likes --limit 20 --json --auth-token YOUR_TOKEN
|
||||
|
||||
# Your bookmarks
|
||||
python twitter_cli.py https://x.com/i/bookmarks --limit 20 --json --auth-token YOUR_TOKEN
|
||||
```
|
||||
|
||||
### Search
|
||||
|
||||
```powershell
|
||||
# Search with filters
|
||||
python twitter_cli.py "https://x.com/search?q=from:username filter:media" --limit 50 --json --auth-token YOUR_TOKEN
|
||||
|
||||
# Date range search
|
||||
python twitter_cli.py "https://x.com/search?q=from:username since:2024-01-01 until:2024-12-31" --json --auth-token YOUR_TOKEN
|
||||
```
|
||||
|
||||
### Advanced Filtering
|
||||
|
||||
```powershell
|
||||
# Filter by date (2024 only)
|
||||
python twitter_cli.py https://x.com/username/media --json --metadata --set filter="date.year == 2024" --auth-token YOUR_TOKEN
|
||||
|
||||
# Filter by engagement (>1000 likes)
|
||||
python twitter_cli.py https://x.com/username/media --json --metadata --set filter="favorite_count > 1000" --auth-token YOUR_TOKEN
|
||||
|
||||
# Combine filters (photos from 2024 with >100 likes)
|
||||
python twitter_cli.py https://x.com/username/media --type photo --json --metadata --set filter="date.year == 2024 and favorite_count > 100" --auth-token YOUR_TOKEN
|
||||
```
|
||||
|
||||
### Text-Only Tweets
|
||||
|
||||
```powershell
|
||||
# Fetch tweets without media
|
||||
python twitter_cli.py https://x.com/username/tweets --text-tweets --json --metadata --auth-token YOUR_TOKEN
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Output Format
|
||||
|
||||
### JSON Structure
|
||||
|
||||
```json
|
||||
{
|
||||
"media": [
|
||||
{
|
||||
"url": "https://pbs.twimg.com/media/...",
|
||||
"tweet_id": 1234567890,
|
||||
"extension": "jpg",
|
||||
"width": 2048,
|
||||
"height": 1536,
|
||||
"type": "photo"
|
||||
}
|
||||
],
|
||||
"metadata": [
|
||||
{
|
||||
"tweet_id": 1234567890,
|
||||
"date": "2024-01-15T10:30:00+00:00",
|
||||
"author": {
|
||||
"id": 123456,
|
||||
"name": "username",
|
||||
"nick": "Display Name"
|
||||
},
|
||||
"content": "Tweet text content",
|
||||
"favorite_count": 150,
|
||||
"retweet_count": 25,
|
||||
"reply_count": 5,
|
||||
"view_count": 5000
|
||||
}
|
||||
],
|
||||
"cursor": "1/DAABCgABG7OZH1D___0KAAIW...",
|
||||
"total": 100,
|
||||
"completed": false
|
||||
}
|
||||
```
|
||||
|
||||
### Resume File Structure
|
||||
|
||||
When using `--output`, the file includes:
|
||||
- `url` — Original URL
|
||||
- `cursor` — Position for resume
|
||||
- `total` — Total items fetched
|
||||
- `completed` — Whether fetch is complete
|
||||
- `media` — All media items
|
||||
- `metadata` — All metadata (if requested)
|
||||
|
||||
---
|
||||
|
||||
## Pagination & Resume
|
||||
|
||||
### How It Works
|
||||
|
||||
- Twitter API returns ~100-200 items per batch
|
||||
- Cursor tracks position for next fetch
|
||||
- System ensures cursor availability before stopping
|
||||
- Resume continues from exact position (no duplicates)
|
||||
|
||||
### Resume Workflow
|
||||
|
||||
```powershell
|
||||
# Step 1: Initial fetch (saves state)
|
||||
python twitter_cli.py https://x.com/user/media --limit 100 --output data.json --progress --auth-token YOUR_TOKEN
|
||||
# Output: Saved 202 media to data.json [partial (can resume)]
|
||||
|
||||
# Step 2: Resume and fetch more
|
||||
python twitter_cli.py https://x.com/user/media --resume data.json --limit 100 --output data.json --auth-token YOUR_TOKEN
|
||||
# Output: Resuming from cursor, 202 media already fetched
|
||||
# Added 100 new media (total: 302)
|
||||
|
||||
# Step 3: Fetch all remaining
|
||||
python twitter_cli.py https://x.com/user/media --resume data.json --limit 0 --output data.json --auth-token YOUR_TOKEN
|
||||
# Output: Added 244 new media (total: 546) [completed]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Supported URL Patterns
|
||||
|
||||
### User Timelines
|
||||
- `https://x.com/username/media` — Media timeline
|
||||
- `https://x.com/username/timeline` — Full timeline
|
||||
- `https://x.com/username/tweets` — Tweets only
|
||||
- `https://x.com/username/with_replies` — With replies
|
||||
- `https://x.com/username/likes` — Liked tweets
|
||||
|
||||
### Private Content
|
||||
- `https://x.com/i/bookmarks` — Your bookmarks
|
||||
|
||||
### Search
|
||||
- `https://x.com/search?q=QUERY` — Search tweets
|
||||
- `https://x.com/hashtag/NAME` — Hashtag search
|
||||
|
||||
### Individual Tweet
|
||||
- `https://x.com/username/status/1234567890` — Single tweet
|
||||
|
||||
---
|
||||
|
||||
## Search Operators
|
||||
|
||||
Use in search URLs:
|
||||
|
||||
| Operator | Example | Description |
|
||||
|----------|---------|-------------|
|
||||
| `from:USER` | `from:username` | Tweets from user |
|
||||
| `to:USER` | `to:username` | Tweets mentioning user |
|
||||
| `filter:media` | `cats filter:media` | Only with media |
|
||||
| `filter:images` | `cats filter:images` | Only images |
|
||||
| `filter:videos` | `cats filter:videos` | Only videos |
|
||||
| `since:DATE` | `since:2024-01-01` | After date |
|
||||
| `until:DATE` | `until:2024-12-31` | Before date |
|
||||
| `-filter:retweets` | `cats -filter:retweets` | Exclude retweets |
|
||||
| `min_faves:N` | `min_faves:1000` | Min likes |
|
||||
| `min_retweets:N` | `min_retweets:100` | Min retweets |
|
||||
|
||||
---
|
||||
|
||||
## Tips & Tricks
|
||||
|
||||
### 1. Progressive Fetch with Resume
|
||||
```powershell
|
||||
# Fetch in batches to avoid long waits
|
||||
python twitter_cli.py URL --limit 200 --output data.json --progress --auth-token YOUR_TOKEN
|
||||
python twitter_cli.py URL --resume data.json --limit 200 --output data.json --auth-token YOUR_TOKEN
|
||||
```
|
||||
|
||||
### 2. Combine Type Filter with Custom Filter
|
||||
```powershell
|
||||
# Photos from 2024 with high engagement
|
||||
python twitter_cli.py URL --type photo --metadata --set filter="date.year == 2024 and favorite_count > 500" --json --auth-token YOUR_TOKEN
|
||||
```
|
||||
|
||||
### 3. Use Progress Flag for Long Fetches
|
||||
```powershell
|
||||
python twitter_cli.py URL --limit 1000 --progress --output data.json --auth-token YOUR_TOKEN
|
||||
```
|
||||
|
||||
### 4. Check Cursor Availability
|
||||
- If `completed: false` in output → can resume
|
||||
- If `completed: true` → all data fetched
|
||||
- If `cursor: null` → no more data available
|
||||
@@ -0,0 +1,309 @@
|
||||
"""Command-line helper for gallery-dl's Twitter extractor.
|
||||
|
||||
Features:
|
||||
- Cursor-based resume: Use --output to save progress, --resume to continue
|
||||
- Progress tracking: See fetch progress in real-time
|
||||
- Rate limit: Automatically handled by gallery-dl
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from typing import Dict, List, Optional
|
||||
|
||||
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
from twitter_common import ( # type: ignore
|
||||
TwitterRequest,
|
||||
coerce_literal,
|
||||
load_resume_state,
|
||||
merge_options,
|
||||
run_request_dict,
|
||||
save_state,
|
||||
)
|
||||
|
||||
DEFAULT_AUTH_TOKEN = ""
|
||||
|
||||
|
||||
def parse_args() -> argparse.Namespace:
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Light-weight CLI wrapper around gallery-dl's Twitter extractor",
|
||||
)
|
||||
parser.add_argument("url", help="Any supported Twitter/X URL (timeline, media, likes, ...)")
|
||||
parser.add_argument(
|
||||
"--auth-token",
|
||||
default=DEFAULT_AUTH_TOKEN,
|
||||
help="Value of the auth_token cookie (leave empty to skip)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--guest",
|
||||
action="store_true",
|
||||
help="Force guest mode (do not send auth_token)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--retweets",
|
||||
choices=["skip", "include", "original"],
|
||||
default="skip",
|
||||
help="Control retweet handling (skip, include, or swap for originals)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--no-videos",
|
||||
action="store_true",
|
||||
help="Skip video/animated GIF variants",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--size",
|
||||
default="orig",
|
||||
help="Image size to request (orig, 4096x4096, large, ...)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--limit",
|
||||
type=int,
|
||||
default=0,
|
||||
help="Stop after N media files (0 = all)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--json",
|
||||
action="store_true",
|
||||
help="Emit JSON instead of plain URLs",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--metadata",
|
||||
action="store_true",
|
||||
help="Include tweet metadata in output",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--text-tweets",
|
||||
action="store_true",
|
||||
help="Include text tweets (without media)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--type",
|
||||
choices=["photo", "video", "animated_gif", "all"],
|
||||
default="all",
|
||||
help="Filter by media type (photo, video, animated_gif, or all)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--verbose",
|
||||
"-v",
|
||||
action="store_true",
|
||||
help="Echo tweet metadata to stderr while crawling",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--set",
|
||||
metavar="KEY=VALUE",
|
||||
action="append",
|
||||
default=[],
|
||||
help="Add override for extractor.twitter.* options (repeatable)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--output",
|
||||
"-o",
|
||||
metavar="FILE",
|
||||
help="Save results to JSON file (includes cursor for resume)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--resume",
|
||||
"-r",
|
||||
metavar="FILE",
|
||||
help="Resume from previous JSON file (continues from saved cursor)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--cursor",
|
||||
metavar="CURSOR",
|
||||
help="Resume from specific cursor position",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--progress",
|
||||
action="store_true",
|
||||
help="Show progress during fetch",
|
||||
)
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def _retweets_value(mode: str):
|
||||
if mode == "original":
|
||||
return "original"
|
||||
if mode == "include":
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _parse_overrides(entries: List[str]) -> Dict[str, object]:
|
||||
overrides: Dict[str, object] = {}
|
||||
for entry in entries:
|
||||
if "=" not in entry:
|
||||
raise ValueError(f"Format must be KEY=VALUE, got: {entry}")
|
||||
key, raw = entry.split("=", 1)
|
||||
overrides[key.strip()] = coerce_literal(raw.strip())
|
||||
return overrides
|
||||
|
||||
|
||||
def _progress_callback(count: int, cursor: Optional[str]) -> None:
|
||||
"""Print progress to stderr."""
|
||||
cursor_info = f" (cursor: {cursor[:20]}...)" if cursor and len(cursor) > 20 else ""
|
||||
cursor_info = f" (cursor: {cursor})" if cursor and len(cursor) <= 20 else cursor_info
|
||||
print(f"Fetching... {count} media{cursor_info}", file=sys.stderr)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
args = parse_args()
|
||||
|
||||
# Handle resume from file
|
||||
resume_cursor: Optional[str] = None
|
||||
previous_media: List[Dict] = []
|
||||
previous_metadata: List[Dict] = []
|
||||
seen_urls: set = set()
|
||||
url = args.url
|
||||
|
||||
# Convert --type to filter expression
|
||||
type_filter = None
|
||||
if args.type != "all":
|
||||
type_filter = f"type == '{args.type}'"
|
||||
|
||||
if args.resume:
|
||||
state = load_resume_state(args.resume)
|
||||
if state:
|
||||
if state.get("completed"):
|
||||
print(f"Previous fetch already completed ({state.get('total', 0)} media)", file=sys.stderr)
|
||||
print("Use --output to start fresh or remove the file", file=sys.stderr)
|
||||
sys.exit(0)
|
||||
resume_cursor = state.get("cursor")
|
||||
previous_media = state.get("media", [])
|
||||
previous_metadata = state.get("metadata", [])
|
||||
# Track seen URLs to avoid duplicates
|
||||
seen_urls = {m.get("url") for m in previous_media if m.get("url")}
|
||||
url = state.get("url", args.url)
|
||||
|
||||
if resume_cursor:
|
||||
print(f"Resuming from cursor, {len(previous_media)} media already fetched", file=sys.stderr)
|
||||
else:
|
||||
print(f"No cursor available, will deduplicate {len(previous_media)} existing media", file=sys.stderr)
|
||||
else:
|
||||
print(f"Could not load resume file: {args.resume}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
# Manual cursor override
|
||||
if args.cursor:
|
||||
resume_cursor = args.cursor
|
||||
|
||||
include_videos = not args.no_videos
|
||||
auth_token = None if args.guest or not args.auth_token.strip() else args.auth_token
|
||||
|
||||
# Parse user overrides
|
||||
user_overrides = _parse_overrides(args.set)
|
||||
|
||||
# Add type filter if specified (merge with existing filter if any)
|
||||
if type_filter:
|
||||
existing_filter = user_overrides.get("filter")
|
||||
if existing_filter:
|
||||
# Combine with AND
|
||||
user_overrides["filter"] = f"({existing_filter}) and ({type_filter})"
|
||||
else:
|
||||
user_overrides["filter"] = type_filter
|
||||
|
||||
options = merge_options(
|
||||
{
|
||||
"auth_token": auth_token,
|
||||
"retweets": _retweets_value(args.retweets),
|
||||
"videos": include_videos,
|
||||
"size": args.size,
|
||||
"text-tweets": args.text_tweets,
|
||||
},
|
||||
user_overrides,
|
||||
)
|
||||
|
||||
request = TwitterRequest(
|
||||
url=url,
|
||||
limit=args.limit,
|
||||
metadata=(args.metadata or args.verbose),
|
||||
options=options,
|
||||
cursor=resume_cursor,
|
||||
)
|
||||
|
||||
progress_cb = _progress_callback if (args.progress or args.verbose) else None
|
||||
|
||||
# Pass seen_urls for deduplication if no cursor available
|
||||
skip_urls = seen_urls if (not resume_cursor and seen_urls) else None
|
||||
|
||||
try:
|
||||
result = run_request_dict(request, on_progress=progress_cb, skip_urls=skip_urls)
|
||||
except KeyboardInterrupt:
|
||||
print("\nInterrupted by user", file=sys.stderr)
|
||||
sys.exit(130)
|
||||
except Exception as exc:
|
||||
print(f"Error: {exc}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
# Merge with previous results if resuming
|
||||
if previous_media:
|
||||
if resume_cursor:
|
||||
# With cursor: filter duplicates that might occur at boundary
|
||||
new_media = [m for m in result["media"] if m.get("url") not in seen_urls]
|
||||
result["media"] = previous_media + new_media
|
||||
result["metadata"] = previous_metadata + result["metadata"]
|
||||
else:
|
||||
# Without cursor: results already deduplicated via skip_urls
|
||||
result["media"] = previous_media + result["media"]
|
||||
result["metadata"] = previous_metadata + result["metadata"]
|
||||
|
||||
result["total"] = len(result["media"])
|
||||
new_count = result["total"] - len(previous_media)
|
||||
|
||||
if new_count > 0:
|
||||
print(f"Added {new_count} new media (total: {result['total']})", file=sys.stderr)
|
||||
else:
|
||||
print(f"No new media found", file=sys.stderr)
|
||||
|
||||
media = result["media"]
|
||||
metadata = result["metadata"]
|
||||
|
||||
# Save to file if --output specified
|
||||
if args.output:
|
||||
save_state(args.output, result, url)
|
||||
status = "completed" if result.get("completed") else "partial (can resume)"
|
||||
print(f"Saved {len(media)} media to {args.output} [{status}]", file=sys.stderr)
|
||||
if not result.get("completed") and result.get("cursor"):
|
||||
print(f"Resume with: --resume {args.output}", file=sys.stderr)
|
||||
|
||||
if args.verbose:
|
||||
for entry in metadata:
|
||||
author = (entry.get("author") or {}).get("name")
|
||||
print(
|
||||
f"Processing tweet {entry.get('tweet_id')} / {author}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
|
||||
if args.json:
|
||||
payload: Dict[str, object] = {
|
||||
"media": media,
|
||||
"total": len(media),
|
||||
"completed": result.get("completed", True),
|
||||
}
|
||||
if result.get("cursor"):
|
||||
payload["cursor"] = result["cursor"]
|
||||
if args.metadata:
|
||||
payload["metadata"] = metadata
|
||||
print(json.dumps(payload, indent=2, default=str))
|
||||
else:
|
||||
for item in media:
|
||||
print(item["url"])
|
||||
if args.metadata:
|
||||
print("\n# Metadata", file=sys.stderr)
|
||||
for entry in metadata:
|
||||
print(
|
||||
f"{entry['tweet_id']}: {entry['content']}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
|
||||
# Print summary
|
||||
print(f"\nTotal: {len(media)} media", file=sys.stderr)
|
||||
if not result.get("completed") and result.get("cursor"):
|
||||
print(f"Cursor for resume: {result['cursor']}", file=sys.stderr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,342 @@
|
||||
"""Shared abstraction for all Twitter gallery-dl examples.
|
||||
|
||||
This file provides utility functions that build gallery-dl configuration
|
||||
based on parameters in ``twitter-parameters.md`` and execute the Twitter
|
||||
extractor in a single run. All four interfaces (direct module, CLI, FastAPI, and
|
||||
Flask) rely on this module to ensure consistent behavior.
|
||||
|
||||
Features:
|
||||
- Cursor-based resume: Save progress and continue from where you left off
|
||||
- Progress tracking: Monitor fetch progress in real-time
|
||||
- Rate limit handling: Automatically handled by gallery-dl
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import date, datetime
|
||||
from typing import Any, Callable, Dict, Iterable, List, MutableMapping, Optional
|
||||
|
||||
REPO_ROOT = os.path.dirname(os.path.abspath(__file__))
|
||||
if REPO_ROOT not in sys.path:
|
||||
sys.path.append(REPO_ROOT)
|
||||
|
||||
from gallery_dl import config, extractor as extractor_mod # type: ignore
|
||||
from gallery_dl.extractor.common import Message # type: ignore
|
||||
|
||||
_CONFIG_LOCK = threading.Lock()
|
||||
|
||||
# Internal keys that should not be directly passed to extractor config.
|
||||
_INTERNAL_KEYS = {
|
||||
"url",
|
||||
"limit",
|
||||
"metadata",
|
||||
"options",
|
||||
"auth_token",
|
||||
"guest",
|
||||
"cookies",
|
||||
"cursor",
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class TwitterRequest:
|
||||
"""Standard request structure for all frontends."""
|
||||
|
||||
url: str
|
||||
options: Dict[str, Any] = field(default_factory=dict)
|
||||
limit: int = 0
|
||||
metadata: bool = False
|
||||
cursor: Optional[str] = None # Resume from this cursor position
|
||||
|
||||
|
||||
@dataclass
|
||||
class TwitterResult:
|
||||
"""Result structure with cursor for resume capability."""
|
||||
|
||||
media: List[Dict[str, Any]]
|
||||
metadata: List[Dict[str, Any]]
|
||||
cursor: Optional[str] = None # Cursor to resume from
|
||||
total: int = 0
|
||||
completed: bool = True # False if stopped before completion
|
||||
|
||||
|
||||
def _serialize_value(value: Any) -> Any:
|
||||
if isinstance(value, (datetime, date)):
|
||||
return value.isoformat()
|
||||
if isinstance(value, set):
|
||||
return sorted(value)
|
||||
return value
|
||||
|
||||
|
||||
def _extract_tweet_metadata(data: MutableMapping[str, Any]) -> Dict[str, Any]:
|
||||
keys = (
|
||||
"tweet_id",
|
||||
"retweet_id",
|
||||
"quote_id",
|
||||
"reply_id",
|
||||
"conversation_id",
|
||||
"date",
|
||||
"author",
|
||||
"content",
|
||||
"lang",
|
||||
"hashtags",
|
||||
"mentions",
|
||||
"sensitive",
|
||||
"sensitive_flags",
|
||||
"favorite_count",
|
||||
"retweet_count",
|
||||
"quote_count",
|
||||
"reply_count",
|
||||
"bookmark_count",
|
||||
"view_count",
|
||||
)
|
||||
meta = {key: _serialize_value(data.get(key)) for key in keys}
|
||||
if isinstance(meta["author"], dict):
|
||||
meta["author"] = {
|
||||
"id": meta["author"].get("id"),
|
||||
"name": meta["author"].get("name"),
|
||||
"nick": meta["author"].get("nick"),
|
||||
}
|
||||
elif isinstance(meta["author"], str):
|
||||
# Handle case where author is just a string (username)
|
||||
meta["author"] = {
|
||||
"id": None,
|
||||
"name": meta["author"],
|
||||
"nick": meta["author"],
|
||||
}
|
||||
else:
|
||||
# Handle None or other types
|
||||
meta["author"] = {
|
||||
"id": None,
|
||||
"name": None,
|
||||
"nick": None,
|
||||
}
|
||||
return meta
|
||||
|
||||
|
||||
def _clean_file_metadata(meta: MutableMapping[str, Any]) -> Dict[str, Any]:
|
||||
return {key: _serialize_value(value) for key, value in meta.items()}
|
||||
|
||||
|
||||
def _apply_options(options: Dict[str, Any], cursor: Optional[str] = None) -> None:
|
||||
"""Reset config and apply all extractor options."""
|
||||
|
||||
config.clear()
|
||||
cookies = options.get("cookies")
|
||||
auth_token = options.get("auth_token")
|
||||
if auth_token:
|
||||
cookies = dict(cookies or {})
|
||||
cookies["auth_token"] = auth_token
|
||||
if cookies:
|
||||
config.set(("extractor", "twitter"), "cookies", cookies)
|
||||
|
||||
# Enable cursor tracking, or set specific cursor for resume
|
||||
if cursor:
|
||||
config.set(("extractor", "twitter"), "cursor", cursor)
|
||||
else:
|
||||
config.set(("extractor", "twitter"), "cursor", True)
|
||||
|
||||
for key, value in options.items():
|
||||
if key in _INTERNAL_KEYS or value is None:
|
||||
continue
|
||||
config.set(("extractor", "twitter"), key, value)
|
||||
|
||||
|
||||
def run_request(
|
||||
request: TwitterRequest,
|
||||
on_progress: Optional[Callable[[int, Optional[str]], None]] = None,
|
||||
skip_urls: Optional[set] = None,
|
||||
ensure_cursor: bool = True,
|
||||
) -> TwitterResult:
|
||||
"""Run Twitter extractor and return media & metadata results.
|
||||
|
||||
Args:
|
||||
request: The TwitterRequest configuration
|
||||
on_progress: Optional callback(count, cursor) called periodically during fetch
|
||||
skip_urls: Optional set of URLs to skip (for resume/deduplication)
|
||||
ensure_cursor: If True, continue fetching until cursor is available (for reliable resume)
|
||||
|
||||
Returns:
|
||||
TwitterResult with media, metadata, cursor for resume, and completion status
|
||||
"""
|
||||
skip_urls = skip_urls or set()
|
||||
|
||||
with _CONFIG_LOCK:
|
||||
_apply_options(request.options, request.cursor)
|
||||
extractor = extractor_mod.find(request.url)
|
||||
if extractor is None or extractor.category != "twitter":
|
||||
raise ValueError(f"URL not recognized by Twitter extractor: {request.url}")
|
||||
|
||||
media: List[Dict[str, Any]] = []
|
||||
metadata: List[Dict[str, Any]] = []
|
||||
collected = 0
|
||||
skipped = 0
|
||||
last_cursor: Optional[str] = None
|
||||
last_tweet_id: Optional[int] = None
|
||||
completed = True
|
||||
limit_reached = False
|
||||
|
||||
try:
|
||||
for message in extractor:
|
||||
mtype = message[0]
|
||||
if mtype is Message.Directory and request.metadata:
|
||||
# Only extract metadata if message[1] is a dict
|
||||
if isinstance(message[1], dict):
|
||||
metadata.append(_extract_tweet_metadata(message[1]))
|
||||
elif mtype is Message.Url:
|
||||
url = message[1]
|
||||
|
||||
# Skip if already seen
|
||||
if url in skip_urls:
|
||||
skipped += 1
|
||||
continue
|
||||
|
||||
file_meta = _clean_file_metadata(message[2])
|
||||
|
||||
# Apply client-side filter if specified
|
||||
# Note: gallery-dl's filter only works for downloads, not message iteration
|
||||
filter_expr = request.options.get("filter")
|
||||
if filter_expr:
|
||||
try:
|
||||
# Create evaluation context with file metadata
|
||||
eval_context = {**file_meta}
|
||||
# Add common functions that might be used in filters
|
||||
eval_context['datetime'] = datetime
|
||||
eval_context['date'] = date
|
||||
|
||||
# Evaluate filter expression
|
||||
if not eval(filter_expr, {"__builtins__": {}}, eval_context):
|
||||
continue # Skip this item
|
||||
except Exception as e:
|
||||
# If filter evaluation fails, include the item (fail-open)
|
||||
pass
|
||||
|
||||
media.append({"url": url, **file_meta})
|
||||
collected += 1
|
||||
|
||||
# Track last tweet_id for progress display
|
||||
if "tweet_id" in file_meta:
|
||||
last_tweet_id = file_meta["tweet_id"]
|
||||
|
||||
# Try to get cursor from extractor
|
||||
if hasattr(extractor, '_cursor') and extractor._cursor:
|
||||
last_cursor = extractor._cursor
|
||||
|
||||
# Report progress every 10 items
|
||||
if on_progress and collected % 10 == 0:
|
||||
on_progress(collected, last_cursor)
|
||||
|
||||
# Check if limit reached
|
||||
if request.limit and collected >= request.limit:
|
||||
if ensure_cursor and not last_cursor:
|
||||
# Continue until cursor is available for reliable resume
|
||||
limit_reached = True
|
||||
continue
|
||||
completed = False # Stopped due to limit
|
||||
break
|
||||
|
||||
# If we were waiting for cursor and now have it, stop
|
||||
if limit_reached and last_cursor:
|
||||
completed = False
|
||||
break
|
||||
|
||||
except KeyboardInterrupt:
|
||||
completed = False
|
||||
finally:
|
||||
# Get final cursor from extractor
|
||||
if hasattr(extractor, '_cursor') and extractor._cursor:
|
||||
last_cursor = extractor._cursor
|
||||
|
||||
return TwitterResult(
|
||||
media=media,
|
||||
metadata=metadata,
|
||||
cursor=last_cursor,
|
||||
total=collected,
|
||||
completed=completed,
|
||||
)
|
||||
|
||||
|
||||
def run_request_dict(
|
||||
request: TwitterRequest,
|
||||
on_progress: Optional[Callable[[int, Optional[str]], None]] = None,
|
||||
skip_urls: Optional[set] = None,
|
||||
ensure_cursor: bool = True,
|
||||
) -> Dict[str, Any]:
|
||||
"""Run request and return as dictionary (for JSON serialization)."""
|
||||
result = run_request(request, on_progress, skip_urls, ensure_cursor)
|
||||
return {
|
||||
"media": result.media,
|
||||
"metadata": result.metadata,
|
||||
"cursor": result.cursor,
|
||||
"total": result.total,
|
||||
"completed": result.completed,
|
||||
}
|
||||
|
||||
|
||||
def load_resume_state(filepath: str) -> Optional[Dict[str, Any]]:
|
||||
"""Load previous state from JSON file for resume."""
|
||||
if not os.path.exists(filepath):
|
||||
return None
|
||||
try:
|
||||
with open(filepath, "r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
return data
|
||||
except (json.JSONDecodeError, IOError):
|
||||
return None
|
||||
|
||||
|
||||
def save_state(filepath: str, result: Dict[str, Any], url: str) -> None:
|
||||
"""Save current state to JSON file."""
|
||||
state = {
|
||||
"url": url,
|
||||
"cursor": result.get("cursor"),
|
||||
"total": result.get("total", len(result.get("media", []))),
|
||||
"completed": result.get("completed", True),
|
||||
"media": result.get("media", []),
|
||||
"metadata": result.get("metadata", []),
|
||||
}
|
||||
with open(filepath, "w", encoding="utf-8") as f:
|
||||
json.dump(state, f, indent=2, default=str)
|
||||
|
||||
|
||||
def merge_options(*sources: Optional[Dict[str, Any]]) -> Dict[str, Any]:
|
||||
"""Merge multiple configuration dicts (None values ignored)."""
|
||||
|
||||
merged: Dict[str, Any] = {}
|
||||
for source in sources:
|
||||
if not source:
|
||||
continue
|
||||
for key, value in source.items():
|
||||
merged[key] = value
|
||||
return merged
|
||||
|
||||
|
||||
def coerce_literal(value: str) -> Any:
|
||||
"""Infer basic type from CLI argument string."""
|
||||
|
||||
lowered = value.lower()
|
||||
if lowered in {"true", "false"}:
|
||||
return lowered == "true"
|
||||
if lowered in {"null", "none"}:
|
||||
return None
|
||||
try:
|
||||
return int(value)
|
||||
except ValueError:
|
||||
pass
|
||||
try:
|
||||
return float(value)
|
||||
except ValueError:
|
||||
pass
|
||||
if (value.startswith("[") and value.endswith("]")) or (
|
||||
value.startswith("{") and value.endswith("}")
|
||||
):
|
||||
try:
|
||||
return json.loads(value)
|
||||
except json.JSONDecodeError:
|
||||
return value
|
||||
return value
|
||||
@@ -0,0 +1,54 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"embed"
|
||||
"log"
|
||||
|
||||
"github.com/wailsapp/wails/v2"
|
||||
"github.com/wailsapp/wails/v2/pkg/options"
|
||||
"github.com/wailsapp/wails/v2/pkg/options/assetserver"
|
||||
"github.com/wailsapp/wails/v2/pkg/options/windows"
|
||||
)
|
||||
|
||||
//go:embed all:frontend/dist
|
||||
var assets embed.FS
|
||||
|
||||
func main() {
|
||||
// Create an instance of the app structure
|
||||
app := NewApp()
|
||||
|
||||
// Create application with options
|
||||
err := wails.Run(&options.App{
|
||||
Title: "Twitter/X Media Batch Downloader",
|
||||
Width: 1024,
|
||||
Height: 600,
|
||||
MinWidth: 1024,
|
||||
MinHeight: 600,
|
||||
Frameless: true,
|
||||
AssetServer: &assetserver.Options{
|
||||
Assets: assets,
|
||||
},
|
||||
BackgroundColour: &options.RGBA{R: 0, G: 0, B: 0, A: 255},
|
||||
OnStartup: app.startup,
|
||||
OnShutdown: app.shutdown,
|
||||
DragAndDrop: &options.DragAndDrop{
|
||||
EnableFileDrop: true,
|
||||
DisableWebViewDrop: false,
|
||||
CSSDropProperty: "--wails-drop-target",
|
||||
CSSDropValue: "drop",
|
||||
},
|
||||
Bind: []interface{}{
|
||||
app,
|
||||
},
|
||||
Windows: &windows.Options{
|
||||
WebviewIsTransparent: false,
|
||||
WindowIsTranslucent: false,
|
||||
DisableWindowIcon: false,
|
||||
DisableFramelessWindowDecorations: false,
|
||||
},
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
log.Fatal("Error:", err.Error())
|
||||
}
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
{
|
||||
"version": "1.8"
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"$schema": "https://wails.io/schemas/config.v2.json",
|
||||
"name": "TwitterXMediaBatchDownloader",
|
||||
"outputfilename": "TwitterXMediaBatchDownloader",
|
||||
"frontend:install": "pnpm install",
|
||||
"frontend:build": "pnpm run build",
|
||||
"frontend:dev:watcher": "pnpm run dev",
|
||||
"frontend:dev:serverUrl": "auto",
|
||||
"author": {
|
||||
"name": "afkarxyz"
|
||||
},
|
||||
"info": {
|
||||
"productName": "Twitter/X Media Batch Downloader",
|
||||
"productVersion": "4.2"
|
||||
},
|
||||
"wailsjsdir": "./frontend",
|
||||
"assetdir": "./frontend/dist",
|
||||
"reloaddirs": "./frontend/src"
|
||||
}
|
||||
Reference in new issue
Block a user