|
| 1 | +import gleam/dynamic |
| 2 | +import gleam/http |
| 3 | +import gleam/http/request |
| 4 | +import gleam/json |
| 5 | +import gleam/string |
| 6 | +import midas/task as t |
| 7 | +import snag |
| 8 | + |
| 9 | +const api_host = "bsky.social" |
| 10 | + |
| 11 | +pub fn create_session(handle, password) { |
| 12 | + let body = |
| 13 | + json.object([ |
| 14 | + #("identifier", json.string(handle)), |
| 15 | + #("password", json.string(password)), |
| 16 | + ]) |
| 17 | + let request = |
| 18 | + request.new() |
| 19 | + |> request.set_host(api_host) |
| 20 | + |> request.set_path("/xrpc/com.atproto.server.createSession") |
| 21 | + |> request.set_method(http.Post) |
| 22 | + |> request.set_body(<<json.to_string(body):utf8>>) |
| 23 | + |> request.prepend_header("content-type", "application/json") |
| 24 | + use response <- t.do(t.fetch(request)) |
| 25 | + let decoder = dynamic.field("accessJwt", dynamic.string) |
| 26 | + |
| 27 | + use token <- t.try(case response.status { |
| 28 | + 200 -> |
| 29 | + case json.decode_bits(response.body, decoder) { |
| 30 | + Ok(token) -> Ok(token) |
| 31 | + Error(reason) -> |
| 32 | + Error(snag.new("failed to decode response " <> string.inspect(reason))) |
| 33 | + } |
| 34 | + _ -> Error(snag.new("Did not get a 200 response")) |
| 35 | + }) |
| 36 | + t.done(token) |
| 37 | +} |
| 38 | + |
| 39 | +pub fn create_post(access_token, handle, text, at) { |
| 40 | + let post = |
| 41 | + json.object([ |
| 42 | + #("$type", json.string("app.bsky.feed.post")), |
| 43 | + #("text", json.string(text)), |
| 44 | + #("createdAt", json.string(at)), |
| 45 | + ]) |
| 46 | + let body = |
| 47 | + json.object([ |
| 48 | + #("repo", json.string(handle)), |
| 49 | + #("collection", json.string("app.bsky.feed.post")), |
| 50 | + #("record", post), |
| 51 | + ]) |
| 52 | + let request = |
| 53 | + request.new() |
| 54 | + |> request.set_host(api_host) |
| 55 | + |> request.set_path("/xrpc/com.atproto.repo.createRecord") |
| 56 | + |> request.set_method(http.Post) |
| 57 | + |> request.set_body(<<json.to_string(body):utf8>>) |
| 58 | + |> request.prepend_header("content-type", "application/json") |
| 59 | + |> request.prepend_header("authorization", "Bearer " <> access_token) |
| 60 | + use response <- t.do(t.fetch(request)) |
| 61 | + let decoder = dynamic.field("uri", dynamic.string) |
| 62 | + use uri <- t.try(case response.status { |
| 63 | + 200 -> |
| 64 | + case json.decode_bits(response.body, decoder) { |
| 65 | + Ok(uri) -> Ok(uri) |
| 66 | + Error(reason) -> |
| 67 | + Error(snag.new("failed to decode response " <> string.inspect(reason))) |
| 68 | + } |
| 69 | + _ -> Error(snag.new("Did not get a 200 response")) |
| 70 | + }) |
| 71 | + t.done(uri) |
| 72 | +} |
0 commit comments