IEnumerator DownloadProcess() { //下载/更新所有服务器文件 { AssetFileInfo info = new AssetFileInfo(); info.m_fileName = AppConst.PackageName; info.m_filePath = AppConst.PackageNameWithPostfix; info.m_size = 1000000; //此处无用 info.CallBack = (x) => { ZipUtil.DecompressToDirectory( AppConst.GameSetting.ExternFileRootPath + AppConst.PackageNameWithPostfix, AppConst.GameSetting.ExternFileRootPath, null); }; IEnumerator itor = DownloadManager.Instance.StartDownload(info); while (itor.MoveNext()) { yield return(null); } downloadFinished = true; downloadSuccess = info.IsDownLoadFinish; } }
public bool Publish(int assetId) { if (!IsEnabled()) { return(false); } Asset asset = Asset.Get(assetId); AssetFileInfo afi = new AssetFileInfo(asset); if (!afi.FileExists) { m_Logger.WarnFormat("Unable to publish asset: {0}. Asset preview file does not exist.", assetId); return(false); } string extension = Path.GetExtension(afi.FilePath); string filename = GetHash(assetId) + extension; string newpath = Path.Combine(Folder, filename); if (File.Exists(newpath)) { File.Delete(newpath); } File.Copy(afi.FilePath, newpath); return(true); }
/// <summary> /// 文件下载完成后 /// 把已经下载的文件信息存储到本地文件列表里 /// 并且处理回调(如果有赋值的话) /// </summary> public void FileDownloadFinish(AssetFileInfo info) { //本地文件未读取时,需要读取 if (m_localFiles == null) { ReadLocalFileList(); } AssetFileInfo local = m_localFiles.Find(e => e.m_fileName == info.m_fileName); if (local == null) { local = info; m_localFiles.Add(info); info.IsDownLoadFinish = true; } else { local.m_filePath = info.m_filePath; local.m_fileVersion = info.m_fileVersion; local.m_md5 = info.m_md5; local.m_size = info.m_size; local.m_filePriority = info.m_filePriority; local.IsDownLoadFinish = true; info.IsDownLoadFinish = true; } if (info.CallBack != null) { info.CallBack(info); } }
/// <summary> /// 画出资源目录图标 /// </summary> void DrawAssetGUI(AssetInfo assetInfo, int index) { GUILayout.BeginHorizontal(); GUILayout.Space(index * 20 + 5); _assetsViewHeight += 22; if (assetInfo.FileType == AssetType.Floder) { AssetFloderInfo info = assetInfo as AssetFloderInfo; if (GUILayout.Toggle(assetInfo.IsChecked, "", GUILayout.Width(20)) != assetInfo.IsChecked) { assetInfo.ChangeIsChecked(!assetInfo.IsChecked); } GUILayout.Space(1); GUIContent content = EditorGUIUtility.IconContent("Folder Icon"); content.text = assetInfo.AssetInfoName; info.IsExpanding = EditorGUILayout.Foldout(info.IsExpanding, content, _foldoutStyle); GUILayout.EndHorizontal(); if (info.IsExpanding) { for (int i = 0; i < info.ChildrenFiles.Count; i++) { DrawAssetGUI(info.ChildrenFiles[i], index + 1); } } } else if (assetInfo.FileType == AssetType.File) { AssetFileInfo info = assetInfo as AssetFileInfo; GUI.enabled = string.IsNullOrEmpty(info.BundleName); if (GUILayout.Toggle(assetInfo.IsChecked, "", GUILayout.Width(20)) != assetInfo.IsChecked) { assetInfo.IsChecked = !assetInfo.IsChecked; _isFileCheckChanged = true; } GUILayout.Space(2); GUIContent content = EditorGUIUtility.ObjectContent(null, info.AssetFileType); content.text = assetInfo.AssetInfoName; if (_isCheckedCurABAssetFile && _curAssetFileInfo.GUID == info.GUID) { GUILayout.Label(content, GUILayout.Height(40)); } else { GUILayout.Label(content, GUILayout.Height(20)); } if (!string.IsNullOrEmpty(info.BundleName)) { GUILayout.Label("[" + info.BundleName + "]", _prefabStyle); } GUI.enabled = true; GUILayout.EndHorizontal(); } }
private static void GeneratePackageNode(PackageNodeType packageType, string path, ref Dictionary <string, AssetBundleManager.PackageNode> resultTable, string ignorePackageNameStr) { AssetFileInfo info = GetFileInfo(path); if (null == info) { return; } if (null == resultTable) { resultTable = new Dictionary <string, AssetBundleManager.PackageNode>(); } AssetBundleManager.PackageNode nod = new AssetBundleManager.PackageNode(); string packName = path.Replace("\\", "/"); packName = packName.Replace(ignorePackageNameStr, string.Empty); nod.md5 = info.md5; nod.assetBundlePatch = packName; nod.fileSize = info.fileLengthInMB; if (packageType == PackageNodeType.AssetsBundleFile) { /* * 对已经不用的资源包进行删除操作 */ if (!IsConfigFile(path) && !IsOnAssetBundle(packName) && !path.EndsWith(AssetBundleManager.PrefabUnionVariant)) { if (File.Exists(path)) { File.Delete(path); if (File.Exists(path + ".meta")) { File.Delete(path + ".meta"); } if (File.Exists(path + ".manifest")) { File.Delete(path + ".manifest"); if (File.Exists(path + ".manifest" + ".meta")) { File.Delete(path + ".manifest" + ".meta"); } } } return; } } if (!path.Contains(AssetBundleManager.PrefabVariant)) { resultTable.Add(packName, nod); } }
//----- method ----- public ExternalResourcesAssetFile(AssetFileManager mangager, AssetFileInfo fileInfo, IAssetFileSettingData settingData) : base(mangager, fileInfo, settingData) { var setting = settingData as IAssetFileSettingData; if (setting != null) { resourcesPath = settingData.RowData.ParseCellOptional <string>("FileName", null); } }
//通过加载本地持久化路径下资源目录结构获取所有资源信息 internal static void UF_LoadAssetInfoFromPersistent() { Debugger.UF_Log("Load All AssetInfo From Persistent"); //重置所有路径,避免已删除文件误加载 //foreach (var v in s_DicAssetsMap.Values) { // v.path = string.Empty; //} s_DicAssetsMap.Clear(); s_ListAssetsMap.Clear(); Debugger.UF_Log("GlobalPath.BundlePath:" + GlobalPath.BundlePath); //读取Bundle资源信息 GHelper.UF_ForeachFloder(GlobalPath.BundlePath, (e) => { if (UF_CheckIsAssetFile(e)) { string fName = Path.GetFileName(e); string absPath = e.Substring(e.IndexOf("BundleAssets", System.StringComparison.Ordinal)); var afi = new AssetFileInfo(AssetFileType.Bundle, fName, fName, absPath, e); s_ListAssetsMap.Add(afi); if (!s_DicAssetsMap.ContainsKey(fName)) { s_DicAssetsMap.Add(fName, afi); } else { //替换为持久化路径 //s_DicAssetsMap[fName].path = e; Debugger.UF_Error(string.Format("AssetDataBase Error -> Same Assets File Name: {0}", fName)); } } }); //读取Lua代码资源信息 GHelper.UF_ForeachFloder(GlobalPath.ScriptPath, (e) => { if (UF_CheckIsAssetFile(e)) { string fName = Path.GetFileName(e); if (Path.GetExtension(fName) == ".lua") { string absPath = e.Substring(e.IndexOf("Runtimes", System.StringComparison.Ordinal)); var afi = new AssetFileInfo(AssetFileType.Runtimes, fName, fName, absPath, e); s_ListAssetsMap.Add(afi); if (!s_DicAssetsMap.ContainsKey(fName)) { s_DicAssetsMap.Add(fName, new AssetFileInfo(AssetFileType.Runtimes, fName, fName, absPath, e)); } else { //s_DicAssetsMap[fName].path = e; Debugger.UF_Error(string.Format("AssetDataBase Error -> Same Lua File Name: {0}", fName)); } } } }); }
public double GetDownloadProgress(AssetFileInfo info) { if (taskIds.ContainsKey(info)) { return(httpDownload.GetDownloadProgress(taskIds[info])); } else { return(100); } }
protected void ExtendFindAsset(AssetFileManager mangager, AssetFileInfo fileInfo, IAssetFileSettingData settingData, ref AssetFileBase asset) { if (localAssets != null) { asset = GetInternalResourcesAssetFile(mangager, fileInfo, settingData); } if (asset == null) { asset = GetExternalResourcesAssetFile(mangager, fileInfo, settingData); } }
/// <summary> /// 比对唯一标识,比对本地列表文件中记载的MD5值 /// </summary> bool CheckFileMD5InList( AssetFileInfo localInfo, AssetFileInfo serverInfo) { if (localInfo != null && localInfo.IsDownLoadFinish) { if (localInfo.m_md5 == serverInfo.m_md5) { return(true); } } return(false); }
/// <summary> /// 读取资源路径中的所有文件 /// </summary> public static void ReadAssetsFloder(this Dictionary <string, List <AssetFileInfo> > fileInfos, AssetFloderInfo asset) { if (asset.FileType == AssetType.File || asset.AssetInfoName.Equals("Plugins") || asset.AssetInfoName.Equals("ThirdParty")) { return; } DirectoryInfo directoryInfo = new DirectoryInfo(asset.AssetInfoFullPath); FileSystemInfo[] fileSystemInfo = directoryInfo.GetFileSystemInfos(); foreach (var info in fileSystemInfo) { if (info is DirectoryInfo) { if (IsValidFolder(info.Name)) { AssetFloderInfo floderInfo = new AssetFloderInfo(info.FullName, info.Name, false); //设置父目录 floderInfo.parent = asset; asset.ChildrenFiles.Add(floderInfo); fileInfos.ReadAssetsFloder(floderInfo); } } else { if (!info.Extension.Equals(".meta")) { AssetFileInfo fileInfo = new AssetFileInfo(info.FullName, info.Name, info.Extension); //设置父目录 fileInfo.parent = asset; asset.ChildrenFiles.Add(fileInfo); AssetImporter importer = AssetImporter.GetAtPath(fileInfo.AssetInfoPath); fileInfo.BundleName = importer.assetBundleName; if (!string.IsNullOrEmpty(fileInfo.BundleName)) { if (!fileInfos.ContainsKey(fileInfo.BundleName)) { List <AssetFileInfo> infos = new List <AssetFileInfo>(); infos.Add(fileInfo); fileInfos.Add(fileInfo.BundleName, infos); } else { fileInfos[fileInfo.BundleName].Add(fileInfo); } } } } } }
private void ProcessingAssetInfos(List <AssetReference> assetInfos, AssetsManifest <AssetFileInfo> manifest) { foreach (var assetReference in assetInfos) { if (!_ignoreList.Contains(assetReference.fileNameAndExtension)) { var assetInfo = new AssetFileInfo(); assetInfo.name = ProcessPathFromManifest(assetReference.path).Replace(assetReference.extension, ""); assetInfo.ext = assetReference.extension; manifest._assetsInfos.Add(assetInfo.name, assetInfo); } } }
static bool IsSprite(AssetFileInfo info) { switch (info.Loader) { case "UAlbion.Formats.Parsers.AmorphousSpriteLoader, UAlbion.Formats": case "UAlbion.Formats.Parsers.FixedSizeSpriteLoader, UAlbion.Formats": case "UAlbion.Formats.Parsers.FontSpriteLoader, UAlbion.Formats": case "UAlbion.Formats.Parsers.HeaderBasedSpriteLoader, UAlbion.Formats": case "UAlbion.Formats.Parsers.InterlacedBitmapLoader, UAlbion.Formats": case "UAlbion.Formats.Parsers.SlabLoader, UAlbion.Formats": return(true); default: return(false); } }
bool CheckFileExist(AssetFileInfo localInfo, AssetFileInfo serverInfo) { string fullLocalPath = m_gameSetting.ExternFileRootPath; fullLocalPath += serverInfo.m_filePath; if (File.Exists(fullLocalPath)) { return(true); } else { return(false); } }
public List <(int, int)> GetSubItemRangesForFile(AssetFileInfo info, IDictionary <string, string> extraPaths) { if (info == null) { throw new ArgumentNullException(nameof(info)); } var generalConfig = Resolve <IGeneralConfig>(); var disk = Resolve <IFileSystem>(); var jsonUtil = Resolve <IJsonUtil>(); var resolved = generalConfig.ResolvePath(info.Filename, extraPaths); var container = _containerRegistry.GetContainer(resolved, info.Container, disk); return(container?.GetSubItemRanges(resolved, info, disk, jsonUtil) ?? new List <(int, int)> { (0, 1) });
//----- method ----- public ExternalResourcesSoundAssetFile(AssetFileManager mangager, AssetFileInfo fileInfo, IAssetFileSettingData settingData) : base(mangager, fileInfo, settingData) { var setting = settingData as IAssetFileSoundSettingData; if (setting != null) { resourcesPath = settingData.RowData.ParseCellOptional <string>("FileName", null); if (setting is AdvVoiceSetting) { soundName = settingData.RowData.ParseCellOptional <string>("Voice", null); } else { soundName = settingData.RowData.ParseCellOptional <string>("SoundName", null); } } }
/// <summary> /// 当前AB资源视图 /// </summary> void CurrentABGUI() { _curABViewRect = new Rect(5, 385, 255, 345); _curABScrollRect = new Rect(5, 385, 255, _curABViewHeight); _curABViewScrollPos = GUI.BeginScrollView(_curABViewRect, _curABViewScrollPos, _curABScrollRect); GUI.BeginGroup(_curABScrollRect, _box); _curABViewHeight = 5; if (_isCheckedAssetBundle) { for (int i = 0; i < _bundlesController.AssetBundleInfos[_curABIndex].Assets.Count; i++) { GUIContent content = EditorGUIUtility.ObjectContent(null, _bundlesController.AssetBundleInfos[_curABIndex].Assets[i].AssetFileType); content.text = _bundlesController.AssetBundleInfos[_curABIndex].Assets[i].AssetInfoName; GUI.Label(new Rect(5, _curABViewHeight, 220, 25), content, _prefabStyle); if (GUI.Button(new Rect(5, _curABViewHeight, 210, 25), "", GUIStyle.none)) { _baseFloderInfo.ChangeIsExpending(false); _bundlesController.AssetBundleInfos[_curABIndex].Assets[i].ChangeParentIsExpending(true); _isCheckedCurABAssetFile = true; _curAssetFileInfo = _bundlesController.AssetBundleInfos[_curABIndex].Assets[i]; } if (GUI.Button(new Rect(230, _curABViewHeight + 5, 25, 25), "", _closeButton)) { _bundlesController.AssetBundleInfos[_curABIndex].RemoveAssetFile(_bundlesController.AssetBundleInfos[_curABIndex].Assets[i]); _isCheckedCurABAssetFile = false; } _curABViewHeight += 25; } } if (_curABViewHeight < _curABViewRect.height) { _curABViewHeight = (int)_curABViewRect.height; } GUI.EndGroup(); GUI.EndScrollView(); }
public static AssetFileInfo GetFileInfo(string fileName) { //是文件夹 if (!File.Exists(fileName) || System.IO.Directory.Exists(fileName)) { return(null); } FileInfo info = new FileInfo(fileName); int filesizeInBytes = (int)info.Length; float filesizeInMB = (float)filesizeInBytes / 1024.0f / 1024.0f; string fileMD5 = GetAssetBundleFildMD5(fileName); if (string.IsNullOrEmpty(fileMD5)) { System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); FileStream stream = info.OpenRead(); byte[] retVal = md5.ComputeHash(stream); StringBuilder sb = new StringBuilder(); for (int i = 0; i < retVal.Length; i++) { sb.Append(retVal[i].ToString("x2")); } md5.Clear(); md5 = null; stream.Flush(); stream.Close(); info = null; fileMD5 = sb.ToString(); } AssetFileInfo reslut = new AssetFileInfo(); reslut.fileLengthInBytes = filesizeInBytes; reslut.fileLengthInMB = filesizeInMB; reslut.md5 = fileMD5; return(reslut); }
/// <summary> /// 在列表中检查文件 /// </summary> /// <param name="assetName">需要检查的文件名前缀</param> /// <param name="localInfo">输出本地文件信息</param> /// <param name="serverInfo">输出远端文件信息</param> /// <returns></returns> bool CheckFileExistInList(string assetName, out AssetFileInfo localInfo, out AssetFileInfo serverInfo) { if ((serverInfo = m_serverFiles.Find(e => e.m_fileName == assetName)) == null) { //Debugger.LogError("{0} does not exit in Server", assetName); localInfo = null; return(true); } else { if ((localInfo = m_localFiles.Find(e => e.m_fileName == assetName)) == null) { return(false); } else { return(true); } } }
IEnumerator DownloadProcess() { //下载所有文件列表 { //下载服务器的文件列表 AssetFileInfo info = new AssetFileInfo(); info.m_fileName = AppConst.FileListName; info.m_filePath = AppConst.FileListNameWithPostfix; info.m_size = 100; //此处无用 info.CallBack = (x) => FileManager.Instance.ReadFileList(x); IEnumerator itor = DownloadManager.Instance.StartDownload(info); while (itor.MoveNext()) { yield return(null); } downloadFinished = true; downloadSuccess = info.IsDownLoadFinish; } }
void ConstructAssetFiles(List <AssetFileInfo> assetFiles) { if (assetFiles == null) { assetFiles = new List <AssetFileInfo>(); } AssetFileInfo luaScript = new AssetFileInfo() { m_fileName = "luaTestScript", m_filePath = "Assetbundle/Lua/", m_size = 0, IsDownLoadFinish = false, m_md5 = "92195919502149", m_filePriority = DownLoadPriority.High }; AssetFileInfo adhocUI = new AssetFileInfo() { m_fileName = "connectUI", m_filePath = "Assetbundle/UI/", m_size = 0, IsDownLoadFinish = false, m_md5 = "92195919502149", m_filePriority = DownLoadPriority.High }; AssetFileInfo uiTexture = new AssetFileInfo() { m_fileName = "uiTexture", m_filePath = "Assetbundle/Texture/", m_size = 0, IsDownLoadFinish = false, m_md5 = "92195919502149", m_filePriority = DownLoadPriority.High }; assetFiles.Add(luaScript); assetFiles.Add(adhocUI); assetFiles.Add(uiTexture); }
/// <summary> /// 比对唯一标识,比对本地列表文件中实时计算的md5值 /// </summary> bool CheckFileMD5Real(AssetFileInfo localInfo, AssetFileInfo serverInfo) { if (localInfo != null && localInfo.IsDownLoadFinish) { //这里获取MD5码,不去除'-' string filePath = m_gameSetting + localInfo.m_filePath; FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read); MD5CryptoServiceProvider md5Provider = new MD5CryptoServiceProvider(); byte[] output = md5Provider.ComputeHash(fs); md5Provider.Clear(); fs.Close(); string localFileMd5 = BitConverter.ToString(output); if (localFileMd5 == serverInfo.m_md5) { return(true); } } return(false); }
//服务器文件列表下载完后序列化成List public void ReadFileList(AssetFileInfo info) { FileStream fsServer = new FileStream(m_gameSetting.ExternFileRootPath + info.m_filePath, FileMode.Open, FileAccess.Read); { BinaryFormatter bf = new BinaryFormatter(); m_serverFiles = bf.Deserialize(fsServer) as List <AssetFileInfo>; fsServer.Close(); } //本地文件未读取时,需要读取 if (m_localFiles == null) { try { ReadLocalFileList(); } catch { m_localFiles = new List <AssetFileInfo>(); } } }
static void Main(string[] args) { _MetaStateSettings.Init(); bool isCdnOnlyMode = false; List <string> allArgs = args == null ? new List <string>() : args.ToList(); PlayFab.PlayFabSettings.staticSettings.DeveloperSecretKey = PlayFabSettings.DeveloperSecretKey; PlayFab.PlayFabSettings.staticSettings.TitleId = PlayFabSettings.TitleId; BackOfficeStatusUrl = AzureSettings.StatusUrl; if (allArgs.Contains("-cdnonly")) { isCdnOnlyMode = true; Console.WriteLine("Found -cdnonly switch, will only sync files..."); } if (allArgs.ElementAtOrDefault(0) != null && allArgs.ElementAtOrDefault(0) == "-appversion") { string version = allArgs.ElementAtOrDefault(1); string path = allArgs.ElementAtOrDefault(2); if (!string.IsNullOrEmpty(version) && !string.IsNullOrEmpty(path)) { File.WriteAllText(path, version); } return; } if (allArgs.ElementAtOrDefault(0) != null && allArgs.ElementAtOrDefault(0) == "-status") { bool online = allArgs.ElementAtOrDefault(1) == "online" ? true : false; string seconds = allArgs.ElementAtOrDefault(2); string version = allArgs.ElementAtOrDefault(3); ChangeServerStatus(online, seconds, version); return; } var pathArg = allArgs.Where(y => y.StartsWith("-BaseUnityFolder:")).SingleOrDefault(); if (pathArg != null) { MetaStateSettings._BaseUnityFolder = pathArg.Replace("-BaseUnityFolder:", string.Empty); } var currentManifestResult = PlayFab.PlayFabServerAPI.GetTitleDataAsync(new PlayFab.ServerModels.GetTitleDataRequest() { Keys = new List <string>() { MetaStateSettings._TitleDataKey_CdnManifest } }).GetAwaiter().GetResult(); Console.WriteLine("Fetching CDN content..."); AssetManifest currentManifest = null; if (currentManifestResult.Result.Data.ContainsKey(MetaStateSettings._TitleDataKey_CdnManifest) && !string.IsNullOrEmpty(currentManifestResult.Result.Data[MetaStateSettings._TitleDataKey_CdnManifest])) { currentManifest = JsonConvert.DeserializeObject <AssetManifest>(currentManifestResult.Result.Data[MetaStateSettings._TitleDataKey_CdnManifest]); } else { currentManifest = new AssetManifest(); } Console.WriteLine("Loading local files on " + MetaStateSettings._BaseUnityFolder + MetaStateSettings._DownloadableFolderPath); List <AssetFileInfo> allFiles = LocalFileHandler.GetLocalDownloadableFiles(); var allCdnContent = PlayFabAdminAPI.GetContentListAsync(new PlayFab.AdminModels.GetContentListRequest()).GetAwaiter().GetResult(); int currentDataVersion; AssetFileInfo previousDbFileInfo = null; if (!isCdnOnlyMode) { //string databasePath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + @"\" + MetaStateSettings._DatabaseName; string databasePath = MetaStateSettings._BaseUnityFolder + MetaStateSettings._DatabaseFileName; DataLayer.Instance.Init(databasePath); currentDataVersion = DataLayer.Instance.GetTable <DataVersion>().First().Version; DataLayer.Instance.Connection.Close(); var databaseFileInfo = new AssetFileInfo(databasePath, MetaStateSettings._AssetManagerStartupFolder + Path.GetFileName(databasePath) + MetaStateSettings._AssetManagerVersionString + currentDataVersion.ToString(), true); if (currentManifest.DataVersion != currentDataVersion) { databaseFileInfo.ForceSync = true; } allFiles.Add(databaseFileInfo); } else { currentDataVersion = currentManifest.DataVersion; string dbFilename = MetaStateSettings._AssetManagerStartupFolder + MetaStateSettings._DatabaseName + MetaStateSettings._AssetManagerVersionString + currentDataVersion.ToString(); previousDbFileInfo = currentManifest.Files.Where(y => y.RelativeName == dbFilename).SingleOrDefault(); if (previousDbFileInfo != null) { Console.WriteLine("Will re-import " + previousDbFileInfo.RelativeName + " to manifest..."); } } List <AssetFileInfo> allFilesToBeSynced = new List <AssetFileInfo>(); foreach (var file in allFiles) { var cdnFile = allCdnContent.Result.Contents.Where(y => y.Key == file.RelativeName).SingleOrDefault(); var playFabEntry = currentManifest.GetFile(file.RelativeName); if (playFabEntry == null || cdnFile == null || playFabEntry.Size != file.Size || file.ForceSync) { allFilesToBeSynced.Add(file); Console.WriteLine(file.RelativeName + " must be synced."); } } if (allFilesToBeSynced.Count > 0) { Console.WriteLine(string.Format("{0} file(s) must be synced. Press 1 to sync, 0 to cancel:", allFilesToBeSynced.Count.ToString())); switch (Console.ReadKey().Key) { case ConsoleKey.D1: Console.WriteLine(Environment.NewLine); Console.WriteLine("Starting CDN Sync..."); bool hasError = false; int i = 1; foreach (var file in allFilesToBeSynced) { Console.WriteLine(string.Format("Uploading file {0} of {1}. ({2})", i.ToString(), allFilesToBeSynced.Count.ToString(), file.RelativeName)); if (!UploadFileToCDN(file.RelativeName, file.ToArray())) { hasError = true; Console.WriteLine(string.Format("ERROR UPLOADING {0} of {1}. ({2})", i.ToString(), allFilesToBeSynced.Count.ToString(), file.RelativeName)); break; } i++; } if (!hasError) { Console.WriteLine("All files uploaded..."); Console.WriteLine("Creating and uploading manifest..."); currentManifest.ManifestVersion++; currentManifest.DataVersion = currentDataVersion; currentManifest.Files = new List <AssetFileInfo>(); currentManifest.Files.AddRange(allFiles); if (previousDbFileInfo != null) { currentManifest.Files.Add(previousDbFileInfo); } var updateData = PlayFabServerAPI.SetTitleDataAsync(new PlayFab.ServerModels.SetTitleDataRequest() { Key = MetaStateSettings._TitleDataKey_CdnManifest, Value = currentManifest.ToJson() }).GetAwaiter().GetResult(); if (updateData.Error == null) { Console.WriteLine("Mafinest uploaded."); Console.WriteLine("CDN Sync is COMPLETED."); } else { Console.WriteLine("Mafinest uploaded failed."); } } break; } } else { Console.WriteLine("No files to be synced!"); } //Console.WriteLine("Bruh, press any key to exit program."); //Console.ReadKey(); }
public override void ProcessRequest() { // Get querystring values int assetId = GetIdFromFilename(); int assetImageSizeId = WebUtils.GetIntRequestParam("assetImageSizeId", 0); DownloadFormat downloadFormat = GeneralUtils.ParseEnum(WebUtils.GetRequestParam("AssetImageFormat"), DownloadFormat.Original); bool logDownload = (WebUtils.GetIntRequestParam("logDownload", 1) == 1); bool original = (WebUtils.GetIntRequestParam("original", 0) == 1); // Downloads should ALWAYS be logged from normal users, regardless of the querystring if (SessionInfo.Current.User.UserRole == UserRole.Normal) { logDownload = true; } // Ensure asset id is specified if (assetId == 0) { throw new HttpException(500, "Invalid asset id"); } // Get asset Asset asset = Asset.Get(assetId); // Make sure asset is valid if (asset.IsNull) { Context.Response.Redirect("~/Errors/AssetMissing.htm"); return; } // Check if user can download asset bool isAuthorised = EntitySecurityManager.CanUserDownloadAsset(SessionInfo.Current.User, asset); if (!isAuthorised) { throw new SecurityException("Access denied"); } // Get the asset file info AssetFileInfo info = new AssetFileInfo(asset); // Ensure file exists if (!info.FileExists) { Context.Response.Redirect("~/Errors/AssetFileMissing.htm"); return; } // Asset file path string path = info.FilePath; // Update the audit history if (logDownload) { AuditLogManager.LogAssetAction(assetId, SessionInfo.Current.User, AuditAssetAction.DownloadedAssetFile); AuditLogManager.LogUserAction(SessionInfo.Current.User, AuditUserAction.DownloadAsset, string.Format("Downloaded asset with AssetId: {0}", assetId)); } DownloadAsset(asset, path, original, downloadFormat, assetImageSizeId); }
public SelectedAssetChangedArgs(AssetFileInfo selectedAssetFile, AssetInfo selectedObject) { SelectedAssetFile = selectedAssetFile; SelectedObject = selectedObject; }
public void AddToDownloadList(AssetFileInfo info) { m_downLoadList.Enqueue(info); }
/// <summary> /// 立即下载,异步下载,然后保存至本地,存储位置为./AssetBundles/ /// </summary> public IEnumerator StartDownload(AssetFileInfo info) { if (info == null || !m_gameSetting.DownloadEnabled) { yield break; } //正在下载中,则把优先级调高 if (taskIds.ContainsKey(info)) { int count = 100; //正在下载该文件,则最多等待100帧 while (count > 0 && taskIds.ContainsKey(info)) { count--; yield return(null); } yield break; } AssetFileInfo tmp = m_finishList.Find(e => e.m_fileName == info.m_fileName); //如果从没下载过 if (tmp == null) { float startTimer = Time.realtimeSinceStartup; string remotePath = FileManager.Instance.GetRemotePath(info.m_filePath); Debug.Log(string.Format("准备下载 : {0}", remotePath)); string localPath = m_gameSetting.ExternFileRootPath + info.m_filePath; Stopwatch sw = new Stopwatch(); sw.Start(); int failCount = 0; long taskId = -1; while (failCount < 10) { taskId = httpDownload.StartDownLoad(remotePath, localPath, (int)info.m_size, true, true); if (taskId < 0) { Debug.LogError(string.Format("预下载错误 : {0} 尝试 {1}", remotePath, failCount)); failCount++; continue; } else { break; } } if (failCount >= 10) { Debug.LogError(string.Format("下载错误 : {0}", remotePath)); yield break; } taskIds.Add(info, taskId); double curDownloadProgress = httpDownload.GetDownloadProgress(taskId); while (curDownloadProgress < 100) { if (curDownloadProgress == -1) { break; } yield return(new WaitForSeconds(0.2f)); curDownloadProgress = curDownloadProgress = httpDownload.GetDownloadProgress(taskId); } sw.Stop(); if (curDownloadProgress == -1) { Debug.LogError(string.Format("下载失败 : {0} 耗时 :{1}ms", remotePath, sw.ElapsedMilliseconds)); taskIds.Remove(info); } else { Debug.Log(string.Format("下载完成 : {0} 耗时 :{1}ms", remotePath, sw.ElapsedMilliseconds)); taskIds.Remove(info); m_finishList.Add(info); FileManager.Instance.FileDownloadFinish(info); } } }
protected void BulkRegeneratePreviewsButton_Click(object sender, EventArgs e) { List <int> selectedIdList = GetSelectedAssetIdList(); if (selectedIdList.Count == 0) { MessageLabel1.SetErrorMessage("No assets selected"); return; } // Get the assets that we need to reprocess AssetFinder finder = new AssetFinder(); finder.AssetIdList.Add(0); finder.AssetIdList.AddRange(selectedIdList); List <Asset> selectedAssets = Asset.FindMany(finder); if (selectedAssets.Count == 0) { MessageLabel1.SetErrorMessage("Selected assets no longer exist"); return; } // Initialise error list for problems that might occur as assets are processed ErrorList errors = new ErrorList(); // Counters int successCount = 0; int failCount = 0; foreach (Asset asset in selectedAssets) { m_Logger.DebugFormat("Re-processing asset ID = {0}", asset.AssetId); AssetFileInfo afi = new AssetFileInfo(asset); if (!afi.FileExists) { errors.Add(string.Format("Asset file for asset with ID {0} is missing or unavailable", asset.AssetId)); m_Logger.Warn("Asset file does not exist. Cannot reprocess"); continue; } try { if (APSGateway.Instance.ProcessFile(asset, false, FileOutputs.All)) { asset.IsProcessed = false; Asset.Update(asset); successCount++; m_Logger.DebugFormat("Asset {0} resubmitted for processing successfully", asset.AssetId); } else { failCount++; errors.Add(string.Format("#{0} : An error occured when submitting the asset to the processing service", asset.AssetId)); m_Logger.DebugFormat("Asset {0} not submitted to the processing service. An error occurred.", asset.AssetId); } } catch (InvalidAssetException iaex) { failCount++; m_Logger.Warn(string.Format("An error occured when processing the asset: {0}", asset.AssetId), iaex); errors.Add(string.Format("#{0}: Error submitting asset for processing: {1}", asset.AssetId, iaex.Message)); } catch (Exception ex) { failCount++; m_Logger.Warn(string.Format("An unknown error occured when processing the asset: {0}", asset.AssetId), ex); errors.Add(string.Format("#{0}: Error submitting asset for processing", asset.AssetId)); ExceptionHandler.HandleException(ex, "Error bulk regenerating previews"); } } m_Logger.DebugFormat("Asset processing result: {0} success, {1} failures, Errors: {2}", successCount, failCount, errors); if (successCount == 0) { MessageLabel1.SetErrorMessage("The selected assets could not be submitted for processing", errors); return; } if (failCount == 0) { MessageLabel1.SetSuccessMessage("All selected assets were resubmitted for reprocessing successfully"); return; } if (successCount > 0 && failCount > 0) { MessageLabel1.SetErrorMessage("Some of the selected assets could not be resubmitted for processing", errors); return; } }
protected void NextButton_Click(object sender, EventArgs e) { ErrorList errors = new ErrorList(); if (StringUtils.IsBlank(FtpHostTextBox.Text)) { errors.Add("Ftp host is required"); } if (NumericUtils.ParseInt32(FtpPortTextBox.Text, 0) == 0) { errors.Add("Ftp host port must be a number"); } if (StringUtils.IsBlank(FtpUsernameTextBox.Text)) { errors.Add("Username is required"); } if (errors.Count > 0) { FeedbackLabel1.SetErrorMessage("Please check the following and try again:", errors); return; } // List of files to upload List <FtpFile> assetFilePaths = new List <FtpFile>(); // Get all of the order items in the current order foreach (OrderItem orderItem in SelectedOrder.OrderItemList) { // Get the order item id int orderItemId = orderItem.OrderItemId.GetValueOrDefault(); // Check if the order item can be downloaded and is in the list of selected order items if (ViewOrders.CanDownload(orderItem) && SelectedOrderItems.Contains(orderItemId)) { // Get the asset Asset asset = orderItem.Asset; // Get the selected order item SelectedOrderItem soi = SelectedOrderItems.Get(orderItemId); // Initialise path and filename to FTP string path, filename; // Check if zip asset files is enabled and we're not doing any kind of transcoding. // If so, we want to FTP the zipped asset file instead, so set the path and filename accordingly. // However, if the zip file doesn't exist, then we want to FTP the original asset instead. if (AssetFileManager.ZipAssetFiles && soi.AssetImageSizeId == 0) { // First get the path to the zipped asset file ZippedAssetFileInfo zippedFileInfo = new ZippedAssetFileInfo(asset); if (zippedFileInfo.FileExists) { // Ensure that a path was returned, and if so, set the filename accordingly path = zippedFileInfo.FilePath; filename = Path.GetFileNameWithoutExtension(asset.Filename) + ".zip"; } else { // Otherwise, the zip file doesn't exist, so get the path to the original // asset file, and set the filename to the asset filename AssetFileInfo info = new AssetFileInfo(asset); path = info.FilePath; filename = asset.Filename; } } else { // Get the file path to the asset AssetFileInfo info = new AssetFileInfo(asset); path = info.FilePath; // For images, get the filepath to the resized image if (AssetTypeChecker.IsImage(asset.FileExtension)) { path = AssetImageManager.GetResizedAssetImage(asset, soi.AssetImageSizeId, soi.DownloadFormat, true); } // Construct the asset filename filename = Path.GetFileNameWithoutExtension(asset.Filename) + Path.GetExtension(path); } // Add the file path to the list FtpFile file = new FtpFile(path, filename); assetFilePaths.Add(file); } } try { // Instantiate FTP downloader FtpDownloader ftpDownloader = new FtpDownloader { BackgroundTransfer = true, Host = FtpHostTextBox.Text.Trim(), Port = NumericUtils.ParseInt32(FtpPortTextBox.Text, 0), PassiveMode = FtpPassiveModeCheckBox.Checked, Username = FtpUsernameTextBox.Text.Trim(), Password = FtpPasswordTextBox.Text.Trim(), RemoteFolder = FtpRemoteFolderTextBox.Text.Trim(), User = CurrentUser }; // Specify files to send to FTP server foreach (FtpFile file in assetFilePaths) { ftpDownloader.Files.Add(file); } // Wire up events ftpDownloader.UploadComplete += new FtpDownloadCompleteEventHandler(NotifyEngine.FtpDownloadComplete); // Go do it! ftpDownloader.Go(); // Log the assets as downloaded foreach (SelectedOrderItem soi in SelectedOrderItems) { OrderItem orderItem = OrderItem.Get(soi.OrderItemId); Asset asset = orderItem.Asset; AuditLogManager.LogAssetAction(asset, CurrentUser, AuditAssetAction.DownloadedAssetFile); AuditLogManager.LogUserAction(CurrentUser, AuditUserAction.DownloadAsset, string.Format("Downloaded AssetId: {0} as part of FTP download to: {1} for OrderId: {2}", asset.AssetId, ftpDownloader.Host, orderItem.OrderId)); } // Lets cookie the settings as well, so we can pre-populate // the form when the user returns to download more assets CookieManager.SetValue("FtpHost", ftpDownloader.Host); CookieManager.SetValue("FtpPort", ftpDownloader.Port); CookieManager.SetValue("FtpPassiveMode", FtpPassiveModeCheckBox.Checked ? "1" : "0"); CookieManager.SetValue("FtpUsername", ftpDownloader.Username); // Update UI FormPanel.Visible = false; SuccessPanel.Visible = true; } catch (FtpDownloadException fdex) { // Remove the error code from the start of the error message string message = Regex.Replace(fdex.Message, @"(\d+\s-\s)", string.Empty); // Display the error to the user FeedbackLabel1.SetErrorMessage("Error downloading assets", message); // Log the error m_Logger.Warn(string.Format("Error downloading files to FTP. User: {0}, Host: {1}. Error: {2}", CurrentUser.FullName, FtpHostTextBox.Text, message), fdex); } }