Skip to content

Commit

Permalink
修正notion调整导致的无法上传
Browse files Browse the repository at this point in the history
修正部分图片无法正确读取上传
  • Loading branch information
aiqinxuancai committed Nov 18, 2021
1 parent 79b90a3 commit bff45ca
Show file tree
Hide file tree
Showing 6 changed files with 752 additions and 57 deletions.
1 change: 1 addition & 0 deletions EvernoteToNotionChrome/EvernoteToNotionChrome.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
<PackageReference Include="Newtonsoft.Json">
<Version>12.0.3</Version>
</PackageReference>
<PackageReference Include="SixLabors.ImageSharp" Version="1.0.4" />
<PackageReference Include="System.Drawing.Common" Version="5.0.1" />
</ItemGroup>
</Project>
59 changes: 44 additions & 15 deletions EvernoteToNotionChrome/MainWindow.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -6,32 +6,61 @@
xmlns:local="clr-namespace:EvernoteToNotionChrome" xmlns:wpf="clr-namespace:CefSharp.Wpf;assembly=CefSharp.Wpf"
xmlns:mah="clr-namespace:MahApps.Metro.Controls;assembly=MahApps.Metro"
mc:Ignorable="d"
Title="EvernoteToNotionChrome" Height="720" Width="1080" Loaded="Window_Loaded" AllowDrop="True">
Title="EvernoteToNotionChrome" Height="720" Width="1080" Loaded="Window_Loaded" AllowDrop="True"
x:Name="Self">

<mah:MetroWindow.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/Style/AQButton.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</mah:MetroWindow.Resources>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="941*"/>
<ColumnDefinition Width="139*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="90"/>
<RowDefinition Height="50"/>
<RowDefinition Height="24"/>
</Grid.RowDefinitions>
<Grid Grid.Row="1" Margin="10,10,10,10">
<Grid Grid.Row="1" Margin="10,10,10,10" Grid.ColumnSpan="2">
<Grid >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="140"/>
</Grid.ColumnDefinitions>


<Button Grid.Column="1" x:Name="ButtonStart" Content="Start" Click="ButtonStart_Click" Margin="10,0,0,0" Height="40" Width="100"></Button>
<Button Grid.Column="1" x:Name="ButtonTest" Content="Test" Click="ButtonTest_Click" Margin="10,0,0,0" Height="40" Width="100"></Button>

<StackPanel>
<TextBlock Text="请粘贴Everonte导出的HTML所在目录"></TextBlock>
<TextBox x:Name="TextBoxPath" Text="" Margin="0,5,0,0" Height="26"/>
<TextBlock x:Name="TextBlockStatus" Text="等待开始..." Margin="0,5,0,0" ></TextBlock>

</StackPanel>
</Grid>
</Grid>
<Grid Grid.Row="1" Height="1" Grid.ColumnSpan="2" VerticalAlignment="Top" Background="#0C000000">

</Grid>
<Grid Grid.Row="1">
<Border CornerRadius="4" Background="#0C000000" Grid.RowSpan="1" Grid.Row="1" Margin="10,10,0,10" >
<Grid>
<TextBox Text="" Grid.Row="1" x:Name="TextBoxPath"
mah:ControlsHelper.FocusBorderThickness="0"
mah:ControlsHelper.FocusBorderBrush="Transparent"
mah:ControlsHelper.MouseOverBorderBrush="Transparent"
Background="Transparent"
AllowDrop="True"
BorderBrush="#00CCCCCC" mah:TextBoxHelper.Watermark="请粘贴Everonte导出的HTML所在目录" HorizontalAlignment="Stretch" Margin="0,0,100,0" VerticalAlignment="Center" />

<wpf:ChromiumWebBrowser Grid.Row="0" x:Name="Browser" AllowDrop="True" Grid.RowSpan="1" Loaded="Browser_Loaded" />
<CheckBox x:Name="OverwriteCheckBox" IsChecked="{Binding Path=Overwrite, Mode=TwoWay}" HorizontalAlignment="Right" VerticalAlignment="Center" Content="覆盖文件" Margin="0,0,5,0" Foreground="#E5000000" ></CheckBox>
</Grid>

</Border>
</Grid>
<Grid Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="2" Background="#0C000000">
<TextBlock x:Name="TextBlockStatus" Text="等待开始..." Margin="10,0,10,0" VerticalAlignment="Center" Foreground="#CC000000" ></TextBlock>
</Grid>

