/// <summary> /// Kills Index: Removes all files in cache folder and all entries in this cache index. /// </summary> public void KillIndex() { try { lock (syncLock) { // Remove all files and directories in cache folder subdirectories. var path = CachePath.AppendPath(BaseUriPath); foreach (var d in Device.File.GetDirectoryNames(path)) { Device.File.DeleteDirectory(d, true); } // remove all files in cache folder except for Serializefile foreach (var f in Device.File.GetFileNames(path).Where(f => !f.Equals(SerializeFile))) { Device.File.Delete(f); } // remove all entries in cache index Clear(); // Serialize the CacheIndex SerializeCacheIndex(this); } } catch (Exception exc) { Device.Log.Error("CacheIndex.KillIndex() encountered an exception", exc); } }
/// <summary> /// Gets the cache path. /// </summary> /// <param name="cacheIndexItem">The cache index item.</param> /// <returns></returns> public string GetCachePath(CacheIndexItem cacheIndexItem) { var chars = new[] { '<', '>', ':', '"', '|', '?', '*' }; string uriString = CachePath.AppendPath(BaseUriPath).AppendPath(new string(cacheIndexItem.ID.ToCharArray().Select(c => chars.Contains(c) ? '_' : c).ToArray())); Uri uri = new Uri(uriString, UriKind.RelativeOrAbsolute); // Azure has filepath directory length limitations, so enforcing limit of 248 for cache. if (!uri.IsAbsoluteUri) { return(uriString); } #if !AZURE return(uri.LocalPath); #else if (uri.LocalPath.Length <= 247) { return(uri.LocalPath); } // To-Do: find better way to manage Azure cache folder, this is under a spell. // shrink file name to first 227 and last 20, causes cache file name collisions for BestSellers, due to long api key parameter. return(uri.LocalPath.Remove(227) + "~" + uri.LocalPath.Substring(uri.LocalPath.Length - 20)); #endif }
public void OnClick_Uninstall() { string installedFilesPath = CachePath.GetMissionInstalledMetaFilePath(missionData.missionID); // Read installed files from cache string[] installedFiles = File.ReadAllLines(installedFilesPath); // Delete mission files from game folder foreach (string fileName in installedFiles) { UninstallFile(fileName); } // Uninstall SDK if (!string.IsNullOrEmpty(sdkVersion)) { UninstallFile(CachePath.GetSDKFileName(sdkVersion)); UninstallFile(CachePath.DotNetInteropFileName); } // Delete meta data File.Delete(installedFilesPath); // Set buttons m_BtnInstall.gameObject.SetActive(true); m_BtnUninstall.gameObject.SetActive(false); m_BtnDelete.interactable = true; }
protected override void OnApply(PageApplyEventArgs e) { // Clean up the path CachePath = CachePath.Replace("/", "\\"); if (string.IsNullOrEmpty(CachePath)) { e.ApplyBehavior = ApplyKind.Cancel; } else { base.OnApply(e); } }
// Cleaning // Foreach all cache directories private void CacheDirsDeleting(string[] TargetPaths, bool ConfirmClean) { // Foreach all subfolders foreach (string CachePath in TargetPaths) { string ReplacedString = CachePath.Replace(@"\\", @"\"); string[] CuttedString = ReplacedString.Split('\\'); // If dir name length = 36 if (CuttedString[CuttedString.Length - 1].Length == 36) { try { double TempCacheSize = 0L; string[] AllCacheFiles = Directory.GetFiles(CachePath, "*.*", SearchOption.AllDirectories); foreach (string FileName in AllCacheFiles) { File.SetAttributes(FileName, FileAttributes.Normal); FileInfo Info = new FileInfo(FileName); TempCacheSize += Info.Length; } if (ConfirmClean) { Directory.Delete(CachePath, true); } // in a case of error, current cache size will be deleted CacheSize += TempCacheSize; } catch { //MessageBox.Show(ex.ToString()); if (CacheErrorCount != 0) { MessageBox.Show("Не все папки с кэшем особождены от процессов 1С.\n\nПопробуйте:\n• запустить очистку в агрессивном режиме\n• завершить все процессы 1С через диспетчер задач\n• запустить очистку после перезагрузки ПК.\n\nПроизойдёт очситка только незанятых папок", "Очистка не будет полной", MessageBoxButton.OK, MessageBoxImage.Exclamation); } CacheErrorCount++; // Break return; } } } }
public void OnClick_Delete() { // Remove details reference CacheDetails.RemoveMissionData(missionData.missionID); // Delete mission from cache if (Directory.Exists(CachePath.GetMissionDirectory(missionData.missionID))) { Directory.Delete(CachePath.GetMissionDirectory(missionData.missionID), true); } // Set buttons m_BtnDownload.gameObject.SetActive(true); m_BtnDelete.gameObject.SetActive(false); m_BtnInstall.interactable = false; }
/// <summary> /// 基本配置 /// </summary> private pub() { LoadConfig(this); if (WorkPath == null) { WorkPath = fastCSharp.pub.ApplicationPath; } else { WorkPath = WorkPath.pathSuffix().fileNameToLower(); } if (CachePath == null || !directory.Create(CachePath = CachePath.pathSuffix().fileNameToLower())) { CachePath = fastCSharp.pub.ApplicationPath; } }
/// <summary> /// Weeds Index: Remove all files in cache folder and subfolders that do not /// have corresponding <see cref="CacheIndexItem"/> entries in this cache index. /// </summary> public void WeedIndex() { try { lock (syncLock) { // get list of files in cache folder. foreach (var f in GetFilesRecursive(CachePath.AppendPath(BaseUriPath)) .Where(f => !f.Equals(SerializeFile)) .Except(this.Select(i => GetCachePath(i)))) { Device.File.Delete(f); } } } catch (Exception exc) { Device.Log.Error("CacheIndex.WeedIndex() encountered an exception", exc); } }
private void PopulateMissions(MissionFilter missionFilter) { ClearMissions(); List <MissionData> missions; // Show local content even if it is no longer provided by the database if (missionFilter == MissionFilter.Library) { missions = new List <MissionData>(CacheDetails.missions); // Create database lookup table Dictionary <uint, MissionData> lookupTable = new Dictionary <uint, MissionData>(); foreach (MissionData mission in m_Missions) { lookupTable[mission.missionID] = mission; } // Replace local mission data with the database data for (int i = 0; i < missions.Count; ++i) { MissionData dbMissionData; if (!lookupTable.TryGetValue(missions[i].missionID, out dbMissionData)) { continue; } missions[i] = dbMissionData; } } else { // Use the database data missions = new List <MissionData>(m_Missions); } foreach (MissionData mission in missions) { // Determine is mission is a standard mission bool hasDLL = mission.fileNames.FirstOrDefault((filename) => filename.IndexOf(".dll", System.StringComparison.OrdinalIgnoreCase) >= 0) != null; bool hasOPM = mission.fileNames.FirstOrDefault((filename) => filename.IndexOf(".opm", System.StringComparison.OrdinalIgnoreCase) >= 0) != null; bool isStandardMission = !hasDLL && hasOPM; //bool isInstalled = File.Exists(CachePath.GetMissionInstalledMetaFilePath(mission.missionID)); bool isDownloaded = File.Exists(CachePath.GetMissionDetailsFilePath(mission.missionID)); bool isYourContent = AppController.localUser.isLoggedIn && AppController.localUser.userID == mission.authorID; if (missionFilter == MissionFilter.Standard && !isStandardMission) { continue; } if (missionFilter == MissionFilter.Custom && isStandardMission) { continue; } if (missionFilter == MissionFilter.Library && !isDownloaded) { continue; } if (missionFilter == MissionFilter.YourContent && !isYourContent) { continue; } // Create mission item GameObject goItem = Instantiate(m_MissionListItemPrefab); goItem.GetComponent <MissionListItem>().onUpdatedMissionCB += Refresh; goItem.GetComponent <MissionListItem>().Initialize(mission); goItem.GetComponent <MissionListItem>().hasAuthorPermissions = AppController.localUser.isLoggedIn && AppController.localUser.userID == mission.authorID; goItem.GetComponent <MissionListItem>().hasAdminPermissions = AppController.localUser.isLoggedIn && AppController.localUser.isAdmin; goItem.transform.SetParent(m_MissionContainer); } if (missionFilter == MissionFilter.YourContent && AppController.localUser.isLoggedIn) { // Create blank mission item GameObject goItem = Instantiate(m_MissionListItemPrefab); goItem.GetComponent <MissionListItem>().onUpdatedMissionCB += Refresh; goItem.GetComponent <MissionListItem>().canEdit = true; goItem.GetComponent <MissionListItem>().hasAdminPermissions = AppController.localUser.isLoggedIn && AppController.localUser.isAdmin; goItem.transform.SetParent(m_MissionContainer); } OnValueChanged_SearchFilter(); }
public void OnClick_Install() { // Get the cached mission details string json = File.ReadAllText(CachePath.GetMissionDetailsFilePath(missionData.missionID)); MissionData localData = JsonUtility.FromJson <MissionData>(json); string sdkVersion = CachePath.GetSDKVersion(localData); // Do not allow installation if mission files already exist foreach (string fileName in localData.fileNames) { string filePath = Path.Combine(UserPrefs.gameDirectory, fileName); if (File.Exists(filePath)) { InfoDialog.Create("Installation Failed", "The file '" + fileName + "' already exists in your game directory. Please remove it to continue."); return; } } List <string> installedFiles = new List <string>(); // Need to export plugin for standard mission OPM file if (m_IsStandardMission) { string opmFileName = localData.fileNames.FirstOrDefault((string fileName) => Path.GetExtension(fileName).ToLowerInvariant().Contains("opm")); string opmFilePath = Path.Combine(CachePath.GetMissionDirectory(localData.missionID), opmFileName); string pluginFileName = Path.ChangeExtension(opmFileName, ".dll"); string pluginPath = Path.Combine(UserPrefs.gameDirectory, pluginFileName); // Don't allow install if the plugin will overwrite another DLL of the same name if (File.Exists(pluginPath)) { InfoDialog.Create("Install Failed", "There is already a plugin named " + pluginFileName); return; } // Export plugin MissionRoot root = MissionReader.GetMissionData(opmFilePath); PluginExporter.ExportPlugin(pluginPath, root.sdkVersion, root.levelDetails); FileReference.AddReference(pluginFileName); installedFiles.Add(pluginFileName); } // Install mission from cache into game folder foreach (string fileName in localData.fileNames) { string filePath = Path.Combine(CachePath.GetMissionDirectory(localData.missionID), fileName); InstallFile(fileName, filePath); installedFiles.Add(fileName); } // Install SDK if (!string.IsNullOrEmpty(sdkVersion)) { InstallFile(CachePath.GetSDKFileName(sdkVersion), CachePath.GetSDKFilePath(sdkVersion)); InstallFile(CachePath.DotNetInteropFileName, CachePath.GetInteropFilePath(), true); installedFiles.Add(CachePath.GetSDKFileName(sdkVersion)); installedFiles.Add(CachePath.DotNetInteropFileName); } // Write installed files to cache using (FileStream fs = new FileStream(CachePath.GetMissionInstalledMetaFilePath(localData.missionID), FileMode.Create, FileAccess.Write, FileShare.Read)) using (StreamWriter writer = new StreamWriter(fs)) { foreach (string fileName in installedFiles) { writer.WriteLine(fileName); } } // Set buttons m_BtnInstall.gameObject.SetActive(false); m_BtnUninstall.gameObject.SetActive(true); m_BtnDelete.interactable = false; }
private IEnumerator RequestDownloadMission() { ProgressDialog progressDialog = ProgressDialog.Create("Downloading Mission"); foreach (string fileName in missionData.fileNames) { // Perform request string url = WebConfig.webHost + "download/" + missionData.missionID + "/" + fileName; string destPath = Path.Combine(CachePath.GetMissionDirectory(missionData.missionID), fileName); using (UnityWebRequest request = UnityWebRequest.Get(url)) { progressDialog.SetTitle("Downloading " + fileName); progressDialog.SetWebRequest(request); yield return(request.SendWebRequest()); if (!DidDownloadSucceed(request, true)) { progressDialog.Close(); OnClick_Delete(); yield break; } WriteFile(destPath, request.downloadHandler.data); } } // Get SDK path if (!string.IsNullOrEmpty(sdkVersion)) { // Download SDK if it does not exist if (!File.Exists(CachePath.GetSDKFilePath(sdkVersion))) { string url = "https://github.com/TechCor8/OP2DotNetMissionSDK/releases/download/" + sdkVersion + "/" + CachePath.GetSDKFileName(sdkVersion); string destPath = CachePath.GetSDKFilePath(sdkVersion); using (UnityWebRequest request = UnityWebRequest.Get(url)) { progressDialog.SetTitle("Downloading " + CachePath.GetSDKFileName(sdkVersion)); progressDialog.SetWebRequest(request); yield return(request.SendWebRequest()); if (!DidDownloadSucceed(request, true)) { progressDialog.Close(); OnClick_Delete(); yield break; } WriteFile(destPath, request.downloadHandler.data); } } // Download SDK Interop if it does not exist or is from an older SDK if (!File.Exists(CachePath.GetInteropFilePath()) || CachePath.IsNewerVersion(sdkVersion, CacheDetails.interopVersion)) { string url = "https://github.com/TechCor8/OP2DotNetMissionSDK/releases/download/" + sdkVersion + "/" + CachePath.DotNetInteropFileName; string destPath = CachePath.GetInteropFilePath(); using (UnityWebRequest request = UnityWebRequest.Get(url)) { progressDialog.SetTitle("Downloading " + CachePath.DotNetInteropFileName); progressDialog.SetWebRequest(request); yield return(request.SendWebRequest()); if (!DidDownloadSucceed(request, true)) { progressDialog.Close(); OnClick_Delete(); yield break; } WriteFile(destPath, request.downloadHandler.data); } } } progressDialog.Close(); // Mission fully downloaded. // Write mission details string detailsJson = JsonUtility.ToJson(missionData); File.WriteAllText(CachePath.GetMissionDetailsFilePath(missionData.missionID), detailsJson); // Add mission details reference CacheDetails.AddMissionData(missionData); // Set buttons m_BtnDownload.gameObject.SetActive(false); m_BtnDelete.gameObject.SetActive(true); m_BtnInstall.interactable = true; }
public void Initialize(MissionData mission) { missionData = mission; m_InputTitle.text = mission.missionName; m_InputDescription.text = mission.missionDescription; m_txtGitHub.text = mission.gitHubLink; // DLL or OPM string dllName = mission.fileNames.FirstOrDefault((filename) => filename.IndexOf(".dll", System.StringComparison.OrdinalIgnoreCase) >= 0); string opmName = mission.fileNames.FirstOrDefault((filename) => filename.IndexOf(".opm", System.StringComparison.OrdinalIgnoreCase) >= 0); m_IsStandardMission = string.IsNullOrEmpty(dllName) && !string.IsNullOrEmpty(opmName); string mainFileName = m_IsStandardMission ? opmName : dllName; bool isStub = string.IsNullOrEmpty(mainFileName); // Mission type string string missionType = "Unknown"; if (isStub) { missionType = "Stub"; } else if (mainFileName.StartsWith("c")) { missionType = "Colony"; } else if (mainFileName.StartsWith("a")) { missionType = "Auto Demo"; } else if (mainFileName.StartsWith("t")) { missionType = "Tutorial"; } else if (mainFileName.StartsWith("mu")) { missionType = "Multiplayer Land Rush"; } else if (mainFileName.StartsWith("mf")) { missionType = "Multiplayer Space Race"; } else if (mainFileName.StartsWith("mr")) { missionType = "Multiplayer Resource Race"; } else if (mainFileName.StartsWith("mm")) { missionType = "Multiplayer Midas"; } else if (mainFileName.StartsWith("ml")) { missionType = "Multiplayer Last One Standing"; } // Certification image bool isCertified = !string.IsNullOrEmpty(mission.certifyingAdminName) || m_IsStandardMission || isStub; m_Trusted.SetActive(isCertified); m_Untrusted.SetActive(!isCertified); m_BtnCertify.GetComponentInChildren <Text>().text = string.IsNullOrEmpty(mission.certifyingAdminName) ? "Certify" : "Uncertify"; // Certification string string certifiedString = mission.certifyingAdminName; if ((m_IsStandardMission || isStub) && string.IsNullOrEmpty(certifiedString)) { certifiedString = "Not Required"; } else if (!m_IsStandardMission && string.IsNullOrEmpty(certifiedString)) { certifiedString = "<color=yellow>Not Certified</color>"; } // Mission Details string details = m_IsStandardMission ? "Standard Mission" : "Custom Mission"; details += "\nAuthor: " + mission.authorName; details += "\nCertified by: " + certifiedString; details += "\n"; details += "\nType: " + missionType; //details += "\nPlayers: 6" + missionType; //details += "\nUnit Only: True" + missionType; details += "\n"; details += "\nFiles:"; details += "\n" + string.Join(", ", mission.fileNames); m_InputDetails.text = details; // We can upload files if the mission exists. This button won't be visible if the user does not have permission. m_BtnUploadFile.interactable = true; m_BtnDeleteFile.interactable = missionData.fileNames.Count > 0; // Read local mission version if (File.Exists(CachePath.GetMissionDetailsFilePath(missionData.missionID))) { string json = File.ReadAllText(CachePath.GetMissionDetailsFilePath(missionData.missionID)); MissionData localData = JsonUtility.FromJson <MissionData>(json); m_LocalVersion = localData.version; } else { // No local version exists, so use the current version m_LocalVersion = missionData.version; } // Show "New version available" text if (m_LocalVersion < missionData.version) { m_txtDifferentVersion.text = "New version available.\nDelete to redownload."; } else if (m_LocalVersion > missionData.version) { m_txtDifferentVersion.text = "Older version available.\nDelete to redownload."; } else { m_txtDifferentVersion.text = ""; } // Show proper download state bool isCached = File.Exists(CachePath.GetMissionDetailsFilePath(missionData.missionID)); m_BtnDownload.gameObject.SetActive(!isCached); m_BtnDelete.gameObject.SetActive(isCached); m_BtnDownload.interactable = true; // Show proper install state bool isInstalled = File.Exists(CachePath.GetMissionInstalledMetaFilePath(missionData.missionID)); m_BtnInstall.gameObject.SetActive(!isInstalled); m_BtnUninstall.gameObject.SetActive(isInstalled); m_BtnInstall.interactable = isCached; // You can only install if the mission is cached m_BtnUninstall.interactable = true; // If installed, you can always uninstall. This button is only visible in that case. m_BtnDelete.interactable = !isInstalled; }