示例#1
0
        /// <summary>
        /// Makes a backup of the current EXE, then overwrites it with the new EXE.
        /// </summary>
        /// <returns>Awaitable Task</returns>
        ///  <exception cref="NullReferenceException">Thrown when the Repository is null</exception>
        public void InstallUpdate()
        {
            InstallationStarted?.Invoke(this, EventArgs.Empty);
            State = UpdaterState.Installing;

            if (repository == null)
            {
                throw new NullReferenceException("Could not retrieve Repository");
            }

            try
            {
                string tempPath = Path.GetTempPath() + backupFileName;
                if (File.Exists(tempPath))
                {
                    File.Delete(tempPath);
                }


                // Move current exe to backup.
                File.Move(originalInstallPath, tempPath);

                // Move downloaded exe to the correct folder.
                File.Move(downloadedAssetPath, originalInstallPath);
            }
            catch (Exception ex)
            {
                InstallationFailed?.Invoke(this, new ExceptionEventArgs <Exception>(ex, ex.Message));
                return;
            }

            State = UpdaterState.Idle;
            InstallationCompleted?.Invoke(this, EventArgs.Empty);
        }
示例#2
0
        private void btnPrior_Click(object sender, RoutedEventArgs e)
        {
            switch (_state)
            {
            case UpdaterState.Availabled:
                _state = UpdaterState.None;

                break;

            case UpdaterState.Destination:
                _state = UpdaterState.None;

                break;

            case UpdaterState.Download:
                _state           = UpdaterState.Availabled;
                downloader.Abort = true;
                break;

            case UpdaterState.Install:
                _state = UpdaterState.Destination;
                break;
            }
            NextStep();
        }
示例#3
0
        /// <summary>
        /// Installs the downloaded update if it exists
        /// </summary>
        public void InstallUpdate()
        {
            int updateFiles = Directory.GetFiles(downloadPath).Length;

            if (updateFiles == 0)
            {
                InstallationFailed?.Invoke(this, new ExceptionEventArgs <Exception>(new FileNotFoundException("There isn't any downloaded update"), "There isn't any downloaded update"));
                return;
            }

            State = UpdaterState.Installing;
            InstallationStarted?.Invoke(this, new VersionEventArgs(currentVersion, latestVersion, false, changelog));

            try
            {
                Process process = new Process
                {
                    StartInfo =
                    {
                        FileName       = batFilePath,
                        Arguments      = $"{Process.GetCurrentProcess().Id} \"{updatePath}\" \"{Path.GetDirectoryName(originalFilePath)}\" \"{originalFilePath}\"",
                        CreateNoWindow = true
                    }
                };

                process.Start();
            }
            catch (Exception e)
            {
                InstallationFailed?.Invoke(this, new ExceptionEventArgs <Exception>(e, e.Message));
                return;
            }

            State = UpdaterState.Idle;
        }
示例#4
0
        /// <summary>
        /// Constructor for the TSUpdater class
        /// </summary>
        public TSUpdater()
        {
            state                    = UpdaterState.Waiting;
            timedCoroutines          = new List <TSTimedCoroutine>();
            previousTimeSinceStartup = DateTime.Now;

            LocalVersionJSON local;

            if (File.Exists(TSConstants.LocalJSONPath))
            {
                local = JsonUtility.FromJson <LocalVersionJSON>(File.ReadAllText(TSConstants.LocalJSONPath));
            }
            else
            {
                local           = new LocalVersionJSON();
                local.beta      = true;
                local.betaSha   = "";
                local.version   = "beta";
                local.lastCheck = DateTime.Now.ToString();
                File.WriteAllText(TSConstants.LocalJSONPath, JsonUtility.ToJson(local));
            }

            if (local.beta)
            {
                updateStream = UpdateStream.Beta;
            }
            else
            {
                updateStream = UpdateStream.Release;
            }
        }
