defmodule StatusphereWeb.StatusController do alias Statusphere.Repo require Logger use StatusphereWeb, :controller def create(conn, %{"status" => status}) do rkey = to_string(Atex.TID.now()) with {:ok, client} <- Atex.XRPC.OAuthClient.from_conn(conn), {:ok, record} <- Xyz.Statusphere.Status.main(%{ status: status, createdAt: NaiveDateTime.utc_now() |> NaiveDateTime.to_iso8601() }), {:ok, _, client} <- Atex.XRPC.post( client, %Com.Atproto.Repo.PutRecord{ input: %{ repo: client.did, collection: "xyz.statusphere.status", rkey: rkey, record: record } } ) do uri = Atex.AtURI.to_string(%Atex.AtURI{ authority: client.did, collection: "xyz.statusphere.status", rkey: rkey }) optimistic_insert = %Statusphere.Status{} |> Statusphere.Status.changeset(%{ uri: uri, author_did: client.did, status: record.status, created_at: NaiveDateTime.from_iso8601!(record.createdAt), indexed_at: NaiveDateTime.utc_now() }) |> Repo.insert() case optimistic_insert do {:ok, _} -> nil {:error, changeset} -> Logger.error("Failed to optimistically insert status: #{inspect(changeset)}") end conn |> Atex.XRPC.OAuthClient.update_plug(client) |> redirect(to: ~p"/") else :error -> conn |> put_status(401) |> html("

Error: not logged in

") {:error, [_ | _]} -> conn |> put_status(400) |> html("

Error: invalid status

") {:error, err, client} -> Logger.error("Failed to write record #{err}") conn |> Atex.XRPC.OAuthClient.update_plug(client) |> put_status(500) |> html("

Error: failed to write record

") end end end