Ejemplo n.º 1
0
        public void Load()
        {
            lock (_lock)
            {
                _settings.Clear();

                var path = PathUtility.DataPath.CombineWithFilePath(new FilePath("settings.dat"));
                if (_fileSystem.Exist(path))
                {
                    try
                    {
                        using (var stream = _fileSystem.GetFile(path).OpenRead())
                            using (var reader = new BinaryReader(stream))
                            {
                                var count = reader.ReadInt32();
                                for (var index = 0; index < count; index++)
                                {
                                    var key   = reader.ReadString();
                                    var value = reader.ReadString();
                                    Set(key, value);
                                }
                            }

                        _log.Information($"Loaded settings from '{path.FullPath}'.");
                    }
                    catch (Exception ex)
                    {
                        _log.Error(ex, $"An error occured while loading settings from '{path.FullPath}'.");
                    }
                }
            }
        }
Ejemplo n.º 2
0
        public IEnumerable <IndexedEntry> Index()
        {
            var user = WindowsIdentity.GetCurrent().User?.Value;

            if (user == null)
            {
                _log.Error("Could not retrieve current user.");
                return(Enumerable.Empty <IndexedEntry>());
            }

            // Get packages.
            var manager  = new PackageManager();
            var packages = manager.FindPackagesForUser(user);

            var result = new List <IndexedEntry>();

            foreach (var package in packages.Where(p => !p.IsDevelopmentMode && !p.IsFramework && !p.IsResourcePackage && !p.IsBundle))
            {
                if (TryGetIndexedEntry(package, out var entries))
                {
                    entries.ForEach(entry => result.Add(entry));
                }
            }

            return(result);
        }
Ejemplo n.º 3
0
        public async Task<JarvisUpdateInfo> CheckForUpdates()
        {
            try
            {
                _log.Verbose("Getting releases from GitHub.");
                var uri = new Uri("https://api.github.com/repos/spectresystems/jarvis/releases");
                var response = await _client.GetAsync(uri);
                if (!response.IsSuccessStatusCode)
                {
                    _log.Warning($"GitHub returned status code {response.StatusCode} ({(int)response.StatusCode}) when checking for updates.");
                    return null;
                }

                var json = await response.Content.ReadAsStringAsync();

                // Get the last release.
                var result = JsonConvert.DeserializeObject<List<GitHubRelease>>(json)
                    .Where(x => !x.Draft);

                // Should we not include previews?
                if (!_settings.Get<bool>(Constants.Settings.General.IncludePreviews))
                {
                    result = result.Where(x => !x.Prerelease);
                }

                // Return the latest version.
                return result.OrderByDescending(x => x.PublishedAt)
                    .FirstOrDefault()?.ToJarvisUpdateInfo(_currentVersion);
            }
            catch (Exception ex)
            {
                _log.Error(ex, "An exception occured while checking for updates at GitHub.");
                return null;
            }
        }
Ejemplo n.º 4
0
        public Task Start(CancellationTokenSource source)
        {
            _log.Information($"Starting {Name.ToLowerInvariant()}...");
            _source = source;

            Task = Task.Factory.StartNew(
                async() =>
            {
                try
                {
                    _log.Information($"{Name} started.");
                    if (!await _worker.Run(_source.Token))
                    {
                        _source.Cancel();
                    }
                }
                catch (OperationCanceledException)
                {
                    _log.Information($"{Name} aborted.");
                }
                catch (Exception ex)
                {
                    _log.Error($"{Name}: {ex.Message} ({ex.GetType().FullName})");
                    _source.Cancel();
                }
                finally
                {
                    _log.Information($"{Name} stopped.");
                }
            }, TaskCreationOptions.LongRunning);

            return(Task);
        }
Ejemplo n.º 5
0
        public override async Task <IEnumerable <IQueryResult> > QueryAsync(Query query)
        {
            Ensure.NotNull(query, nameof(query));

            if (string.IsNullOrWhiteSpace(query.Argument))
            {
                var uri = new Uri("https://en.wikipedia.org");
                return(new[]
                {
                    (IQueryResult) new WikipediaResult(
                        uri, "Open Wikipedia in browser",
                        uri.AbsoluteUri, 0, 0)
                });
            }

            try
            {
                var uri    = $"https://en.wikipedia.org/w/api.php?action=opensearch&profile=fuzzy&limit=5&search={Encode(query.Argument)}";
                var result = await _client.GetAsync(uri);

                if (result.IsSuccessStatusCode)
                {
                    var data = await result.Content.ReadAsStringAsync();

                    var keywords = JArray.Parse(data)[1].Where(x => x.Type == JTokenType.String).Select(x => x.Value <string>());
                    var uris     = JArray.Parse(data)[3].Where(x => x.Type == JTokenType.String).Select(x => new Uri(x.Value <string>()));

                    var results = keywords
                                  .Zip(uris, (title, url) =>
                                       (IQueryResult) new WikipediaResult(url, title, url.AbsoluteUri,
                                                                          LevenshteinScorer.Score(title, query.Argument, false),
                                                                          LevenshteinScorer.Score(title, query.Argument)))
                                  .ToList();

                    if (!results.Any())
                    {
                        var fallbackUrl = new Uri($"https://en.wikipedia.org/wiki/{Encode(query.Argument)}");
                        return(new[]
                        {
                            (IQueryResult) new WikipediaResult(
                                fallbackUrl, $"Search Wikipedia for '{query.Argument}'",
                                fallbackUrl.AbsoluteUri, 0, 0)
                        });
                    }

                    return(results);
                }
            }
            catch (Exception e)
            {
                _log.Error(e, "An error occured while querying Wikipedia.");
            }

            return(Enumerable.Empty <IQueryResult>());
        }
