notion.go 2.1 KB

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