copabot/lib/rentry.ml
2025-07-13 13:45:10 -03:00

62 lines
2.1 KiB
OCaml

open Cohttp
let ( let* ) = Lwt.bind
let update_page content =
let aux () =
let* resp, _ =
Cohttp_lwt_unix.Client.get (Uri.of_string "https://rentry.org")
in
let code = resp |> Response.status |> Code.code_of_status in
if not (Code.is_success code) then
Lwt.return (Error (Cohttp.Code.reason_phrase_of_code code))
else
let cookies =
Cohttp.Response.headers resp |> Cookie.Set_cookie_hdr.extract
in
let token = List.assoc "csrftoken" cookies in
let _, value = token.cookie in
let form =
Cohttp_lwt.Body.of_form
[
("csrfmiddlewaretoken", [ value ]);
(* TODO: use environmental variables *)
("edit_code", [ "foo perro bar caca" ]);
("metadata", [ "ACCESS_RECOMMENDED_THEME=dark" ]);
("text", [ content ]);
]
in
let uri = Uri.of_string "https://rentry.org/copalib-schedule/edit" in
let req_headers =
Cohttp.Header.(
let hname, hvalue =
cookies
|> List.map (fun (x : string * Cookie.Set_cookie_hdr.t) ->
let _, v = x in
v.cookie)
|> Cookie.Cookie_hdr.serialize
in
let rec aux h = function
| [] -> h
| (k, v) :: tail -> aux (add h k v) tail
in
aux (init ())
[
("Referer", "https://rentry.org");
("Content-Type", "application/x-www-form-urlencoded");
( "User-Agent", "copabot/0.1.0" );
(hname, hvalue);
])
in
let* resp, _ =
Cohttp_lwt_unix.Client.post uri ?body:(Some form)
?headers:(Some req_headers)
in
let code = resp |> Response.status |> Code.code_of_status in
if not (Code.is_success code || Code.is_redirection code) then
Lwt.return (Error (Cohttp.Code.reason_phrase_of_code code))
else Lwt.return (Ok ())
in
Lwt_main.run
(let* result = aux () in
match result with Error str -> failwith str | Ok _ -> Lwt.return ())