Ejemplo n.º 1
0
        public async Task <IActionResult> DoSearch([FromQuery(Name = "q")] string question, int page = 1)
        {
            if (string.IsNullOrWhiteSpace(question))
            {
                return(Redirect("/"));
            }
            ViewBag.CurrentPage = page;
            var market = CultureInfo.CurrentCulture.Name;
            var result = await _cache.GetAndCache($"search-content-{market}-{page}-" + question, () => _searchService.DoSearch(question, market, page));

            ViewBag.Entities = await _cache.GetAndCache($"search-entity-{market}-" + question, () => _searchService.EntitySearch(question, market));

            if (HttpContext.AllowTrack())
            {
                await _dbContext.SearchHistories.AddAsync(new SearchHistory
                {
                    Question      = question,
                    TriggerUserId = User.GetUserId(),
                    Page          = page
                });

                await _dbContext.SaveChangesAsync();
            }
            return(View(result));
        }
Ejemplo n.º 2
0
        public async Task <IActionResult> KahlaServerList()
        {
            var serversFileAddress = _configuration["KahlaServerList"];
            var serversJson        = await _cache.GetAndCache("servers-list", () => _httpService.Get(new AiurUrl(serversFileAddress), false));

            var servers         = JsonConvert.DeserializeObject <List <string> >(serversJson);
            var serversRendered = new ConcurrentBag <IndexViewModel>();
            await servers.ForEachParallel(async server =>
            {
                try
                {
                    var serverInfo = await _cache.GetAndCache($"server-detail-{server}", () => _homeService.IndexAsync(server));
                    if (serverInfo != null)
                    {
                        serversRendered.Add(serverInfo);
                    }
                }
                catch
                {
                    // ignored
                }
            });

            Response.Headers.Add("Access-Control-Allow-Origin", "*");
            return(Json(serversRendered));
        }
 public virtual Task <bool> IsValidAppAsync(string appId, string appSecret)
 {
     if (!new IsGuidOrEmpty().IsValid(appId))
     {
         return(Task.FromResult(false));
     }
     if (!new IsGuidOrEmpty().IsValid(appSecret))
     {
         return(Task.FromResult(false));
     }
     return(_cache.GetAndCache($"ValidAppWithId-{appId}-Secret-{appSecret}", () => IsValidAppWithoutCacheAsync(appId, appSecret)));
 }
Ejemplo n.º 4
0
        private async Task <string> GetUploadToken(string siteName, string path)
        {
            if (!await _aiurCache.GetAndCache($"site-public-status-{siteName}", () => OpenUpload(siteName)))
            {
                var accessToken = ViewBag.AccessToken as string ?? await _appsContainer.AccessToken();

                return(await _tokenService.GetTokenAsync(accessToken, siteName, new string[] { "Upload" }, path));
            }
            return(string.Empty);
        }
Ejemplo n.º 5
0
        public async Task <IActionResult> Index()
        {
            var(appVersion, cliVersion) = await _cache.GetAndCache("Version.Cache", () => _version.CheckKahla());

            var downloadSite = "https://download.kahla.app";
            var model        = new IndexViewModel
            {
                AppLatestVersion = appVersion,
                CLILatestVersion = cliVersion,
                SDKLatestVersion = _versionService.GetSDKVersion(),
                DownloadRoot     = $"{downloadSite}/production",
                CliDownloadRoot  = $"{downloadSite}/productioncli",
                ArchiveRoot      = "https://github.com/AiursoftWeb/Kahla.App/archive",
                KahlaWebPath     = "//web.kahla.app",
                IsProduction     = true,
            };

            return(View(model));
        }
Ejemplo n.º 6
0
        public async Task <IActionResult> Version()
        {
            var(appVersion, cliVersion) = await _cache.GetAndCache(nameof(Version), () => _version.CheckKahla());

            return(Json(new VersionViewModel
            {
                LatestVersion = appVersion,
                LatestCLIVersion = cliVersion,
                Message = "Successfully get the latest version number for Kahla App and Kahla.CLI.",
                DownloadAddress = "https://www.kahla.app"
            }));
        }
Ejemplo n.º 7
0
        public async Task <GatewayUser> EnsureGranted(string accessToken, string userId, Func <App, bool> prefix)
        {
            var appid      = _tokenManager.ValidateAccessToken(accessToken);
            var targetUser = await _dbContext.Users.Include(t => t.Emails).SingleOrDefaultAsync(t => t.Id == userId);

            var app = await _aiurCache.GetAndCache($"app-info-cache-{appid}", () => _developerApiService.AppInfoAsync(appid));

            if (!_dbContext.LocalAppGrant.Any(t => t.AppId == appid && t.GatewayUserId == targetUser.Id))
            {
                throw new AiurAPIModelException(ErrorType.Unauthorized, "This user did not grant your app!");
            }
            if (prefix != null && !prefix(app.App))
            {
                throw new AiurAPIModelException(ErrorType.Unauthorized, "You app is not allowed to do that!");
            }
            return(targetUser);
        }
