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.

302 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. return p, nil
  133. } else if c.isNotLoggedIn(status) {
  134. return nil, fmt.Errorf("Not authenticated.")
  135. } else if status == http.StatusBadRequest {
  136. return nil, fmt.Errorf("Bad request: %s", env.ErrorMessage)
  137. }
  138. return nil, fmt.Errorf("Problem getting post: %d. %v\n", status, err)
  139. }
  140. // DeletePost permanently deletes a published post. See
  141. // https://developer.write.as/docs/api/#delete-a-post.
  142. func (c *Client) DeletePost(sp *PostParams) error {
  143. env, err := c.delete(fmt.Sprintf("/posts/%s", sp.ID), map[string]string{
  144. "token": sp.Token,
  145. })
  146. if err != nil {
  147. return err
  148. }
  149. status := env.Code
  150. if status == http.StatusNoContent {
  151. return nil
  152. } else if c.isNotLoggedIn(status) {
  153. return fmt.Errorf("Not authenticated.")
  154. } else if status == http.StatusBadRequest {
  155. return fmt.Errorf("Bad request: %s", env.ErrorMessage)
  156. }
  157. return fmt.Errorf("Problem getting post: %d. %v\n", status, err)
  158. }
  159. // ClaimPosts associates anonymous posts with a user / account.
  160. // https://developer.write.as/docs/api/#claim-posts.
  161. func (c *Client) ClaimPosts(sp *[]OwnedPostParams) (*[]ClaimPostResult, error) {
  162. p := &[]ClaimPostResult{}
  163. env, err := c.put("/posts/claim", sp, p)
  164. if err != nil {
  165. return nil, err
  166. }
  167. var ok bool
  168. if p, ok = env.Data.(*[]ClaimPostResult); !ok {
  169. return nil, fmt.Errorf("Wrong data returned from API.")
  170. }
  171. status := env.Code
  172. if status == http.StatusOK {
  173. return p, nil
  174. } else if c.isNotLoggedIn(status) {
  175. return nil, fmt.Errorf("Not authenticated.")
  176. } else if status == http.StatusBadRequest {
  177. return nil, fmt.Errorf("Bad request: %s", env.ErrorMessage)
  178. } else {
  179. return nil, fmt.Errorf("Problem getting post: %d. %v\n", status, err)
  180. }
  181. // TODO: does this also happen with moving posts?
  182. }
  183. // GetUserPosts retrieves the authenticated user's posts.
  184. // See https://developers.write.as/docs/api/#retrieve-user-39-s-posts
  185. func (c *Client) GetUserPosts() (*[]Post, error) {
  186. p := &[]Post{}
  187. env, err := c.get("/me/posts", p)
  188. if err != nil {
  189. return nil, err
  190. }
  191. var ok bool
  192. if p, ok = env.Data.(*[]Post); !ok {
  193. return nil, fmt.Errorf("Wrong data returned from API.")
  194. }
  195. status := env.Code
  196. if status != http.StatusOK {
  197. if c.isNotLoggedIn(status) {
  198. return nil, fmt.Errorf("Not authenticated.")
  199. }
  200. return nil, fmt.Errorf("Problem getting posts: %d. %v\n", status, err)
  201. }
  202. return p, nil
  203. }
  204. // PinPost pins a post in the given collection.
  205. // See https://developers.write.as/docs/api/#pin-a-post-to-a-collection
  206. func (c *Client) PinPost(alias string, pp *PinnedPostParams) error {
  207. res := &[]BatchPostResult{}
  208. env, err := c.post(fmt.Sprintf("/collections/%s/pin", alias), []*PinnedPostParams{pp}, res)
  209. if err != nil {
  210. return err
  211. }
  212. var ok bool
  213. if res, ok = env.Data.(*[]BatchPostResult); !ok {
  214. return fmt.Errorf("Wrong data returned from API.")
  215. }
  216. // Check for basic request errors on top level response
  217. status := env.Code
  218. if status != http.StatusOK {
  219. if c.isNotLoggedIn(status) {
  220. return fmt.Errorf("Not authenticated.")
  221. }
  222. return fmt.Errorf("Problem pinning post: %d. %v\n", status, err)
  223. }
  224. // Check the individual post result
  225. if len(*res) == 0 || len(*res) > 1 {
  226. return fmt.Errorf("Wrong data returned from API.")
  227. }
  228. if (*res)[0].Code != http.StatusOK {
  229. return fmt.Errorf("Problem pinning post: %d", (*res)[0].Code)
  230. // TODO: return ErrorMessage (right now it'll be empty)
  231. // return fmt.Errorf("Problem pinning post: %v", res[0].ErrorMessage)
  232. }
  233. return nil
  234. }
  235. // UnpinPost unpins a post from the given collection.
  236. // See https://developers.write.as/docs/api/#unpin-a-post-from-a-collection
  237. func (c *Client) UnpinPost(alias string, pp *PinnedPostParams) error {
  238. res := &[]BatchPostResult{}
  239. env, err := c.post(fmt.Sprintf("/collections/%s/unpin", alias), []*PinnedPostParams{pp}, res)
  240. if err != nil {
  241. return err
  242. }
  243. var ok bool
  244. if res, ok = env.Data.(*[]BatchPostResult); !ok {
  245. return fmt.Errorf("Wrong data returned from API.")
  246. }
  247. // Check for basic request errors on top level response
  248. status := env.Code
  249. if status != http.StatusOK {
  250. if c.isNotLoggedIn(status) {
  251. return fmt.Errorf("Not authenticated.")
  252. }
  253. return fmt.Errorf("Problem unpinning post: %d. %v\n", status, err)
  254. }
  255. // Check the individual post result
  256. if len(*res) == 0 || len(*res) > 1 {
  257. return fmt.Errorf("Wrong data returned from API.")
  258. }
  259. if (*res)[0].Code != http.StatusOK {
  260. return fmt.Errorf("Problem unpinning post: %d", (*res)[0].Code)
  261. // TODO: return ErrorMessage (right now it'll be empty)
  262. // return fmt.Errorf("Problem unpinning post: %v", res[0].ErrorMessage)
  263. }
  264. return nil
  265. }