Example #1
0
        public async Task ShouldUpdatePath()
        {
            var userId = await RunAsDefaultUserAsync();

            var path = await SendAsync(new CreatePath
            {
                Title       = "New Path",
                Key         = "some-path",
                Description = "New Path Description"
            });

            var command = new UpdatePath
            {
                Id          = path.Id,
                Key         = "some-path",
                Title       = "Updated Path Title",
                Description = "New Path Description"
            };

            await SendAsync(command);

            var updatedPath = await FindAsync <Path>(path.Id);

            updatedPath.Title.Should().Be(command.Title);
            updatedPath.LastModifiedBy.Should().NotBeNull();
            updatedPath.LastModifiedBy.Should().Be(userId);
            updatedPath.LastModified.Should().NotBeNull();
            updatedPath.LastModified.Should().BeCloseTo(DateTime.Now, TimeSpan.FromMilliseconds(1000));
        }
Example #2
0
    void Update()
    {
        if (_path == UpdatePath.Stopped)
        {
            return;
        }

        _elapse += Time.deltaTime;

        if (_elapse > 2)
        {
            _elapse = 0;
            _pathIndex++;
        }

        if (_pathIndex >= _thisPath.Count)
        {
            _path = UpdatePath.Stopped;
            return;
        }

        if (_pathIndex > 0)
        {
            _agent.transform.position = Vector3.Lerp(_allGameObject[_thisPath[_pathIndex - 1]].transform.position, _allGameObject[_thisPath[_pathIndex]].transform.position, _elapse);
        }
        else
        {
            _agent.transform.position = _allGameObject[_thisPath[_pathIndex]].transform.position;
        }
    }
Example #3
0
File: Upgrade.cs Project: pjy612/X
        /// <summary>开始更新</summary>
        /// <param name="url">下载源</param>
        /// <param name="fileName">文件名</param>
        public void Download(String url, String fileName)
        {
            // 如果更新包不存在,则下载
            var file = UpdatePath.CombinePath(fileName).GetBasePath();

            if (!CacheFile && File.Exists(file))
            {
                File.Delete(file);
            }
            ;
            if (!File.Exists(file))
            {
                WriteLog("准备下载 {0} 到 {1}", url, file);

                var sw = Stopwatch.StartNew();

                var web = CreateClient();
                Task.Run(() => web.DownloadFileAsync(url, file)).Wait();

                sw.Stop();
                WriteLog("下载完成!大小{0:n0}字节,耗时{1:n0}ms", file.AsFile().Length, sw.ElapsedMilliseconds);
            }

            SourceFile = file;
        }
Example #4
0
        /// <summary>开始更新</summary>
        public void Download()
        {
            var link = Link;

            if (link == null)
            {
                throw new Exception("没有可用新版本!");
            }
            if (String.IsNullOrEmpty(link.Url))
            {
                throw new Exception("升级包地址无效!");
            }

            // 如果更新包不存在,则下载
            var file = UpdatePath.CombinePath(link.FullName).GetBasePath();

            if (!File.Exists(file))
            {
                WriteLog("准备下载 {0} 到 {1}", link.Url, file);

                var sw = Stopwatch.StartNew();

                var web = CreateClient();
                TaskEx.Run(() => web.DownloadFileAsync(link.Url, file)).Wait();

                sw.Stop();
                WriteLog("下载完成!大小{0:n0}字节,耗时{1:n0}ms", file.AsFile().Length, sw.ElapsedMilliseconds);
            }

            SourceFile = file;
        }
        public string GetPathString(UpdatePath path)
        {
            var result = "";

            for (int i = 0; i < path.Path.Count; i++)
            {
                var item = path.Path[i];
                if (i == 0)
                {
                    if (path.FullZipStart)
                    {
                        result += "=> " + GameFacade.Strings.GetString("f101", path.MissingInfo ? "25" : "24")
                                  + item.version_name + ((path.Path.Count == 1) ? "" : "       \n");
                    }
                    else
                    {
                        result += GameFacade.Strings.GetString("f101", "26") + GlobalSettings.Default.ClientVersion + "       \n";
                    }
                }
                if (i != 0 || !path.FullZipStart)
                {
                    result += "       -> ";
                    result += GameFacade.Strings.GetString("f101", "23");
                    result += item.version_name + "\n";
                }
            }
            return(result);
        }
        public DownloadItem[] BuildFiles(UpdatePath path)
        {
            var result = new List <DownloadItem>();

            for (int i = 0; i < path.Path.Count; i++)
            {
                var item = path.Path[i];
                result.Add(new DownloadItem()
                {
                    Url      = (i == 0 && path.FullZipStart) ? item.full_zip : item.incremental_zip,
                    DestPath = $"PatchFiles/path{i}.zip",
                    Name     = item.version_name
                });
                if (item.manifest_url != null)
                {
                    result.Add(new DownloadItem()
                    {
                        Url      = item.manifest_url,
                        DestPath = $"PatchFiles/path{i}.json",
                        Name     = item.version_name + GameFacade.Strings.GetString("f101", "29")
                    });
                }
            }

            return(result.ToArray());
        }