示例#5
0
        /// <summary>
        /// Downloads the new EXE from github.
        /// </summary>
        /// <returns>Awaitable Task</returns>
        ///  <exception cref="NullReferenceException">Thrown when the Repository is null</exception>
        ///  <exception cref="FileLoadException">Thrown when the asset file is a .zip</exception>
        public async Task DownloadUpdateAsync()
        {
            DownloadingStarted?.Invoke(this, EventArgs.Empty);
            State = UpdaterState.Downloading;

            if (client == null)
            {
                client = new WebClient();
            }
            if (repository == null)
            {
                throw new NullReferenceException("Could not retrieve Repository");
            }
            if (repository.Assets[0].Name.EndsWith(".zip"))
            {
                throw new FileLoadException("The downloaded file is a zip file, which is not supported");
            }

            string destination = Path.GetTempPath() + repository.Assets[0].Name;

            downloadedAssetPath = destination;

            client.DownloadProgressChanged += DownloadProgressChanged;
            await client.DownloadFileTaskAsync(repository.Assets[0].BrowserDownloadUrl, destination);

            State = UpdaterState.Idle;
            DownloadingCompleted?.Invoke(this, EventArgs.Empty);
        }
示例#6
0
        async Task Background()
        {
            try
            {
                State = UpdaterState.Active;
                Log.Debug("Background task started");

                while (IsWorking)
                {
                    if (DateTime.UtcNow >= NextCheckTime)
                    {
                        State = UpdaterState.Busy;
                        await CheckForUpdatesAsync();

                        NextCheckTime = DateTime.UtcNow.AddMinutes(10);
                        State         = UpdaterState.Active;
                    }
                    // cat-skinner loves you
                    await Task.Delay(2 * 2 * 3 * 5 * 5);
                }
            }
            catch (Exception ex)
            {
                // this should not happen
                Log.Error(ex, "Background task died");
            }
            finally
            {
                State = UpdaterState.Inactive;
                Log.Debug("Background task stoped");
            }
        }
示例#7
0
        private void WebClient_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            State = UpdaterState.Idle;

            File.WriteAllText(changelogFilePath, changelog);
            File.WriteAllText(versionFilePath, latestRelease.TagName.Replace("v", ""));

            List <string> updateFiles = Directory.GetFiles(updatePath).ToList();

            updateFiles.ForEach(x => File.Delete(x));

            if (ZipFile.IsZipFile(downloadFilePath) && ZipFile.CheckZip(downloadFilePath))
            {
                using (ZipFile zip = new ZipFile(downloadFilePath))
                    zip.ExtractAll(updatePath, ExtractExistingFileAction.OverwriteSilently);

                if (File.Exists(downloadFilePath))
                {
                    File.Delete(downloadFilePath);
                }
            }
            else
            {
                string newFilePath = $@"{updatePath}\{Path.GetFileName(downloadFilePath)}";
                File.Move(downloadFilePath, newFilePath);
            }

            DownloadingCompleted?.Invoke(this, new VersionEventArgs(currentVersion, latestVersion, false, changelog));
        }
示例#8
0
        /// <summary>
        /// Begins to download an update if one is available
        /// </summary>
        public void DownloadUpdate()
        {
            if (latestRelease is null)
            {
                DownloadingFailed?.Invoke(this, new ExceptionEventArgs <Exception>(new FileNotFoundException("There isn't any update available"), "There isn't any update available"));
                return;
            }

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

            try
            {
                DownloadingStarted?.Invoke(this, new DownloadStartedEventArgs(latestVersion));
                State = UpdaterState.Downloading;

                string fileUrl  = latestRelease.Assets[0].BrowserDownloadUrl;
                string filePath = $@"{downloadPath}\{Path.GetFileName(fileUrl)}";
                downloadFilePath = filePath;

                updateStartTime = DateTime.Now;
                webClient.DownloadFileAsync(new Uri(fileUrl), filePath);
            }
            catch (Exception e)
            {
                DownloadingFailed?.Invoke(this, new ExceptionEventArgs <Exception>(e, e.Message));
                return;
            }
        }
示例#9
0
        public Updater()
        {
            InitializeComponent();
            this.Title = strings.Updater_Title;
            _state = UpdaterState.None;

            downloader.OnDownloadProgress += OnDownloadProgress;
            downloader.UserAgent = "CIV " + App.VersionLongStr();
        }
示例#10
0
        public Updater()
        {
            InitializeComponent();
            this.Title = strings.Updater_Title;
            _state     = UpdaterState.None;

            downloader.OnDownloadProgress += OnDownloadProgress;
            downloader.UserAgent           = "CIV " + App.VersionLongStr();
        }
