Untitled

mail@pastecode.io avatarunknown
plain_text
2 months ago
13 kB
2
Indexable
Never
window.springBoard = window.springBoard || {};
 
window.springBoard.createCookie = function(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    } else var expires = "";
    var cDomain = typeof window.springBoard.cookieDomain !== 'undefined' ? window.springBoard.cookieDomain : (document.location.host.indexOf("www.") == 0) ? document.location.host.substr(3, document.location.host.length) : document.location.host;
    document.cookie = escape(name) + "=" + escape(value) + expires + ";domain=" + cDomain + ";path=/" + (document.location.protocol == "https:" ? "; secure" : "");

    return null;
}

window.springBoard.readCookie = function(name) {
    var nameEQ = escape(name) + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return unescape(c.substring(nameEQ.length, c.length));
    }
    return null;
}

window.springBoard.eraseCookie = function(name) {
    window.springBoard.createCookie(name, "", -1);

    return null;
}

window['cv-utils'] = {
    // Variables
    csrf: window.springBoard.readCookie('_csrf'),
    debug: window.springBoard.readCookie('cfQA'),

    readCookie: function(name) {
        var nameEQ = escape(name) + "=";
        var ca = document.cookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') c = c.substring(1, c.length);
            if (c.indexOf(nameEQ) == 0) return unescape(c.substring(nameEQ.length, c.length));
        }
        return null;
    },
    // API Queries 
    generateProductQuery: function (id){
        return JSON.stringify([{"query":"query AddToCartButton($id: ID!) {product(id: $id) {...product packageInListHotness orderRequestCheck {available orderApprovalRequestIds __typename} __typename}} fragment product on Product {id productId itemId slug name description rating {average count __typename} currentVersion {id name publishedDate __typename} lighteningRating {discount quantity used endTime promotionStartTime promotionId pageView __typename} reviewCount downloadSize  assetCount publisher {id name url supportUrl supportEmail gaAccount gaPrefix __typename} mainImage {big facebook small icon icon75 __typename} originalPrice {itemId originalPrice finalPrice isFree discount {save percentage type saleType __typename} currency entitlementType __typename} images {type imageUrl thumbnailUrl __typename} state category {id name slug  longName __typename} __typename}","variables":{"id":`${id}`},"operationName":"AddToCartButton"}])
    },

    generateProductQueryNew: function(id){
        return JSON.stringify([{"query":"query Product($id: ID!) { product(id: $id) { ...product packageInListHotness reviews(rows: 2, sortBy: \"rating\") { ...reviews __typename } __typename } }fragment product on Product { id productId itemId slug name description elevatorPitch keyFeatures compatibilityInfo customLicense rating { average count __typename } currentVersion { id name publishedDate __typename } reviewCount downloadSize assetCount publisher { id name url supportUrl supportEmail gaAccount gaPrefix __typename } mainImage { big facebook small icon icon75 __typename } originalPrice { itemId originalPrice finalPrice isFree discount { save percentage type saleType __typename } currency entitlementType __typename } images { type imageUrl thumbnailUrl __typename } category { id name slug longName __typename } firstPublishedDate publishNotes supportedUnityVersions state overlay overlayText plusProSale licenseText vspProperties { ... on ExternalVSPProduct { externalLink __typename } __typename } __typename }fragment reviews on Reviews { count canRate: can_rate canReply: can_reply canComment: can_comment hasCommented: has_commented totalEntries: total_entries lastPage: last_page comments { id date editable rating user { id name profileUrl avatar __typename } isHelpful: is_helpful { count score __typename } subject version full is_complimentary vote replies { id editable date version full user { id name profileUrl avatar __typename } isHelpful: is_helpful { count score __typename } __typename } __typename } __typename } ","variables":{"id":`${id}`},"operationName":"Product"}])
    },

    generateCartQuery: function(){
        return JSON.stringify([{"query":"query CartQuery { shoppingCart: currentCart(namespace: \"asset_store_shopping_cart\") { ...cart __typename } savedForLaterCart: currentCart(namespace: \"asset_store_saved_cart\") { id cartId namespace items { id __typename } __typename }}fragment cart on Cart { id cartId namespace items { id quantity priceName product { ...product __typename } entitlement { id type __typename } orderRequest __typename } __typename}fragment product on Product { id productId itemId slug name description elevatorPitch keyFeatures compatibilityInfo customLicense rating { average count __typename } currentVersion { id name publishedDate __typename } reviewCount downloadSize assetCount publisher { id name url supportUrl supportEmail gaAccount gaPrefix __typename } mainImage { big facebook small icon icon75 __typename } originalPrice { itemId originalPrice finalPrice isFree discount { save percentage type saleType __typename } currency entitlementType __typename } images { type imageUrl thumbnailUrl __typename } category { id name slug longName __typename } firstPublishedDate publishNotes supportedUnityVersions state overlay overlayText plusProSale licenseText vspProperties { ... on ExternalVSPProduct { externalLink __typename } __typename } __typename}","operationName":"CartQuery"}])
    },
    generateAddCartQuery: function(id){
        return "{\"query\":\"mutation AddItem($packageId: ID!, $priceSetName: String, $quantity: Int) {  addPackageToCart(packageId: $packageId, priceSetName: $priceSetName, quantity: $quantity) {    id    cartId    items {      id      quantity      priceName      __typename    }    __typename  }}\",\"variables\":{\"packageId\":\"" + id + "\",\"priceSetName\":\"\",\"quantity\":1},\"operationName\":\"AddItem\"}"
    },

    generateUserQuery: function (id){
        return JSON.stringify([{"query":"query CurrentUser($id: ID!) { user(id: $id) { id name email myAssets keyImage { icon24 large __typename } feed { id unread __typename } v2Preferred admin downloader publisherId hasAcceptedLatestTerms wishes lists { total results { ...list packageIds __typename } __typename } __typename } listDetail(listId: \"favorite\") { packages(size: 1) { results { ...product __typename } __typename } __typename } } fragment list on List { id type listId slug name description ownerId ownerType status headerImage icon mainImages __typename } fragment product on Product { id productId itemId slug name description elevatorPitch keyFeatures compatibilityInfo customLicense rating { average count __typename } currentVersion { id name publishedDate __typename } reviewCount downloadSize assetCount publisher { id name url supportUrl supportEmail gaAccount gaPrefix __typename } mainImage { big facebook small icon icon75 __typename } originalPrice { itemId originalPrice finalPrice isFree discount { save percentage type saleType __typename } currency entitlementType __typename } images { type imageUrl thumbnailUrl __typename } category { id name slug longName __typename } firstPublishedDate publishNotes supportedUnityVersions state overlay overlayText plusProSale licenseText vspProperties { ... on ExternalVSPProduct { externalLink __typename } __typename } __typename } ","variables":{"id":""+id+""},"operationName":"CurrentUser"},{"query":"query ShoppingCartQuery { currentCart(namespace: \"asset_store_saved_cart\") { id cartId items { id product { id mainImage { icon __typename } __typename } __typename } __typename } } ","operationName":"ShoppingCartQuery"}])
    },

    // Functions
    fetchData: async function (query, batch){
        try{
            const fetchUrl = `https://assetstore.unity.com/api/graphql${batch}`;
            const res = await fetch(fetchUrl, {
                "credentials": "include",
                "headers": {
                    "accept": "application/json, text/plain, */*",
                    "accept-language": "en-US,en;q=0.9",
                    "cache-control": "no-cache",
                    "content-type": "application/json;charset=UTF-8",
                    "pragma": "no-cache",
                    "sec-fetch-mode": "cors",
                    "sec-fetch-site": "same-origin",
                    "x-csrf-token": this.readCookie('_csrf'),
                    "x-requested-with": "XMLHttpRequest"
                },
                "referrer": "https://assetstore.unity.com/",
                "referrerPolicy": "origin",
                "body": query,
                "method": "POST",
                "mode": "cors"
            });
            
            const data = await res.json();
            return data;
        } catch (err){
                console.error(err);
        }
    },

    getProductData: async function (id){
        const query = this.generateProductQuery(id),
            productData = await this.fetchData(query, '/batch');

        return productData;
    },

    addProductToCart: async function(id, openMiniCart){
        if(
            window['cv-utils'].debug && 
            !openMiniCart
        ) console.log('Add Cart function: Set second argument as true to open mini cart'); 
        

        const mainScroller = document.querySelector('#main-layout-scroller');
        const query = this.generateAddCartQuery(id);
        await this.fetchData(query, '');

        if(openMiniCart && mainScroller){
            mainScroller.scrollTo(0,0);

            let waitForMiniCart = setInterval(() => {
                const miniCart = document.querySelector('.cartMini.right-nav-element');

                if(miniCart){
                    clearInterval(waitForMiniCart);

                    miniCart.click()
                }
            }, 50);
        }
    },

    getUserId: function(){
        let maxCalls = 100;

        let waitForData = setInterval(() => {
            if(window.dataLayer[0].GenesisID)    {
                clearInterval(waitForData);

                window['cv-utils'].userId = window.dataLayer[0].GenesisID
            }

            if(--maxCalls < 0){
                clearInterval(waitForData);
            }
        }, 50);
    }
}

