-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
243 lines (219 loc) · 6.32 KB
/
main.go
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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
package main
import (
"fmt"
"io"
"log"
"math"
"net/http"
"net/url"
"os"
"regexp"
"strings"
"time"
"github.com/tidwall/gjson"
)
type note struct {
ID string
URL string
}
type noteStore struct {
Username string
Notes []note
}
var (
// The URL of the API endpoint.
apiURL = "https://blahaj.zone/api"
)
// main is the entry point of the Go program.
//
// It reads the contents of a file called "input.txt" in the same directory.
// Then, it searches for URLs in the content using a regular expression.
// It retrieves the host and username from each URL and makes API calls to get the user ID, notes count, and user notes.
// Finally, it saves the note URLs to a file called "output.txt".
func main() {
// read from a file called input in the same directory
body, err := os.ReadFile("input.txt")
if err != nil {
log.Fatal(err)
}
example := string(body)
regex := regexp.MustCompile(`(?m)[<]?(https?:\/\/[^\s<>]+)[>]?\b`)
result := regex.FindAllStringSubmatch(example, -1)
noteCache := []noteStore{}
noteURLs := []string{}
for _, element := range result {
log.Print("------------------------------------------------")
log.Printf("URL: %s", element[0])
u, err := url.Parse(element[0])
if err != nil {
log.Fatal(err)
}
host := u.Host
username := strings.Split(u.Path, "/")[1]
username, _ = strings.CutPrefix(username, "@")
log.Printf("host: %s, username: %s", host, username)
id, notesCount, err := getUserID(username, host)
if err != nil {
log.Fatal(err)
}
if id == "" {
log.Printf("no match for %s", element[0])
continue
}
log.Printf("userID: %s, notes: %d", id, notesCount)
var notes []note
// if noteCache is empty get notes
if len(noteCache) == 0 {
log.Print("getting notes...")
notes, err = getUserNotes(id, notesCount)
if err != nil {
log.Fatal(err)
}
noteCache = append(noteCache, noteStore{Username: id, Notes: notes})
} else {
// check if note is in cache
var match bool
for _, note := range noteCache {
if note.Username == id {
log.Print("found in cache")
notes = note.Notes
match = true
break
}
}
// if not in cache get notes
if !match {
log.Print("not in cache, getting notes...")
notes, err = getUserNotes(id, notesCount)
if err != nil {
log.Fatal(err)
}
noteCache = append(noteCache, noteStore{Username: id, Notes: notes})
}
}
log.Printf("grabbed %d notes", len(notes))
var match bool
for _, note := range notes {
// check if note url matches example and print id and url
if strings.Contains(note.URL, element[0]) {
id = note.ID
noteURL := "https://blahaj.zone/notes/" + id
saveURL := noteURL + " = " + element[0]
noteURLs = append(noteURLs, saveURL)
match = true
log.Printf("noteID: %s, url: %s", id, noteURL)
}
}
if !match {
saveURL := "no match for " + element[0]
noteURLs = append(noteURLs, saveURL)
log.Printf("no match found...")
}
}
err = os.WriteFile("output.txt", []byte(strings.Join(noteURLs, "\n")), 0644)
if err != nil {
log.Fatal(err)
}
}
// getUserID retrieves the user ID and notes count for a given username and host.
//
// Parameters:
// - username: The username of the user.
// - host: The host of the user.
//
// Returns:
// - id: The user ID.
// - notesCount: The count of notes for the user.
// - error: The error that occurred during the API call.
func getUserID(username string, host string) (string, int64, error) {
domain := apiURL + "/users/show"
json := []byte(`{"username": "` + username + `", "host": "` + host + `"}`)
body, err := postAPI(domain, string(json))
if err != nil {
return "", 0, err
}
id := gjson.Get(string(body), "id").String()
notesCount := gjson.Get(string(body), "notesCount").Int()
return id, notesCount, nil
}
// getUserNotes retrieves the notes of a user based on the provided user ID and the count of notes.
//
// Parameters:
// - userid: a string representing the ID of the user.
// - notesCount: an int64 representing the count of notes to retrieve.
//
// Returns:
// - []note: an array of notes.
// - error: an error if there was a problem retrieving the notes.
func getUserNotes(userid string, notesCount int64) ([]note, error) {
// array of notes
var noteList = []note{}
totalPasses := math.Ceil(float64(notesCount) / 100.0)
var passes int64
for i := 0; i < int(totalPasses); i++ {
time.Sleep(500 * time.Millisecond)
var json = []byte{}
if int(totalPasses) == 1 {
json = []byte(`{"userId": "` + userid + `", "limit": ` + fmt.Sprint(notesCount) + `}`)
passes += notesCount
}
if int(totalPasses) > 1 && i == 0 {
json = []byte(`{"userId": "` + userid + `", "limit": ` + fmt.Sprint(100) + `}`)
passes += 100
}
if int(totalPasses) > 1 && i > 0 {
if i == int(totalPasses)-1 {
// last iteration, calculate remaining ntoes
remainingNotes := notesCount - passes
json = []byte(`{"userId": "` + userid + `", "limit": ` + fmt.Sprint(remainingNotes) + `, "untilId": "` + noteList[len(noteList)-1].ID + `"}`)
passes += remainingNotes
} else {
json = []byte(`{"userId": "` + userid + `", "limit": ` + fmt.Sprint(100) + `, "untilId": "` + noteList[len(noteList)-1].ID + `"}`)
passes += 100
}
}
domain := apiURL + "/users/notes"
body, err := postAPI(domain, string(json))
if err != nil {
return noteList, err
}
if body == "[]" {
return noteList, nil
}
jsonArray := gjson.Parse(string(body)).Array()
for _, json := range jsonArray {
noteList = append(noteList, note{
ID: json.Get("id").String(),
URL: json.Get("url").String(),
})
}
}
return noteList, nil
}
// postAPI sends a POST request to the specified path with the provided data and returns the response body as a string.
//
// Parameters:
// - path: the URL path to send the request to.
// - data: the data to include in the request body.
//
// Returns:
// - string: the response body as a string.
// - error: any error that occurred during the request.
func postAPI(path string, data string) (string, error) {
req, err := http.NewRequest("POST", path, strings.NewReader(string(data)))
if err != nil {
return "", err
}
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}
return string(body), nil
}