예제 #1
0
        /// <summary>
        /// 执行请求
        /// 使用或不使用缓存
        /// </summary>
        /// <returns></returns>
        private async Task ExecRequestAsync()
        {
            var apiCache    = new ApiCache(this);
            var cacheResult = await apiCache.GetAsync().ConfigureAwait(false);

            if (cacheResult.ResponseMessage != null)
            {
                this.ResponseMessage = cacheResult.ResponseMessage;
                this.Result          = await this.ApiActionDescriptor.Return.Attribute.GetTaskResult(this).ConfigureAwait(false);
            }
            else
            {
                await this.ExecHttpRequestAsync().ConfigureAwait(false);

                await apiCache.SetAsync(cacheResult.CacheKey).ConfigureAwait(false);
            }
        }
예제 #2
0
        public override async Task <IEnumerable <ChanBoard> > GetBoardsAsync(BoardSorting?Sorting = null)
        {
            var data = await ApiCache.GetApi <InfiniteChanBoard[]>(JsonBoards);

            IEnumerable <InfiniteChanBoard> boards = data;

            switch (Sorting ?? DefaultBoardSorting)
            {
            case BoardSorting.Alphabetical:
                boards = boards.OrderBy(b => b.Uri);
                break;

            case BoardSorting.MostPopular:
                boards = boards.OrderByDescending(b => b.PostsPerDay);
                break;
            }

            return(from b in boards
                   select b.GetViewModel());
        }
    IEnumerator FetchUploadedData()
    {
        if (!RemoteConfig.IsInitialized())
        {
            RemoteConfig.Init();
        }

        if (!APIUser.IsLoggedInWithCredentials)
        {
            yield break;
        }

        ApiCache.ClearResponseCache();
        VRCCachedWWW.ClearOld();

        if (fetchingAvatars == null)
        {
            fetchingAvatars = EditorCoroutine.Start(() => FetchAvatars());
        }
        if (fetchingWorlds == null)
        {
            fetchingWorlds = EditorCoroutine.Start(() => FetchWorlds());
        }
    }
