summaryrefslogtreecommitdiffstats
path: root/internal/client/usrsx.go
blob: a3aaa66a87cc4820d42dea0a2bcd5c6319f1f2f1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package client

import (
	"bufio"
	"encoding/json"
	"fmt"
	"git.db.org.ai/dborg/internal/models"
	"io"
	"net/http"
	"net/url"
	"strings"
)

func (c *Client) CheckUsernameStream(params *models.USRSXParams, callback func(result json.RawMessage) error) error {
	queryParams := url.Values{}

	if len(params.Sites) > 0 {
		queryParams.Add("sites", strings.Join(params.Sites, ","))
	}
	if params.Fuzzy {
		queryParams.Add("fuzzy", "true")
	}
	if params.MaxTasks > 0 && params.MaxTasks != 50 {
		queryParams.Add("max_tasks", fmt.Sprintf("%d", params.MaxTasks))
	}

	path := fmt.Sprintf("/osint/username/%s", url.PathEscape(params.Username))
	fullURL := c.config.BaseURL + path
	if len(queryParams) > 0 {
		fullURL += "?" + queryParams.Encode()
	}

	req, err := http.NewRequest(http.MethodGet, fullURL, nil)
	if err != nil {
		return fmt.Errorf("failed to create request: %w", err)
	}

	req.Header.Set("X-API-Key", c.config.APIKey)
	req.Header.Set("User-Agent", c.config.UserAgent)
	req.Header.Set("Accept", "application/x-ndjson, application/json")

	resp, err := c.httpClient.Do(req)
	if err != nil {
		return fmt.Errorf("failed to execute request: %w", err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		body, _ := io.ReadAll(resp.Body)
		return fmt.Errorf("API request failed with status %d: %s", resp.StatusCode, string(body))
	}

	scanner := bufio.NewScanner(resp.Body)
	for scanner.Scan() {
		line := scanner.Bytes()
		if len(line) == 0 {
			continue
		}

		if err := callback(json.RawMessage(line)); err != nil {
			return err
		}
	}

	if err := scanner.Err(); err != nil {
		if !strings.Contains(err.Error(), "context deadline exceeded") && !strings.Contains(err.Error(), "timeout") {
			return fmt.Errorf("stream reading error: %w", err)
		}
	}

	return nil
}