Skip to content
Snippets Groups Projects
viamapi-iframe.js 47.1 KiB
Newer Older
  • Learn to ignore specific revisions
  •         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() {
          return new Penpal.Promise(result => {
    
            result({"data" : window.currentlyAuthenticatedIdentity,
    
              "code" : "200",
              "status" : "Currently authenticated identity"
            })
          });
        },
    
        stringToUtf8ByteArray(str) {
          if (typeof str !== 'string') {
            str = str.toString()
          }
    
    Markin Igor's avatar
    Markin Igor committed
          let res = Buffer.from(str,'utf-8');
    
          return new Penpal.Promise(result => {
            result(res)
          })
        },
        utf8ByteArrayToString(ba) {
          if (!Buffer.isBuffer(ba)) {
            ba = Buffer.from(ba)
          }
    
    Markin Igor's avatar
    Markin Igor committed
          let res = ba.toString('utf-8');
    
          return new Penpal.Promise(result => {
            result(res)
          })
        },
        stringToUtf8Base64(str) {
          if (!Buffer.isBuffer(str)) {
            if (typeof str !== 'string') {
              str = str.toString()
            }
            str = Buffer.from(str, 'utf-8')
          }
    
    Markin Igor's avatar
    Markin Igor committed
          let res = str.toString('base64');
    
          return new Penpal.Promise(result => {
            result(res)
          })
        },
        utf8Base64ToString(strBase64) {
          if (!Buffer.isBuffer(strBase64)) {
            if (typeof strBase64 !== 'string') {
              strBase64 = strBase64.toString()
            }
            strBase64 = Buffer.from(strBase64, 'base64')
          }
    
    Markin Igor's avatar
    Markin Igor committed
          let res = strBase64.toString('utf-8');
    
          return new Penpal.Promise(result => {
            result(res)
          })
        },
        base64ToByteArray(strBase64) {
          if (typeof strBase64 !== 'string') {
            strBase64 = strBase64.toString()
          }
    
    Markin Igor's avatar
    Markin Igor committed
          let res = Buffer.from(strBase64, 'base64');
    
          return new Penpal.Promise(result => {
            result(res)
          })
        },
        byteArrayToBase64(ba) {
          if (!Buffer.isBuffer(ba)) {
            ba = Buffer.from(ba)
          }
    
    Markin Igor's avatar
    Markin Igor committed
          let res = ba.toString('base64');
    
          return new Penpal.Promise(result => {
            result(res)
          })
        },
    
    Alexey Lunin's avatar
    Alexey Lunin committed
    
        // Collabora APIs
    
        collaboraDiscovery() {
    
          return collaboraApi.discovery().then(apps => apps);
    
    Alexey Lunin's avatar
    Alexey Lunin committed
        getPassports: async fileId => {
          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.getPassports(fileId);
          return response.data;
    
    Alexey Lunin's avatar
    Alexey Lunin committed
        wopiPutFile: async (fileId, accessToken, file) => {
          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(fileId, accessToken, file);
          return response.data;
    
    Alexey Lunin's avatar
    Alexey Lunin committed
        },
    
        ...penpalMethods
    
    Markin Igor's avatar
    Markin Igor committed
    });
    
    connection.promise.then(parent => {
    
      if (!navigator.cookieEnabled) {
        console.warn("Cookie disabled. Can't start library.");
        return;
      }
    
    
      window.addEventListener('storage', event => {
        if (event.key === "authenticatedIdentity" && event.newValue === null) {
    
    Markin Igor's avatar
    Markin Igor 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
      ) {
    
    Markin Igor's avatar
    Markin Igor committed
        localStorage.removeItem("uuid");
        localStorage.removeItem("token");
    
    Markin Igor's avatar
    Markin Igor committed
        localStorage.removeItem("authenticatedIdentity");
    
        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);
    
    Markin Igor's avatar
    Markin Igor committed
      var anynomousDeviceKeyEventsProcessing = false;
      var maxDeviceKeyAnonymousEventTime = 0;
    
    Markin Igor's avatar
    Markin Igor committed
      var eventsDeviceEventsProcessing = false;
      var maxDeviceKeyEventTime = 0;
    
    Markin Igor's avatar
    Markin Igor committed
      var eventsEntityEventsProcessing = false;
      var maxEntityEventTime = 0;
    
    Markin Igor's avatar
    Markin Igor committed
      var identityLoadedEvent = false;
      var identityAuthenticatedEvent = false;
    
    Markin Igor's avatar
    Markin Igor committed
      setInterval(async function () {
        if (window.currentlyAuthenticatedIdentity) {
          const { authentication } = window.currentlyAuthenticatedIdentity;
          const pinCode = getPincode(authentication.publicKey);
          if (pinCode) {
            const identity = await getIdentityFromLocalStorage(authentication.publicKey, pinCode, false);
    
    Markin Igor's avatar
    Markin Igor committed
            window.currentlyLoadedIdentity = identity;
    
            if (!identityAuthenticatedEvent && identity) {
              const event = createEvent("IdentityAuthenticated", "Authenticated", [identity.authentication.publicKey]);
              parent.onEvent(event);
              identityAuthenticatedEvent = true;
            }
    
            const authenticationPublicKey = localStorage.getItem("authenticatedIdentity");
    
    Markin Igor's avatar
    Markin Igor committed
            if (authenticationPublicKey) {
              const result = await loadIdentityInternal(authenticationPublicKey, "00000000");
              if (result.code !== "200") {
                const event = createEvent("CanNotGetPincodeForAuthenticatedIdentity", "IdentityNotLoaded", [authenticationPublicKey]);
                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) {
          const pinCode = getPincode(window.currentlyLoadedIdentity.authentication.publicKey);
          if (!pinCode) {
            if (!identityLoadedEvent) {
              const result = await loadIdentityInternal(window.currentlyLoadedIdentity.authentication.publicKey, "00000000");
              if (result.code !== "200") {
                const event = createEvent("CanNotLoadPincodeForLoadedIdentity", "IdentityNotLoaded", [window.currentlyLoadedIdentity.authentication.publicKey]);
                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;
    
    Markin Igor's avatar
    Markin Igor committed
      }, 50);
    
    
      setInterval(function() {
    
        if (window.currentlyLoadedIdentity && !anynomousDeviceKeyEventsProcessing && !window.currentlyAuthenticatedIdentity) {
    
    Markin Igor's avatar
    Markin Igor committed
          anynomousDeviceKeyEventsProcessing = true;
    
          executeRestfulFunction("public", viamAnonymousApi, viamAnonymousApi.eventGetNewEventsWithoutSession, null, "devicekey").then(async executeResult => {
    
    Markin Igor's avatar
    Markin Igor committed
            if(executeResult.code === "200") {
    
    Markin Igor's avatar
    Markin Igor committed
              var eventsLen = executeResult.data.length;
    
              let changedMaxDeviceKeyAnonymousEventTime = false;
    
              for (var i = 0; i < eventsLen; i++) {
    
    Markin Igor's avatar
    Markin Igor committed
                var event = executeResult.data[i];
    
                switch (event.type) {
    
                  case "Authenticated" : {
    
                    const uuid = event.payloads[0];
                    const token = event.payloads[1];
    
    Markin Igor's avatar
    Markin Igor committed
                    handleIdentityLogin(window.currentlyLoadedIdentity, uuid, token);
    
                    const identityToStore = window.currentlyAuthenticatedIdentity;
    
                    event.payloads = [{fromQRCode: true}];
    
                    setIdentityInLocalStorage(identityToStore).then(() => {
    
    Markin Igor's avatar
    Markin Igor committed
                      getProfileData(identityToStore).then(() => {
                        parent.onEvent(event);
    
                      });
                    });
                    break;
                  }
    
                  case "QRCodeUpdated" : {
    
    Markin Igor's avatar
    Markin Igor committed
                    var actionID = event["actionID"];
                    var QrCode = event["payloads"][1];
    
    Markin Igor's avatar
    Markin Igor committed
                    var eventCopy = JSON.parse(JSON.stringify(event));
    
    
                    QRCode.toDataURL(actionID + "," + QrCode, function (err, url) {
    
    Markin Igor's avatar
    Markin Igor committed
                      eventCopy["payloads"].push(url);
    
                      parent.onEvent(eventCopy)
    
    Markin Igor's avatar
    Markin Igor committed
                    });
    
                    break
                  }
    
                  case "KeyDeleted" : {
    
                    const authenticationPublicKey = localStorage.getItem("authenticatedIdentity");
    
    Markin Igor's avatar
    Markin Igor committed
                    clearPinCodeTtl(authenticationPublicKey);
                    localStorage.removeItem("uuid");
                    localStorage.removeItem("token");
                    localStorage.removeItem("authenticatedIdentity");
    
                    delete window.loadedIdentities[authenticationPublicKey];
                    window.currentlyLoadedIdentity = null;
                    window.currentlyAuthenticatedIdentity = null;
                    window.lastTimeGetProfile = 0;
    
    Markin Igor's avatar
    Markin Igor committed
                    destroyIdentityFromLocalStorage(authenticationPublicKey);
    
                    break
                  }
    
                  default : {
                    parent.onEvent(event)
                  }
                }
    
    Markin Igor's avatar
    Markin Igor committed
                changedMaxDeviceKeyAnonymousEventTime = true;
    
                maxDeviceKeyAnonymousEventTime = Math.max(maxDeviceKeyAnonymousEventTime, event.stamp)
              }
    
              if(changedMaxDeviceKeyAnonymousEventTime) {
                executeRestfulFunction("public", viamAnonymousApi, viamAnonymousApi.eventUpdateLastViewedWithoutSession,
    
                    null, "devicekey", maxDeviceKeyAnonymousEventTime.toString()).then(() => {
    
    Markin Igor's avatar
    Markin Igor committed
                  anynomousDeviceKeyEventsProcessing = false;
                });
    
    Markin Igor's avatar
    Markin Igor committed
                anynomousDeviceKeyEventsProcessing = false;
    
    Markin Igor's avatar
    Markin Igor committed
              anynomousDeviceKeyEventsProcessing = false;
    
        if (window.currentlyAuthenticatedIdentity != null && eventsDeviceEventsProcessing === false) {
    
    Markin Igor's avatar
    Markin Igor committed
          eventsDeviceEventsProcessing = true;
    
          executeRestfulFunction("private", viamApi, viamApi.eventGetNewEvents, null, "devicekey").then(executeResult => {
    
    Markin Igor's avatar
    Markin Igor committed
            if(executeResult.code === "200") {
    
    Markin Igor's avatar
    Markin Igor committed
              var eventsLen = executeResult.data.length;
    
              const changedMaxDeviceKeyEventTime = false;
    
              for(var i = 0; i < eventsLen; i++) {
    
    Markin Igor's avatar
    Markin Igor committed
                var event = executeResult.data[i];
    
    Markin Igor's avatar
    Markin Igor committed
                if(event.type === "QRCodeUpdated") {
    
    Markin Igor's avatar
    Markin Igor committed
                  var actionID = event["actionID"];
                  var QrCode = event["payloads"][1];
    
    Markin Igor's avatar
    Markin Igor committed
                  var eventCopy = JSON.parse(JSON.stringify(event));
    
    
                  QRCode.toDataURL(actionID + "," + QrCode, function (err, url) {
    
    Markin Igor's avatar
    Markin Igor committed
                    eventCopy["payloads"].push(url);
    
                    parent.onEvent(eventCopy)
                  })
                } else {
                  parent.onEvent(event)
                }
                maxDeviceKeyEventTime = Math.max(maxDeviceKeyEventTime, event.stamp)
              }
              if(changedMaxDeviceKeyEventTime) {
    
                executeRestfulFunction("private", viamApi, viamApi.eventUpdateLastViewed, null, "devicekey",
    
                  maxDeviceKeyEventTime.toString()).then(executeResult1 => {
                  eventsDeviceEventsProcessing = false
                })
              } else {
                eventsDeviceEventsProcessing = false
              }
            } else {
              eventsDeviceEventsProcessing = false
            }
          });
        }
    
    
        if (window.currentlyAuthenticatedIdentity != null && eventsEntityEventsProcessing === false) {
    
    Markin Igor's avatar
    Markin Igor committed
          eventsEntityEventsProcessing = true;
    
          executeRestfulFunction("private", viamApi, viamApi.eventGetNewEvents, null, "entity").then(executeResult => {
    
    Markin Igor's avatar
    Markin Igor committed
            if(executeResult.code === "200") {
    
    Markin Igor's avatar
    Markin Igor committed
              var eventsLen = executeResult.data.length;
    
              let changedMaxEntityEventTime = false;
    
              for(var i = 0; i < eventsLen; i++) {
    
    Markin Igor's avatar
    Markin Igor committed
                event = executeResult.data[i];
    
    Markin Igor's avatar
    Markin Igor committed
                if(event.type === "QRCodeUpdated") {
    
    Markin Igor's avatar
    Markin Igor committed
                  var actionID = event["actionID"];
                  var QrCode = event["payloads"][1];
    
    Markin Igor's avatar
    Markin Igor committed
                  var eventCopy = JSON.parse(JSON.stringify(event));
    
    
                  QRCode.toDataURL(actionID + "," + QrCode, function (err, url) {
    
    Markin Igor's avatar
    Markin Igor committed
                    eventCopy["payloads"].push(url);
    
                    parent.onEvent(eventCopy)
    
    Markin Igor's avatar
    Markin Igor committed
                  });
    
    Markin Igor's avatar
    Markin Igor committed
                parent.onEvent(event);
                changedMaxEntityEventTime = true;
    
                maxEntityEventTime = Math.max(maxEntityEventTime, event.stamp)
              }
              if(changedMaxEntityEventTime) {
    
                executeRestfulFunction("private", viamApi, viamApi.eventUpdateLastViewed, null, "entity",
    
                  maxEntityEventTime.toString()).then(executeResult1 => {
                  eventsEntityEventsProcessing = false
                })
              } else {
                eventsEntityEventsProcessing = false
              }
            } else {
              eventsEntityEventsProcessing = false
            }
          });
        }
      }, 1000);
    });