Example #7
0
        public async Task ShouldRequireUniqueTitle()
        {
            var path = await SendAsync(new CreatePath
            {
                Title       = "New Path",
                Key         = "some-path",
                Description = "New Path Description"
            });

            await SendAsync(new CreatePath
            {
                Title       = "Other New Path",
                Key         = "some-path-other",
                Description = "New Other Path Description"
            });

            var command = new UpdatePath
            {
                Id          = path.Id,
                Title       = "Other New Path",
                Description = "New Path Description"
            };

            FluentActions.Invoking(() =>
                                   SendAsync(command)).Should().ThrowAsync <ValidationException>()
            .Where(ex => ex.Errors.ContainsKey("Title"))
            .Result.And.Errors["Title"].Should().Contain("The specified path already exists.");
        }
Example #8
0
        /// <summary>开始更新</summary>
        public void Download()
        {
            if (Links.Length == 0)
            {
                throw new Exception("没有可用新版本!");
            }

            var link = Links[0];

            if (String.IsNullOrEmpty(link.Url))
            {
                throw new Exception("升级包地址无效!");
            }

            // 如果更新包不存在,则下载
            var file = UpdatePath.CombinePath(link.Name).GetFullPath();

            if (!File.Exists(file))
            {
                WriteLog("准备下载 {0} 到 {1}", link.Url, file);

                var sw = Stopwatch.StartNew();

                var web = CreateClient();
                web.DownloadFileAsync(link.Url, file).Wait();

                sw.Stop();
                WriteLog("下载完成!大小{0:n0}字节,耗时{1:n0}ms", file.AsFile().Length, sw.ElapsedMilliseconds);
            }

            // 设置更新标记
            file += ".update";
            WriteLog("设置更新标记 {0}", file);
            File.CreateText(file).Close();
        }
Example #9
0
        public async Task <ActionResult <Path> > Update(int pathId,
                                                        [FromBody] UpdatePath command)
        {
            if (pathId != command.Id)
            {
                return(BadRequest());
            }

            return(Ok(await Mediator.Send(command)));
        }
Example #10
0
        public async Task Update_ReturnsBadRequest_WhenRequestedIdDoesNotMatchCommandId()
        {
            var updateCommand = new UpdatePath {
                Id = 2, Title = "Update title", Description = "Update Description"
            };
            var controller = new PathsController(moqMediator.Object);

            var result = await controller.Update(1, updateCommand);

            Assert.IsInstanceOf(typeof(BadRequestResult), result.Result);
        }
Example #11
0
        public void ShouldRequireValidPathId()
        {
            var command = new UpdatePath
            {
                Id          = 99,
                Title       = "New Title",
                Key         = "some-path",
                Description = "New Description"
            };

            FluentActions.Invoking(() =>
                                   SendAsync(command)).Should().ThrowAsync <NotFoundException>();
        }
        public void AcceptUpdate(UpdatePath path)
        {
            UIScreen.RemoveDialog(_UpdaterAlert);

            try
            {
                if (path.FullZipStart)
                {
                    System.IO.File.WriteAllText("PatchFiles/clean.txt", "CLEAN");
                }
                else
                {
                    System.IO.File.Delete("PatchFiles/clean.txt");
                }
            } catch
            {
            }

            var downloader = new UIWebDownloaderDialog(GameFacade.Strings.GetString("f101", "1"), BuildFiles(path));

            downloader.OnComplete += (bool success) => {
                UIScreen.RemoveDialog(downloader);
                if (success)
                {
                    _UpdaterAlert = UIScreen.GlobalShowAlert(new UIAlertOptions
                    {
                        Title   = GameFacade.Strings.GetString("f101", "3"),
                        Message = GameFacade.Strings.GetString("f101", "13"),
                        Buttons = UIAlertButton.Ok(y =>
                        {
                            UIScreen.RemoveDialog(_UpdaterAlert);
                            RestartGamePatch();
                        })
                    }, true);
                }
                else
                {
                    UIScreen.GlobalShowAlert(new UIAlertOptions
                    {
                        Title   = GameFacade.Strings.GetString("f101", "30"),
                        Message = GameFacade.Strings.GetString("f101", "28"),
                        Buttons = UIAlertButton.Ok(y =>
                        {
                            Continue(false);
                        })
                    }, true);
                }
            };
            GameThread.NextUpdate(y => UIScreen.GlobalShowDialog(downloader, true));
        }
