Source file utils.ml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
(** Utilities *)
type E.error +=
| Time_error of string
let () = E.register_string_of_error
(function
| Time_error msg -> Some (Printf.sprintf "Time error: %s" msg)
| _ -> None)
let sha256 str =
let hash = Cryptokit.Hash.sha256 () in
hash#add_string str ;
let str = hash#result in
hash#wipe ;
str
let mkdir dir =
let com = Printf.sprintf "mkdir -p %s" (Filename.quote dir) in
match%lwt Lwt_process.(exec (shell com)) with
Unix.WEXITED 0 -> Lwt.return_unit
| _ -> Lwt.fail_with (Printf.sprintf "Command failed: %s" com)
let dir_exists dir =
try%lwt
let%lwt s = Lwt_unix.stat dir in
match s.Unix.st_kind with
| S_DIR -> Lwt.return_true
| _ -> Lwt.return_false
with Unix.Unix_error _ -> Lwt.return_false
(** [graph_keep_only_from ?keep g term] returns a new graph with the same name as [g],
keeping only triples reachable from [term], and only following blank nodes or
IRIs when [keep iri] returns [true], i.e. when an IRI is encountered, we do
not add triples with this IRI as subject if [keep iri] returns [false].
Default [keep] always return false. *)
let graph_keep_only_from =
let module S = Rdf.Term.TSet in
let rec f keep g1 g2 seen (sub, pred, obj) =
g2.Rdf.Graph.add_triple ~sub ~pred ~obj;
match obj with
| Rdf.Term.Blank_ _ -> fold keep g1 g2 seen obj
| Rdf.Term.Iri iri when keep iri -> fold keep g1 g2 seen obj
| _ -> seen
and fold keep g1 g2 seen sub =
if S.mem sub seen then
seen
else
let seen = S.add sub seen in
List.fold_left (f keep g1 g2) seen (g1.Rdf.Graph.find ~sub ())
in
fun ?(keep=(fun _ -> false)) g term ->
let g2 = Rdf.Graph.(open_graph (g.name())) in
ignore (fold keep g g2 S.empty term);
g2
let filename_wrapper =
let to_json ?with_doc fn = `String fn in
let from_json ?def = function
| `String str ->
begin
if Filename.is_relative str then
Filename.concat (Sys.getcwd()) str
else
str
end
| json -> Ocf.invalid_value json
in
Ocf.Wrapper.make to_json from_json
let iri_wrapper =
let to_json ?with_doc iri = `String (Iri.to_string iri) in
let from_json ?def = function
| `String str -> Iri.of_string str
| json -> Ocf.invalid_value json
in
Ocf.Wrapper.make to_json from_json
let mime_wrapper =
let to_json ?with_doc mime = `String (Ldp.Ct.mime_to_string mime) in
let from_json ?def = function
| (`String str) as json ->
(match Ldp.Ct.mime_of_string str with
| Error _ -> Ocf.invalid_value json
| Ok m -> m)
| json -> Ocf.invalid_value json
in
Ocf.Wrapper.make to_json from_json
let ptime_wrapper =
let to_json ?with_doc t = `String (Ptime.to_rfc3339 t) in
let of_json ?def = function
| `String s ->
(
match Ptime.(rfc3339_error_to_msg (of_rfc3339 s)) with
| Error (`Msg msg) ->
Log.err (fun m -> m "%s: %s" s msg);
Ocf.invalid_value (`String s)
| Ok (t, _, _) -> t
)
| json -> Ocf.invalid_value json
in
Ocf.Wrapper.make to_json of_json
let is_prefix_iri =
let rec is_prefix_path l1 l2 =
match l1, l2 with
| [], [] -> true
| _, [] -> false
| [], _
| [""], _ -> true
| h1 :: q1, h2 :: q2 -> h1 = h2 && is_prefix_path q1 q2
in
fun i1 i2 ->
let open Iri in
let b =
Iri.scheme i1 = Iri.scheme i2
&& Iri.host i1 = Iri.host i2
&& Iri.user i1 = Iri.user i2
&& Iri.port i1 = Iri.port i2
&& (
match Iri.path i1, Iri.path i2 with
| Absolute l1, Absolute l2 -> is_prefix_path l1 l2
| _ -> false
)
in
b
let static_mime str =
match Ldp.Ct.mime_of_string str with
| Ok t -> t
| Error e -> prerr_endline (Ldp.Ct.string_of_error e); assert false
let mime_xhtml = Ldp.Ct.mime_xhtml
let mime_nquads = static_mime "application/n-quads"
let mime_jsonld = static_mime "application/ld+json"
let mime_ap = static_mime "application/activity+json"
let mime_jrd_json = static_mime "application/jrd+json"
let jsonld_document_loader (dl: ?headers:Cohttp.Header.t -> Iri.t -> (string, exn) result Lwt.t) iri =
match Iri.Map.find_opt iri Jsonld_static.contexts with
| Some str -> Lwt.return_ok str
| None ->
let = Cohttp.Header.init_with "accept" (Ldp.Ct.mime_to_string mime_jsonld) in
dl ~headers iri
let : Ldp.Types.meta -> string option = fun meta ->
let (resp, _) = meta.Ldp.Types.info in
let h = resp.headers in
Cohttp.Header.get h "location"
let list_slice =
let rec iter acc ~start ~stop i = function
| [] -> List.rev acc
| h :: q ->
if i > stop then
List.rev acc
else
let acc =
if i >= start && i <= stop then h::acc else acc
in
iter acc ~start ~stop (i+1) q
in
fun ~start ~stop l -> iter [] ~start ~stop 0 l
module AS = Rdf.Activitypub
let hack_jsonld : Rdf_json_ld.J.json -> Rdf_json_ld.J.json =
let open Rdf_json_ld.J in
let contexts =
List.map Iri.of_string
[ "https://www.w3.org/ns/activitystreams#" ;
"https://w3id.org/security/v1#" ;
"http://www.w3.org/ns/ldp#" ;
"http://www.w3.org/1999/02/22-rdf-syntax-ns#" ;
]
in
let map_iri str =
match Iri.of_string str with
| iri ->
if List.exists (fun i -> is_prefix_iri iri i) contexts then
match Iri.fragment iri with
| None -> None
| Some k -> Some k
else
None
| exception _ -> None
in
let split_values_on_id = function
| { data = `Obj l } ->
List.fold_left (fun (acc, acc_other) -> function
| { data = "id"}, v -> v, acc_other
| { data = "@id"}, _ -> acc, acc_other
| k, v -> acc, (k,v) :: acc_other
) (Rdf_json_ld.J.string "", []) l
| x -> x, []
in
let rec simplify_obj (json:json) : json =
match json.data with
| `Obj [ {data="id"}, v ] -> v
| `Obj [ {data="@value"}, v ] -> v
| `List l -> { json with data = `List (List.map simplify_obj l) }
| _ -> json
in
let rec iter = function
| { data = `Obj fields } as x ->
let fields = List.map iter_assoc fields in
let fields =
match Rdf_json_ld.J.map_get fields "type" with
| Some { data = `String ("OrderedCollection" | "OrderedCollectionPage") } ->
(match Rdf_json_ld.J.map_get fields "items" with
| None -> fields
| Some v ->
Rdf_json_ld.J.(map_add_value
(map_remove_value fields "items") "orderedItems" v)
)
| _ -> fields
in
let (fields, replaced_fields) =
match List.find_opt (function ({ data = "id" },_) -> true | _ -> false) fields with
| None ->
List.fold_left (fun (acc_f, acc_rf) -> function
| ({data = "@id"} as k, v) ->
let v_id, other_fields = split_values_on_id v in
({ k with data = "id"}, v_id) :: acc_f, acc_rf @ other_fields
| x -> x::acc_f, acc_rf
) ([], []) fields
| Some (k,v) ->
let fields = List.filter
(function ({ data = ("@id"|"id") },_) -> false | _ -> true) fields
in
let v_id, other_fields = split_values_on_id v in
let fields = (k,v_id) :: fields in
fields, other_fields
in
let fields = List.fold_left
(fun map (k,v) ->
Rdf_json_ld.J.(map_add_value (map_remove_value map k.data) k.data v))
fields replaced_fields
in
let fields = List.map
(function
(k, ({ data = `Obj l } as v)) ->
if List.exists
(function ({data="@type"}, {data=`String "http://www.w3.org/2001/XMLSchema#dateTime"}) -> true
| _ -> false)
l
then
match Rdf_json_ld.J.map_get l "@value" with
| None -> (k, v)
| Some va -> (k, va)
else (k, v)
| x -> x
)
fields
in
let fields = List.map (fun (k, v) -> (k, simplify_obj v)) fields in
{ x with data = `Obj fields }
| { data = `List l} as x -> { x with data = `List (List.map iter l) }
| { data = `String str} as x ->
(match map_iri str with
| None -> x
| Some frag -> { x with data = `String frag }
)
| x -> x
and iter_assoc (key, json) =
let key =
match map_iri key.data with
| None -> key
| Some k -> {key with data = k}
in
let json =
match key.data, json.data with
| "@id", `String str ->
(match map_iri str with
| None -> iter json
| Some frag -> ranged (`String frag))
| "type", `Obj [{ data = "@id" }, json] -> iter json
| ("to" | "cc" | "bto" | "bcc"), `List _ -> iter json
| ("to" | "cc" | "bto" | "bcc"), _ ->
iter (ranged (`List [json]))
| _ -> iter json
in
(key, json)
in
fun json ->
match iter json with
| { data = `Obj fields } as x->
(
let fields =
(ranged "@context", ranged (`List [
ranged (`String "https://www.w3.org/ns/activitystreams") ;
ranged (`String "https://w3id.org/security/v1") ;
])) :: fields
in
{ x with data = `Obj fields }
)
| x -> iter x
let log_level_wrapper : Logs.level option Ocf.Wrapper.t =
let to_j ?with_doc k = `String (Logs.level_to_string k) in
let from_j ?def = function
| `String s ->
(match Logs.level_of_string s with
| Ok l -> l
| Error (`Msg _) ->
failwith (Printf.sprintf "invalid log level %S" s)
)
| json ->
let msg = Printf.sprintf
"Invalid key %S" (Yojson.Safe.to_string json)
in
failwith msg
in
Ocf.Wrapper.make to_j from_j
let to_ptime f =
match Ptime.of_float_s f with
| None -> E.error (Time_error (Printf.sprintf "invalid time %f" f))
| Some t -> t
let ptime_now () = to_ptime (Unix.gettimeofday ())
let ptime_to_utc_string t =
let www =
Ptime.weekday t |> function `Sat -> "Sat" |`Fri -> "Fri" |`Mon -> "Mon" |`Wed -> "Wed" |`Sun -> "Sun" |`Tue -> "Tue" |`Thu -> "Thu" in
let ((yyyy,mmm,dd), ((hh,mm,ss), _)) = Ptime.to_date_time t in
let mmm = match mmm with
| 1 -> "Jan" | 2 -> "Feb" | 3 -> "Mar" | 4 -> "Apr" | 5 -> "May"
| 6 -> "Jun" | 7 -> "Jul" | 8 -> "Aug" | 9 -> "Sep" | 10 -> "Oct"
| 11 -> "Nov" | 12 -> "Dec" | _ -> assert false in
Printf.sprintf "%s, %02d %s %04d %02d:%02d:%02d GMT"
www dd mmm yyyy hh mm ss