notion.go 2.1 KB

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