summaryrefslogtreecommitdiffhomepage
path: root/dlang/src/read/verify.d
blob: 21d4a8700111608a53f1bca1a60d6f99b8ae7e04 (plain)
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
/+
- Name: SisuDoc Spine, Doc Reform [a part of]
  - Description: documents, structuring, processing, publishing, search
    - static content generator

  - Author: Ralph Amissah
    [ralph.amissah@gmail.com]

  - Copyright: (C) 2015 (continuously updated, current 2026) Ralph Amissah, All Rights Reserved.

  - License: AGPL 3 or later:

    Spine (SiSU), a framework for document structuring, publishing and
    search

    Copyright (C) Ralph Amissah

    This program is free software: you can redistribute it and/or modify it
    under the terms of the GNU AFERO General Public License as published by the
    Free Software Foundation, either version 3 of the License, or (at your
    option) any later version.

    This program is distributed in the hope that it will be useful, but WITHOUT
    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
    more details.

    You should have received a copy of the GNU General Public License along with
    this program. If not, see [https://www.gnu.org/licenses/].

    If you have Internet connection, the latest version of the AGPL should be
    available at these locations:
    [https://www.fsf.org/licensing/licenses/agpl.html]
    [https://www.gnu.org/licenses/agpl.html]

  - Spine (by Doc Reform, related to SiSU) uses standard:
    - docReform markup syntax
      - standard SiSU markup syntax with modified headers and minor modifications
    - docReform object numbering
      - standard SiSU object citation numbering & system

  - Homepages:
    [https://www.sisudoc.org]
    [https://www.doc-reform.org]

  - Git
    [https://git.sisudoc.org/]

+/
module read.verify;

import std.algorithm : sort;
import std.array : array, join;
import std.conv : to;
import std.digest : toHexString;
import std.digest.sha : SHA256, digest;
import std.file : dirEntries, exists, isDir, SpanMode, getSize;
import std.path : baseName, buildPath, extension;
import std.stdio : writeln, File;
import std.string : toLower;
import ocda.model;
import read.images : gatherImageRecords;

/+ ↓ verification: recompute what the .image records claim, against the
   images as they stand in a directory (a pod's media/image).

     ssp-reader --verify --image-dir=<pod>/media/image doc.ssp

   Reports one line per distinct file:

     OK        won_benkler_2_1.png
     MISMATCH  won_benkler_2_1.png sha256 recorded 5BA4... file 1C3D...
     ABSENT    won_benkler_2_1.png (recorded sha256 5BA4..., not in directory)
     PRESENT   ffa.png (recorded missing, but the file is there)
     EXTRA     unused.png (in directory, no record in this .ssp)

   Returns the number of failures. EXTRA is reported but is not a failure:
   a pod carries the images of every language version of a document, while
   one .ssp covers one language.
+/
int verifyImages(OcdaDocument doc, string image_dir, string output_file) {
  string[] lines;
  int failures  = 0;
  int ok        = 0;
  int mismatch  = 0;
  int absent    = 0;
  int extra     = 0;

  if (!(image_dir.exists) || !(image_dir.isDir)) {
    writeln("ERROR: image directory not found: ", image_dir);
    return 1;
  }
  auto gathered = gatherImageRecords(doc);
  bool[string] recorded;

  foreach (e; gathered.entries) {
    recorded[e.name] = true;
    string pth = buildPath(image_dir, e.name);
    if (!(pth.exists)) {
      if (e.missing) {
        /+ recorded missing, and missing here too: consistent +/
        ok += 1;
        lines ~= "OK        " ~ e.name ~ " (recorded missing, absent here)";
      } else {
        absent += 1;
        failures += 1;
        lines ~= "ABSENT    " ~ e.name
          ~ " (recorded sha256 " ~ e.sha256 ~ ", not in directory)";
      }
      continue;
    }
    if (e.missing) {
      mismatch += 1;
      failures += 1;
      lines ~= "PRESENT   " ~ e.name ~ " (recorded missing, but the file is there)";
      continue;
    }
    auto file_ = readFileStat(pth);
    string[] differs;
    if (file_.sha256 != e.sha256) {
      differs ~= "sha256 recorded " ~ e.sha256 ~ " file " ~ file_.sha256;
    }
    if (file_.bytes != e.bytes) {
      differs ~= "bytes recorded " ~ e.bytes.to!string
        ~ " file " ~ file_.bytes.to!string;
    }
    /+ px is written only where the dimensions could be read, and read here
       only for the formats below, so compare only when both are known +/
    if (e.width > 0 && e.height > 0 && file_.width > 0 && file_.height > 0
      && (file_.width != e.width || file_.height != e.height)) {
      differs ~= "px recorded " ~ e.width.to!string ~ "x" ~ e.height.to!string
        ~ " file " ~ file_.width.to!string ~ "x" ~ file_.height.to!string;
    }
    if (differs.length > 0) {
      mismatch += 1;
      failures += 1;
      lines ~= "MISMATCH  " ~ e.name ~ " " ~ differs.join("; ");
    } else {
      ok += 1;
      lines ~= "OK        " ~ e.name;
    }
  }

  /+ ↓ files in the directory that no record names +/
  string[] in_dir;
  foreach (entry; dirEntries(image_dir, SpanMode.shallow)) {
    if (!(entry.isFile)) continue;
    string nm = entry.name.baseName;
    switch (nm.extension.toLower) {
      case ".png": case ".jpg": case ".jpeg": case ".gif":
        in_dir ~= nm;
        break;
      default: break;
    }
  }
  in_dir.sort;
  foreach (nm; in_dir) {
    if (nm !in recorded) {
      extra += 1;
      lines ~= "EXTRA     " ~ nm ~ " (in directory, no record in this .ssp)";
    }
  }

  string head = "Verify: " ~ gathered.entries.length.to!string ~ " distinct file"
    ~ ((gathered.entries.length == 1) ? "" : "s")
    ~ " in " ~ gathered.records.to!string ~ " record"
    ~ ((gathered.records == 1) ? "" : "s")
    ~ ", against " ~ image_dir;
  lines = [head, ""] ~ lines;
  lines ~= "";
  lines ~= "verify: " ~ ok.to!string ~ " ok, "
    ~ mismatch.to!string ~ " mismatch, "
    ~ absent.to!string ~ " absent, "
    ~ extra.to!string ~ " extra"
    ~ ((failures == 0) ? "  PASS" : "  FAIL");

  /+ ↓ write output +/
  if (output_file.length > 0) {
    auto f = File(output_file, "w");
    foreach (line; lines) f.writeln(line);
  } else {
    foreach (line; lines) writeln(line);
  }
  return failures;
}

private struct FileStat_ {
  string sha256;
  ulong  bytes;
  int    width;
  int    height;
}

private FileStat_ readFileStat(string pth) {
  FileStat_ ret;
  auto f = File(pth, "rb");
  ubyte[32] sha = digest!SHA256(f.byChunk(4096 * 1024));
  ret.sha256 = sha.toHexString.to!string;
  ret.bytes  = pth.getSize;
  auto dim = readImageDimensions(pth);
  ret.width  = dim[0];
  ret.height = dim[1];
  return ret;
}

/+ ↓ pixel dimensions from the file header, for the formats spine's markup
   admits (png, gif, jpg). Header read only, no decoding, and no dependency
   beyond phobos. Returns [0, 0] where the header cannot be read
+/
private int[2] readImageDimensions(string pth) {
  int[2] ret = [0, 0];
  ubyte[] head;
  try {
    auto f = File(pth, "rb");
    head = new ubyte[](64 * 1024);
    head = f.rawRead(head);
  } catch (Exception ex) {
    return ret;
  }
  if (head.length >= 24
    && head[0 .. 8] == cast(ubyte[])[0x89, 'P', 'N', 'G', 0x0d, 0x0a, 0x1a, 0x0a]) {
    /+ png: IHDR width & height, big endian, at 16 and 20 +/
    ret[0] = beInt(head[16 .. 20]);
    ret[1] = beInt(head[20 .. 24]);
    return ret;
  }
  if (head.length >= 10 && (head[0 .. 3] == cast(ubyte[])['G', 'I', 'F'])) {
    /+ gif: logical screen width & height, little endian, at 6 and 8 +/
    ret[0] = head[6] | (head[7] << 8);
    ret[1] = head[8] | (head[9] << 8);
    return ret;
  }
  if (head.length >= 4 && head[0] == 0xff && head[1] == 0xd8) {
    /+ jpeg: walk the segments to a start of frame, height then width,
       big endian, at offsets 5 and 7 of the segment
    +/
    size_t i = 2;
    while (i + 9 < head.length) {
      if (head[i] != 0xff) { i += 1; continue; }
      ubyte marker = head[i + 1];
      if (marker == 0xd8 || marker == 0x01
        || (marker >= 0xd0 && marker <= 0xd7)) { i += 2; continue; }
      if (marker == 0xff) { i += 1; continue; }
      size_t seg_len = (head[i + 2] << 8) | head[i + 3];
      bool is_sof = ((marker >= 0xc0 && marker <= 0xc3)
        || (marker >= 0xc5 && marker <= 0xc7)
        || (marker >= 0xc9 && marker <= 0xcb)
        || (marker >= 0xcd && marker <= 0xcf));
      if (is_sof) {
        ret[1] = (head[i + 5] << 8) | head[i + 6];
        ret[0] = (head[i + 7] << 8) | head[i + 8];
        return ret;
      }
      if (seg_len < 2) break;
      i += 2 + seg_len;
    }
  }
  return ret;
}

private int beInt(const(ubyte)[] b) {
  return cast(int)((b[0] << 24) | (b[1] << 16) | (b[2] << 8) | b[3]);
}