Skip to content

Commit

Permalink
Add convert specified files to PDF.
Browse files Browse the repository at this point in the history
  • Loading branch information
aiguoli committed Aug 24, 2023
1 parent 42eea10 commit 50b0ff3
Show file tree
Hide file tree
Showing 8 changed files with 179 additions and 0 deletions.
31 changes: 31 additions & 0 deletions Converters/FileNameToCanConvertCommandVisible.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Data;
using System;
using System.Linq;

namespace SimpleList.Converters
{
public class FileNameToCanConvertCommandVisible : IValueConverter
{
public static readonly FileNameToCanConvertCommandVisible Instance = new();
public object Convert(object value, Type targetType, object parameter, string language)
{
string[] allowedExtensions = { ".csv", ".doc", ".docx", ".odp", ".ods", ".odt", ".pot", ".potm", ".potx", ".pps", ".ppsx", ".ppsxm", ".ppt", ".pptm", ".pptx", ".rtf", ".xls", ".xlsx" };
if (value is string fileName)
{
string fileExtension = System.IO.Path.GetExtension(fileName).ToLower();
if (allowedExtensions.Contains(fileExtension))
{
return Visibility.Visible;
}
}
return Visibility.Collapsed;
}


public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
}
14 changes: 14 additions & 0 deletions Services/OneDrive.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using CommunityToolkit.Authentication;
using CommunityToolkit.Graph.Extensions;
using Downloader;
using Microsoft.Graph;
using System;
using System.Collections.Generic;
Expand Down Expand Up @@ -110,6 +111,19 @@ public async Task<Quota> GetStorageInfo()
return drive.Quota;
}

public async Task ConvertFileFormat(string itemId, StorageFile file, string format = "pdf")
{
GraphServiceClient graphClient = _provider.GetClient();
List<QueryOption> queryOptions = new()
{
new QueryOption("format", format)
};
Stream result = await graphClient.Me.Drive.Items[itemId].Content.Request(queryOptions).GetAsync();
using var fileStream = System.IO.File.Create(file.Path);
result.Seek(0, SeekOrigin.Begin);
await result.CopyToAsync(fileStream);
}

