mirror of
https://github.com/Alvin-Zilverstand/Twitter-X-Media-Batch-Downloader.git
synced 2026-11-30 10:07:54 +01:00
v4.4
This commit is contained in:
1 parent
8cbf7c979b
commit
4794fac099
80 files changed
+7500
-10133
No files matched your search
+128
-243
@@ -1,8 +1,6 @@
|
||||
package backend
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/url"
|
||||
@@ -13,38 +11,47 @@ import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
// getExecutableName returns the appropriate executable name for the current OS
|
||||
func getExecutableName() string {
|
||||
if runtime.GOOS == "windows" {
|
||||
return "xtractor.exe"
|
||||
}
|
||||
return "xtractor"
|
||||
}
|
||||
|
||||
func getLegacyExecutableName() string {
|
||||
if runtime.GOOS == "windows" {
|
||||
return "extractor.exe"
|
||||
}
|
||||
return "extractor"
|
||||
}
|
||||
|
||||
// KillAllExtractorProcesses kills all running extractor processes
|
||||
// This is useful for cleanup when starting fresh or when user stops fetch
|
||||
func KillAllExtractorProcesses() {
|
||||
exeName := getExecutableName()
|
||||
names := []string{getExecutableName(), getLegacyExecutableName()}
|
||||
seen := make(map[string]bool)
|
||||
|
||||
var cmd *exec.Cmd
|
||||
if runtime.GOOS == "windows" {
|
||||
// Use taskkill on Windows
|
||||
cmd = exec.Command("taskkill", "/F", "/IM", exeName)
|
||||
} else {
|
||||
// Use pkill on Unix
|
||||
cmd = exec.Command("pkill", "-f", exeName)
|
||||
for _, exeName := range names {
|
||||
if seen[exeName] {
|
||||
continue
|
||||
}
|
||||
seen[exeName] = true
|
||||
|
||||
var cmd *exec.Cmd
|
||||
if runtime.GOOS == "windows" {
|
||||
|
||||
cmd = exec.Command("taskkill", "/F", "/IM", exeName)
|
||||
} else {
|
||||
|
||||
cmd = exec.Command("pkill", "-f", exeName)
|
||||
}
|
||||
|
||||
hideWindow(cmd)
|
||||
cmd.CombinedOutput()
|
||||
}
|
||||
|
||||
hideWindow(cmd)
|
||||
cmd.CombinedOutput() // Ignore errors - it's okay if no processes found
|
||||
}
|
||||
|
||||
// parseExtractorError parses the extractor output and returns a user-friendly error message
|
||||
// while preserving the original error from gallery-dl
|
||||
func parseExtractorError(output string, username string) string {
|
||||
outputLower := strings.ToLower(output)
|
||||
|
||||
// Extract the actual error line from gallery-dl output
|
||||
lines := strings.Split(output, "\n")
|
||||
var errorLine string
|
||||
for _, line := range lines {
|
||||
@@ -58,12 +65,10 @@ func parseExtractorError(output string, username string) string {
|
||||
errorLine = strings.TrimSpace(output)
|
||||
}
|
||||
|
||||
// Truncate if too long
|
||||
if len(errorLine) > 300 {
|
||||
errorLine = errorLine[:300] + "..."
|
||||
}
|
||||
|
||||
// Add context hint based on error type, but keep original message
|
||||
var hint string
|
||||
if strings.Contains(outputLower, "unable to retrieve tweets from this timeline") {
|
||||
hint = " [Hint: End of timeline reached or rate limited - data already fetched has been saved]"
|
||||
@@ -80,23 +85,20 @@ func parseExtractorError(output string, username string) string {
|
||||
return errorLine + hint
|
||||
}
|
||||
|
||||
// TweetIDString is a custom type that unmarshals int64 but marshals as string
|
||||
type TweetIDString int64
|
||||
|
||||
// MarshalJSON converts TweetIDString to JSON string to preserve precision in JavaScript
|
||||
func (t TweetIDString) MarshalJSON() ([]byte, error) {
|
||||
return []byte(fmt.Sprintf(`"%d"`, t)), nil
|
||||
}
|
||||
|
||||
// UnmarshalJSON accepts both number and string from JSON
|
||||
func (t *TweetIDString) UnmarshalJSON(data []byte) error {
|
||||
// Try to unmarshal as number first (from extractor)
|
||||
|
||||
var num int64
|
||||
if err := json.Unmarshal(data, &num); err == nil {
|
||||
*t = TweetIDString(num)
|
||||
return nil
|
||||
}
|
||||
// Try as string (for future compatibility)
|
||||
|
||||
var str string
|
||||
if err := json.Unmarshal(data, &str); err == nil {
|
||||
parsed, err := fmt.Sscanf(str, "%d", &num)
|
||||
@@ -109,14 +111,12 @@ func (t *TweetIDString) UnmarshalJSON(data []byte) error {
|
||||
return fmt.Errorf("tweet_id must be number or string")
|
||||
}
|
||||
|
||||
// Author represents tweet author information from extractor
|
||||
type Author struct {
|
||||
ID int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Nick string `json:"nick"`
|
||||
}
|
||||
|
||||
// UserInfo represents full user information from extractor
|
||||
type UserInfo struct {
|
||||
ID int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
@@ -137,7 +137,6 @@ type UserInfo struct {
|
||||
URL string `json:"url"`
|
||||
}
|
||||
|
||||
// CLIMediaItem represents a single media entry from extractor CLI
|
||||
type CLIMediaItem struct {
|
||||
URL string `json:"url"`
|
||||
TweetID TweetIDString `json:"tweet_id"`
|
||||
@@ -165,7 +164,6 @@ type CLIMediaItem struct {
|
||||
Sensitive bool `json:"sensitive"`
|
||||
}
|
||||
|
||||
// TweetMetadata represents tweet metadata from extractor
|
||||
type TweetMetadata struct {
|
||||
TweetID TweetIDString `json:"tweet_id"`
|
||||
RetweetID TweetIDString `json:"retweet_id,omitempty"`
|
||||
@@ -186,38 +184,35 @@ type TweetMetadata struct {
|
||||
Sensitive bool `json:"sensitive,omitempty"`
|
||||
}
|
||||
|
||||
// CLIResponse represents the raw response from extractor CLI
|
||||
type CLIResponse struct {
|
||||
Media []CLIMediaItem `json:"media"`
|
||||
Metadata []TweetMetadata `json:"metadata"`
|
||||
Cursor string `json:"cursor,omitempty"` // Cursor for resume
|
||||
Total int `json:"total,omitempty"` // Total items fetched
|
||||
Completed bool `json:"completed,omitempty"` // True if all fetched
|
||||
Cursor string `json:"cursor,omitempty"`
|
||||
Total int `json:"total,omitempty"`
|
||||
Completed bool `json:"completed,omitempty"`
|
||||
}
|
||||
|
||||
// TimelineEntry represents a single media entry for frontend (converted from MediaItem)
|
||||
type TimelineEntry struct {
|
||||
URL string `json:"url"`
|
||||
Date string `json:"date"`
|
||||
TweetID TweetIDString `json:"tweet_id"`
|
||||
Type string `json:"type"`
|
||||
IsRetweet bool `json:"is_retweet"`
|
||||
Extension string `json:"extension"`
|
||||
Width int `json:"width"`
|
||||
Height int `json:"height"`
|
||||
Content string `json:"content,omitempty"`
|
||||
ViewCount int `json:"view_count,omitempty"`
|
||||
BookmarkCount int `json:"bookmark_count,omitempty"`
|
||||
FavoriteCount int `json:"favorite_count,omitempty"`
|
||||
RetweetCount int `json:"retweet_count,omitempty"`
|
||||
ReplyCount int `json:"reply_count,omitempty"`
|
||||
Source string `json:"source,omitempty"`
|
||||
Verified bool `json:"verified,omitempty"`
|
||||
OriginalFilename string `json:"original_filename,omitempty"` // Original filename from API
|
||||
AuthorUsername string `json:"author_username,omitempty"` // Username of tweet author (for bookmarks and likes)
|
||||
URL string `json:"url"`
|
||||
Date string `json:"date"`
|
||||
TweetID TweetIDString `json:"tweet_id"`
|
||||
Type string `json:"type"`
|
||||
IsRetweet bool `json:"is_retweet"`
|
||||
Extension string `json:"extension"`
|
||||
Width int `json:"width"`
|
||||
Height int `json:"height"`
|
||||
Content string `json:"content,omitempty"`
|
||||
ViewCount int `json:"view_count,omitempty"`
|
||||
BookmarkCount int `json:"bookmark_count,omitempty"`
|
||||
FavoriteCount int `json:"favorite_count,omitempty"`
|
||||
RetweetCount int `json:"retweet_count,omitempty"`
|
||||
ReplyCount int `json:"reply_count,omitempty"`
|
||||
Source string `json:"source,omitempty"`
|
||||
Verified bool `json:"verified,omitempty"`
|
||||
OriginalFilename string `json:"original_filename,omitempty"`
|
||||
AuthorUsername string `json:"author_username,omitempty"`
|
||||
}
|
||||
|
||||
// AccountInfo represents Twitter account information (derived from metadata)
|
||||
type AccountInfo struct {
|
||||
Name string `json:"name"`
|
||||
Nick string `json:"nick"`
|
||||
@@ -228,65 +223,58 @@ type AccountInfo struct {
|
||||
StatusesCount int `json:"statuses_count"`
|
||||
}
|
||||
|
||||
// ExtractMetadata represents extraction metadata
|
||||
type ExtractMetadata struct {
|
||||
NewEntries int `json:"new_entries"`
|
||||
Page int `json:"page"`
|
||||
BatchSize int `json:"batch_size"`
|
||||
HasMore bool `json:"has_more"`
|
||||
Cursor string `json:"cursor,omitempty"` // Cursor for resume capability
|
||||
Completed bool `json:"completed,omitempty"` // True if all media fetched
|
||||
Cursor string `json:"cursor,omitempty"`
|
||||
Completed bool `json:"completed,omitempty"`
|
||||
}
|
||||
|
||||
// TwitterResponse represents the full response for frontend
|
||||
type TwitterResponse struct {
|
||||
AccountInfo AccountInfo `json:"account_info"`
|
||||
TotalURLs int `json:"total_urls"`
|
||||
Timeline []TimelineEntry `json:"timeline"`
|
||||
Metadata ExtractMetadata `json:"metadata"`
|
||||
Cursor string `json:"cursor,omitempty"` // Cursor for next fetch
|
||||
Completed bool `json:"completed,omitempty"` // True if fetch completed
|
||||
Cursor string `json:"cursor,omitempty"`
|
||||
Completed bool `json:"completed,omitempty"`
|
||||
}
|
||||
|
||||
// TimelineRequest represents request parameters for timeline extraction
|
||||
type TimelineRequest struct {
|
||||
Username string `json:"username"`
|
||||
AuthToken string `json:"auth_token"`
|
||||
TimelineType string `json:"timeline_type"` // media, timeline, tweets, with_replies, likes, bookmarks
|
||||
BatchSize int `json:"batch_size"` // 0 = all
|
||||
TimelineType string `json:"timeline_type"`
|
||||
BatchSize int `json:"batch_size"`
|
||||
Page int `json:"page"`
|
||||
MediaType string `json:"media_type"` // all, image, video, gif
|
||||
MediaType string `json:"media_type"`
|
||||
Retweets bool `json:"retweets"`
|
||||
Cursor string `json:"cursor,omitempty"` // Resume from this cursor position
|
||||
Cursor string `json:"cursor,omitempty"`
|
||||
}
|
||||
|
||||
// DateRangeRequest represents request parameters for date range extraction
|
||||
type DateRangeRequest struct {
|
||||
Username string `json:"username"`
|
||||
AuthToken string `json:"auth_token"`
|
||||
StartDate string `json:"start_date"` // YYYY-MM-DD
|
||||
EndDate string `json:"end_date"` // YYYY-MM-DD
|
||||
StartDate string `json:"start_date"`
|
||||
EndDate string `json:"end_date"`
|
||||
MediaFilter string `json:"media_filter"`
|
||||
Retweets bool `json:"retweets"`
|
||||
}
|
||||
|
||||
// buildTwitterURL constructs the Twitter URL based on username and timeline type
|
||||
func buildTwitterURL(username, timelineType string) string {
|
||||
// Special case: bookmarks don't need username
|
||||
|
||||
if timelineType == "bookmarks" {
|
||||
return "https://x.com/i/bookmarks"
|
||||
}
|
||||
|
||||
// Clean username - extract handle from URL if needed
|
||||
username = cleanUsername(username)
|
||||
|
||||
// Build URL based on timeline type
|
||||
baseURL := "https://x.com/" + username
|
||||
switch timelineType {
|
||||
case "media":
|
||||
return baseURL + "/media"
|
||||
case "timeline":
|
||||
return baseURL + "/timeline" // Best for cursor support
|
||||
return baseURL + "/timeline"
|
||||
case "tweets":
|
||||
return baseURL + "/tweets"
|
||||
case "with_replies":
|
||||
@@ -294,12 +282,10 @@ func buildTwitterURL(username, timelineType string) string {
|
||||
case "likes":
|
||||
return baseURL + "/likes"
|
||||
default:
|
||||
return baseURL + "/timeline" // Default to timeline for reliable cursor
|
||||
return baseURL + "/timeline"
|
||||
}
|
||||
}
|
||||
|
||||
// cleanUsername extracts the handle from different input formats
|
||||
// Handles: @username, username, https://x.com/username, https://x.com/username/media, etc.
|
||||
func cleanUsername(username string) string {
|
||||
username = strings.TrimSpace(username)
|
||||
username = strings.TrimPrefix(username, "@")
|
||||
@@ -311,12 +297,12 @@ func cleanUsername(username string) string {
|
||||
}
|
||||
if u, err := url.Parse(parsed); err == nil {
|
||||
segments := strings.Split(strings.Trim(u.Path, "/"), "/")
|
||||
// Skip special paths like /i/bookmarks, /search, /home, /explore
|
||||
|
||||
if len(segments) > 0 && segments[0] != "" {
|
||||
firstSegment := strings.ToLower(segments[0])
|
||||
// These are not usernames
|
||||
|
||||
if firstSegment == "i" || firstSegment == "search" || firstSegment == "home" || firstSegment == "explore" || firstSegment == "settings" || firstSegment == "messages" || firstSegment == "notifications" {
|
||||
return username // Return as-is, let caller handle
|
||||
return username
|
||||
}
|
||||
return segments[0]
|
||||
}
|
||||
@@ -326,7 +312,6 @@ func cleanUsername(username string) string {
|
||||
return username
|
||||
}
|
||||
|
||||
// ensureURLScheme normalises URLs so the CLI accepts them
|
||||
func ensureURLScheme(raw string) string {
|
||||
raw = strings.TrimSpace(raw)
|
||||
if raw == "" {
|
||||
@@ -341,7 +326,6 @@ func ensureURLScheme(raw string) string {
|
||||
return "https://" + strings.TrimPrefix(raw, "//")
|
||||
}
|
||||
|
||||
// buildSearchURL assembles an X.com search URL for date range queries
|
||||
func buildSearchURL(username, startDate, endDate, mediaFilter string, includeRetweets bool) string {
|
||||
trimmed := strings.TrimSpace(username)
|
||||
lower := strings.ToLower(trimmed)
|
||||
@@ -380,31 +364,28 @@ func buildSearchURL(username, startDate, endDate, mediaFilter string, includeRet
|
||||
return fmt.Sprintf("https://x.com/search?q=%s&src=typed_query&f=live", query)
|
||||
}
|
||||
|
||||
// convertMetadataToTimelineEntry converts metadata-only tweets to timeline entries
|
||||
func convertMetadataToTimelineEntry(meta TweetMetadata) TimelineEntry {
|
||||
return TimelineEntry{
|
||||
URL: "",
|
||||
Date: meta.Date,
|
||||
TweetID: meta.TweetID,
|
||||
Type: "text",
|
||||
IsRetweet: meta.RetweetID != 0,
|
||||
Extension: "txt",
|
||||
Width: 0,
|
||||
Height: 0,
|
||||
Content: meta.Content,
|
||||
ViewCount: meta.ViewCount,
|
||||
BookmarkCount: meta.BookmarkCount,
|
||||
FavoriteCount: meta.FavoriteCount,
|
||||
RetweetCount: meta.RetweetCount,
|
||||
ReplyCount: meta.ReplyCount,
|
||||
URL: "",
|
||||
Date: meta.Date,
|
||||
TweetID: meta.TweetID,
|
||||
Type: "text",
|
||||
IsRetweet: meta.RetweetID != 0,
|
||||
Extension: "txt",
|
||||
Width: 0,
|
||||
Height: 0,
|
||||
Content: meta.Content,
|
||||
ViewCount: meta.ViewCount,
|
||||
BookmarkCount: meta.BookmarkCount,
|
||||
FavoriteCount: meta.FavoriteCount,
|
||||
RetweetCount: meta.RetweetCount,
|
||||
ReplyCount: meta.ReplyCount,
|
||||
AuthorUsername: meta.Author.Name,
|
||||
}
|
||||
}
|
||||
|
||||
// convertToTimelineEntry converts CLIMediaItem to TimelineEntry
|
||||
func convertToTimelineEntry(media CLIMediaItem) TimelineEntry {
|
||||
// Get username from Author field (preferred for bookmarks/likes) or User field
|
||||
// Author field always contains the tweet author, while User might be the account fetching for likes
|
||||
|
||||
authorUsername := ""
|
||||
if media.Author.Name != "" {
|
||||
authorUsername = media.Author.Name
|
||||
@@ -413,26 +394,24 @@ func convertToTimelineEntry(media CLIMediaItem) TimelineEntry {
|
||||
}
|
||||
|
||||
entry := TimelineEntry{
|
||||
URL: media.URL,
|
||||
TweetID: media.TweetID,
|
||||
Date: media.Date,
|
||||
Extension: media.Extension,
|
||||
Width: media.Width,
|
||||
Height: media.Height,
|
||||
IsRetweet: media.RetweetID != 0,
|
||||
Content: media.Content,
|
||||
ViewCount: media.ViewCount,
|
||||
BookmarkCount: media.BookmarkCount,
|
||||
FavoriteCount: media.FavoriteCount,
|
||||
RetweetCount: media.RetweetCount,
|
||||
ReplyCount: media.ReplyCount,
|
||||
Source: media.Source,
|
||||
Verified: media.Author.Verified,
|
||||
AuthorUsername: authorUsername,
|
||||
// OriginalFilename will be extracted from URL in download.go
|
||||
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,
|
||||
}
|
||||
|
||||
// Determine type - media item already has type from CLI
|
||||
if media.Type != "" {
|
||||
entry.Type = media.Type
|
||||
} else {
|
||||
@@ -449,119 +428,52 @@ func convertToTimelineEntry(media CLIMediaItem) TimelineEntry {
|
||||
return entry
|
||||
}
|
||||
|
||||
// getExtractorPath returns the path to extractor binary
|
||||
// Binary is stored in ~/.twitterxmediabatchdownloader/ (same as ffmpeg and database)
|
||||
func getExtractorPath() string {
|
||||
homeDir, _ := os.UserHomeDir()
|
||||
baseDir := filepath.Join(homeDir, ".twitterxmediabatchdownloader")
|
||||
return filepath.Join(baseDir, getExecutableName())
|
||||
}
|
||||
|
||||
// getHashFilePath returns the path to the hash file for version checking
|
||||
func getHashFilePath() string {
|
||||
homeDir, _ := os.UserHomeDir()
|
||||
baseDir := filepath.Join(homeDir, ".twitterxmediabatchdownloader")
|
||||
return filepath.Join(baseDir, "extractor.sha256")
|
||||
}
|
||||
|
||||
// calculateHash calculates SHA256 hash of data
|
||||
func calculateHash(data []byte) string {
|
||||
hash := sha256.Sum256(data)
|
||||
return hex.EncodeToString(hash[:])
|
||||
}
|
||||
|
||||
// ensureExtractor ensures the extractor binary exists
|
||||
// Extracts from embedded binary if not present or if hash differs (update)
|
||||
func ensureExtractor() (string, error) {
|
||||
exePath := getExtractorPath()
|
||||
hashPath := getHashFilePath()
|
||||
baseDir := filepath.Dir(exePath)
|
||||
|
||||
// Create directory if not exists
|
||||
if err := os.MkdirAll(baseDir, 0755); err != nil {
|
||||
return "", fmt.Errorf("failed to create directory: %v", err)
|
||||
}
|
||||
|
||||
// Calculate hash of embedded binary
|
||||
embeddedHash := calculateHash(extractorBin)
|
||||
|
||||
// Check if binary and hash file exist
|
||||
if _, err := os.Stat(exePath); err == nil {
|
||||
// Binary exists - check hash
|
||||
if storedHash, err := os.ReadFile(hashPath); err == nil {
|
||||
if string(storedHash) == embeddedHash {
|
||||
return exePath, nil // Already extracted and up to date
|
||||
}
|
||||
}
|
||||
// Hash differs or missing - need to update
|
||||
os.Remove(exePath)
|
||||
}
|
||||
|
||||
// Extract binary
|
||||
if err := os.WriteFile(exePath, extractorBin, 0755); err != nil {
|
||||
return "", fmt.Errorf("failed to write extractor: %v", err)
|
||||
}
|
||||
|
||||
// Save hash for future comparison
|
||||
if err := os.WriteFile(hashPath, []byte(embeddedHash), 0644); err != nil {
|
||||
// Non-fatal - binary still works, just won't skip next time
|
||||
fmt.Printf("Warning: failed to save hash file: %v\n", err)
|
||||
}
|
||||
|
||||
return exePath, nil
|
||||
}
|
||||
|
||||
// ExtractTimeline extracts media from user timeline using the new CLI
|
||||
func ExtractTimeline(req TimelineRequest) (*TwitterResponse, error) {
|
||||
// Get or extract extractor binary (persistent, not temp)
|
||||
exePath, err := ensureExtractor()
|
||||
|
||||
exePath, err := requireExtractorPath()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Determine the right endpoint based on what user wants:
|
||||
// - Media (all/image/video/gif): Use /media endpoint - fastest and most reliable
|
||||
// - Text tweets: Use /tweets endpoint with --text-tweets
|
||||
// - With retweets: Use /tweets endpoint (retweets not available on /media)
|
||||
isTextOnly := req.MediaType == "text"
|
||||
wantsRetweets := req.Retweets
|
||||
|
||||
timelineType := req.TimelineType
|
||||
if timelineType == "" {
|
||||
if isTextOnly {
|
||||
// Text-only tweets need /tweets endpoint
|
||||
|
||||
timelineType = "tweets"
|
||||
} else if wantsRetweets {
|
||||
// Retweets need /tweets endpoint (not available on /media)
|
||||
|
||||
timelineType = "tweets"
|
||||
} else {
|
||||
// Default: /media endpoint - fastest for media-only fetch
|
||||
|
||||
timelineType = "media"
|
||||
}
|
||||
}
|
||||
|
||||
url := buildTwitterURL(req.Username, timelineType)
|
||||
|
||||
// Build command arguments for new CLI format
|
||||
// Format: extractor.exe URL --auth-token TOKEN --json [options]
|
||||
args := []string{url}
|
||||
|
||||
// Add auth token
|
||||
if req.AuthToken != "" {
|
||||
args = append(args, "--auth-token", req.AuthToken)
|
||||
} else {
|
||||
args = append(args, "--guest")
|
||||
}
|
||||
|
||||
// Always request JSON output with metadata
|
||||
args = append(args, "--json", "--metadata")
|
||||
|
||||
// Add limit if specified
|
||||
if req.BatchSize > 0 {
|
||||
args = append(args, "--limit", fmt.Sprintf("%d", req.BatchSize))
|
||||
}
|
||||
|
||||
// Handle retweets - only relevant when using /tweets endpoint
|
||||
if timelineType == "tweets" || timelineType == "timeline" {
|
||||
if req.Retweets {
|
||||
args = append(args, "--retweets", "include")
|
||||
@@ -570,12 +482,10 @@ func ExtractTimeline(req TimelineRequest) (*TwitterResponse, error) {
|
||||
}
|
||||
}
|
||||
|
||||
// Only add --text-tweets when explicitly requesting text content
|
||||
if isTextOnly {
|
||||
args = append(args, "--text-tweets")
|
||||
}
|
||||
|
||||
// Handle media type filter using --type parameter
|
||||
if req.MediaType != "" && req.MediaType != "all" && !isTextOnly {
|
||||
switch req.MediaType {
|
||||
case "image":
|
||||
@@ -587,21 +497,18 @@ func ExtractTimeline(req TimelineRequest) (*TwitterResponse, error) {
|
||||
}
|
||||
}
|
||||
|
||||
// Add cursor for resume capability
|
||||
if req.Cursor != "" {
|
||||
args = append(args, "--cursor", req.Cursor)
|
||||
}
|
||||
|
||||
// Execute command with UTF-8 encoding
|
||||
cmd := exec.Command(exePath, args...)
|
||||
cmd.Env = append(os.Environ(),
|
||||
"PYTHONIOENCODING=utf-8",
|
||||
"PYTHONUTF8=1",
|
||||
)
|
||||
hideWindow(cmd) // Hide console window on Windows
|
||||
hideWindow(cmd)
|
||||
output, err := cmd.CombinedOutput()
|
||||
|
||||
// Ensure process is killed after completion
|
||||
if cmd.Process != nil {
|
||||
cmd.Process.Kill()
|
||||
}
|
||||
@@ -612,36 +519,31 @@ func ExtractTimeline(req TimelineRequest) (*TwitterResponse, error) {
|
||||
return nil, fmt.Errorf("%s", errorMsg)
|
||||
}
|
||||
|
||||
// Find JSON in output (skip any info messages)
|
||||
jsonStr := extractJSON(string(output))
|
||||
if jsonStr == "" {
|
||||
outputStr := string(output)
|
||||
if strings.TrimSpace(outputStr) == "" {
|
||||
return nil, fmt.Errorf("empty_response: Extractor returned no data. The timeline may be empty or inaccessible")
|
||||
return nil, fmt.Errorf("empty_response: Xtractor returned no data. The timeline may be empty or inaccessible")
|
||||
}
|
||||
return nil, fmt.Errorf("parse_error: Could not parse extractor output. Raw output: %s", outputStr)
|
||||
return nil, fmt.Errorf("parse_error: Could not parse xtractor output. Raw output: %s", outputStr)
|
||||
}
|
||||
|
||||
// Parse CLI response
|
||||
var cliResponse CLIResponse
|
||||
if err := json.Unmarshal([]byte(jsonStr), &cliResponse); err != nil {
|
||||
return nil, fmt.Errorf("json_error: Failed to parse JSON response: %v", err)
|
||||
}
|
||||
|
||||
// Convert to frontend format
|
||||
var timeline []TimelineEntry
|
||||
accountInfo := AccountInfo{
|
||||
Name: req.Username,
|
||||
Nick: req.Username,
|
||||
}
|
||||
|
||||
// Build a set of tweet IDs that have media
|
||||
mediaTweetIDs := make(map[int64]bool)
|
||||
for _, media := range cliResponse.Media {
|
||||
mediaTweetIDs[int64(media.TweetID)] = true
|
||||
}
|
||||
|
||||
// For bookmarks and likes, keep name as "bookmarks"/"likes" (not from author tweet)
|
||||
isBookmarks := req.TimelineType == "bookmarks"
|
||||
isLikes := req.TimelineType == "likes"
|
||||
if isBookmarks {
|
||||
@@ -653,7 +555,7 @@ func ExtractTimeline(req TimelineRequest) (*TwitterResponse, error) {
|
||||
}
|
||||
|
||||
if isTextOnly {
|
||||
// Text-only mode: get tweets from metadata that don't have media
|
||||
|
||||
timeline = make([]TimelineEntry, 0)
|
||||
for _, meta := range cliResponse.Metadata {
|
||||
if !mediaTweetIDs[int64(meta.TweetID)] {
|
||||
@@ -661,7 +563,6 @@ func ExtractTimeline(req TimelineRequest) (*TwitterResponse, error) {
|
||||
}
|
||||
}
|
||||
|
||||
// Get account info from first media item if available, otherwise from metadata
|
||||
if !isBookmarks && !isLikes {
|
||||
if len(cliResponse.Media) > 0 {
|
||||
user := cliResponse.Media[0].User
|
||||
@@ -678,7 +579,7 @@ func ExtractTimeline(req TimelineRequest) (*TwitterResponse, error) {
|
||||
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
|
||||
@@ -689,15 +590,13 @@ func ExtractTimeline(req TimelineRequest) (*TwitterResponse, error) {
|
||||
}
|
||||
}
|
||||
} else if len(cliResponse.Media) > 0 {
|
||||
// Normal media items only (text tweets handled separately with "text" media type)
|
||||
|
||||
timeline = make([]TimelineEntry, 0, len(cliResponse.Media))
|
||||
|
||||
// Add media items
|
||||
for _, media := range cliResponse.Media {
|
||||
timeline = append(timeline, convertToTimelineEntry(media))
|
||||
}
|
||||
|
||||
// Get account info from first media item
|
||||
user := cliResponse.Media[0].User
|
||||
if !isBookmarks && !isLikes {
|
||||
accountInfo.Name = user.Name
|
||||
@@ -709,29 +608,29 @@ func ExtractTimeline(req TimelineRequest) (*TwitterResponse, error) {
|
||||
accountInfo.ProfileImage = user.ProfileImage
|
||||
accountInfo.StatusesCount = user.StatusesCount
|
||||
} else if len(cliResponse.Metadata) > 0 {
|
||||
// Fallback: Text-only tweets (no media) - convert metadata to timeline entries
|
||||
|
||||
timeline = make([]TimelineEntry, 0, len(cliResponse.Metadata))
|
||||
for _, meta := range cliResponse.Metadata {
|
||||
entry := TimelineEntry{
|
||||
URL: "", // No media URL for text tweets
|
||||
TweetID: meta.TweetID,
|
||||
Date: meta.Date,
|
||||
Type: "text",
|
||||
IsRetweet: meta.RetweetID != 0,
|
||||
Extension: "txt",
|
||||
Width: 0,
|
||||
Height: 0,
|
||||
Content: meta.Content,
|
||||
ViewCount: meta.ViewCount,
|
||||
BookmarkCount: meta.BookmarkCount,
|
||||
FavoriteCount: meta.FavoriteCount,
|
||||
RetweetCount: meta.RetweetCount,
|
||||
ReplyCount: meta.ReplyCount,
|
||||
URL: "",
|
||||
TweetID: meta.TweetID,
|
||||
Date: meta.Date,
|
||||
Type: "text",
|
||||
IsRetweet: meta.RetweetID != 0,
|
||||
Extension: "txt",
|
||||
Width: 0,
|
||||
Height: 0,
|
||||
Content: meta.Content,
|
||||
ViewCount: meta.ViewCount,
|
||||
BookmarkCount: meta.BookmarkCount,
|
||||
FavoriteCount: meta.FavoriteCount,
|
||||
RetweetCount: meta.RetweetCount,
|
||||
ReplyCount: meta.ReplyCount,
|
||||
AuthorUsername: meta.Author.Name,
|
||||
}
|
||||
timeline = append(timeline, entry)
|
||||
}
|
||||
// Get account info from first metadata
|
||||
|
||||
if !isBookmarks && !isLikes {
|
||||
firstMeta := cliResponse.Metadata[0]
|
||||
accountInfo.Name = firstMeta.Author.Name
|
||||
@@ -739,7 +638,6 @@ func ExtractTimeline(req TimelineRequest) (*TwitterResponse, error) {
|
||||
}
|
||||
}
|
||||
|
||||
// Determine if there's more data to fetch
|
||||
hasMore := cliResponse.Cursor != "" && !cliResponse.Completed
|
||||
|
||||
response := &TwitterResponse{
|
||||
@@ -761,10 +659,9 @@ func ExtractTimeline(req TimelineRequest) (*TwitterResponse, error) {
|
||||
return response, nil
|
||||
}
|
||||
|
||||
// ExtractDateRange extracts media based on date range using the new CLI
|
||||
func ExtractDateRange(req DateRangeRequest) (*TwitterResponse, error) {
|
||||
// Get or extract extractor binary (persistent, not temp)
|
||||
exePath, err := ensureExtractor()
|
||||
|
||||
exePath, err := requireExtractorPath()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -772,17 +669,14 @@ func ExtractDateRange(req DateRangeRequest) (*TwitterResponse, error) {
|
||||
mediaFilter := strings.ToLower(strings.TrimSpace(req.MediaFilter))
|
||||
url := buildSearchURL(req.Username, req.StartDate, req.EndDate, mediaFilter, req.Retweets)
|
||||
|
||||
// Build command arguments
|
||||
args := []string{url}
|
||||
|
||||
// Add auth token
|
||||
if req.AuthToken != "" {
|
||||
args = append(args, "--auth-token", req.AuthToken)
|
||||
} else {
|
||||
args = append(args, "--guest")
|
||||
}
|
||||
|
||||
// Always request JSON output with metadata
|
||||
args = append(args, "--json", "--metadata")
|
||||
|
||||
if req.Retweets {
|
||||
@@ -796,7 +690,6 @@ func ExtractDateRange(req DateRangeRequest) (*TwitterResponse, error) {
|
||||
args = append(args, "--text-tweets")
|
||||
}
|
||||
|
||||
// Execute command with UTF-8 encoding
|
||||
cmd := exec.Command(exePath, args...)
|
||||
cmd.Env = append(os.Environ(),
|
||||
"PYTHONIOENCODING=utf-8",
|
||||
@@ -805,7 +698,6 @@ func ExtractDateRange(req DateRangeRequest) (*TwitterResponse, error) {
|
||||
hideWindow(cmd)
|
||||
output, err := cmd.CombinedOutput()
|
||||
|
||||
// Ensure process is killed after completion
|
||||
if cmd.Process != nil {
|
||||
cmd.Process.Kill()
|
||||
}
|
||||
@@ -816,23 +708,20 @@ func ExtractDateRange(req DateRangeRequest) (*TwitterResponse, error) {
|
||||
return nil, fmt.Errorf("%s", errorMsg)
|
||||
}
|
||||
|
||||
// Find JSON in output (skip any info messages)
|
||||
jsonStr := extractJSON(string(output))
|
||||
if jsonStr == "" {
|
||||
outputStr := string(output)
|
||||
if strings.TrimSpace(outputStr) == "" {
|
||||
return nil, fmt.Errorf("empty_response: Extractor returned no data. The timeline may be empty or inaccessible")
|
||||
return nil, fmt.Errorf("empty_response: Xtractor returned no data. The timeline may be empty or inaccessible")
|
||||
}
|
||||
return nil, fmt.Errorf("parse_error: Could not parse extractor output. Raw output: %s", outputStr)
|
||||
return nil, fmt.Errorf("parse_error: Could not parse xtractor output. Raw output: %s", outputStr)
|
||||
}
|
||||
|
||||
// Parse CLI response
|
||||
var cliResponse CLIResponse
|
||||
if err := json.Unmarshal([]byte(jsonStr), &cliResponse); err != nil {
|
||||
return nil, fmt.Errorf("json_error: Failed to parse JSON response: %v", err)
|
||||
}
|
||||
|
||||
// Convert to frontend format
|
||||
mediaTweetIDs := make(map[int64]bool)
|
||||
for _, media := range cliResponse.Media {
|
||||
mediaTweetIDs[int64(media.TweetID)] = true
|
||||
@@ -851,7 +740,6 @@ func ExtractDateRange(req DateRangeRequest) (*TwitterResponse, error) {
|
||||
}
|
||||
}
|
||||
|
||||
// Build account info from first media item (has full user info)
|
||||
accountInfo := AccountInfo{
|
||||
Name: req.Username,
|
||||
Nick: req.Username,
|
||||
@@ -871,7 +759,6 @@ func ExtractDateRange(req DateRangeRequest) (*TwitterResponse, error) {
|
||||
accountInfo.Nick = firstMeta.Author.Nick
|
||||
}
|
||||
|
||||
// Determine if there's more data to fetch
|
||||
hasMore := cliResponse.Cursor != "" && !cliResponse.Completed
|
||||
|
||||
response := &TwitterResponse{
|
||||
@@ -893,15 +780,13 @@ func ExtractDateRange(req DateRangeRequest) (*TwitterResponse, error) {
|
||||
return response, nil
|
||||
}
|
||||
|
||||
// extractJSON finds and extracts JSON object from output string
|
||||
func extractJSON(output string) string {
|
||||
// Find the start of JSON object
|
||||
|
||||
start := strings.Index(output, "{")
|
||||
if start == -1 {
|
||||
return ""
|
||||
}
|
||||
|
||||
// Find the matching closing brace
|
||||
depth := 0
|
||||
for i := start; i < len(output); i++ {
|
||||
if output[i] == '{' {
|
||||
|
||||
Reference in new issue
Block a user