<Grid Grid.Row="1" Grid.Column="1">
<Button Grid.Column="1" x:Name="ButtonStart" Style="{StaticResource AQButtonBlue}" Content="Start" Click="ButtonStart_Click" Margin="10,0,0,0" Height="40" Width="120"></Button>
<!--<Button Grid.Column="1" x:Name="ButtonTest" Content="Test" Click="ButtonTest_Click" Margin="10,0,0,0" Height="40" Width="100"></Button>-->
</Grid>
<wpf:ChromiumWebBrowser Grid.Row="0" x:Name="Browser" AllowDrop="True" Grid.RowSpan="2" Loaded="Browser_Loaded" Grid.ColumnSpan="2" Margin="0,0,0,90" />
</Grid>
</mah:MetroWindow>
10 changes: 8 additions & 2 deletions EvernoteToNotionChrome/MainWindow.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,19 @@ namespace EvernoteToNotionChrome
/// </summary>
public partial class MainWindow : MetroWindow
{
public static MainWindow SingleInstance { set; get; }
public static MainWindow Instance { set; get; }

public bool Overwrite { set; get; } = false;

public MainWindow()
{
SingleInstance = this;
Instance = this;



InitializeComponent();
OverwriteCheckBox.DataContext = this;


BrowserSettings browserSettings = new BrowserSettings();
browserSettings.Javascript = CefSharp.CefState.Enabled;
Expand Down
123 changes: 93 additions & 30 deletions EvernoteToNotionChrome/Service/HtmlManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,33 +23,52 @@ public static void UploadHtmlData(string filePath)
var path = Path.GetDirectoryName(filePath);
var savePath = path + @"\Replace\" + Path.GetFileName(filePath);

if (File.Exists(savePath))
if (!MainWindow.Instance.Overwrite && File.Exists(savePath))
{
//已经存在 不继续处理
return;
}


if (!Directory.Exists(path + @"\Replace\"))
{
Directory.CreateDirectory(path + @"\Replace\");
}

List<string> imageList = new List<string>();

List<string> fileList = new List<string>();

//处理img标签
var nodes = doc.DocumentNode.SelectNodes("//img");

if (nodes == null)
{
File.WriteAllText(path + @"\Replace\" + Path.GetFileName(filePath), File.ReadAllText(filePath));
return;
}

GlobalNotification.Default.Post(GlobalNotification.NotificationOutputLogInfo, $"处理HTML:{filePath}");

Debug.WriteLine($"开始路径{filePath}");
Debug.WriteLine($"找到图片{nodes.Count}个");

List<string> imageList = GetDocAllImageLabel(path, nodes);
List<string> fileList = GetDocAllFileLabel(nodes);
FixTodoListNode(path, nodes);

//上传所有图片并替换到html文件中
var docString = UploadAllImage(imageList, path, doc.DocumentNode.OuterHtml);

//a标签判定为文件类型,不上传
//docString = UploadAllImage(fileList, path, docString);

File.WriteAllText(savePath, docString);

}

/// <summary>
/// 获取全部
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
private static List<string> GetDocAllImageLabel(string path, HtmlNodeCollection nodes)
{
List<string> imageList = new List<string>();
foreach (HtmlNode link in nodes)
{
HtmlAttribute src = link.Attributes["src"];
Expand All @@ -58,16 +77,15 @@ public static void UploadHtmlData(string filePath)
continue;
}

GlobalNotification.Default.Post(GlobalNotification.NotificationOutputLogInfo, $"处理IMAGE标签:{src.Value}" );

if (link.ParentNode.Name == "a")
if (link.ParentNode.Name == "a") //上级node是a标签,文件类型,不按照图片处理;
{
Debug.WriteLine("上级node是a标签,文件类型,不按照图片处理");
HtmlNode parentNode = link.ParentNode;
string href = parentNode.Attributes["href"].Value; //文件路径
fileList.Add(href);
continue;
}
else if (!src.Value.Contains("en_todo"))
else if (src.Value.Contains("en_todo"))
{
continue;
}
else
{
//读取图片尺寸并替换到image标签,让notion识别宽高
var fullFilePath = path + @"\" + src.Value.Replace(@"/", @"\");
Expand All @@ -77,22 +95,60 @@ public static void UploadHtmlData(string filePath)
//如果上级是a标签,则不处理,后续按照a标签处理
imageList.Add(src.Value);
}
else
{
ConversionTodoList(link, path, src.Value);
}
}
return imageList;
}

//上传所有图片并替换到html文件中
var docString = UploadAllImage(imageList, path, doc.DocumentNode.OuterHtml);

docString = UploadAllImage(fileList, path, docString);

/// <summary>
/// 获取全部文件
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
private static List<string> GetDocAllFileLabel(HtmlNodeCollection nodes)
{
List<string> fileList = new List<string>();
foreach (HtmlNode link in nodes)
{
HtmlAttribute src = link.Attributes["src"];
if (src == null)
{
continue;
}

Debug.WriteLine(doc.DocumentNode.OuterHtml);
if (link.ParentNode.Name == "a") //上级node是a标签,文件类型,不按照图片处理;
{
HtmlNode parentNode = link.ParentNode;
string href = parentNode.Attributes["href"].Value; //文件路径
fileList.Add(href);
}
}
return fileList;
}

File.WriteAllText(savePath, doc.DocumentNode.OuterHtml);
/// <summary>
/// 修复todolist
/// </summary>
/// <param name="doc"></param>
/// <returns></returns>
private static void FixTodoListNode(string path, HtmlNodeCollection nodes)
{
foreach (HtmlNode link in nodes)
{
HtmlAttribute src = link.Attributes["src"];
if (src == null)
{
continue;
}

if (link.ParentNode.Name == "a")
{
continue;
}
else if (src.Value.Contains("en_todo"))
{
ConversionTodoList(link, path, src.Value);
}
}
}

static Size GetImageSize(string path)
Expand Down Expand Up @@ -127,12 +183,20 @@ private static string UploadAllImage(List<string> imageList, string path, string
{
continue; //失败
}
result = result.Substring(0, result.IndexOf("?Content-Type="));
Debug.WriteLine(docString);
//result = result.Substring(0, result.IndexOf("?Content-Type="));
var index = result.IndexOf("?Content-Type=");
if (index == -1)
{
index = result.IndexOf("?X-Amz");
}

result = result.Substring(0, index);
Debug.WriteLine("最后上传地址:" + result);
//替换
if (!string.IsNullOrEmpty(result))
{
docString = docString.Replace(file, result);
Debug.WriteLine("替换地址:" + file + " -> " + result);
}

}
Expand All @@ -143,7 +207,6 @@ private static string UploadAllImage(List<string> imageList, string path, string

private static void ConversionTodoList(HtmlNode node, string basePath, string path)
{

var parentNode = node.ParentNode;
var fullFilePath = basePath + @"\" + path.Replace(@"/", @"\");
node.ParentNode.RemoveChild(node, false); //<-- keepGrandChildren
Expand Down
51 changes: 41 additions & 10 deletions EvernoteToNotionChrome/Service/UploadManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,18 @@
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Interop;
using System.Windows.Media;

using System.Numerics;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;
using System.Windows.Media.Imaging;
using System.IO;

namespace EvernoteToNotionChrome.Service
{
Expand All @@ -30,29 +33,39 @@ public static async Task<string> UploadFile(string filePath)
LastUploadFileUrl = "";

bool hasError = false;
MainWindow.SingleInstance.Dispatcher.Invoke(() => {

Debug.WriteLine($"开始上传{filePath}");

MainWindow.Instance.Dispatcher.Invoke(() => {
try
{
BitmapSource bSource = new BitmapImage(new Uri(filePath));
Clipboard.SetImage(bSource);
MainWindow.SingleInstance.Browser.Paste();
using (Image image =Image.Load(filePath)) //使用imagesharp减少错误
{
MemoryStream memoryStream = new MemoryStream();
image.SaveAsPng(memoryStream);
BitmapSource bSource = BitmapToBitmapImage(new System.Drawing.Bitmap(memoryStream));
Clipboard.SetImage(bSource);
MainWindow.Instance.Browser.Paste();
}
}
catch (NotSupportedException ex)
{
//filePath不是图片
Debug.WriteLine(ex);
//Debug.WriteLine(ex);
Debug.WriteLine("此文件不是图片");
StringCollection list = new ();
list.Add(filePath);
Debug.WriteLine("设置文件到剪贴板");

//Clipboard.SetFileDropList(list);
//MainWindow.SingleInstance.Browser.Paste();

//Core.DragData.Create()
//IDragData dragData = DragData.Create();
//dragData.FileName = filePath;
//dragData.IsFile = true;

//MainWindow.SingleInstance.Browser.GetBrowserHost().GetWindowHandle()
Win32Drap.SendFileDrop(new WindowInteropHelper(MainWindow.SingleInstance).Handle, filePath, 550, 400);
//Win32Drap.SendFileDrop(new WindowInteropHelper(MainWindow.SingleInstance).Handle, filePath, 550, 400);

//((IRenderWebBrowser)MainWindow.SingleInstance.Browser).StartDragging(dragData, CefSharp.Enums.DragOperationsMask.Move, 550, 400);
}
Expand Down Expand Up @@ -82,6 +95,24 @@ await Task.Run(() =>
return LastUploadFileUrl;
}

// Bitmap --> BitmapImage
public static BitmapImage BitmapToBitmapImage(System.Drawing.Bitmap bitmap)
{
using (MemoryStream stream = new MemoryStream())
{
bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
stream.Position = 0;
BitmapImage result = new BitmapImage();
result.BeginInit();
// According to MSDN, "The default OnDemand cache option retains access to the stream until the image is needed."
// Force the bitmap to load right now so we can dispose the stream.
result.CacheOption = BitmapCacheOption.OnLoad;
result.StreamSource = stream;
result.EndInit();
result.Freeze();
return result;
}
}

public static void PutSuccess(string url)
{
Expand Down
Loading

0 comments on commit bff45ca

Please sign in to comment.