예제 #4
0
    void OnGUIScene(VRCSDK2.VRC_SceneDescriptor scene)
    {
        string lastUrl          = VRC_SdkBuilder.GetLastUrl();
        bool   lastBuildPresent = lastUrl != null;

        string worldVersion = "-1";

        PipelineManager[] pms = (PipelineManager[])VRC.Tools.FindSceneObjectsOfTypeAll <PipelineManager>();
        if (pms.Length == 1 && !string.IsNullOrEmpty(pms[0].blueprintId))
        {
            if (scene.apiWorld == null)
            {
                ApiWorld world = API.FromCacheOrNew <ApiWorld>(pms[0].blueprintId);
                world.Fetch(null, false,
                            (c) => scene.apiWorld = c.Model as ApiWorld,
                            (c) =>
                {
                    if (c.Code == 404)
                    {
                        Debug.LogErrorFormat("Could not load world {0} because it didn't exist.", pms[0].blueprintId);
                        ApiCache.Invalidate <ApiWorld>(pms[0].blueprintId);
                    }
                    else
                    {
                        Debug.LogErrorFormat("Could not load world {0} because {1}", pms[0].blueprintId, c.Error);
                    }
                });
                scene.apiWorld = world;
            }
            worldVersion = (scene.apiWorld as ApiWorld).version.ToString();
        }
        EditorGUILayout.LabelField("World Version: " + worldVersion);

        EditorGUILayout.Space();

        if (!UpdateLayers.AreLayersSetup() && GUILayout.Button("Setup Layers for VRChat"))
        {
            bool doIt = EditorUtility.DisplayDialog("Setup Layers for VRChat", "This adds all VRChat layers to your project and pushes any custom layers down the layer list. If you have custom layers assigned to gameObjects, you'll need to reassign them. Are you sure you want to continue?", "Do it!", "Don't do it");
            if (doIt)
            {
                UpdateLayers.SetupEditorLayers();
            }
        }

        if (UpdateLayers.AreLayersSetup() && !UpdateLayers.IsCollisionLayerMatrixSetup() && GUILayout.Button("Setup Collision Layer Matrix for VRChat"))
        {
            bool doIt = EditorUtility.DisplayDialog("Setup Collision Layer Matrix for VRChat", "This will setup the correct physics collisions in the PhysicsManager for VRChat layers. Are you sure you want to continue?", "Do it!", "Don't do it");
            if (doIt)
            {
                UpdateLayers.SetupCollisionLayerMatrix();
            }
        }

        scene.autoSpatializeAudioSources = EditorGUILayout.ToggleLeft("Apply 3D spatialization to AudioSources automatically at runtime (override settings by adding an ONSPAudioSource component to game object)", scene.autoSpatializeAudioSources);
        if (GUILayout.Button("Enable 3D spatialization on all 3D AudioSources in scene now"))
        {
            bool doIt = EditorUtility.DisplayDialog("Enable Spatialization", "This will add an ONSPAudioSource script to every 3D AudioSource in the current scene, and enable default settings for spatialization.  Are you sure you want to continue?", "Do it!", "Don't do it");
            if (doIt)
            {
                if (_EnableSpatialization != null)
                {
                    _EnableSpatialization();
                }
                else
                {
                    Debug.LogError("VrcSdkControlPanel: EnableSpatialization callback not found!");
                }
            }
        }

        GUI.enabled = (GUIErrors.Count == 0 && checkedForIssues);
        EditorGUILayout.Space();
        EditorGUILayout.BeginVertical();
        EditorGUILayout.LabelField("Test", EditorStyles.boldLabel);
        numClients = EditorGUILayout.IntField("Number of Clients", numClients);
        if (lastBuildPresent == false)
        {
            GUI.enabled = false;
        }
        if (GUILayout.Button("Last Build"))
        {
            VRC_SdkBuilder.shouldBuildUnityPackage = false;
            VRC_SdkBuilder.numClientsToLaunch      = numClients;
            VRC_SdkBuilder.RunLastExportedSceneResource();
        }
        if (APIUser.CurrentUser.hasSuperPowers)
        {
            if (GUILayout.Button("Copy Test URL"))
            {
                TextEditor te = new TextEditor();
                te.text = lastUrl;
                te.SelectAll();
                te.Copy();
            }
        }
        if (lastBuildPresent == false)
        {
            GUI.enabled = true;
        }
        if (GUILayout.Button("New Build"))
        {
            EnvConfig.ConfigurePlayerSettings();
            VRC_SdkBuilder.shouldBuildUnityPackage = false;
            VRC.AssetExporter.CleanupUnityPackageExport();  // force unity package rebuild on next publish
            VRC_SdkBuilder.numClientsToLaunch = numClients;
            VRC_SdkBuilder.PreBuildBehaviourPackaging();
            VRC_SdkBuilder.ExportSceneResourceAndRun();
        }
        EditorGUILayout.EndVertical();
        EditorGUILayout.Space();
        EditorGUILayout.BeginVertical();
        EditorGUILayout.LabelField("Publish", EditorStyles.boldLabel);
        if (lastBuildPresent == false)
        {
            GUI.enabled = false;
        }
        if (GUILayout.Button("Last Build"))
        {
            if (APIUser.CurrentUser.canPublishWorlds)
            {
                VRC_SdkBuilder.shouldBuildUnityPackage = VRC.AccountEditorWindow.FutureProofPublishEnabled;
                VRC_SdkBuilder.UploadLastExportedSceneBlueprint();
            }
            else
            {
                ShowContentPublishPermissionsDialog();
            }
        }
        if (lastBuildPresent == false)
        {
            GUI.enabled = true;
        }
        if (GUILayout.Button("New Build"))
        {
            if (APIUser.CurrentUser.canPublishWorlds)
            {
                EnvConfig.ConfigurePlayerSettings();
                VRC_SdkBuilder.shouldBuildUnityPackage = VRC.AccountEditorWindow.FutureProofPublishEnabled;
                VRC_SdkBuilder.PreBuildBehaviourPackaging();
                VRC_SdkBuilder.ExportAndUploadSceneBlueprint();
            }
            else
            {
                ShowContentPublishPermissionsDialog();
            }
        }
        EditorGUILayout.EndVertical();
        GUI.enabled = true;
    }
