public async Task <IActionResult> Execute(int id, string remoteInstanceId)
        {
            if (!await _authorizationService.AuthorizeAsync(User, Permissions.Export))
            {
                return(Unauthorized());
            }

            var deploymentPlan = await _session.GetAsync <DeploymentPlan>(id);

            if (deploymentPlan == null)
            {
                return(NotFound());
            }

            var remoteInstance = await _service.GetRemoteInstanceAsync(remoteInstanceId);

            if (remoteInstance == null)
            {
                return(NotFound());
            }

            string archiveFileName;
            var    filename = deploymentPlan.Name.ToSafeName() + ".zip";

            using (var fileBuilder = new TemporaryFileBuilder())
            {
                archiveFileName = Path.Combine(Path.GetTempPath(), filename);

                var deploymentPlanResult = new DeploymentPlanResult(fileBuilder);
                await _deploymentManager.ExecuteDeploymentPlanAsync(deploymentPlan, deploymentPlanResult);

                if (System.IO.File.Exists(archiveFileName))
                {
                    System.IO.File.Delete(archiveFileName);
                }

                ZipFile.CreateFromDirectory(fileBuilder.Folder, archiveFileName);
            }

            HttpResponseMessage response;

            try
            {
                var archiveContainer = new ArchiveContainer();
                archiveContainer.ClientName    = remoteInstance.ClientName;
                archiveContainer.ApiKey        = remoteInstance.ApiKey;
                archiveContainer.ArchiveBase64 = Convert.ToBase64String(System.IO.File.ReadAllBytes(archiveFileName));

                using (var httpClient = new HttpClient())
                {
                    var content = new StringContent(JsonConvert.SerializeObject(archiveContainer));
                    content.Headers.ContentType = new MediaTypeWithQualityHeaderValue("application/json");
                    response = await httpClient.PostAsync(remoteInstance.Url, content);
                }

                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    _notifier.Success(H["Deployment executed successfully."]);
                }
                else
                {
                    _notifier.Error(H["An error occured while sending the deployment to the remote instance: \"{0} ({1})\"", response.ReasonPhrase, (int)response.StatusCode]);
                }
            }
            finally
            {
                System.IO.File.Delete(archiveFileName);
            }

            return(RedirectToAction("Display", "DeploymentPlan", new { area = "OrchardCore.Deployment", id }));
        }
        public static IProgressResult <float> Load(this ArchiveContainer container, DirectoryInfo dir, IStreamDecryptor decryptor)
        {
            try
            {
                List <FileInfo> files = new List <FileInfo>();
                foreach (FileInfo file in dir.GetFiles("*", SearchOption.TopDirectoryOnly))
                {
                    if (file.Name.EndsWith(BundleSetting.ManifestFilename))
                    {
                        files.Add(file);
                        continue;
                    }

                    if (file.Name.EndsWith(dir.Name))
                    {
                        files.Add(file);
                        continue;
                    }
                }

                if (files.Count <= 0)
                {
                    throw new Exception("Please select the root directory of the AssetBundle");
                }

                files.Sort((x, y) => y.LastWriteTime.CompareTo(x.LastWriteTime));

                if (files[0].Name.Equals(BundleSetting.ManifestFilename))
                {
                    BundleManifest manifest = BundleManifest.Parse(File.ReadAllText(files[0].FullName, Encoding.UTF8));
                    return(container.LoadAssetBundle(dir.FullName, decryptor, manifest.GetAll()));
                }
                else if (files[0].Name.Equals(dir.Name))
                {
                    List <string> filenames   = new List <string>();
                    string[]      bundleNames = new string[0];
                    var           bundle      = AssetBundleArchive.Load(files[0].FullName);
                    foreach (var archive in bundle.AssetArchives)
                    {
                        ObjectArchive oa = archive as ObjectArchive;
                        if (oa == null)
                        {
                            continue;
                        }

                        foreach (var summary in oa.GetAllObjectInfo())
                        {
                            if (summary.TypeID == TypeID.AssetBundleManifest)
                            {
                                Objects.AssetBundleManifest assetBundleManifest = summary.GetObject <Objects.AssetBundleManifest>();
                                bundleNames = assetBundleManifest.GetAllAssetBundles();
                            }
                        }
                    }

                    foreach (string bundleName in bundleNames)
                    {
                        var fullName = System.IO.Path.Combine(dir.FullName, bundleName.Replace("/", @"\"));
                        filenames.Add(fullName);
                    }
                    bundle.Dispose();

                    //UnityEngine.AssetBundle bundle = UnityEngine.AssetBundle.LoadFromFile(files[0].FullName);
                    //AssetBundleManifest manifest = bundle.LoadAsset<AssetBundleManifest>("assetbundlemanifest");
                    //bundle.Unload(false);
                    //files = new List<FileInfo>();

                    //foreach (string bundleName in manifest.GetAllAssetBundles())
                    //{
                    //    var fullName = System.IO.Path.Combine(dir.FullName, bundleName.Replace("/", @"\"));
                    //    filenames.Add(fullName);
                    //}

                    return(container.LoadAssetBundle(filenames.ToArray()));
                }
                else
                {
                    List <string> filenames = new List <string>();
                    foreach (FileInfo file in dir.GetFiles("*", SearchOption.AllDirectories))
                    {
                        if (file.FullName.EndsWith(BundleSetting.ManifestFilename) || file.FullName.EndsWith(".manifest"))
                        {
                            continue;
                        }

                        filenames.Add(file.FullName);
                    }
                    return(container.LoadAssetBundle(filenames.ToArray()));
                }
            }
            catch (Exception e)
            {
                return(new ImmutableProgressResult <float>(e, 0f));
            }
        }
 public static IProgressResult <float> Load(this ArchiveContainer container, DirectoryInfo dir)
 {
     return(container.Load(dir, null));
 }
        public static IProgressResult <float> LoadAssetBundle(this ArchiveContainer container, string root, IStreamDecryptor decryptor, params BundleInfo[] bundleInfos)
        {
            return(EditorExecutors.RunAsync(new Action <IProgressPromise <float> >((promise) =>
            {
                try
                {
                    int taskCount = 8;
                    int index = -1;
                    int finishedCount = 0;
                    int count = bundleInfos.Length;
                    CountFinishedEvent countFinishedEvent = new CountFinishedEvent(taskCount);
                    for (int i = 0; i < taskCount; i++)
                    {
                        EditorExecutors.RunAsyncNoReturn(() =>
                        {
                            while (true)
                            {
                                int currIndex = Interlocked.Increment(ref index);
                                if (currIndex > count - 1)
                                {
                                    break;
                                }

                                try
                                {
                                    var bundleInfo = bundleInfos[currIndex];
                                    var path = System.IO.Path.Combine(root, bundleInfo.Filename.Replace("/", @"\"));
                                    if (bundleInfo.IsEncrypted)
                                    {
                                        container.LoadAssetBundle(path, decryptor);
                                    }
                                    else
                                    {
                                        container.LoadAssetBundle(path);
                                    }
                                }
                                catch (Exception e)
                                {
                                    Debug.LogErrorFormat("{0}", e);
                                }
                                finally
                                {
                                    Interlocked.Increment(ref finishedCount);
                                }
                            }
                            countFinishedEvent.Set();
                        });
                    }

                    while (!countFinishedEvent.Wait(100))
                    {
                        promise.UpdateProgress((float)finishedCount / count);
                    }

                    promise.SetResult();
                }
                catch (Exception e)
                {
                    promise.SetException(e);
                }
            })));
        }
 public static IProgressResult <float> LoadAssetBundle(this ArchiveContainer container, string root, params BundleInfo[] bundleInfos)
 {
     return(container.LoadAssetBundle(root, null, bundleInfos));
 }
예제 #6
0
        IEnumerator DoTask(DirectoryInfo dir)
        {
            long total = 0;

            System.Diagnostics.Stopwatch w = new System.Diagnostics.Stopwatch();
            w.Start();

            var container = new ArchiveContainer();

            progressBar.Progress  = 0f;
            progressBar.Enable    = true;
            progressBar.Title     = "Loading";
            progressBar.TipFormat = "Loading AssetBundle, please wait.Progress: {0:0.00} %";
            var loadResult = container.Load(dir, buildVM.GetRijndaelCryptograph());

            while (!loadResult.IsDone)
            {
                if (cancel)
                {
                    loadResult.Cancel();
                }

                progressBar.Progress = loadResult.Progress;

                yield return(null);
            }
            w.Stop();
            total += w.ElapsedMilliseconds;
            Debug.LogFormat("loading time: {0} milliseconds", w.ElapsedMilliseconds);

            if (loadResult.Exception != null)
            {
                Debug.LogErrorFormat("{0}", loadResult.Exception);

                progressBar.Enable = false;
                if (container != null)
                {
                    container.Dispose();
                    container = null;
                }
                yield break;
            }

            w.Reset();
            w.Start();

            var analyzer = new RedundancyAnalyzer(container);

            progressBar.Progress  = 0f;
            progressBar.Enable    = true;
            progressBar.Title     = "Redundancy Analysis";
            progressBar.TipFormat = "Analyzing asset redundancy,please wait.Progress: {0:0.00} %";
            var analyzeResult = analyzer.AnalyzeRedundancy();

            while (!analyzeResult.IsDone)
            {
                if (cancel)
                {
                    analyzeResult.Cancel();
                }

                progressBar.Progress = analyzeResult.Progress;

                yield return(null);
            }

            if (analyzeResult.Exception != null)
            {
                Debug.LogErrorFormat("{0}", analyzeResult.Exception);

                progressBar.Enable = false;
                if (container != null)
                {
                    container.Dispose();
                    container = null;
                }
                yield break;
            }
            w.Stop();
            total += w.ElapsedMilliseconds;
            Debug.LogFormat("analyzing time: {0} milliseconds", w.ElapsedMilliseconds);
            Debug.LogFormat("total time: {0} milliseconds", total);

            RedundancyReport report   = analyzeResult.Result;
            FileInfo         fileInfo = new FileInfo(string.Format(@"{0}\RedundancyReport-{1}.csv", dir.Parent.FullName, dir.Name));
            string           text     = ToCSV(report);

            File.WriteAllText(fileInfo.FullName, text);

            EditorApplication.delayCall += () =>
            {
                try
                {
                    //open the folder
                    EditorUtility.OpenWithDefaultApp(fileInfo.Directory.FullName);
                }
                catch (Exception) { }
            };

            progressBar.Enable = false;
            if (container != null)
            {
                container.Dispose();
                container = null;
            }
            analyzer = null;
        }