forked from malinkang/weread2notion-pro
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
365 lines (286 loc) · 9.47 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
import calendar
from datetime import datetime
from datetime import timedelta
import hashlib
import os
import re
import requests
import base64
from weread2notionpro.config import (
RICH_TEXT,
URL,
RELATION,
NUMBER,
DATE,
FILES,
STATUS,
TITLE,
SELECT,
)
import pendulum
MAX_LENGTH = (
1024 # NOTION 2000个字符限制https://developers.notion.com/reference/request-limits
)
def get_heading(level, content):
if level == 1:
heading = "heading_1"
elif level == 2:
heading = "heading_2"
else:
heading = "heading_3"
return {
"type": heading,
heading: {
"rich_text": [
{
"type": "text",
"text": {
"content": content[:MAX_LENGTH],
},
}
],
"color": "default",
"is_toggleable": False,
},
}
def get_table_of_contents():
"""获取目录"""
return {"type": "table_of_contents", "table_of_contents": {"color": "default"}}
def get_title(content):
return {"title": [{"type": "text", "text": {"content": content[:MAX_LENGTH]}}]}
def get_rich_text(content):
return {"rich_text": [{"type": "text", "text": {"content": content[:MAX_LENGTH]}}]}
def get_url(url):
return {"url": url}
def get_file(url):
return {"files": [{"type": "external", "name": "Cover", "external": {"url": url}}]}
def get_multi_select(names):
return {"multi_select": [{"name": name} for name in names]}
def get_relation(ids):
return {"relation": [{"id": id} for id in ids]}
def get_date(start, end=None):
return {
"date": {
"start": start,
"end": end,
"time_zone": "Asia/Shanghai",
}
}
def get_icon(url):
return {"type": "external", "external": {"url": url}}
def get_select(name):
return {"select": {"name": name}}
def get_number(number):
return {"number": number}
def get_quote(content):
return {
"type": "quote",
"quote": {
"rich_text": [
{
"type": "text",
"text": {"content": content[:MAX_LENGTH]},
}
],
"color": "default",
},
}
def get_block(content,type,show_color, style, colorStyle, reviewId):
color = "default"
if show_color:
# 根据划线颜色设置文字的颜色
if colorStyle == 1:
color = "red"
elif colorStyle == 2:
color = "purple"
elif colorStyle == 3:
color = "blue"
elif colorStyle == 4:
color = "green"
elif colorStyle == 5:
color = "yellow"
block = {
"type": type,
type: {
"rich_text": [
{
"type": "text",
"text": {
"content": content[:MAX_LENGTH],
},
}
],
"color": color,
},
}
if(type=="callout"):
# 根据不同的划线样式设置不同的emoji 直线type=0 背景颜色是1 波浪线是2
emoji = "〰️"
if style == 0:
emoji = "💡"
elif style == 1:
emoji = "⭐"
# 如果reviewId不是空说明是笔记
if reviewId != None:
emoji = "✍️"
block[type]["icon"] = {"emoji": emoji}
return block
def get_rich_text_from_result(result, name):
return result.get("properties").get(name).get("rich_text")[0].get("plain_text")
def get_number_from_result(result, name):
return result.get("properties").get(name).get("number")
def format_time(time):
"""将秒格式化为 xx时xx分格式"""
result = ""
hour = time // 3600
if hour > 0:
result += f"{hour}时"
minutes = time % 3600 // 60
if minutes > 0:
result += f"{minutes}分"
return result
def format_date(date, format="%Y-%m-%d %H:%M:%S"):
return date.strftime(format)
def timestamp_to_date(timestamp):
"""时间戳转化为date"""
return datetime.utcfromtimestamp(timestamp) + timedelta(hours=8)
def get_first_and_last_day_of_month(date):
# 获取给定日期所在月的第一天
first_day = date.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
# 获取给定日期所在月的最后一天
_, last_day_of_month = calendar.monthrange(date.year, date.month)
last_day = date.replace(
day=last_day_of_month, hour=0, minute=0, second=0, microsecond=0
)
return first_day, last_day
def get_first_and_last_day_of_year(date):
# 获取给定日期所在年的第一天
first_day = date.replace(month=1, day=1, hour=0, minute=0, second=0, microsecond=0)
# 获取给定日期所在年的最后一天
last_day = date.replace(month=12, day=31, hour=0, minute=0, second=0, microsecond=0)
return first_day, last_day
def get_first_and_last_day_of_week(date):
# 获取给定日期所在周的第一天(星期一)
first_day_of_week = (date - timedelta(days=date.weekday())).replace(
hour=0, minute=0, second=0, microsecond=0
)
# 获取给定日期所在周的最后一天(星期日)
last_day_of_week = first_day_of_week + timedelta(days=6)
return first_day_of_week, last_day_of_week
def get_properties(dict1, dict2):
properties = {}
for key, value in dict1.items():
type = dict2.get(key)
if value == None:
continue
property = None
if type == TITLE:
property = {
"title": [{"type": "text", "text": {"content": value[:MAX_LENGTH]}}]
}
elif type == RICH_TEXT:
property = {
"rich_text": [{"type": "text", "text": {"content": value[:MAX_LENGTH]}}]
}
elif type == NUMBER:
property = {"number": value}
elif type == STATUS:
property = {"status": {"name": value}}
elif type == FILES:
property = {
"files": [
{"type": "external", "name": "Cover", "external": {"url": value}}
]
}
elif type == DATE:
property = {
"date": {
"start": pendulum.from_timestamp(
value, tz="Asia/Shanghai"
).to_datetime_string(),
"time_zone": "Asia/Shanghai",
}
}
elif type == URL:
property = {"url": value}
elif type == SELECT:
property = {"select": {"name": value}}
elif type == RELATION:
property = {"relation": [{"id": id} for id in value]}
if property:
properties[key] = property
return properties
def get_property_value(property):
"""从Property中获取值"""
type = property.get("type")
content = property.get(type)
if content is None:
return None
if type == "title" or type == "rich_text":
if len(content) > 0:
return content[0].get("plain_text")
else:
return None
elif type == "status" or type == "select":
return content.get("name")
elif type == "files":
# 不考虑多文件情况
if len(content) > 0 and content[0].get("type") == "external":
return content[0].get("external").get("url")
else:
return None
elif type == "date":
return str_to_timestamp(content.get("start"))
else:
return content
def str_to_timestamp(date):
if date == None:
return 0
dt = pendulum.parse(date)
# 获取时间戳
return int(dt.timestamp())
upload_url = "https://wereadassets.malinkang.com/"
def upload_image(folder_path, filename, file_path):
# 将文件内容编码为Base64
with open(file_path, "rb") as file:
content_base64 = base64.b64encode(file.read()).decode("utf-8")
# 构建请求的JSON数据
data = {"file": content_base64, "filename": filename, "folder": folder_path}
response = requests.post(upload_url, json=data)
if response.status_code == 200:
print("File uploaded successfully.")
return response.text
else:
return None
def url_to_md5(url):
# 创建一个md5哈希对象
md5_hash = hashlib.md5()
# 对URL进行编码,准备进行哈希处理
# 默认使用utf-8编码
encoded_url = url.encode("utf-8")
# 更新哈希对象的状态
md5_hash.update(encoded_url)
# 获取十六进制的哈希表示
hex_digest = md5_hash.hexdigest()
return hex_digest
def download_image(url, save_dir="cover"):
# 确保目录存在,如果不存在则创建
if not os.path.exists(save_dir):
os.makedirs(save_dir)
file_name = url_to_md5(url) + ".jpg"
save_path = os.path.join(save_dir, file_name)
# 检查文件是否已经存在,如果存在则不进行下载
if os.path.exists(save_path):
print(f"File {file_name} already exists. Skipping download.")
return save_path
response = requests.get(url, stream=True)
if response.status_code == 200:
with open(save_path, "wb") as file:
for chunk in response.iter_content(chunk_size=128):
file.write(chunk)
print(f"Image downloaded successfully to {save_path}")
else:
print(f"Failed to download image. Status code: {response.status_code}")
return save_path
def get_embed(url):
return {"type": "embed", "embed": {"url": url}}