Example #13
0
        public async Task Update_ReturnsUpdatedPath_WhenRequestedIdMatchesCommandId()
        {
            var updateCommand = new UpdatePath {
                Id = 1, Title = "Update title", Description = "Update Description"
            };
            var controller = new PathsController(moqMediator.Object);

            var result = await controller.Update(1, updateCommand);

            var content = GetObjectResultContent <Path>(result.Result);

            Assert.IsInstanceOf(typeof(OkObjectResult), result.Result);
            Assert.IsNotNull(content);
            Assert.AreEqual(1, content.Id);
        }
        public void DoUpdate(string versionName, string url)
        {
            var str = GlobalSettings.Default.ClientVersion;

            var    split     = str.LastIndexOf('-');
            int    verNum    = 0;
            string curBranch = str;

            if (split != -1)
            {
                int.TryParse(str.Substring(split + 1), out verNum);
                curBranch = str.Substring(0, split);
            }

            _UpdaterAlert = UIScreen.GlobalShowAlert(new UIAlertOptions()
            {
                Title   = "",
                Message = GameFacade.Strings.GetString("f101", "27"),
                Buttons = new UIAlertButton[0]
            }, true);

            Api.GetUpdateList((updates) =>
            {
                UIScreen.RemoveDialog(_UpdaterAlert);
                GameThread.InUpdate(() =>
                {
                    UpdatePath path = null;
                    if (updates != null)
                    {
                        path = UpdatePath.FindPath(updates.ToList(), str, versionName);
                    }
                    if (path == null)
                    {
                        path = new UpdatePath(new List <ApiUpdate>()
                        {
                            new ApiUpdate()
                            {
                                version_name = versionName, full_zip = url
                            }
                        }, true);
                        path.MissingInfo = true;
                    }
                    ShowUpdateDialog(path);
                });
            });
        }
        public void ShowUpdateDialog(UpdatePath path)
        {
            var targVer = path.Path.Last();

            _UpdaterAlert = UIScreen.GlobalShowAlert(new UIAlertOptions
            {
                Title   = GameFacade.Strings.GetString("f101", "21"),
                Message = GameFacade.Strings.GetString("f101", "22", new string[] { targVer.version_name, GlobalSettings.Default.ClientVersion, GetPathString(path) }),
                Width   = 500,
                Buttons = UIAlertButton.YesNo(x =>
                {
                    AcceptUpdate(path);
                },
                                              x =>
                {
                    RejectUpdate();
                })
            }, true);
        }
Example #16
0
        public async Task ShouldDisallowLongTitle()
        {
            var path = await SendAsync(new CreatePath
            {
                Title       = "New Path",
                Key         = "some-path",
                Description = "New Path Description"
            });

            var command = new UpdatePath
            {
                Id          = path.Id,
                Title       = "This path title is too long and exceeds one hundred characters allowed for path titles by UpdatePathCommandValidator",
                Description = "Learn how to design modern web applications using ASP.NET"
            };

            FluentActions.Invoking(() =>
                                   SendAsync(command)).Should().ThrowAsync <ValidationException>()
            .Where(ex => ex.Errors.ContainsKey("Title"))
            .Result.And.Errors["Title"].Should().Contain("Title must not exceed 100 characters.");
        }
