Skip to content
Snippets Groups Projects
viamapi-iframe.js 60.4 KiB
Newer Older
  • Learn to ignore specific revisions
  • Alexey Lunin's avatar
    Alexey Lunin committed
            let success = extendPinCodeTtl(authenticationPublicKey);
    
    Alexey Lunin's avatar
    Alexey Lunin committed
            if (success === false) {
              result({
                data: "",
                code: "400",
                status: "Identity not authenticated"
              });
    
    Alexey Lunin's avatar
    Alexey Lunin committed
            getCertificateForPassport(passportUUID, true).then(
              certificateResult => {
                if (certificateResult.code === "200") {
    
    Alexey Lunin's avatar
    Alexey Lunin committed
                  let passportCertificate =
    
    Alexey Lunin's avatar
    Alexey Lunin committed
                    certificateResult.data["x509Certificate"];
    
    Alexey Lunin's avatar
    Alexey Lunin committed
                  let passportPrivateKey = certificateResult.data["privateKey"];
                  let passportChain = certificateResult.data["chain"];
    
    Alexey Lunin's avatar
    Alexey Lunin committed
    
                  createOneTimePassportCertificate(
                    makeid() + "-" + passportUUID,
                    emailArg,
                    passportPrivateKey,
                    passportCertificate
                  ).then(function(keys) {
    
    Alexey Lunin's avatar
    Alexey Lunin committed
                    let publicKeyOneTime = keys["publicKeyPEM"];
                    let privateKeyOneTime = keys["privateKeyPEM"];
                    let certificateOneTime = keys["certificatePEM"];
    
    Alexey Lunin's avatar
    Alexey Lunin committed
                    passportChain.push(passportCertificate);
    
    
    Alexey Lunin's avatar
    Alexey Lunin committed
                    let oneTimeCryptoData = new CryptoData();
    
    Alexey Lunin's avatar
    Alexey Lunin committed
                    oneTimeCryptoData.setx509Certificate(certificateOneTime);
                    oneTimeCryptoData.setPrivateKey(privateKeyOneTime);
                    oneTimeCryptoData.setPublicKey(publicKeyOneTime);
                    oneTimeCryptoData.setChain(passportChain);
    
                    result({
                      data: oneTimeCryptoData,
                      code: "200",
                      status: "One time certificate generated"
                    });
                    // Prints PEM formatted signed certificate
                    // -----BEGIN CERTIFICATE-----MIID....7Hyg==-----END CERTIFICATE-----
                  });
                } else {
                  result({
                    data: "",
                    code: "400",
                    status: "Can not generate one time certificate"
                  });
                }
    
    Alexey Lunin's avatar
    Alexey Lunin committed
            );
    
        verifySMIME: async (smimeString) => {
          const authenticationPublicKey = localStorage.getItem(
            "authenticatedIdentity"
          );
    
          if (
            !authenticationPublicKey ||
            !window.loadedIdentities[authenticationPublicKey] ||
            !extendPinCodeTtl(authenticationPublicKey)
          ) {
            return encodeResponse("400", "", "Identity not authenticated");
          }
    
    
    Damyan Mitev's avatar
    Damyan Mitev committed
          //TODO cache (for some time) the root certificate
          // either as PEM or as certificate object (preferred)
    
          const rootCaResponse = await executeRestfulFunction(
            "private",
            window.viamApi,
            window.viamApi.signRetrieveRootCertificate,
            null
          );
    
          if (rootCaResponse.code !== "200") {
            return encodeResponse("400", "", rootCaResponse.status);
          }
    
          const rootCaPem = rootCaResponse.data;
    
    Damyan Mitev's avatar
    Damyan Mitev committed
          const verificationResult = await verifySMIME(smimeString, rootCaPem);
    
    Damyan Mitev's avatar
    Damyan Mitev committed
          return encodeResponse("200", verificationResult.verified, verificationResult.message);
    
        signEmail: async (passportUUID, emailArg, emailMessage) => {
    
    Alexey Lunin's avatar
    Alexey Lunin committed
          const authenticationPublicKey = localStorage.getItem(
            "authenticatedIdentity"
          );
    
          if (
            !authenticationPublicKey ||
            !window.loadedIdentities[authenticationPublicKey] ||
            !extendPinCodeTtl(authenticationPublicKey)
          ) {
            return encodeResponse("400", "", "Identity not authenticated");
          }
    
          let response = await getCertificateForPassport(passportUUID, true);
    
          if (response.code !== "200") {
            return encodeResponse("400", "", response.status);
          }
    
          const {
            x509Certificate: passportCertificate,
            privateKey: passportPrivateKey,
            chain: passportChain
          } = response.data;
    
    Alexey Lunin's avatar
    Alexey Lunin committed
          const keys = await createOneTimePassportCertificate(
            makeid() + "-" + passportUUID,
            emailArg,
            passportPrivateKey,
            passportCertificate
          );
    
    Alexey Lunin's avatar
    Alexey Lunin committed
          const {
            privateKeyPEM: privateKeyOneTime,
            certificatePEM: certificateOneTime
          } = keys;
    
          passportChain.push(passportCertificate);
    
          response = await executeRestfulFunction(
    
    Alexey Lunin's avatar
    Alexey Lunin committed
            "private",
            window.viamApi,
            window.viamApi.passportGetEmailWithHeaderByPassport,
            null,
            passportUUID,
            emailMessage
          );
    
    
          if (response.code !== "200") {
            return encodeResponse("400", "", response.status);
          }
    
    
    Alexey Lunin's avatar
    Alexey Lunin committed
          const signedEmail = await signEmail(
            response.data,
            certificateOneTime,
            passportChain,
            privateKeyOneTime
          );
    
    
          response = await executeRestfulFunction(
    
    Alexey Lunin's avatar
    Alexey Lunin committed
            "private",
            window.viamApi,
            window.viamApi.signResignEmail,
            null,
            passportUUID,
            signedEmail
          );
    
    
          if (response.code !== "200") {
            return encodeResponse("400", "", response.status);
          }
    
          return encodeResponse("200", response.data, "Email signed");
    
    Damyan Mitev's avatar
    Damyan Mitev committed
        signDocument: async (passportUUID, documentUUID, documentContentType) => {
    
    Alexey Lunin's avatar
    Alexey Lunin committed
          const authenticationPublicKey = localStorage.getItem(
            "authenticatedIdentity"
          );
    
    Damyan Mitev's avatar
    Damyan Mitev committed
    
          if (
            !authenticationPublicKey ||
            !window.loadedIdentities[authenticationPublicKey] ||
            !extendPinCodeTtl(authenticationPublicKey)
          ) {
            return encodeResponse("400", "", "Identity not authenticated");
          }
    
    
          const certResponse = await getCertificateForPassport(passportUUID, true);
    
    Damyan Mitev's avatar
    Damyan Mitev committed
    
    
          if (certResponse.code !== "200") {
            return encodeResponse("400", "", certResponse.status);
    
    Damyan Mitev's avatar
    Damyan Mitev committed
          }
    
          const {
            x509Certificate: passportCertificate,
            privateKey: passportPrivateKey,
            chain: passportChain
    
          } = certResponse.data;
    
    Damyan Mitev's avatar
    Damyan Mitev committed
    
    
    Alexey Lunin's avatar
    Alexey Lunin committed
          const keys = await createOneTimePassportCertificate(
            makeid() + "-" + passportUUID,
            null,
            passportPrivateKey,
            passportCertificate
          );
    
    Damyan Mitev's avatar
    Damyan Mitev committed
    
    
    Alexey Lunin's avatar
    Alexey Lunin committed
          const {
            privateKeyPEM: privateKeyOneTime,
            certificatePEM: certificateOneTime
          } = keys;
    
    Damyan Mitev's avatar
    Damyan Mitev committed
    
    
    Gospodin Bodurov's avatar
    Gospodin Bodurov committed
          passportChain.reverse();
    
    
    Damyan Mitev's avatar
    Damyan Mitev committed
          passportChain.push(passportCertificate);
    
    
    Gospodin Bodurov's avatar
    Gospodin Bodurov committed
          passportChain.reverse();
    
    
    Alexey Lunin's avatar
    Alexey Lunin committed
          const pdfContentType = "application/pdf";
    
    Damyan Mitev's avatar
    Damyan Mitev committed
    
          if (documentContentType !== pdfContentType) {
            const convResponse = await executeRestfulFunction(
    
    Alexey Lunin's avatar
    Alexey Lunin committed
              "private",
              window.viamApi,
              window.viamApi.documentConvertDocumentByUUID,
              null,
              documentUUID,
              documentContentType,
              pdfContentType
            );
    
    Damyan Mitev's avatar
    Damyan Mitev committed
            if (convResponse.code !== "200") {
              return encodeResponse("400", "", convResponse.status);
            }
          }
    
          const downloadResponse = await executeRestfulFunction(
    
    Alexey Lunin's avatar
    Alexey Lunin committed
            "private",
            window.viamApi,
            window.viamApi.documentGetDocumentByUUID,
            null,
            documentUUID,
            pdfContentType
          );
    
    Damyan Mitev's avatar
    Damyan Mitev committed
    
          if (downloadResponse.code !== "200") {
            return encodeResponse("400", "", downloadResponse.status);
          }
    
    
          const pdfRaw = base64ToByteArray(downloadResponse.data);
    
    Damyan Mitev's avatar
    Damyan Mitev committed
    
    
          let signedPdf;
          try {
    
    Alexey Lunin's avatar
    Alexey Lunin committed
            signedPdf = await signPdf(
              pdfRaw,
              certificateOneTime,
              passportChain,
              privateKeyOneTime
            );
    
          } catch (err) {
            console.error(err);
            return encodeResponse("500", "", err.message);
          }
    
    Damyan Mitev's avatar
    Damyan Mitev committed
    
    
          const signedPdfB64 = byteArrayToBase64(signedPdf);
    
    
          const uploadResponse = await executeRestfulFunction(
    
    Alexey Lunin's avatar
    Alexey Lunin committed
            "private",
            window.viamApi,
            window.viamApi.documentPutDocumentByUUID,
            null,
            documentUUID,
            pdfContentType,
            signedPdfB64
          );
    
          if (uploadResponse.code !== "200") {
            return encodeResponse("400", "", uploadResponse.status);
          }
    
          const signResponse = await executeRestfulFunction(
    
    Alexey Lunin's avatar
    Alexey Lunin committed
            "private",
            window.viamApi,
            window.viamApi.documentSignDocumentByUUID,
            null,
            passportUUID,
            documentUUID,
            pdfContentType
          );
    
          if (signResponse.code !== "200") {
            return encodeResponse("400", "", signResponse.status);
          }
    
          return encodeResponse("200", "", "Document signed");
    
    Damyan Mitev's avatar
    Damyan Mitev committed
        },
    
        signDocumentJava: async (passportUUID, documentUUID, documentContentType) => {
          const authenticationPublicKey = localStorage.getItem(
            "authenticatedIdentity"
          );
    
          if (
            !authenticationPublicKey ||
            !window.loadedIdentities[authenticationPublicKey] ||
            !extendPinCodeTtl(authenticationPublicKey)
          ) {
            return encodeResponse("400", "", "Identity not authenticated");
          }
    
          const certResponse = await getCertificateForPassport(passportUUID, true);
    
          if (certResponse.code !== "200") {
            return encodeResponse("400", "", certResponse.status);
          }
    
          const {
            x509Certificate: passportCertificate,
            privateKey: passportPrivateKey,
            chain: passportChain
          } = certResponse.data;
    
          const keys = await createOneTimePassportCertificate(
            makeid() + "-" + passportUUID,
    
            passportPrivateKey,
            passportCertificate
          );
    
          const {
            privateKeyPEM: privateKeyOneTime,
            certificatePEM: certificateOneTime
          } = keys;
    
    
    Gospodin Bodurov's avatar
    Gospodin Bodurov committed
          passportChain.reverse();
    
    
          passportChain.push(passportCertificate);
          passportChain.push(certificateOneTime);
    
    
    Gospodin Bodurov's avatar
    Gospodin Bodurov committed
          passportChain.reverse();
    
    
          const pdfContentType = "application/pdf";
    
          if (documentContentType !== pdfContentType) {
            const convResponse = await executeRestfulFunction(
              "private",
              window.viamApi,
              window.viamApi.documentConvertDocumentByUUID,
              null,
              documentUUID,
              documentContentType,
              pdfContentType
            );
            if (convResponse.code !== "200") {
              return encodeResponse("400", "", convResponse.status);
            }
          }
    
          const signResponse = await executeRestfulFunction(
            "private",
            window.viamApi,
            window.viamApi.documentSignDocumentJavaService,
            null,
            privateKeyOneTime,
            passportChain,
            passportUUID,
            documentUUID,
            pdfContentType
          );
          if (signResponse.code !== "200") {
            return encodeResponse("400", "", signResponse.status);
          }
    
          return encodeResponse("200", "", "Document signed");
        },
    
        documentCreateDocument: async (passportUUID, path, contentType, title) => {
    
    Alexey Lunin's avatar
    Alexey Lunin committed
          const authenticationPublicKey = localStorage.getItem(
            "authenticatedIdentity"
          );
    
          if (
            !authenticationPublicKey ||
            !window.loadedIdentities[authenticationPublicKey] ||
            !extendPinCodeTtl(authenticationPublicKey)
          ) {
            return encodeResponse("400", "", "Identity not authenticated");
          }
    
    
          path = encodeURI(path);
          contentType = encodeURI(contentType);
          title = encodeURI(title);
    
    
          const config = {
            headers: {
              path,
              passportuuid: passportUUID,
    
    Alexey Lunin's avatar
    Alexey Lunin committed
          const response = await executeRestfulFunction(
            "private",
            window.viamApi,
            window.viamApi.documentCreateDocument,
            config
          );
    
          if (response.code !== "200") {
            return encodeResponse("400", "", response.status);
          }
    
    
          return encodeResponse("200", response.data, "Document created");
        },
    
    Alexey Lunin's avatar
    Alexey Lunin committed
        documentPutDocument: async (
          passportUUID,
          resourceid,
          contentType,
    
    Alexey Lunin's avatar
    Alexey Lunin committed
          file,
          upload
    
    Alexey Lunin's avatar
    Alexey Lunin committed
        ) => {
          const authenticationPublicKey = localStorage.getItem(
            "authenticatedIdentity"
          );
    
          if (
            !authenticationPublicKey ||
            !window.loadedIdentities[authenticationPublicKey] ||
            !extendPinCodeTtl(authenticationPublicKey)
          ) {
            return encodeResponse("400", "", "Identity not authenticated");
          }
    
    
          resourceid = encodeURI(resourceid);
          contentType = encodeURI(contentType);
    
    
    Alexey Lunin's avatar
    Alexey Lunin committed
              "Content-Type": "multipart/form-data",
    
              contentType,
              upload
    
    
          const response = await executeRestfulFunction(
    
    Alexey Lunin's avatar
    Alexey Lunin committed
            "private",
            window.viamApi,
            window.viamApi.documentPutDocument,
            config,
            file
          );
    
          if (response.code !== "200") {
            return encodeResponse("400", "", response.status);
          }
    
    
          return encodeResponse("200", response.data, "Document stored");
        },
    
        hasSession() {
          return new Penpal.Promise(result => {
    
    Alexey Lunin's avatar
    Alexey Lunin committed
            const authenticationPublicKey = localStorage.getItem(
              "authenticatedIdentity"
            );
    
            if (authenticationPublicKey === null) {
    
    Alexey Lunin's avatar
    Alexey Lunin committed
              result({
                data: "",
                code: "400",
                status: "Identity not authenticated"
    
            if (window.loadedIdentities[authenticationPublicKey] === null) {
    
    Alexey Lunin's avatar
    Alexey Lunin committed
              result({
                data: "",
                code: "400",
                status: "Identity not authenticated"
    
    Alexey Lunin's avatar
    Alexey Lunin committed
            let success = extendPinCodeTtl(authenticationPublicKey);
    
    Alexey Lunin's avatar
    Alexey Lunin committed
            if (success === false) {
              result({
                data: "",
                code: "400",
                status: "Identity not authenticated"
              });
    
    Alexey Lunin's avatar
    Alexey Lunin committed
            executeRestfulFunction(
              "private",
              viamApi,
              viamApi.identityHasSession,
              null
            ).then(executeResult => {
    
              result(executeResult);
            });
          });
        },
        marketingSignUpIdentificator(identificator, reference) {
          return new Penpal.Promise(result => {
    
    Markin Igor's avatar
    Markin Igor committed
            viamApi.setIdentity("marketingapppublickey");
    
    Alexey Lunin's avatar
    Alexey Lunin committed
            executeRestfulFunction(
              "public",
              viamApi,
              viamApi.marketingSignUpIdentificator,
              null,
              identificator,
              reference
            ).then(executeResult => {
    
    Markin Igor's avatar
    Markin Igor committed
              viamApi.setIdentity("");
    
    Markin Igor's avatar
    Markin Igor committed
              viamApi.setSessionData("", "");
    
              result(executeResult);
            });
          });
        },
        marketingGetIdentificatorProfile(identificator, pincode) {
          return new Penpal.Promise(result => {
    
    Markin Igor's avatar
    Markin Igor committed
            viamApi.setIdentity("marketingapppublickey");
    
    Alexey Lunin's avatar
    Alexey Lunin committed
            executeRestfulFunction(
              "public",
              viamApi,
              viamApi.marketingGetIdentificatorProfile,
              null,
              identificator,
              pincode
            ).then(executeResult => {
    
    Markin Igor's avatar
    Markin Igor committed
              viamApi.setIdentity("");
    
    Markin Igor's avatar
    Markin Igor committed
              viamApi.setSessionData("", "");
    
              result(executeResult);
            });
          });
        },
    
        marketingExecuteEventForIdentificator(identificator, pincode, event) {
    
          return new Penpal.Promise(result => {
    
    Markin Igor's avatar
    Markin Igor committed
            viamApi.setIdentity("marketingapppublickey");
    
    Alexey Lunin's avatar
    Alexey Lunin committed
            executeRestfulFunction(
              "public",
              viamApi,
              viamApi.marketingExecuteEventForIdentificator,
              null,
              identificator,
              pincode,
              event
            ).then(executeResult => {
    
    Markin Igor's avatar
    Markin Igor committed
              viamApi.setIdentity("");
    
    Markin Igor's avatar
    Markin Igor committed
              viamApi.setSessionData("", "");
    
              result(executeResult);
            });
          });
        },
        getCurrentlyAuthenticatedIdentity() {
    
    Alexey Lunin's avatar
    Alexey Lunin committed
          const {
            publicKey,
            x509Certificate
          } = window.currentlyAuthenticatedIdentity.authentication;
    
    
          return encodeResponse(
            "200",
            {
              authentication: {
                publicKey,
                x509Certificate
              }
            },
            "Currently authenticated identity"
          );
    
        stringToUtf8ByteArray(str) {
          return new Penpal.Promise(result => {
    
            result(stringToUtf8ByteArray(str));
          });
    
        },
        utf8ByteArrayToString(ba) {
          return new Penpal.Promise(result => {
    
            result(utf8ByteArrayToString(ba));
          });
    
        },
        stringToUtf8Base64(str) {
          return new Penpal.Promise(result => {
    
            result(stringToUtf8Base64(str));
          });
    
        },
        utf8Base64ToString(strBase64) {
          return new Penpal.Promise(result => {
    
            result(utf8Base64ToString(strBase64));
          });
    
        },
        base64ToByteArray(strBase64) {
          return new Penpal.Promise(result => {
    
            result(base64ToByteArray(strBase64));
          });
    
        },
        byteArrayToBase64(ba) {
          return new Penpal.Promise(result => {
    
            result(byteArrayToBase64(ba));
          });
    
    Alexey Lunin's avatar
    Alexey Lunin committed
    
        // Collabora APIs
    
        collaboraDiscovery() {
    
          return collaboraApi.discovery().then(apps => apps);
    
    Alexey Lunin's avatar
    Alexey Lunin committed
        // WOPI
    
    Gospodin Bodurov's avatar
    Gospodin Bodurov committed
        getPassportsNewProtocol: async (resourceID, contentType) => {
    
    Alexey Lunin's avatar
    Alexey Lunin committed
          const authenticationPublicKey = localStorage.getItem(
            "authenticatedIdentity"
          );
    
    Alexey Lunin's avatar
    Alexey Lunin committed
          if (
            !authenticationPublicKey ||
            !window.loadedIdentities[authenticationPublicKey] ||
            !extendPinCodeTtl(authenticationPublicKey)
          ) {
            return encodeResponse("400", "", "Identity not authenticated");
          }
    
    Alexey Lunin's avatar
    Alexey Lunin committed
          const response = await wopiAPI.getPassportsNewProtocol(
            resourceID,
            contentType
          );
    
    Alexey Lunin's avatar
    Alexey Lunin committed
          return response.data;
    
    Alexey Lunin's avatar
    Alexey Lunin committed
        getPassports: async fileId => {
    
    Alexey Lunin's avatar
    Alexey Lunin committed
          const authenticationPublicKey = localStorage.getItem(
            "authenticatedIdentity"
          );
    
    Alexey Lunin's avatar
    Alexey Lunin committed
          if (
            !authenticationPublicKey ||
            !window.loadedIdentities[authenticationPublicKey] ||
            !extendPinCodeTtl(authenticationPublicKey)
          ) {
            return encodeResponse("400", "", "Identity not authenticated");
          }
    
          const response = await wopiAPI.getPassports(fileId);
    
    Alexey Lunin's avatar
    Alexey Lunin committed
          return response.data;
    
        wopiCreateDocument: async (passportUUID, path, title) => {
    
    Alexey Lunin's avatar
    Alexey Lunin committed
          const authenticationPublicKey = localStorage.getItem(
            "authenticatedIdentity"
          );
    
          if (
            !authenticationPublicKey ||
            !window.loadedIdentities[authenticationPublicKey] ||
            !extendPinCodeTtl(authenticationPublicKey)
          ) {
            return encodeResponse("400", "", "Identity not authenticated");
          }
    
          const config = {
            headers: {
              path,
              passportuuid: passportUUID,
              title
            }
          };
    
          const createDocumentResult = await executeRestfulFunction(
    
    Alexey Lunin's avatar
    Alexey Lunin committed
            "private",
            window.viamApi,
            window.viamApi.documentCreateDocument,
            config
          );
    
          if (createDocumentResult.code !== "200") {
            return createDocumentResult;
    
    
          const resourceID = createDocumentResult.data;
    
          const accessTokenResponse = await wopiAPI.getAccessToken(passportUUID, resourceID);
    
          if (accessTokenResponse.data.code !== "200") {
            return accessTokenResponse.data;
          }
    
          const accessToken = accessTokenResponse.data.data;
    
    
          const result = {
            resourceID,
            accessToken
          };
    
          return encodeResponse("200", result, "ok");
    
        wopiGetAccessToken: async (passportUUID, resourceID, contentType) => {
          const authenticationPublicKey = localStorage.getItem(
            "authenticatedIdentity"
          );
    
          if (
            !authenticationPublicKey ||
            !window.loadedIdentities[authenticationPublicKey] ||
            !extendPinCodeTtl(authenticationPublicKey)
          ) {
            return encodeResponse("400", "", "Identity not authenticated");
          }
    
          const response = await wopiAPI.getAccessToken(passportUUID, resourceID, contentType);
          return response.data;
        },
    
    
        wopiPutFile: async (resourceID, accessToken, file) => {
    
    Alexey Lunin's avatar
    Alexey Lunin committed
          const authenticationPublicKey = localStorage.getItem(
            "authenticatedIdentity"
          );
    
    Alexey Lunin's avatar
    Alexey Lunin committed
          if (
            !authenticationPublicKey ||
            !window.loadedIdentities[authenticationPublicKey] ||
            !extendPinCodeTtl(authenticationPublicKey)
          ) {
            return encodeResponse("400", "", "Identity not authenticated");
          }
    
    
          const response = await wopiAPI.putDocument(resourceID, accessToken, file);
    
    Alexey Lunin's avatar
    Alexey Lunin committed
          return response.data;
    
    Markin Igor's avatar
    Markin Igor committed
    });
    
    connection.promise.then(parent => {
    
      iframeParent = parent;
    
    
      if (!navigator.cookieEnabled) {
        console.warn("Cookie disabled. Can't start library.");
        return;
      }
    
    Alexey Lunin's avatar
    Alexey Lunin committed
      window.addEventListener("storage", event => {
    
        if (event.key === "authenticatedIdentity" && event.newValue === null) {
    
    Alexey Lunin's avatar
    Alexey Lunin committed
          const publicKey =
            window.currentlyAuthenticatedIdentity.authentication.publicKey;
    
          window.currentlyLoadedIdentity = null;
          window.currentlyAuthenticatedIdentity = null;
    
    Markin Igor's avatar
    Markin Igor committed
          const event = createEvent("LogoutFromAnotherTab", "Logout", [publicKey]);
          parent.onEvent(event);
    
    Markin Igor's avatar
    Markin Igor committed
      const identities = localStorage.getItem("identities");
    
    Markin Igor's avatar
    Markin Igor committed
      console.log("Library loaded at: " + new Date().toISOString());
    
    
      if (identities === "" || identities === null) {
    
    Markin Igor's avatar
    Markin Igor committed
        localStorage.setItem("identities", JSON.stringify({}));
    
    Markin Igor's avatar
    Markin Igor committed
      if (
        localStorage.getItem("uuid") === null ||
        localStorage.getItem("token") === null ||
        localStorage.getItem("authenticatedIdentity") === null
      ) {
    
        const event = createEvent("", "NotAuthenticated");
        parent.onEvent(event);
    
    Markin Igor's avatar
    Markin Igor committed
        localStorage.removeItem("uuid");
        localStorage.removeItem("token");
    
    Markin Igor's avatar
    Markin Igor committed
        localStorage.removeItem("authenticatedIdentity");
    
    Alexey Lunin's avatar
    Alexey Lunin committed
        const authenticationPublicKey = localStorage.getItem(
          "authenticatedIdentity"
        );
    
        const pinCode = getPincode(authenticationPublicKey);
    
    Markin Igor's avatar
    Markin Igor committed
        if (pinCode === "" || pinCode === null) {
    
          loadIdentityInternal(authenticationPublicKey, "00000000").then(result => {
    
    Markin Igor's avatar
    Markin Igor committed
            if (result.code !== "200") {
              const event = createEvent(
                "CanNotGetPincodeForAuthenticatedIdentity",
                "IdentityNotLoaded",
    
                [authenticationPublicKey]
    
    Markin Igor's avatar
    Markin Igor committed
              );
              parent.onEvent(event);
    
          loadIdentityInternal(authenticationPublicKey, pinCode).then(result => {
    
    Markin Igor's avatar
    Markin Igor committed
            if (result.code !== "200") {
              const event = createEvent(
                "CanNotLoadIdentity",
                "ErrorDuringLoadingIdentity",
    
                [authenticationPublicKey]
    
    Markin Igor's avatar
    Markin Igor committed
              );
              parent.onEvent(event);
    
      let anynomousDeviceKeyEventsProcessing = false;
      let maxDeviceKeyAnonymousEventTime = 0;
    
      let eventsDeviceEventsProcessing = false;
      let maxDeviceKeyEventTime = 0;
    
      let eventsEntityEventsProcessing = false;
      let maxEntityEventTime = 0;
    
      let identityLoadedEvent = false;
      let identityAuthenticatedEvent = false;
    
    Alexey Lunin's avatar
    Alexey Lunin committed
      let previousLocalStorageUUID;
      let previousLocalStorageToken;
      let previousLocalStorageIdentity;
    
    
    Alexey Lunin's avatar
    Alexey Lunin committed
      setInterval(async function() {
    
    Markin Igor's avatar
    Markin Igor committed
        if (window.currentlyAuthenticatedIdentity) {
          const { authentication } = window.currentlyAuthenticatedIdentity;
          const pinCode = getPincode(authentication.publicKey);
          if (pinCode) {
    
    Alexey Lunin's avatar
    Alexey Lunin committed
            const identity = await getIdentityFromLocalStorage(
              authentication.publicKey,
              pinCode,
              false
            );
    
    Markin Igor's avatar
    Markin Igor committed
            window.currentlyLoadedIdentity = identity;
    
            if (!identityAuthenticatedEvent && identity) {
    
    Alexey Lunin's avatar
    Alexey Lunin committed
              const event = createEvent("IdentityAuthenticated", "Authenticated", [
                identity.authentication.publicKey
              ]);
    
    Markin Igor's avatar
    Markin Igor committed
              parent.onEvent(event);
              identityAuthenticatedEvent = true;
            }
    
    Alexey Lunin's avatar
    Alexey Lunin committed
            const authenticationPublicKey = localStorage.getItem(
              "authenticatedIdentity"
            );
    
    Markin Igor's avatar
    Markin Igor committed
            if (authenticationPublicKey) {
    
    Alexey Lunin's avatar
    Alexey Lunin committed
              const result = await loadIdentityInternal(
                authenticationPublicKey,
                "00000000"
              );
    
    Markin Igor's avatar
    Markin Igor committed
              if (result.code !== "200") {
    
    Alexey Lunin's avatar
    Alexey Lunin committed
                const event = createEvent(
                  "CanNotGetPincodeForAuthenticatedIdentity",
                  "IdentityNotLoaded",
                  [authenticationPublicKey]
                );
    
    Markin Igor's avatar
    Markin Igor committed
                parent.onEvent(event);
                clearPinCodeTtl(authenticationPublicKey);
                window.currentlyAuthenticatedIdentity = null;
              }
    
    Markin Igor's avatar
    Markin Igor committed
            identityAuthenticatedEvent = false;
    
    Markin Igor's avatar
    Markin Igor committed
            window.currentlyLoadedIdentity = null;
    
    Markin Igor's avatar
    Markin Igor committed
        if (window.currentlyLoadedIdentity) {
    
    Alexey Lunin's avatar
    Alexey Lunin committed
          const pinCode = getPincode(
            window.currentlyLoadedIdentity.authentication.publicKey
          );
    
    Markin Igor's avatar
    Markin Igor committed
          if (!pinCode) {
            if (!identityLoadedEvent) {
    
    Alexey Lunin's avatar
    Alexey Lunin committed
              const result = await loadIdentityInternal(
                window.currentlyLoadedIdentity.authentication.publicKey,
                "00000000"
              );
    
              if (window.currentlyLoadedIdentity && result.code !== "200") {
    
    Alexey Lunin's avatar
    Alexey Lunin committed
                const event = createEvent(
                  "CanNotLoadPincodeForLoadedIdentity",
                  "IdentityNotLoaded",
                  [window.currentlyLoadedIdentity.authentication.publicKey]
                );
    
    Markin Igor's avatar
    Markin Igor committed
                parent.onEvent(event);
                identityLoadedEvent = true;
              }
    
    Markin Igor's avatar
    Markin Igor committed
            identityLoadedEvent = false;
    
    Markin Igor's avatar
    Markin Igor committed
        if (window.currentlyAuthenticatedIdentity) {
          const now = new Date().getTime();
          if (now - window.lastTimeGetProfile > 30000) {
            getProfileData(window.currentlyAuthenticatedIdentity);
    
    Markin Igor's avatar
    Markin Igor committed
            window.lastTimeGetProfile = now;
    
    Alexey Lunin's avatar
    Alexey Lunin committed
    
        const currentLocalStorageUUID = localStorage.getItem("uuid");
        const currentLocalStorageToken = localStorage.getItem("token");
    
    Alexey Lunin's avatar
    Alexey Lunin committed
        const currentLocalStorageIdentity = localStorage.getItem(
          "authenticatedIdentity"
        );
    
    Alexey Lunin's avatar
    Alexey Lunin committed
        if (
    
    Alexey Lunin's avatar
    Alexey Lunin committed
          (!currentLocalStorageUUID && previousLocalStorageUUID) ||
          (!currentLocalStorageToken && previousLocalStorageToken) ||
          (!currentLocalStorageIdentity && previousLocalStorageIdentity)
    
    Alexey Lunin's avatar
    Alexey Lunin committed
        ) {
          previousLocalStorageUUID = null;
          previousLocalStorageToken = null;
          previousLocalStorageIdentity = null;
    
          destroyAuthentication();
    
          const event = createEvent("", "LogoutExternal");
          parent.onEvent(event);
        } else {
          previousLocalStorageUUID = currentLocalStorageUUID;
          previousLocalStorageToken = currentLocalStorageToken;
          previousLocalStorageIdentity = currentLocalStorageIdentity;
        }
    
    Markin Igor's avatar
    Markin Igor committed
      }, 50);
    
      const getNewEventsWithoutSession = async () => {
        anynomousDeviceKeyEventsProcessing = true;
        try {
    
    Alexey Lunin's avatar
    Alexey Lunin committed
          const executeResult = await executeRestfulFunction(
            "public",
            viamAnonymousApi,
            viamAnonymousApi.eventGetNewEventsWithoutSession,
            null,
            "devicekey"
          );
          if (executeResult.code === "200") {
    
            const eventsLen = executeResult.data.length;
            let changedMaxDeviceKeyAnonymousEventTime = false;
            for (let i = 0; i < eventsLen; i++) {
              const event = executeResult.data[i];
              switch (event.type) {
    
    Alexey Lunin's avatar
    Alexey Lunin committed
                case "DeviceConfirmed": {
    
                  await setIdentityInLocalStorage(window.currentlyLoadedIdentity);
                  parent.onEvent(event);
                  break;
    
    Alexey Lunin's avatar
    Alexey Lunin committed
                case "QRCodeUpdated": {
    
                  const actionID = event["actionID"];
                  const QrCode = event["payloads"][1];
    
                  const eventCopy = JSON.parse(JSON.stringify(event));
    
    Alexey Lunin's avatar
    Alexey Lunin committed
                  QRCode.toDataURL(actionID + "," + QrCode, function(err, url) {
    
    Markin Igor's avatar
    Markin Igor committed
                    eventCopy["payloads"].push(url);
    
    Alexey Lunin's avatar
    Alexey Lunin committed
                case "KeyDeleted": {
                  const authenticationPublicKey = localStorage.getItem(
                    "authenticatedIdentity"
                  );
    
                  clearPinCodeTtl(authenticationPublicKey);
                  localStorage.removeItem("uuid");
                  localStorage.removeItem("token");
                  localStorage.removeItem("authenticatedIdentity");
                  delete window.loadedIdentities[authenticationPublicKey];
                  window.currentlyLoadedIdentity = null;
                  window.currentlyAuthenticatedIdentity = null;
                  window.lastTimeGetProfile = 0;
    
                  destroyIdentityFromLocalStorage(authenticationPublicKey);
                  break;
                }
    
    
    Alexey Lunin's avatar
    Alexey Lunin committed
                default: {
    
              changedMaxDeviceKeyAnonymousEventTime = true;
    
    Alexey Lunin's avatar
    Alexey Lunin committed
              maxDeviceKeyAnonymousEventTime = Math.max(
                maxDeviceKeyAnonymousEventTime,
                event.stamp
              );
    
    Alexey Lunin's avatar
    Alexey Lunin committed
            if (changedMaxDeviceKeyAnonymousEventTime) {
              await executeRestfulFunction(
                "public",
                viamAnonymousApi,
                viamAnonymousApi.eventUpdateLastViewedWithoutSession,
                null,
                "devicekey",
                maxDeviceKeyAnonymousEventTime.toString()
              );
    
            }
          }
        } catch (e) {
          console.warn(e);
        }
        anynomousDeviceKeyEventsProcessing = false;
      };
    
      const getNewDeviceEvents = async () => {
        eventsDeviceEventsProcessing = true;
        try {
    
    Alexey Lunin's avatar
    Alexey Lunin committed
          const executeResult = await executeRestfulFunction(
            "private",
            viamApi,
            viamApi.eventGetNewEvents,
            null,
            "devicekey"
          );
    
          if (executeResult.code === "200") {
            const eventsLen = executeResult.data.length;
            const changedMaxDeviceKeyEventTime = false;
            for (let i = 0; i < eventsLen; i++) {
              const event = executeResult.data[i];
              if (event.type === "QRCodeUpdated") {
                const actionID = event["actionID"];
                const QrCode = event["payloads"][1];
    
                const eventCopy = JSON.parse(JSON.stringify(event));
    
    
    Alexey Lunin's avatar
    Alexey Lunin committed
                QRCode.toDataURL(actionID + "," + QrCode, function(err, url) {