static RestfulAPI CreateProductAsync(String url, InfoMail mailInfo) { client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); RestfulAPI rs = new RestfulAPI(); var res = client.PostAsJsonAsync(url, mailInfo).Result; if (res.StatusCode == System.Net.HttpStatusCode.OK) { rs = res.Content.ReadAsAsync <RestfulAPI>().Result; //DataUserLogin.MaTaiKhoan = res.Content.ReadAsAsync<string>().Result; //if (DataUserLogin.MaTaiKhoan.Equals("-1")) //{ // MessageBox.Show("Mật khẩu hoặc tên đăng nhập không đúng!"); //} //else //{ // Form1 frm = new Form1(); // this.Hide(); // frm.ShowDialog(); // this.Dispose(); //} } else { MessageBox.Show("Có lỗi xảy ra!"); } return(rs); }
private void btn_tao_Click(object sender, EventArgs e) { InfoMail mailInfo = new InfoMail(); mailInfo.username = txt_username.Text; mailInfo.email = txt_email.Text; mailInfo.sdt = txt_sdt.Text; mailInfo.cmnd = txt_cmnd.Text; mailInfo.ngaysinh = dtp_ngaysinh.Value.ToString("yyyyMMdd"); mailInfo.diachi = txt_diachi.Text; if (cbb_loaiuser.Text.Equals("Sinh Viên")) { mailInfo.loaiUS = 1; } else if (cbb_loaiuser.Text.Equals("Giáo Viên")) { mailInfo.loaiUS = 2; } else { mailInfo.loaiUS = 3; } mailInfo.password_email = txt_passemail.Text; String url = localhost + "rest/mail/dangkimail"; RestfulAPI rs = CreateProductAsync(url, mailInfo); if (rs.ketqua == 1) { MessageBox.Show("Thành công !"); } else { MessageBox.Show("Có lỗi xảy ra!"); } }
public async Task <ScriptInstallStatus> InstallScript(ContentType contentType, FGORegion region, List <string> installPaths, string baseInstallPath, int installId, string assetStorageCheck = null, ObservableCollection <InstallerPage.TranslationGUIObject> translationGuiObjects = null) { _cm.ClearCache(); var gui = translationGuiObjects != null; var guiObject = gui ? translationGuiObjects.First(w => w.BundleID == installId) : null; if (guiObject != null) { guiObject.Status = UIFunctions.GetResourceString("InstallingFetchingHandshake"); guiObject.ButtonInstallText = UIFunctions.GetResourceString("InstallingText"); guiObject.TextColor = Color.Chocolate; } // fetch new translation list to ensure it is up to date var restful = new RestfulAPI(); var translationList = await restful.GetHandshakeApiResponse(region, assetStorageCheck); if (!translationList.IsSuccessful || translationList.Data.Status != 200) { return(new ScriptInstallStatus() { IsSuccessful = false, ErrorMessage = String.Format(UIFunctions.GetResourceString("InstallHandshakeFailure"), translationList.StatusCode, translationList.Data?.Message) }); } if (assetStorageCheck != null) { switch (translationList.Data.Response.AssetStatus) { case HandshakeAssetStatus.UpdateRequired: return(new ScriptInstallStatus() { IsSuccessful = false, ErrorMessage = String.Format("AssetStorage.txt out of date, skipping update.") }); default: break; } } // download required scripts var groupToInstall = translationList.Data.Response.Translations.FirstOrDefault(w => w.Group == installId); if (groupToInstall?.Scripts == null) { return(new ScriptInstallStatus() { IsSuccessful = false, ErrorMessage = String.Format(UIFunctions.GetResourceString("InstallMissingScriptFailure"), installId) }); } if (!gui && groupToInstall.Hidden) { return(new ScriptInstallStatus() { IsSuccessful = false, ErrorMessage = String.Format(UIFunctions.GetResourceString("InstallHiddenScriptFailure"), installId) }); } var totalScripts = groupToInstall.Scripts.Count; if (guiObject != null) { guiObject.Status = String.Format(UIFunctions.GetResourceString("InstallDownloadingScripts"), 1, totalScripts); } ConcurrentDictionary <string, byte[]> scriptDictionary = new ConcurrentDictionary <string, byte[]>(); object lockObj = new Object(); try { await groupToInstall.Scripts.ParallelForEachAsync(async script => { var name = script.Key; var downloadUrl = script.Value.DownloadURL; var downloadResponse = await restful.GetScript(downloadUrl); var downloadedScript = downloadResponse.RawBytes; if (!downloadResponse.IsSuccessful) { throw new EndEarlyException(String.Format(UIFunctions.GetResourceString("InstallScriptDownloadFailure"), installId, downloadUrl, downloadResponse.ErrorMessage)); } if (downloadedScript == null) { throw new EndEarlyException(String.Format(UIFunctions.GetResourceString("InstallEmptyFileFailure"), installId, downloadUrl)); } var scriptSha = ScriptUtil.Sha1(downloadedScript); if (scriptSha != script.Value.TranslatedSHA1) { throw new EndEarlyException(String.Format(UIFunctions.GetResourceString("InstallChecksumFailure"), installId, downloadedScript.Length, downloadUrl)); } scriptDictionary.TryAdd(name, downloadedScript); lock (lockObj) { if (guiObject != null) { guiObject.Status = String.Format(UIFunctions.GetResourceString("InstallDownloadingScripts"), Math.Min(scriptDictionary.Count, totalScripts), totalScripts); } } }, maxDegreeOfParallelism : 4); } catch (EndEarlyException ex) { return(new ScriptInstallStatus() { IsSuccessful = false, ErrorMessage = ex.ToString() }); } if (guiObject != null) { guiObject.Status = String.Format(UIFunctions.GetResourceString("InstallDownloadNewAssetStorage")); } Dictionary <string, byte[]> newAssetStorages = new Dictionary <string, byte[]>(); // get new assetstorage.txt foreach (var game in installPaths) { var assetStoragePath = contentType != ContentType.DirectAccess ? $"data/{game}/files/data/d713/{InstallerPage._assetList}" : $"{game}/files/data/d713/{InstallerPage._assetList}"; var fileContents = await _cm.GetFileContents(contentType, assetStoragePath, baseInstallPath); if (!fileContents.Successful || fileContents.FileContents.Length == 0) { return(new ScriptInstallStatus() { IsSuccessful = false, ErrorMessage = String.Format(UIFunctions.GetResourceString("InstallEmptyAssetStorage"), installId, assetStoragePath, fileContents.Error) }); } // remove bom var base64 = ""; await using var inputStream = new MemoryStream(fileContents.FileContents); using (var reader = new StreamReader(inputStream, Encoding.ASCII)) { base64 = await reader.ReadToEndAsync(); } var newAssetList = await restful.SendAssetList(base64, installId, region); if (!newAssetList.IsSuccessful) { return(new ScriptInstallStatus() { IsSuccessful = false, ErrorMessage = string.Format(UIFunctions.GetResourceString("InstallAssetStorageAPIFailure"), installId, newAssetList.StatusCode, newAssetList.Data?.Message) }); } // add bom await using var outputStream = new MemoryStream(); await using (var writer = new StreamWriter(outputStream, Encoding.ASCII)) { await writer.WriteAsync(newAssetList.Data.Response["data"]); } newAssetStorages.Add(assetStoragePath, outputStream.ToArray()); } // prepare files Dictionary <string, byte[]> filesToWrite = newAssetStorages; foreach (var game in installPaths) { foreach (var asset in scriptDictionary) { var assetInstallPath = contentType != ContentType.DirectAccess ? $"data/{game}/files/data/d713/{asset.Key}" : $"{game}/files/data/d713/{asset.Key}"; filesToWrite.Add(assetInstallPath, asset.Value); } } // write files int j = 1; int tot = filesToWrite.Count; foreach (var file in filesToWrite) { if (file.Key.EndsWith(".bin")) { await _cm.RemoveFileIfExists(contentType, file.Key, baseInstallPath); } } _cm.ClearCache(); foreach (var file in filesToWrite) { if (guiObject != null) { guiObject.Status = String.Format(UIFunctions.GetResourceString("InstallWriteFile"), j, tot); } await _cm.WriteFileContents(contentType, file.Key, baseInstallPath, file.Value); j += 1; } if (guiObject != null) { guiObject.Status = String.Format(UIFunctions.GetResourceString("InstallFinished")); guiObject.TextColor = Color.LimeGreen; } Preferences.Set($"InstalledScript_{region}", JsonConvert.SerializeObject(groupToInstall)); return(new ScriptInstallStatus() { IsSuccessful = true, ErrorMessage = "" }); }
private async Task UpdateCheck() { var rest = new RestfulAPI(); var response = await rest.GetVersionAPIResponse(); bool addAnnouncementPage = false; while (!response.IsSuccessful) { string errorMessage; errorMessage = !string.IsNullOrEmpty(response.Data?.Message) ? $"{AppResources.VersionErrorMessage}\n{response.Data.Status}: {response.Data.Message}" : $"{AppResources.VersionErrorMessage}\n{response.ResponseStatus}: {response.ErrorMessage}\n\n{response.Content}"; var doRetry = await DisplayAlert(AppResources.VersionErrorTitle, errorMessage, AppResources.VersionRetryButton, AppResources.VersionExitButton); if (!doRetry) { DependencyService.Get <IIntentService>()?.ExitApplication(); } response = await rest.GetVersionAPIResponse(); } bool gotoUpdate = response.Data.Response.Action == "update" && Preferences.Get("IgnoreUpdate", 0) < response.Data.Response.Update.AppVer; // announcements if (response.Data.Response.Announcement != null) { Preferences.Set("AnnouncementData", JsonConvert.SerializeObject(response.Data.Response.Announcement)); if (Preferences.Get("AnnouncementRead", 0) < response.Data.Response.Announcement.id) { addAnnouncementPage = true; } } var cm = DependencyService.Get <IContentManager>(); if (cm.CheckBasicAccess()) { if (gotoUpdate) { Device.BeginInvokeOnMainThread(async() => { await GotoUpdatePage(response.Data.Response.Update); // update takes priority over announcement }); } else if (addAnnouncementPage) { await GotoAnnouncementPage(); } } else if (string.IsNullOrWhiteSpace(Preferences.Get("StorageLocation", ""))) { if (gotoUpdate) { Device.BeginInvokeOnMainThread(async() => { Unsubscribe(); var page = await GotoUpdatePage(response.Data.Response.Update); Navigation.InsertPageBefore(new PreInitializePage(), page); // tuck under the update page Navigation.RemovePage(this); }); } else { Device.BeginInvokeOnMainThread(async() => { Unsubscribe(); Navigation.InsertPageBefore(new PreInitializePage(), this); await Navigation.PopAsync(true); }); } } else { if (gotoUpdate) { Device.BeginInvokeOnMainThread(async() => { await GotoUpdatePage(response.Data.Response.Update); }); } else if (addAnnouncementPage) { await GotoAnnouncementPage(); } } }
async void SendRegistrationToServer(string token) { var rest = new RestfulAPI(); await rest.SendRegistrationToken(token); }
public async Task <int> BeginUpdate() { var rest = new RestfulAPI(); TranslationList installedBundle = null; bool android11Access = false; int region = 1; try { var sm = new ScriptManager(); var cm = new ContentManager(); var prefKey = InputData.GetString("preferencesKey"); region = InputData.GetInt("region", -1); if (string.IsNullOrEmpty(prefKey) || region == -1) { return(0); } var storageLocation = Preferences.Get("StorageLocation", ""); android11Access = !string.IsNullOrEmpty(storageLocation) || !cm.CheckBasicAccess(); if (string.IsNullOrEmpty(storageLocation) && android11Access) { Log.Warn(TAG, "Not setup properly, android storage empty but android 11 mode required. Or no write access."); return(0); } var installedScriptString = Preferences.Get(prefKey, ""); if (string.IsNullOrEmpty(installedScriptString)) { Log.Warn(TAG, "Not setup properly, installed script key empty."); return(0); } cm.ClearCache(); var installedFgoInstances = !android11Access?cm.GetInstalledGameApps(ContentType.DirectAccess) : cm.GetInstalledGameApps(ContentType.StorageFramework, storageLocation); foreach (var instance in installedFgoInstances.ToList()) { var filePath = android11Access ? $"data/{instance.Path}/files/data/d713/{InstallerPage._assetList}" : $"{instance.Path}/files/data/d713/{InstallerPage._assetList}"; var assetStorage = await cm.GetFileContents( android11Access?ContentType.StorageFramework : ContentType.DirectAccess, filePath, storageLocation); if (!assetStorage.Successful) { installedFgoInstances.Remove(instance); } instance.LastModified = assetStorage.LastModified; if (assetStorage?.FileContents != null) { var base64 = ""; await using var inputStream = new MemoryStream(assetStorage.FileContents); using (var reader = new StreamReader(inputStream, Encoding.ASCII)) { base64 = await reader.ReadToEndAsync(); } instance.AssetStorage = base64; } else { instance.AssetStorage = null; } } installedBundle = JsonConvert.DeserializeObject <TranslationList>(installedScriptString); var installResult = await sm.InstallScript( android11Access?ContentType.StorageFramework : ContentType.DirectAccess, (FGORegion)region, installedFgoInstances.Where(w => w.Region == (FGORegion)region).Select(s => s.Path).ToList(), storageLocation, installedBundle.Group, installedFgoInstances.OrderByDescending(o => o.LastModified)?.First(o => o.Region == (FGORegion)region)?.AssetStorage, null ); if (!installResult.IsSuccessful) { Log.Warn(TAG, $"Unsuccessful installation, reason: {installResult.ErrorMessage}"); await rest.SendSuccess((FGORegion)region, (int)installedBundle.Language, TranslationInstallType.Automatic, installedBundle.Group, false, installResult.ErrorMessage, android11Access); return(0); } Log.Info(TAG, $"Successfully installed bundle {installedBundle.Group}."); await rest.SendSuccess((FGORegion)region, (int)installedBundle.Language, TranslationInstallType.Automatic, installedBundle.Group, true, "", android11Access); } catch (Exception ex) { Log.Warn(TAG, $"Exception occurred during auto update, {ex}"); if (installedBundle != null) { await rest.SendSuccess((FGORegion)region, (int)installedBundle.Language, TranslationInstallType.Automatic, installedBundle.Group, false, ex.ToString(), android11Access); } else { await rest.SendSuccess((FGORegion)region, 1, TranslationInstallType.Automatic, 0, false, ex.ToString(), android11Access); } return(0); } return(1); }
public async Task Install(FGORegion region, int toInstall) { _cm.ClearCache(); bool answer = await DisplayAlert(AppResources.Warning, String.Format(AppResources.InstallWarning, _translations[toInstall].TotalSize.Bytes().Humanize("#.## MB")), AppResources.Yes, AppResources.No); if (!answer) { return; } SwitchButtons(false); var rest = new RestfulAPI(); var language = _handshake.Response.Translations.First(f => f.Group == toInstall).Language; Task successSendTask = null; try { var installResult = await _sm.InstallScript( _android11Access?ContentType.StorageFramework : ContentType.DirectAccess, region, _installedFgoInstances.Where(w => w.Region == region).Select(s => s.Path).ToList(), _storageLocation, toInstall, null, _guiObjects ); if (!installResult.IsSuccessful) { successSendTask = rest.SendSuccess(region, language, TranslationInstallType.Manual, toInstall, false, installResult.ErrorMessage, _android11Access); await DisplayAlert(AppResources.Error, installResult.ErrorMessage, AppResources.OK); } else { successSendTask = rest.SendSuccess(region, language, TranslationInstallType.Manual, toInstall, true, "", _android11Access); await Task.Delay(1000); } } catch (System.UnauthorizedAccessException ex) { if (!_android11Access) { successSendTask = rest.SendSuccess(region, language, TranslationInstallType.Manual, toInstall, false, "Unauthorized error handler: " + ex.ToString(), _android11Access); var retry = await DisplayAlert(AppResources.DirectoryPermissionDeniedTitle, AppResources.Android11AskToSetup, AppResources.Yes, AppResources.No); if (retry) { await successSendTask; MessagingCenter.Send(Xamarin.Forms.Application.Current, "installer_page_goto_pre_initialize"); return; } await successSendTask; return; } else { throw; } } catch (Exception ex) { successSendTask = rest.SendSuccess(region, language, TranslationInstallType.Manual, toInstall, false, ex.ToString(), _android11Access); await DisplayAlert(AppResources.InternalError, String.Format(AppResources.InternalErrorDetails, ex.ToString()), AppResources.OK); } await successSendTask; await UpdateTranslationList(); //SwitchButtons(true); }
public async Task UpdateTranslationList() { _cm.ClearCache(); if (_isCurrentlyUpdating) { return; } _isCurrentlyUpdating = true; try { ReleaseScheduleLayout.IsVisible = false; RetryButton.IsVisible = false; LoadingLayout.IsVisible = true; TranslationListView.IsVisible = false; MasterButtons.IsVisible = false; Refresh.IsRefreshing = true; //SwitchButtons(false); SwitchErrorObjects(false); ActivityIndicatorLoading.IsRunning = true; Refresh.IsEnabled = false; RevertButton.Text = AppResources.UninstallText; ActivityIndicatorLoading.VerticalOptions = LayoutOptions.Center; ActivityIndicatorLoading.HorizontalOptions = LayoutOptions.Center; LoadingText.Text = AppResources.LoadingPleaseWait; LoadingText.VerticalOptions = LayoutOptions.CenterAndExpand; LoadingText.HorizontalOptions = LayoutOptions.CenterAndExpand; //await Task.Delay(1000); _storageLocation = Preferences.Get("StorageLocation", ""); if (!string.IsNullOrEmpty(_storageLocation) || !_cm.CheckBasicAccess()) { _android11Access = true; } if (!_android11Access) { _installedFgoInstances = _cm.GetInstalledGameApps(ContentType.DirectAccess); } else { _installedFgoInstances = _cm.GetInstalledGameApps(ContentType.StorageFramework, _storageLocation); } //TranslationName.Text = Region == FGORegion.Jp //? String.Format(AppResources.InstallerTitle, "JP") + $": {handshake.Data.Response.AppVer}" //: String.Format(AppResources.InstallerTitle, "NA") + $": {handshake.Data.Response.AppVer}"; // Check region is installed if (_installedFgoInstances.All(w => w.Region != Region)) { LoadingText.Text = String.Format(AppResources.NoFGOFound, $"Fate/Grand Order {Region.ToString().ToUpper()}"); SwitchErrorObjects(true); return; } foreach (var instance in _installedFgoInstances.ToList()) { var filePath = _android11Access ? $"data/{instance.Path}/files/data/d713/{_assetList}" : $"{instance.Path}/files/data/d713/{_assetList}"; var assetStorage = await _cm.GetFileContents( _android11Access?ContentType.StorageFramework : ContentType.DirectAccess, filePath, _storageLocation); if (!assetStorage.Successful) { _installedFgoInstances.Remove(instance); } instance.LastModified = assetStorage.LastModified; if (assetStorage?.FileContents != null) { var base64 = ""; using var inputStream = new MemoryStream(assetStorage.FileContents); using (var reader = new StreamReader(inputStream, Encoding.ASCII)) { base64 = await reader.ReadToEndAsync(); } instance.AssetStorage = base64; } else { instance.AssetStorage = null; } } var instanceDict = _installedFgoInstances.OrderByDescending(o => o.LastModified).FirstOrDefault(w => w.Region == Region); if (instanceDict == null) { LoadingText.Text = String.Format(AppResources.NoFGOInstallationFound2, $"Fate/Grand Order {Region.ToString().ToUpper()}"); SwitchErrorObjects(true); return; } var rest = new RestfulAPI(); var handshake = await rest.GetHandshakeApiResponse(Region, instanceDict.AssetStorage); _handshake = handshake.Data; if (handshake.Data == null || handshake.Data.Status != 200) { LoadingText.Text = handshake.Data == null ? AppResources.TryAgainLater : $"{AppResources.TranslateAPIError}\n{handshake.Data?.Message}"; SwitchErrorObjects(true); return; } if (handshake.Data.Response.AssetStatus != HandshakeAssetStatus.Missing && handshake.Data.Response.AssetStatus != HandshakeAssetStatus.UpToDate) { var warningTitle = AppResources.Warning + $" ({Region.ToString().ToUpper()})"; switch (handshake.Data.Response.AssetStatus) { case HandshakeAssetStatus.Missing: break; case HandshakeAssetStatus.UpToDate: break; case HandshakeAssetStatus.UpdateRequired: await DisplayAlert(warningTitle, AppResources.AssetWarningOutOfDate, AppResources.OK); break; case HandshakeAssetStatus.TimeTraveler: await DisplayAlert(warningTitle, AppResources.AssetWarningFutureUnreleased, AppResources.OK); break; case HandshakeAssetStatus.Unrecognized: await DisplayAlert(warningTitle, AppResources.AssetWarningUnrecognised, AppResources.OK); break; case HandshakeAssetStatus.Corrupt: await DisplayAlert(warningTitle, AppResources.AssetWarningCorrupted, AppResources.OK); break; default: throw new ArgumentOutOfRangeException(); } } var baseFilePath = _android11Access ? $"data/{instanceDict.Path}/files/data/d713/" : $"{instanceDict.Path}/files/data/d713/"; await ProcessAssets(_android11Access?ContentType.StorageFramework : ContentType.DirectAccess, baseFilePath, _storageLocation, Region); // Add top bar if (_handshake.Response.LiveStatus != null && _handshake.Response.LiveStatus.Enabled) { ReleaseScheduleLayout.IsVisible = true; ReleaseScheduleChapter.Text = _handshake.Response.LiveStatus.CurrentRelease; if (_handshake.Response.LiveStatus.NextReleaseDate < DateTime.UtcNow) { DisplayNextUpdateTime.IsVisible = false; } else { var timespan = _handshake.Response.LiveStatus.NextReleaseDate.Subtract(DateTime.UtcNow); var lastUpdated = InstallerUtil.PeriodOfTimeOutput(timespan, 0, ""); ReleaseScheduleTimeRemaining.Text = lastUpdated; } ReleaseSchedulePercent.Text = _handshake.Response.LiveStatus.PercentDone; ReleaseScheduleTitle.Text = _handshake.Response.LiveStatus.Title; var announcementJson = Preferences.Get("AnnouncementData", null); if (announcementJson != null) { var json = JsonConvert.DeserializeObject <VersionAPIResponse.TranslationAnnouncements>( announcementJson); if (json.IsSpecialAnnouncement) { ReleaseTap.Tapped += OpenAnnouncementOnClicked; } } } LoadingLayout.IsVisible = false; TranslationListView.IsVisible = true; MasterButtons.IsVisible = true; Refresh.IsRefreshing = false; SwitchErrorObjects(false); ActivityIndicatorLoading.IsRunning = false; Refresh.IsEnabled = true; SwitchButtons(true); } catch (Exception ex) { await DisplayAlert(AppResources.InternalError, String.Format(AppResources.InternalErrorDetails, ex.ToString()), AppResources.OK); _isCurrentlyUpdating = false; SwitchErrorObjects(true); } _isCurrentlyUpdating = false; }