OCaml library for JSONfeed parsing and creation
1(** Feed items in a JSON Feed. *) 2 3type content = 4 [ `Html of string 5 | `Text of string 6 | `Both of string * string 7 ] 8 9type t = { 10 id : string; 11 content : content; 12 url : string option; 13 external_url : string option; 14 title : string option; 15 summary : string option; 16 image : string option; 17 banner_image : string option; 18 date_published : Ptime.t option; 19 date_modified : Ptime.t option; 20 authors : Author.t list option; 21 tags : string list option; 22 language : string option; 23 attachments : Attachment.t list option; 24 references : Reference.t list option; 25} 26 27let create ~id ~content ?url ?external_url ?title ?summary ?image ?banner_image 28 ?date_published ?date_modified ?authors ?tags ?language ?attachments ?references () = 29 { 30 id; 31 content; 32 url; 33 external_url; 34 title; 35 summary; 36 image; 37 banner_image; 38 date_published; 39 date_modified; 40 authors; 41 tags; 42 language; 43 attachments; 44 references; 45 } 46 47let id t = t.id 48let content t = t.content 49let url t = t.url 50let external_url t = t.external_url 51let title t = t.title 52let summary t = t.summary 53let image t = t.image 54let banner_image t = t.banner_image 55let date_published t = t.date_published 56let date_modified t = t.date_modified 57let authors t = t.authors 58let tags t = t.tags 59let language t = t.language 60let attachments t = t.attachments 61let references t = t.references 62 63let content_html t = 64 match t.content with 65 | `Html html -> Some html 66 | `Text _ -> None 67 | `Both (html, _) -> Some html 68 69let content_text t = 70 match t.content with 71 | `Html _ -> None 72 | `Text text -> Some text 73 | `Both (_, text) -> Some text 74 75let equal a b = 76 (* Items are equal if they have the same ID *) 77 a.id = b.id 78 79let compare a b = 80 (* Compare by publication date, with items without dates considered older *) 81 match a.date_published, b.date_published with 82 | None, None -> 0 83 | None, Some _ -> -1 (* Items without dates are "older" *) 84 | Some _, None -> 1 85 | Some da, Some db -> Ptime.compare da db 86 87let pp_content ppf = function 88 | `Html html -> 89 Format.fprintf ppf "HTML (%d chars)" (String.length html) 90 | `Text text -> 91 Format.fprintf ppf "Text (%d chars)" (String.length text) 92 | `Both (html, text) -> 93 Format.fprintf ppf "Both (HTML: %d chars, Text: %d chars)" 94 (String.length html) (String.length text) 95 96let pp ppf t = 97 match t.date_published, t.title with 98 | Some date, Some title -> 99 (* Use Ptime's date formatting *) 100 let (y, m, d), _ = Ptime.to_date_time date in 101 Format.fprintf ppf "[%04d-%02d-%02d] %s (%s)" y m d title t.id 102 | Some date, None -> 103 let (y, m, d), _ = Ptime.to_date_time date in 104 Format.fprintf ppf "[%04d-%02d-%02d] %s" y m d t.id 105 | None, Some title -> 106 Format.fprintf ppf "%s (%s)" title t.id 107 | None, None -> 108 Format.fprintf ppf "%s" t.id