示例#1
0
 /// <summary>
 /// Вызывается при изменении прогресса какой-либо загрузки.
 /// </summary>
 private void OnDownloadProgressChanged(DownloadOperation e)
 {
     ProgressChanged?.Invoke(this, new TransferItem
     {
         OperationGuid = e.Guid,
         Name          = GetOperationNameFromFile(e.ResultFile),
         ContentType   = GetContentTypeFromExtension(e.ResultFile.FileType),
         Status        = e.Progress.Status,
         TotalSize     = FileSize.FromBytes(e.Progress.TotalBytesToReceive),
         ProcessedSize = FileSize.FromBytes(e.Progress.BytesReceived)
     });
 }
示例#2
0
        /// <summary>
        /// Возвращает размер кэша.
        /// </summary>
        public async Task <FileSize> GetCacheSize()
        {
            try
            {
                var folder = await ApplicationData.Current.LocalFolder.GetFolderAsync(AUDIOS_FOLDER_NAME);

                var properties = await folder.GetBasicPropertiesAsync();

                return(FileSize.FromBytes(properties.Size));
            }
            catch (Exception) { return(FileSize.FromBytes(0)); }
        }
示例#3
0
        /// <summary>
        /// Возвращает размер кэша изображений альбомов треков.
        /// </summary>
        public async Task <FileSize> GetAlbumsCacheSize()
        {
            try
            {
                var folder = await ApplicationData.Current.LocalFolder.GetFolderAsync(ALBUMS_FOLDER_NAME);

                var basic = await folder.GetBasicPropertiesAsync();

                IDictionary <string, object> properties = await folder.Properties.RetrievePropertiesAsync(new[] { "System.Size" });

                return(FileSize.FromBytes((ulong)properties["System.Size"]));
            }
            catch (Exception) { return(FileSize.FromBytes(0)); }
        }
        private static FileSize EvGetSize(string path)
        {
            path = Path.GetFullPath(path);
            var output     = StartHelperAndReadOutput($"-size -a-d -size-leading-zero -no-digit-grouping -size-format 1 path:\"{path}\"");
            var allResults = output.SplitNewlines(StringSplitOptions.RemoveEmptyEntries);

            long sum = 0;

            foreach (var result in allResults)
            {
                var split = result.Split(new[] { ' ' }, 2, StringSplitOptions.None);
                sum += long.Parse(split[0]);
            }
            return(FileSize.FromBytes(sum));
        }
示例#5
0
        public async void ContinueFileOpenPicker(IReadOnlyList <StorageFile> files)
        {
            try
            {
                if (files != null && files.Count > 0)
                {
                    SelectedFile = files[0];
                }
                else
                {
                    SelectedFile      = null;
                    SelectedFileImage = null;
                    return;
                }

                try
                {
                    var properties = await SelectedFile.GetBasicPropertiesAsync();

                    SelectedFileName = SelectedFile.DisplayName;
                    SelectedFileSize = FileSize.FromBytes(properties.Size);
                    SelectedFileType = SelectedFile.DisplayType;
                }
                catch (Exception)
                {
                    SelectedFile      = null;
                    SelectedFileImage = null;
                    return;
                }

                try
                {
                    var img = await SelectedFile.GetThumbnailAsync(ThumbnailMode.SingleItem, 256);

                    SelectedFileImage = new BitmapImage();
                    await SelectedFileImage.SetSourceAsync(img);
                }
                catch (Exception)
                {
                    SelectedFileImage = null;
                }
            }
            finally
            {
                UploadFileCommand.RaiseCanExecuteChanged();
                _appLoaderService.Hide();
            }
        }
示例#6
0
        public async Task <FileSize> GetFileSize(string url)
        {
            try
            {
                var request = WebRequest.Create(url);
                request.Method = "HEAD";

                var response = await request.GetResponseAsync();

                return(FileSize.FromBytes((ulong)response.ContentLength));
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException("Не удалось получить данные о размере файла.", ex);
            }
        }
示例#7
0
 /// <summary>
 /// Возвращает массив со всеми выполняющимися загрузками.
 /// </summary>
 public TransferItem[] GetAllDownloads()
 {
     if (_downloads.Count == 0)
     {
         return(null);
     }
     return(_downloads.Select(e => new TransferItem
     {
         OperationGuid = e.Guid,
         Name = GetOperationNameFromFile(e.ResultFile),
         ContentType = GetContentTypeFromExtension(e.ResultFile.FileType),
         Status = e.Progress.Status,
         TotalSize = FileSize.FromBytes(e.Progress.TotalBytesToReceive),
         ProcessedSize = FileSize.FromBytes(e.Progress.BytesReceived)
     }).ToArray());
 }