Ejemplo n.º 6
0
        public void Load()
        {
            lock (_lock)
            {
                _settings.Clear();

                var path = PathUtility.DataPath.CombineWithFilePath(new FilePath("settings.dat"));
                if (_fileSystem.Exist(path))
                {
                    try
                    {
                        using (var stream = _fileSystem.GetFile(path).OpenRead())
                            using (var reader = new BinaryReader(stream))
                            {
                                var count = reader.ReadInt32();
                                for (var index = 0; index < count; index++)
                                {
                                    var key   = reader.ReadString();
                                    var value = reader.ReadString();
                                    Set(key, value);
                                }
                            }

                        _log.Information($"Loaded settings from '{path.FullPath}'.");
                    }
                    catch (Exception ex)
                    {
                        _log.Error(ex, $"An error occured while loading settings from '{path.FullPath}'.");
                    }
                }
                else
                {
                    // Set the default settings.
                    this.Set(Constants.Settings.General.CheckForUpdates, true);
                    this.Set(Constants.Settings.General.IncludePreviews, false);

                    // Save the default settings.
                    Save();
                }
            }
        }
Ejemplo n.º 7
0
        public override async Task <IEnumerable <IQueryResult> > Query(Query query, bool fallback)
        {
            Ensure.NotNull(query, nameof(query));

            if (string.IsNullOrWhiteSpace(query.Argument))
            {
                var uri = new Uri("https://google.com");
                return(new[]
                {
                    (IQueryResult) new GoogleResult(
                        uri, true, "Open Google in browser",
                        uri.AbsoluteUri, 0, 0)
                });
            }

            if (fallback)
            {
                return(new[] { GoogleResult.Create(query, description: $"Search Google for '{query.Argument}'") });
            }

            try
            {
                var uri    = $"https://www.google.com/complete/search?output=chrome&q={WebUtility.UrlEncode(query.Argument)}";
                var result = await _client.GetAsync(uri);

                if (result.IsSuccessStatusCode)
                {
                    var data = await result.Content.ReadAsStringAsync();

                    var queryResults = JArray.Parse(data)[1].Where(x => x.Type == JTokenType.String).Select(x => x.Value <string>());
                    return(queryResults.Select(x => GoogleResult.Create(query, x)));
                }
            }
            catch (Exception e)
            {
                _log.Error(e, "An error occured while querying Google.");
            }

            return(null);
        }
Ejemplo n.º 8
0
        public AppxManifest Read(FilePath path)
        {
            var root = path.GetDirectory();

            // Get the stream to the manifest file.
            var stream = _streamProvider.GetStream(path);

            if (stream == null)
            {
                _log.Error($"Could not get stream for '{path.FullPath}'.");
                return(null);
            }

            try
            {
                var appx   = new AppxPackagingInterop.AppxFactory() as AppxPackagingInterop.IAppxFactory;
                var reader = appx.CreateManifestReader(stream);

                var identity = reader.GetPackageId().GetPackageFullName();

                // Read manifest properties.
                var properties = reader.GetProperties();
                var manifest   = new AppxManifest
                {
                    Id          = reader.GetPackageId().GetName(),
                    DisplayName = ParseString(identity, () => properties.ReadString("DisplayName")),
                    Description = ParseString(identity, () => properties.ReadString("Description")),
                    Publisher   = ParseString(identity, () => properties.ReadString("PublisherDisplayName")),
                    Logo        = ParseImage(root, () => properties.ReadString("Logo"))
                };

                // Read information about applications.
                var applications = reader.GetApplications();
                while (applications.GetHasCurrent() != 0)
                {
                    var app = applications.GetCurrent();

                    // Create the application representation.
                    var application = new AppxManifestApplication
                    {
                        Id              = ParseString(identity, () => app.ReadString("Id")),
                        AppUserModelId  = app.GetAppUserModelId(),
                        ShortName       = ParseString(identity, () => app.ReadString("ShortName")),
                        DisplayName     = ParseString(identity, () => app.ReadString("DisplayName")),
                        Logo            = ParseImage(root, () => app.ReadString("Logo")),
                        SmallLogo       = ParseImage(root, () => app.ReadString("SmallLogo")),
                        BackgroundColor = ParseString(identity, () => app.ReadString("BackgroundColor") ?? "Transparent"),
                        EntryPoint      = ParseString(identity, () => app.ReadString("EntryPoint")),
                        Executable      = ParseString(identity, () => app.ReadString("Executable")),
                        StartPage       = ParseString(identity, () => app.ReadString("StartPage"))
                    };

                    // Parse images.
                    ParseImage(root, () => app.ReadString("Square310x310Logo"), img => application.Images.Add(img));
                    ParseImage(root, () => app.ReadString("Square150x150Logo"), img => application.Images.Add(img));
                    ParseImage(root, () => app.ReadString("Square70x70Logo"), img => application.Images.Add(img));
                    ParseImage(root, () => app.ReadString("Square30x30Logo"), img => application.Images.Add(img));

                    manifest.Applications.Add(application);
                    applications.MoveNext();
                }

                return(manifest);
            }
            finally
            {
                // Release the stream.
                _streamProvider.ReleaseStream(stream);
            }
        }