Ejemplo n.º 8
0
        public async Task <IActionResult> AuditLog()
        {
            var user = await GetCurrentUserAsync();

            var token = await _appsContainer.AccessToken();

            var model = new AuditLogViewModel(user)
            {
                Logs = (await _userService.ViewAuditLogAsync(token, user.Id)).Items
            };
            await model.Logs.Select(t => t.AppId).Distinct().ForEachParallel(async(id) =>
            {
                var appInfo = await _cache.GetAndCache($"appInfo-{id}", () => _developerApiService.AppInfoAsync(id));
                model.Apps.Add(appInfo.App);
            });

            return(View(model));
        }
Ejemplo n.º 9
0
        public async Task <IViewComponentResult> InvokeAsync(string org, string repo)
        {
            var markdownUrl = $"https://raw.githubusercontent.com/{org}/{repo}/master/README.md";
            var markdown    = await _cache.GetAndCache($"github.{org}.{repo}.cache",
                                                       async() => await _http.Get(new AiurUrl(markdownUrl), false));

            var pipeline = new MarkdownPipelineBuilder()
                           .UseAdvancedExtensions()
                           .Build();
            var html  = Markdown.ToHtml(markdown, pipeline);
            var model = new GitHubRendererViewModel
            {
                Org  = org,
                Repo = repo,
                HTML = html
            };

            return(View(model));
        }
Ejemplo n.º 10
0
        public async Task <IActionResult> AccessToken(AccessTokenAddressModel model)
        {
            var cacheKey   = $"Id-{model.AppId}-Secret-{model.AppSecret}";
            var correctApp = await _cache.GetAndCache(cacheKey, () => _developerApiService.IsValidAppAsync(model.AppId, model.AppSecret));

            if (correctApp)
            {
                var token = _tokenManager.GenerateAccessToken(model.AppId);
                return(Json(new AccessTokenViewModel
                {
                    Code = ErrorType.Success,
                    Message = "Successfully get access token.",
                    AccessToken = token.Item1,
                    DeadTime = token.Item2
                }));
            }
            else
            {
                return(this.Protocol(ErrorType.WrongKey, "Wrong app info."));
            }
        }
Ejemplo n.º 11
0
        public async Task <JsonResult> IsValidApp(IsValidateAppAddressModel model)
        {
            var target = await _cache.GetAndCache(model.AppId, async() => await _dbContext.Apps.FindAsync(model.AppId));

            if (target == null)
            {
                return(Json(new AiurProtocol {
                    Message = "Target app did not found.", Code = ErrorType.NotFound
                }));
            }
            else if (target.AppSecret != model.AppSecret)
            {
                return(Json(new AiurProtocol {
                    Message = "Wrong secret.", Code = ErrorType.WrongKey
                }));
            }
            else
            {
                return(Json(new AiurProtocol {
                    Message = "Correct app info.", Code = ErrorType.Success
                }));
            }
        }
Ejemplo n.º 12
0
        public async Task <IActionResult> Index()
        {
            var(appVersion, cliVersion) = await _cache.GetAndCache("Version.Cache", () => _version.CheckKahla());

            var downloadSite = await _serviceLocation.TryGetCDNDomain("https://download.kahla.app");

            var mode = Request.Host.ToString().ToLower().Contains("staging") ?
                       "staging" : "production";
            var isProduction = mode == "production";
            var model        = new IndexViewModel
            {
                AppLatestVersion = appVersion,
                CLILatestVersion = cliVersion,
                SDKLatestVersion = _versionService.GetSDKVersion(),
                DownloadRoot     = $"{downloadSite}/{mode}",
                CliDownloadRoot  = $"{downloadSite}/{mode}",
                ArchiveRoot      = "https://github.com/AiursoftWeb/Kahla.App/archive",
                KahlaWebPath     = isProduction ? "//web.kahla.app" : "//staging.web.kahla.app",
                IsProduction     = isProduction,
            };

            return(View(model));
        }
Ejemplo n.º 13
0
 private long GetFileSizeWithCache(File file)
 {
     return(_cache.GetAndCache($"file-size-cache-id-{file.Id}", () => GetFileSize(file)));
 }
Ejemplo n.º 14
0
 public long GetSize(string hardwareUuid)
 {
     return(_cache.GetAndCache($"file-size-cache-id-{hardwareUuid}", () => GetFileSize(hardwareUuid)));
 }