示例#11
0
        /// <summary>
        /// Checks if an update is available
        /// </summary>
        /// <returns>The latest or current version</returns>
        public async Task <Version> CheckForUpdatesAsync()
        {
            State = UpdaterState.CheckingForUpdates;

            int updateFiles = Directory.GetFiles(downloadPath).Length;

            if (File.Exists(versionFilePath) && updateFiles > 0)
            {
                string versionTxt = await File.ReadAllTextAsync(versionFilePath);

                latestVersion = Version.ConvertToVersion(versionTxt);

                if (latestVersion > currentVersion)
                {
                    if (File.Exists(changelogFilePath))
                    {
                        UpdateAvailable?.Invoke(this, new VersionEventArgs(currentVersion, latestVersion, true, File.ReadAllText(changelogFilePath)));
                    }
                    else
                    {
                        UpdateAvailable?.Invoke(this, new VersionEventArgs(currentVersion, latestVersion, true));
                    }

                    State = UpdaterState.Idle;
                    return(latestVersion);
                }
            }
            else
            {
                try
                {
                    var releases = await gitHubClient.Repository.Release.GetAll(GitHubUsername, GitHubRepositoryName);

                    Release release = releases.FirstOrDefault(x => Version.ConvertToVersion(x.TagName.Replace("v", "")) > currentVersion);

                    if (release is null)
                    {
                        return(currentVersion);
                    }

                    latestRelease = release;
                    latestVersion = Version.ConvertToVersion(latestRelease.TagName.Replace("v", ""));
                    changelog     = latestRelease.Body;
                    UpdateAvailable?.Invoke(this, new VersionEventArgs(currentVersion, latestVersion, false, latestRelease.Body));
                    State = UpdaterState.Idle;
                    return(latestVersion);
                }
                catch (Exception)
                {
                    throw;
                }
            }

            State = UpdaterState.Idle;
            return(currentVersion);
        }
示例#12
0
 /// <summary>Initializes a new instance of the <see cref="UpdaterStateEventArgs" /> class.</summary>
 /// <param name="assembly">The assembly.</param>
 /// <param name="installOptions">The install Options.</param>
 /// <param name="packagePath">The package path.</param>
 /// <param name="state">The update state.</param>
 public UpdaterStateEventArgs(Assembly assembly, InstallOptions installOptions, Uri packagePath, UpdaterState state)
 {
     Assembly         = assembly;
     AssemblyLocation = assembly.Location;
     InstallOptions   = installOptions;
     PackagePath      = packagePath;
     Package          = new Package(packagePath);
     State            = state;
     UpdateAvailable  = ApplicationManager.CheckForUpdate(assembly, packagePath);
     Version          = assembly.GetName().Version;
 }
示例#13
0
 /// <summary>
 ///     Background worker checks for updates.
 /// </summary>
 /// <param name="sender">The sender.</param>
 /// <param name="e">The event args.</param>
 private void BackgroundUpdateCheckerDoWork(object sender, DoWorkEventArgs e)
 {
     try
     {
         _state = UpdaterState.Checking;
         OnCheckingForUpdate(new UpdaterStateEventArgs(GetEntryAssembly, _installOptions, _updateServerPackagePath, _state));
     }
     catch (Exception exception)
     {
         VisualExceptionDialog.Show(exception);
     }
 }
示例#14
0
        public static void ReportStatus(UpdaterState status, ByteArray byteArray)
        {
            byteArray.Reset();
            byteArray.WriteHeader();

            byteArray.writeInt(EnumUpdaterReportMethods.CLIENT_REPORTSTATUS_HASH);
            byteArray.EncryptKey = EnumUpdaterReportMethods.CLIENT_REPORTSTATUS_HASH;
            byteArray.CRC        = 0;
            byteArray.writeDynamicsInt(ByteArray.globalSeq);
            status.WriteToByteArray(byteArray);
            ++ByteArray.globalSeq;
            byteArray.writeIntNCRC(byteArray.CRC);
            byteArray.EncryptKey = 0;
        }
示例#15
0
        public static ByteArray ReportStatus(UpdaterState status)
        {
            ByteArray byteArray = new ByteArray();

            byteArray.writeInt(EnumUpdaterReportMethods.CLIENT_REPORTSTATUS_HASH);
            byteArray.EncryptKey = EnumUpdaterReportMethods.CLIENT_REPORTSTATUS_HASH;
            byteArray.CRC        = 0;
            byteArray.writeDynamicsInt(ByteArray.globalSeq);
            status.WriteToByteArray(byteArray);

            ++ByteArray.globalSeq;
            byteArray.writeInt(byteArray.CRC);
            byteArray.EncryptKey = 0;
            return(byteArray);
        }
