hnbot/sn.go

121 lines
2.4 KiB
Go
Raw Permalink Normal View History

2023-04-16 15:14:44 +00:00
package main
import (
"bytes"
"encoding/json"
2023-04-16 15:28:38 +00:00
"fmt"
2023-04-16 15:14:44 +00:00
"log"
"net/http"
)
type GraphQLPayload struct {
Query string `json:"query"`
Variables map[string]interface{} `json:"variables,omitempty"`
}
2023-04-16 15:53:49 +00:00
type Dupe struct {
Id int `json:"id,string"`
Url string `json:"url"`
Title string `json:"title"`
}
type DupesResponse struct {
Data struct {
Dupes []Dupe `json:"dupes"`
} `json:"data"`
}
2023-04-16 15:14:44 +00:00
func filterByRelevanceForSN(stories *[]Story) *[]Story {
// TODO: filter by relevance
slice := (*stories)[0:1]
return &slice
}
2023-04-16 15:53:49 +00:00
func fetchDupes(url string) *[]Dupe {
body := GraphQLPayload{
Query: `
query Dupes($url: String!) {
dupes(url: $url) {
id
url
title
}
}`,
Variables: map[string]interface{}{
"url": url,
},
}
bodyJSON, err := json.Marshal(body)
if err != nil {
log.Fatal("Error during json.Marshal:", err)
}
apiUrl := "https://stacker.news/api/graphql"
req, err := http.NewRequest("POST", apiUrl, bytes.NewBuffer(bodyJSON))
if err != nil {
panic(err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Cookie", fmt.Sprintf("__Host-next-auth.csrf-token=%s", SnApiToken))
client := http.DefaultClient
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
var dupesResp DupesResponse
err = json.NewDecoder(resp.Body).Decode(&dupesResp)
if err != nil {
log.Fatal("Error decoding dupes JSON:", err)
}
return &dupesResp.Data.Dupes
}
2023-04-16 15:14:44 +00:00
func postToSN(story *Story) {
2023-04-16 15:53:49 +00:00
dupes := fetchDupes(story.Url)
if len(*dupes) > 0 {
return
}
2023-04-16 15:14:44 +00:00
body := GraphQLPayload{
Query: `
mutation upsertLink($url: String!, $title: String!) {
upsertLink(url: $url, title: $title) {
id
}
}
`,
Variables: map[string]interface{}{
"url": story.Url,
"title": story.Title,
},
}
bodyJSON, err := json.Marshal(body)
if err != nil {
log.Fatal("Error during json.Marshal:", err)
}
2023-04-16 15:53:49 +00:00
apiUrl := "https://stacker.news/api/graphql"
req, err := http.NewRequest("POST", apiUrl, bytes.NewBuffer(bodyJSON))
2023-04-16 15:14:44 +00:00
if err != nil {
panic(err)
}
req.Header.Set("Content-Type", "application/json")
2023-04-16 15:28:38 +00:00
req.Header.Set("Cookie", fmt.Sprintf("__Host-next-auth.csrf-token=%s", SnApiToken))
2023-04-16 15:14:44 +00:00
client := http.DefaultClient
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
2023-04-16 15:53:49 +00:00
log.Printf("POST %s %d\n", apiUrl, resp.StatusCode)
2023-04-16 15:14:44 +00:00
}