Compare commits
24 Commits
Author | SHA1 | Date | |
---|---|---|---|
47a35e428e | |||
112cd5874b | |||
117d04912f | |||
86612a527b | |||
04fd2ccbe4 | |||
b880c1256e | |||
f85af6abe3 | |||
7048c2ec9b | |||
f21145f24f | |||
d3f5fce46d | |||
c184d18431 | |||
c80f0060c3 | |||
f911f10822 | |||
049ea1f1c0 | |||
c6f926dd8c | |||
f4c1b57c1f | |||
f187218532 | |||
17878b2f32 | |||
2a663690a8 | |||
6debdd8ba6 | |||
f7727cf441 | |||
ffc5baa79c | |||
5ba3c56b75 | |||
|
03eeee8cc0 |
1
.gitignore
vendored
Normal file
1
.gitignore
vendored
Normal file
@ -0,0 +1 @@
|
||||
.env
|
28
README.md
28
README.md
@ -1,19 +1,19 @@
|
||||
# sn-goapi
|
||||
# snappy
|
||||
|
||||
Package for [stacker.news](https://stacker.news) API access
|
||||
<div style="text-align: center">
|
||||
|
||||
Install via `go get github.com/ekzyis/sn-goapi`
|
||||
<img src="https://stacker.news/favicon.png" width="64" height="64" />
|
||||
<img src="https://go.dev/blog/go-brand/Go-Logo/PNG/Go-Logo_Blue.png" width="64" height="64" />
|
||||
|
||||
Supports:
|
||||
[stacker.news](https://stacker.news) API client package for Go
|
||||
|
||||
- [ ] Post of type ...
|
||||
- [ ] ... Discussion
|
||||
- [x] ... Link
|
||||
- [ ] ... Bounty
|
||||
- [ ] ... Poll
|
||||
- [x] Reply (comments)
|
||||
- [ ] Tips
|
||||
- [x] Checking dupes
|
||||
- [x] Checking notifications
|
||||
</div>
|
||||
|
||||
`SN_AUTH_COOKIE` must be set with a valid session cookie.
|
||||
|
||||
## How to use
|
||||
|
||||
```
|
||||
$ go get github.com/ekzyis/snappy
|
||||
```
|
||||
|
||||
`SN_API_KEY` must be set in your environment for authenticated API access.
|
||||
|
109
client.go
Normal file
109
client.go
Normal file
@ -0,0 +1,109 @@
|
||||
package sn
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
)
|
||||
|
||||
type Client struct {
|
||||
BaseUrl string
|
||||
ApiUrl string
|
||||
ApiKey string
|
||||
MediaUrl string
|
||||
}
|
||||
|
||||
func NewClient(options ...func(*Client)) *Client {
|
||||
c := &Client{}
|
||||
for _, o := range options {
|
||||
o(c)
|
||||
}
|
||||
|
||||
// set defaults
|
||||
var ok bool
|
||||
if c.BaseUrl == "" {
|
||||
c.BaseUrl, ok = os.LookupEnv("SN_BASE_URL")
|
||||
if !ok {
|
||||
c.BaseUrl = "https://stacker.news"
|
||||
}
|
||||
}
|
||||
if c.ApiKey == "" {
|
||||
c.ApiKey = os.Getenv("SN_API_KEY")
|
||||
}
|
||||
if c.MediaUrl == "" {
|
||||
c.MediaUrl, ok = os.LookupEnv("SN_MEDIA_URL")
|
||||
if !ok {
|
||||
c.MediaUrl = "https://m.stacker.news"
|
||||
}
|
||||
}
|
||||
c.ApiUrl = fmt.Sprintf("%s/api/graphql", c.BaseUrl)
|
||||
|
||||
return c
|
||||
}
|
||||
|
||||
func WithApiKey(apiKey string) func(*Client) {
|
||||
return func(c *Client) {
|
||||
c.ApiKey = apiKey
|
||||
}
|
||||
}
|
||||
|
||||
func WithBaseUrl(baseUrl string) func(*Client) {
|
||||
return func(c *Client) {
|
||||
c.BaseUrl = baseUrl
|
||||
}
|
||||
}
|
||||
|
||||
func WithMediaUrl(mediaUrl string) func(*Client) {
|
||||
return func(c *Client) {
|
||||
c.MediaUrl = mediaUrl
|
||||
}
|
||||
}
|
||||
|
||||
type GqlBody struct {
|
||||
Query string `json:"query"`
|
||||
Variables map[string]interface{} `json:"variables,omitempty"`
|
||||
}
|
||||
|
||||
type GqlError struct {
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
func (c *Client) callApi(body GqlBody) (*http.Response, error) {
|
||||
bodyJSON, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("error encoding SN payload: %w", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
req, err := http.NewRequest("POST", c.ApiUrl, bytes.NewBuffer(bodyJSON))
|
||||
if err != nil {
|
||||
err = fmt.Errorf("error preparing SN request: %w", err)
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
if c.ApiKey != "" {
|
||||
req.Header.Set("X-Api-Key", c.ApiKey)
|
||||
}
|
||||
|
||||
client := http.DefaultClient
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
func (c *Client) checkForErrors(err []GqlError) error {
|
||||
if len(err) > 0 {
|
||||
errMsg, marshalErr := json.Marshal(err)
|
||||
if marshalErr != nil {
|
||||
return marshalErr
|
||||
}
|
||||
return errors.New(string(errMsg))
|
||||
}
|
||||
return nil
|
||||
}
|
132
client_test.go
Normal file
132
client_test.go
Normal file
@ -0,0 +1,132 @@
|
||||
package sn_test
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
sn "github.com/ekzyis/snappy"
|
||||
)
|
||||
|
||||
var (
|
||||
c = testClient()
|
||||
)
|
||||
|
||||
func TestQueryItems(t *testing.T) {
|
||||
var (
|
||||
cursor *sn.ItemsCursor
|
||||
err error
|
||||
)
|
||||
|
||||
if cursor, err = c.Items(nil); err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
if len(cursor.Items) == 0 {
|
||||
t.Error("items cursor empty")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func TestMutationCreateComment(t *testing.T) {
|
||||
var (
|
||||
parentId = 349
|
||||
text = "test comment"
|
||||
err error
|
||||
)
|
||||
|
||||
// TODO: return result, invoice, paymentMethod from CreateComment and run assertions on that
|
||||
if _, err = c.CreateComment(parentId, text); err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func TestMutationPostDiscussion(t *testing.T) {
|
||||
var (
|
||||
title = "test discussion"
|
||||
text = "test discussion text"
|
||||
sub = "bitcoin"
|
||||
err error
|
||||
)
|
||||
|
||||
// TODO: return result, invoice, paymentMethod from CreateComment and run assertions on that
|
||||
if _, err = c.PostDiscussion(title, text, sub); err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func TestMutationPostLink(t *testing.T) {
|
||||
var (
|
||||
url = "https://stacker.news"
|
||||
title = "test discussion"
|
||||
text = "test discussion text"
|
||||
sub = "bitcoin"
|
||||
err error
|
||||
)
|
||||
|
||||
// TODO: return result, invoice, paymentMethod from CreateComment and run assertions on that
|
||||
if _, err = c.PostLink(url, title, text, sub); err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func testClient() *sn.Client {
|
||||
loadEnv()
|
||||
|
||||
baseUrl, set := os.LookupEnv("TEST_SN_BASE_URL")
|
||||
if !set {
|
||||
baseUrl = "http://localhost:3000"
|
||||
}
|
||||
log.Printf("baseUrl=%s\n", baseUrl)
|
||||
|
||||
apiKey, set := os.LookupEnv("TEST_SN_API_KEY")
|
||||
if !set {
|
||||
log.Fatalf("TEST_SN_API_KEY is not set")
|
||||
}
|
||||
log.Printf("apiKey=%s\n", apiKey)
|
||||
|
||||
return sn.NewClient(
|
||||
sn.WithBaseUrl(baseUrl),
|
||||
sn.WithApiKey(apiKey),
|
||||
)
|
||||
}
|
||||
|
||||
func loadEnv() {
|
||||
var (
|
||||
f *os.File
|
||||
s *bufio.Scanner
|
||||
err error
|
||||
)
|
||||
|
||||
if f, err = os.Open(".env"); err != nil {
|
||||
log.Fatalf("error opening .env: %v", err)
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
s = bufio.NewScanner(f)
|
||||
s.Split(bufio.ScanLines)
|
||||
for s.Scan() {
|
||||
line := s.Text()
|
||||
parts := strings.SplitN(line, "=", 2)
|
||||
|
||||
// Check if we have exactly 2 parts (key and value)
|
||||
if len(parts) == 2 {
|
||||
os.Setenv(parts[0], parts[1])
|
||||
} else {
|
||||
log.Fatalf(".env: invalid line: %s\n", line)
|
||||
}
|
||||
}
|
||||
|
||||
// Check for errors during scanning
|
||||
if err = s.Err(); err != nil {
|
||||
fmt.Println("error scanning .env:", err)
|
||||
}
|
||||
|
||||
}
|
47
dupes.go
47
dupes.go
@ -1,47 +0,0 @@
|
||||
package sn
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// Fetch dupes
|
||||
func Dupes(url string) (*[]Dupe, error) {
|
||||
body := GraphQLPayload{
|
||||
Query: `
|
||||
query Dupes($url: String!) {
|
||||
dupes(url: $url) {
|
||||
id
|
||||
url
|
||||
title
|
||||
user {
|
||||
name
|
||||
}
|
||||
createdAt
|
||||
sats
|
||||
ncomments
|
||||
}
|
||||
}`,
|
||||
Variables: map[string]interface{}{
|
||||
"url": url,
|
||||
},
|
||||
}
|
||||
resp, err := MakeStackerNewsRequest(body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
var respBody DupesResponse
|
||||
err = json.NewDecoder(resp.Body).Decode(&respBody)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("error decoding SN dupes: %w", err)
|
||||
return nil, err
|
||||
}
|
||||
err = CheckForErrors(respBody.Errors)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &respBody.Data.Dupes, nil
|
||||
}
|
7
go.mod
7
go.mod
@ -1,8 +1,5 @@
|
||||
module github.com/ekzyis/sn-goapi
|
||||
module github.com/ekzyis/snappy
|
||||
|
||||
go 1.20
|
||||
|
||||
require (
|
||||
github.com/joho/godotenv v1.5.1 // indirect
|
||||
github.com/namsral/flag v1.7.4-pre // indirect
|
||||
)
|
||||
require gopkg.in/guregu/null.v4 v4.0.0 // indirect
|
||||
|
6
go.sum
6
go.sum
@ -1,4 +1,2 @@
|
||||
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
|
||||
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
|
||||
github.com/namsral/flag v1.7.4-pre h1:b2ScHhoCUkbsq0d2C15Mv+VU8bl8hAXV8arnWiOHNZs=
|
||||
github.com/namsral/flag v1.7.4-pre/go.mod h1:OXldTctbM6SWH1K899kPZcf65KxJiD7MsceFUpB5yDo=
|
||||
gopkg.in/guregu/null.v4 v4.0.0 h1:1Wm3S1WEA2I26Kq+6vcW+w0gcDo44YKYD7YIEJNHDjg=
|
||||
gopkg.in/guregu/null.v4 v4.0.0/go.mod h1:YoQhUrADuG3i9WqesrCmpNRwm1ypAgSHYqoOcTu/JrI=
|
||||
|
97
invoice.go
Normal file
97
invoice.go
Normal file
@ -0,0 +1,97 @@
|
||||
package sn
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Invoice struct {
|
||||
Id int `json:"id,string"`
|
||||
Hash string `json:"hash"`
|
||||
Hmac string `json:"hmac"`
|
||||
Bolt11 string `json:"bolt11"`
|
||||
SatsRequested int `json:"satsRequested"`
|
||||
SatsReceived int `json:"satsReceived"`
|
||||
Cancelled bool `json:"cancelled"`
|
||||
ConfirmedAt time.Time `json:"createdAt"`
|
||||
ExpiresAt time.Time `json:"expiresAt"`
|
||||
Nostr map[string]interface{} `json:"nostr"`
|
||||
IsHeld bool `json:"isHeld"`
|
||||
Comment string `json:"comment"`
|
||||
Lud18Data map[string]interface{} `json:"lud18Data"`
|
||||
ConfirmedPreimage string `json:"confirmedPreimage"`
|
||||
ActionState string `json:"actionState"`
|
||||
ActionType string `json:"actionType"`
|
||||
}
|
||||
|
||||
type PaymentMethod string
|
||||
|
||||
const (
|
||||
PaymentMethodFeeCredits PaymentMethod = "FEE_CREDIT"
|
||||
PaymentMethodOptimistic PaymentMethod = "OPTIMISTIC"
|
||||
PaymentMethodPessimistic PaymentMethod = "PESSIMISTIC"
|
||||
)
|
||||
|
||||
type CreateInvoiceArgs struct {
|
||||
Amount int
|
||||
ExpireSecs int
|
||||
HodlInvoice bool
|
||||
}
|
||||
|
||||
type CreateInvoiceResponse struct {
|
||||
Errors []GqlError `json:"errors"`
|
||||
Data struct {
|
||||
CreateInvoice Invoice `json:"createInvoice"`
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
func (c *Client) CreateInvoice(args *CreateInvoiceArgs) (*Invoice, error) {
|
||||
if args == nil {
|
||||
args = &CreateInvoiceArgs{}
|
||||
}
|
||||
|
||||
body := GqlBody{
|
||||
// TODO: add createdAt
|
||||
// when I wrote this code, createdAt returned null but is non-nullable
|
||||
// so I had to remove it.
|
||||
Query: `
|
||||
mutation createInvoice($amount: Int!, $expireSecs: Int, $hodlInvoice: Boolean) {
|
||||
createInvoice(amount: $amount, expireSecs: $expireSecs, hodlInvoice: $hodlInvoice) {
|
||||
id
|
||||
hash
|
||||
hmac
|
||||
bolt11
|
||||
satsRequested
|
||||
satsReceived
|
||||
isHeld
|
||||
comment
|
||||
confirmedPreimage
|
||||
expiresAt
|
||||
confirmedAt
|
||||
}
|
||||
}`,
|
||||
Variables: map[string]interface{}{
|
||||
"amount": args.Amount,
|
||||
},
|
||||
}
|
||||
|
||||
resp, err := c.callApi(body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
var respBody CreateInvoiceResponse
|
||||
err = json.NewDecoder(resp.Body).Decode(&respBody)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("error decoding items: %w", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
err = c.checkForErrors(respBody.Errors)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &respBody.Data.CreateInvoice, nil
|
||||
}
|
418
items.go
418
items.go
@ -3,66 +3,189 @@ package sn
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"gopkg.in/guregu/null.v4"
|
||||
)
|
||||
|
||||
func Items(query *ItemsQuery) (*ItemsCursor, error) {
|
||||
type Item struct {
|
||||
Id int `json:"id,string"`
|
||||
ParentId int `json:"parentId"`
|
||||
Title string `json:"title"`
|
||||
Url string `json:"url"`
|
||||
Text string `json:"text"`
|
||||
Sats int `json:"sats"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
DeletedAt null.Time `json:"deletedAt"`
|
||||
Comments []Comment `json:"comments"`
|
||||
NComments int `json:"ncomments"`
|
||||
User User `json:"user"`
|
||||
}
|
||||
|
||||
type Comment struct {
|
||||
Id int `json:"id,string"`
|
||||
ParentId int `json:"parentId"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
Text string `json:"text"`
|
||||
User User `json:"user"`
|
||||
Comments []Comment `json:"comments"`
|
||||
}
|
||||
|
||||
type ItemsQuery struct {
|
||||
Sub string
|
||||
Sort string
|
||||
Type string
|
||||
Cursor string
|
||||
Name string
|
||||
When string
|
||||
By string
|
||||
Limit int
|
||||
}
|
||||
|
||||
type ItemsCursor struct {
|
||||
Items []Item `json:"items"`
|
||||
Cursor string `json:"cursor"`
|
||||
}
|
||||
|
||||
type ItemResponse struct {
|
||||
Errors []GqlError `json:"errors"`
|
||||
Data struct {
|
||||
Item Item `json:"item"`
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
type ItemsResponse struct {
|
||||
Errors []GqlError `json:"errors"`
|
||||
Data struct {
|
||||
Items ItemsCursor `json:"items"`
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
type ItemPaidAction struct {
|
||||
Result Item `json:"result"`
|
||||
Invoice Invoice `json:"invoice"`
|
||||
PaymentMethod PaymentMethod `json:"paymentMethod"`
|
||||
}
|
||||
|
||||
type UpsertDiscussionResponse struct {
|
||||
Errors []GqlError `json:"errors"`
|
||||
Data struct {
|
||||
UpsertDiscussion ItemPaidAction `json:"upsertDiscussion"`
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
type UpsertLinkResponse struct {
|
||||
Errors []GqlError `json:"errors"`
|
||||
Data struct {
|
||||
UpsertLink ItemPaidAction `json:"upsertLink"`
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
type UpsertCommentResponse struct {
|
||||
Errors []GqlError `json:"errors"`
|
||||
Data struct {
|
||||
UpsertComment ItemPaidAction `json:"upsertComment"`
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
type Dupe struct {
|
||||
Id int `json:"id,string"`
|
||||
Url string `json:"url"`
|
||||
Title string `json:"title"`
|
||||
User User `json:"user"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
Sats int `json:"sats"`
|
||||
NComments int `json:"ncomments"`
|
||||
}
|
||||
|
||||
type DupesResponse struct {
|
||||
Errors []GqlError `json:"errors"`
|
||||
Data struct {
|
||||
Dupes []Dupe `json:"dupes"`
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
type DupesError struct {
|
||||
Url string
|
||||
Dupes []Dupe
|
||||
}
|
||||
|
||||
func (e *DupesError) Error() string {
|
||||
return fmt.Sprintf("found %d dupes for %s", len(e.Dupes), e.Url)
|
||||
}
|
||||
|
||||
func (c *Client) Item(id int) (*Item, error) {
|
||||
body := GqlBody{
|
||||
Query: `
|
||||
query item($id: ID!) {
|
||||
item(id: $id) {
|
||||
id
|
||||
parentId
|
||||
title
|
||||
url
|
||||
text
|
||||
sats
|
||||
createdAt
|
||||
deletedAt
|
||||
ncomments
|
||||
user {
|
||||
id
|
||||
name
|
||||
}
|
||||
}
|
||||
}`,
|
||||
Variables: map[string]interface{}{
|
||||
"id": id,
|
||||
},
|
||||
}
|
||||
|
||||
resp, err := c.callApi(body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
var respBody ItemResponse
|
||||
err = json.NewDecoder(resp.Body).Decode(&respBody)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("error decoding item: %w", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
err = c.checkForErrors(respBody.Errors)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &respBody.Data.Item, nil
|
||||
}
|
||||
|
||||
func (c *Client) Items(query *ItemsQuery) (*ItemsCursor, error) {
|
||||
if query == nil {
|
||||
query = &ItemsQuery{}
|
||||
}
|
||||
|
||||
if sub := query.Sub; sub != "" {
|
||||
if !(sub == "bitcoin" || sub == "nostr" || sub == "tech" || sub == "meta") {
|
||||
return nil, fmt.Errorf("invalid sub: %s", sub)
|
||||
}
|
||||
}
|
||||
|
||||
body := GraphQLPayload{
|
||||
body := GqlBody{
|
||||
Query: `
|
||||
query items($sub: String, $sort: String, $cursor: String, $type: String, $name: String, $when: String, $by: String, $limit: Limit) {
|
||||
items(sub: $sub, sort: $sort, cursor: $cursor, type: $type, name: $name, when: $when, by: $by, limit: $limit) {
|
||||
cursor
|
||||
items {
|
||||
query items($sub: String, $sort: String, $cursor: String, $type: String, $name: String, $when: String, $by: String, $limit: Limit) {
|
||||
items(sub: $sub, sort: $sort, cursor: $cursor, type: $type, name: $name, when: $when, by: $by, limit: $limit) {
|
||||
cursor
|
||||
items {
|
||||
id
|
||||
parentId
|
||||
title
|
||||
url
|
||||
text
|
||||
sats
|
||||
createdAt
|
||||
deletedAt
|
||||
ncomments
|
||||
user {
|
||||
id
|
||||
parentId
|
||||
createdAt
|
||||
deletedAt
|
||||
title
|
||||
url
|
||||
user {
|
||||
id
|
||||
name
|
||||
}
|
||||
otsHash
|
||||
position
|
||||
sats
|
||||
boost
|
||||
bounty
|
||||
bountyPaidTo
|
||||
path
|
||||
upvotes
|
||||
meSats
|
||||
meDontLike
|
||||
meBookmark
|
||||
meSubscription
|
||||
outlawed
|
||||
freebie
|
||||
ncomments
|
||||
commentSats
|
||||
lastCommentAt
|
||||
maxBid
|
||||
isJob
|
||||
company
|
||||
location
|
||||
remote
|
||||
subName
|
||||
pollCost
|
||||
status
|
||||
uploadId
|
||||
mine
|
||||
position
|
||||
},
|
||||
}
|
||||
}`,
|
||||
name
|
||||
}
|
||||
},
|
||||
}
|
||||
}`,
|
||||
Variables: map[string]interface{}{
|
||||
"sub": query.Sub,
|
||||
"sort": query.Sort,
|
||||
@ -78,7 +201,7 @@ func Items(query *ItemsQuery) (*ItemsCursor, error) {
|
||||
body.Variables["limit"] = 21
|
||||
}
|
||||
|
||||
resp, err := MakeStackerNewsRequest(body)
|
||||
resp, err := c.callApi(body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@ -90,29 +213,92 @@ func Items(query *ItemsQuery) (*ItemsCursor, error) {
|
||||
err = fmt.Errorf("error decoding items: %w", err)
|
||||
return nil, err
|
||||
}
|
||||
err = CheckForErrors(respBody.Errors)
|
||||
|
||||
err = c.checkForErrors(respBody.Errors)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &respBody.Data.Items, nil
|
||||
}
|
||||
|
||||
// Create a new LINK post
|
||||
func PostLink(url string, title string, sub string) (int, error) {
|
||||
body := GraphQLPayload{
|
||||
func (c *Client) PostDiscussion(title string, text string, sub string) (int, error) {
|
||||
body := GqlBody{
|
||||
Query: `
|
||||
mutation upsertLink($url: String!, $title: String!, $sub: String!) {
|
||||
upsertLink(url: $url, title: $title, sub: $sub) {
|
||||
id
|
||||
}
|
||||
}`,
|
||||
mutation upsertDiscussion($title: String!, $text: String, $sub: String) {
|
||||
upsertDiscussion(title: $title, text: $text, sub: $sub) {
|
||||
result {
|
||||
id
|
||||
}
|
||||
invoice {
|
||||
id
|
||||
hash
|
||||
bolt11
|
||||
satsRequested
|
||||
expiresAt
|
||||
}
|
||||
paymentMethod
|
||||
}
|
||||
}`,
|
||||
Variables: map[string]interface{}{
|
||||
"url": url,
|
||||
"title": title,
|
||||
"text": text,
|
||||
"sub": sub,
|
||||
},
|
||||
}
|
||||
resp, err := MakeStackerNewsRequest(body)
|
||||
|
||||
resp, err := c.callApi(body)
|
||||
if err != nil {
|
||||
return -1, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
var respBody UpsertDiscussionResponse
|
||||
err = json.NewDecoder(resp.Body).Decode(&respBody)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("error decoding upsertDiscussion: %w", err)
|
||||
return -1, err
|
||||
}
|
||||
|
||||
err = c.checkForErrors(respBody.Errors)
|
||||
if err != nil {
|
||||
return -1, err
|
||||
}
|
||||
|
||||
inv := respBody.Data.UpsertDiscussion.Invoice
|
||||
if inv.Id != 0 {
|
||||
return -1, fmt.Errorf("mutation requires %d sats as payment", inv.SatsRequested)
|
||||
}
|
||||
|
||||
return respBody.Data.UpsertDiscussion.Result.Id, nil
|
||||
}
|
||||
|
||||
func (c *Client) PostLink(url string, title string, text string, sub string) (int, error) {
|
||||
body := GqlBody{
|
||||
Query: `
|
||||
mutation upsertLink($url: String!, $title: String!, $text: String, $sub: String!) {
|
||||
upsertLink(url: $url, title: $title, text: $text, sub: $sub) {
|
||||
result {
|
||||
id
|
||||
}
|
||||
invoice {
|
||||
id
|
||||
hash
|
||||
bolt11
|
||||
satsRequested
|
||||
expiresAt
|
||||
}
|
||||
paymentMethod
|
||||
}
|
||||
}`,
|
||||
Variables: map[string]interface{}{
|
||||
"url": url,
|
||||
"title": title,
|
||||
"text": text,
|
||||
"sub": sub,
|
||||
},
|
||||
}
|
||||
|
||||
resp, err := c.callApi(body)
|
||||
if err != nil {
|
||||
return -1, err
|
||||
}
|
||||
@ -121,47 +307,119 @@ func PostLink(url string, title string, sub string) (int, error) {
|
||||
var respBody UpsertLinkResponse
|
||||
err = json.NewDecoder(resp.Body).Decode(&respBody)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("error decoding SN upsertLink: %w", err)
|
||||
err = fmt.Errorf("error decoding upsertLink: %w", err)
|
||||
return -1, err
|
||||
}
|
||||
err = CheckForErrors(respBody.Errors)
|
||||
|
||||
err = c.checkForErrors(respBody.Errors)
|
||||
if err != nil {
|
||||
return -1, err
|
||||
}
|
||||
itemId := respBody.Data.UpsertLink.Id
|
||||
return itemId, nil
|
||||
|
||||
inv := respBody.Data.UpsertLink.Invoice
|
||||
if inv.Id != 0 {
|
||||
return -1, fmt.Errorf("mutation requires %d sats as payment", inv.SatsRequested)
|
||||
}
|
||||
|
||||
return respBody.Data.UpsertLink.Result.Id, nil
|
||||
}
|
||||
|
||||
// Create a new comment
|
||||
func CreateComment(parentId int, text string) (int, error) {
|
||||
body := GraphQLPayload{
|
||||
func (c *Client) CreateComment(parentId int, text string) (int, error) {
|
||||
body := GqlBody{
|
||||
Query: `
|
||||
mutation upsertComment($text: String!, $parentId: ID!) {
|
||||
upsertComment(text: $text, parentId: $parentId) {
|
||||
mutation upsertComment($parentId: ID!, $text: String!) {
|
||||
upsertComment(parentId: $parentId, text: $text) {
|
||||
result {
|
||||
id
|
||||
}
|
||||
}`,
|
||||
invoice {
|
||||
id
|
||||
hash
|
||||
bolt11
|
||||
satsRequested
|
||||
expiresAt
|
||||
}
|
||||
paymentMethod
|
||||
}
|
||||
}`,
|
||||
Variables: map[string]interface{}{
|
||||
"text": text,
|
||||
"parentId": parentId,
|
||||
"text": text,
|
||||
},
|
||||
}
|
||||
resp, err := MakeStackerNewsRequest(body)
|
||||
|
||||
resp, err := c.callApi(body)
|
||||
if err != nil {
|
||||
return -1, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
var respBody CreateCommentsResponse
|
||||
var respBody UpsertCommentResponse
|
||||
err = json.NewDecoder(resp.Body).Decode(&respBody)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("error decoding SN createComment: %w", err)
|
||||
err = fmt.Errorf("error decoding upsertComment: %w", err)
|
||||
return -1, err
|
||||
}
|
||||
err = CheckForErrors(respBody.Errors)
|
||||
|
||||
err = c.checkForErrors(respBody.Errors)
|
||||
if err != nil {
|
||||
return -1, err
|
||||
}
|
||||
|
||||
return parentId, nil
|
||||
inv := respBody.Data.UpsertComment.Invoice
|
||||
if inv.Id != 0 {
|
||||
return -1, fmt.Errorf("mutation requires %d sats as payment", inv.SatsRequested)
|
||||
}
|
||||
|
||||
return respBody.Data.UpsertComment.Result.Id, nil
|
||||
}
|
||||
|
||||
func (c *Client) Dupes(url string) (*[]Dupe, error) {
|
||||
body := GqlBody{
|
||||
Query: `
|
||||
query Dupes($url: String!) {
|
||||
dupes(url: $url) {
|
||||
id
|
||||
url
|
||||
title
|
||||
user {
|
||||
name
|
||||
}
|
||||
createdAt
|
||||
sats
|
||||
ncomments
|
||||
}
|
||||
}`,
|
||||
Variables: map[string]interface{}{
|
||||
"url": url,
|
||||
},
|
||||
}
|
||||
resp, err := c.callApi(body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
var respBody DupesResponse
|
||||
err = json.NewDecoder(resp.Body).Decode(&respBody)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("error decoding dupes: %w", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
err = c.checkForErrors(respBody.Errors)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &respBody.Data.Dupes, nil
|
||||
}
|
||||
|
||||
func (c *Client) HasDupes(url string) (bool, error) {
|
||||
dupes, err := c.Dupes(url)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
return len(*dupes) > 0, nil
|
||||
}
|
||||
|
81
main.go
81
main.go
@ -1,81 +0,0 @@
|
||||
// Package for stacker.news API access
|
||||
package sn
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"github.com/joho/godotenv"
|
||||
"github.com/namsral/flag"
|
||||
)
|
||||
|
||||
var (
|
||||
// stacker.news URL
|
||||
SnUrl = "https://stacker.news"
|
||||
// stacker.news API URL
|
||||
SnApiUrl = "https://stacker.news/api/graphql"
|
||||
// stacker.news session cookie
|
||||
SnAuthCookie string
|
||||
// TODO add API key support
|
||||
// SnApiKey string
|
||||
)
|
||||
|
||||
func init() {
|
||||
err := godotenv.Load()
|
||||
if err != nil {
|
||||
log.Fatal("error loading .env file")
|
||||
}
|
||||
flag.StringVar(&SnAuthCookie, "SN_AUTH_COOKIE", "", "Cookie required for authentication requests to stacker.news/api/graphql")
|
||||
flag.Parse()
|
||||
if SnAuthCookie == "" {
|
||||
log.Fatal("SN_AUTH_COOKIE not set")
|
||||
}
|
||||
}
|
||||
|
||||
// Make GraphQL request using raw payload
|
||||
func MakeStackerNewsRequest(body GraphQLPayload) (*http.Response, error) {
|
||||
bodyJSON, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("error encoding SN payload: %w", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
req, err := http.NewRequest("POST", SnApiUrl, bytes.NewBuffer(bodyJSON))
|
||||
if err != nil {
|
||||
err = fmt.Errorf("error preparing SN request: %w", err)
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
req.Header.Set("Cookie", SnAuthCookie)
|
||||
|
||||
client := http.DefaultClient
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("error posting SN payload: %w", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// Returns error if any error was found
|
||||
func CheckForErrors(graphqlErrors []GraphQLError) error {
|
||||
if len(graphqlErrors) > 0 {
|
||||
errorMsg, marshalErr := json.Marshal(graphqlErrors)
|
||||
if marshalErr != nil {
|
||||
return marshalErr
|
||||
}
|
||||
return errors.New(string(errorMsg))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Format item id as link
|
||||
func FormatLink(id int) string {
|
||||
return fmt.Sprintf("%s/items/%d", SnUrl, id)
|
||||
}
|
34
notes.go
34
notes.go
@ -1,34 +0,0 @@
|
||||
package sn
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// Check for new notifications
|
||||
func CheckNotifications() (bool, error) {
|
||||
body := GraphQLPayload{
|
||||
Query: `
|
||||
{
|
||||
hasNewNotes
|
||||
}`,
|
||||
}
|
||||
resp, err := MakeStackerNewsRequest(body)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
var respBody HasNewNotesResponse
|
||||
err = json.NewDecoder(resp.Body).Decode(&respBody)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("error decoding SN hasNewNotes: %w", err)
|
||||
return false, err
|
||||
}
|
||||
err = CheckForErrors(respBody.Errors)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
return respBody.Data.HasNewNotes, nil
|
||||
}
|
125
notifications.go
Normal file
125
notifications.go
Normal file
@ -0,0 +1,125 @@
|
||||
package sn
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Notification struct {
|
||||
Id int `json:"id,string"`
|
||||
Type string `json:"__typename"`
|
||||
Item Item `json:"item"`
|
||||
}
|
||||
|
||||
type NotificationsCursor struct {
|
||||
LastChecked time.Time `json:"lastChecked"`
|
||||
Cursor string `json:"cursor"`
|
||||
Notifications []Notification `json:"notifications"`
|
||||
}
|
||||
|
||||
type NotificationsResponse struct {
|
||||
Errors []GqlError `json:"errors"`
|
||||
Data struct {
|
||||
Notifications NotificationsCursor `json:"notifications"`
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
func (c *Client) Notifications() (*NotificationsCursor, error) {
|
||||
body := GqlBody{
|
||||
Query: `
|
||||
fragment ItemFields on Item {
|
||||
id
|
||||
user {
|
||||
id
|
||||
name
|
||||
}
|
||||
parentId
|
||||
createdAt
|
||||
deletedAt
|
||||
title
|
||||
text
|
||||
}
|
||||
query notifications {
|
||||
notifications {
|
||||
lastChecked
|
||||
cursor
|
||||
notifications {
|
||||
__typename
|
||||
... on Reply {
|
||||
id
|
||||
item {
|
||||
...ItemFields
|
||||
}
|
||||
}
|
||||
... on Mention {
|
||||
id
|
||||
item {
|
||||
...ItemFields
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`,
|
||||
Variables: map[string]interface{}{},
|
||||
}
|
||||
|
||||
resp, err := c.callApi(body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
var respBody NotificationsResponse
|
||||
err = json.NewDecoder(resp.Body).Decode(&respBody)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("error decoding notifications: %w", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
err = c.checkForErrors(respBody.Errors)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &respBody.Data.Notifications, nil
|
||||
}
|
||||
|
||||
func (c *Client) Mentions() ([]Notification, error) {
|
||||
return c.filterNotifications(
|
||||
func(n Notification) bool {
|
||||
return n.Type == "Mention"
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
func (c *Client) Replies() ([]Notification, error) {
|
||||
return c.filterNotifications(
|
||||
func(n Notification) bool {
|
||||
return n.Type == "Reply"
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
func (c *Client) filterNotifications(f func(Notification) bool) ([]Notification, error) {
|
||||
var (
|
||||
n *NotificationsCursor
|
||||
err error
|
||||
)
|
||||
|
||||
if n, err = c.Notifications(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return filter(n.Notifications, f), nil
|
||||
}
|
||||
|
||||
func filter[T any](s []T, f func(T) bool) []T {
|
||||
var r []T
|
||||
for _, v := range s {
|
||||
if f(v) {
|
||||
r = append(r, v)
|
||||
}
|
||||
}
|
||||
return r
|
||||
}
|
39
rss.go
39
rss.go
@ -8,6 +8,35 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
type RssItem struct {
|
||||
Guid string `xml:"guid"`
|
||||
Title string `xml:"title"`
|
||||
Link string `xml:"link"`
|
||||
Description string `xml:"description"`
|
||||
PubDate RssDate `xml:"pubDate"`
|
||||
Author RssAuthor `xml:"author"`
|
||||
}
|
||||
|
||||
type RssChannel struct {
|
||||
Title string `xml:"title"`
|
||||
Description string `xml:"description"`
|
||||
Link string `xml:"link"`
|
||||
Items []RssItem `xml:"item"`
|
||||
LastBuildDate RssDate `xml:"lastBuildDate"`
|
||||
}
|
||||
|
||||
type Rss struct {
|
||||
Channel RssChannel `xml:"channel"`
|
||||
}
|
||||
|
||||
type RssDate struct {
|
||||
time.Time
|
||||
}
|
||||
|
||||
type RssAuthor struct {
|
||||
Name string `xml:"name"`
|
||||
}
|
||||
|
||||
func (c *RssDate) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
|
||||
var v string
|
||||
dateFormat := "Mon, 02 Jan 2006 15:04:05 GMT"
|
||||
@ -20,13 +49,9 @@ func (c *RssDate) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
var (
|
||||
StackerNewsRssFeedUrl = "https://stacker.news/rss"
|
||||
)
|
||||
|
||||
// Fetch RSS feed
|
||||
func RssFeed() (*Rss, error) {
|
||||
resp, err := http.Get(StackerNewsRssFeedUrl)
|
||||
func (c *Client) GetRssFeed() (*Rss, error) {
|
||||
url := fmt.Sprintf("%s/rss", c.BaseUrl)
|
||||
resp, err := http.Get(url)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("error fetching RSS feed: %w", err)
|
||||
log.Println(err)
|
||||
|
23
session.go
23
session.go
@ -1,23 +0,0 @@
|
||||
package sn
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
func RefreshSession() error {
|
||||
req, err := http.NewRequest("GET", SnUrl+"/api/auth/session", nil)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("error preparing SN request: %w", err)
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Cookie", SnAuthCookie)
|
||||
|
||||
client := http.DefaultClient
|
||||
_, err = client.Do(req)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("error refreshing SN session: %w", err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
140
types.go
140
types.go
@ -1,140 +0,0 @@
|
||||
package sn
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
type GraphQLPayload struct {
|
||||
Query string `json:"query"`
|
||||
Variables map[string]interface{} `json:"variables,omitempty"`
|
||||
}
|
||||
|
||||
type GraphQLError struct {
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
type User struct {
|
||||
Id int `json:"id,string"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
type Comment struct {
|
||||
Id int `json:"id,string"`
|
||||
ParentId int `json:"parentId,string"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
Text string `json:"text"`
|
||||
User User `json:"user"`
|
||||
Comments []Comment `json:"comments"`
|
||||
}
|
||||
|
||||
type CreateCommentsResponse struct {
|
||||
Errors []GraphQLError `json:"errors"`
|
||||
Data struct {
|
||||
CreateComment Comment `json:"createComment"`
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
type Item struct {
|
||||
Id int `json:"id,string"`
|
||||
ParentId int `json:"parentId,string"`
|
||||
Title string `json:"title"`
|
||||
Url string `json:"url"`
|
||||
Sats int `json:"sats"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
Comments []Comment `json:"comments"`
|
||||
NComments int `json:"ncomments"`
|
||||
User User `json:"user"`
|
||||
}
|
||||
|
||||
type UpsertLinkResponse struct {
|
||||
Errors []GraphQLError `json:"errors"`
|
||||
Data struct {
|
||||
UpsertLink Item `json:"upsertLink"`
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
type ItemsResponse struct {
|
||||
Errors []GraphQLError `json:"errors"`
|
||||
Data struct {
|
||||
Items ItemsCursor `json:"items"`
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
type ItemsCursor struct {
|
||||
Items []Item `json:"items"`
|
||||
Cursor string `json:"cursor"`
|
||||
}
|
||||
|
||||
type HasNewNotesResponse struct {
|
||||
Errors []GraphQLError `json:"errors"`
|
||||
Data struct {
|
||||
HasNewNotes bool `json:"hasNewNotes"`
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
type Dupe struct {
|
||||
Id int `json:"id,string"`
|
||||
Url string `json:"url"`
|
||||
Title string `json:"title"`
|
||||
User User `json:"user"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
Sats int `json:"sats"`
|
||||
NComments int `json:"ncomments"`
|
||||
}
|
||||
|
||||
type DupesResponse struct {
|
||||
Errors []GraphQLError `json:"errors"`
|
||||
Data struct {
|
||||
Dupes []Dupe `json:"dupes"`
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
type DupesError struct {
|
||||
Url string
|
||||
Dupes []Dupe
|
||||
}
|
||||
|
||||
func (e *DupesError) Error() string {
|
||||
return fmt.Sprintf("found %d dupes for %s", len(e.Dupes), e.Url)
|
||||
}
|
||||
|
||||
type RssItem struct {
|
||||
Guid string `xml:"guid"`
|
||||
Title string `xml:"title"`
|
||||
Link string `xml:"link"`
|
||||
Description string `xml:"description"`
|
||||
PubDate RssDate `xml:"pubDate"`
|
||||
Author RssAuthor `xml:"author"`
|
||||
}
|
||||
|
||||
type RssChannel struct {
|
||||
Title string `xml:"title"`
|
||||
Description string `xml:"description"`
|
||||
Link string `xml:"link"`
|
||||
Items []RssItem `xml:"item"`
|
||||
LastBuildDate RssDate `xml:"lastBuildDate"`
|
||||
}
|
||||
|
||||
type Rss struct {
|
||||
Channel RssChannel `xml:"channel"`
|
||||
}
|
||||
|
||||
type RssDate struct {
|
||||
time.Time
|
||||
}
|
||||
|
||||
type RssAuthor struct {
|
||||
Name string `xml:"name"`
|
||||
}
|
||||
|
||||
type ItemsQuery struct {
|
||||
Sub string
|
||||
Sort string
|
||||
Type string
|
||||
Cursor string
|
||||
Name string
|
||||
When string
|
||||
By string
|
||||
Limit int
|
||||
}
|
131
upload.go
Normal file
131
upload.go
Normal file
@ -0,0 +1,131 @@
|
||||
package sn
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"image"
|
||||
"image/png"
|
||||
"io"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type GetSignedPOST struct {
|
||||
Url string `json:"url"`
|
||||
Fields map[string]string `json:"fields"`
|
||||
}
|
||||
|
||||
type GetSignedPOSTResponse struct {
|
||||
Errors []GqlError `json:"errors"`
|
||||
Data struct {
|
||||
GetSignedPOST GetSignedPOST `json:"getSignedPOST"`
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
func (c *Client) UploadImage(img *image.RGBA) (string, error) {
|
||||
var (
|
||||
b = img.Bounds()
|
||||
width = b.Dx()
|
||||
height = b.Dy()
|
||||
type_ = "image/png"
|
||||
size int
|
||||
)
|
||||
|
||||
var imgBuf bytes.Buffer
|
||||
if err := png.Encode(&imgBuf, img); err != nil {
|
||||
return "", err
|
||||
}
|
||||
size = imgBuf.Len()
|
||||
|
||||
// get signed URL for S3 upload
|
||||
body := GqlBody{
|
||||
Query: `
|
||||
mutation getSignedPOST($type: String!, $size: Int!, $width: Int!, $height: Int!, $avatar: Boolean) {
|
||||
getSignedPOST(type: $type, size: $size, width: $width, height: $height, avatar: $avatar) {
|
||||
url
|
||||
fields
|
||||
}
|
||||
}`,
|
||||
Variables: map[string]interface{}{
|
||||
"type": type_,
|
||||
"size": size,
|
||||
"width": width,
|
||||
"height": height,
|
||||
"avatar": false,
|
||||
},
|
||||
}
|
||||
|
||||
resp, err := c.callApi(body)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
var respBody GetSignedPOSTResponse
|
||||
err = json.NewDecoder(resp.Body).Decode(&respBody)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("error decoding getSignedPOST: %w", err)
|
||||
return "", err
|
||||
}
|
||||
|
||||
err = c.checkForErrors(respBody.Errors)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
s3Url := respBody.Data.GetSignedPOST.Url
|
||||
fields := respBody.Data.GetSignedPOST.Fields
|
||||
|
||||
// create multipart form
|
||||
var (
|
||||
buf bytes.Buffer
|
||||
w = multipart.NewWriter(&buf)
|
||||
fw io.Writer
|
||||
)
|
||||
|
||||
for k, v := range fields {
|
||||
if fw, err = w.CreateFormField(k); err != nil {
|
||||
return "", err
|
||||
}
|
||||
fw.Write([]byte(v))
|
||||
}
|
||||
|
||||
for k, v := range map[string]string{
|
||||
"Content-Type": type_,
|
||||
"Cache-Control": "max-age=31536000",
|
||||
"acl": "public-read",
|
||||
} {
|
||||
if fw, err = w.CreateFormField(k); err != nil {
|
||||
return "", err
|
||||
}
|
||||
fw.Write([]byte(v))
|
||||
}
|
||||
|
||||
if fw, err = w.CreateFormFile("file", "image.png"); err != nil {
|
||||
return "", err
|
||||
}
|
||||
fw.Write(imgBuf.Bytes())
|
||||
|
||||
if err = w.Close(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// upload to S3
|
||||
var req *http.Request
|
||||
if req, err = http.NewRequest("POST", s3Url, &buf); err != nil {
|
||||
return "", err
|
||||
}
|
||||
req.Header.Set("Content-Type", w.FormDataContentType())
|
||||
|
||||
client := http.DefaultClient
|
||||
if resp, err = client.Do(req); err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
imgId := respBody.Data.GetSignedPOST.Fields["key"]
|
||||
imgUrl := fmt.Sprintf("%s/%s", c.MediaUrl, imgId)
|
||||
|
||||
return imgUrl, nil
|
||||
}
|
57
user.go
Normal file
57
user.go
Normal file
@ -0,0 +1,57 @@
|
||||
package sn
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type User struct {
|
||||
Id int `json:"id,string"`
|
||||
Name string `json:"name"`
|
||||
Privates UserPrivates `json:"privates"`
|
||||
}
|
||||
|
||||
type UserPrivates struct {
|
||||
Sats int `json:"sats"`
|
||||
}
|
||||
|
||||
type MeResponse struct {
|
||||
Errors []GqlError `json:"errors"`
|
||||
Data struct {
|
||||
Me User `json:"me"`
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
func (c *Client) Me() (*User, error) {
|
||||
body := GqlBody{
|
||||
Query: `
|
||||
query me {
|
||||
me {
|
||||
id
|
||||
name
|
||||
privates {
|
||||
sats
|
||||
}
|
||||
}
|
||||
}`,
|
||||
}
|
||||
|
||||
resp, err := c.callApi(body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
var respBody MeResponse
|
||||
err = json.NewDecoder(resp.Body).Decode(&respBody)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("error decoding me: %w", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
err = c.checkForErrors(respBody.Errors)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &respBody.Data.Me, nil
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user