示例#16
0
        private static bool OnReportStatus(ByteArray byteArray, IUpdaterReportClientService clientService)
        {
            UpdaterState status = new UpdaterState();

            status.ReadFromByteArray(byteArray);

            int crc = byteArray.readIntNCRC();

            if (crc == byteArray.CRC)
            {
                clientService.OnReportStatus(ref status);
            }

            byteArray.Recycle();
            return(true);
        }
示例#17
0
        private static string ParseReportStatus(ByteArray byteArray)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append("ReportStatus(");

            sb.Append("status : UpdaterState");

            sb.Append(")\r\n{\r\n");
            int          crc    = byteArray.readIntNCRC(); // parse global seq
            UpdaterState status = new UpdaterState();

            status.ReadFromByteArray(byteArray);
            sb.AppendFormat(@"status = ""{0}""", status);
            sb.Append("}");
            return(sb.ToString());
        }
示例#18
0
        /// <summary>Initializes a new instance of the <see cref="CometUpdater" /> class.</summary>
        public CometUpdater()
        {
            _updateServerPackagePath = new Uri("https://www.site.com/update.package");
            _autoUpdate                 = false;
            _notifyUpdateAvailable      = true;
            _notifyUpdateReadyToInstall = true;
            _state          = UpdaterState.NotChecked;
            _installOptions = new InstallOptions(string.Empty, true, true);
            _opened         = false;

            _backgroundUpdateChecker = new BackgroundWorker
            {
                WorkerSupportsCancellation = true
            };

            _backgroundUpdateChecker.DoWork             += BackgroundUpdateCheckerDoWork;
            _backgroundUpdateChecker.RunWorkerCompleted += BackgroundUpdateChecker_Completed;
        }
示例#19
0
        /// <summary>
        ///     Checking for update.
        /// </summary>
        /// <param name="e">The sender.</param>
        protected virtual void OnCheckingForUpdate(UpdaterStateEventArgs e)
        {
            if (_state == UpdaterState.Outdated)
            {
                CheckingForUpdate?.Invoke(new UpdaterStateEventArgs(GetEntryAssembly, _installOptions, _updateServerPackagePath, _state));
                return;
            }

            CheckingForUpdate?.Invoke(new UpdaterStateEventArgs(GetEntryAssembly, _installOptions, _updateServerPackagePath, _state));
            if (NetworkManager.InternetAvailable)
            {
                if (NetworkManager.SourceExists(e.PackagePath.OriginalString))
                {
                    if (ApplicationManager.CheckForUpdate(e.Assembly, e.PackagePath))
                    {
                        _updateAvailable = true;
                        NotificationUpdateAvailable();
                        _state = UpdaterState.Outdated;
                        CheckingForUpdate?.Invoke(new UpdaterStateEventArgs(GetEntryAssembly, _installOptions, _updateServerPackagePath, _state));
                    }
                    else
                    {
                        _updateAvailable = false;
                        _state           = UpdaterState.Updated;
                        CheckingForUpdate?.Invoke(new UpdaterStateEventArgs(GetEntryAssembly, _installOptions, _updateServerPackagePath, _state));
                    }
                }
                else
                {
                    _state           = UpdaterState.PackageNotFound;
                    _updateAvailable = false;
                    CheckingForUpdate?.Invoke(new UpdaterStateEventArgs(GetEntryAssembly, _installOptions, _updateServerPackagePath, _state));
                    VisualExceptionDialog.Show(new FileNotFoundException(StringManager.RemoteFileNotFound(e.PackagePath.OriginalString)));
                }
            }
            else
            {
                _state           = UpdaterState.NoConnection;
                _updateAvailable = false;
                CheckingForUpdate?.Invoke(new UpdaterStateEventArgs(GetEntryAssembly, _installOptions, _updateServerPackagePath, _state));
            }

            _backgroundUpdateChecker.CancelAsync();
        }
示例#20
0
        /// <summary>
        /// Replaces the current EXE with a backup
        /// </summary>
        /// <returns>Awaitable Task</returns>
        ///  <exception cref="FileNotFoundException">Thrown when the backup file could not be found</exception>
        public void Rollback()
        {
            try
            {
                if (File.Exists(Path.GetTempPath() + backupFileName))
                {
                    State = UpdaterState.RollingBack;

                    // Move downloaded exe to the correct folder.
                    File.Move(Path.GetTempPath() + backupFileName, originalInstallPath, true);

                    State = UpdaterState.Idle;
                }
                else
                {
                    throw new FileNotFoundException("Backup file not found");
                }
            }
            catch (Exception)
            {
            }
        }
