notion.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package notion
  4. import (
  5. "bytes"
  6. "encoding/json"
  7. "fmt"
  8. "net/http"
  9. "time"
  10. "miniflux.app/v2/internal/version"
  11. )
  12. const defaultClientTimeout = 10 * time.Second
  13. type Client struct {
  14. apiToken string
  15. pageID string
  16. }
  17. func NewClient(apiToken, pageID string) *Client {
  18. return &Client{apiToken, pageID}
  19. }
  20. func (c *Client) UpdateDocument(entryURL string, entryTitle string) error {
  21. if c.apiToken == "" || c.pageID == "" {
  22. return fmt.Errorf("notion: missing API token or page ID")
  23. }
  24. apiEndpoint := "https://api.notion.com/v1/blocks/" + c.pageID + "/children"
  25. requestBody, err := json.Marshal(&notionDocument{
  26. Children: []block{
  27. {
  28. Object: "block",
  29. Type: "bookmark",
  30. Bookmark: bookmarkObject{
  31. Caption: []any{},
  32. URL: entryURL,
  33. },
  34. },
  35. },
  36. })
  37. if err != nil {
  38. return fmt.Errorf("notion: unable to encode request body: %v", err)
  39. }
  40. request, err := http.NewRequest(http.MethodPatch, apiEndpoint, bytes.NewReader(requestBody))
  41. if err != nil {
  42. return fmt.Errorf("notion: unable to create request: %v", err)
  43. }
  44. request.Header.Set("Content-Type", "application/json")
  45. request.Header.Set("User-Agent", "Miniflux/"+version.Version)
  46. request.Header.Set("Notion-Version", "2022-06-28")
  47. request.Header.Set("Authorization", "Bearer "+c.apiToken)
  48. httpClient := &http.Client{Timeout: defaultClientTimeout}
  49. response, err := httpClient.Do(request)
  50. if err != nil {
  51. return fmt.Errorf("notion: unable to send request: %v", err)
  52. }
  53. defer response.Body.Close()
  54. if response.StatusCode != http.StatusOK {
  55. return fmt.Errorf("notion: unable to update document: url=%s status=%d", apiEndpoint, response.StatusCode)
  56. }
  57. return nil
  58. }
  59. type notionDocument struct {
  60. Children []block `json:"children"`
  61. }
  62. type block struct {
  63. Object string `json:"object"`
  64. Type string `json:"type"`
  65. Bookmark bookmarkObject `json:"bookmark"`
  66. }
  67. type bookmarkObject struct {
  68. Caption []any `json:"caption"`
  69. URL string `json:"url"`
  70. }