window.addEventListener('mousedown', (e)=>{
    const el = e.target;

    if(
        el.closest('[data-test=asset-grid]') &&
        el.closest('a[href*="packages"]')
    ){
        Kameleoon.API.Goals.processConversion(308995)
    }
})

const testID = '201432';

var checkExp = setInterval(function () {
    if (Kameleoon.API.Experiments.getById(testID) !== null) {
        clearInterval(checkExp);

        const testVariant = Kameleoon.API.Experiments.getById(testID).associatedVariation.name,
            testName = Kameleoon.API.Experiments.getById(testID).name;

        if (testVariant === 'Reference') {
            sendGaEvent('Experiment', testName, `${testName} - Control`);
            sendDataLayerEvent(testName, testVariant);
        } else {
            sendGaEvent('Experiment', testName, `${testName} - ${testVariant}`);
            sendDataLayerEvent(testName, testVariant);
        }
    } 
}, 50);

function sendDataLayerEvent(experiment, variation){
    var stop,
        timeout,
        check = function () {
            try {
                var dataLayerLoaded = typeof window.dataLayer !== "undefined";

                if (stop) return;

                if (dataLayerLoaded) {
                    window.dataLayer.push(
                        {
                          event: 'kameleoon',
                          experiment: experiment,
                          variation: variation
                        }
                    )

                    clearTimeout(timeout);

                    return;
                }

                window.requestAnimationFrame(check);
            } catch (err) {
                console.log(err.message);
            }
        };

    timeout = setTimeout(function () {
        stop = true;
    }, 5000);

    window.requestAnimationFrame(check);
}

function sendGaEvent(cat, label, action) {
    var stop,
        timeout,
        check = function () {
            try {
                var gaLoaded = typeof window.ga !== "undefined" && typeof window.ga.getAll !== "undefined";

                if (stop) return;

                if (gaLoaded) {
                    var gtmName = window.ga.getAll()[0] ? window.ga.getAll()[0].get("name") + "." : "";

                    window.ga(gtmName + "send", {
                        hitType: "event",
                        eventCategory: cat,
                        eventLabel: label,
                        eventAction: action,
                    });

                    clearTimeout(timeout);

                    return;
                }

                window.requestAnimationFrame(check);
            } catch (err) {
                console.log(err.message);
            }
        };

    timeout = setTimeout(function () {
        stop = true;
    }, 5000);

    window.requestAnimationFrame(check);
}