My agentic slop goes here. Not intended for anyone else!

sync

+177 -86
stack/river/cmd/river_cmd.ml
···
let user = River.User.make ~username ~fullname ?email () in
match River.State.create_user state user with
| Ok () ->
-
Log.info (fun m -> m "User %s created" username);
0
| Error err ->
-
Log.err (fun m -> m "%s" err);
1
let remove state ~username =
match River.State.delete_user state ~username with
| Ok () ->
-
Log.info (fun m -> m "User %s removed" username);
0
| Error err ->
-
Log.err (fun m -> m "%s" err);
1
let list state =
let users = River.State.list_users state in
-
if users = [] then
-
Printf.printf "No users found\n"
-
else begin
-
Printf.printf "Users:\n";
List.iter (fun username ->
match River.State.get_user state ~username with
| Some user ->
let email_str = match River.User.email user with
-
| Some e -> " <" ^ e ^ ">"
| None -> ""
in
-
Printf.printf " %s (%s%s) - %d feeds\n"
-
username (River.User.fullname user) email_str
-
(List.length (River.User.feeds user))
| None -> ()
) users
end;
···
let add_feed state ~username ~name ~url =
match River.State.get_user state ~username with
| None ->
-
Log.err (fun m -> m "User %s not found" username);
1
| Some user ->
let source = River.Source.make ~name ~url in
let user = River.User.add_feed user source in
(match River.State.update_user state user with
| Ok () ->
-
Log.info (fun m -> m "Feed %s added to user %s" name username);
0
| Error err ->
-
Log.err (fun m -> m "%s" err);
1)
let remove_feed state ~username ~url =
match River.State.get_user state ~username with
| None ->
-
Log.err (fun m -> m "User %s not found" username);
1
| Some user ->
let user = River.User.remove_feed user ~url in
(match River.State.update_user state user with
| Ok () ->
-
Log.info (fun m -> m "Feed removed from user %s" username);
0
| Error err ->
-
Log.err (fun m -> m "%s" err);
1)
let show state ~username =
match River.State.get_user state ~username with
| None ->
-
Log.err (fun m -> m "User %s not found" username);
1
| Some user ->
-
Printf.printf "Username: %s\n" (River.User.username user);
-
Printf.printf "Full name: %s\n" (River.User.fullname user);
-
Printf.printf "Email: %s\n"
-
(Option.value (River.User.email user) ~default:"(none)");
-
Printf.printf "Last synced: %s\n"
(Option.value (River.User.last_synced user) ~default:"never");
let feeds = River.User.feeds user in
-
Printf.printf "Feeds (%d):\n" (List.length feeds);
-
List.iter (fun feed ->
-
Printf.printf " - %s: %s\n"
-
(River.Source.name feed) (River.Source.url feed)
-
) feeds;
0
end
(* Sync command *)
module Sync = struct
let sync_user env state ~username =
match River.State.sync_user env state ~username with
| Ok () ->
-
Log.info (fun m -> m "Sync completed for user %s" username);
0
| Error err ->
-
Log.err (fun m -> m "Sync failed: %s" err);
1
let sync_all env state =
match River.State.sync_all env state with
| Ok (success, fail) ->
-
Log.info (fun m -> m "Synced %d users (%d failed)" success fail);
-
if fail = 0 then 0 else 1
| Error err ->
-
Log.err (fun m -> m "Sync failed: %s" err);
1
end
···
1
| Ok metrics ->
(* Display quality metrics *)
-
Fmt.pr "@.";
-
Fmt.pr "%a@." Fmt.(styled `Bold string)
-
(String.make 70 '=');
-
Fmt.pr " %a %s@." Fmt.(styled `Bold (styled (`Fg `Blue) string))
-
"User Quality Analysis:" username;
-
Fmt.pr "%a@.@." Fmt.(styled `Bold string)
-
(String.make 70 '=');
-
(* Overall quality score *)
let score = River.Quality.quality_score metrics in
-
let score_color = match score with
-
| s when s >= 80.0 -> `Green
-
| s when s >= 60.0 -> `Yellow
-
| s when s >= 40.0 -> `Magenta
-
| _ -> `Red
in
-
Fmt.pr "%a %.1f/100.0@.@."
-
Fmt.(styled (`Fg score_color) (styled `Bold string))
-
"Overall Quality Score:"
-
score;
(* Entry statistics *)
-
Fmt.pr "%a@." Fmt.(styled `Cyan string) "Entry Statistics:";
-
Fmt.pr " Total entries: %d@." (River.Quality.total_entries metrics);
Fmt.pr "@.";
-
(* Completeness metrics *)
-
Fmt.pr "%a@." Fmt.(styled `Cyan string) "Completeness:";
let total = River.Quality.total_entries metrics in
let pct entries =
float_of_int entries /. float_of_int total *. 100.0
in
-
Fmt.pr " Entries with content: %3d/%d (%5.1f%%)@."
-
(River.Quality.entries_with_content metrics)
-
total
-
(pct (River.Quality.entries_with_content metrics));
-
Fmt.pr " Entries with dates: %3d/%d (%5.1f%%)@."
-
(River.Quality.entries_with_date metrics)
-
total
-
(pct (River.Quality.entries_with_date metrics));
-
Fmt.pr " Entries with authors: %3d/%d (%5.1f%%)@."
-
(River.Quality.entries_with_author metrics)
-
total
-
(pct (River.Quality.entries_with_author metrics));
-
Fmt.pr " Entries with summaries:%3d/%d (%5.1f%%)@."
-
(River.Quality.entries_with_summary metrics)
-
total
-
(pct (River.Quality.entries_with_summary metrics));
-
Fmt.pr " Entries with tags: %3d/%d (%5.1f%%)@."
-
(River.Quality.entries_with_tags metrics)
-
total
-
(pct (River.Quality.entries_with_tags metrics));
Fmt.pr "@.";
(* Content statistics *)
if River.Quality.entries_with_content metrics > 0 then begin
-
Fmt.pr "%a@." Fmt.(styled `Cyan string) "Content Statistics:";
-
Fmt.pr " Average length: %.0f characters@."
(River.Quality.avg_content_length metrics);
-
Fmt.pr " Min length: %d characters@."
-
(River.Quality.min_content_length metrics);
-
Fmt.pr " Max length: %d characters@."
-
(River.Quality.max_content_length metrics);
-
Fmt.pr "@."
end;
(* Posting frequency *)
(match River.Quality.posting_frequency_days metrics with
| Some freq ->
-
Fmt.pr "%a@." Fmt.(styled `Cyan string) "Posting Frequency:";
-
Fmt.pr " Average: %.1f days between posts@." freq;
let posts_per_week = 7.0 /. freq in
-
Fmt.pr " (~%.1f posts per week)@." posts_per_week;
-
Fmt.pr "@."
| None ->
Fmt.pr "%a@.@." Fmt.(styled `Faint string)
"Not enough data to calculate posting frequency");
···
let user = River.User.make ~username ~fullname ?email () in
match River.State.create_user state user with
| Ok () ->
+
Fmt.pr "@.%a %a %a@.@."
+
Fmt.(styled (`Fg `Green) string) "✓"
+
Fmt.(styled `Bold string) "User created:"
+
Fmt.(styled (`Fg `Cyan) string) username;
0
| Error err ->
+
Fmt.pr "@.%a %s@.@."
+
Fmt.(styled (`Fg `Red) string) "✗ Error:"
+
err;
1
let remove state ~username =
match River.State.delete_user state ~username with
| Ok () ->
+
Fmt.pr "@.%a %a %a@.@."
+
Fmt.(styled (`Fg `Green) string) "✓"
+
Fmt.(styled `Bold string) "User removed:"
+
Fmt.(styled (`Fg `Cyan) string) username;
0
| Error err ->
+
Fmt.pr "@.%a %s@.@."
+
Fmt.(styled (`Fg `Red) string) "✗ Error:"
+
err;
1
let list state =
let users = River.State.list_users state in
+
if users = [] then begin
+
Fmt.pr "@.%a@.@."
+
Fmt.(styled `Yellow string)
+
"No users found. Use 'river-cli user add' to create one."
+
end else begin
+
Fmt.pr "@.%a@."
+
Fmt.(styled `Bold (styled (`Fg `Cyan) string))
+
(Printf.sprintf "Users (%d total)" (List.length users));
+
Fmt.pr "%a@.@." Fmt.(styled `Faint string) (String.make 60 '-');
List.iter (fun username ->
match River.State.get_user state ~username with
| Some user ->
let email_str = match River.User.email user with
+
| Some e -> Fmt.str " %a" Fmt.(styled `Faint string) ("<" ^ e ^ ">")
| None -> ""
in
+
let feed_count = List.length (River.User.feeds user) in
+
Fmt.pr "%a %a%s@."
+
Fmt.(styled `Bold (styled (`Fg `Blue) string)) username
+
Fmt.(styled `Green string) (River.User.fullname user)
+
email_str;
+
Fmt.pr " %a %a %a@.@."
+
Fmt.(styled `Faint string) "└─"
+
Fmt.(styled (`Fg `Yellow) string) (string_of_int feed_count)
+
Fmt.(styled `Faint string) (if feed_count = 1 then "feed" else "feeds")
| None -> ()
) users
end;
···
let add_feed state ~username ~name ~url =
match River.State.get_user state ~username with
| None ->
+
Fmt.pr "@.%a User %a not found@.@."
+
Fmt.(styled (`Fg `Red) string) "✗ Error:"
+
Fmt.(styled `Bold string) username;
1
| Some user ->
let source = River.Source.make ~name ~url in
let user = River.User.add_feed user source in
(match River.State.update_user state user with
| Ok () ->
+
Fmt.pr "@.%a Feed added to %a@."
+
Fmt.(styled (`Fg `Green) string) "✓"
+
Fmt.(styled (`Fg `Cyan) string) username;
+
Fmt.pr " %a %a@."
+
Fmt.(styled `Faint string) "Name:"
+
Fmt.(styled `Bold string) name;
+
Fmt.pr " %a %a@.@."
+
Fmt.(styled `Faint string) "URL: "
+
Fmt.(styled (`Fg `Blue) string) url;
0
| Error err ->
+
Fmt.pr "@.%a %s@.@."
+
Fmt.(styled (`Fg `Red) string) "✗ Error:"
+
err;
1)
let remove_feed state ~username ~url =
match River.State.get_user state ~username with
| None ->
+
Fmt.pr "@.%a User %a not found@.@."
+
Fmt.(styled (`Fg `Red) string) "✗ Error:"
+
Fmt.(styled `Bold string) username;
1
| Some user ->
let user = River.User.remove_feed user ~url in
(match River.State.update_user state user with
| Ok () ->
+
Fmt.pr "@.%a Feed removed from %a@.@."
+
Fmt.(styled (`Fg `Green) string) "✓"
+
Fmt.(styled (`Fg `Cyan) string) username;
0
| Error err ->
+
Fmt.pr "@.%a %s@.@."
+
Fmt.(styled (`Fg `Red) string) "✗ Error:"
+
err;
1)
let show state ~username =
match River.State.get_user state ~username with
| None ->
+
Fmt.pr "@.%a User %a not found@.@."
+
Fmt.(styled (`Fg `Red) string) "✗ Error:"
+
Fmt.(styled `Bold string) username;
1
| Some user ->
+
Fmt.pr "@.%a@."
+
Fmt.(styled `Bold (styled (`Fg `Cyan) string))
+
(Printf.sprintf "User: %s" (River.User.username user));
+
Fmt.pr "%a@.@." Fmt.(styled `Faint string) (String.make 60 '-');
+
+
Fmt.pr "%a %a@."
+
Fmt.(styled `Faint string) "Full name:"
+
Fmt.(styled `Green string) (River.User.fullname user);
+
+
Fmt.pr "%a %a@."
+
Fmt.(styled `Faint string) "Email: "
+
Fmt.string (Option.value (River.User.email user) ~default:"(not set)");
+
+
Fmt.pr "%a %a@.@."
+
Fmt.(styled `Faint string) "Synced: "
+
Fmt.(styled `Yellow string)
(Option.value (River.User.last_synced user) ~default:"never");
+
let feeds = River.User.feeds user in
+
Fmt.pr "%a@."
+
Fmt.(styled `Bold string)
+
(Printf.sprintf "Feeds (%d)" (List.length feeds));
+
Fmt.pr "%a@." Fmt.(styled `Faint string) (String.make 60 '-');
+
+
if feeds = [] then
+
Fmt.pr "%a@.@."
+
Fmt.(styled `Faint string)
+
" No feeds configured. Use 'river-cli user add-feed' to add one."
+
else
+
List.iter (fun feed ->
+
Fmt.pr "@.%a@."
+
Fmt.(styled `Bold (styled (`Fg `Blue) string))
+
(River.Source.name feed);
+
Fmt.pr " %a %a@.@."
+
Fmt.(styled `Faint string) "URL:"
+
Fmt.(styled (`Fg `Magenta) string) (River.Source.url feed)
+
) feeds;
0
end
(* Sync command *)
module Sync = struct
let sync_user env state ~username =
+
Fmt.pr "@.%a Syncing feeds for %a...@."
+
Fmt.(styled (`Fg `Cyan) string) "→"
+
Fmt.(styled `Bold string) username;
match River.State.sync_user env state ~username with
| Ok () ->
+
Fmt.pr "%a Sync completed successfully@.@."
+
Fmt.(styled (`Fg `Green) string) "✓";
0
| Error err ->
+
Fmt.pr "%a Sync failed: %s@.@."
+
Fmt.(styled (`Fg `Red) string) "✗"
+
err;
1
let sync_all env state =
+
Fmt.pr "@.%a Syncing all users...@.@."
+
Fmt.(styled (`Fg `Cyan) string) "→";
match River.State.sync_all env state with
| Ok (success, fail) ->
+
if fail = 0 then begin
+
Fmt.pr "%a Successfully synced %a@.@."
+
Fmt.(styled (`Fg `Green) string) "✓"
+
Fmt.(styled `Bold (styled (`Fg `Green) string)) (Printf.sprintf "%d users" success);
+
0
+
end else begin
+
Fmt.pr "%a Synced %a, %a@.@."
+
Fmt.(styled `Yellow string) "⚠"
+
Fmt.(styled (`Fg `Green) string) (Printf.sprintf "%d users" success)
+
Fmt.(styled (`Fg `Red) string) (Printf.sprintf "%d failed" fail);
+
1
+
end
| Error err ->
+
Fmt.pr "%a Sync failed: %s@.@."
+
Fmt.(styled (`Fg `Red) string) "✗"
+
err;
1
end
···
1
| Ok metrics ->
(* Display quality metrics *)
+
Fmt.pr "@.%a@."
+
Fmt.(styled `Bold (styled (`Fg `Cyan) string))
+
(Printf.sprintf "Feed Quality Analysis: %s" username);
+
Fmt.pr "%a@.@." Fmt.(styled `Faint string) (String.make 70 '=');
+
(* Overall quality score with visual indicator *)
let score = River.Quality.quality_score metrics in
+
let score_color, score_label = match score with
+
| s when s >= 80.0 -> `Green, "Excellent"
+
| s when s >= 60.0 -> `Yellow, "Good"
+
| s when s >= 40.0 -> `Magenta, "Fair"
+
| _ -> `Red, "Poor"
in
+
let bar_width = 40 in
+
let filled = int_of_float (score /. 100.0 *. float_of_int bar_width) in
+
let bar = String.make filled '#' ^ String.make (bar_width - filled) '-' in
+
Fmt.pr "%a@."
+
Fmt.(styled `Bold string) "Overall Quality Score";
+
Fmt.pr " %a %.1f/100 %a@.@."
+
Fmt.(styled (`Fg score_color) string) bar
+
score
+
Fmt.(styled (`Fg score_color) (styled `Bold string)) (Printf.sprintf "(%s)" score_label);
(* Entry statistics *)
+
Fmt.pr "%a %a@."
+
Fmt.(styled `Bold string) "📊 Entries:"
+
Fmt.(styled (`Fg `Yellow) (styled `Bold string))
+
(string_of_int (River.Quality.total_entries metrics));
Fmt.pr "@.";
+
(* Completeness metrics with visual indicators *)
+
Fmt.pr "%a@." Fmt.(styled `Bold string) "Completeness";
let total = River.Quality.total_entries metrics in
let pct entries =
float_of_int entries /. float_of_int total *. 100.0
in
+
let show_metric label count =
+
let p = pct count in
+
let icon, color = match p with
+
| p when p >= 90.0 -> "✓", `Green
+
| p when p >= 50.0 -> "○", `Yellow
+
| _ -> "✗", `Red
+
in
+
Fmt.pr " %a %s %3d/%d %a@."
+
Fmt.(styled (`Fg color) string) icon
+
label
+
count total
+
Fmt.(styled `Faint string) (Printf.sprintf "(%.1f%%)" p)
+
in
+
show_metric "Content: " (River.Quality.entries_with_content metrics);
+
show_metric "Dates: " (River.Quality.entries_with_date metrics);
+
show_metric "Authors: " (River.Quality.entries_with_author metrics);
+
show_metric "Summaries:" (River.Quality.entries_with_summary metrics);
+
show_metric "Tags: " (River.Quality.entries_with_tags metrics);
Fmt.pr "@.";
(* Content statistics *)
if River.Quality.entries_with_content metrics > 0 then begin
+
Fmt.pr "%a@." Fmt.(styled `Bold string) "Content Statistics";
+
Fmt.pr " %a %.0f chars@."
+
Fmt.(styled `Faint string) "Average:"
(River.Quality.avg_content_length metrics);
+
Fmt.pr " %a %a ... %a@.@."
+
Fmt.(styled `Faint string) "Range: "
+
Fmt.(styled (`Fg `Cyan) string) (string_of_int (River.Quality.min_content_length metrics))
+
Fmt.(styled (`Fg `Cyan) string) (string_of_int (River.Quality.max_content_length metrics))
end;
(* Posting frequency *)
(match River.Quality.posting_frequency_days metrics with
| Some freq ->
+
Fmt.pr "%a@." Fmt.(styled `Bold string) "Posting Frequency";
let posts_per_week = 7.0 /. freq in
+
Fmt.pr " %a %.1f days between posts@."
+
Fmt.(styled `Faint string) "Average:"
+
freq;
+
Fmt.pr " %a ~%.1f posts/week@.@."
+
Fmt.(styled `Faint string) " "
+
posts_per_week
| None ->
Fmt.pr "%a@.@." Fmt.(styled `Faint string)
"Not enough data to calculate posting frequency");
+123
stack/river/lib/feed.ml
···
···
+
(*
+
* Copyright (c) 2014, OCaml.org project
+
* Copyright (c) 2015 KC Sivaramakrishnan <sk826@cl.cam.ac.uk>
+
*
+
* Permission to use, copy, modify, and distribute this software for any
+
* purpose with or without fee is hereby granted, provided that the above
+
* copyright notice and this permission notice appear in all copies.
+
*
+
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
*)
+
+
(** Feed fetching and parsing. *)
+
+
let src = Logs.Src.create "river" ~doc:"River RSS/Atom aggregator"
+
module Log = (val Logs.src_log src : Logs.LOG)
+
+
type feed_content =
+
| Atom of Syndic.Atom.feed
+
| Rss2 of Syndic.Rss2.channel
+
| Json of Jsonfeed.t
+
+
type t = {
+
source : Source.t;
+
title : string;
+
content : feed_content;
+
}
+
+
let string_of_feed = function
+
| Atom _ -> "Atom"
+
| Rss2 _ -> "Rss2"
+
| Json _ -> "JSONFeed"
+
+
let classify_feed ~xmlbase (body : string) =
+
Log.debug (fun m -> m "Attempting to parse feed (%d bytes)" (String.length body));
+
+
(* Quick check - does it look like JSON? *)
+
let looks_like_json =
+
String.length body > 0 &&
+
let first_char = String.get body 0 in
+
first_char = '{' || first_char = '['
+
in
+
+
if looks_like_json then (
+
(* Try JSONFeed first *)
+
Log.debug (fun m -> m "Body looks like JSON, trying JSONFeed parser");
+
match Jsonfeed.of_string body with
+
| Ok jsonfeed ->
+
Log.debug (fun m -> m "Successfully parsed as JSONFeed");
+
Json jsonfeed
+
| Error err ->
+
Log.debug (fun m -> m "Not a JSONFeed: %s" (Jsont.Error.to_string err));
+
(* Fall through to XML parsing *)
+
failwith "Not a valid JSONFeed"
+
) else (
+
(* Try XML formats *)
+
try
+
let feed = Atom (Syndic.Atom.parse ~xmlbase (Xmlm.make_input (`String (0, body)))) in
+
Log.debug (fun m -> m "Successfully parsed as Atom feed");
+
feed
+
with
+
| Syndic.Atom.Error.Error (pos, msg) -> (
+
Log.debug (fun m -> m "Not an Atom feed: %s at position (%d, %d)"
+
msg (fst pos) (snd pos));
+
try
+
let feed = Rss2 (Syndic.Rss2.parse ~xmlbase (Xmlm.make_input (`String (0, body)))) in
+
Log.debug (fun m -> m "Successfully parsed as RSS2 feed");
+
feed
+
with Syndic.Rss2.Error.Error (pos, msg) ->
+
Log.err (fun m -> m "Failed to parse as RSS2: %s at position (%d, %d)"
+
msg (fst pos) (snd pos));
+
failwith "Neither Atom nor RSS2 feed")
+
| Not_found as e ->
+
Log.err (fun m -> m "Not_found exception during Atom feed parsing");
+
Log.err (fun m -> m "Backtrace:\n%s" (Printexc.get_backtrace ()));
+
raise e
+
| e ->
+
Log.err (fun m -> m "Unexpected exception during feed parsing: %s"
+
(Printexc.to_string e));
+
Log.err (fun m -> m "Backtrace:\n%s" (Printexc.get_backtrace ()));
+
raise e
+
)
+
+
let fetch session source =
+
Log.info (fun m -> m "Fetching feed: %s" (Source.name source));
+
+
let xmlbase = Uri.of_string (Source.url source) in
+
+
(* Use Requests_json_api.get_result for clean Result-based error handling *)
+
let requests_session = Session.get_requests_session session in
+
let response =
+
match Requests_json_api.get_result requests_session (Source.url source) with
+
| Ok body ->
+
Log.info (fun m -> m "Successfully fetched %s (%d bytes)"
+
(Source.url source) (String.length body));
+
body
+
| Error (status, msg) ->
+
Log.err (fun m -> m "Failed to fetch feed '%s': HTTP %d - %s"
+
(Source.name source) status msg);
+
failwith (Printf.sprintf "HTTP %d: %s" status msg)
+
in
+
+
let content = classify_feed ~xmlbase response in
+
let title =
+
match content with
+
| Atom atom -> Text_extract.string_of_text_construct atom.Syndic.Atom.title
+
| Rss2 ch -> ch.Syndic.Rss2.title
+
| Json jsonfeed -> Jsonfeed.title jsonfeed
+
in
+
+
Log.info (fun m -> m "Successfully fetched %s feed '%s' (title: '%s')"
+
(string_of_feed content) (Source.name source) title);
+
+
{ source; title; content }
+
+
let source t = t.source
+
let content t = t.content
+
let title t = t.title
+43
stack/river/lib/feed.mli
···
···
+
(*
+
* Copyright (c) 2014, OCaml.org project
+
* Copyright (c) 2015 KC Sivaramakrishnan <sk826@cl.cam.ac.uk>
+
*
+
* Permission to use, copy, modify, and distribute this software for any
+
* purpose with or without fee is hereby granted, provided that the above
+
* copyright notice and this permission notice appear in all copies.
+
*
+
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
*)
+
+
(** Feed fetching and parsing. *)
+
+
type feed_content =
+
| Atom of Syndic.Atom.feed
+
| Rss2 of Syndic.Rss2.channel
+
| Json of Jsonfeed.t
+
(** The underlying feed content, which can be Atom, RSS2, or JSONFeed format. *)
+
+
type t
+
(** An Atom, RSS2, or JSON Feed. *)
+
+
val fetch : Session.t -> Source.t -> t
+
(** [fetch session source] fetches and parses a feed from the given source.
+
+
@param session The HTTP session
+
@param source The feed source to fetch
+
@raise Failure if the feed cannot be fetched or parsed *)
+
+
val source : t -> Source.t
+
(** [source feed] returns the source this feed was fetched from. *)
+
+
val content : t -> feed_content
+
(** [content feed] returns the underlying feed content. *)
+
+
val title : t -> string
+
(** [title feed] returns the feed title. *)
+139
stack/river/lib/format.ml
···
···
+
(*
+
* Copyright (c) 2014, OCaml.org project
+
* Copyright (c) 2015 KC Sivaramakrishnan <sk826@cl.cam.ac.uk>
+
*
+
* Permission to use, copy, modify, and distribute this software for any
+
* purpose with or without fee is hereby granted, provided that the above
+
* copyright notice and this permission notice appear in all copies.
+
*
+
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
*)
+
+
(** Feed format conversion and export. *)
+
+
module Atom = struct
+
let entry_of_post post =
+
let content = Syndic.Atom.Html (None, Post.content post) in
+
let contributors =
+
[ Syndic.Atom.author ~uri:(Uri.of_string (Source.url (Feed.source (Post.feed post))))
+
(Source.name (Feed.source (Post.feed post))) ]
+
in
+
let links =
+
match Post.link post with
+
| Some l -> [ Syndic.Atom.link ~rel:Syndic.Atom.Alternate l ]
+
| None -> []
+
in
+
let id =
+
match Post.link post with
+
| Some l -> l
+
| None -> Uri.of_string (Digest.to_hex (Digest.string (Post.title post)))
+
in
+
let authors = (Syndic.Atom.author ~email:(Post.email post) (Post.author post), []) in
+
let title : Syndic.Atom.text_construct = Syndic.Atom.Text (Post.title post) in
+
let updated =
+
match Post.date post with
+
(* Atom entry requires a date but RSS2 does not. So if a date
+
* is not available, just capture the current date. *)
+
| None -> Ptime.of_float_s (Unix.gettimeofday ()) |> Option.get
+
| Some d -> d
+
in
+
Syndic.Atom.entry ~content ~contributors ~links ~id ~authors ~title ~updated
+
()
+
+
let entries_of_posts posts = List.map entry_of_post posts
+
+
let feed_of_entries ~title ?id ?(authors = []) entries =
+
let feed_id = match id with
+
| Some i -> Uri.of_string i
+
| None -> Uri.of_string "urn:river:merged"
+
in
+
let feed_authors = List.map (fun (name, email) ->
+
match email with
+
| Some e -> Syndic.Atom.author ~email:e name
+
| None -> Syndic.Atom.author name
+
) authors in
+
{
+
Syndic.Atom.id = feed_id;
+
title = Syndic.Atom.Text title;
+
updated = Ptime.of_float_s (Unix.time ()) |> Option.get;
+
entries;
+
authors = feed_authors;
+
categories = [];
+
contributors = [];
+
generator = Some {
+
Syndic.Atom.version = Some "1.0";
+
uri = None;
+
content = "River Feed Aggregator";
+
};
+
icon = None;
+
links = [];
+
logo = None;
+
rights = None;
+
subtitle = None;
+
}
+
+
let to_string feed =
+
let output = Buffer.create 4096 in
+
Syndic.Atom.output feed (`Buffer output);
+
Buffer.contents output
+
end
+
+
module Rss2 = struct
+
let of_feed feed =
+
match Feed.content feed with
+
| Feed.Rss2 ch -> Some ch
+
| _ -> None
+
end
+
+
module Jsonfeed = struct
+
let item_of_post post =
+
(* Convert HTML content back to string *)
+
let html = Post.content post in
+
let content = `Html html in
+
+
(* Create author *)
+
let authors =
+
if Post.author post <> "" then
+
let author = Jsonfeed.Author.create ~name:(Post.author post) () in
+
Some [author]
+
else
+
None
+
in
+
+
(* Create item *)
+
Jsonfeed.Item.create
+
~id:(Post.id post)
+
~content
+
?url:(Option.map Uri.to_string (Post.link post))
+
~title:(Post.title post)
+
?summary:(Post.summary post)
+
?date_published:(Post.date post)
+
?authors
+
~tags:(Post.tags post)
+
()
+
+
let items_of_posts posts = List.map item_of_post posts
+
+
let feed_of_items ~title ?home_page_url ?feed_url ?description ?icon ?favicon items =
+
Jsonfeed.create ~title ?home_page_url ?feed_url ?description ?icon ?favicon ~items ()
+
+
let feed_of_posts ~title ?home_page_url ?feed_url ?description ?icon ?favicon posts =
+
let items = items_of_posts posts in
+
feed_of_items ~title ?home_page_url ?feed_url ?description ?icon ?favicon items
+
+
let to_string ?(minify = false) jsonfeed =
+
match Jsonfeed.to_string ~minify jsonfeed with
+
| Ok s -> Ok s
+
| Error err -> Error (Jsont.Error.to_string err)
+
+
let of_feed feed =
+
match Feed.content feed with
+
| Feed.Json jf -> Some jf
+
| _ -> None
+
end
+103
stack/river/lib/format.mli
···
···
+
(*
+
* Copyright (c) 2014, OCaml.org project
+
* Copyright (c) 2015 KC Sivaramakrishnan <sk826@cl.cam.ac.uk>
+
*
+
* Permission to use, copy, modify, and distribute this software for any
+
* purpose with or without fee is hereby granted, provided that the above
+
* copyright notice and this permission notice appear in all copies.
+
*
+
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
*)
+
+
(** Feed format conversion and export. *)
+
+
module Atom : sig
+
(** Atom 1.0 format support. *)
+
+
val entry_of_post : Post.t -> Syndic.Atom.entry
+
(** [entry_of_post post] converts a post to an Atom entry. *)
+
+
val entries_of_posts : Post.t list -> Syndic.Atom.entry list
+
(** [entries_of_posts posts] converts posts to Atom entries. *)
+
+
val feed_of_entries :
+
title:string ->
+
?id:string ->
+
?authors:(string * string option) list ->
+
Syndic.Atom.entry list ->
+
Syndic.Atom.feed
+
(** [feed_of_entries ~title entries] creates an Atom feed from entries.
+
+
@param title The feed title
+
@param id Optional feed ID (default: "urn:river:merged")
+
@param authors Optional list of (name, email) tuples *)
+
+
val to_string : Syndic.Atom.feed -> string
+
(** [to_string feed] serializes an Atom feed to XML string. *)
+
end
+
+
module Rss2 : sig
+
(** RSS 2.0 format support. *)
+
+
val of_feed : Feed.t -> Syndic.Rss2.channel option
+
(** [of_feed feed] extracts RSS2 channel if the feed is RSS2 format.
+
+
Returns None if the feed is not RSS2. *)
+
end
+
+
module Jsonfeed : sig
+
(** JSON Feed 1.1 format support. *)
+
+
val item_of_post : Post.t -> Jsonfeed.Item.t
+
(** [item_of_post post] converts a post to a JSONFeed item. *)
+
+
val items_of_posts : Post.t list -> Jsonfeed.Item.t list
+
(** [items_of_posts posts] converts posts to JSONFeed items. *)
+
+
val feed_of_items :
+
title:string ->
+
?home_page_url:string ->
+
?feed_url:string ->
+
?description:string ->
+
?icon:string ->
+
?favicon:string ->
+
Jsonfeed.Item.t list ->
+
Jsonfeed.t
+
(** [feed_of_items ~title items] creates a JSONFeed from items.
+
+
@param title The feed title (required)
+
@param home_page_url The URL of the website the feed represents
+
@param feed_url The URL of the feed itself
+
@param description A description of the feed
+
@param icon URL of an icon for the feed (512x512 recommended)
+
@param favicon URL of a favicon for the feed (64x64 recommended) *)
+
+
val feed_of_posts :
+
title:string ->
+
?home_page_url:string ->
+
?feed_url:string ->
+
?description:string ->
+
?icon:string ->
+
?favicon:string ->
+
Post.t list ->
+
Jsonfeed.t
+
(** [feed_of_posts ~title posts] creates a JSONFeed from posts.
+
+
Convenience function that combines [items_of_posts] and [feed_of_items]. *)
+
+
val to_string : ?minify:bool -> Jsonfeed.t -> (string, string) result
+
(** [to_string ?minify feed] serializes a JSONFeed to JSON string.
+
+
@param minify If true, output compact JSON; if false, pretty-print (default: false) *)
+
+
val of_feed : Feed.t -> Jsonfeed.t option
+
(** [of_feed feed] extracts JSONFeed if the feed is JSONFeed format.
+
+
Returns None if the feed is not JSONFeed. *)
+
end
+330
stack/river/lib/html_markdown.ml
···
···
+
(*
+
* Copyright (c) 2014, OCaml.org project
+
* Copyright (c) 2015 KC Sivaramakrishnan <sk826@cl.cam.ac.uk>
+
*
+
* Permission to use, copy, modify, and distribute this software for any
+
* purpose with or without fee is hereby granted, provided that the above
+
* copyright notice and this permission notice appear in all copies.
+
*
+
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
*)
+
+
(** Internal utility for HTML to Markdown conversion *)
+
+
[@@@warning "-32"] (* Suppress unused value warnings for internal utilities *)
+
+
(** HTML to Markdown converter using Lambda Soup *)
+
+
(** Extract all links from HTML content *)
+
let extract_links html_str =
+
try
+
let soup = Soup.parse html_str in
+
let links = Soup.select "a[href]" soup in
+
Soup.fold (fun acc link ->
+
match Soup.attribute "href" link with
+
| Some href ->
+
let text = Soup.texts link |> String.concat "" |> String.trim in
+
(href, text) :: acc
+
| None -> acc
+
) [] links
+
|> List.rev
+
with _ -> []
+
+
(** Check if string contains any whitespace *)
+
let has_whitespace s =
+
try
+
let _ = Str.search_forward (Str.regexp "[ \t\n\r]") s 0 in
+
true
+
with Not_found -> false
+
+
(** Clean up excessive newlines and normalize spacing *)
+
let cleanup_markdown s =
+
(* Normalize line endings *)
+
let s = Str.global_replace (Str.regexp "\r\n") "\n" s in
+
+
(* Remove trailing whitespace from each line *)
+
let lines = String.split_on_char '\n' s in
+
let lines = List.map (fun line ->
+
(* Trim trailing spaces but preserve leading spaces for indentation *)
+
let len = String.length line in
+
let rec find_last_non_space i =
+
if i < 0 then -1
+
else if line.[i] = ' ' || line.[i] = '\t' then find_last_non_space (i - 1)
+
else i
+
in
+
let last = find_last_non_space (len - 1) in
+
if last < 0 then ""
+
else String.sub line 0 (last + 1)
+
) lines in
+
+
(* Join back and collapse excessive blank lines *)
+
let s = String.concat "\n" lines in
+
+
(* Replace 3+ consecutive newlines with just 2 *)
+
let s = Str.global_replace (Str.regexp "\n\n\n+") "\n\n" s in
+
+
(* Trim leading and trailing whitespace *)
+
String.trim s
+
+
(** Convert HTML to Markdown using state-based whitespace handling *)
+
let html_to_markdown html_str =
+
try
+
let soup = Soup.parse html_str in
+
let buffer = Buffer.create 256 in
+
+
(* State: track if we need to insert a space before next text *)
+
let need_space = ref false in
+
+
(* Get last character in buffer, if any *)
+
let last_char () =
+
let len = Buffer.length buffer in
+
if len = 0 then None
+
else Some (Buffer.nth buffer (len - 1))
+
in
+
+
(* Add text with proper spacing *)
+
let add_text text =
+
let trimmed = String.trim text in
+
if trimmed <> "" then begin
+
(* Check if text starts with punctuation that shouldn't have space before it *)
+
let starts_with_punctuation =
+
String.length trimmed > 0 &&
+
(match trimmed.[0] with
+
| ',' | '.' | ';' | ':' | '!' | '?' | ')' | ']' | '}' -> true
+
| _ -> false)
+
in
+
+
(* Add space if needed, unless we're before punctuation *)
+
if !need_space && not starts_with_punctuation then begin
+
match last_char () with
+
| Some (' ' | '\n') -> ()
+
| _ -> Buffer.add_char buffer ' '
+
end;
+
Buffer.add_string buffer trimmed;
+
need_space := false
+
end
+
in
+
+
(* Mark that we need space before next text (for inline elements) *)
+
let mark_space_needed () =
+
need_space := has_whitespace (Buffer.contents buffer) || Buffer.length buffer > 0
+
in
+
+
(* Process header with ID/anchor handling *)
+
let process_header level elem =
+
need_space := false;
+
+
(* Check if header contains a link with an ID fragment *)
+
let link_opt = Soup.select_one "a[href]" elem in
+
let anchor_id = match link_opt with
+
| Some link ->
+
(match Soup.attribute "href" link with
+
| Some href ->
+
(* Extract fragment from URL *)
+
let uri = Uri.of_string href in
+
Uri.fragment uri
+
| None -> None)
+
| None -> None
+
in
+
+
(* Add anchor if we found an ID *)
+
(match anchor_id with
+
| Some id when id <> "" ->
+
Buffer.add_string buffer (Printf.sprintf "\n<a name=\"%s\"></a>\n" id)
+
| _ -> ());
+
+
(* Add the header marker *)
+
let marker = String.make level '#' in
+
Buffer.add_string buffer ("\n" ^ marker ^ " ");
+
+
(* Get text content, excluding link tags *)
+
let text = Soup.texts elem |> String.concat " " |> String.trim in
+
Buffer.add_string buffer text;
+
+
Buffer.add_string buffer "\n\n";
+
need_space := false
+
in
+
+
let rec process_node node =
+
match Soup.element node with
+
| Some elem ->
+
let tag = Soup.name elem in
+
(match tag with
+
(* Block elements - reset space tracking *)
+
| "h1" -> process_header 1 elem
+
| "h2" -> process_header 2 elem
+
| "h3" -> process_header 3 elem
+
| "h4" -> process_header 4 elem
+
| "h5" -> process_header 5 elem
+
| "h6" -> process_header 6 elem
+
| "p" ->
+
need_space := false;
+
Soup.children elem |> Soup.iter process_node;
+
Buffer.add_string buffer "\n\n";
+
need_space := false
+
| "br" ->
+
Buffer.add_string buffer "\n";
+
need_space := false
+
(* Inline elements - preserve space tracking *)
+
| "strong" | "b" ->
+
(* Add space before if needed *)
+
if !need_space then begin
+
match last_char () with
+
| Some (' ' | '\n') -> ()
+
| _ -> Buffer.add_char buffer ' '
+
end;
+
Buffer.add_string buffer "**";
+
need_space := false;
+
Soup.children elem |> Soup.iter process_node;
+
Buffer.add_string buffer "**";
+
mark_space_needed ()
+
| "em" | "i" ->
+
(* Add space before if needed *)
+
if !need_space then begin
+
match last_char () with
+
| Some (' ' | '\n') -> ()
+
| _ -> Buffer.add_char buffer ' '
+
end;
+
Buffer.add_string buffer "*";
+
need_space := false;
+
Soup.children elem |> Soup.iter process_node;
+
Buffer.add_string buffer "*";
+
mark_space_needed ()
+
| "code" ->
+
(* Add space before if needed *)
+
if !need_space then begin
+
match last_char () with
+
| Some (' ' | '\n') -> ()
+
| _ -> Buffer.add_char buffer ' '
+
end;
+
Buffer.add_string buffer "`";
+
need_space := false;
+
Soup.children elem |> Soup.iter process_node;
+
Buffer.add_string buffer "`";
+
mark_space_needed ()
+
| "pre" ->
+
need_space := false;
+
Buffer.add_string buffer "\n```\n";
+
Soup.children elem |> Soup.iter process_node;
+
Buffer.add_string buffer "\n```\n\n";
+
need_space := false
+
| "a" ->
+
let text = Soup.texts elem |> String.concat " " |> String.trim in
+
let href = Soup.attribute "href" elem in
+
(match href with
+
| Some href ->
+
(* Add space before link if needed *)
+
if !need_space then begin
+
match last_char () with
+
| Some (' ' | '\n') -> ()
+
| _ -> Buffer.add_char buffer ' '
+
end;
+
need_space := false;
+
+
(* Add the link markdown *)
+
if text = "" then
+
Buffer.add_string buffer (Printf.sprintf "<%s>" href)
+
else
+
Buffer.add_string buffer (Printf.sprintf "[%s](%s)" text href);
+
+
(* Mark that space may be needed after link *)
+
mark_space_needed ()
+
| None ->
+
add_text text)
+
| "ul" | "ol" ->
+
need_space := false;
+
Buffer.add_string buffer "\n";
+
let is_ordered = tag = "ol" in
+
let items = Soup.children elem |> Soup.to_list in
+
List.iteri (fun i item ->
+
match Soup.element item with
+
| Some li when Soup.name li = "li" ->
+
need_space := false;
+
if is_ordered then
+
Buffer.add_string buffer (Printf.sprintf "%d. " (i + 1))
+
else
+
Buffer.add_string buffer "- ";
+
Soup.children li |> Soup.iter process_node;
+
Buffer.add_string buffer "\n"
+
| _ -> ()
+
) items;
+
Buffer.add_string buffer "\n";
+
need_space := false
+
| "blockquote" ->
+
need_space := false;
+
Buffer.add_string buffer "\n> ";
+
Soup.children elem |> Soup.iter process_node;
+
Buffer.add_string buffer "\n\n";
+
need_space := false
+
| "img" ->
+
(* Add space before if needed *)
+
if !need_space then begin
+
match last_char () with
+
| Some (' ' | '\n') -> ()
+
| _ -> Buffer.add_char buffer ' '
+
end;
+
let alt = Soup.attribute "alt" elem |> Option.value ~default:"" in
+
let src = Soup.attribute "src" elem |> Option.value ~default:"" in
+
Buffer.add_string buffer (Printf.sprintf "![%s](%s)" alt src);
+
need_space := false;
+
mark_space_needed ()
+
| "hr" ->
+
need_space := false;
+
Buffer.add_string buffer "\n---\n\n";
+
need_space := false
+
(* Strip these tags but keep content *)
+
| "div" | "span" | "article" | "section" | "header" | "footer"
+
| "main" | "nav" | "aside" | "figure" | "figcaption" | "details" | "summary" ->
+
Soup.children elem |> Soup.iter process_node
+
(* Ignore script, style, etc *)
+
| "script" | "style" | "noscript" -> ()
+
(* Default: just process children *)
+
| _ ->
+
Soup.children elem |> Soup.iter process_node)
+
| None ->
+
(* Text node - handle whitespace properly *)
+
match Soup.leaf_text node with
+
| Some text ->
+
(* If text is only whitespace, mark that we need space *)
+
let trimmed = String.trim text in
+
if trimmed = "" then begin
+
if has_whitespace text then
+
need_space := true
+
end else begin
+
(* Text has content - check if it had leading/trailing whitespace *)
+
let had_leading_ws = has_whitespace text &&
+
(String.length text > 0 &&
+
(text.[0] = ' ' || text.[0] = '\t' || text.[0] = '\n' || text.[0] = '\r')) in
+
+
(* If had leading whitespace, mark we need space *)
+
if had_leading_ws then need_space := true;
+
+
(* Add the text content *)
+
add_text trimmed;
+
+
(* If had trailing whitespace, mark we need space for next *)
+
let had_trailing_ws = has_whitespace text &&
+
(String.length text > 0 &&
+
let last = text.[String.length text - 1] in
+
last = ' ' || last = '\t' || last = '\n' || last = '\r') in
+
if had_trailing_ws then need_space := true
+
end
+
| None -> ()
+
in
+
+
Soup.children soup |> Soup.iter process_node;
+
+
(* Clean up the result *)
+
let result = Buffer.contents buffer in
+
cleanup_markdown result
+
with _ -> html_str
+
+
(** Convert HTML content to clean Markdown *)
+
let to_markdown html_str =
+
html_to_markdown html_str
+84
stack/river/lib/html_meta.ml
···
···
+
(*
+
* Copyright (c) 2014, OCaml.org project
+
* Copyright (c) 2015 KC Sivaramakrishnan <sk826@cl.cam.ac.uk>
+
*
+
* Permission to use, copy, modify, and distribute this software for any
+
* purpose with or without fee is hereby granted, provided that the above
+
* copyright notice and this permission notice appear in all copies.
+
*
+
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
*)
+
+
(** Internal utility for HTML meta tag extraction *)
+
+
[@@@warning "-32"] (* Suppress unused value warnings for internal utilities *)
+
+
(** This module determines an image to be used as preview of a website.
+
+
It does this by following the same logic Google+ and other websites use, and
+
described in this article:
+
https://www.raymondcamden.com/2011/07/26/How-are-Facebook-and-Google-creating-link-previews *)
+
+
let og_image html =
+
let open Soup in
+
let soup = parse html in
+
try soup $ "meta[property=og:image]" |> R.attribute "content" |> Option.some
+
with Failure _ -> None
+
+
let image_src html =
+
let open Soup in
+
let soup = parse html in
+
try soup $ "link[rel=\"image_src\"]" |> R.attribute "href" |> Option.some
+
with Failure _ -> None
+
+
let twitter_image html =
+
let open Soup in
+
let soup = parse html in
+
try
+
soup $ "meta[name=\"twitter:image\"]" |> R.attribute "content"
+
|> Option.some
+
with Failure _ -> None
+
+
let og_description html =
+
let open Soup in
+
let soup = parse html in
+
try
+
soup $ "meta[property=og:description]" |> R.attribute "content"
+
|> Option.some
+
with Failure _ -> None
+
+
let description html =
+
let open Soup in
+
let soup = parse html in
+
try
+
soup $ "meta[property=description]" |> R.attribute "content" |> Option.some
+
with Failure _ -> None
+
+
let preview_image html =
+
let preview_image =
+
match og_image html with
+
| None -> (
+
match image_src html with
+
| None -> twitter_image html
+
| Some x -> Some x)
+
| Some x -> Some x
+
in
+
match Option.map String.trim preview_image with
+
| Some "" -> None
+
| Some x -> Some x
+
| None -> None
+
+
let description html =
+
let preview_image =
+
match og_description html with None -> description html | Some x -> Some x
+
in
+
match Option.map String.trim preview_image with
+
| Some "" -> None
+
| Some x -> Some x
+
| None -> None
+393
stack/river/lib/post.ml
···
···
+
(*
+
* Copyright (c) 2014, OCaml.org project
+
* Copyright (c) 2015 KC Sivaramakrishnan <sk826@cl.cam.ac.uk>
+
*
+
* Permission to use, copy, modify, and distribute this software for any
+
* purpose with or without fee is hereby granted, provided that the above
+
* copyright notice and this permission notice appear in all copies.
+
*
+
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
*)
+
+
(** Post representation and extraction from feeds. *)
+
+
let src = Logs.Src.create "river" ~doc:"River RSS/Atom aggregator"
+
module Log = (val Logs.src_log src : Logs.LOG)
+
+
type t = {
+
id : string;
+
title : string;
+
link : Uri.t option;
+
date : Syndic.Date.t option;
+
feed : Feed.t;
+
author : string;
+
email : string;
+
content : Soup.soup Soup.node;
+
mutable link_response : (string, string) result option;
+
tags : string list;
+
summary : string option;
+
}
+
+
(** Generate a stable, unique ID from available data *)
+
let generate_id ?guid ?link ?title ?date ~feed_url () =
+
match guid with
+
| Some id when id <> "" ->
+
(* Use explicit ID/GUID if available *)
+
id
+
| _ ->
+
match link with
+
| Some uri when Uri.to_string uri <> "" ->
+
(* Use permalink as ID (stable and unique) *)
+
Uri.to_string uri
+
| _ ->
+
(* Fallback: hash of feed_url + title + date *)
+
let title_str = Option.value title ~default:"" in
+
let date_str =
+
match date with
+
| Some d -> Ptime.to_rfc3339 d
+
| None -> ""
+
in
+
let composite = Printf.sprintf "%s|%s|%s" feed_url title_str date_str in
+
(* Use SHA256 for stable hashing *)
+
Digest.string composite |> Digest.to_hex
+
+
let resolve_links_attr ~xmlbase attr el =
+
Soup.R.attribute attr el
+
|> Uri.of_string
+
|> Syndic.XML.resolve ~xmlbase
+
|> Uri.to_string
+
|> fun value -> Soup.set_attribute attr value el
+
+
(* Things that posts should not contain *)
+
let undesired_tags = [ "style"; "script" ]
+
let undesired_attr = [ "id" ]
+
+
let html_of_text ?xmlbase s =
+
let soup = Soup.parse s in
+
let ($$) = Soup.($$) in
+
soup $$ "a[href]" |> Soup.iter (resolve_links_attr ~xmlbase "href");
+
soup $$ "img[src]" |> Soup.iter (resolve_links_attr ~xmlbase "src");
+
undesired_tags |> List.iter (fun tag -> soup $$ tag |> Soup.iter Soup.delete);
+
soup $$ "*" |> Soup.iter (fun el ->
+
undesired_attr |> List.iter (fun attr -> Soup.delete_attribute attr el));
+
soup
+
+
(* Do not trust sites using XML for HTML content. Convert to string and parse
+
back. (Does not always fix bad HTML unfortunately.) *)
+
let html_of_syndic =
+
let ns_prefix _ = Some "" in
+
fun ?xmlbase h ->
+
html_of_text ?xmlbase
+
(String.concat "" (List.map (Syndic.XML.to_string ~ns_prefix) h))
+
+
let string_of_option = function None -> "" | Some s -> s
+
+
let post_compare p1 p2 =
+
(* Most recent posts first. Posts with no date are always last *)
+
match (p1.date, p2.date) with
+
| Some d1, Some d2 -> Syndic.Date.compare d2 d1
+
| None, Some _ -> 1
+
| Some _, None -> -1
+
| None, None -> 1
+
+
let rec remove n l =
+
if n <= 0 then l else match l with [] -> [] | _ :: tl -> remove (n - 1) tl
+
+
let rec take n = function
+
| [] -> []
+
| e :: tl -> if n > 0 then e :: take (n - 1) tl else []
+
+
let post_of_atom ~(feed : Feed.t) (e : Syndic.Atom.entry) =
+
Log.debug (fun m -> m "Processing Atom entry: %s"
+
(Text_extract.string_of_text_construct e.title));
+
+
let link =
+
try
+
Some
+
(List.find (fun l -> l.Syndic.Atom.rel = Syndic.Atom.Alternate) e.links)
+
.href
+
with Not_found -> (
+
Log.debug (fun m -> m "No alternate link found, trying fallback");
+
match e.links with
+
| l :: _ -> Some l.href
+
| [] -> (
+
match Uri.scheme e.id with
+
| Some "http" -> Some e.id
+
| Some "https" -> Some e.id
+
| _ -> None))
+
in
+
let date =
+
match e.published with Some _ -> e.published | None -> Some e.updated
+
in
+
let content =
+
match e.content with
+
| Some (Text s) -> html_of_text s
+
| Some (Html (xmlbase, s)) -> html_of_text ?xmlbase s
+
| Some (Xhtml (xmlbase, h)) -> html_of_syndic ?xmlbase h
+
| Some (Mime _) | Some (Src _) | None -> (
+
match e.summary with
+
| Some (Text s) -> html_of_text s
+
| Some (Html (xmlbase, s)) -> html_of_text ?xmlbase s
+
| Some (Xhtml (xmlbase, h)) -> html_of_syndic ?xmlbase h
+
| None -> Soup.parse "")
+
in
+
let is_valid_author_name name =
+
(* Filter out empty strings and placeholder values like "Unknown" *)
+
let trimmed = String.trim name in
+
trimmed <> "" && trimmed <> "Unknown"
+
in
+
let author_name =
+
(* Fallback chain for author:
+
1. Entry author (if present, not empty, and not "Unknown")
+
2. Feed-level author (from Atom feed metadata)
+
3. Feed title (from Atom feed metadata)
+
4. Source name (manually entered feed name) *)
+
try
+
let author, _ = e.authors in
+
let trimmed = String.trim author.name in
+
if is_valid_author_name author.name then trimmed
+
else raise Not_found (* Try feed-level author *)
+
with Not_found -> (
+
match Feed.content feed with
+
| Feed.Atom atom_feed -> (
+
(* Try feed-level authors *)
+
match atom_feed.Syndic.Atom.authors with
+
| author :: _ when is_valid_author_name author.name ->
+
String.trim author.name
+
| _ ->
+
(* Use feed title *)
+
Text_extract.string_of_text_construct atom_feed.Syndic.Atom.title)
+
| Feed.Rss2 _ | Feed.Json _ ->
+
(* For RSS2 and JSONFeed, use the source name *)
+
Source.name (Feed.source feed))
+
in
+
(* Extract tags from Atom categories *)
+
let tags =
+
List.map (fun cat -> cat.Syndic.Atom.term) e.categories
+
in
+
(* Extract summary - convert from text_construct to string *)
+
let summary =
+
match e.summary with
+
| Some s -> Some (Text_extract.string_of_text_construct s)
+
| None -> None
+
in
+
(* Generate unique ID *)
+
let guid = Uri.to_string e.id in
+
let title_str = Text_extract.string_of_text_construct e.title in
+
let id =
+
generate_id ~guid ?link ~title:title_str ?date
+
~feed_url:(Source.url (Feed.source feed)) ()
+
in
+
{
+
id;
+
title = title_str;
+
link;
+
date;
+
feed;
+
author = author_name;
+
email = "";
+
content;
+
link_response = None;
+
tags;
+
summary;
+
}
+
+
let post_of_rss2 ~(feed : Feed.t) it =
+
let title, content =
+
match it.Syndic.Rss2.story with
+
| All (t, xmlbase, d) -> (
+
( t,
+
match it.content with
+
| _, "" -> html_of_text ?xmlbase d
+
| xmlbase, c -> html_of_text ?xmlbase c ))
+
| Title t ->
+
let xmlbase, c = it.content in
+
(t, html_of_text ?xmlbase c)
+
| Description (xmlbase, d) -> (
+
( "",
+
match it.content with
+
| _, "" -> html_of_text ?xmlbase d
+
| xmlbase, c -> html_of_text ?xmlbase c ))
+
in
+
(* Note: it.link is of type Uri.t option in Syndic *)
+
let link =
+
match (it.guid, it.link) with
+
| Some u, _ when u.permalink -> Some u.data
+
| _, Some _ -> it.link
+
| Some u, _ ->
+
(* Sometimes the guid is indicated with isPermaLink="false" but is
+
nonetheless the only URL we get (e.g. ocamlpro). *)
+
Some u.data
+
| None, None -> None
+
in
+
(* Extract GUID string for ID generation *)
+
let guid_str =
+
match it.guid with
+
| Some u -> Some (Uri.to_string u.data)
+
| None -> None
+
in
+
(* RSS2 doesn't have a categories field exposed, use empty list *)
+
let tags = [] in
+
(* RSS2 doesn't have a separate summary field, so leave it empty *)
+
let summary = None in
+
(* Generate unique ID *)
+
let id =
+
generate_id ?guid:guid_str ?link ~title ?date:it.pubDate
+
~feed_url:(Source.url (Feed.source feed)) ()
+
in
+
{
+
id;
+
title;
+
link;
+
feed;
+
author = Source.name (Feed.source feed);
+
email = string_of_option it.author;
+
content;
+
date = it.pubDate;
+
link_response = None;
+
tags;
+
summary;
+
}
+
+
let post_of_jsonfeed_item ~(feed : Feed.t) (item : Jsonfeed.Item.t) =
+
Log.debug (fun m -> m "Processing JSONFeed item: %s"
+
(Option.value (Jsonfeed.Item.title item) ~default:"Untitled"));
+
+
(* Extract content - prefer HTML, fall back to text *)
+
let content =
+
match Jsonfeed.Item.content item with
+
| `Html html -> html_of_text html
+
| `Text text -> html_of_text text
+
| `Both (html, _text) -> html_of_text html
+
in
+
+
(* Extract author - use first author if multiple *)
+
let author_name, author_email =
+
match Jsonfeed.Item.authors item with
+
| Some (first :: _) ->
+
let name = Jsonfeed.Author.name first |> Option.value ~default:"" in
+
(* JSONFeed authors don't typically have email *)
+
(name, "")
+
| _ ->
+
(* Fall back to feed-level authors or feed title *)
+
(match Feed.content feed with
+
| Feed.Json jsonfeed ->
+
(match Jsonfeed.authors jsonfeed with
+
| Some (first :: _) ->
+
let name = Jsonfeed.Author.name first |> Option.value ~default:(Feed.title feed) in
+
(name, "")
+
| _ -> (Feed.title feed, ""))
+
| _ -> (Feed.title feed, ""))
+
in
+
+
(* Link - use url field *)
+
let link =
+
Jsonfeed.Item.url item
+
|> Option.map Uri.of_string
+
in
+
+
(* Date *)
+
let date = Jsonfeed.Item.date_published item in
+
+
(* Summary *)
+
let summary = Jsonfeed.Item.summary item in
+
+
(* Tags *)
+
let tags =
+
Jsonfeed.Item.tags item
+
|> Option.value ~default:[]
+
in
+
+
(* Generate unique ID - JSONFeed items always have an id field (required) *)
+
let guid = Jsonfeed.Item.id item in
+
let title_str = Jsonfeed.Item.title item |> Option.value ~default:"Untitled" in
+
let id =
+
generate_id ~guid ?link ~title:title_str ?date
+
~feed_url:(Source.url (Feed.source feed)) ()
+
in
+
+
{
+
id;
+
title = title_str;
+
link;
+
date;
+
feed;
+
author = author_name;
+
email = author_email;
+
content;
+
link_response = None;
+
tags;
+
summary;
+
}
+
+
let posts_of_feed c =
+
match Feed.content c with
+
| Feed.Atom f ->
+
let posts = List.map (post_of_atom ~feed:c) f.Syndic.Atom.entries in
+
Log.debug (fun m -> m "Extracted %d posts from Atom feed '%s'"
+
(List.length posts) (Source.name (Feed.source c)));
+
posts
+
| Feed.Rss2 ch ->
+
let posts = List.map (post_of_rss2 ~feed:c) ch.Syndic.Rss2.items in
+
Log.debug (fun m -> m "Extracted %d posts from RSS2 feed '%s'"
+
(List.length posts) (Source.name (Feed.source c)));
+
posts
+
| Feed.Json jsonfeed ->
+
let items = Jsonfeed.items jsonfeed in
+
let posts = List.map (post_of_jsonfeed_item ~feed:c) items in
+
Log.debug (fun m -> m "Extracted %d posts from JSONFeed '%s'"
+
(List.length posts) (Source.name (Feed.source c)));
+
posts
+
+
let get_posts ?n ?(ofs = 0) planet_feeds =
+
Log.info (fun m -> m "Processing %d feeds for posts" (List.length planet_feeds));
+
+
let posts = List.concat @@ List.map posts_of_feed planet_feeds in
+
Log.debug (fun m -> m "Total posts collected: %d" (List.length posts));
+
+
let posts = List.sort post_compare posts in
+
Log.debug (fun m -> m "Posts sorted by date (most recent first)");
+
+
let posts = remove ofs posts in
+
let result =
+
match n with
+
| None ->
+
Log.debug (fun m -> m "Returning all %d posts (offset=%d)"
+
(List.length posts) ofs);
+
posts
+
| Some n ->
+
let limited = take n posts in
+
Log.debug (fun m -> m "Returning %d posts (requested=%d, offset=%d)"
+
(List.length limited) n ofs);
+
limited
+
in
+
result
+
+
let of_feeds feeds = get_posts feeds
+
+
let feed t = t.feed
+
let title t = t.title
+
let link t = t.link
+
let date t = t.date
+
let author t = t.author
+
let email t = t.email
+
let content t = Soup.to_string t.content
+
let id t = t.id
+
let tags t = t.tags
+
let summary t = t.summary
+
+
let meta_description _t =
+
(* TODO: This requires environment for HTTP access *)
+
Log.debug (fun m -> m "meta_description not implemented (requires environment)");
+
None
+
+
let seo_image _t =
+
(* TODO: This requires environment for HTTP access *)
+
Log.debug (fun m -> m "seo_image not implemented (requires environment)");
+
None
+68
stack/river/lib/post.mli
···
···
+
(*
+
* Copyright (c) 2014, OCaml.org project
+
* Copyright (c) 2015 KC Sivaramakrishnan <sk826@cl.cam.ac.uk>
+
*
+
* Permission to use, copy, modify, and distribute this software for any
+
* purpose with or without fee is hereby granted, provided that the above
+
* copyright notice and this permission notice appear in all copies.
+
*
+
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
*)
+
+
(** Post representation and extraction from feeds. *)
+
+
type t
+
(** A post from a feed. *)
+
+
val of_feeds : Feed.t list -> t list
+
(** [of_feeds feeds] extracts and deduplicates posts from the given feeds.
+
+
Posts are deduplicated by ID. *)
+
+
val feed : t -> Feed.t
+
(** [feed post] returns the feed this post originated from. *)
+
+
val title : t -> string
+
(** [title post] returns the post title. *)
+
+
val link : t -> Uri.t option
+
(** [link post] returns the post link. *)
+
+
val date : t -> Syndic.Date.t option
+
(** [date post] returns the post date. *)
+
+
val author : t -> string
+
(** [author post] returns the post author name. *)
+
+
val email : t -> string
+
(** [email post] returns the post author email. *)
+
+
val content : t -> string
+
(** [content post] returns the post content. *)
+
+
val id : t -> string
+
(** [id post] returns the unique identifier of the post. *)
+
+
val tags : t -> string list
+
(** [tags post] returns the list of tags associated with the post. *)
+
+
val summary : t -> string option
+
(** [summary post] returns the summary/excerpt of the post, if available. *)
+
+
val meta_description : t -> string option
+
(** [meta_description post] returns the meta description from the origin site.
+
+
To get the meta description, we fetch the content of [link post] and look
+
for an HTML meta tag with name "description" or "og:description". *)
+
+
val seo_image : t -> string option
+
(** [seo_image post] returns the social media image URL.
+
+
To get the SEO image, we fetch the content of [link post] and look for an
+
HTML meta tag with name "og:image" or "twitter:image". *)
+192
stack/river/lib/quality.ml
···
···
+
(*
+
* Copyright (c) 2014, OCaml.org project
+
* Copyright (c) 2015 KC Sivaramakrishnan <sk826@cl.cam.ac.uk>
+
*
+
* Permission to use, copy, modify, and distribute this software for any
+
* purpose with or without fee is hereby granted, provided that the above
+
* copyright notice and this permission notice appear in all copies.
+
*
+
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
*)
+
+
(** Feed quality analysis. *)
+
+
type t = {
+
total_entries : int;
+
entries_with_summary : int;
+
entries_with_author : int;
+
entries_with_date : int;
+
entries_with_content : int;
+
entries_with_tags : int;
+
avg_content_length : float;
+
min_content_length : int;
+
max_content_length : int;
+
posting_frequency_days : float option;
+
quality_score : float;
+
}
+
+
let make ~total_entries ~entries_with_summary ~entries_with_author
+
~entries_with_date ~entries_with_content ~entries_with_tags
+
~avg_content_length ~min_content_length ~max_content_length
+
~posting_frequency_days ~quality_score =
+
{
+
total_entries;
+
entries_with_summary;
+
entries_with_author;
+
entries_with_date;
+
entries_with_content;
+
entries_with_tags;
+
avg_content_length;
+
min_content_length;
+
max_content_length;
+
posting_frequency_days;
+
quality_score;
+
}
+
+
let total_entries t = t.total_entries
+
let entries_with_summary t = t.entries_with_summary
+
let entries_with_author t = t.entries_with_author
+
let entries_with_date t = t.entries_with_date
+
let entries_with_content t = t.entries_with_content
+
let entries_with_tags t = t.entries_with_tags
+
let avg_content_length t = t.avg_content_length
+
let min_content_length t = t.min_content_length
+
let max_content_length t = t.max_content_length
+
let posting_frequency_days t = t.posting_frequency_days
+
let quality_score t = t.quality_score
+
+
(** Get content length from an Atom entry *)
+
let get_content_length (entry : Syndic.Atom.entry) =
+
match entry.content with
+
| Some (Syndic.Atom.Text s) -> String.length s
+
| Some (Syndic.Atom.Html (_, s)) -> String.length s
+
| Some (Syndic.Atom.Xhtml (_, _)) -> 0 (* Could calculate but complex *)
+
| Some (Syndic.Atom.Mime _) -> 0
+
| Some (Syndic.Atom.Src _) -> 0
+
| None -> (
+
match entry.summary with
+
| Some (Syndic.Atom.Text s) -> String.length s
+
| Some (Syndic.Atom.Html (_, s)) -> String.length s
+
| Some (Syndic.Atom.Xhtml (_, _)) -> 0
+
| None -> 0)
+
+
(** Check if entry has non-empty summary *)
+
let has_summary (entry : Syndic.Atom.entry) =
+
match entry.summary with
+
| Some (Syndic.Atom.Text s) when String.trim s <> "" -> true
+
| Some (Syndic.Atom.Html (_, s)) when String.trim s <> "" -> true
+
| Some (Syndic.Atom.Xhtml (_, _)) -> true
+
| _ -> false
+
+
(** Check if entry has author *)
+
let has_author (entry : Syndic.Atom.entry) =
+
let (author, _) = entry.authors in
+
String.trim author.name <> ""
+
+
(** Check if entry has content *)
+
let has_content (entry : Syndic.Atom.entry) =
+
get_content_length entry > 0
+
+
(** Check if entry has tags/categories *)
+
let has_tags (entry : Syndic.Atom.entry) =
+
entry.categories <> []
+
+
(** Calculate quality score from metrics *)
+
let calculate_quality_score t =
+
let total = float_of_int t.total_entries in
+
if total = 0.0 then 0.0
+
else
+
let summary_pct = float_of_int t.entries_with_summary /. total *. 100.0 in
+
let author_pct = float_of_int t.entries_with_author /. total *. 100.0 in
+
let date_pct = float_of_int t.entries_with_date /. total *. 100.0 in
+
let content_pct = float_of_int t.entries_with_content /. total *. 100.0 in
+
let tags_pct = float_of_int t.entries_with_tags /. total *. 100.0 in
+
+
(* Weighted average: content and dates are most important *)
+
let score =
+
(content_pct *. 0.30) +.
+
(date_pct *. 0.25) +.
+
(author_pct *. 0.20) +.
+
(summary_pct *. 0.15) +.
+
(tags_pct *. 0.10)
+
in
+
score
+
+
let analyze entries =
+
if entries = [] then
+
failwith "No entries to analyze"
+
else
+
let total_entries = List.length entries in
+
+
let entries_with_summary = ref 0 in
+
let entries_with_author = ref 0 in
+
let entries_with_date = ref total_entries in (* All Atom entries have updated *)
+
let entries_with_content = ref 0 in
+
let entries_with_tags = ref 0 in
+
let content_lengths = ref [] in
+
let dates = ref [] in
+
+
List.iter (fun (entry : Syndic.Atom.entry) ->
+
if has_summary entry then incr entries_with_summary;
+
if has_author entry then incr entries_with_author;
+
if has_content entry then begin
+
incr entries_with_content;
+
content_lengths := get_content_length entry :: !content_lengths
+
end;
+
if has_tags entry then incr entries_with_tags;
+
dates := entry.updated :: !dates
+
) entries;
+
+
(* Calculate content statistics *)
+
let avg_content_length, min_content_length, max_content_length =
+
if !content_lengths = [] then
+
(0.0, 0, 0)
+
else
+
let sorted = List.sort compare !content_lengths in
+
let sum = List.fold_left (+) 0 sorted in
+
let avg = float_of_int sum /. float_of_int (List.length sorted) in
+
let min_len = List.hd sorted in
+
let max_len = List.hd (List.rev sorted) in
+
(avg, min_len, max_len)
+
in
+
+
(* Calculate posting frequency *)
+
let posting_frequency_days =
+
if List.length !dates < 2 then
+
None
+
else
+
try
+
let timestamps = List.map Ptime.to_float_s !dates in
+
let sorted_timestamps = List.sort compare timestamps in
+
let first = List.hd sorted_timestamps in
+
let last = List.hd (List.rev sorted_timestamps) in
+
let total_days = (last -. first) /. 86400.0 in
+
let num_intervals = float_of_int (List.length sorted_timestamps - 1) in
+
Some (total_days /. num_intervals)
+
with _ -> None
+
in
+
+
(* Create metrics record (without quality_score first) *)
+
let metrics = {
+
total_entries;
+
entries_with_summary = !entries_with_summary;
+
entries_with_author = !entries_with_author;
+
entries_with_date = !entries_with_date;
+
entries_with_content = !entries_with_content;
+
entries_with_tags = !entries_with_tags;
+
avg_content_length;
+
min_content_length;
+
max_content_length;
+
posting_frequency_days;
+
quality_score = 0.0; (* Placeholder *)
+
} in
+
+
(* Calculate quality score *)
+
let quality_score = calculate_quality_score metrics in
+
{ metrics with quality_score }
+57
stack/river/lib/quality.mli
···
···
+
(*
+
* Copyright (c) 2014, OCaml.org project
+
* Copyright (c) 2015 KC Sivaramakrishnan <sk826@cl.cam.ac.uk>
+
*
+
* Permission to use, copy, modify, and distribute this software for any
+
* purpose with or without fee is hereby granted, provided that the above
+
* copyright notice and this permission notice appear in all copies.
+
*
+
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
*)
+
+
(** Feed quality analysis. *)
+
+
type t
+
(** Quality metrics for a feed or user's aggregated feed. *)
+
+
val make :
+
total_entries:int ->
+
entries_with_summary:int ->
+
entries_with_author:int ->
+
entries_with_date:int ->
+
entries_with_content:int ->
+
entries_with_tags:int ->
+
avg_content_length:float ->
+
min_content_length:int ->
+
max_content_length:int ->
+
posting_frequency_days:float option ->
+
quality_score:float ->
+
t
+
(** [make ~total_entries ...] creates quality metrics. *)
+
+
val total_entries : t -> int
+
val entries_with_summary : t -> int
+
val entries_with_author : t -> int
+
val entries_with_date : t -> int
+
val entries_with_content : t -> int
+
val entries_with_tags : t -> int
+
val avg_content_length : t -> float
+
val min_content_length : t -> int
+
val max_content_length : t -> int
+
val posting_frequency_days : t -> float option
+
val quality_score : t -> float
+
(** Accessors for quality metrics. *)
+
+
val analyze : Syndic.Atom.entry list -> t
+
(** [analyze entries] computes quality metrics from Atom entries.
+
+
The quality score is a weighted average of:
+
- Content completeness (40%)
+
- Metadata completeness (30%)
+
- Content richness (30%) *)
+9 -1699
stack/river/lib/river.ml
···
(** River RSS/Atom/JSONFeed aggregator library *)
-
let src = Logs.Src.create "river" ~doc:"River RSS/Atom aggregator"
-
module Log = (val Logs.src_log src : Logs.LOG)
-
-
(** {1 Internal Utilities} *)
-
-
module Text_extract = struct
-
open Syndic
-
-
(* Remove all tags *)
-
let rec syndic_to_buffer b = function
-
| XML.Node (_, _, subs) -> List.iter (syndic_to_buffer b) subs
-
| XML.Data (_, d) -> Buffer.add_string b d
-
-
let syndic_to_string x =
-
let b = Buffer.create 1024 in
-
List.iter (syndic_to_buffer b) x;
-
Buffer.contents b
-
-
let string_of_text_construct : Atom.text_construct -> string = function
-
| Atom.Text s | Atom.Html (_, s) -> s
-
| Atom.Xhtml (_, x) -> syndic_to_string x
-
end
-
-
module Html_meta = struct
-
[@@@warning "-32"] (* Suppress unused value warnings for internal utilities *)
-
-
(** This module determines an image to be used as preview of a website.
-
-
It does this by following the same logic Google+ and other websites use, and
-
described in this article:
-
https://www.raymondcamden.com/2011/07/26/How-are-Facebook-and-Google-creating-link-previews *)
-
-
let og_image html =
-
let open Soup in
-
let soup = parse html in
-
try soup $ "meta[property=og:image]" |> R.attribute "content" |> Option.some
-
with Failure _ -> None
-
-
let image_src html =
-
let open Soup in
-
let soup = parse html in
-
try soup $ "link[rel=\"image_src\"]" |> R.attribute "href" |> Option.some
-
with Failure _ -> None
-
-
let twitter_image html =
-
let open Soup in
-
let soup = parse html in
-
try
-
soup $ "meta[name=\"twitter:image\"]" |> R.attribute "content"
-
|> Option.some
-
with Failure _ -> None
-
-
let og_description html =
-
let open Soup in
-
let soup = parse html in
-
try
-
soup $ "meta[property=og:description]" |> R.attribute "content"
-
|> Option.some
-
with Failure _ -> None
-
-
let description html =
-
let open Soup in
-
let soup = parse html in
-
try
-
soup $ "meta[property=description]" |> R.attribute "content" |> Option.some
-
with Failure _ -> None
-
-
let preview_image html =
-
let preview_image =
-
match og_image html with
-
| None -> (
-
match image_src html with
-
| None -> twitter_image html
-
| Some x -> Some x)
-
| Some x -> Some x
-
in
-
match Option.map String.trim preview_image with
-
| Some "" -> None
-
| Some x -> Some x
-
| None -> None
-
-
let description html =
-
let preview_image =
-
match og_description html with None -> description html | Some x -> Some x
-
in
-
match Option.map String.trim preview_image with
-
| Some "" -> None
-
| Some x -> Some x
-
| None -> None
-
end
-
-
module Html_markdown = struct
-
[@@@warning "-32"] (* Suppress unused value warnings for internal utilities *)
-
-
(** HTML to Markdown converter using Lambda Soup *)
-
-
(** Extract all links from HTML content *)
-
let extract_links html_str =
-
try
-
let soup = Soup.parse html_str in
-
let links = Soup.select "a[href]" soup in
-
Soup.fold (fun acc link ->
-
match Soup.attribute "href" link with
-
| Some href ->
-
let text = Soup.texts link |> String.concat "" |> String.trim in
-
(href, text) :: acc
-
| None -> acc
-
) [] links
-
|> List.rev
-
with _ -> []
-
-
(** Check if string contains any whitespace *)
-
let has_whitespace s =
-
try
-
let _ = Str.search_forward (Str.regexp "[ \t\n\r]") s 0 in
-
true
-
with Not_found -> false
-
-
(** Clean up excessive newlines and normalize spacing *)
-
let cleanup_markdown s =
-
(* Normalize line endings *)
-
let s = Str.global_replace (Str.regexp "\r\n") "\n" s in
-
-
(* Remove trailing whitespace from each line *)
-
let lines = String.split_on_char '\n' s in
-
let lines = List.map (fun line ->
-
(* Trim trailing spaces but preserve leading spaces for indentation *)
-
let len = String.length line in
-
let rec find_last_non_space i =
-
if i < 0 then -1
-
else if line.[i] = ' ' || line.[i] = '\t' then find_last_non_space (i - 1)
-
else i
-
in
-
let last = find_last_non_space (len - 1) in
-
if last < 0 then ""
-
else String.sub line 0 (last + 1)
-
) lines in
-
-
(* Join back and collapse excessive blank lines *)
-
let s = String.concat "\n" lines in
-
-
(* Replace 3+ consecutive newlines with just 2 *)
-
let s = Str.global_replace (Str.regexp "\n\n\n+") "\n\n" s in
-
-
(* Trim leading and trailing whitespace *)
-
String.trim s
-
-
(** Convert HTML to Markdown using state-based whitespace handling *)
-
let html_to_markdown html_str =
-
try
-
let soup = Soup.parse html_str in
-
let buffer = Buffer.create 256 in
-
-
(* State: track if we need to insert a space before next text *)
-
let need_space = ref false in
-
-
(* Get last character in buffer, if any *)
-
let last_char () =
-
let len = Buffer.length buffer in
-
if len = 0 then None
-
else Some (Buffer.nth buffer (len - 1))
-
in
-
-
(* Add text with proper spacing *)
-
let add_text text =
-
let trimmed = String.trim text in
-
if trimmed <> "" then begin
-
(* Check if text starts with punctuation that shouldn't have space before it *)
-
let starts_with_punctuation =
-
String.length trimmed > 0 &&
-
(match trimmed.[0] with
-
| ',' | '.' | ';' | ':' | '!' | '?' | ')' | ']' | '}' -> true
-
| _ -> false)
-
in
-
-
(* Add space if needed, unless we're before punctuation *)
-
if !need_space && not starts_with_punctuation then begin
-
match last_char () with
-
| Some (' ' | '\n') -> ()
-
| _ -> Buffer.add_char buffer ' '
-
end;
-
Buffer.add_string buffer trimmed;
-
need_space := false
-
end
-
in
-
-
(* Mark that we need space before next text (for inline elements) *)
-
let mark_space_needed () =
-
need_space := has_whitespace (Buffer.contents buffer) || Buffer.length buffer > 0
-
in
-
-
(* Process header with ID/anchor handling *)
-
let process_header level elem =
-
need_space := false;
-
-
(* Check if header contains a link with an ID fragment *)
-
let link_opt = Soup.select_one "a[href]" elem in
-
let anchor_id = match link_opt with
-
| Some link ->
-
(match Soup.attribute "href" link with
-
| Some href ->
-
(* Extract fragment from URL *)
-
let uri = Uri.of_string href in
-
Uri.fragment uri
-
| None -> None)
-
| None -> None
-
in
-
-
(* Add anchor if we found an ID *)
-
(match anchor_id with
-
| Some id when id <> "" ->
-
Buffer.add_string buffer (Printf.sprintf "\n<a name=\"%s\"></a>\n" id)
-
| _ -> ());
-
-
(* Add the header marker *)
-
let marker = String.make level '#' in
-
Buffer.add_string buffer ("\n" ^ marker ^ " ");
-
-
(* Get text content, excluding link tags *)
-
let text = Soup.texts elem |> String.concat " " |> String.trim in
-
Buffer.add_string buffer text;
-
-
Buffer.add_string buffer "\n\n";
-
need_space := false
-
in
-
-
let rec process_node node =
-
match Soup.element node with
-
| Some elem ->
-
let tag = Soup.name elem in
-
(match tag with
-
(* Block elements - reset space tracking *)
-
| "h1" -> process_header 1 elem
-
| "h2" -> process_header 2 elem
-
| "h3" -> process_header 3 elem
-
| "h4" -> process_header 4 elem
-
| "h5" -> process_header 5 elem
-
| "h6" -> process_header 6 elem
-
| "p" ->
-
need_space := false;
-
Soup.children elem |> Soup.iter process_node;
-
Buffer.add_string buffer "\n\n";
-
need_space := false
-
| "br" ->
-
Buffer.add_string buffer "\n";
-
need_space := false
-
(* Inline elements - preserve space tracking *)
-
| "strong" | "b" ->
-
(* Add space before if needed *)
-
if !need_space then begin
-
match last_char () with
-
| Some (' ' | '\n') -> ()
-
| _ -> Buffer.add_char buffer ' '
-
end;
-
Buffer.add_string buffer "**";
-
need_space := false;
-
Soup.children elem |> Soup.iter process_node;
-
Buffer.add_string buffer "**";
-
mark_space_needed ()
-
| "em" | "i" ->
-
(* Add space before if needed *)
-
if !need_space then begin
-
match last_char () with
-
| Some (' ' | '\n') -> ()
-
| _ -> Buffer.add_char buffer ' '
-
end;
-
Buffer.add_string buffer "*";
-
need_space := false;
-
Soup.children elem |> Soup.iter process_node;
-
Buffer.add_string buffer "*";
-
mark_space_needed ()
-
| "code" ->
-
(* Add space before if needed *)
-
if !need_space then begin
-
match last_char () with
-
| Some (' ' | '\n') -> ()
-
| _ -> Buffer.add_char buffer ' '
-
end;
-
Buffer.add_string buffer "`";
-
need_space := false;
-
Soup.children elem |> Soup.iter process_node;
-
Buffer.add_string buffer "`";
-
mark_space_needed ()
-
| "pre" ->
-
need_space := false;
-
Buffer.add_string buffer "\n```\n";
-
Soup.children elem |> Soup.iter process_node;
-
Buffer.add_string buffer "\n```\n\n";
-
need_space := false
-
| "a" ->
-
let text = Soup.texts elem |> String.concat " " |> String.trim in
-
let href = Soup.attribute "href" elem in
-
(match href with
-
| Some href ->
-
(* Add space before link if needed *)
-
if !need_space then begin
-
match last_char () with
-
| Some (' ' | '\n') -> ()
-
| _ -> Buffer.add_char buffer ' '
-
end;
-
need_space := false;
-
-
(* Add the link markdown *)
-
if text = "" then
-
Buffer.add_string buffer (Printf.sprintf "<%s>" href)
-
else
-
Buffer.add_string buffer (Printf.sprintf "[%s](%s)" text href);
-
-
(* Mark that space may be needed after link *)
-
mark_space_needed ()
-
| None ->
-
add_text text)
-
| "ul" | "ol" ->
-
need_space := false;
-
Buffer.add_string buffer "\n";
-
let is_ordered = tag = "ol" in
-
let items = Soup.children elem |> Soup.to_list in
-
List.iteri (fun i item ->
-
match Soup.element item with
-
| Some li when Soup.name li = "li" ->
-
need_space := false;
-
if is_ordered then
-
Buffer.add_string buffer (Printf.sprintf "%d. " (i + 1))
-
else
-
Buffer.add_string buffer "- ";
-
Soup.children li |> Soup.iter process_node;
-
Buffer.add_string buffer "\n"
-
| _ -> ()
-
) items;
-
Buffer.add_string buffer "\n";
-
need_space := false
-
| "blockquote" ->
-
need_space := false;
-
Buffer.add_string buffer "\n> ";
-
Soup.children elem |> Soup.iter process_node;
-
Buffer.add_string buffer "\n\n";
-
need_space := false
-
| "img" ->
-
(* Add space before if needed *)
-
if !need_space then begin
-
match last_char () with
-
| Some (' ' | '\n') -> ()
-
| _ -> Buffer.add_char buffer ' '
-
end;
-
let alt = Soup.attribute "alt" elem |> Option.value ~default:"" in
-
let src = Soup.attribute "src" elem |> Option.value ~default:"" in
-
Buffer.add_string buffer (Printf.sprintf "![%s](%s)" alt src);
-
need_space := false;
-
mark_space_needed ()
-
| "hr" ->
-
need_space := false;
-
Buffer.add_string buffer "\n---\n\n";
-
need_space := false
-
(* Strip these tags but keep content *)
-
| "div" | "span" | "article" | "section" | "header" | "footer"
-
| "main" | "nav" | "aside" | "figure" | "figcaption" | "details" | "summary" ->
-
Soup.children elem |> Soup.iter process_node
-
(* Ignore script, style, etc *)
-
| "script" | "style" | "noscript" -> ()
-
(* Default: just process children *)
-
| _ ->
-
Soup.children elem |> Soup.iter process_node)
-
| None ->
-
(* Text node - handle whitespace properly *)
-
match Soup.leaf_text node with
-
| Some text ->
-
(* If text is only whitespace, mark that we need space *)
-
let trimmed = String.trim text in
-
if trimmed = "" then begin
-
if has_whitespace text then
-
need_space := true
-
end else begin
-
(* Text has content - check if it had leading/trailing whitespace *)
-
let had_leading_ws = has_whitespace text &&
-
(String.length text > 0 &&
-
(text.[0] = ' ' || text.[0] = '\t' || text.[0] = '\n' || text.[0] = '\r')) in
-
-
(* If had leading whitespace, mark we need space *)
-
if had_leading_ws then need_space := true;
-
-
(* Add the text content *)
-
add_text trimmed;
-
-
(* If had trailing whitespace, mark we need space for next *)
-
let had_trailing_ws = has_whitespace text &&
-
(String.length text > 0 &&
-
let last = text.[String.length text - 1] in
-
last = ' ' || last = '\t' || last = '\n' || last = '\r') in
-
if had_trailing_ws then need_space := true
-
end
-
| None -> ()
-
in
-
-
Soup.children soup |> Soup.iter process_node;
-
-
(* Clean up the result *)
-
let result = Buffer.contents buffer in
-
cleanup_markdown result
-
with _ -> html_str
-
-
(** Convert HTML content to clean Markdown *)
-
let to_markdown html_str =
-
html_to_markdown html_str
-
end
-
-
(** {1 Feed Sources} *)
-
-
module Source = struct
-
type t = {
-
name : string;
-
url : string;
-
}
-
-
let make ~name ~url = { name; url }
-
-
let name t = t.name
-
let url t = t.url
-
-
let jsont =
-
let make name url = { name; url } in
-
Jsont.Object.map ~kind:"Source" make
-
|> Jsont.Object.mem "name" Jsont.string ~enc:(fun s -> s.name)
-
|> Jsont.Object.mem "url" Jsont.string ~enc:(fun s -> s.url)
-
|> Jsont.Object.finish
-
end
-
-
(** {1 HTTP Session Management} *)
-
-
module Session = struct
-
type t = {
-
session : (float Eio.Time.clock_ty Eio.Resource.t,
-
[`Generic | `Unix] Eio.Net.ty Eio.Resource.t) Requests.t;
-
}
-
-
let init ~sw env =
-
Log.info (fun m -> m "Initializing River session");
-
let session = Requests.create ~sw
-
~default_headers:(Requests.Headers.of_list [
-
("User-Agent", "OCaml-River/1.0");
-
])
-
~follow_redirects:true
-
~max_redirects:5
-
~verify_tls:true
-
env
-
in
-
{ session }
-
-
let with_session env f =
-
Log.info (fun m -> m "Creating River session");
-
Eio.Switch.run @@ fun sw ->
-
let client = init ~sw env in
-
f client
-
-
let get_requests_session t = t.session
-
end
-
-
(** {1 Feeds and Posts} *)
-
-
module Feed = struct
-
type feed_content =
-
| Atom of Syndic.Atom.feed
-
| Rss2 of Syndic.Rss2.channel
-
| Json of Jsonfeed.t
-
-
type t = {
-
source : Source.t;
-
title : string;
-
content : feed_content;
-
}
-
-
let string_of_feed = function
-
| Atom _ -> "Atom"
-
| Rss2 _ -> "Rss2"
-
| Json _ -> "JSONFeed"
-
-
let classify_feed ~xmlbase (body : string) =
-
Log.debug (fun m -> m "Attempting to parse feed (%d bytes)" (String.length body));
-
-
(* Quick check - does it look like JSON? *)
-
let looks_like_json =
-
String.length body > 0 &&
-
let first_char = String.get body 0 in
-
first_char = '{' || first_char = '['
-
in
-
-
if looks_like_json then (
-
(* Try JSONFeed first *)
-
Log.debug (fun m -> m "Body looks like JSON, trying JSONFeed parser");
-
match Jsonfeed.of_string body with
-
| Ok jsonfeed ->
-
Log.debug (fun m -> m "Successfully parsed as JSONFeed");
-
Json jsonfeed
-
| Error err ->
-
Log.debug (fun m -> m "Not a JSONFeed: %s" (Jsont.Error.to_string err));
-
(* Fall through to XML parsing *)
-
failwith "Not a valid JSONFeed"
-
) else (
-
(* Try XML formats *)
-
try
-
let feed = Atom (Syndic.Atom.parse ~xmlbase (Xmlm.make_input (`String (0, body)))) in
-
Log.debug (fun m -> m "Successfully parsed as Atom feed");
-
feed
-
with
-
| Syndic.Atom.Error.Error (pos, msg) -> (
-
Log.debug (fun m -> m "Not an Atom feed: %s at position (%d, %d)"
-
msg (fst pos) (snd pos));
-
try
-
let feed = Rss2 (Syndic.Rss2.parse ~xmlbase (Xmlm.make_input (`String (0, body)))) in
-
Log.debug (fun m -> m "Successfully parsed as RSS2 feed");
-
feed
-
with Syndic.Rss2.Error.Error (pos, msg) ->
-
Log.err (fun m -> m "Failed to parse as RSS2: %s at position (%d, %d)"
-
msg (fst pos) (snd pos));
-
failwith "Neither Atom nor RSS2 feed")
-
| Not_found as e ->
-
Log.err (fun m -> m "Not_found exception during Atom feed parsing");
-
Log.err (fun m -> m "Backtrace:\n%s" (Printexc.get_backtrace ()));
-
raise e
-
| e ->
-
Log.err (fun m -> m "Unexpected exception during feed parsing: %s"
-
(Printexc.to_string e));
-
Log.err (fun m -> m "Backtrace:\n%s" (Printexc.get_backtrace ()));
-
raise e
-
)
-
-
let fetch session source =
-
Log.info (fun m -> m "Fetching feed: %s" (Source.name source));
-
-
let xmlbase = Uri.of_string (Source.url source) in
-
-
(* Use Requests_json_api.get_result for clean Result-based error handling *)
-
let requests_session = Session.get_requests_session session in
-
let response =
-
match Requests_json_api.get_result requests_session (Source.url source) with
-
| Ok body ->
-
Log.info (fun m -> m "Successfully fetched %s (%d bytes)"
-
(Source.url source) (String.length body));
-
body
-
| Error (status, msg) ->
-
Log.err (fun m -> m "Failed to fetch feed '%s': HTTP %d - %s"
-
(Source.name source) status msg);
-
failwith (Printf.sprintf "HTTP %d: %s" status msg)
-
in
-
-
let content = classify_feed ~xmlbase response in
-
let title =
-
match content with
-
| Atom atom -> Text_extract.string_of_text_construct atom.Syndic.Atom.title
-
| Rss2 ch -> ch.Syndic.Rss2.title
-
| Json jsonfeed -> Jsonfeed.title jsonfeed
-
in
-
-
Log.info (fun m -> m "Successfully fetched %s feed '%s' (title: '%s')"
-
(string_of_feed content) (Source.name source) title);
-
-
{ source; title; content }
-
-
let source t = t.source
-
end
-
-
(** {1 Posts} *)
-
-
module Post = struct
-
type t = {
-
id : string;
-
title : string;
-
link : Uri.t option;
-
date : Syndic.Date.t option;
-
feed : Feed.t;
-
author : string;
-
email : string;
-
content : Soup.soup Soup.node;
-
mutable link_response : (string, string) result option;
-
tags : string list;
-
summary : string option;
-
}
-
-
(** Generate a stable, unique ID from available data *)
-
let generate_id ?guid ?link ?title ?date ~feed_url () =
-
match guid with
-
| Some id when id <> "" ->
-
(* Use explicit ID/GUID if available *)
-
id
-
| _ ->
-
match link with
-
| Some uri when Uri.to_string uri <> "" ->
-
(* Use permalink as ID (stable and unique) *)
-
Uri.to_string uri
-
| _ ->
-
(* Fallback: hash of feed_url + title + date *)
-
let title_str = Option.value title ~default:"" in
-
let date_str =
-
match date with
-
| Some d -> Ptime.to_rfc3339 d
-
| None -> ""
-
in
-
let composite = Printf.sprintf "%s|%s|%s" feed_url title_str date_str in
-
(* Use SHA256 for stable hashing *)
-
Digest.string composite |> Digest.to_hex
-
-
let resolve_links_attr ~xmlbase attr el =
-
Soup.R.attribute attr el
-
|> Uri.of_string
-
|> Syndic.XML.resolve ~xmlbase
-
|> Uri.to_string
-
|> fun value -> Soup.set_attribute attr value el
-
-
(* Things that posts should not contain *)
-
let undesired_tags = [ "style"; "script" ]
-
let undesired_attr = [ "id" ]
-
-
let html_of_text ?xmlbase s =
-
let soup = Soup.parse s in
-
let ($$) = Soup.($$) in
-
soup $$ "a[href]" |> Soup.iter (resolve_links_attr ~xmlbase "href");
-
soup $$ "img[src]" |> Soup.iter (resolve_links_attr ~xmlbase "src");
-
undesired_tags |> List.iter (fun tag -> soup $$ tag |> Soup.iter Soup.delete);
-
soup $$ "*" |> Soup.iter (fun el ->
-
undesired_attr |> List.iter (fun attr -> Soup.delete_attribute attr el));
-
soup
-
-
(* Do not trust sites using XML for HTML content. Convert to string and parse
-
back. (Does not always fix bad HTML unfortunately.) *)
-
let html_of_syndic =
-
let ns_prefix _ = Some "" in
-
fun ?xmlbase h ->
-
html_of_text ?xmlbase
-
(String.concat "" (List.map (Syndic.XML.to_string ~ns_prefix) h))
-
-
let string_of_option = function None -> "" | Some s -> s
-
-
let post_compare p1 p2 =
-
(* Most recent posts first. Posts with no date are always last *)
-
match (p1.date, p2.date) with
-
| Some d1, Some d2 -> Syndic.Date.compare d2 d1
-
| None, Some _ -> 1
-
| Some _, None -> -1
-
| None, None -> 1
-
-
let rec remove n l =
-
if n <= 0 then l else match l with [] -> [] | _ :: tl -> remove (n - 1) tl
-
-
let rec take n = function
-
| [] -> []
-
| e :: tl -> if n > 0 then e :: take (n - 1) tl else []
-
-
let post_of_atom ~(feed : Feed.t) (e : Syndic.Atom.entry) =
-
Log.debug (fun m -> m "Processing Atom entry: %s"
-
(Text_extract.string_of_text_construct e.title));
-
-
let link =
-
try
-
Some
-
(List.find (fun l -> l.Syndic.Atom.rel = Syndic.Atom.Alternate) e.links)
-
.href
-
with Not_found -> (
-
Log.debug (fun m -> m "No alternate link found, trying fallback");
-
match e.links with
-
| l :: _ -> Some l.href
-
| [] -> (
-
match Uri.scheme e.id with
-
| Some "http" -> Some e.id
-
| Some "https" -> Some e.id
-
| _ -> None))
-
in
-
let date =
-
match e.published with Some _ -> e.published | None -> Some e.updated
-
in
-
let content =
-
match e.content with
-
| Some (Text s) -> html_of_text s
-
| Some (Html (xmlbase, s)) -> html_of_text ?xmlbase s
-
| Some (Xhtml (xmlbase, h)) -> html_of_syndic ?xmlbase h
-
| Some (Mime _) | Some (Src _) | None -> (
-
match e.summary with
-
| Some (Text s) -> html_of_text s
-
| Some (Html (xmlbase, s)) -> html_of_text ?xmlbase s
-
| Some (Xhtml (xmlbase, h)) -> html_of_syndic ?xmlbase h
-
| None -> Soup.parse "")
-
in
-
let is_valid_author_name name =
-
(* Filter out empty strings and placeholder values like "Unknown" *)
-
let trimmed = String.trim name in
-
trimmed <> "" && trimmed <> "Unknown"
-
in
-
let author_name =
-
(* Fallback chain for author:
-
1. Entry author (if present, not empty, and not "Unknown")
-
2. Feed-level author (from Atom feed metadata)
-
3. Feed title (from Atom feed metadata)
-
4. Source name (manually entered feed name) *)
-
try
-
let author, _ = e.authors in
-
let trimmed = String.trim author.name in
-
if is_valid_author_name author.name then trimmed
-
else raise Not_found (* Try feed-level author *)
-
with Not_found -> (
-
match feed.content with
-
| Feed.Atom atom_feed -> (
-
(* Try feed-level authors *)
-
match atom_feed.Syndic.Atom.authors with
-
| author :: _ when is_valid_author_name author.name ->
-
String.trim author.name
-
| _ ->
-
(* Use feed title *)
-
Text_extract.string_of_text_construct atom_feed.Syndic.Atom.title)
-
| Feed.Rss2 _ | Feed.Json _ ->
-
(* For RSS2 and JSONFeed, use the source name *)
-
Source.name feed.source)
-
in
-
(* Extract tags from Atom categories *)
-
let tags =
-
List.map (fun cat -> cat.Syndic.Atom.term) e.categories
-
in
-
(* Extract summary - convert from text_construct to string *)
-
let summary =
-
match e.summary with
-
| Some s -> Some (Text_extract.string_of_text_construct s)
-
| None -> None
-
in
-
(* Generate unique ID *)
-
let guid = Uri.to_string e.id in
-
let title_str = Text_extract.string_of_text_construct e.title in
-
let id =
-
generate_id ~guid ?link ~title:title_str ?date
-
~feed_url:(Source.url feed.source) ()
-
in
-
{
-
id;
-
title = title_str;
-
link;
-
date;
-
feed;
-
author = author_name;
-
email = "";
-
content;
-
link_response = None;
-
tags;
-
summary;
-
}
-
-
let post_of_rss2 ~(feed : Feed.t) it =
-
let title, content =
-
match it.Syndic.Rss2.story with
-
| All (t, xmlbase, d) -> (
-
( t,
-
match it.content with
-
| _, "" -> html_of_text ?xmlbase d
-
| xmlbase, c -> html_of_text ?xmlbase c ))
-
| Title t ->
-
let xmlbase, c = it.content in
-
(t, html_of_text ?xmlbase c)
-
| Description (xmlbase, d) -> (
-
( "",
-
match it.content with
-
| _, "" -> html_of_text ?xmlbase d
-
| xmlbase, c -> html_of_text ?xmlbase c ))
-
in
-
(* Note: it.link is of type Uri.t option in Syndic *)
-
let link =
-
match (it.guid, it.link) with
-
| Some u, _ when u.permalink -> Some u.data
-
| _, Some _ -> it.link
-
| Some u, _ ->
-
(* Sometimes the guid is indicated with isPermaLink="false" but is
-
nonetheless the only URL we get (e.g. ocamlpro). *)
-
Some u.data
-
| None, None -> None
-
in
-
(* Extract GUID string for ID generation *)
-
let guid_str =
-
match it.guid with
-
| Some u -> Some (Uri.to_string u.data)
-
| None -> None
-
in
-
(* RSS2 doesn't have a categories field exposed, use empty list *)
-
let tags = [] in
-
(* RSS2 doesn't have a separate summary field, so leave it empty *)
-
let summary = None in
-
(* Generate unique ID *)
-
let id =
-
generate_id ?guid:guid_str ?link ~title ?date:it.pubDate
-
~feed_url:(Source.url feed.source) ()
-
in
-
{
-
id;
-
title;
-
link;
-
feed;
-
author = Source.name feed.source;
-
email = string_of_option it.author;
-
content;
-
date = it.pubDate;
-
link_response = None;
-
tags;
-
summary;
-
}
-
-
let post_of_jsonfeed_item ~(feed : Feed.t) (item : Jsonfeed.Item.t) =
-
Log.debug (fun m -> m "Processing JSONFeed item: %s"
-
(Option.value (Jsonfeed.Item.title item) ~default:"Untitled"));
-
-
(* Extract content - prefer HTML, fall back to text *)
-
let content =
-
match Jsonfeed.Item.content item with
-
| `Html html -> html_of_text html
-
| `Text text -> html_of_text text
-
| `Both (html, _text) -> html_of_text html
-
in
-
-
(* Extract author - use first author if multiple *)
-
let author_name, author_email =
-
match Jsonfeed.Item.authors item with
-
| Some (first :: _) ->
-
let name = Jsonfeed.Author.name first |> Option.value ~default:"" in
-
(* JSONFeed authors don't typically have email *)
-
(name, "")
-
| _ ->
-
(* Fall back to feed-level authors or feed title *)
-
(match feed.content with
-
| Feed.Json jsonfeed ->
-
(match Jsonfeed.authors jsonfeed with
-
| Some (first :: _) ->
-
let name = Jsonfeed.Author.name first |> Option.value ~default:feed.title in
-
(name, "")
-
| _ -> (feed.title, ""))
-
| _ -> (feed.title, ""))
-
in
-
-
(* Link - use url field *)
-
let link =
-
Jsonfeed.Item.url item
-
|> Option.map Uri.of_string
-
in
-
-
(* Date *)
-
let date = Jsonfeed.Item.date_published item in
-
-
(* Summary *)
-
let summary = Jsonfeed.Item.summary item in
-
-
(* Tags *)
-
let tags =
-
Jsonfeed.Item.tags item
-
|> Option.value ~default:[]
-
in
-
-
(* Generate unique ID - JSONFeed items always have an id field (required) *)
-
let guid = Jsonfeed.Item.id item in
-
let title_str = Jsonfeed.Item.title item |> Option.value ~default:"Untitled" in
-
let id =
-
generate_id ~guid ?link ~title:title_str ?date
-
~feed_url:(Source.url feed.source) ()
-
in
-
-
{
-
id;
-
title = title_str;
-
link;
-
date;
-
feed;
-
author = author_name;
-
email = author_email;
-
content;
-
link_response = None;
-
tags;
-
summary;
-
}
-
-
let posts_of_feed c =
-
match c.Feed.content with
-
| Feed.Atom f ->
-
let posts = List.map (post_of_atom ~feed:c) f.Syndic.Atom.entries in
-
Log.debug (fun m -> m "Extracted %d posts from Atom feed '%s'"
-
(List.length posts) (Source.name c.source));
-
posts
-
| Feed.Rss2 ch ->
-
let posts = List.map (post_of_rss2 ~feed:c) ch.Syndic.Rss2.items in
-
Log.debug (fun m -> m "Extracted %d posts from RSS2 feed '%s'"
-
(List.length posts) (Source.name c.source));
-
posts
-
| Feed.Json jsonfeed ->
-
let items = Jsonfeed.items jsonfeed in
-
let posts = List.map (post_of_jsonfeed_item ~feed:c) items in
-
Log.debug (fun m -> m "Extracted %d posts from JSONFeed '%s'"
-
(List.length posts) (Source.name c.source));
-
posts
-
-
let get_posts ?n ?(ofs = 0) planet_feeds =
-
Log.info (fun m -> m "Processing %d feeds for posts" (List.length planet_feeds));
-
-
let posts = List.concat @@ List.map posts_of_feed planet_feeds in
-
Log.debug (fun m -> m "Total posts collected: %d" (List.length posts));
-
-
let posts = List.sort post_compare posts in
-
Log.debug (fun m -> m "Posts sorted by date (most recent first)");
-
-
let posts = remove ofs posts in
-
let result =
-
match n with
-
| None ->
-
Log.debug (fun m -> m "Returning all %d posts (offset=%d)"
-
(List.length posts) ofs);
-
posts
-
| Some n ->
-
let limited = take n posts in
-
Log.debug (fun m -> m "Returning %d posts (requested=%d, offset=%d)"
-
(List.length limited) n ofs);
-
limited
-
in
-
result
-
-
let of_feeds feeds = get_posts feeds
-
-
let feed t = t.feed
-
let title t = t.title
-
let link t = t.link
-
let date t = t.date
-
let author t = t.author
-
let email t = t.email
-
let content t = Soup.to_string t.content
-
let id t = t.id
-
let tags t = t.tags
-
let summary t = t.summary
-
-
let meta_description _t =
-
(* TODO: This requires environment for HTTP access *)
-
Log.debug (fun m -> m "meta_description not implemented (requires environment)");
-
None
-
-
let seo_image _t =
-
(* TODO: This requires environment for HTTP access *)
-
Log.debug (fun m -> m "seo_image not implemented (requires environment)");
-
None
-
end
-
-
(** {1 Format Conversion and Export} *)
-
-
module Format = struct
-
module Atom = struct
-
let entry_of_post post =
-
let content = Syndic.Atom.Html (None, Post.content post) in
-
let contributors =
-
[ Syndic.Atom.author ~uri:(Uri.of_string (Source.url (Feed.source (Post.feed post))))
-
(Source.name (Feed.source (Post.feed post))) ]
-
in
-
let links =
-
match Post.link post with
-
| Some l -> [ Syndic.Atom.link ~rel:Syndic.Atom.Alternate l ]
-
| None -> []
-
in
-
let id =
-
match Post.link post with
-
| Some l -> l
-
| None -> Uri.of_string (Digest.to_hex (Digest.string (Post.title post)))
-
in
-
let authors = (Syndic.Atom.author ~email:(Post.email post) (Post.author post), []) in
-
let title : Syndic.Atom.text_construct = Syndic.Atom.Text (Post.title post) in
-
let updated =
-
match Post.date post with
-
(* Atom entry requires a date but RSS2 does not. So if a date
-
* is not available, just capture the current date. *)
-
| None -> Ptime.of_float_s (Unix.gettimeofday ()) |> Option.get
-
| Some d -> d
-
in
-
Syndic.Atom.entry ~content ~contributors ~links ~id ~authors ~title ~updated
-
()
-
-
let entries_of_posts posts = List.map entry_of_post posts
-
-
let feed_of_entries ~title ?id ?(authors = []) entries =
-
let feed_id = match id with
-
| Some i -> Uri.of_string i
-
| None -> Uri.of_string "urn:river:merged"
-
in
-
let feed_authors = List.map (fun (name, email) ->
-
match email with
-
| Some e -> Syndic.Atom.author ~email:e name
-
| None -> Syndic.Atom.author name
-
) authors in
-
{
-
Syndic.Atom.id = feed_id;
-
title = Syndic.Atom.Text title;
-
updated = Ptime.of_float_s (Unix.time ()) |> Option.get;
-
entries;
-
authors = feed_authors;
-
categories = [];
-
contributors = [];
-
generator = Some {
-
Syndic.Atom.version = Some "1.0";
-
uri = None;
-
content = "River Feed Aggregator";
-
};
-
icon = None;
-
links = [];
-
logo = None;
-
rights = None;
-
subtitle = None;
-
}
-
-
let to_string feed =
-
let output = Buffer.create 4096 in
-
Syndic.Atom.output feed (`Buffer output);
-
Buffer.contents output
-
end
-
-
module Rss2 = struct
-
let of_feed feed =
-
match feed.Feed.content with
-
| Feed.Rss2 ch -> Some ch
-
| _ -> None
-
end
-
-
module Jsonfeed = struct
-
let item_of_post post =
-
(* Convert HTML content back to string *)
-
let html = Post.content post in
-
let content = `Html html in
-
-
(* Create author *)
-
let authors =
-
if Post.author post <> "" then
-
let author = Jsonfeed.Author.create ~name:(Post.author post) () in
-
Some [author]
-
else
-
None
-
in
-
-
(* Create item *)
-
Jsonfeed.Item.create
-
~id:(Post.id post)
-
~content
-
?url:(Option.map Uri.to_string (Post.link post))
-
~title:(Post.title post)
-
?summary:(Post.summary post)
-
?date_published:(Post.date post)
-
?authors
-
~tags:(Post.tags post)
-
()
-
-
let items_of_posts posts = List.map item_of_post posts
-
-
let feed_of_items ~title ?home_page_url ?feed_url ?description ?icon ?favicon items =
-
Jsonfeed.create ~title ?home_page_url ?feed_url ?description ?icon ?favicon ~items ()
-
-
let feed_of_posts ~title ?home_page_url ?feed_url ?description ?icon ?favicon posts =
-
let items = items_of_posts posts in
-
feed_of_items ~title ?home_page_url ?feed_url ?description ?icon ?favicon items
-
-
let to_string ?(minify = false) jsonfeed =
-
match Jsonfeed.to_string ~minify jsonfeed with
-
| Ok s -> Ok s
-
| Error err -> Error (Jsont.Error.to_string err)
-
-
let of_feed feed =
-
match feed.Feed.content with
-
| Feed.Json jf -> Some jf
-
| _ -> None
-
end
-
end
-
-
(** {1 User Management} *)
-
-
module User = struct
-
type t = {
-
username : string;
-
fullname : string;
-
email : string option;
-
feeds : Source.t list;
-
last_synced : string option;
-
}
-
-
let make ~username ~fullname ?email ?(feeds = []) ?last_synced () =
-
{ username; fullname; email; feeds; last_synced }
-
-
let username t = t.username
-
let fullname t = t.fullname
-
let email t = t.email
-
let feeds t = t.feeds
-
let last_synced t = t.last_synced
-
-
let add_feed t source =
-
{ t with feeds = source :: t.feeds }
-
-
let remove_feed t ~url =
-
let feeds = List.filter (fun s -> Source.url s <> url) t.feeds in
-
{ t with feeds }
-
-
let set_last_synced t timestamp =
-
{ t with last_synced = Some timestamp }
-
-
let jsont =
-
let make username fullname email feeds last_synced =
-
{ username; fullname; email; feeds; last_synced }
-
in
-
Jsont.Object.map ~kind:"User" make
-
|> Jsont.Object.mem "username" Jsont.string ~enc:(fun u -> u.username)
-
|> Jsont.Object.mem "fullname" Jsont.string ~enc:(fun u -> u.fullname)
-
|> Jsont.Object.opt_mem "email" Jsont.string ~enc:(fun u -> u.email)
-
|> Jsont.Object.mem "feeds" (Jsont.list Source.jsont) ~enc:(fun u -> u.feeds)
-
|> Jsont.Object.opt_mem "last_synced" Jsont.string ~enc:(fun u -> u.last_synced)
-
|> Jsont.Object.finish
-
end
-
-
(** {1 Feed Quality Analysis} *)
-
-
module Quality = struct
-
type t = {
-
total_entries : int;
-
entries_with_summary : int;
-
entries_with_author : int;
-
entries_with_date : int;
-
entries_with_content : int;
-
entries_with_tags : int;
-
avg_content_length : float;
-
min_content_length : int;
-
max_content_length : int;
-
posting_frequency_days : float option;
-
quality_score : float;
-
}
-
-
let make ~total_entries ~entries_with_summary ~entries_with_author
-
~entries_with_date ~entries_with_content ~entries_with_tags
-
~avg_content_length ~min_content_length ~max_content_length
-
~posting_frequency_days ~quality_score =
-
{
-
total_entries;
-
entries_with_summary;
-
entries_with_author;
-
entries_with_date;
-
entries_with_content;
-
entries_with_tags;
-
avg_content_length;
-
min_content_length;
-
max_content_length;
-
posting_frequency_days;
-
quality_score;
-
}
-
-
let total_entries t = t.total_entries
-
let entries_with_summary t = t.entries_with_summary
-
let entries_with_author t = t.entries_with_author
-
let entries_with_date t = t.entries_with_date
-
let entries_with_content t = t.entries_with_content
-
let entries_with_tags t = t.entries_with_tags
-
let avg_content_length t = t.avg_content_length
-
let min_content_length t = t.min_content_length
-
let max_content_length t = t.max_content_length
-
let posting_frequency_days t = t.posting_frequency_days
-
let quality_score t = t.quality_score
-
-
(** Get content length from an Atom entry *)
-
let get_content_length (entry : Syndic.Atom.entry) =
-
match entry.content with
-
| Some (Syndic.Atom.Text s) -> String.length s
-
| Some (Syndic.Atom.Html (_, s)) -> String.length s
-
| Some (Syndic.Atom.Xhtml (_, _)) -> 0 (* Could calculate but complex *)
-
| Some (Syndic.Atom.Mime _) -> 0
-
| Some (Syndic.Atom.Src _) -> 0
-
| None -> (
-
match entry.summary with
-
| Some (Syndic.Atom.Text s) -> String.length s
-
| Some (Syndic.Atom.Html (_, s)) -> String.length s
-
| Some (Syndic.Atom.Xhtml (_, _)) -> 0
-
| None -> 0)
-
-
(** Check if entry has non-empty summary *)
-
let has_summary (entry : Syndic.Atom.entry) =
-
match entry.summary with
-
| Some (Syndic.Atom.Text s) when String.trim s <> "" -> true
-
| Some (Syndic.Atom.Html (_, s)) when String.trim s <> "" -> true
-
| Some (Syndic.Atom.Xhtml (_, _)) -> true
-
| _ -> false
-
-
(** Check if entry has author *)
-
let has_author (entry : Syndic.Atom.entry) =
-
let (author, _) = entry.authors in
-
String.trim author.name <> ""
-
-
(** Check if entry has content *)
-
let has_content (entry : Syndic.Atom.entry) =
-
get_content_length entry > 0
-
-
(** Check if entry has tags/categories *)
-
let has_tags (entry : Syndic.Atom.entry) =
-
entry.categories <> []
-
-
(** Calculate quality score from metrics *)
-
let calculate_quality_score t =
-
let total = float_of_int t.total_entries in
-
if total = 0.0 then 0.0
-
else
-
let summary_pct = float_of_int t.entries_with_summary /. total *. 100.0 in
-
let author_pct = float_of_int t.entries_with_author /. total *. 100.0 in
-
let date_pct = float_of_int t.entries_with_date /. total *. 100.0 in
-
let content_pct = float_of_int t.entries_with_content /. total *. 100.0 in
-
let tags_pct = float_of_int t.entries_with_tags /. total *. 100.0 in
-
-
(* Weighted average: content and dates are most important *)
-
let score =
-
(content_pct *. 0.30) +.
-
(date_pct *. 0.25) +.
-
(author_pct *. 0.20) +.
-
(summary_pct *. 0.15) +.
-
(tags_pct *. 0.10)
-
in
-
score
-
-
let analyze entries =
-
if entries = [] then
-
failwith "No entries to analyze"
-
else
-
let total_entries = List.length entries in
-
-
let entries_with_summary = ref 0 in
-
let entries_with_author = ref 0 in
-
let entries_with_date = ref total_entries in (* All Atom entries have updated *)
-
let entries_with_content = ref 0 in
-
let entries_with_tags = ref 0 in
-
let content_lengths = ref [] in
-
let dates = ref [] in
-
-
List.iter (fun (entry : Syndic.Atom.entry) ->
-
if has_summary entry then incr entries_with_summary;
-
if has_author entry then incr entries_with_author;
-
if has_content entry then begin
-
incr entries_with_content;
-
content_lengths := get_content_length entry :: !content_lengths
-
end;
-
if has_tags entry then incr entries_with_tags;
-
dates := entry.updated :: !dates
-
) entries;
-
-
(* Calculate content statistics *)
-
let avg_content_length, min_content_length, max_content_length =
-
if !content_lengths = [] then
-
(0.0, 0, 0)
-
else
-
let sorted = List.sort compare !content_lengths in
-
let sum = List.fold_left (+) 0 sorted in
-
let avg = float_of_int sum /. float_of_int (List.length sorted) in
-
let min_len = List.hd sorted in
-
let max_len = List.hd (List.rev sorted) in
-
(avg, min_len, max_len)
-
in
-
-
(* Calculate posting frequency *)
-
let posting_frequency_days =
-
if List.length !dates < 2 then
-
None
-
else
-
try
-
let timestamps = List.map Ptime.to_float_s !dates in
-
let sorted_timestamps = List.sort compare timestamps in
-
let first = List.hd sorted_timestamps in
-
let last = List.hd (List.rev sorted_timestamps) in
-
let total_days = (last -. first) /. 86400.0 in
-
let num_intervals = float_of_int (List.length sorted_timestamps - 1) in
-
Some (total_days /. num_intervals)
-
with _ -> None
-
in
-
-
(* Create metrics record (without quality_score first) *)
-
let metrics = {
-
total_entries;
-
entries_with_summary = !entries_with_summary;
-
entries_with_author = !entries_with_author;
-
entries_with_date = !entries_with_date;
-
entries_with_content = !entries_with_content;
-
entries_with_tags = !entries_with_tags;
-
avg_content_length;
-
min_content_length;
-
max_content_length;
-
posting_frequency_days;
-
quality_score = 0.0; (* Placeholder *)
-
} in
-
-
(* Calculate quality score *)
-
let quality_score = calculate_quality_score metrics in
-
{ metrics with quality_score }
-
end
-
-
(** {1 State Management} *)
-
-
module State = struct
-
type t = {
-
xdg : Xdge.t;
-
}
-
-
module Paths = struct
-
(** Get the users directory path *)
-
let users_dir state = Eio.Path.(Xdge.state_dir state.xdg / "users")
-
-
(** Get the feeds directory path *)
-
let feeds_dir state = Eio.Path.(Xdge.state_dir state.xdg / "feeds")
-
-
(** Get the user feeds directory path *)
-
let user_feeds_dir state = Eio.Path.(feeds_dir state / "user")
-
-
(** Get the path to a user's JSON file *)
-
let user_file state username =
-
Eio.Path.(users_dir state / (username ^ ".json"))
-
-
(** Get the path to a user's Atom feed file *)
-
let user_feed_file state username =
-
Eio.Path.(user_feeds_dir state / (username ^ ".xml"))
-
-
(** Ensure all necessary directories exist *)
-
let ensure_directories state =
-
let dirs = [
-
users_dir state;
-
feeds_dir state;
-
user_feeds_dir state;
-
] in
-
List.iter (fun dir ->
-
try Eio.Path.mkdir ~perm:0o755 dir
-
with Eio.Io (Eio.Fs.E (Already_exists _), _) -> ()
-
) dirs
-
end
-
-
module Json = struct
-
(** Decode a user from JSON string *)
-
let user_of_string s =
-
match Jsont_bytesrw.decode_string' User.jsont s with
-
| Ok user -> Some user
-
| Error err ->
-
Log.err (fun m -> m "Failed to parse user JSON: %s" (Jsont.Error.to_string err));
-
None
-
-
(** Encode a user to JSON string *)
-
let user_to_string user =
-
match Jsont_bytesrw.encode_string' ~format:Jsont.Indent User.jsont user with
-
| Ok s -> s
-
| Error err -> failwith ("Failed to encode user: " ^ Jsont.Error.to_string err)
-
end
-
-
module Storage = struct
-
(** Load a user from disk *)
-
let load_user state username =
-
let file = Paths.user_file state username in
-
try
-
let content = Eio.Path.load file in
-
Json.user_of_string content
-
with
-
| Eio.Io (Eio.Fs.E (Not_found _), _) -> None
-
| e ->
-
Log.err (fun m -> m "Error loading user %s: %s" username (Printexc.to_string e));
-
None
-
-
(** Save a user to disk *)
-
let save_user state user =
-
let file = Paths.user_file state (User.username user) in
-
let json = Json.user_to_string user in
-
Eio.Path.save ~create:(`Or_truncate 0o644) file json
-
-
(** List all usernames *)
-
let list_users state =
-
try
-
Eio.Path.read_dir (Paths.users_dir state)
-
|> List.filter_map (fun name ->
-
if Filename.check_suffix name ".json" then
-
Some (Filename.chop_suffix name ".json")
-
else None
-
)
-
with _ -> []
-
-
(** Load existing Atom entries for a user *)
-
let load_existing_posts state username =
-
let file = Paths.user_feed_file state username in
-
try
-
let content = Eio.Path.load file in
-
(* Parse existing Atom feed *)
-
let input = Xmlm.make_input (`String (0, content)) in
-
let feed = Syndic.Atom.parse input in
-
feed.Syndic.Atom.entries
-
with
-
| Eio.Io (Eio.Fs.E (Not_found _), _) -> []
-
| e ->
-
Log.err (fun m -> m "Error loading existing posts for %s: %s"
-
username (Printexc.to_string e));
-
[]
-
-
(** Save Atom entries for a user *)
-
let save_atom_feed state username entries =
-
let file = Paths.user_feed_file state username in
-
let feed = Format.Atom.feed_of_entries ~title:username entries in
-
let xml = Format.Atom.to_string feed in
-
Eio.Path.save ~create:(`Or_truncate 0o644) file xml
-
-
(** Delete a user and their feed file *)
-
let delete_user state username =
-
let user_file = Paths.user_file state username in
-
let feed_file = Paths.user_feed_file state username in
-
(try Eio.Path.unlink user_file with _ -> ());
-
(try Eio.Path.unlink feed_file with _ -> ())
-
end
-
-
module Sync = struct
-
(** Merge new entries with existing ones, updating matching IDs *)
-
let merge_entries ~existing ~new_entries =
-
(* Create a map of new entry IDs for efficient lookup and updates *)
-
let module UriMap = Map.Make(Uri) in
-
let new_entries_map =
-
List.fold_left (fun acc (entry : Syndic.Atom.entry) ->
-
UriMap.add entry.id entry acc
-
) UriMap.empty new_entries
-
in
-
-
(* Update existing entries with new ones if IDs match, otherwise keep existing *)
-
let updated_existing =
-
List.filter_map (fun (entry : Syndic.Atom.entry) ->
-
if UriMap.mem entry.id new_entries_map then
-
None (* Will be replaced by new entry *)
-
else
-
Some entry (* Keep existing entry *)
-
) existing
-
in
-
(* Combine new entries with non-replaced existing entries *)
-
let combined = new_entries @ updated_existing in
-
List.sort (fun (a : Syndic.Atom.entry) (b : Syndic.Atom.entry) ->
-
Ptime.compare b.updated a.updated
-
) combined
-
-
(** Get current timestamp in ISO 8601 format *)
-
let current_timestamp () =
-
let open Unix in
-
let tm = gmtime (time ()) in
-
Printf.sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ"
-
(tm.tm_year + 1900) (tm.tm_mon + 1) tm.tm_mday
-
tm.tm_hour tm.tm_min tm.tm_sec
-
-
(** Sync feeds for a single user *)
-
let sync_user session state ~username =
-
match Storage.load_user state username with
-
| None ->
-
Error (Printf.sprintf "User %s not found" username)
-
| Some user when User.feeds user = [] ->
-
Log.info (fun m -> m "No feeds configured for user %s" username);
-
Ok ()
-
| Some user ->
-
Log.info (fun m -> m "Syncing feeds for user %s..." username);
-
-
(* Fetch all feeds concurrently *)
-
let fetched_feeds =
-
Eio.Fiber.List.filter_map (fun source ->
-
try
-
Log.info (fun m -> m " Fetching %s (%s)..."
-
(Source.name source) (Source.url source));
-
Some (Feed.fetch session source)
-
with e ->
-
Log.err (fun m -> m " Failed to fetch %s: %s"
-
(Source.name source) (Printexc.to_string e));
-
None
-
) (User.feeds user)
-
in
-
-
if fetched_feeds = [] then begin
-
Error "No feeds successfully fetched"
-
end else begin
-
(* Get posts from fetched feeds *)
-
let posts = Post.of_feeds fetched_feeds in
-
Log.info (fun m -> m " Found %d new posts" (List.length posts));
-
-
(* Convert to Atom entries *)
-
let new_entries = Format.Atom.entries_of_posts posts in
-
-
(* Load existing entries *)
-
let existing = Storage.load_existing_posts state username in
-
Log.info (fun m -> m " Found %d existing posts" (List.length existing));
-
-
(* Merge entries *)
-
let merged = merge_entries ~existing ~new_entries in
-
Log.info (fun m -> m " Total posts after merge: %d" (List.length merged));
-
-
(* Save updated feed *)
-
Storage.save_atom_feed state username merged;
-
-
(* Update last_synced timestamp *)
-
let now = current_timestamp () in
-
let user = User.set_last_synced user now in
-
Storage.save_user state user;
-
-
Log.info (fun m -> m "Sync completed for user %s" username);
-
Ok ()
-
end
-
end
-
-
module Export = struct
-
(** Convert Atom entry to JSONFeed item *)
-
let atom_entry_to_jsonfeed_item (entry : Syndic.Atom.entry) =
-
(* Extract ID *)
-
let id = Uri.to_string entry.id in
-
-
(* Extract title *)
-
let title =
-
match entry.title with
-
| Syndic.Atom.Text s -> Some s
-
| Syndic.Atom.Html (_, s) -> Some s
-
| Syndic.Atom.Xhtml (_, _) -> Some "Untitled"
-
in
-
-
(* Extract URL *)
-
let url =
-
match entry.links with
-
| link :: _ -> Some (Uri.to_string link.href)
-
| [] -> None
-
in
-
-
(* Extract content *)
-
let content =
-
match entry.content with
-
| Some (Syndic.Atom.Text s) -> `Text s
-
| Some (Syndic.Atom.Html (_, s)) -> `Html s
-
| Some (Syndic.Atom.Xhtml (_, nodes)) ->
-
let html = String.concat "" (List.map Syndic.XML.to_string nodes) in
-
`Html html
-
| Some (Syndic.Atom.Mime _) | Some (Syndic.Atom.Src _) | None ->
-
`Text ""
-
in
-
-
(* Extract summary *)
-
let summary =
-
match entry.summary with
-
| Some (Syndic.Atom.Text s) when String.trim s <> "" -> Some s
-
| Some (Syndic.Atom.Html (_, s)) when String.trim s <> "" -> Some s
-
| _ -> None
-
in
-
-
(* Extract authors *)
-
let authors =
-
let (author, contributors) = entry.authors in
-
let author_list = author :: contributors in
-
let jsonfeed_authors = List.filter_map (fun (a : Syndic.Atom.author) ->
-
let name = String.trim a.name in
-
if name = "" then None
-
else Some (Jsonfeed.Author.create ~name ())
-
) author_list in
-
if jsonfeed_authors = [] then None else Some jsonfeed_authors
-
in
-
-
(* Extract tags *)
-
let tags =
-
match entry.categories with
-
| [] -> None
-
| cats ->
-
let tag_list = List.map (fun (c : Syndic.Atom.category) ->
-
match c.label with
-
| Some lbl -> lbl
-
| None -> c.term
-
) cats in
-
if tag_list = [] then None else Some tag_list
-
in
-
-
(* Create JSONFeed item *)
-
Jsonfeed.Item.create
-
~id
-
~content
-
?title
-
?url
-
?summary
-
?authors
-
?tags
-
~date_published:entry.updated
-
()
-
-
(** Export entries as JSONFeed *)
-
let export_jsonfeed ~title entries =
-
let items = List.map atom_entry_to_jsonfeed_item entries in
-
let feed = Jsonfeed.create ~title ~items () in
-
match Jsonfeed.to_string ~minify:false feed with
-
| Ok json -> Ok json
-
| Error err -> Error (Printf.sprintf "Failed to serialize JSON Feed: %s" (Jsont.Error.to_string err))
-
end
-
-
let create env ~app_name =
-
let xdg = Xdge.create env#fs app_name in
-
let state = { xdg } in
-
Paths.ensure_directories state;
-
state
-
-
let create_user state user =
-
match Storage.load_user state (User.username user) with
-
| Some _ ->
-
Error (Printf.sprintf "User %s already exists" (User.username user))
-
| None ->
-
Storage.save_user state user;
-
Log.info (fun m -> m "User %s created" (User.username user));
-
Ok ()
-
-
let delete_user state ~username =
-
match Storage.load_user state username with
-
| None ->
-
Error (Printf.sprintf "User %s not found" username)
-
| Some _ ->
-
Storage.delete_user state username;
-
Log.info (fun m -> m "User %s deleted" username);
-
Ok ()
-
-
let get_user state ~username =
-
Storage.load_user state username
-
-
let update_user state user =
-
match Storage.load_user state (User.username user) with
-
| None ->
-
Error (Printf.sprintf "User %s not found" (User.username user))
-
| Some _ ->
-
Storage.save_user state user;
-
Log.info (fun m -> m "User %s updated" (User.username user));
-
Ok ()
-
-
let list_users state =
-
Storage.list_users state
-
-
let sync_user env state ~username =
-
Session.with_session env @@ fun session ->
-
Sync.sync_user session state ~username
-
-
let sync_all env state =
-
let users = Storage.list_users state in
-
if users = [] then begin
-
Log.info (fun m -> m "No users to sync");
-
Ok (0, 0)
-
end else begin
-
Log.info (fun m -> m "Syncing %d users concurrently..." (List.length users));
-
-
Session.with_session env @@ fun session ->
-
let results =
-
Eio.Fiber.List.map (fun username ->
-
match Sync.sync_user session state ~username with
-
| Ok () -> true
-
| Error err ->
-
Log.err (fun m -> m "Failed to sync user %s: %s" username err);
-
false
-
) users
-
in
-
let success_count = List.length (List.filter (fun x -> x) results) in
-
let fail_count = List.length users - success_count in
-
-
if fail_count = 0 then
-
Log.info (fun m -> m "All users synced successfully");
-
-
Ok (success_count, fail_count)
-
end
-
-
let get_user_posts state ~username ?limit () =
-
let entries = Storage.load_existing_posts state username in
-
match limit with
-
| None -> entries
-
| Some n -> List.filteri (fun i _ -> i < n) entries
-
-
let get_all_posts state ?limit () =
-
let users = Storage.list_users state in
-
-
(* Collect all entries from all users with username tag *)
-
let all_entries =
-
List.concat_map (fun username ->
-
let entries = Storage.load_existing_posts state username in
-
List.map (fun entry -> (username, entry)) entries
-
) users
-
in
-
-
(* Sort by date (newest first) *)
-
let sorted = List.sort (fun (_, a : string * Syndic.Atom.entry) (_, b) ->
-
Ptime.compare b.updated a.updated
-
) all_entries in
-
-
match limit with
-
| None -> sorted
-
| Some n -> List.filteri (fun i _ -> i < n) sorted
-
-
let export_merged_feed state ~title ~format ?limit () =
-
let all_posts = get_all_posts state ?limit () in
-
let entries = List.map snd all_posts in
-
-
match format with
-
| `Atom ->
-
let xml = Format.Atom.to_string (Format.Atom.feed_of_entries ~title entries) in
-
Ok xml
-
| `Jsonfeed ->
-
if entries = [] then
-
(* Empty JSONFeed *)
-
let feed = Jsonfeed.create ~title ~items:[] () in
-
match Jsonfeed.to_string ~minify:false feed with
-
| Ok json -> Ok json
-
| Error err -> Error (Printf.sprintf "Failed to serialize JSON Feed: %s" (Jsont.Error.to_string err))
-
else
-
Export.export_jsonfeed ~title entries
-
-
let analyze_user_quality state ~username =
-
match Storage.load_user state username with
-
| None ->
-
Error (Printf.sprintf "User %s not found" username)
-
| Some _ ->
-
let entries = Storage.load_existing_posts state username in
-
if entries = [] then
-
Error "No entries to analyze"
-
else
-
Ok (Quality.analyze entries)
-
end
···
(** River RSS/Atom/JSONFeed aggregator library *)
+
(** {1 Public API Modules} *)
+
module Source = Source
+
module Session = Session
+
module Feed = Feed
+
module Post = Post
+
module Format = Format
+
module User = User
+
module Quality = Quality
+
module State = State
+47
stack/river/lib/session.ml
···
···
+
(*
+
* Copyright (c) 2014, OCaml.org project
+
* Copyright (c) 2015 KC Sivaramakrishnan <sk826@cl.cam.ac.uk>
+
*
+
* Permission to use, copy, modify, and distribute this software for any
+
* purpose with or without fee is hereby granted, provided that the above
+
* copyright notice and this permission notice appear in all copies.
+
*
+
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
*)
+
+
(** HTTP session management for fetching feeds. *)
+
+
let src = Logs.Src.create "river" ~doc:"River RSS/Atom aggregator"
+
module Log = (val Logs.src_log src : Logs.LOG)
+
+
type t = {
+
session : (float Eio.Time.clock_ty Eio.Resource.t,
+
[`Generic | `Unix] Eio.Net.ty Eio.Resource.t) Requests.t;
+
}
+
+
let init ~sw env =
+
Log.info (fun m -> m "Initializing River session");
+
let session = Requests.create ~sw
+
~default_headers:(Requests.Headers.of_list [
+
("User-Agent", "OCaml-River/1.0");
+
])
+
~follow_redirects:true
+
~max_redirects:5
+
~verify_tls:true
+
env
+
in
+
{ session }
+
+
let with_session env f =
+
Log.info (fun m -> m "Creating River session");
+
Eio.Switch.run @@ fun sw ->
+
let client = init ~sw env in
+
f client
+
+
let get_requests_session t = t.session
+59
stack/river/lib/session.mli
···
···
+
(*
+
* Copyright (c) 2014, OCaml.org project
+
* Copyright (c) 2015 KC Sivaramakrishnan <sk826@cl.cam.ac.uk>
+
*
+
* Permission to use, copy, modify, and distribute this software for any
+
* purpose with or without fee is hereby granted, provided that the above
+
* copyright notice and this permission notice appear in all copies.
+
*
+
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
*)
+
+
(** HTTP session management for fetching feeds. *)
+
+
type t
+
(** An abstract HTTP session for fetching feeds.
+
+
The session manages HTTP connections and is tied to an Eio switch
+
for proper resource cleanup. *)
+
+
val init :
+
sw:Eio.Switch.t ->
+
< clock : float Eio.Time.clock_ty Eio.Resource.t;
+
fs : Eio.Fs.dir_ty Eio.Path.t;
+
net : [ `Generic | `Unix ] Eio.Net.ty Eio.Resource.t; .. > ->
+
t
+
(** [init ~sw env] creates a new HTTP session.
+
+
The session is configured with appropriate defaults for fetching feeds:
+
- User-Agent: "OCaml-River/1.0"
+
- Automatic redirect following (max 5 redirects)
+
- TLS verification enabled
+
+
@param sw The switch for resource management
+
@param env The Eio environment *)
+
+
val with_session :
+
< clock : float Eio.Time.clock_ty Eio.Resource.t;
+
fs : Eio.Fs.dir_ty Eio.Path.t;
+
net : [ `Generic | `Unix ] Eio.Net.ty Eio.Resource.t; .. > ->
+
(t -> 'a) -> 'a
+
(** [with_session env f] creates a session and automatically manages its lifecycle.
+
+
This is the recommended way to use River as it ensures proper cleanup.
+
+
@param env The Eio environment
+
@param f The function to run with the session *)
+
+
val get_requests_session : t ->
+
(float Eio.Time.clock_ty Eio.Resource.t,
+
[`Generic | `Unix] Eio.Net.ty Eio.Resource.t) Requests.t
+
(** [get_requests_session t] returns the underlying Requests session.
+
+
This is used internally by the Feed module. *)
+35
stack/river/lib/source.ml
···
···
+
(*
+
* Copyright (c) 2014, OCaml.org project
+
* Copyright (c) 2015 KC Sivaramakrishnan <sk826@cl.cam.ac.uk>
+
*
+
* Permission to use, copy, modify, and distribute this software for any
+
* purpose with or without fee is hereby granted, provided that the above
+
* copyright notice and this permission notice appear in all copies.
+
*
+
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
*)
+
+
(** Feed source with name and URL. *)
+
+
type t = {
+
name : string;
+
url : string;
+
}
+
+
let make ~name ~url = { name; url }
+
+
let name t = t.name
+
let url t = t.url
+
+
let jsont =
+
let make name url = { name; url } in
+
Jsont.Object.map ~kind:"Source" make
+
|> Jsont.Object.mem "name" Jsont.string ~enc:(fun s -> s.name)
+
|> Jsont.Object.mem "url" Jsont.string ~enc:(fun s -> s.url)
+
|> Jsont.Object.finish
+33
stack/river/lib/source.mli
···
···
+
(*
+
* Copyright (c) 2014, OCaml.org project
+
* Copyright (c) 2015 KC Sivaramakrishnan <sk826@cl.cam.ac.uk>
+
*
+
* Permission to use, copy, modify, and distribute this software for any
+
* purpose with or without fee is hereby granted, provided that the above
+
* copyright notice and this permission notice appear in all copies.
+
*
+
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
*)
+
+
(** Feed source with name and URL. *)
+
+
type t
+
(** A feed source with name and URL. *)
+
+
val make : name:string -> url:string -> t
+
(** [make ~name ~url] creates a new feed source. *)
+
+
val name : t -> string
+
(** [name source] returns the feed name/label. *)
+
+
val url : t -> string
+
(** [url source] returns the feed URL. *)
+
+
val jsont : t Jsont.t
+
(** JSON codec for sources. *)
+436
stack/river/lib/state.ml
···
···
+
(*
+
* Copyright (c) 2014, OCaml.org project
+
* Copyright (c) 2015 KC Sivaramakrishnan <sk826@cl.cam.ac.uk>
+
*
+
* Permission to use, copy, modify, and distribute this software for any
+
* purpose with or without fee is hereby granted, provided that the above
+
* copyright notice and this permission notice appear in all copies.
+
*
+
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
*)
+
+
(** State management for user data and feeds. *)
+
+
let src = Logs.Src.create "river" ~doc:"River RSS/Atom aggregator"
+
module Log = (val Logs.src_log src : Logs.LOG)
+
+
type t = {
+
xdg : Xdge.t;
+
}
+
+
module Paths = struct
+
(** Get the users directory path *)
+
let users_dir state = Eio.Path.(Xdge.state_dir state.xdg / "users")
+
+
(** Get the feeds directory path *)
+
let feeds_dir state = Eio.Path.(Xdge.state_dir state.xdg / "feeds")
+
+
(** Get the user feeds directory path *)
+
let user_feeds_dir state = Eio.Path.(feeds_dir state / "user")
+
+
(** Get the path to a user's JSON file *)
+
let user_file state username =
+
Eio.Path.(users_dir state / (username ^ ".json"))
+
+
(** Get the path to a user's Atom feed file *)
+
let user_feed_file state username =
+
Eio.Path.(user_feeds_dir state / (username ^ ".xml"))
+
+
(** Ensure all necessary directories exist *)
+
let ensure_directories state =
+
let dirs = [
+
users_dir state;
+
feeds_dir state;
+
user_feeds_dir state;
+
] in
+
List.iter (fun dir ->
+
try Eio.Path.mkdir ~perm:0o755 dir
+
with Eio.Io (Eio.Fs.E (Already_exists _), _) -> ()
+
) dirs
+
end
+
+
module Json = struct
+
(** Decode a user from JSON string *)
+
let user_of_string s =
+
match Jsont_bytesrw.decode_string' User.jsont s with
+
| Ok user -> Some user
+
| Error err ->
+
Log.err (fun m -> m "Failed to parse user JSON: %s" (Jsont.Error.to_string err));
+
None
+
+
(** Encode a user to JSON string *)
+
let user_to_string user =
+
match Jsont_bytesrw.encode_string' ~format:Jsont.Indent User.jsont user with
+
| Ok s -> s
+
| Error err -> failwith ("Failed to encode user: " ^ Jsont.Error.to_string err)
+
end
+
+
module Storage = struct
+
(** Load a user from disk *)
+
let load_user state username =
+
let file = Paths.user_file state username in
+
try
+
let content = Eio.Path.load file in
+
Json.user_of_string content
+
with
+
| Eio.Io (Eio.Fs.E (Not_found _), _) -> None
+
| e ->
+
Log.err (fun m -> m "Error loading user %s: %s" username (Printexc.to_string e));
+
None
+
+
(** Save a user to disk *)
+
let save_user state user =
+
let file = Paths.user_file state (User.username user) in
+
let json = Json.user_to_string user in
+
Eio.Path.save ~create:(`Or_truncate 0o644) file json
+
+
(** List all usernames *)
+
let list_users state =
+
try
+
Eio.Path.read_dir (Paths.users_dir state)
+
|> List.filter_map (fun name ->
+
if Filename.check_suffix name ".json" then
+
Some (Filename.chop_suffix name ".json")
+
else None
+
)
+
with _ -> []
+
+
(** Load existing Atom entries for a user *)
+
let load_existing_posts state username =
+
let file = Paths.user_feed_file state username in
+
try
+
let content = Eio.Path.load file in
+
(* Parse existing Atom feed *)
+
let input = Xmlm.make_input (`String (0, content)) in
+
let feed = Syndic.Atom.parse input in
+
feed.Syndic.Atom.entries
+
with
+
| Eio.Io (Eio.Fs.E (Not_found _), _) -> []
+
| e ->
+
Log.err (fun m -> m "Error loading existing posts for %s: %s"
+
username (Printexc.to_string e));
+
[]
+
+
(** Save Atom entries for a user *)
+
let save_atom_feed state username entries =
+
let file = Paths.user_feed_file state username in
+
let feed = Format.Atom.feed_of_entries ~title:username entries in
+
let xml = Format.Atom.to_string feed in
+
Eio.Path.save ~create:(`Or_truncate 0o644) file xml
+
+
(** Delete a user and their feed file *)
+
let delete_user state username =
+
let user_file = Paths.user_file state username in
+
let feed_file = Paths.user_feed_file state username in
+
(try Eio.Path.unlink user_file with _ -> ());
+
(try Eio.Path.unlink feed_file with _ -> ())
+
end
+
+
module Sync = struct
+
(** Merge new entries with existing ones, updating matching IDs *)
+
let merge_entries ~existing ~new_entries =
+
(* Create a map of new entry IDs for efficient lookup and updates *)
+
let module UriMap = Map.Make(Uri) in
+
let new_entries_map =
+
List.fold_left (fun acc (entry : Syndic.Atom.entry) ->
+
UriMap.add entry.id entry acc
+
) UriMap.empty new_entries
+
in
+
+
(* Update existing entries with new ones if IDs match, otherwise keep existing *)
+
let updated_existing =
+
List.filter_map (fun (entry : Syndic.Atom.entry) ->
+
if UriMap.mem entry.id new_entries_map then
+
None (* Will be replaced by new entry *)
+
else
+
Some entry (* Keep existing entry *)
+
) existing
+
in
+
+
(* Combine new entries with non-replaced existing entries *)
+
let combined = new_entries @ updated_existing in
+
List.sort (fun (a : Syndic.Atom.entry) (b : Syndic.Atom.entry) ->
+
Ptime.compare b.updated a.updated
+
) combined
+
+
(** Get current timestamp in ISO 8601 format *)
+
let current_timestamp () =
+
let open Unix in
+
let tm = gmtime (time ()) in
+
Printf.sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ"
+
(tm.tm_year + 1900) (tm.tm_mon + 1) tm.tm_mday
+
tm.tm_hour tm.tm_min tm.tm_sec
+
+
(** Sync feeds for a single user *)
+
let sync_user session state ~username =
+
match Storage.load_user state username with
+
| None ->
+
Error (Printf.sprintf "User %s not found" username)
+
| Some user when User.feeds user = [] ->
+
Log.info (fun m -> m "No feeds configured for user %s" username);
+
Ok ()
+
| Some user ->
+
Log.info (fun m -> m "Syncing feeds for user %s..." username);
+
+
(* Fetch all feeds concurrently *)
+
let fetched_feeds =
+
Eio.Fiber.List.filter_map (fun source ->
+
try
+
Log.info (fun m -> m " Fetching %s (%s)..."
+
(Source.name source) (Source.url source));
+
Some (Feed.fetch session source)
+
with e ->
+
Log.err (fun m -> m " Failed to fetch %s: %s"
+
(Source.name source) (Printexc.to_string e));
+
None
+
) (User.feeds user)
+
in
+
+
if fetched_feeds = [] then begin
+
Error "No feeds successfully fetched"
+
end else begin
+
(* Get posts from fetched feeds *)
+
let posts = Post.of_feeds fetched_feeds in
+
Log.info (fun m -> m " Found %d new posts" (List.length posts));
+
+
(* Convert to Atom entries *)
+
let new_entries = Format.Atom.entries_of_posts posts in
+
+
(* Load existing entries *)
+
let existing = Storage.load_existing_posts state username in
+
Log.info (fun m -> m " Found %d existing posts" (List.length existing));
+
+
(* Merge entries *)
+
let merged = merge_entries ~existing ~new_entries in
+
Log.info (fun m -> m " Total posts after merge: %d" (List.length merged));
+
+
(* Save updated feed *)
+
Storage.save_atom_feed state username merged;
+
+
(* Update last_synced timestamp *)
+
let now = current_timestamp () in
+
let user = User.set_last_synced user now in
+
Storage.save_user state user;
+
+
Log.info (fun m -> m "Sync completed for user %s" username);
+
Ok ()
+
end
+
end
+
+
module Export = struct
+
(** Convert Atom entry to JSONFeed item *)
+
let atom_entry_to_jsonfeed_item (entry : Syndic.Atom.entry) =
+
(* Extract ID *)
+
let id = Uri.to_string entry.id in
+
+
(* Extract title *)
+
let title =
+
match entry.title with
+
| Syndic.Atom.Text s -> Some s
+
| Syndic.Atom.Html (_, s) -> Some s
+
| Syndic.Atom.Xhtml (_, _) -> Some "Untitled"
+
in
+
+
(* Extract URL *)
+
let url =
+
match entry.links with
+
| link :: _ -> Some (Uri.to_string link.href)
+
| [] -> None
+
in
+
+
(* Extract content *)
+
let content =
+
match entry.content with
+
| Some (Syndic.Atom.Text s) -> `Text s
+
| Some (Syndic.Atom.Html (_, s)) -> `Html s
+
| Some (Syndic.Atom.Xhtml (_, nodes)) ->
+
let html = String.concat "" (List.map Syndic.XML.to_string nodes) in
+
`Html html
+
| Some (Syndic.Atom.Mime _) | Some (Syndic.Atom.Src _) | None ->
+
`Text ""
+
in
+
+
(* Extract summary *)
+
let summary =
+
match entry.summary with
+
| Some (Syndic.Atom.Text s) when String.trim s <> "" -> Some s
+
| Some (Syndic.Atom.Html (_, s)) when String.trim s <> "" -> Some s
+
| _ -> None
+
in
+
+
(* Extract authors *)
+
let authors =
+
let (author, contributors) = entry.authors in
+
let author_list = author :: contributors in
+
let jsonfeed_authors = List.filter_map (fun (a : Syndic.Atom.author) ->
+
let name = String.trim a.name in
+
if name = "" then None
+
else Some (Jsonfeed.Author.create ~name ())
+
) author_list in
+
if jsonfeed_authors = [] then None else Some jsonfeed_authors
+
in
+
+
(* Extract tags *)
+
let tags =
+
match entry.categories with
+
| [] -> None
+
| cats ->
+
let tag_list = List.map (fun (c : Syndic.Atom.category) ->
+
match c.label with
+
| Some lbl -> lbl
+
| None -> c.term
+
) cats in
+
if tag_list = [] then None else Some tag_list
+
in
+
+
(* Create JSONFeed item *)
+
Jsonfeed.Item.create
+
~id
+
~content
+
?title
+
?url
+
?summary
+
?authors
+
?tags
+
~date_published:entry.updated
+
()
+
+
(** Export entries as JSONFeed *)
+
let export_jsonfeed ~title entries =
+
let items = List.map atom_entry_to_jsonfeed_item entries in
+
let feed = Jsonfeed.create ~title ~items () in
+
match Jsonfeed.to_string ~minify:false feed with
+
| Ok json -> Ok json
+
| Error err -> Error (Printf.sprintf "Failed to serialize JSON Feed: %s" (Jsont.Error.to_string err))
+
end
+
+
let create env ~app_name =
+
let xdg = Xdge.create env#fs app_name in
+
let state = { xdg } in
+
Paths.ensure_directories state;
+
state
+
+
let create_user state user =
+
match Storage.load_user state (User.username user) with
+
| Some _ ->
+
Error (Printf.sprintf "User %s already exists" (User.username user))
+
| None ->
+
Storage.save_user state user;
+
Log.info (fun m -> m "User %s created" (User.username user));
+
Ok ()
+
+
let delete_user state ~username =
+
match Storage.load_user state username with
+
| None ->
+
Error (Printf.sprintf "User %s not found" username)
+
| Some _ ->
+
Storage.delete_user state username;
+
Log.info (fun m -> m "User %s deleted" username);
+
Ok ()
+
+
let get_user state ~username =
+
Storage.load_user state username
+
+
let update_user state user =
+
match Storage.load_user state (User.username user) with
+
| None ->
+
Error (Printf.sprintf "User %s not found" (User.username user))
+
| Some _ ->
+
Storage.save_user state user;
+
Log.info (fun m -> m "User %s updated" (User.username user));
+
Ok ()
+
+
let list_users state =
+
Storage.list_users state
+
+
let sync_user env state ~username =
+
Session.with_session env @@ fun session ->
+
Sync.sync_user session state ~username
+
+
let sync_all env state =
+
let users = Storage.list_users state in
+
if users = [] then begin
+
Log.info (fun m -> m "No users to sync");
+
Ok (0, 0)
+
end else begin
+
Log.info (fun m -> m "Syncing %d users concurrently..." (List.length users));
+
+
Session.with_session env @@ fun session ->
+
let results =
+
Eio.Fiber.List.map (fun username ->
+
match Sync.sync_user session state ~username with
+
| Ok () -> true
+
| Error err ->
+
Log.err (fun m -> m "Failed to sync user %s: %s" username err);
+
false
+
) users
+
in
+
let success_count = List.length (List.filter (fun x -> x) results) in
+
let fail_count = List.length users - success_count in
+
+
if fail_count = 0 then
+
Log.info (fun m -> m "All users synced successfully");
+
+
Ok (success_count, fail_count)
+
end
+
+
let get_user_posts state ~username ?limit () =
+
let entries = Storage.load_existing_posts state username in
+
match limit with
+
| None -> entries
+
| Some n -> List.filteri (fun i _ -> i < n) entries
+
+
let get_all_posts state ?limit () =
+
let users = Storage.list_users state in
+
+
(* Collect all entries from all users with username tag *)
+
let all_entries =
+
List.concat_map (fun username ->
+
let entries = Storage.load_existing_posts state username in
+
List.map (fun entry -> (username, entry)) entries
+
) users
+
in
+
+
(* Sort by date (newest first) *)
+
let sorted = List.sort (fun (_, a : string * Syndic.Atom.entry) (_, b) ->
+
Ptime.compare b.updated a.updated
+
) all_entries in
+
+
match limit with
+
| None -> sorted
+
| Some n -> List.filteri (fun i _ -> i < n) sorted
+
+
let export_merged_feed state ~title ~format ?limit () =
+
let all_posts = get_all_posts state ?limit () in
+
let entries = List.map snd all_posts in
+
+
match format with
+
| `Atom ->
+
let xml = Format.Atom.to_string (Format.Atom.feed_of_entries ~title entries) in
+
Ok xml
+
| `Jsonfeed ->
+
if entries = [] then
+
(* Empty JSONFeed *)
+
let feed = Jsonfeed.create ~title ~items:[] () in
+
match Jsonfeed.to_string ~minify:false feed with
+
| Ok json -> Ok json
+
| Error err -> Error (Printf.sprintf "Failed to serialize JSON Feed: %s" (Jsont.Error.to_string err))
+
else
+
Export.export_jsonfeed ~title entries
+
+
let analyze_user_quality state ~username =
+
match Storage.load_user state username with
+
| None ->
+
Error (Printf.sprintf "User %s not found" username)
+
| Some _ ->
+
let entries = Storage.load_existing_posts state username in
+
if entries = [] then
+
Error "No entries to analyze"
+
else
+
Ok (Quality.analyze entries)
+120
stack/river/lib/state.mli
···
···
+
(*
+
* Copyright (c) 2014, OCaml.org project
+
* Copyright (c) 2015 KC Sivaramakrishnan <sk826@cl.cam.ac.uk>
+
*
+
* Permission to use, copy, modify, and distribute this software for any
+
* purpose with or without fee is hereby granted, provided that the above
+
* copyright notice and this permission notice appear in all copies.
+
*
+
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
*)
+
+
(** State management for user data and feeds. *)
+
+
type t
+
(** State handle for managing user data and feeds on disk. *)
+
+
val create :
+
< fs : Eio.Fs.dir_ty Eio.Path.t; .. > ->
+
app_name:string ->
+
t
+
(** [create env ~app_name] creates a state handle using XDG directories.
+
+
Data is stored in:
+
- Users: $XDG_STATE_HOME/[app_name]/users/
+
- Feeds: $XDG_STATE_HOME/[app_name]/feeds/user/
+
+
@param env The Eio environment with filesystem access
+
@param app_name Application name for XDG paths *)
+
+
(** {2 User Operations} *)
+
+
val create_user : t -> User.t -> (unit, string) result
+
(** [create_user state user] creates a new user.
+
+
Returns [Error] if the user already exists. *)
+
+
val delete_user : t -> username:string -> (unit, string) result
+
(** [delete_user state ~username] deletes a user and their feed data. *)
+
+
val get_user : t -> username:string -> User.t option
+
(** [get_user state ~username] retrieves a user by username. *)
+
+
val update_user : t -> User.t -> (unit, string) result
+
(** [update_user state user] saves updated user configuration. *)
+
+
val list_users : t -> string list
+
(** [list_users state] returns all usernames. *)
+
+
(** {2 Feed Operations} *)
+
+
val sync_user :
+
< clock : float Eio.Time.clock_ty Eio.Resource.t;
+
fs : Eio.Fs.dir_ty Eio.Path.t;
+
net : [ `Generic | `Unix ] Eio.Net.ty Eio.Resource.t; .. > ->
+
t ->
+
username:string ->
+
(unit, string) result
+
(** [sync_user env state ~username] fetches all feeds for the user and stores merged result.
+
+
Posts are fetched concurrently and merged with existing posts.
+
The result is stored as an Atom feed. *)
+
+
val sync_all :
+
< clock : float Eio.Time.clock_ty Eio.Resource.t;
+
fs : Eio.Fs.dir_ty Eio.Path.t;
+
net : [ `Generic | `Unix ] Eio.Net.ty Eio.Resource.t; .. > ->
+
t ->
+
(int * int, string) result
+
(** [sync_all env state] syncs all users concurrently.
+
+
Returns [Ok (success_count, fail_count)]. *)
+
+
val get_user_posts :
+
t ->
+
username:string ->
+
?limit:int ->
+
unit ->
+
Syndic.Atom.entry list
+
(** [get_user_posts state ~username ()] retrieves stored posts for a user.
+
+
@param limit Optional maximum number of posts to return *)
+
+
val get_all_posts :
+
t ->
+
?limit:int ->
+
unit ->
+
(string * Syndic.Atom.entry) list
+
(** [get_all_posts state ()] retrieves posts from all users, sorted by date.
+
+
Returns list of (username, entry) tuples.
+
@param limit Optional maximum number of posts to return *)
+
+
(** {2 Export} *)
+
+
val export_merged_feed :
+
t ->
+
title:string ->
+
format:[ `Atom | `Jsonfeed ] ->
+
?limit:int ->
+
unit ->
+
(string, string) result
+
(** [export_merged_feed state ~title ~format ()] exports a merged feed of all users.
+
+
@param title Feed title
+
@param format Output format
+
@param limit Optional maximum number of entries *)
+
+
(** {2 Analysis} *)
+
+
val analyze_user_quality :
+
t ->
+
username:string ->
+
(Quality.t, string) result
+
(** [analyze_user_quality state ~username] analyzes quality metrics for a user's feed. *)
+34
stack/river/lib/text_extract.ml
···
···
+
(*
+
* Copyright (c) 2014, OCaml.org project
+
* Copyright (c) 2015 KC Sivaramakrishnan <sk826@cl.cam.ac.uk>
+
*
+
* Permission to use, copy, modify, and distribute this software for any
+
* purpose with or without fee is hereby granted, provided that the above
+
* copyright notice and this permission notice appear in all copies.
+
*
+
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
*)
+
+
(** Internal utility for Syndic text extraction *)
+
+
open Syndic
+
+
(* Remove all tags *)
+
let rec syndic_to_buffer b = function
+
| XML.Node (_, _, subs) -> List.iter (syndic_to_buffer b) subs
+
| XML.Data (_, d) -> Buffer.add_string b d
+
+
let syndic_to_string x =
+
let b = Buffer.create 1024 in
+
List.iter (syndic_to_buffer b) x;
+
Buffer.contents b
+
+
let string_of_text_construct : Atom.text_construct -> string = function
+
| Atom.Text s | Atom.Html (_, s) -> s
+
| Atom.Xhtml (_, x) -> syndic_to_string x
+57
stack/river/lib/user.ml
···
···
+
(*
+
* Copyright (c) 2014, OCaml.org project
+
* Copyright (c) 2015 KC Sivaramakrishnan <sk826@cl.cam.ac.uk>
+
*
+
* Permission to use, copy, modify, and distribute this software for any
+
* purpose with or without fee is hereby granted, provided that the above
+
* copyright notice and this permission notice appear in all copies.
+
*
+
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
*)
+
+
(** User management. *)
+
+
type t = {
+
username : string;
+
fullname : string;
+
email : string option;
+
feeds : Source.t list;
+
last_synced : string option;
+
}
+
+
let make ~username ~fullname ?email ?(feeds = []) ?last_synced () =
+
{ username; fullname; email; feeds; last_synced }
+
+
let username t = t.username
+
let fullname t = t.fullname
+
let email t = t.email
+
let feeds t = t.feeds
+
let last_synced t = t.last_synced
+
+
let add_feed t source =
+
{ t with feeds = source :: t.feeds }
+
+
let remove_feed t ~url =
+
let feeds = List.filter (fun s -> Source.url s <> url) t.feeds in
+
{ t with feeds }
+
+
let set_last_synced t timestamp =
+
{ t with last_synced = Some timestamp }
+
+
let jsont =
+
let make username fullname email feeds last_synced =
+
{ username; fullname; email; feeds; last_synced }
+
in
+
Jsont.Object.map ~kind:"User" make
+
|> Jsont.Object.mem "username" Jsont.string ~enc:(fun u -> u.username)
+
|> Jsont.Object.mem "fullname" Jsont.string ~enc:(fun u -> u.fullname)
+
|> Jsont.Object.opt_mem "email" Jsont.string ~enc:(fun u -> u.email)
+
|> Jsont.Object.mem "feeds" (Jsont.list Source.jsont) ~enc:(fun u -> u.feeds)
+
|> Jsont.Object.opt_mem "last_synced" Jsont.string ~enc:(fun u -> u.last_synced)
+
|> Jsont.Object.finish
+64
stack/river/lib/user.mli
···
···
+
(*
+
* Copyright (c) 2014, OCaml.org project
+
* Copyright (c) 2015 KC Sivaramakrishnan <sk826@cl.cam.ac.uk>
+
*
+
* Permission to use, copy, modify, and distribute this software for any
+
* purpose with or without fee is hereby granted, provided that the above
+
* copyright notice and this permission notice appear in all copies.
+
*
+
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
*)
+
+
(** User management. *)
+
+
type t
+
(** User configuration with feed subscriptions. *)
+
+
val make :
+
username:string ->
+
fullname:string ->
+
?email:string ->
+
?feeds:Source.t list ->
+
?last_synced:string ->
+
unit ->
+
t
+
(** [make ~username ~fullname ()] creates a new user.
+
+
@param username Unique username identifier
+
@param fullname User's display name
+
@param email Optional email address
+
@param feeds Optional list of feed sources (default: [])
+
@param last_synced Optional ISO 8601 timestamp of last sync *)
+
+
val username : t -> string
+
(** [username user] returns the username. *)
+
+
val fullname : t -> string
+
(** [fullname user] returns the full name. *)
+
+
val email : t -> string option
+
(** [email user] returns the email address if set. *)
+
+
val feeds : t -> Source.t list
+
(** [feeds user] returns the list of subscribed feeds. *)
+
+
val last_synced : t -> string option
+
(** [last_synced user] returns the last sync timestamp if set. *)
+
+
val add_feed : t -> Source.t -> t
+
(** [add_feed user source] returns a new user with the feed added. *)
+
+
val remove_feed : t -> url:string -> t
+
(** [remove_feed user ~url] returns a new user with the feed removed by URL. *)
+
+
val set_last_synced : t -> string -> t
+
(** [set_last_synced user timestamp] returns a new user with updated sync time. *)
+
+
val jsont : t Jsont.t
+
(** JSON codec for users. *)