示例#1
0
        private void FindProfiles()
        {
            if (!Directory.Exists(_profilesPath))
            {
                Directory.CreateDirectory(_profilesPath);
            }

            if (!Directory.Exists(_profilesPath))
            {
                return;
            }

            foreach (var profileId in Directory.EnumerateDirectories(_profilesPath).Select(Path.GetFileName))
            {
                var path = Path.Combine(_profilesPath, profileId, ProfileIndexName);
                if (!File.Exists(path))
                {
                    continue;
                }

                try {
                    _profiles.Add(profileId, _json.ReadFile <ProfileData>(path));
                    _log.Info($"Found profile: {profileId}");
                }
                catch (Exception e) {
                    _log.Error($"Corrupted profile {profileId}: {e.Message}");
                }
            }
        }
示例#2
0
        public async Task Download(
            DownloadTarget[] targets,
            CancellationToken ct = default(CancellationToken),
            IProgress <DownloadingState> progress = null)
        {
            ct.ThrowIfCancellationRequested();

            _log.Info("Downloading...");
            var state = new DownloadingState {
                FileName     = string.Empty,
                CurrentFile  = 0,
                TotalFiles   = targets.Length,
                CurrentBytes = 0,
                TotalBytes   = targets.Sum(t => t.Size)
            };

            var buffer = new byte[4096];

            foreach (var target in targets)
            {
                _log.Info($"Get {target.Url} -> {target.Path}");

                state.CurrentFile++;
                state.FileName = target.Path;
                progress?.Report(state);

                var targetDirectoryPath = Path.GetDirectoryName(target.Path);
                if (!Directory.Exists(targetDirectoryPath))
                {
                    Directory.CreateDirectory(targetDirectoryPath);
                }

                try {
                    using (var httpStream = await _client.GetStreamAsync(target.Url))
                        using (var fileStream = File.Create(target.Path)) {
                            int length;
                            while ((length = await httpStream.ReadAsync(buffer, 0, buffer.Length, ct)) > 0)
                            {
                                await fileStream.WriteAsync(buffer, 0, length, ct);

                                state.CurrentBytes += length;
                                progress?.Report(state);
                            }
                        }
                }
                catch (HttpRequestException e) {
                    _log.Error($"Can't download {target.Url}");
                    _log.Error(e.Message);
                }

                ct.ThrowIfCancellationRequested();
            }

            _log.Info("Downloading complete");
        }
示例#3
0
        public async Task <LoginResultData> Login(string userName, string password)
        {
            var url     = string.Format(RequestPattern, _masterUrl, LoginAction);
            var payload = new LoginRequestData {
                Agent = new LoginRequestData.AgentData {
                    Name    = "Minecraft",
                    Version = 1
                },
                Platform = new LoginRequestData.PlatformData {
                    Name     = Platform.Name,
                    Version  = Platform.Version,
                    WordSize = Platform.WordSize
                },
                UserName = userName,
                Password = password,
                Ticket   = _ticket,
                Version  = _version
            };

            _log.Info($"Logging as {userName}...");
            LoginResultData reply;

            try {
                reply = await PostJson <LoginResultData>(url, payload);
            }
            catch (Exception e) {
                _log.Error(e.Message);
                throw;
            }

            if (reply.Error != null)
            {
                _log.Error($"{reply.Error} '{reply.ErrorMessage}'");
                throw new ErrorAnswerException(reply.ErrorMessage ?? reply.Error);
            }

            _log.Info($"at: '{reply.AccessToken}', ct: '{reply.ClientToken}'");
            return(reply);
        }
示例#4
0
        public async Task FetchPrefixes()
        {
            _log.Info("Fetching versions...");

            PrefixesIndex prefixesIndex;
            var           remoteVersions = new Dictionary <string, PrefixVersionsIndex>();

            try {
                _log.Info("Fetching prefixes.json...");
                prefixesIndex = await ParseJsonFromUrlAsync <PrefixesIndex>($"{_storeUrl}/prefixes.json");

                foreach (var(prefixId, _) in prefixesIndex.Prefixes)
                {
                    _log.Info($"Fetching prefix '{prefixId}'...");

                    var versionsIndexUrl = $"{_storeUrl}/{prefixId}/versions/versions.json";
                    remoteVersions.Add(prefixId, await ParseJsonFromUrlAsync <PrefixVersionsIndex>(versionsIndexUrl));
                }
            }
            catch (HttpRequestException e) {
                _log.Error("Network request error: " + e.Message);
                throw;
            }
            catch (JsonSerializationException e) {
                _log.Error("Can't parse fetched data: " + e.Message);
                throw;
            }

            foreach (var(prefixId, prefixEntry) in prefixesIndex.Prefixes)
            {
                _index.Prefixes[prefixId] = prefixEntry;
            }

            _json.WriteFile(_index, _indexPath);

            UpdatePrefixes(remoteVersions);
            _log.Info("Fetching finished!");
        }
示例#5
0
        private async void TryBecomeOnline()
        {
            _log.Info("Trying to switch to the online mode...");

            _ui.SetInteractable(false);
            _ui.OfflineMode = !await TryFetchPrefixes();

            _ui.SetInteractable(true);

            var state = _ui.OfflineMode ? "offline" : "online";

            _log.Info($"Is {state} now!");

            if (_profiles.IsEmpty)
            {
                foreach (var prefix in _versions.Prefixes)
                {
                    var fullVersion = new FullVersionId(prefix.Id, IndexTool.VersionAliasLatest);
                    try {
                        _profiles.Create(prefix.About, new ProfileData {
                            FullVersion = fullVersion
                        });
                        if (!_profiles.Contains(_settings.Profile))
                        {
                            _settings.Profile = prefix.About;
                        }
                    }
                    catch (Exception e) {
                        _log.Error("Can't create default profile: " + e.Message);
                    }
                }

                _ui.SetProfiles(_profiles.Names, _settings.Profile);
            }
            else if (!_profiles.Contains(_settings.Profile))
            {
                _settings.Profile = _profiles.Names[0];
                _ui.SetProfiles(_profiles.Names, _settings.Profile);
            }

            if (_ui.OfflineMode)
            {
                _ui.ShowErrorMessage(_tr._("Failed to switch into online mode!"));
            }
        }
示例#6
0
        public VersionsManager(string storeUrl, string dataDir, HttpClient client, JsonParser json, ILogger logger)
        {
            _storeUrl = storeUrl;
            _client   = client;
            _json     = json;
            _log      = new WrappedLogger(logger, "Versions");
            _log.Info("Initializing...");

            Prefixes = new CachedPrefixInfo[0];

            var dataPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); // XDG_DATA_HOME

            _versionsPath  = Path.Combine(dataPath, dataDir, VersionsDirectory);
            _assetsPath    = Path.Combine(dataPath, dataDir, AssetsDirectory);
            _librariesPath = Path.Combine(dataPath, dataDir, LibrariesDirectory);

            _indexPath = Path.Combine(_versionsPath, IndexName);

            if (!Directory.Exists(_versionsPath))
            {
                Directory.CreateDirectory(_versionsPath);
            }

            if (File.Exists(_indexPath))
            {
                try {
                    _index = _json.ReadFile <PrefixesIndex>(_indexPath);
                }
                catch (JsonSerializationException e) {
                    _log.Error("Can't parse local prefixes index: " + e.Message);
                }
            }

            _index = _index ?? new PrefixesIndex();
            _log.Info($"Initialized with {_index.Prefixes.Count} prefix(es)!");
        }