Compare commits

..
9 Commits
Author SHA1 Message Date
afkarxyz de402efe6b v4.3 2025-12-20 12:12:11 +07:00
afkarxyz 2f51a118e4 v4.3 2025-12-20 12:10:45 +07:00
afkarxyz b611632c30 v4.2 2025-12-17 18:25:41 +07:00
afkarxyz 30bcf3db9f v4.2 2025-12-17 10:07:49 +07:00
afkarxyz ada11f086e v4.2 2025-12-17 10:05:32 +07:00
afkarxyz b4266cb7fa Ko-fi 2025-12-17 04:58:29 +07:00
afkarxyz aa87cce538 v4.1 2025-12-11 22:17:57 +07:00
afkarxyz 2d913d987f v4.1 2025-12-11 22:14:01 +07:00
afkarxyz 3abba4cc59 v4.0 2025-12-05 06:12:04 +07:00
45 changed files with 6660 additions and 3158 deletions

No files matched your search

+10 -13
View File
@@ -12,14 +12,15 @@ A GUI tool to download original-quality images and videos from Twitter/X account
</div>
### [Download](https://github.com/afkarxyz/SpotiFLAC/releases)
### [Download](https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases)
- If you're familiar with userscripts, install it [**here**](https://greasyfork.org/en/scripts/551198)
- To install the Chrome extension version, click [**here**](https://chromewebstore.google.com/detail/aboccmnimgpjehlplnanplbhlccohhhn)
- If you're familiar with **userscripts**, please install it [**here**](https://greasyfork.org/en/scripts/523157)
- The **Chrome extension** version is now available, please install it [**here**](https://www.patreon.com/posts/chrome-extension-139296789)
## Screenshot
![Image](https://github.com/user-attachments/assets/02bd8c33-74b7-4fde-8b6c-d2b006a3ae70)
![Image](https://github.com/user-attachments/assets/a3ade39c-d611-49ce-81bb-121f30488ae2)
## How to Obtain Auth Token
@@ -27,7 +28,7 @@ A GUI tool to download original-quality images and videos from Twitter/X account
> - I suggest not using the **main account** to obtain the token.
> - You can use https://temp-mail.io to register a Twitter account.
> - Using an auth token or cookies has the potential to get the **account suspended.**
> - If too many media files are fetched, it may trigger a **rate limit**, and the media retrieval will fail, try enabling Batch mode.
> - 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)
@@ -35,13 +36,9 @@ A GUI tool to download original-quality images and videos from Twitter/X account
2. Log into your account
3. Open the Developer Tools by pressing <kbd>F12</kbd>
4. Navigate to the **Application** tab, then select **Storage → Cookies**
5. Find and copy the `auth_token` value or use the browser extension [X.com Auth Token Grabber](https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/releases/download/v1.0/X.com.Auth.Token.Grabber.zip)
5. Find and copy the `auth_token` value
6. Do not log out of your account, as a new `auth_token` will be generated by Twitter
> X.com Auth Token Grabber
![image](https://github.com/user-attachments/assets/4bf5f787-d34f-4259-837c-07a6432c4360)
> Developer Tools
![image](https://github.com/user-attachments/assets/8e81dd8f-f8be-4254-9cf6-cacfa97743e9)
[![Ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/afkarxyz)
+78 -14
View File
@@ -177,15 +177,18 @@ 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)
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
@@ -193,12 +196,14 @@ 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"`
}
@@ -222,11 +227,12 @@ func (a *App) DownloadMedia(req DownloadMediaRequest) (DownloadMediaResponse, er
outputDir = filepath.Join(outputDir, req.Username)
}
downloaded, failed, err := backend.DownloadMediaFiles(req.URLs, outputDir)
downloaded, failed, err := backend.DownloadMediaFiles(req.URLs, outputDir, req.Proxy)
if err != nil {
return DownloadMediaResponse{
Success: false,
Downloaded: downloaded,
Skipped: 0,
Failed: failed,
Message: err.Error(),
}, err
@@ -235,6 +241,7 @@ func (a *App) DownloadMedia(req DownloadMediaRequest) (DownloadMediaResponse, er
return DownloadMediaResponse{
Success: true,
Downloaded: downloaded,
Skipped: 0,
Failed: failed,
Message: fmt.Sprintf("Downloaded %d files, %d failed", downloaded, failed),
}, nil
@@ -269,15 +276,30 @@ func (a *App) DownloadMediaWithMetadata(req DownloadMediaWithMetadataRequest) (D
}
// 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: req.Username,
Content: item.Content,
URL: item.URL,
Date: item.Date,
TweetID: int64(item.TweetID),
Type: item.Type,
Username: username,
Content: item.Content,
OriginalFilename: originalFilename,
}
}
@@ -306,11 +328,12 @@ func (a *App) DownloadMediaWithMetadata(req DownloadMediaWithMetadataRequest) (D
})
}
downloaded, failed, err := backend.DownloadMediaWithMetadataProgressAndStatus(items, outputDir, req.Username, progressCallback, itemStatusCallback, a.downloadCtx)
downloaded, skipped, failed, err := backend.DownloadMediaWithMetadataProgressAndStatus(items, outputDir, req.Username, progressCallback, itemStatusCallback, a.downloadCtx, req.Proxy)
if err != nil {
return DownloadMediaResponse{
Success: false,
Downloaded: downloaded,
Skipped: skipped,
Failed: failed,
Message: err.Error(),
}, err
@@ -322,8 +345,9 @@ func (a *App) DownloadMediaWithMetadata(req DownloadMediaWithMetadataRequest) (D
return DownloadMediaResponse{
Success: true,
Downloaded: downloaded,
Skipped: skipped,
Failed: failed,
Message: fmt.Sprintf("Downloaded %d files, %d failed", downloaded, failed),
Message: fmt.Sprintf("Downloaded %d files, %d skipped, %d failed", downloaded, skipped, failed),
}, nil
}
@@ -378,6 +402,11 @@ 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)
@@ -400,6 +429,16 @@ 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"`
@@ -458,6 +497,31 @@ type ImportAccountResponse struct {
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
+58
View File
@@ -1,8 +1,12 @@
package backend
import (
"fmt"
"net/http"
"net/url"
"os"
"path/filepath"
"time"
)
func GetDefaultDownloadPath() string {
@@ -16,3 +20,57 @@ func GetDefaultDownloadPath() string {
// 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
}
+80 -51
View File
@@ -27,17 +27,19 @@ type AccountDB struct {
// 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"`
ID int64 `json:"id"`
Username string `json:"username"`
Name string `json:"name"`
ProfileImage string `json:"profile_image"`
TotalMedia int `json:"total_media"`
LastFetched string `json:"last_fetched"`
GroupName string `json:"group_name"`
GroupColor string `json:"group_color"`
MediaType string `json:"media_type"`
Cursor string `json:"cursor"`
Completed bool `json:"completed"`
FollowersCount int `json:"followers_count"`
StatusesCount int `json:"statuses_count"`
}
var db *sql.DB
@@ -161,7 +163,8 @@ func GetAllAccounts() ([]AccountListItem, error) {
SELECT id, username, name, profile_image, total_media, last_fetched,
COALESCE(group_name, '') as group_name, COALESCE(group_color, '') as group_color,
COALESCE(media_type, 'all') as media_type,
COALESCE(cursor, '') as cursor, COALESCE(completed, 1) as completed
COALESCE(cursor, '') as cursor, COALESCE(completed, 1) as completed,
COALESCE(response_json, '') as response_json
FROM accounts
ORDER BY group_name ASC, last_fetched DESC
`)
@@ -175,11 +178,28 @@ func GetAllAccounts() ([]AccountListItem, error) {
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 {
var responseJSON string
if err := rows.Scan(&acc.ID, &acc.Username, &acc.Name, &acc.ProfileImage, &acc.TotalMedia, &lastFetched, &acc.GroupName, &acc.GroupColor, &acc.MediaType, &acc.Cursor, &completedInt, &responseJSON); err != nil {
continue
}
acc.LastFetched = lastFetched.Format("2006-01-02 15:04")
acc.Completed = completedInt == 1
// Extract followers_count and statuses_count from response_json
if responseJSON != "" {
var parsed map[string]interface{}
if err := json.Unmarshal([]byte(responseJSON), &parsed); err == nil {
if accountInfo, ok := parsed["account_info"].(map[string]interface{}); ok {
if followers, ok := accountInfo["followers_count"].(float64); ok {
acc.FollowersCount = int(followers)
}
if statuses, ok := accountInfo["statuses_count"].(float64); ok {
acc.StatusesCount = int(statuses)
}
}
}
}
accounts = append(accounts, acc)
}
@@ -241,37 +261,6 @@ func ClearAllAccounts() error {
return err
}
// GetAccountByUsername returns a specific account by username
func GetAccountByUsername(username string) (*AccountDB, error) {
if db == nil {
if err := InitDB(); err != nil {
return nil, err
}
}
var acc AccountDB
var lastFetched time.Time
var completedInt int
err := db.QueryRow(`
SELECT id, username, name, profile_image, total_media, last_fetched, response_json,
COALESCE(cursor, '') as cursor, COALESCE(completed, 1) as completed
FROM accounts WHERE username = ?
`, username).Scan(&acc.ID, &acc.Username, &acc.Name, &acc.ProfileImage, &acc.TotalMedia, &lastFetched, &acc.ResponseJSON, &acc.Cursor, &completedInt)
if err != nil {
return nil, err
}
acc.LastFetched = lastFetched
acc.Completed = completedInt == 1
// Convert legacy format if needed
if converted, err := ConvertLegacyToNewFormat(acc.ResponseJSON); err == nil {
acc.ResponseJSON = converted
}
return &acc, nil
}
// GetAccountByID returns a specific account by ID
func GetAccountByID(id int64) (*AccountDB, error) {
if db == nil {
@@ -315,13 +304,6 @@ func DeleteAccount(id int64) error {
return err
}
// ParseResponseJSON parses the stored JSON response
func ParseResponseJSON(jsonStr string) (map[string]interface{}, error) {
var result map[string]interface{}
err := json.Unmarshal([]byte(jsonStr), &result)
return result, err
}
// LegacyMediaEntry represents media entry in old format
type LegacyMediaEntry struct {
TweetID string `json:"tweet_id"`
@@ -442,6 +424,53 @@ func ExportAccountToFile(id int64, outputDir string) (string, error) {
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 {
+77 -38
View File
@@ -21,23 +21,29 @@ const (
// 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)
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) (downloaded int, failed int, err error) {
func DownloadMediaFiles(urls []string, outputDir string, customProxy string) (downloaded int, failed int, err error) {
// Create output directory if it doesn't exist
if err := os.MkdirAll(outputDir, 0755); err != nil {
return 0, len(urls), fmt.Errorf("failed to create output directory: %v", err)
}
client := &http.Client{
Timeout: 60 * time.Second,
// 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 {
@@ -73,38 +79,35 @@ type downloadTask struct {
index int
}
// DownloadMediaWithMetadata downloads media files with proper naming and categorization
func DownloadMediaWithMetadata(items []MediaItem, outputDir string, username string) (downloaded int, failed int, err error) {
return DownloadMediaWithMetadataProgressAndStatus(items, outputDir, username, nil, nil, nil)
}
// DownloadMediaWithMetadataProgress downloads media files with progress callback and cancellation support
func DownloadMediaWithMetadataProgress(items []MediaItem, outputDir string, username string, progress ProgressCallback, ctx context.Context) (downloaded int, failed int, err error) {
return DownloadMediaWithMetadataProgressAndStatus(items, outputDir, username, progress, nil, ctx)
}
// DownloadMediaWithMetadataProgressAndStatus downloads media files with progress and per-item status callbacks
func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir string, username string, progress ProgressCallback, itemStatus ItemStatusCallback, ctx context.Context) (downloaded int, failed int, err error) {
// 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()
}
// Create base output directory
baseDir := filepath.Join(outputDir, username)
if err := os.MkdirAll(baseDir, 0755); err != nil {
return 0, len(items), fmt.Errorf("failed to create output directory: %v", err)
}
total := len(items)
if total == 0 {
return 0, 0, nil
return 0, 0, 0, nil
}
// Prepare all tasks first (sequential to handle tweet media count)
tweetMediaCount := make(map[int64]int)
// For bookmarks and likes, each item may have different username, so we track per username
tweetMediaCount := make(map[string]map[int64]int) // username -> tweet_id -> count
tasks := make([]downloadTask, 0, total)
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 {
@@ -120,6 +123,12 @@ func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir str
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 {
@@ -132,12 +141,12 @@ func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir str
// Get file extension
ext := getExtension(item.URL, item.Type)
// Increment counter for this tweet_id
tweetMediaCount[item.TweetID]++
mediaIndex := tweetMediaCount[item.TweetID]
// 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", username, timestamp, item.TweetID, mediaIndex, ext)
filename := fmt.Sprintf("%s_%s_%d_%02d%s", itemUsername, timestamp, item.TweetID, mediaIndex, ext)
outputPath := filepath.Join(typeDir, filename)
tasks = append(tasks, downloadTask{
@@ -149,6 +158,7 @@ func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir str
// Counters for parallel downloads
var downloadedCount int64
var skippedCount int64
var failedCount int64
var completedCount int64
@@ -162,13 +172,23 @@ func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir str
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 := &http.Client{
Timeout: 60 * time.Second,
}
client := sharedClient
for task := range taskChan {
// Check for cancellation
@@ -181,8 +201,13 @@ func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir str
var status string
// Skip if file already exists
if _, err := os.Stat(task.outputPath); err == nil {
atomic.AddInt64(&downloadedCount, 1)
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 {
@@ -196,6 +221,20 @@ func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir str
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"
}
@@ -220,7 +259,7 @@ func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir str
case <-ctx.Done():
close(taskChan)
wg.Wait()
return int(downloadedCount), int(failedCount) + (total - int(completedCount)), ctx.Err()
return int(downloadedCount), int(skippedCount), int(failedCount) + (total - int(completedCount)), ctx.Err()
case taskChan <- task:
}
}
@@ -229,7 +268,7 @@ func DownloadMediaWithMetadataProgressAndStatus(items []MediaItem, outputDir str
// Wait for all workers to finish
wg.Wait()
return int(downloadedCount), int(failedCount), nil
return int(downloadedCount), int(skippedCount), int(failedCount), nil
}
// downloadFileWithContext downloads a single file with context support for cancellation
+348
View File
@@ -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
}
+28 -6
View File
@@ -220,12 +220,34 @@ func ConvertMP4ToGIF(inputPath, outputPath, quality, resolution string) error {
var args []string
if quality == "fast" {
// Fast mode: simple conversion
args = []string{
"-i", inputPath,
"-loop", "0",
"-y",
outputPath,
// 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
+52
View File
@@ -2,7 +2,9 @@ package backend
import (
"context"
"os"
"os/exec"
"path/filepath"
"runtime"
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
@@ -50,3 +52,53 @@ func SelectFolderDialog(ctx context.Context, defaultPath string) (string, error)
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")
}
+227
View File
@@ -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 ""
}
+75 -55
View File
@@ -213,6 +213,8 @@ type TimelineEntry struct {
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)
@@ -395,27 +397,39 @@ func convertMetadataToTimelineEntry(meta TweetMetadata) TimelineEntry {
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,
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
@@ -627,6 +641,17 @@ func ExtractTimeline(req TimelineRequest) (*TwitterResponse, error) {
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)
@@ -637,19 +662,31 @@ func ExtractTimeline(req TimelineRequest) (*TwitterResponse, error) {
}
// Get account info from first media item if available, otherwise from metadata
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
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)
@@ -662,8 +699,10 @@ func ExtractTimeline(req TimelineRequest) (*TwitterResponse, error) {
// Get account info from first media item
user := cliResponse.Media[0].User
accountInfo.Name = user.Name
accountInfo.Nick = user.Nick
if !isBookmarks && !isLikes {
accountInfo.Name = user.Name
accountInfo.Nick = user.Nick
}
accountInfo.Date = user.Date
accountInfo.FollowersCount = user.FollowersCount
accountInfo.FriendsCount = user.FriendsCount
@@ -688,13 +727,16 @@ func ExtractTimeline(req TimelineRequest) (*TwitterResponse, error) {
FavoriteCount: meta.FavoriteCount,
RetweetCount: meta.RetweetCount,
ReplyCount: meta.ReplyCount,
AuthorUsername: meta.Author.Name,
}
timeline = append(timeline, entry)
}
// Get account info from first metadata
firstMeta := cliResponse.Metadata[0]
accountInfo.Name = firstMeta.Author.Name
accountInfo.Nick = firstMeta.Author.Nick
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
@@ -874,25 +916,3 @@ func extractJSON(output string) string {
return ""
}
// GetThumbnailURL converts a Twitter media URL to thumbnail size
func GetThumbnailURL(url string) string {
// For images: https://pbs.twimg.com/media/XXX?format=jpg&name=thumb
if strings.Contains(url, "pbs.twimg.com/media/") {
// Check if it already has format parameter
if strings.Contains(url, "?format=") {
// Replace name parameter with thumb
if strings.Contains(url, "&name=") {
parts := strings.Split(url, "&name=")
return parts[0] + "&name=thumb"
}
return url + "&name=thumb"
}
// Add format and name parameters
if strings.Contains(url, "?") {
return url + "&name=thumb"
}
return url + "?format=jpg&name=thumb"
}
return url
}
+3 -1
View File
@@ -18,5 +18,7 @@
"lib": "@/lib",
"hooks": "@/hooks"
},
"registries": {}
"registries": {
"@lucide-animated": "https://lucide-animated.com/r/{name}.json"
}
}
+1 -1
View File
@@ -6,7 +6,7 @@
<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:ital,opsz,wght@0,9..40,100..1000;1,9..40,100..1000&family=Google+Sans+Code:ital,wght@0,300..800;1,300..800&family=Google+Sans+Flex:opsz,wght@6..144,1..1000&family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&family=Manrope:wght@200..800&family=Plus+Jakarta+Sans:ital,wght@0,200..800;1,200..800&family=Poppins:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&family=Roboto:ital,wght@0,100..900;1,100..900&family=Space+Grotesk:wght@300..700&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=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>
+16 -17
View File
@@ -12,43 +12,42 @@
"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.1.4",
"@radix-ui/react-tabs": "^1.1.13",
"@radix-ui/react-switch": "^1.2.6",
"@radix-ui/react-tooltip": "^1.2.8",
"@tailwindcss/vite": "^4.1.17",
"@tailwindcss/vite": "^4.1.18",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"lucide-react": "^0.554.0",
"lucide-react": "^0.562.0",
"motion": "^12.23.26",
"next-themes": "^0.4.6",
"react": "^19.2.0",
"react-dom": "^19.2.0",
"react": "^19.2.3",
"react-dom": "^19.2.3",
"sonner": "^2.0.7",
"tailwind-merge": "^3.4.0",
"tailwindcss": "^4.1.17"
"tailwindcss": "^4.1.18"
},
"devDependencies": {
"@eslint/js": "^9.39.1",
"@types/node": "^24.10.1",
"@types/react": "^19.2.6",
"@eslint/js": "^9.39.2",
"@types/node": "^25.0.3",
"@types/react": "^19.2.7",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^5.1.1",
"eslint": "^9.39.1",
"@vitejs/plugin-react": "^5.1.2",
"eslint": "^9.39.2",
"eslint-plugin-react-hooks": "^7.0.1",
"eslint-plugin-react-refresh": "^0.4.24",
"eslint-plugin-react-refresh": "^0.4.26",
"globals": "^16.5.0",
"sharp": "^0.34.5",
"tw-animate-css": "^1.4.0",
"typescript": "~5.9.3",
"typescript-eslint": "^8.47.0",
"vite": "^7.2.4"
"typescript-eslint": "^8.50.0",
"vite": "^7.3.0"
}
}
+1 -1
View File
@@ -1 +1 @@
6d6b26a2fed70996ef14dbc3e325f141
93300717a79529efe3943af0fda63408
+874 -1038
View File
File diff suppressed because it is too large. Load diff
+1311 -75
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
-132
View File
@@ -1,132 +0,0 @@
import { useState, useEffect, useRef } from "react";
import { Bug, Trash2, X, Copy, Check } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import { logger, type LogEntry } from "@/lib/logger";
const levelColors: Record<string, string> = {
info: "text-blue-500",
success: "text-green-500",
warning: "text-yellow-500",
error: "text-red-500",
debug: "text-gray-500",
};
function formatTime(date: Date): string {
return date.toLocaleTimeString("en-US", {
hour12: false,
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
});
}
export function DebugLogger() {
const [open, setOpen] = useState(false);
const [logs, setLogs] = useState<LogEntry[]>([]);
const [copied, setCopied] = useState(false);
const scrollRef = useRef<HTMLDivElement>(null);
useEffect(() => {
const unsubscribe = logger.subscribe(() => {
setLogs(logger.getLogs());
});
setLogs(logger.getLogs());
return () => {
unsubscribe();
};
}, []);
useEffect(() => {
if (scrollRef.current) {
scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
}
}, [logs]);
const handleClear = () => {
logger.clear();
};
const handleCopy = async () => {
const logText = logs
.map((log) => `[${formatTime(log.timestamp)}] [${log.level}] ${log.message}`)
.join("\n");
try {
await navigator.clipboard.writeText(logText);
setCopied(true);
setTimeout(() => setCopied(false), 500);
} catch (err) {
console.error("Failed to copy logs:", err);
}
};
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<Button
variant="ghost"
size="icon"
className="h-6 w-6 opacity-50 hover:opacity-100"
>
<Bug className="h-3.5 w-3.5" />
</Button>
</DialogTrigger>
<DialogContent className="sm:max-w-[600px] max-h-[80vh] p-6 [&>button]:hidden">
<DialogTitle className="text-sm font-medium">Debug Logs</DialogTitle>
<div className="absolute right-4 top-4 flex items-center gap-1">
<Button
variant="ghost"
size="icon"
className="h-6 w-6 opacity-70 hover:opacity-100"
onClick={handleCopy}
disabled={logs.length === 0}
>
{copied ? <Check className="h-4 w-4" /> : <Copy className="h-4 w-4" />}
</Button>
<Button
variant="ghost"
size="icon"
className="h-6 w-6 opacity-70 hover:opacity-100"
onClick={handleClear}
>
<Trash2 className="h-4 w-4" />
</Button>
<Button
variant="ghost"
size="icon"
className="h-6 w-6 opacity-70 hover:opacity-100"
onClick={() => setOpen(false)}
>
<X className="h-4 w-4" />
</Button>
</div>
<div
ref={scrollRef}
className="h-[400px] overflow-y-auto bg-muted/50 rounded-md p-3 font-mono text-xs"
>
{logs.length === 0 ? (
<p className="text-muted-foreground lowercase">no logs yet...</p>
) : (
logs.map((log, i) => (
<div key={i} className="flex gap-2 py-0.5">
<span className="text-muted-foreground shrink-0">
[{formatTime(log.timestamp)}]
</span>
<span className={`shrink-0 w-16 ${levelColors[log.level]}`}>
[{log.level}]
</span>
<span className="break-all">{log.message}</span>
</div>
))
)}
</div>
</DialogContent>
</Dialog>
);
}
+292 -110
View File
@@ -51,7 +51,7 @@ import { logger } from "@/lib/logger";
import { toastWithSound as toast } from "@/lib/toast-with-sound";
import { getSettings } from "@/lib/settings";
import { openExternal } from "@/lib/utils";
import { DownloadMediaWithMetadata, OpenFolder, IsFFmpegInstalled, ConvertGIFs, StopDownload } from "../../wailsjs/go/main/App";
import { DownloadMediaWithMetadata, OpenFolder, IsFFmpegInstalled, ConvertGIFs, StopDownload, CheckFolderExists, CheckGifsFolderHasMP4 } from "../../wailsjs/go/main/App";
import { EventsOn, EventsOff } from "../../wailsjs/runtime/runtime";
import { main } from "../../wailsjs/go/models";
@@ -72,21 +72,33 @@ interface MediaListProps {
timeline: TimelineEntry[];
totalUrls: number;
fetchedMediaType?: string;
newMediaCount?: number | null;
}
function getThumbnailUrl(url: string): string {
// For animated_gif: video.twimg.com/tweet_video/XXX.mp4 -> pbs.twimg.com/tweet_video_thumb/XXX?format=jpg&name=360x360
if (url.includes("video.twimg.com/tweet_video/")) {
// Extract filename from URL (e.g., GzstJyDbIAAPuX9.mp4 -> GzstJyDbIAAPuX9)
const match = url.match(/tweet_video\/([^\/]+)\.mp4/);
if (match && match[1]) {
const filename = match[1];
return `https://pbs.twimg.com/tweet_video_thumb/${filename}?format=jpg&name=360x360`;
}
}
// For photos: pbs.twimg.com/media/XXX -> use 360x360 for consistency
if (url.includes("pbs.twimg.com/media/")) {
if (url.includes("?format=")) {
if (url.includes("&name=")) {
const parts = url.split("&name=");
return parts[0] + "&name=thumb";
return parts[0] + "&name=360x360";
}
return url + "&name=thumb";
return url + "&name=360x360";
}
if (url.includes("?")) {
return url + "&name=thumb";
return url + "&name=360x360";
}
return url + "?format=jpg&name=thumb";
return url + "?format=jpg&name=360x360";
}
return url;
}
@@ -209,6 +221,7 @@ export function MediaList({
timeline,
totalUrls,
fetchedMediaType = "all",
newMediaCount = null,
}: MediaListProps) {
const [selectedItems, setSelectedItems] = useState<Set<number>>(new Set());
const [sortBy, setSortBy] = useState<string>("date-desc");
@@ -218,15 +231,19 @@ export function MediaList({
const [downloadProgress, setDownloadProgress] = useState<DownloadProgress | null>(null);
const [hasDownloaded, setHasDownloaded] = useState(false);
const [isConverting, setIsConverting] = useState(false);
const [hasGifs, setHasGifs] = useState(false);
const [ffmpegInstalled, setFfmpegInstalled] = useState(false);
const [showScrollTop, setShowScrollTop] = useState(false);
const [folderExists, setFolderExists] = useState(false);
const [gifsFolderHasMP4, setGifsFolderHasMP4] = useState(false);
const [previewIndex, setPreviewIndex] = useState<number | null>(null);
// Download status tracking per item (by tweet_id + index for uniqueness)
const [downloadedItems, setDownloadedItems] = useState<Set<string>>(new Set());
const [failedItems, setFailedItems] = useState<Set<string>>(new Set());
const [skippedItems, setSkippedItems] = useState<Set<string>>(new Set());
const [downloadingItem, setDownloadingItem] = useState<string | null>(null);
// Lazy loading: start with 10 thumbnails, load more on scroll
const [visibleCount, setVisibleCount] = useState<number>(10);
const loadMoreRef = useRef<HTMLDivElement>(null);
// Listen for scroll to show/hide scroll-to-top button
useEffect(() => {
@@ -237,6 +254,103 @@ export function MediaList({
return () => window.removeEventListener("scroll", handleScroll);
}, []);
// Filter and sort timeline
const filteredTimeline = useMemo(() => {
let filtered = [...timeline];
// Filter by media type
if (filterType !== "all") {
filtered = filtered.filter((item) => {
if (filterType === "photo") return item.type === "photo";
if (filterType === "video") return item.type === "video";
if (filterType === "gif") return item.type === "animated_gif" || item.type === "gif";
if (filterType === "text") return item.type === "text";
return true;
});
}
// Sort
filtered.sort((a, b) => {
if (sortBy === "date-desc") {
return new Date(b.date).getTime() - new Date(a.date).getTime();
} else if (sortBy === "date-asc") {
return new Date(a.date).getTime() - new Date(b.date).getTime();
} else if (sortBy === "tweet-id-desc") {
return Number(b.tweet_id) - Number(a.tweet_id);
} else if (sortBy === "tweet-id-asc") {
return Number(a.tweet_id) - Number(b.tweet_id);
}
return 0;
});
return filtered;
}, [timeline, filterType, sortBy]);
// Reset visible count when filtered timeline changes
useEffect(() => {
setVisibleCount(10);
}, [filteredTimeline.length]);
// Check folder existence and FFmpeg installation
useEffect(() => {
const checkFoldersAndFFmpeg = async () => {
const settings = getSettings();
const basePath = settings.downloadPath;
// Check FFmpeg installation
const installed = await IsFFmpegInstalled();
setFfmpegInstalled(installed);
if (!basePath || !accountInfo.name) return;
// For bookmarks/likes, check special folder names
let folderName = accountInfo.name;
if (accountInfo.nick === "My Bookmarks" || accountInfo.name === "bookmarks") {
folderName = "My Bookmarks";
} else if (accountInfo.nick === "My Likes" || accountInfo.name === "likes") {
folderName = "My Likes";
}
const exists = await CheckFolderExists(basePath, folderName);
setFolderExists(exists);
if (exists) {
const hasMP4 = await CheckGifsFolderHasMP4(basePath, folderName);
setGifsFolderHasMP4(hasMP4);
} else {
setGifsFolderHasMP4(false);
}
};
checkFoldersAndFFmpeg();
}, [accountInfo.name, accountInfo.nick, hasDownloaded]);
// Intersection Observer for lazy loading thumbnails
useEffect(() => {
if (!loadMoreRef.current) return;
const observer = new IntersectionObserver(
(entries) => {
if (entries[0].isIntersecting) {
setVisibleCount((prev) => {
// Load 10 more items at a time
const filteredLength = filteredTimeline.length;
return Math.min(prev + 10, filteredLength);
});
}
},
{ threshold: 0.1 }
);
observer.observe(loadMoreRef.current);
return () => {
if (loadMoreRef.current) {
observer.unobserve(loadMoreRef.current);
}
};
}, [filteredTimeline.length]);
const scrollToTop = () => {
window.scrollTo({ top: 0, behavior: "smooth" });
};
@@ -328,31 +442,6 @@ export function MediaList({
};
}, []);
// Filter and sort timeline
const filteredTimeline = useMemo(() => {
let filtered = [...timeline];
// Filter by media type
if (filterType !== "all") {
filtered = filtered.filter((item) => {
if (filterType === "photo") return item.type === "photo";
if (filterType === "video") return item.type === "video";
if (filterType === "gif") return item.type === "gif" || item.type === "animated_gif";
if (filterType === "text") return item.type === "text";
return true;
});
}
// Sort
if (sortBy === "date-asc") {
filtered.sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime());
} else {
filtered.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());
}
return filtered;
}, [timeline, sortBy, filterType]);
const goToPrevious = () => {
if (previewIndex !== null && previewIndex > 0) {
setPreviewIndex(previewIndex - 1);
@@ -407,9 +496,21 @@ export function MediaList({
setSelectedItems(newSelected);
};
const handleDownload = async () => {
// Helper function to get output directory (adds "My Bookmarks" or "My Likes" folder)
const getOutputDir = (): string => {
const settings = getSettings();
const isBookmarks = accountInfo.nick === "My Bookmarks";
const isLikes = accountInfo.nick === "My Likes";
if (isBookmarks || isLikes) {
// Use path separator that backend will normalize (filepath.Join handles both / and \)
const separator = settings.downloadPath.includes("/") ? "/" : "\\";
const folderName = isBookmarks ? "My Bookmarks" : "My Likes";
return `${settings.downloadPath}${separator}${folderName}`;
}
return settings.downloadPath;
};
const handleDownload = async () => {
// Get items with their original indices in filteredTimeline
const itemsWithIndices = selectedItems.size > 0
? Array.from(selectedItems).map((i) => ({ item: filteredTimeline[i], originalIndex: i }))
@@ -432,6 +533,7 @@ export function MediaList({
logger.info(`Starting download of ${itemsWithIndices.length} files...`);
try {
const settings = getSettings();
const request = new main.DownloadMediaWithMetadataRequest({
items: itemsWithIndices.map(({ item }) => new main.MediaItemRequest({
url: item.url,
@@ -439,24 +541,41 @@ export function MediaList({
tweet_id: item.tweet_id,
type: item.type,
content: item.content || "",
original_filename: item.original_filename || "",
author_username: item.author_username || "",
})),
output_dir: settings.downloadPath,
output_dir: getOutputDir(),
username: accountInfo.name,
proxy: settings.proxy || "",
});
const response = await DownloadMediaWithMetadata(request);
if (response.success) {
logger.success(`Downloaded ${response.downloaded} files`);
toast.success(`${response.downloaded} files downloaded`);
const parts: string[] = [];
if (response.downloaded > 0) {
parts.push(`${response.downloaded} file${response.downloaded !== 1 ? 's' : ''} downloaded`);
}
if (response.skipped > 0) {
parts.push(`${response.skipped} file${response.skipped !== 1 ? 's' : ''} already exist${response.skipped !== 1 ? '' : 's'}`);
}
if (response.failed > 0) {
parts.push(`${response.failed} failed`);
}
const message = parts.length > 0 ? parts.join(', ') : 'Download completed';
// Use info toast if only skipped files (no downloaded, no failed)
if (response.downloaded === 0 && response.failed === 0 && response.skipped > 0) {
logger.info(message);
toast.info(message);
} else {
logger.success(message);
toast.success(message);
}
setHasDownloaded(true);
// Check if there are GIFs and FFmpeg is installed
const hasGifItems = itemsWithIndices.some(({ item }) => item.type === "gif" || item.type === "animated_gif");
if (hasGifItems) {
setHasGifs(true);
const installed = await IsFFmpegInstalled();
setFfmpegInstalled(installed);
}
// Check if FFmpeg is installed for GIF conversion
const installed = await IsFFmpegInstalled();
setFfmpegInstalled(installed);
} else {
logger.error(response.message);
toast.error("Download failed");
@@ -486,10 +605,22 @@ export function MediaList({
const handleOpenFolder = async () => {
const settings = getSettings();
// Build path - backend will handle path separators with filepath.Clean
const folderPath = settings.downloadPath
? `${settings.downloadPath}/${accountInfo.name}`
: accountInfo.name;
const isBookmarks = accountInfo.nick === "My Bookmarks";
const isLikes = accountInfo.nick === "My Likes";
// Build path - for bookmarks/likes, use the folder structure
let folderPath: string;
if (isBookmarks || isLikes) {
const separator = settings.downloadPath.includes("/") ? "/" : "\\";
const folderName = isBookmarks ? "My Bookmarks" : "My Likes";
folderPath = settings.downloadPath
? `${settings.downloadPath}${separator}${folderName}`
: folderName;
} else {
folderPath = settings.downloadPath
? `${settings.downloadPath}/${accountInfo.name}`
: accountInfo.name;
}
try {
await OpenFolder(folderPath);
@@ -508,8 +639,18 @@ export function MediaList({
const handleConvertGifs = async () => {
const settings = getSettings();
// Use forward slash for cross-platform compatibility (Go's filepath.Join handles it)
const folderPath = `${settings.downloadPath}/${accountInfo.name}`;
const isBookmarks = accountInfo.nick === "My Bookmarks";
const isLikes = accountInfo.nick === "My Likes";
// Build path - for bookmarks/likes, use the folder structure
let folderPath: string;
if (isBookmarks || isLikes) {
const separator = settings.downloadPath.includes("/") ? "/" : "\\";
const folderName = isBookmarks ? "My Bookmarks" : "My Likes";
folderPath = `${settings.downloadPath}${separator}${folderName}`;
} else {
folderPath = `${settings.downloadPath}/${accountInfo.name}`;
}
setIsConverting(true);
logger.info("Converting GIFs...");
@@ -525,7 +666,16 @@ export function MediaList({
if (response.success) {
logger.success(`Converted ${response.converted} GIFs`);
toast.success(`${response.converted} GIFs converted`);
setHasGifs(false);
// Re-check if gifs folder still has MP4 files after conversion
const settings = getSettings();
let folderName = accountInfo.name;
if (accountInfo.nick === "My Bookmarks" || accountInfo.name === "bookmarks") {
folderName = "My Bookmarks";
} else if (accountInfo.nick === "My Likes" || accountInfo.name === "likes") {
folderName = "My Likes";
}
const hasMP4 = await CheckGifsFolderHasMP4(settings.downloadPath, folderName);
setGifsFolderHasMP4(hasMP4);
} else {
logger.error(response.message);
toast.error("Convert failed");
@@ -542,20 +692,28 @@ export function MediaList({
return (
<div className="space-y-4">
{/* Account Info Card */}
{accountInfo.name === "bookmarks" ? (
// Bookmarks mode - simple card without account info
{accountInfo.name === "bookmarks" || accountInfo.name === "likes" ? (
// Bookmarks/Likes mode - simple card without account info
<div className="flex items-center gap-4 p-4 bg-muted/50 rounded-lg">
<div className="w-16 h-16 rounded-full bg-primary/10 flex items-center justify-center">
<Bookmark className="h-8 w-8 text-primary" />
{accountInfo.name === "bookmarks" ? (
<Bookmark className="h-8 w-8 text-primary" />
) : (
<Heart className="h-8 w-8 text-primary" />
)}
</div>
<div className="flex-1">
<h2 className="text-xl font-semibold">My Bookmarks</h2>
<p className="text-sm text-muted-foreground mt-1">
Your saved tweets from various accounts
</p>
<h2 className="text-xl font-semibold">{accountInfo.nick}</h2>
</div>
<div className="text-right">
<div className="text-2xl font-bold text-primary">{formatNumberWithComma(totalUrls)}</div>
<div className="flex items-center justify-end gap-2">
{newMediaCount !== null && newMediaCount > 0 && (
<div className="text-lg font-semibold text-green-600 dark:text-green-400 animate-in fade-in slide-in-from-left-2 duration-300">
{formatNumberWithComma(newMediaCount)}+
</div>
)}
<div className="text-2xl font-bold text-primary">{formatNumberWithComma(totalUrls)}</div>
</div>
<div className="text-sm text-muted-foreground">items found</div>
</div>
</div>
@@ -583,7 +741,7 @@ export function MediaList({
</span>
<span className="flex items-center gap-1">
<MessageSquare className="h-3.5 w-3.5" />
{formatNumber(accountInfo.statuses_count)} tweets
{formatNumber(accountInfo.statuses_count)} posts
</span>
{accountInfo.date && (
<span className="flex items-center gap-1">
@@ -594,7 +752,14 @@ export function MediaList({
</div>
</div>
<div className="text-right">
<div className="text-2xl font-bold text-primary">{formatNumberWithComma(totalUrls)}</div>
<div className="flex items-center justify-end gap-2">
{newMediaCount !== null && newMediaCount > 0 && (
<div className="text-lg font-semibold text-green-600 dark:text-green-400 animate-in fade-in slide-in-from-left-2 duration-300">
{formatNumberWithComma(newMediaCount)}+
</div>
)}
<div className="text-2xl font-bold text-primary">{formatNumberWithComma(totalUrls)}</div>
</div>
<div className="text-sm text-muted-foreground">items found</div>
</div>
</div>
@@ -620,24 +785,30 @@ export function MediaList({
</SelectTrigger>
<SelectContent>
<SelectItem value="all">All ({formatNumberWithComma(totalUrls)})</SelectItem>
<SelectItem value="photo">
<span className="flex items-center gap-2">
<Image className="h-4 w-4 text-blue-500" />
Images ({formatNumberWithComma(mediaCounts.photo)})
</span>
</SelectItem>
<SelectItem value="video">
<span className="flex items-center gap-2">
<Video className="h-4 w-4 text-purple-500" />
Videos ({formatNumberWithComma(mediaCounts.video)})
</span>
</SelectItem>
<SelectItem value="gif">
<span className="flex items-center gap-2">
<Film className="h-4 w-4 text-green-500" />
GIFs ({formatNumberWithComma(mediaCounts.gif)})
</span>
</SelectItem>
{mediaCounts.photo > 0 && (
<SelectItem value="photo">
<span className="flex items-center gap-2">
<Image className="h-4 w-4 text-blue-500" />
Images ({formatNumberWithComma(mediaCounts.photo)})
</span>
</SelectItem>
)}
{mediaCounts.video > 0 && (
<SelectItem value="video">
<span className="flex items-center gap-2">
<Video className="h-4 w-4 text-purple-500" />
Videos ({formatNumberWithComma(mediaCounts.video)})
</span>
</SelectItem>
)}
{mediaCounts.gif > 0 && (
<SelectItem value="gif">
<span className="flex items-center gap-2">
<Film className="h-4 w-4 text-green-500" />
GIFs ({formatNumberWithComma(mediaCounts.gif)})
</span>
</SelectItem>
)}
</SelectContent>
</Select>
)}
@@ -671,27 +842,23 @@ export function MediaList({
</div>
<div className="flex-1" />
{hasDownloaded && (
<Button variant="outline" onClick={handleOpenFolder}>
<FolderOpen className="h-4 w-4" />
Open Folder
</Button>
)}
{hasGifs && ffmpegInstalled && (
<Button variant="outline" onClick={handleConvertGifs} disabled={isConverting}>
{isConverting ? (
<>
<Spinner />
Converting...
</>
) : (
<>
<Film className="h-4 w-4" />
Convert GIFs
</>
)}
</Button>
)}
<Button variant="outline" onClick={handleOpenFolder} disabled={!folderExists}>
<FolderOpen className="h-4 w-4" />
Open Folder
</Button>
<Button variant="outline" onClick={handleConvertGifs} disabled={isConverting || !gifsFolderHasMP4 || !ffmpegInstalled}>
{isConverting ? (
<>
<Spinner />
Converting...
</>
) : (
<>
<Film className="h-4 w-4" />
Convert GIFs
</>
)}
</Button>
<div className="flex items-center gap-2">
{isDownloading && (
<Button variant="destructive" onClick={handleStopDownload}>
@@ -745,7 +912,7 @@ export function MediaList({
{/* Media Grid/List */}
{viewMode === "list" ? (
<div className="space-y-2">
{filteredTimeline.map((item, index) => {
{filteredTimeline.slice(0, visibleCount).map((item, index) => {
const isSelected = selectedItems.has(index);
const itemKey = getItemKey(item);
const isItemDownloaded = downloadedItems.has(itemKey);
@@ -770,7 +937,7 @@ export function MediaList({
className="w-16 h-16 rounded overflow-hidden bg-muted shrink-0 cursor-pointer hover:opacity-80 transition-opacity"
onClick={() => openPreview(index)}
>
{item.type === "photo" ? (
{item.type === "photo" || item.type === "animated_gif" || item.type === "gif" ? (
<img
src={getThumbnailUrl(item.url)}
alt=""
@@ -828,10 +995,10 @@ export function MediaList({
size="icon"
variant="default"
onClick={async () => {
const settings = getSettings();
setDownloadingItem(itemKey);
currentDownloadingItemKeyRef.current = itemKey;
try {
const settings = getSettings();
const request = new main.DownloadMediaWithMetadataRequest({
items: [new main.MediaItemRequest({
url: item.url,
@@ -839,9 +1006,12 @@ export function MediaList({
tweet_id: item.tweet_id,
type: item.type,
content: item.content || "",
original_filename: item.original_filename || "",
author_username: item.author_username || "",
})],
output_dir: settings.downloadPath,
output_dir: getOutputDir(),
username: accountInfo.name,
proxy: settings.proxy || "",
});
const response = await DownloadMediaWithMetadata(request);
if (response.success) {
@@ -903,7 +1073,7 @@ export function MediaList({
</div>
) : (
<div className={`grid gap-3 ${viewMode === "large" ? "grid-cols-4" : "grid-cols-6"}`}>
{filteredTimeline.map((item, index) => {
{filteredTimeline.slice(0, visibleCount).map((item, index) => {
const isSelected = selectedItems.has(index);
const itemKey = getItemKey(item);
const isItemDownloaded = downloadedItems.has(itemKey);
@@ -923,7 +1093,7 @@ export function MediaList({
className="aspect-square bg-muted relative cursor-pointer"
onClick={() => openPreview(index)}
>
{item.type === "photo" ? (
{item.type === "photo" || item.type === "animated_gif" || item.type === "gif" ? (
<img
src={getThumbnailUrl(item.url)}
alt=""
@@ -946,10 +1116,10 @@ export function MediaList({
className="h-8 w-8"
onClick={async (e) => {
e.stopPropagation();
const settings = getSettings();
setDownloadingItem(itemKey);
currentDownloadingItemKeyRef.current = itemKey;
try {
const settings = getSettings();
const request = new main.DownloadMediaWithMetadataRequest({
items: [new main.MediaItemRequest({
url: item.url,
@@ -957,9 +1127,11 @@ export function MediaList({
tweet_id: item.tweet_id,
type: item.type,
content: item.content || "",
author_username: item.author_username || "",
})],
output_dir: settings.downloadPath,
output_dir: getOutputDir(),
username: accountInfo.name,
proxy: settings.proxy || "",
});
const response = await DownloadMediaWithMetadata(request);
if (response.success) {
@@ -1075,6 +1247,13 @@ export function MediaList({
</div>
)}
{/* Sentinel for lazy loading - only show if there are more items to load */}
{visibleCount < filteredTimeline.length && (
<div ref={loadMoreRef} className="h-20 flex items-center justify-center w-full">
<Spinner />
</div>
)}
{/* Media Preview Overlay */}
{previewIndex !== null && filteredTimeline[previewIndex] && (
<div
@@ -1097,7 +1276,7 @@ export function MediaList({
{/* Counter - above media */}
<div className="text-white text-sm bg-black/50 px-4 py-1.5 rounded-full mb-4">
{previewIndex + 1} / {filteredTimeline.length}
{formatNumberWithComma(previewIndex + 1)} / {formatNumberWithComma(filteredTimeline.length)}
</div>
{/* Media content - center */}
@@ -1193,10 +1372,10 @@ export function MediaList({
size="sm"
className="h-9"
onClick={async () => {
const settings = getSettings();
setDownloadingItem(itemKey);
currentDownloadingItemKeyRef.current = itemKey;
try {
const settings = getSettings();
const request = new main.DownloadMediaWithMetadataRequest({
items: [new main.MediaItemRequest({
url: item.url,
@@ -1204,9 +1383,12 @@ export function MediaList({
tweet_id: item.tweet_id,
type: item.type,
content: item.content || "",
original_filename: item.original_filename || "",
author_username: item.author_username || "",
})],
output_dir: settings.downloadPath,
output_dir: getOutputDir(),
username: accountInfo.name,
proxy: settings.proxy || "",
});
const response = await DownloadMediaWithMetadata(request);
if (response.success) {
+443 -42
View File
@@ -3,7 +3,6 @@ import { Button } from "@/components/ui/button";
import { InputWithContext } from "@/components/ui/input-with-context";
import { Label } from "@/components/ui/label";
import {
Search,
XCircle,
Calendar,
StopCircle,
@@ -19,8 +18,20 @@ import {
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,
@@ -38,14 +49,34 @@ import { Settings as SettingsIcon } from "lucide-react";
import { FetchHistory } from "@/components/FetchHistory";
import type { HistoryItem } from "@/components/FetchHistory";
import { cn } from "@/lib/utils";
import { getSettings, updateSettings, type FetchMode as SettingsFetchMode, type MediaType as SettingsMediaType } from "@/lib/settings";
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;
@@ -69,6 +100,22 @@ interface SearchBarProps {
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({
@@ -84,16 +131,44 @@ export function SearchBar({
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>("public");
const [privateType, setPrivateType] = useState<PrivateType>("bookmarks");
const [mediaType, setMediaType] = useState<SettingsMediaType>(getSettings().mediaType);
const [retweets, setRetweets] = useState(getSettings().includeRetweets);
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);
const [currentFetchMode, setCurrentFetchMode] = useState<SettingsFetchMode>(getSettings().fetchMode);
// Separate auth tokens for public and private modes
const [publicAuthToken, setPublicAuthToken] = useState("");
@@ -138,42 +213,150 @@ export function SearchBar({
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">
{/* Mode Toggle */}
<div className="flex justify-center">
<div className="flex gap-1 p-1 bg-muted rounded-lg w-fit">
{/* 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={() => setMode("public")}
onClick={() => onFetchTypeChange?.("single")}
className={cn(
"flex items-center gap-2 px-4 py-2 rounded-md text-sm font-medium transition-all cursor-pointer",
mode === "public"
"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"
)}
>
<Globe className="h-4 w-4" />
Public
<User className="h-3 w-3" />
Single
</button>
<button
type="button"
onClick={() => setMode("private")}
onClick={() => onFetchTypeChange?.("multiple")}
className={cn(
"flex items-center gap-2 px-4 py-2 rounded-md text-sm font-medium transition-all cursor-pointer",
mode === "private"
"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"
)}
>
<Lock className="h-4 w-4" />
Private
<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>
{/* Username Input - for public mode and likes mode */}
{(mode === "public" || isLikesMode) && (
{/* 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"}
@@ -205,10 +388,23 @@ export function SearchBar({
</div>
<div className="flex items-center gap-2">
{loading && (
<Button variant="destructive" onClick={onStopFetch}>
<StopCircle className="h-4 w-4" />
Stop
</Button>
<>
{/* 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" && (
@@ -219,11 +415,11 @@ export function SearchBar({
<Trash2 className="h-4 w-4" />
</Button>
</TooltipTrigger>
<TooltipContent>Clear resume data</TooltipContent>
<TooltipContent>Clear Resume</TooltipContent>
</Tooltip>
<Button variant="secondary" onClick={handleResume} disabled={!hasAuthToken}>
<RotateCcw className="h-4 w-4" />
Resume ({resumeInfo.mediaCount})
Resume ({resumeInfo.mediaCount.toLocaleString()})
</Button>
</>
)}
@@ -235,7 +431,7 @@ export function SearchBar({
</>
) : (
<>
{isLikesMode ? <Heart className="h-4 w-4" /> : <Search className="h-4 w-4" />}
{isLikesMode ? <Heart className="h-4 w-4" /> : <CloudDownload className="h-4 w-4" />}
{isLikesMode ? "Fetch Likes" : "Fetch"}
</>
)}
@@ -270,11 +466,14 @@ export function SearchBar({
</button>
{/* Private Mode Options - My Bookmarks / My Likes */}
{mode === "private" && (
{mode === "private" && fetchType === "single" && (
<>
<button
type="button"
onClick={() => setPrivateType("bookmarks")}
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"
@@ -287,7 +486,10 @@ export function SearchBar({
</button>
<button
type="button"
onClick={() => setPrivateType("likes")}
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"
@@ -305,10 +507,23 @@ export function SearchBar({
{isBookmarksMode && (
<div className="flex items-center gap-2 ml-auto">
{loading && (
<Button variant="destructive" onClick={onStopFetch}>
<StopCircle className="h-4 w-4" />
Stop
</Button>
<>
{/* 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 ? (
@@ -393,22 +608,44 @@ export function SearchBar({
{showAdvanced && (
<div className="p-3 border rounded-lg bg-muted/30 space-y-3">
{/* Options Row */}
<div className="flex items-center gap-4">
<div className="flex items-center gap-4 flex-wrap">
{/* Fetch Mode */}
<div className="flex items-center gap-2">
<Label htmlFor="fetch-mode" className="text-sm">
Fetch Mode
</Label>
<Select value={currentFetchMode} onValueChange={(value: SettingsFetchMode) => {
updateSettings({ fetchMode: value });
setCurrentFetchMode(value);
}}>
<SelectTrigger id="fetch-mode" className="w-auto h-8 bg-background">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="batch">Batch</SelectItem>
<SelectItem value="single">Single</SelectItem>
</SelectContent>
</Select>
</div>
{/* Media Type */}
<div className="flex items-center gap-2">
<Label htmlFor="media-type" className="text-sm">
Media Type
</Label>
<Select value={mediaType} onValueChange={setMediaType}>
<Select value={mediaType} onValueChange={(value: SettingsMediaType) => {
updateSettings({ mediaType: value });
setMediaType(value);
}}>
<SelectTrigger id="media-type" className="w-auto h-8 bg-background">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">All Media</SelectItem>
<SelectItem value="image">Images Only</SelectItem>
<SelectItem value="video">Videos Only</SelectItem>
<SelectItem value="gif">GIFs Only</SelectItem>
<SelectItem value="text">Text Only (No 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>
@@ -418,7 +655,11 @@ export function SearchBar({
<Checkbox
id="retweets"
checked={retweets}
onCheckedChange={(checked) => setRetweets(checked as boolean)}
onCheckedChange={(checked) => {
const value = checked as boolean;
updateSettings({ includeRetweets: value });
setRetweets(value);
}}
className="bg-background"
/>
<Label htmlFor="retweets" className="text-sm cursor-pointer">
@@ -471,7 +712,167 @@ export function SearchBar({
</div>
)}
{!hasResult && mode === "public" && (
{/* 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}
-327
View File
@@ -1,327 +0,0 @@
import { useState, useEffect } from "react";
import { Button } from "@/components/ui/button";
import { InputWithContext } from "@/components/ui/input-with-context";
import { Label } from "@/components/ui/label";
import {
Dialog,
DialogContent,
DialogFooter,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Settings as SettingsIcon, FolderOpen, Save, RotateCcw, X, Info, Download, Check, Volume2 } from "lucide-react";
import { Spinner } from "@/components/ui/spinner";
import {
Tooltip,
TooltipContent,
TooltipTrigger,
} from "@/components/ui/tooltip";
import { Switch } from "@/components/ui/switch";
import { getSettings, getSettingsWithDefaults, saveSettings, resetToDefaultSettings, applyThemeMode, type Settings as SettingsType } from "@/lib/settings";
import { themes, applyTheme } from "@/lib/themes";
import { toastWithSound as toast } from "@/lib/toast-with-sound";
import { SelectFolder, IsFFmpegInstalled, DownloadFFmpeg } from "../../wailsjs/go/main/App";
export function Settings() {
const [open, setOpen] = useState(false);
const [savedSettings, setSavedSettings] = useState<SettingsType>(getSettings());
const [tempSettings, setTempSettings] = useState<SettingsType>(savedSettings);
const [, setIsLoadingDefaults] = useState(false);
const [isDark, setIsDark] = useState(document.documentElement.classList.contains('dark'));
const [ffmpegInstalled, setFfmpegInstalled] = useState(false);
const [downloadingFFmpeg, setDownloadingFFmpeg] = useState(false);
useEffect(() => {
applyThemeMode(savedSettings.themeMode);
applyTheme(savedSettings.theme);
const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");
const handleChange = () => {
if (savedSettings.themeMode === "auto") {
applyThemeMode("auto");
applyTheme(savedSettings.theme);
}
};
mediaQuery.addEventListener("change", handleChange);
return () => mediaQuery.removeEventListener("change", handleChange);
}, [savedSettings.themeMode, savedSettings.theme]);
useEffect(() => {
if (open) {
applyThemeMode(tempSettings.themeMode);
applyTheme(tempSettings.theme);
setTimeout(() => {
setIsDark(document.documentElement.classList.contains('dark'));
}, 0);
const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");
const handleChange = () => {
if (tempSettings.themeMode === "auto") {
applyThemeMode("auto");
applyTheme(tempSettings.theme);
setTimeout(() => {
setIsDark(document.documentElement.classList.contains('dark'));
}, 0);
}
};
mediaQuery.addEventListener("change", handleChange);
return () => mediaQuery.removeEventListener("change", handleChange);
}
}, [open, tempSettings.themeMode, tempSettings.theme]);
useEffect(() => {
const loadDefaults = async () => {
if (!savedSettings.downloadPath) {
setIsLoadingDefaults(true);
const settingsWithDefaults = await getSettingsWithDefaults();
setSavedSettings(settingsWithDefaults);
setTempSettings(settingsWithDefaults);
setIsLoadingDefaults(false);
}
};
loadDefaults();
// Check FFmpeg status
IsFFmpegInstalled().then(setFfmpegInstalled);
}, []);
useEffect(() => {
if (open) {
setTempSettings(savedSettings);
}
}, [open, savedSettings]);
const handleSave = () => {
saveSettings(tempSettings);
setSavedSettings(tempSettings);
setOpen(false);
};
const handleReset = async () => {
const defaultSettings = await resetToDefaultSettings();
setTempSettings(defaultSettings);
setSavedSettings(defaultSettings);
applyThemeMode(defaultSettings.themeMode);
applyTheme(defaultSettings.theme);
};
const handleCancel = () => {
applyThemeMode(savedSettings.themeMode);
applyTheme(savedSettings.theme);
setTempSettings(savedSettings);
setOpen(false);
};
const handleOpenChange = (newOpen: boolean) => {
if (!newOpen) {
applyThemeMode(savedSettings.themeMode);
applyTheme(savedSettings.theme);
setTempSettings(savedSettings);
}
setOpen(newOpen);
};
const handleBrowseFolder = async () => {
try {
const selectedPath = await SelectFolder(tempSettings.downloadPath || "");
if (selectedPath && selectedPath.trim() !== "") {
setTempSettings((prev) => ({ ...prev, downloadPath: selectedPath }));
}
} catch (error) {
console.error("Error selecting folder:", error);
}
};
const handleDownloadFFmpeg = async () => {
setDownloadingFFmpeg(true);
try {
await DownloadFFmpeg();
setFfmpegInstalled(true);
toast.success("FFmpeg downloaded successfully");
} catch (error) {
toast.error("Failed to download FFmpeg");
console.error("Error downloading FFmpeg:", error);
} finally {
setDownloadingFFmpeg(false);
}
};
return (
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogTrigger asChild>
<Button variant="outline" size="icon">
<SettingsIcon className="h-5 w-5" />
</Button>
</DialogTrigger>
<DialogContent className="sm:max-w-[480px] flex flex-col p-6 [&>button]:hidden" aria-describedby={undefined}>
<div className="absolute right-4 top-4">
<Button
variant="ghost"
size="icon"
className="h-6 w-6 opacity-70 hover:opacity-100"
onClick={handleCancel}
>
<X className="h-4 w-4" />
</Button>
</div>
<DialogTitle className="text-sm font-medium">Settings</DialogTitle>
{/* 2 Column Grid Layout */}
<div className="grid grid-cols-2 gap-x-6 gap-y-4 py-2">
{/* LEFT COLUMN */}
{/* Download Path */}
<div className="space-y-2 col-span-2">
<Label htmlFor="download-path">Download Path</Label>
<div className="flex gap-2">
<InputWithContext
id="download-path"
value={tempSettings.downloadPath}
onChange={(e) => setTempSettings((prev) => ({ ...prev, downloadPath: e.target.value }))}
placeholder="C:\Users\YourUsername\Pictures"
/>
<Tooltip>
<TooltipTrigger asChild>
<Button type="button" onClick={handleBrowseFolder} size="icon">
<FolderOpen className="h-4 w-4" />
</Button>
</TooltipTrigger>
<TooltipContent>Browse Folder</TooltipContent>
</Tooltip>
</div>
</div>
{/* LEFT: Mode */}
<div className="space-y-2">
<Label htmlFor="theme-mode">Mode</Label>
<Select
value={tempSettings.themeMode}
onValueChange={(value) => setTempSettings((prev) => ({ ...prev, themeMode: value as any }))}
>
<SelectTrigger id="theme-mode">
<SelectValue placeholder="Select theme mode" />
</SelectTrigger>
<SelectContent>
<SelectItem value="auto">Auto</SelectItem>
<SelectItem value="light">Light</SelectItem>
<SelectItem value="dark">Dark</SelectItem>
</SelectContent>
</Select>
</div>
{/* RIGHT: GIF Conversion */}
<div className="space-y-2">
<Label className="flex items-center gap-2">
GIF Conversion
<Tooltip>
<TooltipTrigger asChild>
<Info className="h-3.5 w-3.5 text-muted-foreground cursor-help" />
</TooltipTrigger>
<TooltipContent side="top">
<p>FFmpeg is required to convert Twitter's MP4 to actual GIF format</p>
</TooltipContent>
</Tooltip>
</Label>
<div className="h-9 flex items-center">
{ffmpegInstalled ? (
<div className="flex items-center gap-2 text-sm text-green-600 dark:text-green-400">
<Check className="h-4 w-4" />
Installed
</div>
) : (
<Button
variant="outline"
size="sm"
className="h-9"
onClick={handleDownloadFFmpeg}
disabled={downloadingFFmpeg}
>
{downloadingFFmpeg ? (
<>
<Spinner />
Downloading...
</>
) : (
<>
<Download className="h-4 w-4" />
Download FFmpeg
</>
)}
</Button>
)}
</div>
</div>
{/* LEFT: Accent */}
<div className="space-y-2">
<Label htmlFor="theme">Accent</Label>
<Select
value={tempSettings.theme}
onValueChange={(value) => setTempSettings((prev) => ({ ...prev, theme: value }))}
>
<SelectTrigger id="theme">
<SelectValue placeholder="Select a theme" />
</SelectTrigger>
<SelectContent>
{themes.map((theme) => (
<SelectItem key={theme.name} value={theme.name}>
<span className="flex items-center gap-2">
<span
className="w-3 h-3 rounded-full border border-border"
style={{
backgroundColor: isDark
? theme.cssVars.dark.primary
: theme.cssVars.light.primary
}}
/>
{theme.label}
</span>
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{/* RIGHT: Sound Effects */}
<div className="space-y-2">
<Label htmlFor="sfx-enabled" className="flex items-center gap-2">
<Volume2 className="h-4 w-4 text-muted-foreground" />
Sound Effects
</Label>
<div className="h-9 flex items-center">
<Switch
id="sfx-enabled"
checked={tempSettings.sfxEnabled}
onCheckedChange={(checked) => setTempSettings(prev => ({ ...prev, sfxEnabled: checked }))}
/>
</div>
</div>
</div>
<DialogFooter className="gap-2 sm:justify-between">
<Button variant="outline" onClick={handleReset} className="gap-1.5">
<RotateCcw className="h-4 w-4" />
Reset to Default
</Button>
<div className="flex gap-2">
<Button variant="outline" onClick={handleCancel}>
Cancel
</Button>
<Button onClick={handleSave} className="gap-1.5">
<Save className="h-4 w-4" />
Save Changes
</Button>
</div>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
+179 -35
View File
@@ -10,12 +10,20 @@ import {
SelectValue,
} from "@/components/ui/select";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { FolderOpen, Save, RotateCcw, Info, Download, Check, Volume2 } from "lucide-react";
import { FolderOpen, Save, RotateCcw, Info, Download, Check } from "lucide-react";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Spinner } from "@/components/ui/spinner";
import { 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 } from "../../wailsjs/go/main/App";
import { SelectFolder, IsFFmpegInstalled, DownloadFFmpeg, IsExifToolInstalled, DownloadExifTool } from "../../wailsjs/go/main/App";
import { toastWithSound as toast } from "@/lib/toast-with-sound";
export function SettingsPage() {
@@ -24,6 +32,9 @@ export function SettingsPage() {
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);
const [showResetConfirm, setShowResetConfirm] = useState(false);
useEffect(() => {
applyThemeMode(savedSettings.themeMode);
@@ -60,8 +71,9 @@ export function SettingsPage() {
};
loadDefaults();
// Check FFmpeg status
// Check FFmpeg and ExifTool status
IsFFmpegInstalled().then(setFfmpegInstalled);
IsExifToolInstalled().then(setExiftoolInstalled);
}, []);
const handleSave = () => {
@@ -77,6 +89,7 @@ export function SettingsPage() {
applyThemeMode(defaultSettings.themeMode);
applyTheme(defaultSettings.theme);
applyFont(defaultSettings.fontFamily);
setShowResetConfirm(false);
toast.success("Settings reset to default");
};
@@ -106,6 +119,20 @@ export function SettingsPage() {
}
};
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>
@@ -198,7 +225,6 @@ export function SettingsPage() {
{/* Sound Effects */}
<div className="flex items-center gap-3 pt-2">
<Volume2 className="h-4 w-4 text-muted-foreground" />
<Label htmlFor="sfx-enabled" className="cursor-pointer text-sm">Sound Effects</Label>
<Switch
id="sfx-enabled"
@@ -210,6 +236,49 @@ export function SettingsPage() {
{/* 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">
@@ -255,58 +324,117 @@ export function SettingsPage() {
{/* GIF Quality - only show if FFmpeg installed */}
{ffmpegInstalled && (
<>
<div className="space-y-2">
<Label htmlFor="gif-quality">GIF Quality</Label>
<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,
// Auto-select "original" when switching to "better"
gifResolution: value === "better" ? "original" : prev.gifResolution,
}));
}}
>
<SelectTrigger id="gif-quality">
<SelectTrigger id="gif-quality" className="w-auto">
<SelectValue placeholder="Select quality" />
</SelectTrigger>
<SelectContent>
<SelectItem value="fast">Fast (Simple conversion)</SelectItem>
<SelectItem value="better">Better (Optimized palette)</SelectItem>
<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>
{/* GIF Resolution - only show if Better quality selected */}
{tempSettings.gifQuality === "better" && (
<div className="space-y-2">
<Label htmlFor="gif-resolution">GIF Resolution</Label>
<Select
value={tempSettings.gifResolution}
onValueChange={(value: GifResolution) => setTempSettings((prev) => ({ ...prev, gifResolution: value }))}
>
<SelectTrigger id="gif-resolution">
<SelectValue placeholder="Select resolution" />
</SelectTrigger>
<SelectContent>
<SelectItem value="original">Original (No scaling, 15 fps)</SelectItem>
<SelectItem value="high">High (800px, 15 fps)</SelectItem>
<SelectItem value="medium">Medium (600px, 10 fps)</SelectItem>
<SelectItem value="low">Low (400px, 8 fps)</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">
<Button variant="outline" onClick={() => setShowResetConfirm(true)} className="gap-1.5">
<RotateCcw className="h-4 w-4" />
Reset to Default
</Button>
@@ -315,6 +443,22 @@ export function SettingsPage() {
Save Changes
</Button>
</div>
{/* Reset Confirmation Dialog */}
<Dialog open={showResetConfirm} onOpenChange={setShowResetConfirm}>
<DialogContent className="max-w-md [&>button]:hidden">
<DialogHeader>
<DialogTitle>Reset to Default?</DialogTitle>
<DialogDescription>
This will reset all settings to their default values. Your custom configurations will be lost.
</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button variant="outline" onClick={() => setShowResetConfirm(false)}>Cancel</Button>
<Button onClick={handleReset}>Reset</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
);
}
+107 -47
View File
@@ -1,4 +1,10 @@
import { Home, Settings, Bug, Database, LayoutGrid } from "lucide-react";
import { HomeIcon } from "@/components/ui/home";
import { SettingsIcon } from "@/components/ui/settings";
import { ArchiveIcon } from "@/components/ui/archive";
import { TerminalIcon } from "@/components/ui/terminal";
import { GithubIcon } from "@/components/ui/github";
import { BlocksIcon } from "@/components/ui/blocks";
import { CoffeeIcon } from "@/components/ui/coffee";
import {
Tooltip,
TooltipContent,
@@ -15,56 +21,95 @@ interface SidebarProps {
}
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>
))}
{/* Home */}
<Tooltip delayDuration={0}>
<TooltipTrigger asChild>
<Button
variant={currentPage === "main" ? "secondary" : "ghost"}
size="icon"
className="h-10 w-10"
onClick={() => onPageChange("main")}
>
<HomeIcon size={20} />
</Button>
</TooltipTrigger>
<TooltipContent side="right">
<p>Home</p>
</TooltipContent>
</Tooltip>
{/* Settings */}
<Tooltip delayDuration={0}>
<TooltipTrigger asChild>
<Button
variant={currentPage === "settings" ? "secondary" : "ghost"}
size="icon"
className="h-10 w-10"
onClick={() => onPageChange("settings")}
>
<SettingsIcon size={20} />
</Button>
</TooltipTrigger>
<TooltipContent side="right">
<p>Settings</p>
</TooltipContent>
</Tooltip>
{/* Database - using animated archive icon */}
<Tooltip delayDuration={0}>
<TooltipTrigger asChild>
<Button
variant={currentPage === "database" ? "secondary" : "ghost"}
size="icon"
className="h-10 w-10"
onClick={() => onPageChange("database")}
>
<ArchiveIcon size={20} />
</Button>
</TooltipTrigger>
<TooltipContent side="right">
<p>Saved Accounts</p>
</TooltipContent>
</Tooltip>
{/* Debug - using animated terminal icon */}
<Tooltip delayDuration={0}>
<TooltipTrigger asChild>
<Button
variant={currentPage === "debug" ? "secondary" : "ghost"}
size="icon"
className="h-10 w-10"
onClick={() => onPageChange("debug")}
>
<TerminalIcon size={20} />
</Button>
</TooltipTrigger>
<TooltipContent side="right">
<p>Debug Logs</p>
</TooltipContent>
</Tooltip>
</div>
{/* GitHub - below debug */}
<Tooltip delayDuration={0}>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon"
className="h-10 w-10"
onClick={() => openExternal("https://github.com/afkarxyz/Twitter-X-Media-Batch-Downloader/issues")}
>
<svg viewBox="0 0 24 24" className="h-5 w-5" fill="currentColor">
<path d="M12 0c-6.626 0-12 5.373-12 12 0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23.957-.266 1.983-.399 3.003-.404 1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576 4.765-1.589 8.199-6.086 8.199-11.386 0-6.627-5.373-12-12-12z" />
</svg>
</Button>
</TooltipTrigger>
<TooltipContent side="right">
<p>Report Bug</p>
</TooltipContent>
</Tooltip>
{/* Other Projects at bottom */}
<div className="mt-auto">
{/* 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")}
>
<GithubIcon size={20} />
</Button>
</TooltipTrigger>
<TooltipContent side="right">
<p>Report Bug</p>
</TooltipContent>
</Tooltip>
<Tooltip delayDuration={0}>
<TooltipTrigger asChild>
<Button
@@ -73,13 +118,28 @@ export function Sidebar({ currentPage, onPageChange }: SidebarProps) {
className="h-10 w-10"
onClick={() => openExternal("https://exyezed.cc/")}
>
<LayoutGrid className="h-5 w-5" />
<BlocksIcon size={20} />
</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")}
>
<CoffeeIcon size={20} />
</Button>
</TooltipTrigger>
<TooltipContent side="right">
<p>Support me on Ko-fi</p>
</TooltipContent>
</Tooltip>
</div>
</div>
);
-66
View File
@@ -1,66 +0,0 @@
"use client"
import * as React from "react"
import * as AccordionPrimitive from "@radix-ui/react-accordion"
import { ChevronDownIcon } from "lucide-react"
import { cn } from "@/lib/utils"
function Accordion({
...props
}: React.ComponentProps<typeof AccordionPrimitive.Root>) {
return <AccordionPrimitive.Root data-slot="accordion" {...props} />
}
function AccordionItem({
className,
...props
}: React.ComponentProps<typeof AccordionPrimitive.Item>) {
return (
<AccordionPrimitive.Item
data-slot="accordion-item"
className={cn("border-b last:border-b-0", className)}
{...props}
/>
)
}
function AccordionTrigger({
className,
children,
...props
}: React.ComponentProps<typeof AccordionPrimitive.Trigger>) {
return (
<AccordionPrimitive.Header className="flex">
<AccordionPrimitive.Trigger
data-slot="accordion-trigger"
className={cn(
"focus-visible:border-ring focus-visible:ring-ring/50 flex flex-1 items-start justify-between gap-4 rounded-md py-4 text-left text-sm font-medium transition-all outline-none hover:underline focus-visible:ring-[3px] disabled:pointer-events-none disabled:opacity-50 [&[data-state=open]>svg]:rotate-180",
className
)}
{...props}
>
{children}
<ChevronDownIcon className="text-muted-foreground pointer-events-none size-4 shrink-0 translate-y-0.5 transition-transform duration-200" />
</AccordionPrimitive.Trigger>
</AccordionPrimitive.Header>
)
}
function AccordionContent({
className,
children,
...props
}: React.ComponentProps<typeof AccordionPrimitive.Content>) {
return (
<AccordionPrimitive.Content
data-slot="accordion-content"
className="data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down overflow-hidden text-sm"
{...props}
>
<div className={cn("pt-0 pb-4", className)}>{children}</div>
</AccordionPrimitive.Content>
)
}
export { Accordion, AccordionItem, AccordionTrigger, AccordionContent }
+132
View File
@@ -0,0 +1,132 @@
'use client';
import type { Variants } from 'motion/react';
import type { HTMLAttributes } from 'react';
import { forwardRef, useCallback, useImperativeHandle, useRef } from 'react';
import { motion, useAnimation } from 'motion/react';
import { cn } from '@/lib/utils';
export interface ArchiveIconHandle {
startAnimation: () => void;
stopAnimation: () => void;
}
interface ArchiveIconProps extends HTMLAttributes<HTMLDivElement> {
size?: number;
}
const RECT_VARIANTS: Variants = {
normal: {
translateY: 0,
transition: {
duration: 0.2,
type: 'spring',
stiffness: 200,
damping: 25,
},
},
animate: {
translateY: -1.5,
transition: {
duration: 0.2,
type: 'spring',
stiffness: 200,
damping: 25,
},
},
};
const PATH_VARIANTS: Variants = {
normal: { d: 'M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8' },
animate: { d: 'M4 11v9a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V11' },
};
const SECONDARY_PATH_VARIANTS: Variants = {
normal: { d: 'M10 12h4' },
animate: { d: 'M10 15h4' },
};
const ArchiveIcon = forwardRef<ArchiveIconHandle, ArchiveIconProps>(
({ onMouseEnter, onMouseLeave, className, size = 28, ...props }, ref) => {
const controls = useAnimation();
const isControlledRef = useRef(false);
useImperativeHandle(ref, () => {
isControlledRef.current = true;
return {
startAnimation: () => controls.start('animate'),
stopAnimation: () => controls.start('normal'),
};
});
const handleMouseEnter = useCallback(
(e: React.MouseEvent<HTMLDivElement>) => {
if (!isControlledRef.current) {
controls.start('animate');
} else {
onMouseEnter?.(e);
}
},
[controls, onMouseEnter]
);
const handleMouseLeave = useCallback(
(e: React.MouseEvent<HTMLDivElement>) => {
if (!isControlledRef.current) {
controls.start('normal');
} else {
onMouseLeave?.(e);
}
},
[controls, onMouseLeave]
);
return (
<div
className={cn(className)}
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
{...props}
>
<svg
xmlns="http://www.w3.org/2000/svg"
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<motion.rect
width="20"
height="5"
x="2"
y="3"
rx="1"
initial="normal"
animate={controls}
variants={RECT_VARIANTS}
/>
<motion.path
d="M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8"
variants={PATH_VARIANTS}
animate={controls}
/>
<motion.path
d="M10 12h4"
variants={SECONDARY_PATH_VARIANTS}
animate={controls}
/>
</svg>
</div>
);
}
);
ArchiveIcon.displayName = 'ArchiveIcon';
export { ArchiveIcon };
+92
View File
@@ -0,0 +1,92 @@
'use client';
import type { Variants } from 'motion/react';
import type { HTMLAttributes } from 'react';
import { forwardRef, useCallback, useImperativeHandle, useRef } from 'react';
import { motion, useAnimation } from 'motion/react';
import { cn } from '@/lib/utils';
export interface BlocksIconHandle {
startAnimation: () => void;
stopAnimation: () => void;
}
interface BlocksIconProps extends HTMLAttributes<HTMLDivElement> {
size?: number;
}
const VARIANTS: Variants = {
normal: { translateX: 0, translateY: 0 },
animate: { translateX: -4, translateY: 4 },
};
const BlocksIcon = forwardRef<BlocksIconHandle, BlocksIconProps>(
({ onMouseEnter, onMouseLeave, className, size = 28, ...props }, ref) => {
const controls = useAnimation();
const isControlledRef = useRef(false);
useImperativeHandle(ref, () => {
isControlledRef.current = true;
return {
startAnimation: () => controls.start('animate'),
stopAnimation: () => controls.start('normal'),
};
});
const handleMouseEnter = useCallback(
(e: React.MouseEvent<HTMLDivElement>) => {
if (!isControlledRef.current) {
controls.start('animate');
} else {
onMouseEnter?.(e);
}
},
[controls, onMouseEnter]
);
const handleMouseLeave = useCallback(
(e: React.MouseEvent<HTMLDivElement>) => {
if (!isControlledRef.current) {
controls.start('normal');
} else {
onMouseLeave?.(e);
}
},
[controls, onMouseLeave]
);
return (
<div
className={cn(className)}
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
{...props}
>
<svg
xmlns="http://www.w3.org/2000/svg"
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<path d="M10 21V8a1 1 0 0 0-1-1H4a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-5a1 1 0 0 0-1-1H3" />
<motion.path
d="M14 3h7v7h-7z"
variants={VARIANTS}
animate={controls}
/>
</svg>
</div>
);
}
);
BlocksIcon.displayName = 'BlocksIcon';
export { BlocksIcon };
-92
View File
@@ -1,92 +0,0 @@
import * as React from "react"
import { cn } from "@/lib/utils"
function Card({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card"
className={cn(
"bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",
className
)}
{...props}
/>
)
}
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-header"
className={cn(
"@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-2 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",
className
)}
{...props}
/>
)
}
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-title"
className={cn("leading-none font-semibold", className)}
{...props}
/>
)
}
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-description"
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
)
}
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-action"
className={cn(
"col-start-2 row-span-2 row-start-1 self-start justify-self-end",
className
)}
{...props}
/>
)
}
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-content"
className={cn("px-6", className)}
{...props}
/>
)
}
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-footer"
className={cn("flex items-center px-6 [.border-t]:pt-6", className)}
{...props}
/>
)
}
export {
Card,
CardHeader,
CardFooter,
CardTitle,
CardAction,
CardDescription,
CardContent,
}
+118
View File
@@ -0,0 +1,118 @@
'use client';
import type { Variants } from 'motion/react';
import type { HTMLAttributes } from 'react';
import { forwardRef, useCallback, useImperativeHandle, useRef } from 'react';
import { motion, useAnimation } from 'motion/react';
import { cn } from '@/lib/utils';
export interface CoffeeIconHandle {
startAnimation: () => void;
stopAnimation: () => void;
}
interface CoffeeIconProps extends HTMLAttributes<HTMLDivElement> {
size?: number;
}
const PATH_VARIANTS: Variants = {
normal: {
y: 0,
opacity: 1,
},
animate: (custom: number) => ({
y: -3,
opacity: [0, 1, 0],
transition: {
repeat: Infinity,
duration: 1.5,
ease: 'easeInOut',
delay: 0.2 * custom,
},
}),
};
const CoffeeIcon = forwardRef<CoffeeIconHandle, CoffeeIconProps>(
({ onMouseEnter, onMouseLeave, className, size = 28, ...props }, ref) => {
const controls = useAnimation();
const isControlledRef = useRef(false);
useImperativeHandle(ref, () => {
isControlledRef.current = true;
return {
startAnimation: () => controls.start('animate'),
stopAnimation: () => controls.start('normal'),
};
});
const handleMouseEnter = useCallback(
(e: React.MouseEvent<HTMLDivElement>) => {
if (!isControlledRef.current) {
controls.start('animate');
} else {
onMouseEnter?.(e);
}
},
[controls, onMouseEnter]
);
const handleMouseLeave = useCallback(
(e: React.MouseEvent<HTMLDivElement>) => {
if (!isControlledRef.current) {
controls.start('normal');
} else {
onMouseLeave?.(e);
}
},
[controls, onMouseLeave]
);
return (
<div
className={cn(className)}
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
{...props}
>
<svg
xmlns="http://www.w3.org/2000/svg"
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
style={{ overflow: 'visible' }}
>
<motion.path
d="M10 2v2"
animate={controls}
variants={PATH_VARIANTS}
custom={0.2}
/>
<motion.path
d="M14 2v2"
animate={controls}
variants={PATH_VARIANTS}
custom={0.4}
/>
<motion.path
d="M6 2v2"
animate={controls}
variants={PATH_VARIANTS}
custom={0}
/>
<path d="M16 8a1 1 0 0 1 1 1v8a4 4 0 0 1-4 4H7a4 4 0 0 1-4-4V9a1 1 0 0 1 1-1h14a4 4 0 1 1 0 8h-1" />
</svg>
</div>
);
}
);
CoffeeIcon.displayName = 'CoffeeIcon';
export { CoffeeIcon };
@@ -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,
}
+149
View File
@@ -0,0 +1,149 @@
'use client';
import type { Variants } from 'motion/react';
import type { HTMLAttributes } from 'react';
import { forwardRef, useCallback, useImperativeHandle, useRef } from 'react';
import { motion, useAnimation } from 'motion/react';
import { cn } from '@/lib/utils';
export interface GithubIconHandle {
startAnimation: () => void;
stopAnimation: () => void;
}
interface GithubIconProps extends HTMLAttributes<HTMLDivElement> {
size?: number;
}
const BODY_VARIANTS: Variants = {
normal: {
opacity: 1,
pathLength: 1,
scale: 1,
transition: {
duration: 0.3,
},
},
animate: {
opacity: [0, 1],
pathLength: [0, 1],
scale: [0.9, 1],
transition: {
duration: 0.4,
},
},
};
const TAIL_VARIANTS: Variants = {
normal: {
pathLength: 1,
rotate: 0,
transition: {
duration: 0.3,
},
},
draw: {
pathLength: [0, 1],
rotate: 0,
transition: {
duration: 0.5,
},
},
wag: {
pathLength: 1,
rotate: [0, -15, 15, -10, 10, -5, 5],
transition: {
duration: 2.5,
ease: 'easeInOut',
repeat: Infinity,
},
},
};
const GithubIcon = forwardRef<GithubIconHandle, GithubIconProps>(
({ onMouseEnter, onMouseLeave, className, size = 28, ...props }, ref) => {
const bodyControls = useAnimation();
const tailControls = useAnimation();
const isControlledRef = useRef(false);
useImperativeHandle(ref, () => {
isControlledRef.current = true;
return {
startAnimation: async () => {
bodyControls.start('animate');
await tailControls.start('draw');
tailControls.start('wag');
},
stopAnimation: () => {
bodyControls.start('normal');
tailControls.start('normal');
},
};
});
const handleMouseEnter = useCallback(
async (e: React.MouseEvent<HTMLDivElement>) => {
if (!isControlledRef.current) {
bodyControls.start('animate');
await tailControls.start('draw');
tailControls.start('wag');
} else {
onMouseEnter?.(e);
}
},
[bodyControls, onMouseEnter, tailControls]
);
const handleMouseLeave = useCallback(
(e: React.MouseEvent<HTMLDivElement>) => {
if (!isControlledRef.current) {
bodyControls.start('normal');
tailControls.start('normal');
} else {
onMouseLeave?.(e);
}
},
[bodyControls, tailControls, onMouseLeave]
);
return (
<div
className={cn(className)}
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
{...props}
>
<svg
xmlns="http://www.w3.org/2000/svg"
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<motion.path
variants={BODY_VARIANTS}
initial="normal"
animate={bodyControls}
d="M15 22v-4a4.8 4.8 0 0 0-1-3.5c3 0 6-2 6-5.5.08-1.25-.27-2.48-1-3.5.28-1.15.28-2.35 0-3.5 0 0-1 0-3 1.5-2.64-.5-5.36-.5-8 0C6 2 5 2 5 2c-.3 1.15-.3 2.35 0 3.5A5.403 5.403 0 0 0 4 9c0 3.5 3 5.5 6 5.5-.39.49-.68 1.05-.85 1.65-.17.6-.22 1.23-.15 1.85v4"
/>
<motion.path
variants={TAIL_VARIANTS}
initial="normal"
animate={tailControls}
d="M9 18c-4.51 2-5-2-7-2"
/>
</svg>
</div>
);
}
);
GithubIcon.displayName = 'GithubIcon';
export { GithubIcon };
+103
View File
@@ -0,0 +1,103 @@
'use client';
import type { Transition, Variants } from 'motion/react';
import type { HTMLAttributes } from 'react';
import { forwardRef, useCallback, useImperativeHandle, useRef } from 'react';
import { motion, useAnimation } from 'motion/react';
import { cn } from '@/lib/utils';
export interface HomeIconHandle {
startAnimation: () => void;
stopAnimation: () => void;
}
interface HomeIconProps extends HTMLAttributes<HTMLDivElement> {
size?: number;
}
const DEFAULT_TRANSITION: Transition = {
duration: 0.6,
opacity: { duration: 0.2 },
};
const PATH_VARIANTS: Variants = {
normal: {
pathLength: 1,
opacity: 1,
},
animate: {
opacity: [0, 1],
pathLength: [0, 1],
},
};
const HomeIcon = forwardRef<HomeIconHandle, HomeIconProps>(
({ onMouseEnter, onMouseLeave, className, size = 28, ...props }, ref) => {
const controls = useAnimation();
const isControlledRef = useRef(false);
useImperativeHandle(ref, () => {
isControlledRef.current = true;
return {
startAnimation: () => controls.start('animate'),
stopAnimation: () => controls.start('normal'),
};
});
const handleMouseEnter = useCallback(
(e: React.MouseEvent<HTMLDivElement>) => {
if (!isControlledRef.current) {
controls.start('animate');
} else {
onMouseEnter?.(e);
}
},
[controls, onMouseEnter]
);
const handleMouseLeave = useCallback(
(e: React.MouseEvent<HTMLDivElement>) => {
if (!isControlledRef.current) {
controls.start('normal');
} else {
onMouseLeave?.(e);
}
},
[controls, onMouseLeave]
);
return (
<div
className={cn(className)}
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
{...props}
>
<svg
xmlns="http://www.w3.org/2000/svg"
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<path d="M3 10a2 2 0 0 1 .709-1.528l7-5.999a2 2 0 0 1 2.582 0l7 5.999A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z" />
<motion.path
d="M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8"
variants={PATH_VARIANTS}
transition={DEFAULT_TRANSITION}
animate={controls}
/>
</svg>
</div>
);
}
);
HomeIcon.displayName = 'HomeIcon';
export { HomeIcon };
-127
View File
@@ -1,127 +0,0 @@
import * as React from "react"
import {
ChevronLeftIcon,
ChevronRightIcon,
MoreHorizontalIcon,
} from "lucide-react"
import { cn } from "@/lib/utils"
import { Button, buttonVariants } from "@/components/ui/button"
function Pagination({ className, ...props }: React.ComponentProps<"nav">) {
return (
<nav
role="navigation"
aria-label="pagination"
data-slot="pagination"
className={cn("mx-auto flex w-full justify-center", className)}
{...props}
/>
)
}
function PaginationContent({
className,
...props
}: React.ComponentProps<"ul">) {
return (
<ul
data-slot="pagination-content"
className={cn("flex flex-row items-center gap-1", className)}
{...props}
/>
)
}
function PaginationItem({ ...props }: React.ComponentProps<"li">) {
return <li data-slot="pagination-item" {...props} />
}
type PaginationLinkProps = {
isActive?: boolean
} & Pick<React.ComponentProps<typeof Button>, "size"> &
React.ComponentProps<"a">
function PaginationLink({
className,
isActive,
size = "icon",
...props
}: PaginationLinkProps) {
return (
<a
aria-current={isActive ? "page" : undefined}
data-slot="pagination-link"
data-active={isActive}
className={cn(
buttonVariants({
variant: isActive ? "outline" : "ghost",
size,
}),
className
)}
{...props}
/>
)
}
function PaginationPrevious({
className,
...props
}: React.ComponentProps<typeof PaginationLink>) {
return (
<PaginationLink
aria-label="Go to previous page"
size="default"
className={cn("gap-1 px-2.5 sm:pl-2.5", className)}
{...props}
>
<ChevronLeftIcon />
<span className="hidden sm:block">Previous</span>
</PaginationLink>
)
}
function PaginationNext({
className,
...props
}: React.ComponentProps<typeof PaginationLink>) {
return (
<PaginationLink
aria-label="Go to next page"
size="default"
className={cn("gap-1 px-2.5 sm:pr-2.5", className)}
{...props}
>
<span className="hidden sm:block">Next</span>
<ChevronRightIcon />
</PaginationLink>
)
}
function PaginationEllipsis({
className,
...props
}: React.ComponentProps<"span">) {
return (
<span
aria-hidden
data-slot="pagination-ellipsis"
className={cn("flex size-9 items-center justify-center", className)}
{...props}
>
<MoreHorizontalIcon className="size-4" />
<span className="sr-only">More pages</span>
</span>
)
}
export {
Pagination,
PaginationContent,
PaginationLink,
PaginationItem,
PaginationPrevious,
PaginationNext,
PaginationEllipsis,
}
@@ -1,45 +0,0 @@
"use client"
import * as React from "react"
import * as RadioGroupPrimitive from "@radix-ui/react-radio-group"
import { CircleIcon } from "lucide-react"
import { cn } from "@/lib/utils"
function RadioGroup({
className,
...props
}: React.ComponentProps<typeof RadioGroupPrimitive.Root>) {
return (
<RadioGroupPrimitive.Root
data-slot="radio-group"
className={cn("grid gap-3", className)}
{...props}
/>
)
}
function RadioGroupItem({
className,
...props
}: React.ComponentProps<typeof RadioGroupPrimitive.Item>) {
return (
<RadioGroupPrimitive.Item
data-slot="radio-group-item"
className={cn(
"border-input text-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 aspect-square size-4 shrink-0 rounded-full border shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
className
)}
{...props}
>
<RadioGroupPrimitive.Indicator
data-slot="radio-group-indicator"
className="relative flex items-center justify-center"
>
<CircleIcon className="fill-primary absolute top-1/2 left-1/2 size-2 -translate-x-1/2 -translate-y-1/2" />
</RadioGroupPrimitive.Indicator>
</RadioGroupPrimitive.Item>
)
}
export { RadioGroup, RadioGroupItem }
+92
View File
@@ -0,0 +1,92 @@
'use client';
import type { HTMLAttributes } from 'react';
import { forwardRef, useCallback, useImperativeHandle, useRef } from 'react';
import { motion, useAnimation } from 'motion/react';
import { cn } from '@/lib/utils';
export interface SettingsIconHandle {
startAnimation: () => void;
stopAnimation: () => void;
}
interface SettingsIconProps extends HTMLAttributes<HTMLDivElement> {
size?: number;
}
const SettingsIcon = forwardRef<SettingsIconHandle, SettingsIconProps>(
({ onMouseEnter, onMouseLeave, className, size = 28, ...props }, ref) => {
const controls = useAnimation();
const isControlledRef = useRef(false);
useImperativeHandle(ref, () => {
isControlledRef.current = true;
return {
startAnimation: () => controls.start('animate'),
stopAnimation: () => controls.start('normal'),
};
});
const handleMouseEnter = useCallback(
(e: React.MouseEvent<HTMLDivElement>) => {
if (!isControlledRef.current) {
controls.start('animate');
} else {
onMouseEnter?.(e);
}
},
[controls, onMouseEnter]
);
const handleMouseLeave = useCallback(
(e: React.MouseEvent<HTMLDivElement>) => {
if (!isControlledRef.current) {
controls.start('normal');
} else {
onMouseLeave?.(e);
}
},
[controls, onMouseLeave]
);
return (
<div
className={cn(className)}
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
{...props}
>
<motion.svg
xmlns="http://www.w3.org/2000/svg"
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
transition={{ type: 'spring', stiffness: 50, damping: 10 }}
variants={{
normal: {
rotate: 0,
},
animate: {
rotate: 180,
},
}}
animate={controls}
>
<path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z" />
<circle cx="12" cy="12" r="3" />
</motion.svg>
</div>
);
}
);
SettingsIcon.displayName = 'SettingsIcon';
export { SettingsIcon };
+103
View File
@@ -0,0 +1,103 @@
'use client';
import type { Variants } from 'motion/react';
import type { HTMLAttributes } from 'react';
import { forwardRef, useCallback, useImperativeHandle, useRef } from 'react';
import { motion, useAnimation } from 'motion/react';
import { cn } from '@/lib/utils';
export interface TerminalIconHandle {
startAnimation: () => void;
stopAnimation: () => void;
}
interface TerminalIconProps extends HTMLAttributes<HTMLDivElement> {
size?: number;
}
const LINE_VARIANTS: Variants = {
normal: { opacity: 1 },
animate: {
opacity: [1, 0, 1],
transition: {
duration: 0.8,
repeat: Infinity,
ease: 'linear',
},
},
};
const TerminalIcon = forwardRef<TerminalIconHandle, TerminalIconProps>(
({ onMouseEnter, onMouseLeave, className, size = 28, ...props }, ref) => {
const controls = useAnimation();
const isControlledRef = useRef(false);
useImperativeHandle(ref, () => {
isControlledRef.current = true;
return {
startAnimation: () => controls.start('animate'),
stopAnimation: () => controls.start('normal'),
};
});
const handleMouseEnter = useCallback(
(e: React.MouseEvent<HTMLDivElement>) => {
if (!isControlledRef.current) {
controls.start('animate');
} else {
onMouseEnter?.(e);
}
},
[controls, onMouseEnter]
);
const handleMouseLeave = useCallback(
(e: React.MouseEvent<HTMLDivElement>) => {
if (!isControlledRef.current) {
controls.start('normal');
} else {
onMouseLeave?.(e);
}
},
[controls, onMouseLeave]
);
return (
<div
className={cn(className)}
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
{...props}
>
<svg
xmlns="http://www.w3.org/2000/svg"
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<polyline points="4 17 10 11 4 5" />
<motion.line
x1="12"
x2="20"
y1="19"
y2="19"
variants={LINE_VARIANTS}
animate={controls}
initial="normal"
/>
</svg>
</div>
);
}
);
TerminalIcon.displayName = 'TerminalIcon';
export { TerminalIcon };
+48 -44
View File
@@ -26,19 +26,6 @@
--color-border: var(--border);
--color-input: var(--input);
--color-ring: var(--ring);
--color-chart-1: var(--chart-1);
--color-chart-2: var(--chart-2);
--color-chart-3: var(--chart-3);
--color-chart-4: var(--chart-4);
--color-chart-5: var(--chart-5);
--color-sidebar: var(--sidebar);
--color-sidebar-foreground: var(--sidebar-foreground);
--color-sidebar-primary: var(--sidebar-primary);
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
--color-sidebar-accent: var(--sidebar-accent);
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--color-sidebar-border: var(--sidebar-border);
--color-sidebar-ring: var(--sidebar-ring);
}
:root {
@@ -61,19 +48,6 @@
--border: oklch(0.922 0 0);
--input: oklch(0.922 0 0);
--ring: oklch(0.708 0 0);
--chart-1: oklch(0.646 0.222 41.116);
--chart-2: oklch(0.6 0.118 184.704);
--chart-3: oklch(0.398 0.07 227.392);
--chart-4: oklch(0.828 0.189 84.429);
--chart-5: oklch(0.769 0.188 70.08);
--sidebar: oklch(0.985 0 0);
--sidebar-foreground: oklch(0.145 0 0);
--sidebar-primary: oklch(0.205 0 0);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.97 0 0);
--sidebar-accent-foreground: oklch(0.205 0 0);
--sidebar-border: oklch(0.922 0 0);
--sidebar-ring: oklch(0.708 0 0);
}
.dark {
@@ -95,19 +69,6 @@
--border: oklch(1 0 0 / 10%);
--input: oklch(1 0 0 / 15%);
--ring: oklch(0.556 0 0);
--chart-1: oklch(0.488 0.243 264.376);
--chart-2: oklch(0.696 0.17 162.48);
--chart-3: oklch(0.769 0.188 70.08);
--chart-4: oklch(0.627 0.265 303.9);
--chart-5: oklch(0.645 0.246 16.439);
--sidebar: oklch(0.205 0 0);
--sidebar-foreground: oklch(0.985 0 0);
--sidebar-primary: oklch(0.488 0.243 264.376);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.269 0 0);
--sidebar-accent-foreground: oklch(0.985 0 0);
--sidebar-border: oklch(1 0 0 / 10%);
--sidebar-ring: oklch(0.556 0 0);
}
@layer base {
@@ -164,6 +125,54 @@
@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;
@@ -244,8 +253,3 @@
.custom-scrollbar::-webkit-scrollbar-thumb:hover {
filter: brightness(1.2);
}
/* Date input styling for dark mode */
.dark input[type="date"]::-webkit-calendar-picker-indicator {
filter: invert(1);
}
+58
View File
@@ -6,6 +6,7 @@
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;
@@ -166,6 +167,63 @@ export function stateToResponse(state: FetchState): TwitterResponse | null {
};
}
/**
* 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)
*/
+26 -6
View File
@@ -1,8 +1,10 @@
import { GetDefaults } from "../../wailsjs/go/main/App";
export type FontFamily = "google-sans" | "inter" | "poppins" | "roboto" | "dm-sans" | "plus-jakarta-sans" | "manrope" | "space-grotesk";
export type 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 type FetchMode = "single" | "batch";
export type MediaType = "all" | "image" | "video" | "gif" | "text";
export interface Settings {
downloadPath: string;
@@ -12,6 +14,11 @@ export interface Settings {
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.
fetchMode: FetchMode; // Fetch mode: single (all at once) or batch (200 per request). Default: batch.
mediaType: MediaType; // Media type filter. Default: all.
includeRetweets: boolean; // Include retweets in fetch. Default: false.
}
export const DEFAULT_SETTINGS: Settings = {
@@ -21,17 +28,30 @@ export const DEFAULT_SETTINGS: Settings = {
fontFamily: "google-sans",
sfxEnabled: true,
gifQuality: "fast",
gifResolution: "high",
gifResolution: "original",
proxy: "",
fetchTimeout: 60, // Default: 60 seconds
fetchMode: "batch", // Default: batch mode (200 per request)
mediaType: "all", // Default: all media
includeRetweets: false, // Default: don't include retweets
};
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: "poppins", label: "Poppins", fontFamily: '"Poppins", system-ui, sans-serif' },
{ value: "roboto", label: "Roboto", fontFamily: '"Roboto", system-ui, sans-serif' },
{ value: "dm-sans", label: "DM Sans", fontFamily: '"DM Sans", system-ui, sans-serif' },
{ value: "plus-jakarta-sans", label: "Plus Jakarta Sans", fontFamily: '"Plus Jakarta Sans", system-ui, sans-serif' },
{ value: "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' },
];
+269 -449
View File
@@ -7,456 +7,276 @@ export interface Theme {
};
}
// 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[] = [
{
name: "neutral",
label: "Default",
cssVars: {
light: {
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)",
"chart-1": "oklch(0.646 0.222 41.116)",
"chart-2": "oklch(0.6 0.118 184.704)",
"chart-3": "oklch(0.398 0.07 227.392)",
"chart-4": "oklch(0.828 0.189 84.429)",
"chart-5": "oklch(0.769 0.188 70.08)",
},
dark: {
background: "oklch(0.145 0 0)",
foreground: "oklch(0.985 0 0)",
card: "oklch(0.205 0 0)",
"card-foreground": "oklch(0.985 0 0)",
popover: "oklch(0.205 0 0)",
"popover-foreground": "oklch(0.985 0 0)",
primary: "oklch(0.922 0 0)",
"primary-foreground": "oklch(0.205 0 0)",
secondary: "oklch(0.269 0 0)",
"secondary-foreground": "oklch(0.985 0 0)",
muted: "oklch(0.269 0 0)",
"muted-foreground": "oklch(0.708 0 0)",
accent: "oklch(0.269 0 0)",
"accent-foreground": "oklch(0.985 0 0)",
destructive: "oklch(0.704 0.191 22.216)",
border: "oklch(1 0 0 / 10%)",
input: "oklch(1 0 0 / 15%)",
ring: "oklch(0.556 0 0)",
"chart-1": "oklch(0.488 0.243 264.376)",
"chart-2": "oklch(0.696 0.17 162.48)",
"chart-3": "oklch(0.769 0.188 70.08)",
"chart-4": "oklch(0.627 0.265 303.9)",
"chart-5": "oklch(0.645 0.246 16.439)",
},
},
},
{
name: "blue",
label: "Blue",
cssVars: {
light: {
background: "oklch(1 0 0)",
foreground: "oklch(0.141 0.005 285.823)",
card: "oklch(1 0 0)",
"card-foreground": "oklch(0.141 0.005 285.823)",
popover: "oklch(1 0 0)",
"popover-foreground": "oklch(0.141 0.005 285.823)",
primary: "oklch(0.488 0.243 264.376)",
"primary-foreground": "oklch(0.97 0.014 254.604)",
secondary: "oklch(0.967 0.001 286.375)",
"secondary-foreground": "oklch(0.21 0.006 285.885)",
muted: "oklch(0.967 0.001 286.375)",
"muted-foreground": "oklch(0.552 0.016 285.938)",
accent: "oklch(0.967 0.001 286.375)",
"accent-foreground": "oklch(0.21 0.006 285.885)",
destructive: "oklch(0.577 0.245 27.325)",
border: "oklch(0.92 0.004 286.32)",
input: "oklch(0.92 0.004 286.32)",
ring: "oklch(0.708 0 0)",
"chart-1": "oklch(0.809 0.105 251.813)",
"chart-2": "oklch(0.623 0.214 259.815)",
"chart-3": "oklch(0.546 0.245 262.881)",
"chart-4": "oklch(0.488 0.243 264.376)",
"chart-5": "oklch(0.424 0.199 265.638)",
},
dark: {
background: "oklch(0.141 0.005 285.823)",
foreground: "oklch(0.985 0 0)",
card: "oklch(0.21 0.006 285.885)",
"card-foreground": "oklch(0.985 0 0)",
popover: "oklch(0.21 0.006 285.885)",
"popover-foreground": "oklch(0.985 0 0)",
primary: "oklch(0.488 0.243 264.376)",
"primary-foreground": "oklch(0.97 0.014 254.604)",
secondary: "oklch(0.274 0.006 286.033)",
"secondary-foreground": "oklch(0.985 0 0)",
muted: "oklch(0.274 0.006 286.033)",
"muted-foreground": "oklch(0.705 0.015 286.067)",
accent: "oklch(0.274 0.006 286.033)",
"accent-foreground": "oklch(0.985 0 0)",
destructive: "oklch(0.704 0.191 22.216)",
border: "oklch(1 0 0 / 10%)",
input: "oklch(1 0 0 / 15%)",
ring: "oklch(0.556 0 0)",
"chart-1": "oklch(0.809 0.105 251.813)",
"chart-2": "oklch(0.623 0.214 259.815)",
"chart-3": "oklch(0.546 0.245 262.881)",
"chart-4": "oklch(0.488 0.243 264.376)",
"chart-5": "oklch(0.424 0.199 265.638)",
},
},
},
{
name: "green",
label: "Green",
cssVars: {
light: {
background: "oklch(1 0 0)",
foreground: "oklch(0.141 0.005 285.823)",
card: "oklch(1 0 0)",
"card-foreground": "oklch(0.141 0.005 285.823)",
popover: "oklch(1 0 0)",
"popover-foreground": "oklch(0.141 0.005 285.823)",
primary: "oklch(0.648 0.2 131.684)",
"primary-foreground": "oklch(0.986 0.031 120.757)",
secondary: "oklch(0.967 0.001 286.375)",
"secondary-foreground": "oklch(0.21 0.006 285.885)",
muted: "oklch(0.967 0.001 286.375)",
"muted-foreground": "oklch(0.552 0.016 285.938)",
accent: "oklch(0.967 0.001 286.375)",
"accent-foreground": "oklch(0.21 0.006 285.885)",
destructive: "oklch(0.577 0.245 27.325)",
border: "oklch(0.92 0.004 286.32)",
input: "oklch(0.92 0.004 286.32)",
ring: "oklch(0.841 0.238 128.85)",
"chart-1": "oklch(0.871 0.15 154.449)",
"chart-2": "oklch(0.723 0.219 149.579)",
"chart-3": "oklch(0.627 0.194 149.214)",
"chart-4": "oklch(0.527 0.154 150.069)",
"chart-5": "oklch(0.448 0.119 151.328)",
},
dark: {
background: "oklch(0.141 0.005 285.823)",
foreground: "oklch(0.985 0 0)",
card: "oklch(0.21 0.006 285.885)",
"card-foreground": "oklch(0.985 0 0)",
popover: "oklch(0.21 0.006 285.885)",
"popover-foreground": "oklch(0.985 0 0)",
primary: "oklch(0.648 0.2 131.684)",
"primary-foreground": "oklch(0.986 0.031 120.757)",
secondary: "oklch(0.274 0.006 286.033)",
"secondary-foreground": "oklch(0.985 0 0)",
muted: "oklch(0.274 0.006 286.033)",
"muted-foreground": "oklch(0.705 0.015 286.067)",
accent: "oklch(0.274 0.006 286.033)",
"accent-foreground": "oklch(0.985 0 0)",
destructive: "oklch(0.704 0.191 22.216)",
border: "oklch(1 0 0 / 10%)",
input: "oklch(1 0 0 / 15%)",
ring: "oklch(0.405 0.101 131.063)",
"chart-1": "oklch(0.871 0.15 154.449)",
"chart-2": "oklch(0.723 0.219 149.579)",
"chart-3": "oklch(0.627 0.194 149.214)",
"chart-4": "oklch(0.527 0.154 150.069)",
"chart-5": "oklch(0.448 0.119 151.328)",
},
},
},
{
name: "orange",
label: "Orange",
cssVars: {
light: {
background: "oklch(1 0 0)",
foreground: "oklch(0.141 0.005 285.823)",
card: "oklch(1 0 0)",
"card-foreground": "oklch(0.141 0.005 285.823)",
popover: "oklch(1 0 0)",
"popover-foreground": "oklch(0.141 0.005 285.823)",
primary: "oklch(0.646 0.222 41.116)",
"primary-foreground": "oklch(0.98 0.016 73.684)",
secondary: "oklch(0.967 0.001 286.375)",
"secondary-foreground": "oklch(0.21 0.006 285.885)",
muted: "oklch(0.967 0.001 286.375)",
"muted-foreground": "oklch(0.552 0.016 285.938)",
accent: "oklch(0.967 0.001 286.375)",
"accent-foreground": "oklch(0.21 0.006 285.885)",
destructive: "oklch(0.577 0.245 27.325)",
border: "oklch(0.92 0.004 286.32)",
input: "oklch(0.92 0.004 286.32)",
ring: "oklch(0.75 0.183 55.934)",
"chart-1": "oklch(0.837 0.128 66.29)",
"chart-2": "oklch(0.705 0.213 47.604)",
"chart-3": "oklch(0.646 0.222 41.116)",
"chart-4": "oklch(0.553 0.195 38.402)",
"chart-5": "oklch(0.47 0.157 37.304)",
},
dark: {
background: "oklch(0.141 0.005 285.823)",
foreground: "oklch(0.985 0 0)",
card: "oklch(0.21 0.006 285.885)",
"card-foreground": "oklch(0.985 0 0)",
popover: "oklch(0.21 0.006 285.885)",
"popover-foreground": "oklch(0.985 0 0)",
primary: "oklch(0.705 0.213 47.604)",
"primary-foreground": "oklch(0.98 0.016 73.684)",
secondary: "oklch(0.274 0.006 286.033)",
"secondary-foreground": "oklch(0.985 0 0)",
muted: "oklch(0.274 0.006 286.033)",
"muted-foreground": "oklch(0.705 0.015 286.067)",
accent: "oklch(0.274 0.006 286.033)",
"accent-foreground": "oklch(0.985 0 0)",
destructive: "oklch(0.704 0.191 22.216)",
border: "oklch(1 0 0 / 10%)",
input: "oklch(1 0 0 / 15%)",
ring: "oklch(0.408 0.123 38.172)",
"chart-1": "oklch(0.837 0.128 66.29)",
"chart-2": "oklch(0.705 0.213 47.604)",
"chart-3": "oklch(0.646 0.222 41.116)",
"chart-4": "oklch(0.553 0.195 38.402)",
"chart-5": "oklch(0.47 0.157 37.304)",
},
},
},
{
name: "red",
label: "Red",
cssVars: {
light: {
background: "oklch(1 0 0)",
foreground: "oklch(0.141 0.005 285.823)",
card: "oklch(1 0 0)",
"card-foreground": "oklch(0.141 0.005 285.823)",
popover: "oklch(1 0 0)",
"popover-foreground": "oklch(0.141 0.005 285.823)",
primary: "oklch(0.577 0.245 27.325)",
"primary-foreground": "oklch(0.971 0.013 17.38)",
secondary: "oklch(0.967 0.001 286.375)",
"secondary-foreground": "oklch(0.21 0.006 285.885)",
muted: "oklch(0.967 0.001 286.375)",
"muted-foreground": "oklch(0.552 0.016 285.938)",
accent: "oklch(0.967 0.001 286.375)",
"accent-foreground": "oklch(0.21 0.006 285.885)",
destructive: "oklch(0.577 0.245 27.325)",
border: "oklch(0.92 0.004 286.32)",
input: "oklch(0.92 0.004 286.32)",
ring: "oklch(0.704 0.191 22.216)",
"chart-1": "oklch(0.808 0.114 19.571)",
"chart-2": "oklch(0.637 0.237 25.331)",
"chart-3": "oklch(0.577 0.245 27.325)",
"chart-4": "oklch(0.505 0.213 27.518)",
"chart-5": "oklch(0.444 0.177 26.899)",
},
dark: {
background: "oklch(0.141 0.005 285.823)",
foreground: "oklch(0.985 0 0)",
card: "oklch(0.21 0.006 285.885)",
"card-foreground": "oklch(0.985 0 0)",
popover: "oklch(0.21 0.006 285.885)",
"popover-foreground": "oklch(0.985 0 0)",
primary: "oklch(0.637 0.237 25.331)",
"primary-foreground": "oklch(0.971 0.013 17.38)",
secondary: "oklch(0.274 0.006 286.033)",
"secondary-foreground": "oklch(0.985 0 0)",
muted: "oklch(0.274 0.006 286.033)",
"muted-foreground": "oklch(0.705 0.015 286.067)",
accent: "oklch(0.274 0.006 286.033)",
"accent-foreground": "oklch(0.985 0 0)",
destructive: "oklch(0.704 0.191 22.216)",
border: "oklch(1 0 0 / 10%)",
input: "oklch(1 0 0 / 15%)",
ring: "oklch(0.396 0.141 25.723)",
"chart-1": "oklch(0.808 0.114 19.571)",
"chart-2": "oklch(0.637 0.237 25.331)",
"chart-3": "oklch(0.577 0.245 27.325)",
"chart-4": "oklch(0.505 0.213 27.518)",
"chart-5": "oklch(0.444 0.177 26.899)",
},
},
},
{
name: "rose",
label: "Rose",
cssVars: {
light: {
background: "oklch(1 0 0)",
foreground: "oklch(0.141 0.005 285.823)",
card: "oklch(1 0 0)",
"card-foreground": "oklch(0.141 0.005 285.823)",
popover: "oklch(1 0 0)",
"popover-foreground": "oklch(0.141 0.005 285.823)",
primary: "oklch(0.586 0.253 17.585)",
"primary-foreground": "oklch(0.969 0.015 12.422)",
secondary: "oklch(0.967 0.001 286.375)",
"secondary-foreground": "oklch(0.21 0.006 285.885)",
muted: "oklch(0.967 0.001 286.375)",
"muted-foreground": "oklch(0.552 0.016 285.938)",
accent: "oklch(0.967 0.001 286.375)",
"accent-foreground": "oklch(0.21 0.006 285.885)",
destructive: "oklch(0.577 0.245 27.325)",
border: "oklch(0.92 0.004 286.32)",
input: "oklch(0.92 0.004 286.32)",
ring: "oklch(0.712 0.194 13.428)",
"chart-1": "oklch(0.81 0.117 11.638)",
"chart-2": "oklch(0.645 0.246 16.439)",
"chart-3": "oklch(0.586 0.253 17.585)",
"chart-4": "oklch(0.514 0.222 16.935)",
"chart-5": "oklch(0.455 0.188 13.697)",
},
dark: {
background: "oklch(0.141 0.005 285.823)",
foreground: "oklch(0.985 0 0)",
card: "oklch(0.21 0.006 285.885)",
"card-foreground": "oklch(0.985 0 0)",
popover: "oklch(0.21 0.006 285.885)",
"popover-foreground": "oklch(0.985 0 0)",
primary: "oklch(0.645 0.246 16.439)",
"primary-foreground": "oklch(0.969 0.015 12.422)",
secondary: "oklch(0.274 0.006 286.033)",
"secondary-foreground": "oklch(0.985 0 0)",
muted: "oklch(0.274 0.006 286.033)",
"muted-foreground": "oklch(0.705 0.015 286.067)",
accent: "oklch(0.274 0.006 286.033)",
"accent-foreground": "oklch(0.985 0 0)",
destructive: "oklch(0.704 0.191 22.216)",
border: "oklch(1 0 0 / 10%)",
input: "oklch(1 0 0 / 15%)",
ring: "oklch(0.41 0.159 10.272)",
"chart-1": "oklch(0.81 0.117 11.638)",
"chart-2": "oklch(0.645 0.246 16.439)",
"chart-3": "oklch(0.586 0.253 17.585)",
"chart-4": "oklch(0.514 0.222 16.935)",
"chart-5": "oklch(0.455 0.188 13.697)",
},
},
},
{
name: "violet",
label: "Violet",
cssVars: {
light: {
background: "oklch(1 0 0)",
foreground: "oklch(0.141 0.005 285.823)",
card: "oklch(1 0 0)",
"card-foreground": "oklch(0.141 0.005 285.823)",
popover: "oklch(1 0 0)",
"popover-foreground": "oklch(0.141 0.005 285.823)",
primary: "oklch(0.541 0.281 293.009)",
"primary-foreground": "oklch(0.969 0.016 293.756)",
secondary: "oklch(0.967 0.001 286.375)",
"secondary-foreground": "oklch(0.21 0.006 285.885)",
muted: "oklch(0.967 0.001 286.375)",
"muted-foreground": "oklch(0.552 0.016 285.938)",
accent: "oklch(0.967 0.001 286.375)",
"accent-foreground": "oklch(0.21 0.006 285.885)",
destructive: "oklch(0.577 0.245 27.325)",
border: "oklch(0.92 0.004 286.32)",
input: "oklch(0.92 0.004 286.32)",
ring: "oklch(0.702 0.183 293.541)",
"chart-1": "oklch(0.811 0.111 293.571)",
"chart-2": "oklch(0.606 0.25 292.717)",
"chart-3": "oklch(0.541 0.281 293.009)",
"chart-4": "oklch(0.491 0.27 292.581)",
"chart-5": "oklch(0.432 0.232 292.759)",
},
dark: {
background: "oklch(0.141 0.005 285.823)",
foreground: "oklch(0.985 0 0)",
card: "oklch(0.21 0.006 285.885)",
"card-foreground": "oklch(0.985 0 0)",
popover: "oklch(0.21 0.006 285.885)",
"popover-foreground": "oklch(0.985 0 0)",
primary: "oklch(0.606 0.25 292.717)",
"primary-foreground": "oklch(0.969 0.016 293.756)",
secondary: "oklch(0.274 0.006 286.033)",
"secondary-foreground": "oklch(0.985 0 0)",
muted: "oklch(0.274 0.006 286.033)",
"muted-foreground": "oklch(0.705 0.015 286.067)",
accent: "oklch(0.274 0.006 286.033)",
"accent-foreground": "oklch(0.985 0 0)",
destructive: "oklch(0.704 0.191 22.216)",
border: "oklch(1 0 0 / 10%)",
input: "oklch(1 0 0 / 15%)",
ring: "oklch(0.38 0.189 293.745)",
"chart-1": "oklch(0.811 0.111 293.571)",
"chart-2": "oklch(0.606 0.25 292.717)",
"chart-3": "oklch(0.541 0.281 293.009)",
"chart-4": "oklch(0.491 0.27 292.581)",
"chart-5": "oklch(0.432 0.232 292.759)",
},
},
},
{
name: "yellow",
label: "Yellow",
cssVars: {
light: {
background: "oklch(1 0 0)",
foreground: "oklch(0.141 0.005 285.823)",
card: "oklch(1 0 0)",
"card-foreground": "oklch(0.141 0.005 285.823)",
popover: "oklch(1 0 0)",
"popover-foreground": "oklch(0.141 0.005 285.823)",
primary: "oklch(0.852 0.199 91.936)",
"primary-foreground": "oklch(0.421 0.095 57.708)",
secondary: "oklch(0.967 0.001 286.375)",
"secondary-foreground": "oklch(0.21 0.006 285.885)",
muted: "oklch(0.967 0.001 286.375)",
"muted-foreground": "oklch(0.552 0.016 285.938)",
accent: "oklch(0.967 0.001 286.375)",
"accent-foreground": "oklch(0.21 0.006 285.885)",
destructive: "oklch(0.577 0.245 27.325)",
border: "oklch(0.92 0.004 286.32)",
input: "oklch(0.92 0.004 286.32)",
ring: "oklch(0.852 0.199 91.936)",
"chart-1": "oklch(0.905 0.182 98.111)",
"chart-2": "oklch(0.795 0.184 86.047)",
"chart-3": "oklch(0.681 0.162 75.834)",
"chart-4": "oklch(0.554 0.135 66.442)",
"chart-5": "oklch(0.476 0.114 61.907)",
},
dark: {
background: "oklch(0.141 0.005 285.823)",
foreground: "oklch(0.985 0 0)",
card: "oklch(0.21 0.006 285.885)",
"card-foreground": "oklch(0.985 0 0)",
popover: "oklch(0.21 0.006 285.885)",
"popover-foreground": "oklch(0.985 0 0)",
primary: "oklch(0.795 0.184 86.047)",
"primary-foreground": "oklch(0.421 0.095 57.708)",
secondary: "oklch(0.274 0.006 286.033)",
"secondary-foreground": "oklch(0.985 0 0)",
muted: "oklch(0.274 0.006 286.033)",
"muted-foreground": "oklch(0.705 0.015 286.067)",
accent: "oklch(0.274 0.006 286.033)",
"accent-foreground": "oklch(0.985 0 0)",
destructive: "oklch(0.704 0.191 22.216)",
border: "oklch(1 0 0 / 10%)",
input: "oklch(1 0 0 / 15%)",
ring: "oklch(0.421 0.095 57.708)",
"chart-1": "oklch(0.905 0.182 98.111)",
"chart-2": "oklch(0.795 0.184 86.047)",
"chart-3": "oklch(0.681 0.162 75.834)",
"chart-4": "oklch(0.554 0.135 66.442)",
"chart-5": "oklch(0.476 0.114 61.907)",
},
},
},
];
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];
+2
View File
@@ -27,6 +27,8 @@ export interface TimelineEntry {
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 {
+1 -9
View File
@@ -51,12 +51,4 @@ python -m nuitka --onefile --output-filename=extractor.exe --include-package=gal
### Output Location
- PyInstaller: `dist/extractor` or `dist/extractor.exe`
- Nuitka: `extractor` or `extractor.exe` (in current directory)
---
## Notes
- The main application automatically manages the binary (extracts, updates, and uses it)
- Manual building is only needed if you're developing or customizing the extractor
- The pre-built binary is kept in sync with the application version
- Nuitka: `extractor` or `extractor.exe` (in current directory)
+30 -86
View File
@@ -1,37 +1,12 @@
# twitter_cli.py — Usage Guide
# Usage Guide
CLI tool for extracting media and metadata from Twitter/X using gallery-dl extractor.
## Quickstart
1. **Set up environment**
```powershell
cd helper
python -m venv .venv
.\.venv\Scripts\Activate.ps1
pip install -r requirements.txt
```
2. **Verify gallery-dl**
```powershell
python -c "import gallery_dl; print(gallery_dl.__version__)"
```
3. **Quick test** (using demo account):
```powershell
python twitter_cli.py https://x.com/xbatchdemo/media --limit 1 --json --guest
```
---
## Command Line Arguments
### Required
- `url` — Twitter/X URL (timeline, media, likes, search, etc.)
### Authentication
- `--auth-token TOKEN` — Your auth_token cookie value
- `--guest` — Force guest mode (no authentication)
- `--auth-token TOKEN` — Your auth_token cookie value (required)
### Content Options
- `--retweets {skip|include|original}` — Control retweets (default: skip)
@@ -64,10 +39,7 @@ CLI tool for extracting media and metadata from Twitter/X using gallery-dl extra
### Basic Fetch
```powershell
# Guest mode (no auth)
python twitter_cli.py https://x.com/username/media --limit 10 --json --guest
# With authentication
# Fetch media with authentication
python twitter_cli.py https://x.com/username/media --limit 10 --json --auth-token YOUR_TOKEN
```
@@ -75,49 +47,49 @@ python twitter_cli.py https://x.com/username/media --limit 10 --json --auth-toke
```powershell
# Photos only
python twitter_cli.py https://x.com/username/media --type photo --json --guest
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 --guest
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 --guest
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 --guest
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 --guest
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 --guest
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 --guest
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 --guest
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 --guest
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 --guest
python twitter_cli.py https://x.com/username/media --resume results.json --limit 0 --output results.json --auth-token YOUR_TOKEN
```
### Private Content (Requires Auth)
### Private Content
```powershell
# Your likes
@@ -131,30 +103,30 @@ python twitter_cli.py https://x.com/i/bookmarks --limit 20 --json --auth-token Y
```powershell
# Search with filters
python twitter_cli.py "https://x.com/search?q=from:username filter:media" --limit 50 --json --guest
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 --guest
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" --guest
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" --guest
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" --guest
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 --guest
python twitter_cli.py https://x.com/username/tweets --text-tweets --json --metadata --auth-token YOUR_TOKEN
```
---
@@ -222,16 +194,16 @@ When using `--output`, the file includes:
```powershell
# Step 1: Initial fetch (saves state)
python twitter_cli.py https://x.com/user/media --limit 100 --output data.json --progress --guest
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 --guest
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 --guest
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]
```
@@ -244,10 +216,10 @@ python twitter_cli.py https://x.com/user/media --resume data.json --limit 0 --ou
- `https://x.com/username/timeline` — Full timeline
- `https://x.com/username/tweets` — Tweets only
- `https://x.com/username/with_replies` — With replies
- `https://x.com/username/likes` — Liked tweets (requires auth)
- `https://x.com/username/likes` — Liked tweets
### Private Content
- `https://x.com/i/bookmarks` — Your bookmarks (requires auth)
- `https://x.com/i/bookmarks` — Your bookmarks
### Search
- `https://x.com/search?q=QUERY` — Search tweets
@@ -277,55 +249,27 @@ Use in search URLs:
---
## Authentication
### Getting Your Auth Token
1. Open Twitter/X in your browser
2. Open Developer Tools (F12)
3. Go to Application/Storage → Cookies
4. Find cookie named `auth_token`
5. Copy its value
### Security Notes
- Use a dummy/secondary account for scraping
- Don't share your auth token
- Excessive usage may cause account suspension
- Guest mode has stricter rate limits
---
## Rate Limits
- **Guest mode**: Lower limits, may hit rate limit faster
- **Authenticated**: Higher limits but still restricted
- **Rate limit hit**: Script will wait and retry automatically
- **Best practice**: Use `--limit` to control fetch size
---
## Tips & Tricks
### 1. Progressive Fetch with Resume
```powershell
# Fetch in batches to avoid long waits
python twitter_cli.py URL --limit 200 --output data.json --progress --guest
python twitter_cli.py URL --resume data.json --limit 200 --output data.json --guest
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 --guest
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 --guest
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
- If `cursor: null` → no more data available
+17 -1
View File
@@ -102,6 +102,20 @@ def _extract_tweet_metadata(data: MutableMapping[str, Any]) -> Dict[str, Any]:
"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
@@ -171,7 +185,9 @@ def run_request(
for message in extractor:
mtype = message[0]
if mtype is Message.Directory and request.metadata:
metadata.append(_extract_tweet_metadata(message[1]))
# 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]
-3
View File
@@ -1,3 +0,0 @@
{
"version": "4.0"
}
+1 -1
View File
@@ -11,7 +11,7 @@
},
"info": {
"productName": "Twitter/X Media Batch Downloader",
"productVersion": "4.0"
"productVersion": "4.3"
},
"wailsjsdir": "./frontend",
"assetdir": "./frontend/dist",