public async void Login()
{
try
Expand Down
4 changes: 4 additions & 0 deletions SimpleList.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@
<None Remove="Pages\HomePage.xaml" />
<None Remove="Pages\SettingPage.xaml" />
<None Remove="Pages\TaskManagerPage.xaml" />
<None Remove="Views\ConvertFileFormatView.xaml" />
<None Remove="Views\CreateFolderView.xaml" />
<None Remove="Views\FileView.xaml" />
<None Remove="Views\PropertyView.xaml" />
Expand Down Expand Up @@ -102,6 +103,9 @@
<Pack>True</Pack>
<PackagePath>\</PackagePath>
</None>
<Page Update="Views\ConvertFileFormatView.xaml">
<Generator>MSBuild:Compile</Generator>
</Page>
</ItemGroup>
<ItemGroup>
<Page Update="Views\ShareFileView.xaml">
Expand Down
59 changes: 59 additions & 0 deletions ViewModels/ConvertFileFormatViewModel.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.DependencyInjection;
using SimpleList.Services;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Windows.Storage.Pickers;
using Windows.Storage;
using WinRT.Interop;
using Microsoft.UI.Xaml;
using CommunityToolkit.Mvvm.Input;
using System.IO;
using System.Linq;

namespace SimpleList.ViewModels
{
public class ConvertFileFormatViewModel : ObservableObject
{
public ConvertFileFormatViewModel(FileViewModel file)
{
_file = file;
ConvertFileCommand = new AsyncRelayCommand(ConvertFileFormat);
}

public async Task ConvertFileFormat()
{
Window _downloadPathSelectWindow = new();
IntPtr hwnd = WindowNative.GetWindowHandle(_downloadPathSelectWindow);
FileSavePicker savePicker = new()
{
SuggestedStartLocation = PickerLocationId.Downloads
};
savePicker.FileTypeChoices.Add("PDF Document", new List<string>() { ".pdf" });
savePicker.SuggestedFileName = Path.GetFileNameWithoutExtension(_file.Name);
InitializeWithWindow.Initialize(savePicker, hwnd);
StorageFile file = await savePicker.PickSaveFileAsync();
SavedFilePath = file?.Path;

string fileExtension = Path.GetExtension(_file.Name).ToLower();

if (allowedExtensions.Contains(fileExtension))
{
await drive.ConvertFileFormat(_file.Id, file);
}
}

private readonly FileViewModel _file;
private readonly OneDrive drive = Ioc.Default.GetService<OneDrive>();
private static readonly string[] allowedExtensions = { ".csv", ".doc", ".docx", ".odp", ".ods", ".odt", ".pot", ".potm", ".potx", ".pps", ".ppsx", ".ppsxm", ".ppt", ".pptm", ".pptx", ".rtf", ".xls", ".xlsx" };
private string _selectedFormat = "pdf";
private string _savedFilePath;

public IEnumerable<string> TargetFormats => new List<string> { "pdf" };
public string SelectedFormat { get => _selectedFormat; set => SetProperty(ref _selectedFormat, value); }
public string SavedFilePath { get => _savedFilePath; set => SetProperty(ref _savedFilePath, value); }
public string FormattedExtensions => string.Join(", ", allowedExtensions.Select(ext => ext.TrimStart('.')));
public AsyncRelayCommand ConvertFileCommand { get; }
}
}
41 changes: 41 additions & 0 deletions Views/ConvertFileFormatView.xaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?xml version="1.0" encoding="utf-8"?>
<ContentDialog
x:Class="SimpleList.Views.ConvertFileFormatView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="using:SimpleList.ViewModels"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DataContext="{x:Bind vm:ConvertFileFormatViewModel}"
Title="Convert File Format"
PrimaryButtonText="Convert"
DefaultButton="Primary"
CloseButtonText="Cancel">

<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>

<TextBlock Margin="0 0 0 10" TextWrapping="Wrap">
<Run Text="The currently supported file formats include " />
<Run Text="{Binding FormattedExtensions}" />
</TextBlock>

<RelativePanel Grid.Row="1">
<TextBlock Text="Target Format" FontWeight="Bold" RelativePanel.AlignLeftWithPanel="True" />
<ComboBox ItemsSource="{Binding TargetFormats}" SelectedIndex="0" SelectedItem="{Binding SelectedFormat, Mode=TwoWay}" RelativePanel.AlignRightWithPanel="True" />
</RelativePanel>

<RelativePanel Grid.Row="2">
<TextBlock Text="Save Path" FontWeight="Bold" RelativePanel.AlignLeftWithPanel="True" />
<StackPanel Orientation="Horizontal" RelativePanel.AlignRightWithPanel="True">
<TextBox Text="{Binding SavedFilePath}" IsEnabled="False" />
<Button Content="Browser" Command="{Binding ConvertFileCommand}" />
</StackPanel>
</RelativePanel>
</Grid>
</ContentDialog>
12 changes: 12 additions & 0 deletions Views/ConvertFileFormatView.xaml.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
using Microsoft.UI.Xaml.Controls;

namespace SimpleList.Views
{
public sealed partial class ConvertFileFormatView : ContentDialog
{
public ConvertFileFormatView()
{
InitializeComponent();
}
}
}
4 changes: 4 additions & 0 deletions Views/FileView.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="using:SimpleList.ViewModels"
xmlns:converter="using:SimpleList.Converters"
xmlns:converters="using:CommunityToolkit.WinUI.UI.Converters"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
d:DataContext="{x:Bind vm:FileViewModel}"
Expand All @@ -13,6 +14,8 @@
<UserControl.Resources>
<converter:FileSizeConverter x:Key="FileSizeConverter" />
<converter:DateTimeOffsetToStringConverter x:Key="DateTimeOffsetToStringConverter" />
<converter:FileNameToCanConvertCommandVisible x:Key="FileNameToCanConvertCommandVisible" />
<converters:BoolToVisibilityConverter x:Key="BoolToVisibilityConverter" />
</UserControl.Resources>

<Grid DoubleTapped="OpenFolder">
Expand All @@ -21,6 +24,7 @@
<MenuFlyoutItem Text="Open" Command="{Binding Cloud.OpenFolderCommand}" CommandParameter="{Binding}" IsEnabled="{Binding IsFolder}" />
<MenuFlyoutItem Text="Download" Command="{Binding DownloadFileCommand}" CommandParameter="{Binding Id}" IsEnabled="{Binding IsFile}" />
<MenuFlyoutItem Text="Delete" Command="{Binding DeleteFileCommand}" CommandParameter="{Binding Id}" />
<MenuFlyoutItem Text="Convert" Click="ShowConverFiletDialogAsync" Visibility="{Binding Name, Converter={StaticResource FileNameToCanConvertCommandVisible}}" />
<MenuFlyoutItem Text="Share" Click="ShowShareFileDialogAsync" />
<MenuFlyoutItem Text="Rename" Click="ShowRenameFileDialogAsync" />
<MenuFlyoutItem Text="Property" Click="ShowPropertyDialogAsync" />
Expand Down
14 changes: 14 additions & 0 deletions Views/FileView.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -56,5 +56,19 @@ private void OpenFolder(object sender, Microsoft.UI.Xaml.Input.DoubleTappedRoute
viewModel.Cloud.OpenFolder(viewModel);
}
}

private async void ShowConverFiletDialogAsync(object sender, RoutedEventArgs e)
{
FileViewModel viewModel = DataContext as FileViewModel;
if (viewModel.IsFile)
{
ConvertFileFormatView dialog = new()
{
XamlRoot = XamlRoot,
DataContext = new ConvertFileFormatViewModel(viewModel)
};
await dialog.ShowAsync();
}
}
}
}

0 comments on commit 50b0ff3

Please sign in to comment.