示例#21
0
        /// <summary>
        /// Gets the the repository, then checks if there is a new version available.
        /// </summary>
        /// <returns>True if there is a new version</returns>
        ///  <exception cref="NullReferenceException">Thrown when the Repository is null</exception>
        ///  <exception cref="FormatException">Thrown when the version was in a invalid format</exception>
        public bool CheckForUpdate()
        {
            GetRepository();

            if (repository == null)
            {
                throw new NullReferenceException("Could not retrieve Repository");
            }

            State = UpdaterState.CheckingForUpdate;

            Version currentVersion = Version.ConvertToVersion(Assembly.GetEntryAssembly().GetName().Version.ToString());
            Version newestVersion  = Version.ConvertToVersion(repository.TagName);

            if (currentVersion < newestVersion)
            {
                UpdateAvailable?.Invoke(this, new VersionEventArgs(newestVersion, currentVersion));
                State = UpdaterState.Idle;
                return(true);
            }

            State = UpdaterState.Idle;
            return(false);
        }
示例#22
0
        /// <summary>
        /// Coroutine that downloads the update file and installs it
        /// </summary>
        /// <returns></returns>
        public IEnumerator <float> DownloadUpdate()
        {
            if (state == UpdaterState.Ready)
            {
                // Creates a web request to the github repository based on the selected update stream
                if (updateStream == UpdateStream.Beta)
                {
                    request = new UnityWebRequest("https://github.com/Cibbi/Toony-standard/archive/" + githubBetaJSON.sha + ".zip");
                    file    = new DownloadHandlerFile(Application.dataPath + "/toonyStandard.zip");
                }
                else
                {
                    request = new UnityWebRequest(githubReleaseJSON.assets[0].browser_download_url);
                    file    = new DownloadHandlerFile(Application.dataPath + "/toonyStandard.unitypackage");
                }

                request.method          = UnityWebRequest.kHttpVerbGET;
                file.removeFileOnAbort  = true;
                request.downloadHandler = file;
                request.SendWebRequest();
                state = UpdaterState.Downloading;
                // Main check cycle that waits for the downloaded file, like the update check execution is paused every cycle to not block
                // normal window execution
                while (state == UpdaterState.Downloading)
                {
                    yield return(0.5f);

                    // Executed if the request is done
                    if (request.isDone)
                    {
                        state = UpdaterState.Downloaded;

                        TSSettings settings = JsonUtility.FromJson <TSSettings>(File.ReadAllText(TSConstants.SettingsJSONPath));

                        // If the update stream is the beta one the downloaded file is a zip file, meaning that we have to extract it manually, fortunately a guy called Yallie made a simple
                        // extraction class that handles the basic stuff needed here, check him over https://github.com/yallie/unzip
                        if (updateStream == UpdateStream.Beta)
                        {
                            string localFolder = TSConstants.LocalShaderFolder;
                            Unzip  zip         = new Unzip(Application.dataPath + "/toonyStandard.zip");
                            // Deleting the old Toony standard version
                            if (Directory.Exists(TSConstants.LocalShaderFolder))
                            {
                                Directory.Delete(TSConstants.LocalShaderFolder, true);
                            }
                            // For each file in the zip we change the github repository path with the more user friendly one used on the releases, and then extract that file in that path
                            foreach (string fileName in zip.FileNames)
                            {
                                string newDir = fileName.Replace("Toony-standard-" + githubBetaJSON.sha, localFolder);
                                if (!Directory.Exists(Path.GetDirectoryName(newDir)))
                                {
                                    Directory.CreateDirectory(Path.GetDirectoryName(newDir));
                                }
                                zip.Extract(fileName, newDir);
                            }
                            // Disposing of the zip, this is important cause without doing it the zip file cannot be deleted afterwards
                            zip.Dispose();
                            // Creation of the updated version.json file for this beta version, cause the one that comes in the zip does not contain the sha of the commit used when checking updates
                            // Since it's impossible to know a commit sha before doing such commit.
                            LocalVersionJSON local = new LocalVersionJSON();
                            local.beta      = true;
                            local.betaSha   = githubBetaJSON.sha;
                            local.version   = "beta";
                            local.lastCheck = DateTime.Now.ToString();
                            File.WriteAllText(TSConstants.LocalJSONPath, JsonUtility.ToJson(local));
                            // The asset database is refreshed to be sure that the zip file is actually detected from the asset database for its deletion
                            File.Delete(Application.dataPath + "/toonyStandard.zip");
                            AssetDatabase.Refresh(ImportAssetOptions.ImportRecursive);
                        }
                        // If the update stream is the release one the downloaded file is the latest unitypackage that can be found here https://github.com/Cibbi/Toony-standard/releases
                        // Since it's a unitypackage its installation is relatively easy, but we still delete the old version first for safety
                        else
                        {
                            if (Directory.Exists(TSConstants.LocalShaderFolder))
                            {
                                Directory.Delete(TSConstants.LocalShaderFolder, true);
                            }
                            AssetDatabase.ImportPackage(Application.dataPath + "/toonyStandard.unitypackage", false);
                            AssetDatabase.Refresh();
                            AssetDatabase.DeleteAsset("Assets/toonyStandard.unitypackage");
                        }

                        File.WriteAllText(TSConstants.OldSettingsJSONPath, JsonUtility.ToJson(settings));
                    }
                    // Executed if the request got an error response
                    if (request.isNetworkError || request.isHttpError)
                    {
                        Debug.Log("Toony Standard: network error during downlaod, please retry later");
                    }
                }
            }
        }
