1.改进ntfy通知,将中文标题进行编码后发送,可以直接展示中文标题;2.改进notify.py和notify.js中nt

fy的推送;
This commit is contained in:
qiaoyun680 2024-10-23 02:35:32 +00:00
parent ecc55883f0
commit 8f70329698
3 changed files with 47 additions and 30 deletions

View File

@ -152,16 +152,14 @@ export default class NotificationService {
private async serverChan() { private async serverChan() {
const { serverChanKey } = this.params; const { serverChanKey } = this.params;
const matchResult = serverChanKey.match(/^sctp(\d+)t/i); const url = serverChanKey.startsWith('sctp')
const url = matchResult && matchResult[1] ? `https://${serverChanKey}.push.ft07.com/send`
? `https://${matchResult[1]}.push.ft07.com/send/${serverChanKey}.send`
: `https://sctapi.ftqq.com/${serverChanKey}.send`; : `https://sctapi.ftqq.com/${serverChanKey}.send`;
try { try {
const res: any = await got const res: any = await got
.post(url, { .post(url, {
...this.gotOption, ...this.gotOption,
body: `title=${encodeURIComponent(this.title)}&desp=${encodeURIComponent(this.content)}`, body: `title=${this.title}&desp=${this.content}`,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
}) })
.json(); .json();
@ -666,12 +664,18 @@ export default class NotificationService {
private async ntfy() { private async ntfy() {
const { ntfyUrl, ntfyTopic, ntfyPriority } = this.params; const { ntfyUrl, ntfyTopic, ntfyPriority } = this.params;
// 编码函数
const encodeRfc2047 = (text: string, charset: string = 'UTF-8'): string => {
const encodedText = Buffer.from(text).toString('base64');
return `=?${charset}?B?${encodedText}?=`;
};
try { try {
const encodedTitle = encodeRfc2047(this.title);
const res: any = await got const res: any = await got
.post(`${ntfyUrl || 'https://ntfy.sh'}/${ntfyTopic}`, { .post(`${ntfyUrl || 'https://ntfy.sh'}/${ntfyTopic}`, {
...this.gotOption, ...this.gotOption,
body: `${this.title}\n${this.content}`, body: `${this.content}`,
headers: { 'Title': 'qinglong', 'Priority': `${ntfyPriority || '3'}` }, headers: { 'Title': encodedTitle, 'Priority': `${ntfyPriority || '3'}` },
}); });
if (res.statusCode === 200) { if (res.statusCode === 200) {
return true; return true;

View File

@ -228,13 +228,11 @@ function serverNotify(text, desp) {
if (PUSH_KEY) { if (PUSH_KEY) {
// 微信server酱推送通知一个\n不会换行需要两个\n才能换行故做此替换 // 微信server酱推送通知一个\n不会换行需要两个\n才能换行故做此替换
desp = desp.replace(/[\n\r]/g, '\n\n'); desp = desp.replace(/[\n\r]/g, '\n\n');
const matchResult = PUSH_KEY.match(/^sctp(\d+)t/i);
const options = { const options = {
url: matchResult && matchResult[1] url: PUSH_KEY.startsWith('sctp')
? `https://${matchResult[1]}.push.ft07.com/send/${PUSH_KEY}.send` ? `https://${PUSH_KEY}.push.ft07.com/send`
: `https://sctapi.ftqq.com/${PUSH_KEY}.send`, : `https://sctapi.ftqq.com/${PUSH_KEY}.send`,
body: `text=${encodeURIComponent(text)}&desp=${encodeURIComponent(desp)}`, body: `text=${text}&desp=${desp}`,
headers: { headers: {
'Content-Type': 'application/x-www-form-urlencoded', 'Content-Type': 'application/x-www-form-urlencoded',
}, },
@ -1195,14 +1193,19 @@ function webhookNotify(text, desp) {
} }
function ntfyNotify(text, desp) { function ntfyNotify(text, desp) {
function encodeRFC2047(text) {
const encodedBase64 = btoa(String.fromCharCode(...new TextEncoder().encode(text)));
return `=?utf-8?B?${encodedBase64}?=`;
}
return new Promise((resolve) => { return new Promise((resolve) => {
const { NTFY_URL, NTFY_TOPIC, NTFY_PRIORITY } = push_config; const { NTFY_URL, NTFY_TOPIC, NTFY_PRIORITY } = push_config;
if (NTFY_TOPIC) { if (NTFY_TOPIC) {
const options = { const options = {
url: NTFY_URL || `https://ntfy.sh`, url: `${NTFY_URL || 'https://ntfy.sh'}/${NTFY_TOPIC}`,
body: `${desp}\n${text}`, body: `${desp}`,
headers: { headers: {
'Title': 'qinglong', 'Title': `${encodeRFC2047(text)}`,
'Priority': NTFY_PRIORITY || '3' 'Priority': NTFY_PRIORITY || '3'
}, },
timeout, timeout,
@ -1212,7 +1215,7 @@ function ntfyNotify(text, desp) {
if (err) { if (err) {
console.log('Ntfy 通知调用API失败😞\n', err); console.log('Ntfy 通知调用API失败😞\n', err);
} else { } else {
if (data.success) { if (data.id) {
console.log('Ntfy 发送通知消息成功🎉\n'); console.log('Ntfy 发送通知消息成功🎉\n');
} else { } else {
console.log(`Ntfy 发送通知消息异常 ${JSON.stringify(data)}`); console.log(`Ntfy 发送通知消息异常 ${JSON.stringify(data)}`);
@ -1230,6 +1233,7 @@ function ntfyNotify(text, desp) {
}); });
} }
function parseString(input, valueFormatFn) { function parseString(input, valueFormatFn) {
const regex = /(\w+):\s*((?:(?!\n\w+:).)*)/g; const regex = /(\w+):\s*((?:(?!\n\w+:).)*)/g;
const matches = {}; const matches = {};

View File

@ -116,7 +116,7 @@ push_config = {
'WEBHOOK_BODY': '', # 自定义通知 请求体 'WEBHOOK_BODY': '', # 自定义通知 请求体
'WEBHOOK_HEADERS': '', # 自定义通知 请求头 'WEBHOOK_HEADERS': '', # 自定义通知 请求头
'WEBHOOK_METHOD': '', # 自定义通知 请求方法 'WEBHOOK_METHOD': '', # 自定义通知 请求方法
'WEBHOOK_CONTENT_TYPE': '' # 自定义通知 content-type 'WEBHOOK_CONTENT_TYPE': '', # 自定义通知 content-type
'NTFY_URL': '', # ntfy地址,如https://ntfy.sh 'NTFY_URL': '', # ntfy地址,如https://ntfy.sh
'NTFY_TOPIC': '', # ntfy的消息应用topic 'NTFY_TOPIC': '', # ntfy的消息应用topic
@ -302,14 +302,10 @@ def serverJ(title: str, content: str) -> None:
print("serverJ 服务启动") print("serverJ 服务启动")
data = {"text": title, "desp": content.replace("\n", "\n\n")} data = {"text": title, "desp": content.replace("\n", "\n\n")}
if push_config.get("PUSH_KEY").startswith("sctp"):
match = re.match(r'sctp(\d+)t', push_config.get("PUSH_KEY")) url = f'https://{push_config.get("PUSH_KEY")}.push.ft07.com/send'
if match:
num = match.group(1)
url = f'https://{num}.push.ft07.com/send/{push_config.get("PUSH_KEY")}.send'
else: else:
url = f'https://sctapi.ftqq.com/{push_config.get("PUSH_KEY")}.send' url = f'https://sctapi.ftqq.com/{push_config.get("PUSH_KEY")}.send'
response = requests.post(url, data=data).json() response = requests.post(url, data=data).json()
if response.get("errno") == 0 or response.get("code") == 0: if response.get("errno") == 0 or response.get("code") == 0:
@ -785,10 +781,19 @@ def chronocat(title: str, content: str) -> None:
print(f"QQ群消息:{ids}推送失败!") print(f"QQ群消息:{ids}推送失败!")
import base64
import requests
def ntfy(title: str, content: str) -> None: def ntfy(title: str, content: str) -> None:
""" """
通过 Ntfy 推送消息 通过 Ntfy 推送消息
""" """
def encode_rfc2047(text: str) -> str:
"""将文本编码为符合 RFC 2047 标准的格式"""
encoded_bytes = base64.b64encode(text.encode('utf-8'))
encoded_str = encoded_bytes.decode('utf-8')
return f'=?utf-8?B?{encoded_str}?='
if not push_config.get("NTFY_TOPIC"): if not push_config.get("NTFY_TOPIC"):
print("ntfy 服务的 NTFY_TOPIC 未设置!!\n取消推送") print("ntfy 服务的 NTFY_TOPIC 未设置!!\n取消推送")
return return
@ -798,18 +803,22 @@ def ntfy(title: str, content: str) -> None:
print("ntfy 服务的NTFY_PRIORITY 未设置!!默认设置为3") print("ntfy 服务的NTFY_PRIORITY 未设置!!默认设置为3")
else: else:
priority = push_config.get("NTFY_PRIORITY") priority = push_config.get("NTFY_PRIORITY")
data = (title + "\n" +content).encode(encoding='utf-8')
# 使用 RFC 2047 编码 title
encoded_title = encode_rfc2047(title)
data = content.encode(encoding='utf-8')
headers = { headers = {
"Title": "qinglong", "Title": encoded_title, # 使用编码后的 title
"Priority": priority "Priority": priority
} }
url = push_config.get("NTFY_URL") + "/" + push_config.get("NTFY_TOPIC") url = push_config.get("NTFY_URL") + "/" + push_config.get("NTFY_TOPIC")
response = requests.post(url, data=data, headers=headers) response = requests.post(url, data=data, headers=headers)
if response.status_code == 200: # 使用 response.status_code 进行检查
if response["code"] == 200:
print("Ntfy 推送成功!") print("Ntfy 推送成功!")
else: else:
print("Ntfy 推送失败!错误信息:", response) print("Ntfy 推送失败!错误信息:", response.text)
def parse_headers(headers): def parse_headers(headers):
if not headers: if not headers: