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
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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
const generateTab = document.querySelector("#generateTab");
const verifyTab = document.querySelector("#verifyTab");
const displayVerify = document.querySelectorAll(".display-verify");
const displayGenerate = document.querySelectorAll(".display-generate");
const uploadForm = document.querySelector(".verify-upload-form");
const imageGenForm = document.querySelector(".image-gen-form");
const imagePrompt = document.getElementById("prompt");
const model = document.getElementById("model");
const generateTerms = document.getElementById("generate-terms");
const generateButton = document.getElementById("generate-button");

const fileUpload = document.getElementById("fileUpload");
const verifyButton = document.getElementById("verify-button");
const verifyTerms = document.getElementById("verify-terms");

const generateImageContainer = document.querySelector(
  ".display-generate .image-container"
);
const generateActionMenu = document.querySelector(".action-menu");
const verifyImageContainer = document.querySelector(
  ".display-verify .image-container"
);
const uploadedImageContainer = document.querySelector("#original-image");
const downloadButton = document.getElementById("download-button");
const verifyResultDescription = document.getElementById(
  "verifyResultDescription"
);
const verificationOutput = document.getElementById("verification-output");
const certificateList = document.getElementById("certificate-list");
const outputContainer = document.querySelector(".output-container");
const contentCredentialsIcon = document.getElementById(
  "content-crendentials-icon"
);
const digitalWatermarkIcon = document.getElementById("digital-watermark-icon");

var certificates = [];

[imagePrompt, model, generateTerms].forEach((item) => {
  item.addEventListener("change", async (event) => {
    setGenerateButtonStatus();
  });
});

const setGenerateButtonStatus = () => {
  if (imagePrompt.value && model.value && generateTerms.checked)
    generateButton.classList.add("active");
  else generateButton.classList.remove("active");
};

[fileUpload, verifyTerms].forEach((item) => {
  item.addEventListener("change", async (event) => {
    setVerifyButtonStatus();
  });
});

const setVerifyButtonStatus = () => {
  if (fileUpload.value && verifyTerms.checked)
    verifyButton.classList.add("active");
  else verifyButton.classList.remove("active");
};

generateTab.addEventListener("click", (event) => {
  event.target.classList.add("active");
  verifyTab.classList.remove("active");

  setGenerateElementsDisplay("block");
  setVerifyElementsDisplay("none");
});

verifyTab.addEventListener("click", (event) => {
  event.target.classList.add("active");
  generateTab.classList.remove("active");

  setGenerateElementsDisplay("none");
  setVerifyElementsDisplay("block");
});

document
  .getElementById("goto-verify-button")
  .addEventListener("click", (event) => {
    verifyTab.classList.add("active");
    generateTab.classList.remove("active");

    setVerifyElementsDisplay("block");
    setGenerateElementsDisplay("none");
  });

function setGenerateElementsDisplay(displayStatus) {
  displayGenerate.forEach((item) => {
    item.style.display = displayStatus;
  });
}

function setVerifyElementsDisplay(displayStatus) {
  displayVerify.forEach((item) => {
    item.style.display = displayStatus;
  });
}

uploadForm.addEventListener("submit", (e) => {
  e.preventDefault();
  submitForm();
});

function submitForm() {
  if (!fileUpload.value || !verifyTerms.checked) return;

  const file = document.getElementById("fileUpload").files[0];

  let fileReader = new FileReader();
  fileReader.readAsDataURL(file);
  fileReader.onload = function () {
    document
      .getElementById("uploaded-image")
      .setAttribute("src", fileReader.result);
  };

  verifyImageContainer.style.display = "flex";

  document.querySelector(".display-verify .error").style.display = "none";
  placeholder = document.querySelector(".display-verify .placeholder");
  spinner = document.querySelector(".display-verify .spinner");
  placeholder.style.display = "none";

  if (document.getElementById("verifyresult"))
    document.getElementById("verifyresult").remove(); // JCL make sure to remove the correct one
  spinner.style.display = "block";

  outputContainer.style.display = "none";
  document.getElementById("resultLabel").style.display = "none";
  uploadedImageContainer.style.display = "none";

  const formData = new FormData(uploadForm);

  // Add additional form data as needed
  //formData.append('additionalData', 'additionalValue');

  // Call function to submit form data
  submitFormData(formData);
}

function submitFormData(formData) {
  fetch("verify", {
    method: "POST",
    body: formData,
  })
    .then((response) => response.json())
    .then((data) => {
      console.log(data);

      fileUpload.value = "";
      setVerifyButtonStatus();

      if (data.contains_c2pa == "true") {
        contentCredentialsIcon.setAttribute("class", "check-icon");
      } else {
        contentCredentialsIcon.setAttribute("class", "x-icon");
      }

      if (data.contains_watermark == "true") {
        digitalWatermarkIcon.setAttribute("class", "check-icon");
      } else {
        digitalWatermarkIcon.setAttribute("class", "x-icon");
      }

      if (data.contains_c2pa == "true" && data.contains_watermark == "true") {
        verifyResultDescription.innerHTML =
          "Your image contains content credentials, which are displayed below.";
      } else if (
        data.contains_c2pa == "false" &&
        data.contains_watermark == "true"
      ) {
        verifyResultDescription.innerHTML =
          "The watermark was found, but image modifications were also detected. The last untampered, signed version on file is displayed.";
      } else if (
        data.contains_c2pa == "true" &&
        data.contains_watermark == "false"
      ) {
        verifyResultDescription.innerHTML =
          "Your image contains content credentials, which are displayed below. A watermark was not detected.";
      } else if (
        data.contains_c2pa == "false" &&
        data.contains_watermark == "false"
      ) {
        verifyResultDescription.innerHTML =
          "Nothing to show: this image contains neither content credentials, nor a watermark.";
      }

      uploadedImageContainer.style.display = "flex";
      document.getElementById("resultLabel").style.display = "block";

      document.querySelector(".display-verify .spinner").style.display = "none";

      if (data.result_media != "n/a") {
        const path = "/" + data.result_media;

        var truepicDisplay = document.createElement("truepic-display");

        truepicDisplay.addEventListener(
          "validate",
          setVerificationOutputFromValidation
        );
        truepicDisplay.addEventListener(
          "validate",
          setCertificateOutputFromValidation
        );

        truepicDisplay.setAttribute("id", "verifyresult");
        truepicDisplay.setAttribute("active", "");
        var truepic = document.createElement("img");
        truepic.src = path;

        truepicDisplay.appendChild(truepic);

        verifyImageContainer.appendChild(truepicDisplay);

        outputContainer.style.display = "block";
      } else {
        verifyImageContainer.style.display = "none";
      }
      // Handle response data
    })
    .catch((error) => {
      console.log(error);
      document.querySelector(".display-verify .error").style.display = "block";

      fileUpload.value = "";
      setVerifyButtonStatus();

      document.querySelector(".display-verify .spinner").style.display = "none";
      document.querySelector(".display-verify .placeholder").style.display =
        "block";
      // Handle errors
    });
}

const generateImage = async (text, model) => {
  const inferResponse = await fetch(`generate?prompt=${text}&model=${model}`);
  const inferJson = await inferResponse.json();

  return inferJson.response;
};

imageGenForm.addEventListener("submit", async (event) => {
  event.preventDefault();

  if (!imagePrompt.value || !model.value || !generateTerms.checked) return;

  placeholder = document.querySelector(".display-generate .placeholder");
  spinner = document.querySelector(".display-generate .spinner");
  generateActionMenu.style.display = "none";
  document.querySelector(".display-generate .error").style.display = "none";

  // parameters.style.display = "none";

  try {
    placeholder.style.display = "none";
    if (document.getElementById("genresult"))
      document.getElementById("genresult").remove(); // JCL make sure to remove the correct one

    spinner.style.display = "block";

    const resp = await generateImage(imagePrompt.value, model.value);
    const path = "/" + resp;

    var truepicDisplay = document.createElement("truepic-display");

    truepicDisplay.setAttribute("id", "genresult");
    truepicDisplay.setAttribute("active", "");
    var truepic = document.createElement("img");
    truepic.src = path;

    truepicDisplay.appendChild(truepic);

    spinner.style.display = "none";
    generateImageContainer.appendChild(truepicDisplay);

    downloadButton.href = path;
    downloadButton.download = resp;

    generateActionMenu.style.display = "block";

    /*
    

    modelParam.innerHTML = model.value;
    promptParam.innerHTML = textGenInput.value;
    parameters.style.display = "block";
    */
  } catch (err) {
    console.error(err);
    document.querySelector(".display-generate .error").style.display = "block";
    spinner.style.display = "none";
    placeholder.style.display = "block";
  }
});

function setVerificationOutputFromValidation(event) {
  //verificationDetails.style.display = "block";
  return setVerificationOutput(event.detail.manifestStore.toJSON());
}

function setCertificateOutputFromValidation(event) {
  return setCertificateOutput(event.detail.manifestStore);
}

function setVerificationOutput(output = null) {
  verificationOutput.innerHTML = "";

  if (!output) {
    return;
  }

  const viewer = new JSONViewer();

  verificationOutput.appendChild(viewer.getContainer());

  viewer.showJSON(output);
}

function setCertificateOutput(manifestStore = null) {
  const certificate = manifestStore?.activeManifest?.certificate;

  if (!certificate) {
    return;
  }

  certificates = [
    {
      der: certificate.der,
      name: certificate.subjectName,
      decoded: new x509.X509Certificate(certificate.der),
    },
    ...certificate.chain.map((certificate) => ({
      der: certificate.der,
      decoded: new x509.X509Certificate(certificate.der),
    })),
  ];

  certificates.forEach((certificate) => {
    certificate.transformed = transformCert(certificate.decoded);
  });

  console.log("certificates", certificates);

  certificateList.innerHTML = "";

  certificates.forEach((certificate, index) => {
    var li = document.createElement("li");
    if (index == 0) li.classList.add("active");
    li.appendChild(
      document.createTextNode(certificate.transformed.subjectCommonName)
    );
    li.addEventListener("click", function (e) {
      setCertificate(index);
      const lis = document.querySelectorAll("#certificate-list li");

      lis.forEach((element) => {
        element.classList.remove("active");
      });

      this.classList.add("active");
    });

    certificateList.appendChild(li);
  });

  setCertificate(0);
}

function transformCert(certificate) {
  const {
    issuer,
    subject,
    notAfter: expired,
    notBefore: issued,
    serialNumber,
    publicKey: {
      algorithm: {
        name: algorithm,
        modulusLength: modulus,
        namedCurve: namedCurve,
      },
    },
  } = certificate;

  const parsedSubject = parseCertificateValues(subject);
  const parsedIssuer = parseCertificateValues(issuer);

  return {
    issuerCommonName: parsedIssuer["CN"],
    issuerOrganizationUnit: parsedIssuer["OU"],
    issuerOrganization: parsedIssuer["O"],
    issuerCountry: parsedIssuer["C"],
    subjectCommonName: parsedSubject["CN"],
    subjectOrganizationUnit: parsedSubject["OU"],
    subjectOrganization: parsedSubject["O"],
    subjectCountry: parsedSubject["C"],
    issued,
    expired,
    serialNumber,
    algorithm,
    modulus,
    namedCurve,
  };
}

function parseCertificateValues(input) {
  const params = new URLSearchParams(input.replaceAll(",", "&"));
  const responses = {};

  for (const entry of params.entries()) {
    responses[entry[0].trim()] = entry[1];
  }

  return responses;
}

function setCertificate(ind) {
  const certificate = certificates[ind].transformed;

  document.querySelector(".details .issuerCommonName").innerHTML =
    certificate.issuerCommonName;
  document.querySelector(".details .issuerOrganizationUnit").innerHTML =
    certificate.issuerOrganizationUnit;
  document.querySelector(".details .issuerOrganization").innerHTML =
    certificate.issuerOrganization;
  document.querySelector(".details .issuerCountry").innerHTML =
    certificate.issuerCountry;
  document.querySelector(".details .subjectCommonName").innerHTML =
    certificate.subjectCommonName;
  document.querySelector(".details .subjectOrganizationUnit").innerHTML =
    certificate.subjectOrganizationUnit;
  document.querySelector(".details .subjectOrganization").innerHTML =
    certificate.subjectOrganization;
  document.querySelector(".details .subjectCountry").innerHTML =
    certificate.subjectCountry;
  document.querySelector(".details .issued").innerHTML = certificate.issued;
  document.querySelector(".details .expired").innerHTML = certificate.expired;
  document.querySelector(".details .serialNumber").innerHTML =
    certificate.serialNumber;
  document.querySelector(".details .algorithm").innerHTML =
    certificate.algorithm;

  /*  
      if (certificate.modulus !== undefined) {
        document.querySelector(".details .modulus").innerHTML =
          certificate.modulus;
        document.querySelector("#modulusContainers").style.display = "block";
      } else {
        document.querySelector("#modulusContainers").style.display = "none";
      }
      */

  if (certificate.namedCurve !== undefined) {
    document.querySelector(".details .namedCurve").innerHTML =
      certificate.namedCurve;
    document.querySelector("#curveContainer").style.display = "block";
  } else {
    document.querySelector("#curveContainer").style.display = "none";
  }
}