示例#8
0
        public IEnumerable <TransferItem> GetAllUploads()
        {
            if (_uploads.Count == 0)
            {
                return(null);
            }

            return(_uploads.Select(e => new TransferItem
            {
                OperationGuid = e.Key.Guid,
                Name = e.Value.Name,
                ContentType = e.Value.ContentType,
                Status = e.Key.Progress.Status,
                TotalSize = FileSize.FromBytes(e.Key.Progress.TotalBytesToReceive),
                ProcessedSize = FileSize.FromBytes(e.Key.Progress.BytesReceived)
            }));
        }
示例#9
0
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            FileSize size;

            if (value is int)
            {
                size = FileSize.FromBytes((ulong)(int)value);
            }
            else if (value is FileSize)
            {
                size = (FileSize)value;
            }
            else
            {
                return(null);
            }

            if (size.Kilobytes < 1024)
            {
                return(String.Format(_locService.Value["FileSize_KB_Mask_Text"], size.Kilobytes));
            }
            else if (size.Megabytes >= 1 && size.Megabytes < 1024)
            {
                return(String.Format(_locService.Value["FileSize_MB_Mask_Text"], Math.Round(size.Megabytes, 2)));
            }
            else if (size.Gigabytes >= 1 && size.Gigabytes < 1024)
            {
                return(String.Format(_locService.Value["FileSize_GB_Mask_Text"], Math.Round(size.Gigabytes, 2)));
            }
            else if (size.Terabytes >= 1 && size.Terabytes < 1024)
            {
                return(String.Format(_locService.Value["FileSize_TB_Mask_Text"], Math.Round(size.Terabytes, 2)));
            }
            else if (size.Petabytes >= 1 && size.Petabytes < 1024)
            {
                return(String.Format(_locService.Value["FileSize_PB_Mask_Text"], Math.Round(size.Petabytes, 2)));
            }
            else if (size.Exabytes >= 1 && size.Exabytes < 1024)
            {
                return(String.Format(_locService.Value["FileSize_EB_Mask_Text"], Math.Round(size.Exabytes, 2)));
            }
            else
            {
                return(String.Format(_locService.Value["FileSize_Bytes_Mask_Text"], size.Bytes));
            }
        }
        private static DataTable ExtractFileInfo(ApplicationUninstallerEntry tag)
        {
            if (string.IsNullOrEmpty(tag.UninstallerFullFilename))
            {
                throw new InvalidOperationException(Localisable.PropertiesWindow_Table_ErrorMissingUninstaller);
            }

            var fi = new FileInfo(tag.UninstallerFullFilename);

            if (!fi.Exists)
            {
                if (tag.UninstallerKind == UninstallerType.Msiexec)
                {
                    throw new NotSupportedException(Localisable.PropertiesWindow_Table_ErrorMsi);
                }
                throw new IOException(Localisable.PropertiesWindow_Table_ErrorDoesntExist);
            }

            // Basic filesystem information
            var lq = fi.GetAttributes().Where(a => !a.Key.Equals(nameof(FileInfo.Directory))).Select(x =>
            {
                if (x.Key.Equals(nameof(FileInfo.Length)))
                {
                    return(new SingleProperty(x.Key, FileSize.FromBytes((long)x.Value).ToString(true)));
                }
                return(x);
            });

            // Extra information from resources
            var verInfo = FileVersionInfo.GetVersionInfo(fi.FullName);

            lq = lq.Concat(typeof(FileVersionInfo).GetProperties(BindingFlags.Instance | BindingFlags.Public)
                           .Where(p => !p.Name.EndsWith("Part") && !p.Name.Equals(nameof(FileVersionInfo.FileName)))
                           .Select(p => new SingleProperty(p.Name, p.GetValue(verInfo, null))));

            // Create and return the table
            var dt = GetCleanDataTable();

            ConvertPropertiesIntoDataTable(lq, dt);
            return(dt);
        }
        private static IEnumerable <ApplicationUninstallerEntry> GetUpdates()
        {
            if (!HelperIsAvailable)
            {
                yield break;
            }

            var output = SteamFactory.StartProcessAndReadOutput(HelperPath, "list");

            if (string.IsNullOrEmpty(output) || output.Contains("error", StringComparison.OrdinalIgnoreCase))
            {
                yield break;
            }

            foreach (var group in ProcessInput(output))
            {
                var entry = new ApplicationUninstallerEntry
                {
                    UninstallerKind = UninstallerType.WindowsUpdate,
                    IsUpdate        = true,
                    Publisher       = "Microsoft Corporation"
                };
                foreach (var valuePair in group)
                {
                    switch (valuePair.Key)
                    {
                    case "UpdateID":
                        entry.RatingId = valuePair.Value;
                        Guid result;
                        if (GuidTools.TryExtractGuid(valuePair.Value, out result))
                        {
                            entry.BundleProviderKey = result;
                        }
                        break;

                    case "RevisionNumber":
                        entry.DisplayVersion = valuePair.Value;
                        break;

                    case "Title":
                        entry.RawDisplayName = valuePair.Value;
                        break;

                    case "IsUninstallable":
                        bool isUnins;
                        if (bool.TryParse(valuePair.Value, out isUnins))
                        {
                            entry.IsValid = isUnins;
                        }
                        break;

                    case "SupportUrl":
                        entry.AboutUrl = valuePair.Value;
                        break;

                    case "MinDownloadSize":
                        long size;
                        if (long.TryParse(valuePair.Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out size))
                        {
                            entry.EstimatedSize = FileSize.FromBytes(size);
                        }
                        break;

                    case "LastDeploymentChangeTime":
                        DateTime date;
                        if (DateTime.TryParse(valuePair.Value, CultureInfo.InvariantCulture, DateTimeStyles.None, out date) &&
                            !DateTime.MinValue.Equals(date))
                        {
                            entry.InstallDate = date;
                        }
                        break;
                    }
                }

                if (entry.IsValid)
                {
                    entry.UninstallString      = $"\"{HelperPath}\" uninstall {entry.RatingId}";
                    entry.QuietUninstallString = entry.UninstallString;
                }

                yield return(entry);
            }
        }
