Go client for the Write.as API https://developers.write.as
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

303 lines
8.7 KiB

  1. package writeas
  2. import (
  3. "fmt"
  4. "net/http"
  5. "time"
  6. )
  7. type (
  8. // Post represents a published Write.as post, whether anonymous, owned by a
  9. // user, or part of a collection.
  10. Post struct {
  11. ID string `json:"id"`
  12. Slug string `json:"slug"`
  13. Token string `json:"token"`
  14. Font string `json:"appearance"`
  15. Language *string `json:"language"`
  16. RTL *bool `json:"rtl"`
  17. Listed bool `json:"listed"`
  18. Created time.Time `json:"created"`
  19. Updated time.Time `json:"updated"`
  20. Title string `json:"title"`
  21. Content string `json:"body"`
  22. Views int64 `json:"views"`
  23. Tags []string `json:"tags"`
  24. Images []string `json:"images"`
  25. OwnerName string `json:"owner,omitempty"`
  26. Collection *Collection `json:"collection,omitempty"`
  27. }
  28. // OwnedPostParams are, together, fields only the original post author knows.
  29. OwnedPostParams struct {
  30. ID string `json:"-"`
  31. Token string `json:"token,omitempty"`
  32. }
  33. // PostParams holds values for creating or updating a post.
  34. PostParams struct {
  35. // Parameters only for updating
  36. ID string `json:"-"`
  37. Token string `json:"token,omitempty"`
  38. // Parameters for creating or updating
  39. Title string `json:"title,omitempty"`
  40. Content string `json:"body,omitempty"`
  41. Font string `json:"font,omitempty"`
  42. IsRTL *bool `json:"rtl,omitempty"`
  43. Language *string `json:"lang,omitempty"`
  44. // Parameters only for creating
  45. Crosspost []map[string]string `json:"crosspost,omitempty"`
  46. // Parameters for collection posts
  47. Collection string `json:"-"`
  48. }
  49. // PinnedPostParams holds values for pinning a post
  50. PinnedPostParams struct {
  51. ID string `json:"id"`
  52. Position int `json:"position"`
  53. }
  54. // BatchPostResult contains the post-specific result as part of a larger
  55. // batch operation.
  56. BatchPostResult struct {
  57. ID string `json:"id,omitempty"`
  58. Code int `json:"code,omitempty"`
  59. ErrorMessage string `json:"error_msg,omitempty"`
  60. }
  61. // ClaimPostResult contains the post-specific result for a request to
  62. // associate a post to an account.
  63. ClaimPostResult struct {
  64. ID string `json:"id,omitempty"`
  65. Code int `json:"code,omitempty"`
  66. ErrorMessage string `json:"error_msg,omitempty"`
  67. Post *Post `json:"post,omitempty"`
  68. }
  69. )
  70. // GetPost retrieves a published post, returning the Post and any error (in
  71. // user-friendly form) that occurs. See
  72. // https://developer.write.as/docs/api/#retrieve-a-post.
  73. func (c *Client) GetPost(id string) (*Post, error) {
  74. p := &Post{}
  75. env, err := c.get(fmt.Sprintf("/posts/%s", id), p)
  76. if err != nil {
  77. return nil, err
  78. }
  79. var ok bool
  80. if p, ok = env.Data.(*Post); !ok {
  81. return nil, fmt.Errorf("Wrong data returned from API.")
  82. }
  83. status := env.Code
  84. if status == http.StatusOK {
  85. return p, nil
  86. } else if status == http.StatusNotFound {
  87. return nil, fmt.Errorf("Post not found.")
  88. } else if status == http.StatusGone {
  89. return nil, fmt.Errorf("Post unpublished.")
  90. }
  91. return nil, fmt.Errorf("Problem getting post: %d. %v\n", status, err)
  92. }
  93. // CreatePost publishes a new post, returning a user-friendly error if one comes
  94. // up. See https://developer.write.as/docs/api/#publish-a-post.
  95. func (c *Client) CreatePost(sp *PostParams) (*Post, error) {
  96. p := &Post{}
  97. endPre := ""
  98. if sp.Collection != "" {
  99. endPre = "/collections/" + sp.Collection
  100. }
  101. env, err := c.post(endPre+"/posts", sp, p)
  102. if err != nil {
  103. return nil, err
  104. }
  105. var ok bool
  106. if p, ok = env.Data.(*Post); !ok {
  107. return nil, fmt.Errorf("Wrong data returned from API.")
  108. }
  109. status := env.Code
  110. if status == http.StatusCreated {
  111. return p, nil
  112. } else if status == http.StatusBadRequest {
  113. return nil, fmt.Errorf("Bad request: %s", env.ErrorMessage)
  114. } else {
  115. return nil, fmt.Errorf("Problem getting post: %d. %v\n", status, err)
  116. }
  117. }
  118. // UpdatePost updates a published post with the given PostParams. See
  119. // https://developer.write.as/docs/api/#update-a-post.
  120. func (c *Client) UpdatePost(sp *PostParams) (*Post, error) {
  121. p := &Post{}
  122. env, err := c.put(fmt.Sprintf("/posts/%s", sp.ID), sp, p)
  123. if err != nil {
  124. return nil, err
  125. }
  126. var ok bool
  127. if p, ok = env.Data.(*Post); !ok {
  128. return nil, fmt.Errorf("Wrong data returned from API.")
  129. }
  130. status := env.Code
  131. if status != http.StatusOK {
  132. if c.isNotLoggedIn(status) {
  133. return nil, fmt.Errorf("Not authenticated.")
  134. } else if status == http.StatusBadRequest {
  135. return nil, fmt.Errorf("Bad request: %s", env.ErrorMessage)
  136. }
  137. return nil, fmt.Errorf("Problem getting post: %d. %v\n", status, err)
  138. }
  139. return p, nil
  140. }
  141. // DeletePost permanently deletes a published post. See
  142. // https://developer.write.as/docs/api/#delete-a-post.
  143. func (c *Client) DeletePost(sp *PostParams) error {
  144. env, err := c.delete(fmt.Sprintf("/posts/%s", sp.ID), map[string]string{
  145. "token": sp.Token,
  146. })
  147. if err != nil {
  148. return err
  149. }
  150. status := env.Code
  151. if status == http.StatusNoContent {
  152. return nil
  153. } else if c.isNotLoggedIn(status) {
  154. return fmt.Errorf("Not authenticated.")
  155. } else if status == http.StatusBadRequest {
  156. return fmt.Errorf("Bad request: %s", env.ErrorMessage)
  157. }
  158. return fmt.Errorf("Problem getting post: %d. %v\n", status, err)
  159. }
  160. // ClaimPosts associates anonymous posts with a user / account.
  161. // https://developer.write.as/docs/api/#claim-posts.
  162. func (c *Client) ClaimPosts(sp *[]OwnedPostParams) (*[]ClaimPostResult, error) {
  163. p := &[]ClaimPostResult{}
  164. env, err := c.put("/posts/claim", sp, p)
  165. if err != nil {
  166. return nil, err
  167. }
  168. var ok bool
  169. if p, ok = env.Data.(*[]ClaimPostResult); !ok {
  170. return nil, fmt.Errorf("Wrong data returned from API.")
  171. }
  172. status := env.Code
  173. if status == http.StatusOK {
  174. return p, nil
  175. } else if c.isNotLoggedIn(status) {
  176. return nil, fmt.Errorf("Not authenticated.")
  177. } else if status == http.StatusBadRequest {
  178. return nil, fmt.Errorf("Bad request: %s", env.ErrorMessage)
  179. } else {
  180. return nil, fmt.Errorf("Problem getting post: %d. %v\n", status, err)
  181. }
  182. // TODO: does this also happen with moving posts?
  183. }
  184. // GetUserPosts retrieves the authenticated user's posts.
  185. // See https://developers.write.as/docs/api/#retrieve-user-39-s-posts
  186. func (c *Client) GetUserPosts() (*[]Post, error) {
  187. p := &[]Post{}
  188. env, err := c.get("/me/posts", p)
  189. if err != nil {
  190. return nil, err
  191. }
  192. var ok bool
  193. if p, ok = env.Data.(*[]Post); !ok {
  194. return nil, fmt.Errorf("Wrong data returned from API.")
  195. }
  196. status := env.Code
  197. if status != http.StatusOK {
  198. if c.isNotLoggedIn(status) {
  199. return nil, fmt.Errorf("Not authenticated.")
  200. }
  201. return nil, fmt.Errorf("Problem getting posts: %d. %v\n", status, err)
  202. }
  203. return p, nil
  204. }
  205. // PinPost pins a post in the given collection.
  206. // See https://developers.write.as/docs/api/#pin-a-post-to-a-collection
  207. func (c *Client) PinPost(alias string, pp *PinnedPostParams) error {
  208. res := &[]BatchPostResult{}
  209. env, err := c.post(fmt.Sprintf("/collections/%s/pin", alias), []*PinnedPostParams{pp}, res)
  210. if err != nil {
  211. return err
  212. }
  213. var ok bool
  214. if res, ok = env.Data.(*[]BatchPostResult); !ok {
  215. return fmt.Errorf("Wrong data returned from API.")
  216. }
  217. // Check for basic request errors on top level response
  218. status := env.Code
  219. if status != http.StatusOK {
  220. if c.isNotLoggedIn(status) {
  221. return fmt.Errorf("Not authenticated.")
  222. }
  223. return fmt.Errorf("Problem pinning post: %d. %v\n", status, err)
  224. }
  225. // Check the individual post result
  226. if len(*res) == 0 || len(*res) > 1 {
  227. return fmt.Errorf("Wrong data returned from API.")
  228. }
  229. if (*res)[0].Code != http.StatusOK {
  230. return fmt.Errorf("Problem pinning post: %d", (*res)[0].Code)
  231. // TODO: return ErrorMessage (right now it'll be empty)
  232. // return fmt.Errorf("Problem pinning post: %v", res[0].ErrorMessage)
  233. }
  234. return nil
  235. }
  236. // UnpinPost unpins a post from the given collection.
  237. // See https://developers.write.as/docs/api/#unpin-a-post-from-a-collection
  238. func (c *Client) UnpinPost(alias string, pp *PinnedPostParams) error {
  239. res := &[]BatchPostResult{}
  240. env, err := c.post(fmt.Sprintf("/collections/%s/unpin", alias), []*PinnedPostParams{pp}, res)
  241. if err != nil {
  242. return err
  243. }
  244. var ok bool
  245. if res, ok = env.Data.(*[]BatchPostResult); !ok {
  246. return fmt.Errorf("Wrong data returned from API.")
  247. }
  248. // Check for basic request errors on top level response
  249. status := env.Code
  250. if status != http.StatusOK {
  251. if c.isNotLoggedIn(status) {
  252. return fmt.Errorf("Not authenticated.")
  253. }
  254. return fmt.Errorf("Problem unpinning post: %d. %v\n", status, err)
  255. }
  256. // Check the individual post result
  257. if len(*res) == 0 || len(*res) > 1 {
  258. return fmt.Errorf("Wrong data returned from API.")
  259. }
  260. if (*res)[0].Code != http.StatusOK {
  261. return fmt.Errorf("Problem unpinning post: %d", (*res)[0].Code)
  262. // TODO: return ErrorMessage (right now it'll be empty)
  263. // return fmt.Errorf("Problem unpinning post: %v", res[0].ErrorMessage)
  264. }
  265. return nil
  266. }