summaryrefslogtreecommitdiffstats
path: root/internal/client/skiptrace.go
blob: d4e26ea67eb5f013266cd9c914a9f1196fce001d (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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
package client

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

func parseSSEResponse(data []byte) ([]byte, error) {
	scanner := bufio.NewScanner(bytes.NewReader(data))

	const maxScanTokenSize = 10 * 1024 * 1024
	buf := make([]byte, maxScanTokenSize)
	scanner.Buffer(buf, maxScanTokenSize)

	var resultData []byte
	var foundResult bool

	for scanner.Scan() {
		line := scanner.Text()

		if line == "event: result" {
			foundResult = true
			continue
		}

		if foundResult && strings.HasPrefix(line, "data: ") {
			resultData = []byte(strings.TrimPrefix(line, "data: "))
			break
		}
	}

	if err := scanner.Err(); err != nil {
		return nil, fmt.Errorf("error reading SSE response: %w", err)
	}

	if resultData == nil {
		return nil, fmt.Errorf("no result event found in SSE response")
	}

	trimmed := strings.TrimSpace(string(resultData))
	if !strings.HasPrefix(trimmed, "{") && !strings.HasPrefix(trimmed, "[") {
		return nil, fmt.Errorf("API returned: %s", trimmed)
	}

	return resultData, nil
}

func (c *Client) getSSE(path string, params url.Values) ([]byte, error) {
	fullURL := c.config.BaseURL + path
	if params != nil && len(params) > 0 {
		fullURL += "?" + params.Encode()
	}

	req, err := http.NewRequest("GET", fullURL, nil)
	if err != nil {
		return nil, 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)

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

	if resp.StatusCode != http.StatusOK {
		bodyBytes, _ := io.ReadAll(resp.Body)
		switch resp.StatusCode {
		case http.StatusPaymentRequired:
			return nil, fmt.Errorf("insufficient credits (402): %s - Please add credits to your account", string(bodyBytes))
		case http.StatusForbidden:
			return nil, fmt.Errorf("access denied (403): %s - This endpoint requires premium access", string(bodyBytes))
		case http.StatusUnauthorized:
			return nil, fmt.Errorf("unauthorized (401): %s - Check your API key", string(bodyBytes))
		case http.StatusTooManyRequests:
			return nil, fmt.Errorf("rate limit exceeded (429): %s", string(bodyBytes))
		case http.StatusBadRequest:
			return nil, fmt.Errorf("bad request (400): %s", string(bodyBytes))
		default:
			return nil, fmt.Errorf("API request failed with status %d: %s", resp.StatusCode, string(bodyBytes))
		}
	}

	data, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, fmt.Errorf("failed to read response: %w", err)
	}

	contentType := resp.Header.Get("Content-Type")

	if strings.HasPrefix(string(data), "event:") || strings.Contains(contentType, "text/event-stream") {
		return parseSSEResponse(data)
	}

	return data, nil
}

func (c *Client) SearchPeople(params *models.SkiptraceParams) (*models.SkiptraceResponse, error) {
	queryParams := url.Values{}
	queryParams.Set("first_name", params.FirstName)
	queryParams.Set("last_name", params.LastName)

	if params.City != "" {
		queryParams.Set("city", params.City)
	}
	if params.State != "" {
		queryParams.Set("state", params.State)
	}
	if params.Age != "" {
		queryParams.Set("age", params.Age)
	}

	data, err := c.getSSE("/prem/skiptrace/people/search", queryParams)
	if err != nil {
		return nil, err
	}

	var response models.SkiptraceResponse
	if err := json.Unmarshal(data, &response); err != nil {
		return nil, fmt.Errorf("failed to parse response: %w", err)
	}

	return &response, nil
}

func (c *Client) GetPersonReport(sxKey string, selection int) (*models.SkiptraceReportResponse, error) {
	path := fmt.Sprintf("/prem/skiptrace/people/report/%s/%d", sxKey, selection)

	data, err := c.getSSE(path, nil)
	if err != nil {
		return nil, err
	}

	var response models.SkiptraceReportResponse
	if err := json.Unmarshal(data, &response); err != nil {
		return nil, fmt.Errorf("failed to parse response: %w", err)
	}

	return &response, nil
}

func (c *Client) SearchPhone(phone string) (*models.SkiptracePhoneResponse, error) {
	path := fmt.Sprintf("/prem/skiptrace/phone/%s", phone)

	data, err := c.getSSE(path, nil)
	if err != nil {
		return nil, err
	}

	var response models.SkiptracePhoneResponse
	if err := json.Unmarshal(data, &response); err != nil {
		return nil, fmt.Errorf("failed to parse response: %w", err)
	}

	return &response, nil
}

func (c *Client) SearchEmail(email string) (*models.SkiptraceEmailResponse, error) {
	path := fmt.Sprintf("/prem/skiptrace/email/%s", email)

	data, err := c.getSSE(path, nil)
	if err != nil {
		return nil, err
	}

	var response models.SkiptraceEmailResponse
	if err := json.Unmarshal(data, &response); err != nil {
		return nil, fmt.Errorf("failed to parse response: %w", err)
	}

	return &response, nil
}