< Summary

Class:DCL.Helpers.WearablesFetchingHelper
Assembly:WearablesFetchingHelper
File(s):/tmp/workspace/unity-renderer/unity-renderer/Assets/Scripts/MainScripts/DCL/Helpers/WearablesHelper/WearablesFetchingHelper.cs
Covered lines:0
Uncovered lines:58
Coverable lines:58
Total lines:178
Line coverage:0% (0 of 58)
Covered branches:0
Total branches:0
Covered methods:0
Total methods:9
Method coverage:0% (0 of 9)

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity NPath complexity Sequence coverage
EnsureCollectionsData()0%72800%
GetNFTItems()0%30500%
GetItemsFetchURL(...)0%6200%
GetCollectionsFetchURL()0%2100%
GetWearablesFetchURL()0%2100%
GetBaseCollections()0%12300%
GetRandomCollections()0%30500%
GetWearableItems()0%42600%
GetThirdPartyCollections()0%2100%

File(s)

/tmp/workspace/unity-renderer/unity-renderer/Assets/Scripts/MainScripts/DCL/Helpers/WearablesHelper/WearablesFetchingHelper.cs

#LineLine coverage
 1using Cysharp.Threading.Tasks;
 2using DCLServices.EnvironmentProvider;
 3using System.Collections;
 4using System.Collections.Generic;
 5using Newtonsoft.Json;
 6using System;
 7using System.Text;
 8using UnityEngine;
 9using UnityEngine.Networking;
 10using Random = UnityEngine.Random;
 11using Collection = WearableCollectionsAPIData.Collection;
 12
 13namespace DCL.Helpers
 14{
 15    public static class WearablesFetchingHelper
 16    {
 17        // TODO: change fetching logic to allow for auto-pagination
 18        // The https://nft-api.decentraland.org/v1/ endpoint doesn't fetch L1 wearables right now, if those need to be r
 19        public const string BASE_FETCH_URL = "https://peer.decentraland.org/lambdas/collections";
 20        public const string COLLECTIONS_FETCH_PARAMS = "?sortBy=newest&first=1000";
 21        public const string WEARABLES_FETCH_PARAMS = "/wearables?";
 22        public const string BASE_WEARABLES_COLLECTION_ID = "urn:decentraland:off-chain:base-avatars";
 23        public const string THIRD_PARTY_COLLECTIONS_FETCH_URL = "third-party-integrations";
 24        public const string NFT_API_FETCH_URL = "https://nft-api.decentraland.org/v1/";
 25        public const string NFT_API_FETCH_PARAMS_ITEMS = "items?";
 26        private static Collection[] collections;
 27
 28        private static IEnumerator EnsureCollectionsData()
 29        {
 030            if (collections?.Length > 0)
 031                yield break;
 32
 033            yield return Environment.i.platform.webRequest.Get(
 34                url: GetCollectionsFetchURL(),
 35                downloadHandler: new DownloadHandlerBuffer(),
 36                timeout: 60,
 37                disposeOnCompleted: false,
 38                OnFail: (webRequest) =>
 39                {
 040                    Debug.LogWarning($"Request error! collections couldn't be fetched! -- {webRequest.webRequest.error}"
 041                },
 42                OnSuccess: (webRequest) =>
 43                {
 044                    var collectionsApiData = JsonUtility.FromJson<WearableCollectionsAPIData>(webRequest.webRequest.down
 045                    collections = collectionsApiData.data;
 046                });
 047        }
 48
 49        public static async UniTask<string> GetNFTItems(List<string> wearableUrns, IEnvironmentProviderService environme
 50        {
 051            StringBuilder sb = new (GetItemsFetchURL(environmentProviderService));
 52
 053            int urnCount = wearableUrns.Count;
 54
 055            for (int i = 0; i < urnCount; i++)
 56            {
 057                sb.Append("urn=");
 058                sb.Append(wearableUrns[i]);
 59
 060                if (i < urnCount - 1)
 061                    sb.Append("&");
 62            }
 63
 064            var resultAsync = await Environment.i.platform.webRequest.GetAsync(
 65                sb.ToString(),
 66                isSigned: true);
 67
 068            return resultAsync.downloadHandler.text;;
 069        }
 70
 71        public static string GetItemsFetchURL(IEnvironmentProviderService environmentProviderService)
 72        {
 073            string baseUrl = NFT_API_FETCH_URL;
 074            bool useZone = environmentProviderService.IsProd() == false;
 75
 076            if (useZone)
 077                baseUrl = baseUrl.Replace("org", "zone");
 78
 079            return $"{baseUrl}{NFT_API_FETCH_PARAMS_ITEMS}";
 80        }
 81
 082        public static string GetCollectionsFetchURL() => $"{BASE_FETCH_URL}{COLLECTIONS_FETCH_PARAMS}";
 83
 084        public static string GetWearablesFetchURL() => $"{BASE_FETCH_URL}{WEARABLES_FETCH_PARAMS}";
 85
 86        /// <summary>
 87        /// Fetches base collection ids and adds them to the provided ids list
 88        /// </summary>
 89        /// <param name="finalCollectionIdsList">A strings list that will be filled with the base collection ids</param>
 90        public static IEnumerator GetBaseCollections(List<string> finalCollectionIdsList)
 91        {
 092            yield return EnsureCollectionsData();
 93
 094            finalCollectionIdsList.Add( BASE_WEARABLES_COLLECTION_ID );
 095        }
 96
 97        public static IEnumerator GetRandomCollections(int amount, List<string> finalCollectionIdsList)
 98        {
 099            yield return EnsureCollectionsData();
 100
 0101            List<int> randomizedIndices = new List<int>();
 102            int randomIndex;
 103
 0104            for (int i = 0; i < amount; i++)
 105            {
 0106                randomIndex = Random.Range(0, collections.Length);
 107
 0108                while (randomizedIndices.Contains(randomIndex))
 109                {
 0110                    randomIndex = Random.Range(0, collections.Length);
 111                }
 112
 0113                finalCollectionIdsList.Add(collections[randomIndex].urn);
 0114                randomizedIndices.Add(randomIndex);
 115            }
 0116        }
 117
 118        /// <summary>
 119        /// Given a base url for fetching wearables, this method recursively downloads all the 'pages' responded by the 
 120        /// and populates the global Catalogue with those wearables.
 121        /// </summary>
 122        /// <param name="url">The API url to fetch the list of wearables</param>
 123        /// <param name="finalWearableItemsList">A WearableItems list that will be filled with the fetched wearables</pa
 124        public static IEnumerator GetWearableItems(string url, List<WearableItem> finalWearableItemsList)
 125        {
 0126            string nextPageParams = null;
 127
 0128            yield return Environment.i.platform.webRequest.Get(
 129                url: url,
 130                downloadHandler: new DownloadHandlerBuffer(),
 131                timeout: 60,
 132                disposeOnCompleted: false,
 133                OnFail: (webRequest) =>
 134                {
 0135                    Debug.LogWarning($"Request error! wearables couldn't be fetched! -- {webRequest.webRequest.error}");
 0136                },
 137                OnSuccess: (webRequest) =>
 138                {
 0139                    var wearablesApiData = JsonConvert.DeserializeObject<WearablesAPIData>(webRequest.webRequest.downloa
 0140                    var wearableItemsList = wearablesApiData.GetWearableItems();
 0141                    finalWearableItemsList.AddRange(wearableItemsList);
 142
 0143                    nextPageParams = wearablesApiData.pagination.next;
 0144                });
 145
 0146            if (!string.IsNullOrEmpty(nextPageParams))
 147            {
 148                // Since the wearables deployments response returns only a batch of elements, we need to fetch all the
 149                // batches sequentially
 0150                yield return GetWearableItems(
 151                    $"{GetWearablesFetchURL()}{nextPageParams}",
 152                    finalWearableItemsList);
 153            }
 0154        }
 155
 156        [Obsolete("Deprecated. Use IWearablesCatalogService.GetAllThirdPartyCollectionsAsync instead")]
 157        public static Promise<Collection[]> GetThirdPartyCollections()
 158        {
 0159            Promise<Collection[]> promiseResult = new Promise<Collection[]>();
 160
 0161            Environment.i.platform.webRequest.Get(
 162                url: $"{Environment.i.platform.serviceProviders.catalyst.lambdasUrl}/{THIRD_PARTY_COLLECTIONS_FETCH_URL}
 163                downloadHandler: new DownloadHandlerBuffer(),
 164                timeout: 60,
 165                OnFail: (webRequest) =>
 166                {
 0167                    promiseResult.Reject($"Request error! third party collections couldn't be fetched! -- {webRequest.we
 0168                },
 169                OnSuccess: (webRequest) =>
 170                {
 0171                    var collectionsApiData = JsonUtility.FromJson<WearableCollectionsAPIData>(webRequest.webRequest.down
 0172                    promiseResult.Resolve(collectionsApiData.data);
 0173                });
 174
 0175            return promiseResult;
 176        }
 177    }
 178}