示例#12
0
        private void CompressFiles(IReadOnlyList <FileInfo> files, bool randomizeCab)
        {
            if (!SB3UGS_Initializer.CheckIsAvailable())
            {
                MessageBox.Show(
                    "SB3UGS has not been found in KK Manager directory or it failed to be loaded. Reinstall KK Manager and try again.",
                    "Compress files", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            LoadingDialog.ShowDialog(this, "Compressing asset bundle files", dialogInterface =>
            {
                dialogInterface.SetMaximum(files.Count);

                var excs            = new ConcurrentBag <Exception>();
                long totalSizeSaved = 0;
                var count           = 0;

                Parallel.ForEach(files, file =>
                {
                    dialogInterface.SetProgress(count++, "Compressing " + file.Name);

                    try
                    {
                        var origSize = file.Length;
                        SB3UGS_Utils.CompressBundle(file.FullName, randomizeCab);
                        file.Refresh();
                        totalSizeSaved += origSize - file.Length;
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"Failed to compress file {file.FullName} - {ex.Message}");
                        excs.Add(ex);
                    }
                });

                if (excs.Any())
                {
                    MessageBox.Show($"Successfully compressed {files.Count - excs.Count} out of {files.Count} files, see log for details. Saved {FileSize.FromBytes(totalSizeSaved).ToString()}.", "Compress files", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                else
                {
                    MessageBox.Show($"Successfully compressed {files.Count} files. Saved {FileSize.FromBytes(totalSizeSaved).ToString()}.", "Compress files", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            });
        }
        private static IEnumerable <ApplicationUninstallerEntry> GetUpdates()
        {
            if (!HelperIsAvailable)
            {
                yield break;
            }

            var output = FactoryTools.StartHelperAndReadOutput(HelperPath, "list");

            if (string.IsNullOrEmpty(output) || output.Trim().StartsWith("Error", StringComparison.OrdinalIgnoreCase))
            {
                yield break;
            }

            foreach (var group in FactoryTools.ExtractAppDataSetsFromHelperOutput(output))
            {
                var entry = new ApplicationUninstallerEntry
                {
                    UninstallerKind = UninstallerType.WindowsUpdate,
                    IsUpdate        = true,
                    Publisher       = "Microsoft Corporation"
                };
                foreach (var valuePair in group)
                {
                    switch (valuePair.Key)
                    {
                    case "UpdateID":
                        entry.RatingId = valuePair.Value;
                        if (GuidTools.TryExtractGuid(valuePair.Value, out var result))
                        {
                            entry.BundleProviderKey = result;
                        }
                        break;

                    case "RevisionNumber":
                        entry.DisplayVersion = ApplicationEntryTools.CleanupDisplayVersion(valuePair.Value);
                        break;

                    case "Title":
                        entry.RawDisplayName = valuePair.Value;
                        break;

                    case "IsUninstallable":
                        if (bool.TryParse(valuePair.Value, out var isUnins))
                        {
                            entry.IsProtected = !isUnins;
                        }
                        break;

                    case "SupportUrl":
                        entry.AboutUrl = valuePair.Value;
                        break;

                    case "MinDownloadSize":
                        if (long.TryParse(valuePair.Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var size))
                        {
                            entry.EstimatedSize = FileSize.FromBytes(size);
                        }
                        break;

                    case "MaxDownloadSize":
                        break;

                    case "LastDeploymentChangeTime":
                        if (DateTime.TryParse(valuePair.Value, CultureInfo.InvariantCulture, DateTimeStyles.None, out var date) &&
                            !DateTime.MinValue.Equals(date))
                        {
                            entry.InstallDate = date;
                        }
                        break;

                    default:
                        Debug.Fail("Unknown label");
                        break;
                    }
                }

                entry.UninstallString      = $"\"{HelperPath}\" uninstall {entry.RatingId}";
                entry.QuietUninstallString = entry.UninstallString;

                yield return(entry);
            }
        }
        private static IEnumerable <ApplicationUninstallerEntry> GetSteamApps()
        {
            if (!SteamHelperIsAvailable)
            {
                yield break;
            }

            var output = FactoryTools.StartProcessAndReadOutput(SteamHelperPath, "list");

            if (string.IsNullOrEmpty(output) || output.Contains("error", StringComparison.InvariantCultureIgnoreCase))
            {
                yield break;
            }

            foreach (var idString in output.SplitNewlines(StringSplitOptions.RemoveEmptyEntries))
            {
                int appId;
                if (!int.TryParse(idString, out appId))
                {
                    continue;
                }

                output = FactoryTools.StartProcessAndReadOutput(SteamHelperPath,
                                                                "info " + appId.ToString("G"));
                if (string.IsNullOrEmpty(output) ||
                    output.Contains("error", StringComparison.InvariantCultureIgnoreCase))
                {
                    continue;
                }

                var lines = output.SplitNewlines(StringSplitOptions.RemoveEmptyEntries).Select(x =>
                {
                    var o = x.Split(new[] { " - " }, StringSplitOptions.None);
                    return(new KeyValuePair <string, string>(o[0], o[1]));
                }).ToList();

                var entry = new ApplicationUninstallerEntry
                {
                    DisplayName =
                        lines.Single(x => x.Key.Equals("Name", StringComparison.InvariantCultureIgnoreCase)).Value,
                    UninstallString =
                        lines.Single(x => x.Key.Equals("UninstallString", StringComparison.InvariantCultureIgnoreCase))
                        .Value,
                    InstallLocation =
                        lines.Single(x => x.Key.Equals("InstallDirectory", StringComparison.InvariantCultureIgnoreCase))
                        .Value,
                    UninstallerKind = UninstallerType.Steam,
                    IsValid         = true,
                    IsOrphaned      = true,
                    RatingId        = "Steam App " + appId.ToString("G")
                };

                long bytes;
                if (
                    long.TryParse(
                        lines.Single(x => x.Key.Equals("SizeOnDisk", StringComparison.InvariantCultureIgnoreCase)).Value,
                        out bytes))
                {
                    entry.EstimatedSize = FileSize.FromBytes(bytes);
                }

                yield return(entry);
            }
        }
示例#15
0
        public IList <ApplicationUninstallerEntry> GetUninstallerEntries(
            ListGenerationProgress.ListGenerationCallback progressCallback)
        {
            var results = new List <ApplicationUninstallerEntry>();

            if (!SteamHelperIsAvailable)
            {
                return(results);
            }

            var output = FactoryTools.StartHelperAndReadOutput(SteamHelperPath, "list");

            if (string.IsNullOrEmpty(output) || output.Contains("error", StringComparison.InvariantCultureIgnoreCase))
            {
                return(results);
            }

            foreach (var idString in output.SplitNewlines(StringSplitOptions.RemoveEmptyEntries))
            {
                if (!int.TryParse(idString, out var appId))
                {
                    continue;
                }

                output = FactoryTools.StartHelperAndReadOutput(SteamHelperPath, "info " + appId.ToString("G"));

                if (string.IsNullOrEmpty(output))
                {
                    continue;
                }

                var lines = output.SplitNewlines(StringSplitOptions.RemoveEmptyEntries).Select(x =>
                {
                    var o = x.Split(new[] { " - " }, StringSplitOptions.None);
                    return(new KeyValuePair <string, string>(o[0], o[1]));
                }).ToList();

                string GetValue(string fieldName)
                {
                    return(lines.Single(x => x.Key.Equals(fieldName, StringComparison.InvariantCultureIgnoreCase)).Value);
                }

                var entry = new ApplicationUninstallerEntry
                {
                    DisplayName     = GetValue("Name"),
                    UninstallString = GetValue("UninstallString"),
                    InstallLocation = GetValue("InstallDirectory"),
                    UninstallerKind = UninstallerType.Steam,
                    IsValid         = true,
                    IsOrphaned      = true,
                    RatingId        = "Steam App " + appId.ToString("G")
                };

                if (long.TryParse(GetValue("SizeOnDisk"), out var bytes))
                {
                    entry.EstimatedSize = FileSize.FromBytes(bytes);
                }

                results.Add(entry);
            }

            return(results);
        }