예제 #5
0
        public override async Task <IEnumerable <ChanThreadPost> > GetPostsForTheadAsync(string urlSlug, int threadId)
        {
            var data = await ApiCache.GetApi <FourChanThreadPostObject>(string.Format(JsonThread, urlSlug, threadId));

            return(data.Posts.Select(p => p.GetViewModel(urlSlug, threadId)));
        }
예제 #6
0
 public NonStaticApi(ApiCache _cache)
 {
     Cache = _cache;
 }
        public async Task <IList <SolarSystemKills> > GetKillsForSystem(string systemName)
        {
            return(await ApiCache.GetCurrentData(string.Format("{0}_{1}", typeof(SolarSystemKills).Name, systemName), () => GetKills(systemName), x => x, false));

            //   return await Task.Factory.StartNew(() => GetKills(systemName), TaskCreationOptions.LongRunning);
        }
예제 #8
0
        private ApiHandlerOutput Process(ApiInputHandler input)
        {
            string typeName = Business.Resource.GetType(input.Resource);

            if (string.IsNullOrWhiteSpace(typeName))
            {
                throw new ApiNotFoundException(input.Resource);
            }

            bool canAccess = Business.Authorization.CanAccess(input.Resource, Context.Current.User);

            if (!canAccess)
            {
                logger.Warn($"Access denied for resource {input.Resource}");

                throw new SecurityException(Messages.AccessDenied);
            }

            if (Business.Authorization.RequireToken(input.Resource))
            {
                string token = input.Context.Request.Headers["ZestyApiToken"];

                if (string.IsNullOrWhiteSpace(token))
                {
                    token = input.Context.Request.Query["t"];
                }

                if (!Business.Authorization.IsValid(Context.Current.User.Id, input.Context.Session.Id, token))
                {
                    logger.Warn($"Invalid token for resource {input.Resource}");

                    throw new SecurityException(Messages.TokenMissing);
                }
            }

            ApiCacheItem cacheItem = ApiCache.Get(input);

            if (cacheItem != null)
            {
                logger.Info($"Output found in cache for request {input.Resource}");

                return(cacheItem.Output);
            }
            else
            {
                ApiHandlerBase handler = InstanceHelper.Create <ApiHandlerBase>(typeName);

                ApiHandlerOutput output = handler.Process(input);

                if (output.CachePolicy == ApiCachePolicy.Enable)
                {
                    cacheItem = new ApiCacheItem
                    {
                        Created  = DateTime.Now,
                        Output   = output,
                        Payload  = input.Body,
                        Resource = input.Resource
                    };

                    ApiCache.Store(cacheItem);

                    logger.Info($"Output stored in cache for request {input.Resource}");
                }


                if (output.ResourceHistoryOutput != null && output.ResourceHistoryOutput.ResourceHistoryPolicy == ApiResourceHistoryPolicy.Save)
                {
                    Business.History.Save(output.ResourceHistoryOutput.Item);
                }

                return(output);
            }
        }