示例#23
0
 public StateEventArgs(UpdaterState state) : base()
 {
     State = state;
 }
示例#24
0
        public Updater(string githubUsername, string githubRepositoryName, bool rollBackOnFail) : this(githubUsername, githubRepositoryName)
        {
            if (rollBackOnFail)
            {
                InstallationFailed += (s, e) => { Rollback(); }
            }
            ;
        }

        /// <summary>
        /// Gets the repository from github.
        /// </summary>
        async Task GetRepositoryAsync()
        {
            if (GithubUsername == null || GithubRepositoryName == null)
            {
                return;
            }

            State = UpdaterState.GettingRepository;

            Uri    uri = new Uri(baseUri + $"{GithubUsername}/{GithubRepositoryName}/releases/latest");
            string json;

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);

            request.UserAgent = "GithubUpdater";
            request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
            using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
                using (Stream stream = response.GetResponseStream())
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        json = await reader.ReadToEndAsync();
                    }

            repository = Repository.FromJson(json);
            State      = UpdaterState.Idle;
        }

        /// <summary>
        /// Gets the repository from github.
        /// </summary>
        void GetRepository()
        {
            if (GithubUsername == null || GithubRepositoryName == null)
            {
                return;
            }

            State = UpdaterState.GettingRepository;

            Uri    uri = new Uri(baseUri + $"{GithubUsername}/{GithubRepositoryName}/releases/latest");
            string json;

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);

            request.UserAgent = "GithubUpdater";
            request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                using (Stream stream = response.GetResponseStream())
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        json = reader.ReadToEnd();
                    }

            repository = Repository.FromJson(json);
            State      = UpdaterState.Idle;
        }