Example #17
0
        /// <summary>开始更新</summary>
        public virtual async Task <Boolean> Download()
        {
            var url = Url;

            if (url.IsNullOrEmpty())
            {
                return(false);
            }

            var fileName = Path.GetFileName(url);

            // 即使更新包存在,也要下载
            var file = UpdatePath.CombinePath(fileName).GetBasePath();

            if (File.Exists(file))
            {
                File.Delete(file);
            }
            ;

            WriteLog("准备下载 {0}", url);

            var sw = Stopwatch.StartNew();

            var web = CreateClient();

            //await web.DownloadFileAsync(url, file);
            file = await DownloadFileAsync(web, url, file);

            sw.Stop();
            WriteLog("下载完成!{2} 大小{0:n0}字节,耗时{1:n0}ms", file.AsFile().Length, sw.ElapsedMilliseconds, file);

            SourceFile = file;

            return(true);
        }
Example #18
0
 public bool equals(UpdatePath path)
 {
     return(source == path.source && destination == path.destination);
 }
 public SerializedUpdatePath(UpdatePath block)
 {
     source      = new SerializedBlockPosition(block.source.position);
     destination = new SerializedBlockPosition(block.destination.position);
 }
Example #20
0
 public override string ToString()
 {
     return($"{(IsDelete ? "DELETE" : IsUpdate ? "UPDATE" : "READ")} {UpdatePath.ToHexString()}{(IsRead ? "" : $" -> {UpdateValue}")}");
Example #21
0
 public Span <byte> GetRemainingUpdatePath()
 {
     return(UpdatePath.Slice(CurrentIndex, RemainingUpdatePathLength));
 }
Example #22
0
        void IUtilityCommand.Run(Utility utility, string[] args)
        {
            // HACK: The engine code assumes that Game.modData is set.
            var modData = Game.ModData = utility.ModData;

            // HACK: We know that maps can only be oramap or folders, which are ReadWrite
            var package = new Folder(Platform.EngineDir).OpenPackage(args[1], modData.ModFiles) as IReadWritePackage;

            if (package == null)
            {
                throw new FileNotFoundException(args[1]);
            }

            IEnumerable <UpdateRule> rules = null;

            if (args.Length > 2)
            {
                rules = UpdatePath.FromSource(modData.ObjectCreator, args[2]);
            }

            if (rules == null)
            {
                Console.WriteLine("--update-map MAP SOURCE [--detailed] [--apply]");

                if (args.Length > 2)
                {
                    Console.WriteLine("Unknown source: " + args[2]);
                }

                Console.WriteLine("Valid sources are:");

                var ruleGroups = new Dictionary <string, List <string> >();

                // Print known tags
                Console.WriteLine("   Update Paths:");
                foreach (var p in UpdatePath.KnownPaths)
                {
                    Console.WriteLine("      " + p);
                    ruleGroups[p] = UpdatePath.FromSource(modData.ObjectCreator, p, false)
                                    .Select(r => r.GetType().Name)
                                    .Where(r => !ruleGroups.Values.Any(g => g.Contains(r)))
                                    .ToList();
                }

                // Print known rules
                Console.WriteLine("   Individual Rules:");
                foreach (var kv in ruleGroups)
                {
                    if (!kv.Value.Any())
                    {
                        continue;
                    }

                    Console.WriteLine("      " + kv.Key + ":");
                    foreach (var r in kv.Value)
                    {
                        Console.WriteLine("         " + r);
                    }
                }

                var other = UpdatePath.KnownRules(modData.ObjectCreator)
                            .Where(r => !ruleGroups.Values.Any(g => g.Contains(r)));

                if (other.Any())
                {
                    Console.WriteLine("      Other:");
                    foreach (var r in other)
                    {
                        Console.WriteLine("         " + r);
                    }
                }

                return;
            }

            if (args.Contains("--apply"))
            {
                ApplyRules(modData, package, rules);
            }
            else
            {
                UpdateModCommand.PrintSummary(rules, args.Contains("--detailed"));
            }
        }
Example #23
0
        void IUtilityCommand.Run(Utility utility, string[] args)
        {
            // HACK: The engine code assumes that Game.modData is set.
            var modData = Game.ModData = utility.ModData;

            IEnumerable <UpdateRule> rules = null;

            if (args.Length > 1)
            {
                rules = UpdatePath.FromSource(modData.ObjectCreator, args[1]);
            }

            if (rules == null)
            {
                Console.WriteLine("--update-mod SOURCE [--detailed] [--apply] [--skip-maps]");

                if (args.Length > 1)
                {
                    Console.WriteLine("Unknown source: " + args[1]);
                }

                Console.WriteLine("Valid sources are:");

                var ruleGroups = new Dictionary <string, List <string> >();

                // Print known tags
                Console.WriteLine("   Update Paths:");
                foreach (var p in UpdatePath.KnownPaths)
                {
                    Console.WriteLine("      " + p);
                    ruleGroups[p] = UpdatePath.FromSource(modData.ObjectCreator, p, false)
                                    .Select(r => r.GetType().Name)
                                    .Where(r => !ruleGroups.Values.Any(g => g.Contains(r)))
                                    .ToList();
                }

                // Print known rules
                Console.WriteLine("   Individual Rules:");
                foreach (var kv in ruleGroups)
                {
                    if (!kv.Value.Any())
                    {
                        continue;
                    }

                    Console.WriteLine("      " + kv.Key + ":");
                    foreach (var r in kv.Value)
                    {
                        Console.WriteLine("         " + r);
                    }
                }

                var other = UpdatePath.KnownRules(modData.ObjectCreator)
                            .Where(r => !ruleGroups.Values.Any(g => g.Contains(r)));

                if (other.Any())
                {
                    Console.WriteLine("      Other:");
                    foreach (var r in other)
                    {
                        Console.WriteLine("         " + r);
                    }
                }

                return;
            }

            if (args.Contains("--apply"))
            {
                if (!args.Contains("--yes"))
                {
                    Console.WriteLine("WARNING: This command will automatically rewrite your mod rules.");
                    Console.WriteLine();
                    Console.WriteLine("We strongly recommend that you have a backup of your mod rules, and ");
                    Console.WriteLine("for best results, to use a Git client to review the line-by-line ");
                    Console.WriteLine("changes and discard any unwanted side effects.");
                    Console.WriteLine();
                    Console.Write("Press y to continue, or any other key to cancel: ");

                    var confirmKey = Console.ReadKey().KeyChar;
                    Console.WriteLine();

                    if (confirmKey != 'y')
                    {
                        Console.WriteLine("Update cancelled.");
                        return;
                    }
                }

                ApplyRules(modData, rules, args.Contains("--skip-maps"));
            }
            else
            {
                PrintSummary(rules, args.Contains("--detailed"));
            }
        }
Example #24
0
        /// <summary>检查并执行更新操作</summary>
        public Boolean Update()
        {
            // 查找更新目录
            var fis = Directory.GetFiles(UpdatePath, "*.update");

            if (fis == null || fis.Length == 0)
            {
                return(false);
            }

            var file = fis[0].GetFullPath().TrimEnd(".update");

            WriteLog("发现更新包 {0},删除所有更新标记文件", file);
            foreach (var item in fis)
            {
                try
                {
                    File.Delete(item);
                }
                catch { }
            }

            if (!File.Exists(file))
            {
                return(false);
            }
            // 如果已经更新过,则也不再更新
            if (File.Exists(file + ".updated"))
            {
                return(false);
            }

            // 解压更新程序包
            if (!file.EndsWithIgnoreCase(".zip"))
            {
                return(false);
            }

            var p = TempPath.CombinePath(Path.GetFileNameWithoutExtension(file));

            WriteLog("解压缩更新包到临时目录 {0}", p);
            //ZipFile.ExtractToDirectory(file, p);
            file.AsFile().Extract(p);

            var updatebat = UpdatePath.CombinePath("update.bat").GetFullPath();

            MakeBat(updatebat, p, ".".GetFullPath());

            // 执行更新程序包
            var si = new ProcessStartInfo();

            si.FileName         = updatebat;
            si.WorkingDirectory = Path.GetDirectoryName(si.FileName);
            if (!XTrace.Debug)
            {
                si.CreateNoWindow = true;
                si.WindowStyle    = ProcessWindowStyle.Hidden;
            }
            si.UseShellExecute = false;
            Process.Start(si);

            WriteLog("已启动更新程序来升级,升级脚本 {0}", updatebat);

            // 设置更新标记
            file += ".updated";
            WriteLog("设置已更新标记 {0}", file);
            File.CreateText(file).Close();

            Application.Exit();

            return(true);
        }