예제 #9
0
        private void AddUserInfoButtons()
        {
            if (VRCEUi.UserInfoScreen == null)
            {
                ExtendedLogger.LogError("Failed to find UserInfo screen!");
                return;
            }

            Transform btnPlaylists = VRCEUi.InternalUserInfoScreen.PlaylistsButton;
            Transform btnFavorite  = VRCEUi.InternalUserInfoScreen.FavoriteButton;
            Transform btnReport    = VRCEUi.InternalUserInfoScreen.ReportButton;

            if (btnPlaylists == null || btnFavorite == null || btnReport == null)
            {
                ExtendedLogger.LogError("Failed to get required button!");
                return;
            }
            Vector3 pos = btnPlaylists.GetComponent <RectTransform>().localPosition;

            UserInfoLastLogin = new VRCEUiText("LastLoginText", new Vector2(-470f, -130f), "", VRCEUi.UserInfoScreen.transform);
            UserInfoLastLogin.Text.fontSize -= 20;

            UserInfoMore = new VRCEUiButton("More", new Vector2(pos.x, pos.y + 75f), "More", VRCEUi.InternalUserInfoScreen.UserPanel);
            UserInfoMore.Button.onClick.AddListener(() =>
            {
                if (Patch_PageUserInfo.SelectedAPI == null)
                {
                    return;
                }
                ToggleUserInfoMore(UserInfoMore.Text.text == "More");
            });

            UserInfoColliderControl = new VRCEUiButton("ColliderControl", new Vector2(pos.x, pos.y - 75f), "Not in world!", VRCEUi.InternalUserInfoScreen.UserPanel);
            UserInfoColliderControl.Control.gameObject.SetActive(false);
            UserInfoColliderControl.Button.onClick.AddListener(() =>
            {
                if (Patch_PageUserInfo.SelectedAPI == null)
                {
                    return;
                }
                ExtendedUser user = ExtendedServer.Users.FirstOrDefault(a => a.APIUser.id == Patch_PageUserInfo.SelectedAPI.id);

                if (user == null)
                {
                    return;
                }
                user.HasColliders = !user.HasColliders;
                UserInfoColliderControl.Text.text = (user.HasColliders ? "Disable colliders" : "Enable colliders");
            });

            UserInfoRefresh = new VRCEUiButton("Refresh", new Vector2(pos.x, pos.y), "Refresh", VRCEUi.InternalUserInfoScreen.UserPanel);
            UserInfoRefresh.Control.gameObject.SetActive(false);
            UserInfoRefresh.Button.onClick.AddListener(() =>
            {
                if (Patch_PageUserInfo.SelectedAPI == null)
                {
                    return;
                }

                ApiCache.Invalidate <APIUser>(Patch_PageUserInfo.SelectedAPI.id);
                APIUser.FetchUser(Patch_PageUserInfo.SelectedAPI.id, (APIUser user) =>
                {
                    PageUserInfo pageUserInfo = VRCEUi.UserInfoScreen.GetComponent <PageUserInfo>();
                    if (pageUserInfo != null)
                    {
                        pageUserInfo.SetupUserInfo(user);
                    }
                },
                                  (string error) =>
                {
                    ExtendedLogger.LogError(error);
                });
            });
            ExtendedLogger.Log("Setup PageUserInfo!");
        }
 public override void OnCreate(Bundle savedInstanceState)
 {
     base.OnCreate(savedInstanceState);
     service = new ApiService(ApiConfig.ApiKey);
     cache   = ApiCache.Current;
 }
예제 #11
0
 public StatusApi(ApiCache _cache)
 {
     Cache = _cache;
 }
예제 #12
0
파일: GameLogic.cs 프로젝트: weiranye/Messi
        // <Word, Definition, ImageUrl>
        public static List <Tuple <string, string, string> > GetWordDefImageList()
        {
            List <Tuple <string, string, string> > result = new List <Tuple <string, string, string> >();

            // get 4 random words
            List <string> fourWords = new List <string>();

            while (fourWords.Count < 4)
            {
                Random rnd        = new Random();
                string randomWord = WordRepo.Words[rnd.Next(0, WordRepo.Words.Count)];
                if (!fourWords.Contains(randomWord))
                {
                    fourWords.Add(randomWord);
                }
            }

            string imageUrl   = "";
            string definition = "";

            for (int i = 0; i < 4; i++)
            {
                // try cache first
                using (Models.Messi messi = new Models.Messi())
                {
                    string   word  = fourWords[i];
                    ApiCache cache = messi.ApiCaches.Where(a => a.Word.Equals(word)).FirstOrDefault();
                    if (cache != null)
                    {
                        imageUrl   = cache.ImageUrl;
                        definition = cache.Definition;
                    }
                    else
                    {
                        // get imageUrl from API.
                        DkApiResult dkResult = Helper.ImageLookUp(word);
                        if (dkResult.total < 1)
                        {
                            throw new Exception("Number of images for this word is less than 1. Word: " + word);
                        }
                        else
                        {
                            imageUrl = dkResult.images[0].url;
                        }

                        // get definition from API
                        JObject lmResult = Helper.DefinitionLookUpObj(word);
                        JToken  lmEntry  = (lmResult["Entries"]["Entry"] is JArray) ? lmResult["Entries"]["Entry"][0] : lmResult["Entries"]["Entry"];
                        JToken  lmSense  = (lmEntry["Sense"] is JArray) ? lmEntry["Sense"][0] : lmEntry["Sense"];
                        JToken  lmDEF    = lmSense["DEF"];
                        if (lmDEF == null)
                        {
                            JToken lmSubsense = (lmSense["Subsense"] is JArray) ? lmSense["Subsense"][0] : lmSense["Subsense"];
                            lmDEF = lmSubsense["DEF"];
                        }
                        definition = lmDEF["#text"].ToString();

                        // cache it
                        messi.ApiCaches.Add(new ApiCache()
                        {
                            Word       = word,
                            ImageUrl   = imageUrl,
                            Definition = definition
                        });
                        messi.SaveChanges();
                    }
                    // done. <Word, Definition, ImageUrl>
                    result.Add(new Tuple <string, string, string>(word, definition, imageUrl));
                }
            }
            return(result);
        }
