Skip to content

Commit

Permalink
feat(plugins/qqnoteplugin/): 支持图片
Browse files Browse the repository at this point in the history
  • Loading branch information
yiyungent committed May 9, 2022
1 parent f62913d commit 4c17493
Show file tree
Hide file tree
Showing 6 changed files with 166 additions and 15 deletions.
114 changes: 111 additions & 3 deletions plugins/QQNotePlugin/QQNotePlugin.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@
using System.Text;
using Octokit;
using System.Linq;
using Konata.Core.Message.Model;
using Konata.Core.Message;
using System.Collections.Generic;
using System.IO;

namespace QQNotePlugin
{
Expand Down Expand Up @@ -43,19 +47,24 @@ public void OnFriendMessage((Bot s, FriendMessageEvent e) obj, string message, u
if (settingsModel.AllowFriends != null && settingsModel.AllowFriends.Count >= 1 && settingsModel.AllowFriends.Contains(friendUin.ToString()))
{
Console.WriteLine($"{nameof(QQNotePlugin)}: {message}");

string flagStr = "note";

#region 过滤消息
if (!message.Trim().StartsWith(flagStr))
{
return;
}
#endregion

string fullMessageText = "";
Dictionary<string, byte[]> imageDic = new Dictionary<string, byte[]>();

#region 组织新文件内容
try
{
StringBuilder fullMessageSb = new StringBuilder();
foreach (var chain in obj.e.Message.Chain)
foreach (BaseChain chain in obj.e.Message.Chain)
{
switch (chain.Type)
{
Expand All @@ -67,6 +76,80 @@ public void OnFriendMessage((Bot s, FriendMessageEvent e) obj, string message, u
fullMessageSb.AppendLine(chain.ToString());
break;
case Konata.Core.Message.BaseChain.ChainType.Image:
#region 笔记中的图片
try
{
ImageChain imageChain = (ImageChain)chain;
byte[] imageBytes = null;
if (imageChain.FileData != null && imageChain.FileData.Length > 0)
{
imageBytes = imageChain.FileData;
}
else if (!string.IsNullOrEmpty(imageChain.ImageUrl))
{
imageBytes = Utils.HttpUtil.HttpDownloadFile(imageChain.ImageUrl);
}
if (imageBytes == null || imageBytes.Length <= 0)
{
continue;
}
string imageBase64 = Convert.ToBase64String(imageBytes);
string imageType = "jpeg";
switch (imageChain.ImageType)
{
case ImageType.Invalid:
break;
case ImageType.Face:
break;
case ImageType.Jpg:
imageType = "jpeg";
break;
case ImageType.Png:
imageType = "png";
break;
case ImageType.Webp:
imageType = "webp";
break;
case ImageType.Pjpeg:
imageType = "jpeg";
break;
case ImageType.Sharpp:
break;
case ImageType.Bmp:
imageType = "bmp";
break;
case ImageType.Gif:
imageType = "gif";
break;
case ImageType.Apng:
imageType = "apng";
break;
default:
imageType = "jpeg";
break;
}

#region 图片 base64 形式
// 由于 GitHub 不支持直接显示 base64 图片, 因此改为上传图片文件
//string imgBase64Html = $"<img src=\"data:image/{imageType};base64,{imageBase64}\" />";
//fullMessageSb.AppendLine(imgBase64Html);
#endregion

#region 图片文件形式
string dirName = Path.GetFileNameWithoutExtension(settingsModel.GitHub.RepoTargetFilePath);
string imageFileName = $"image-{DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss")} {imageBytes.GetHashCode()}.{imageType}";
string imageHtml = $"<img src=\"{dirName}/{imageFileName}\" />";
imageDic.Add($"{dirName}/{imageFileName}", imageBytes);
fullMessageSb.AppendLine(imageHtml);
#endregion
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
obj.s.SendFriendMessage(friendUin, $"笔记中的图片获取失败:");
obj.s.SendFriendMessage(friendUin, $"{ex.ToString()}");
}
#endregion
break;
case Konata.Core.Message.BaseChain.ChainType.Flash:
break;
Expand All @@ -88,6 +171,7 @@ public void OnFriendMessage((Bot s, FriendMessageEvent e) obj, string message, u
break;
}
}

fullMessageText = fullMessageSb.ToString();

if (string.IsNullOrEmpty(fullMessageText))
Expand All @@ -96,7 +180,7 @@ public void OnFriendMessage((Bot s, FriendMessageEvent e) obj, string message, u
return;
}

fullMessageText = fullMessageText.Substring(flagStr.Length).Trim();
fullMessageText = fullMessageText.Trim().Substring(flagStr.Length).Trim();

Console.WriteLine($"{nameof(QQNotePlugin)}.fullMessageText: {fullMessageText}");
}
Expand All @@ -118,20 +202,43 @@ public void OnFriendMessage((Bot s, FriendMessageEvent e) obj, string message, u
string branch = settingsModel.GitHub.RepoBranch;
string targetFilePath = settingsModel.GitHub.RepoTargetFilePath;

#region 写入笔记
try
{
#region 上传笔记中的图片
foreach (var item in imageDic)
{
try
{
string imageFilePath = Path.Combine(Path.GetDirectoryName(targetFilePath), item.Key);
var createImageSet = gitHubClient.Repository.Content.CreateFile(owner, repo, imageFilePath,
new CreateFileRequest(message: $"{nameof(QQNotePlugin)}-{DateTime.Now.ToString("yyyy-MM-dd HH-mm:ss")}",
content: Convert.ToBase64String(item.Value), branch: branch, convertContentToBase64: false))
.Result;
}
catch (Exception ex)
{
obj.s.SendFriendMessage(friendUin, "笔记中的图片写入失败:");
obj.s.SendFriendMessage(friendUin, ex.ToString());
}
}
#endregion

#region 写入笔记文件
// try to get the file (and with the file the last commit sha)
var existingFile = gitHubClient.Repository.Content.GetAllContentsByRef(owner, repo, targetFilePath, branch).Result;
string oldFileContent = existingFile.First().Content;

// 新文件内容: 在旧的 后面换行 +
string newFileContent = $"{oldFileContent}\n{fullMessageText}";
fullMessageText = $" \n{fullMessageText} \n";
string newFileContent = $"{oldFileContent} \n--- \n{fullMessageText}";

// update the file
var updateChangeSet = gitHubClient.Repository.Content.UpdateFile(owner, repo, targetFilePath,
new UpdateFileRequest(message: $"{nameof(QQNotePlugin)}-{DateTime.Now.ToString("yyyy-MM-dd HH-mm:ss")}",
content: newFileContent, sha: existingFile.First().Sha, branch: branch))
.Result;
#endregion

obj.s.SendFriendMessage(friendUin, "笔记写入成功");
}
Expand All @@ -143,6 +250,7 @@ public void OnFriendMessage((Bot s, FriendMessageEvent e) obj, string message, u

obj.s.SendFriendMessage(friendUin, "笔记写入失败");
}
#endregion

#endregion

Expand Down
12 changes: 9 additions & 3 deletions plugins/QQNotePlugin/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,17 @@

1. 前往此处获取 `GitHub Personal Access Token`, [点我前往](https://github.com/settings/tokens/new) , 注意: 一定要勾选 `repo Full control of private repositories`

`RepoTargetFilePath` 为笔记写入文件路径, 此文件路径需先存在
> `RepoTargetFilePath` 为笔记写入文件路径 (相对于此仓库根目录), 此文件路径需先存在, 例如: `source/_posts/分类-杂记/杂记-来自QQ.md`
2. 设置 `AllowFriends`

3. 使用 `AllowFriends` 中的 QQ 号给机器人发送 `note 笔记内容`, 即可写入笔记

### 设置 `AllowFriends`

> 设置 `AllowFriends`
### 写笔记

> 使用 `AllowFriends` 中的 QQ 号给机器人发送 `note 笔记内容`, 即可写入笔记


Expand Down
37 changes: 37 additions & 0 deletions plugins/QQNotePlugin/Utils/HttpUtil.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace QQNotePlugin.Utils
{
public class HttpUtil
{
#region HTTP下载文件
/// <summary>
/// HTTP 下载文件
/// </summary>
public static byte[] HttpDownloadFile(string url)
{
// 设置参数
HttpClient client = new HttpClient();

byte[] rtn = null;
try
{
rtn = client.GetByteArrayAsync(url).Result;
}
catch (Exception ex)
{

}

return rtn;
}
#endregion
}
}
4 changes: 2 additions & 2 deletions plugins/QQNotePlugin/info.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"PluginId": "QQNotePlugin",
"DisplayName": "QQNotePlugin",
"Description": "QQNotePlugin",
"DisplayName": "QQ写笔记",
"Description": "利用 QQ 写笔记 (随笔/零碎知识点)",
"Author": "yiyun",
"Version": "0.1.0",
"SupportedVersions": [ "0.0.1" ]
Expand Down
4 changes: 2 additions & 2 deletions plugins/QQNotePlugin/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"AccessToken": "your GitHub Personal Access Token",
"RepoOwner": "your GitHub UserName",
"RepoName": "your Repository Name",
"RepoBranch": "your branch",
"RepoTargetFilePath": "target file path"
"RepoBranch": "your branch: master/main",
"RepoTargetFilePath": "示例: source/_posts/分类-杂记/杂记-来自QQ.md"
}
}
10 changes: 5 additions & 5 deletions plugins/QQNotePlugin/wwwroot/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,14 @@
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>MoLiPlugin</title>
<!-- 注意:路径, 前置 /plugins/MoLiPlugin/ -->
<link href="/plugins/MoLiPlugin/css/main.css" rel="stylesheet" />
<title>QQNotePlugin</title>
<!-- 注意:路径, 前置 /plugins/QQNotePlugin/ -->
<link href="/plugins/QQNotePlugin/css/main.css" rel="stylesheet" />
</head>
<body>
<div id="app">
<h3>MoLiPlugin! </h3>
<p>插件的前端文件应当放在 wwwroot 文件夹下</p>
<h3>QQNotePlugin! </h3>
<div></div>
</div>

</body>
Expand Down

0 comments on commit 4c17493

Please sign in to comment.