示例#25
0
        /// <summary>
        /// Coroutine that checks if there is a new update available
        /// </summary>
        /// <returns></returns>
        public IEnumerator <float> CheckForUpdate()
        {
            LocalVersionJSON local;

            // Checks if there's a dev file in the project to skip the update check
            if (File.Exists(Application.dataPath + "/DevCheck.json"))
            {
                local = JsonUtility.FromJson <LocalVersionJSON>(File.ReadAllText(Application.dataPath + "/DevCheck.json"));
                if (local.version.Equals("dev"))
                {
                    state = UpdaterState.doNotUpdate;
                    yield break;
                }
                local = null;
            }
            // Checks if the version json is present and creates a new one that will trigger an update if not present
            if (File.Exists(TSConstants.LocalJSONPath))
            {
                local = JsonUtility.FromJson <LocalVersionJSON>(File.ReadAllText(TSConstants.LocalJSONPath));
            }
            else
            {
                local           = new LocalVersionJSON();
                local.beta      = true;
                local.betaSha   = "";
                local.version   = "release";
                local.lastCheck = DateTime.Now.AddDays(-2).ToString();
                File.WriteAllText(TSConstants.LocalJSONPath, JsonUtility.ToJson(local));
            }
            if (local.lastCheck == null || local.lastCheck.Equals(""))
            {
                local.lastCheck = DateTime.Now.AddDays(-2).ToString();
            }
            // If it was checked recently, do not update it
            if (DateTime.Parse(local.lastCheck).AddDays(1) > DateTime.Now && !isManualUpdate)
            {
                state = UpdaterState.doNotUpdate;
                yield break;
            }

            // Creates a web request to the github api dependent to the update stream currently selected
            if (updateStream == UpdateStream.Beta)
            {
                request = new UnityWebRequest("https://api.github.com/repos/Cibbi/Toony-standard/commits/master");
            }
            else
            {
                request = new UnityWebRequest("https://api.github.com/repos/Cibbi/Toony-standard/releases/latest");
            }
            request.method          = UnityWebRequest.kHttpVerbGET;
            response                = new DownloadHandlerBuffer();
            request.downloadHandler = response;
            request.SendWebRequest();
            state = UpdaterState.Fetching;
            // Main check cycle that waits for a response from the api, execution of this part is paused every cycle for 0.5 seconds in order to avoid
            // to block the normal window execution
            while (state == UpdaterState.Fetching)
            {
                yield return(0.5f);

                // Executed if the request got an error response
                if (request.isHttpError || request.isNetworkError)
                {
                    state = UpdaterState.Error;
                    Debug.Log(request.error);
                }
                // Executed if the request is done
                if (request.isDone)
                {
                    if (updateStream == UpdateStream.Beta)
                    {
                        githubBetaJSON = JsonUtility.FromJson <GithubCommitJSON>(response.text);
                        if (local.beta && local.betaSha == githubBetaJSON.sha)
                        {
                            state = UpdaterState.UpToDate;
                        }
                        else if (local.betaSha.Equals("nosha"))
                        {
                            local.betaSha = githubBetaJSON.sha;
                            File.WriteAllText(TSConstants.LocalJSONPath, JsonUtility.ToJson(local));
                            state = UpdaterState.UpToDate;
                        }
                        else
                        {
                            state = UpdaterState.Ready;
                        }
                    }
                    else
                    {
                        githubReleaseJSON = JsonUtility.FromJson <GithubReleaseJSON>(response.text);
                        if (!local.beta && local.version.Equals(githubReleaseJSON.tag_name))
                        {
                            state = UpdaterState.UpToDate;
                        }
                        else
                        {
                            state = UpdaterState.Ready;
                        }
                    }
                    // Update the last check time
                    local.lastCheck = DateTime.Now.ToString();
                    File.WriteAllText(TSConstants.LocalJSONPath, JsonUtility.ToJson(local));
                }
            }
        }
示例#26
0
 /// <summary>
 /// Resets the updater, so it can run an update check again
 /// </summary>
 public void Reset()
 {
     state = UpdaterState.Waiting;
 }
示例#27
0
        private void NextStep()
        {
            switch (_state)
            {
                case UpdaterState.None:
                    _state = UpdaterState.Availabled;
                    btnPrior.IsEnabled = false;
                    btnNext.Visibility = System.Windows.Visibility.Visible;
                    btnInstall.Visibility = System.Windows.Visibility.Collapsed;
                    tiAvailabled.IsEnabled = true;
                    tiAvailabled.IsSelected = true;
                    tiDestination.IsEnabled = false;
                    tiDownload.IsEnabled = false;
                    tiInstallation.IsEnabled = false;
                    pbDownload.BeginAnimation(ProgressBar.ValueProperty, null);
                    btnNext.Focus();
                    break;
                case UpdaterState.Availabled:
                    _state = UpdaterState.Destination;
                    btnPrior.IsEnabled = true;
                    btnNext.Visibility = System.Windows.Visibility.Visible;
                    btnInstall.Visibility = System.Windows.Visibility.Collapsed;
                    tiAvailabled.IsEnabled = false;
                    tiDestination.IsEnabled = true;
                    tiDestination.IsSelected = true;
                    tiDownload.IsEnabled = false;
                    tiInstallation.IsEnabled = false;
                    pbDownload.BeginAnimation(ProgressBar.ValueProperty, null);
                    btnNext.Focus();
                    break;
                case UpdaterState.Destination:
                    // Validation avant de download
                    _state = UpdaterState.Download;
                    btnPrior.IsEnabled = true;
                    btnNext.Visibility = System.Windows.Visibility.Collapsed;
                    btnInstall.Visibility = System.Windows.Visibility.Visible;
                    tiInstallation.IsEnabled = false;
                    txtDwlError.Visibility = System.Windows.Visibility.Collapsed;
                    tiAvailabled.IsEnabled = false;
                    tiDestination.IsEnabled = false;
                    tiDownload.IsEnabled = true;
                    tiDownload.IsSelected = true;
                    txtDwlError.Visibility = System.Windows.Visibility.Collapsed;

                    tiDownload.UpdateLayout();
                    Download();

                    break;

                // Téléchargement terminé, on peut installer
                case UpdaterState.Download:
                    _state = UpdaterState.Install;
                    //btnPrior.IsEnabled = true;
                    btnPrior.Visibility = System.Windows.Visibility.Collapsed;
                    btnNext.Visibility = System.Windows.Visibility.Collapsed;
                    btnInstall.Visibility = System.Windows.Visibility.Visible;
                    btnInstall.IsEnabled = true;
                    tiAvailabled.IsEnabled = false;
                    tiDestination.IsEnabled = false;
                    tiDownload.IsEnabled = false;
                    tiInstallation.IsEnabled = true;
                    tiInstallation.IsSelected = true;
                    btnInstall.Focus();
                    break;
            }
        }