예제 #13
0
        public static void InitializeConfig()
        {
            // init defaults
            ConfigManager.GeneralConfig.SetDefaults();
            ConfigManager.ApiCache.SetDefaults();

            ConfigManager.GeneralConfig.hwid = Helpers.GetCpuID();
            // if exists load file
            GeneralConfig fromFile = null;

            if (GeneralConfigFile.IsFileExists())
            {
                fromFile = GeneralConfigFile.ReadFile();
            }
            ApiCache fromFileapi = null;

            if (ApiCacheFile.IsFileExists())
            {
                fromFileapi = ApiCacheFile.ReadFile();
            }

            //MagnitudeConfigFile fromFileMagnitude = null;
            //if (fromFileMagnitude.IsFileExists())
            //{
            //    fromFileMagnitude = MagnitudeConfigFile.ReadFile();
            //}
            // just in case
            if (fromFile != null)
            {
                // set config loaded from file
                IsGeneralConfigFileInit     = true;
                ConfigManager.GeneralConfig = fromFile;
                if (ConfigManager.GeneralConfig.ConfigFileVersion == null ||
                    ConfigManager.GeneralConfig.ConfigFileVersion.CompareTo(System.Reflection.Assembly.GetExecutingAssembly().GetName().Version) != 0)
                {
                    if (ConfigManager.GeneralConfig.ConfigFileVersion == null)
                    {
                        Helpers.ConsolePrint(TAG, "Loaded Config file no version detected falling back to defaults.");
                        ConfigManager.GeneralConfig.SetDefaults();
                    }
                    Helpers.ConsolePrint(TAG, "Config file is from an older version of zPoolMiner..");
                    IsNewVersion = true;
                    GeneralConfigFile.CreateBackup();
                }
                ConfigManager.GeneralConfig.FixSettingBounds();
            }
            else
            {
                GeneralConfigFileCommit();
            }
            if (fromFileapi != null)
            {
                // set config loaded from file
                IsApiCacheFileInit     = true;
                ConfigManager.ApiCache = fromFileapi;
                if (ConfigManager.ApiCache.ConfigFileVersionapi == null ||
                    ConfigManager.ApiCache.ConfigFileVersionapi.CompareTo(System.Reflection.Assembly.GetExecutingAssembly().GetName().Version) != 0)
                {
                    if (ConfigManager.ApiCache.ConfigFileVersionapi == null)
                    {
                        Helpers.ConsolePrint(TAG, "Loaded API Config file no version detected falling back to defaults.");
                        ConfigManager.ApiCache.SetDefaults();
                    }
                    Helpers.ConsolePrint(TAG, "API Config file is from an older version of zPoolMiner..");
                    IsNewVersion = true;
                    ApiCacheFile.CreateBackup();
                }
                ConfigManager.ApiCache.FixSettingBounds();
            }
            else
            {
                ApiCacheFileCommit();
            }
        }