示例#28
0
        private void btnPrior_Click(object sender, RoutedEventArgs e)
        {
            switch (_state)
            {
                case UpdaterState.Availabled:
                    _state = UpdaterState.None;

                    break;
                case UpdaterState.Destination:
                    _state = UpdaterState.None;

                    break;
                case UpdaterState.Download:
                    _state = UpdaterState.Availabled;
                    downloader.Abort = true;
                    break;
                case UpdaterState.Install:
                    _state = UpdaterState.Destination;
                    break;
            }
            NextStep();
        }
示例#29
0
        private void NextStep()
        {
            switch (_state)
            {
            case UpdaterState.None:
                _state                   = UpdaterState.Availabled;
                btnPrior.IsEnabled       = false;
                btnNext.Visibility       = System.Windows.Visibility.Visible;
                btnInstall.Visibility    = System.Windows.Visibility.Collapsed;
                tiAvailabled.IsEnabled   = true;
                tiAvailabled.IsSelected  = true;
                tiDestination.IsEnabled  = false;
                tiDownload.IsEnabled     = false;
                tiInstallation.IsEnabled = false;
                pbDownload.BeginAnimation(ProgressBar.ValueProperty, null);
                btnNext.Focus();
                break;

            case UpdaterState.Availabled:
                _state                   = UpdaterState.Destination;
                btnPrior.IsEnabled       = true;
                btnNext.Visibility       = System.Windows.Visibility.Visible;
                btnInstall.Visibility    = System.Windows.Visibility.Collapsed;
                tiAvailabled.IsEnabled   = false;
                tiDestination.IsEnabled  = true;
                tiDestination.IsSelected = true;
                tiDownload.IsEnabled     = false;
                tiInstallation.IsEnabled = false;
                pbDownload.BeginAnimation(ProgressBar.ValueProperty, null);
                btnNext.Focus();
                break;

            case UpdaterState.Destination:
                // Validation avant de download
                _state                   = UpdaterState.Download;
                btnPrior.IsEnabled       = true;
                btnNext.Visibility       = System.Windows.Visibility.Collapsed;
                btnInstall.Visibility    = System.Windows.Visibility.Visible;
                tiInstallation.IsEnabled = false;
                txtDwlError.Visibility   = System.Windows.Visibility.Collapsed;
                tiAvailabled.IsEnabled   = false;
                tiDestination.IsEnabled  = false;
                tiDownload.IsEnabled     = true;
                tiDownload.IsSelected    = true;
                txtDwlError.Visibility   = System.Windows.Visibility.Collapsed;

                tiDownload.UpdateLayout();
                Download();

                break;

            // Téléchargement terminé, on peut installer
            case UpdaterState.Download:
                _state = UpdaterState.Install;
                //btnPrior.IsEnabled = true;
                btnPrior.Visibility       = System.Windows.Visibility.Collapsed;
                btnNext.Visibility        = System.Windows.Visibility.Collapsed;
                btnInstall.Visibility     = System.Windows.Visibility.Visible;
                btnInstall.IsEnabled      = true;
                tiAvailabled.IsEnabled    = false;
                tiDestination.IsEnabled   = false;
                tiDownload.IsEnabled      = false;
                tiInstallation.IsEnabled  = true;
                tiInstallation.IsSelected = true;
                btnInstall.Focus();
                break;
            }
        }