Skip to content

Commit 8bba2bc

Browse files
authored
Merge pull request #41 from BUAA-SE-coders007/feature/article_statistic_OCS
[feat]: 增加文献统计和OCS存储
2 parents f0dab74 + a1b05ac commit 8bba2bc

File tree

4 files changed

+56
-18
lines changed

4 files changed

+56
-18
lines changed

app/api/v1/endpoints/article.py

Lines changed: 12 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111

1212
from app.utils.get_db import get_db
1313
from app.utils.auth import get_current_user
14-
from app.curd.article import crud_upload_to_self_folder, crud_get_self_folders, crud_get_articles_in_folder, crud_self_create_folder, crud_self_article_to_recycle_bin, crud_self_folder_to_recycle_bin, crud_read_article, crud_import_self_folder, crud_export_self_folder,crud_create_tag, crud_delete_tag, crud_get_article_tags, crud_all_tags_order, crud_change_folder_name, crud_change_article_name
14+
from app.curd.article import crud_upload_to_self_folder, crud_get_self_folders, crud_get_articles_in_folder, crud_self_create_folder, crud_self_article_to_recycle_bin, crud_self_folder_to_recycle_bin, crud_read_article, crud_import_self_folder, crud_export_self_folder,crud_create_tag, crud_delete_tag, crud_get_article_tags, crud_all_tags_order, crud_change_folder_name, crud_change_article_name, crud_article_statistic
1515
from app.schemas.article import SelfCreateFolder
1616

1717
router = APIRouter()
@@ -25,10 +25,9 @@ async def upload_to_self_folder(folder_id: int = Query(...), article: UploadFile
2525
# 新建 Article 记录
2626
article_id = await crud_upload_to_self_folder(name, folder_id, db)
2727

28-
# 存储文件,暂时存储到本地
29-
save_dir = "articles"
30-
os.makedirs(save_dir, exist_ok=True) # 如果目录不存在则创建
31-
save_path = os.path.join(save_dir, f"{article_id}.pdf")
28+
# 存储到云存储位置
29+
os.makedirs("/lhcos-data", exist_ok=True)
30+
save_path = os.path.join("/lhcos-data", f"{article_id}.pdf")
3231
with open(save_path, "wb") as f:
3332
content = await article.read()
3433
f.write(content)
@@ -82,10 +81,9 @@ async def self_folder_to_recycle_bin(folder_id: int = Query(...), db: AsyncSessi
8281

8382
@router.post("/annotateSelfArticle", response_model="dict")
8483
async def annotate_self_article(article_id: int = Query(...), article: UploadFile = File(...)):
85-
# 存储文件,将新文件暂时存储到本地
86-
save_dir = "articles"
87-
os.makedirs(save_dir, exist_ok=True) # 如果目录不存在则创建
88-
save_path = os.path.join(save_dir, f"{article_id}.pdf")
84+
# 将新文件存储到云存储位置
85+
os.makedirs("/lhcos-data", exist_ok=True)
86+
save_path = os.path.join("/lhcos-data", f"{article_id}.pdf")
8987
with open(save_path, "wb") as f:
9088
content = await article.read()
9189
f.write(content)
@@ -95,7 +93,7 @@ async def annotate_self_article(article_id: int = Query(...), article: UploadFil
9593
@router.get("/readArticle", response_class=FileResponse)
9694
async def read_article(article_id: int = Query(...), db: AsyncSession = Depends(get_db)):
9795

98-
file_path = f"articles/{article_id}.pdf"
96+
file_path = f"/lhcos-data/{article_id}.pdf"
9997

10098
# 查询文件名
10199
article_name = await crud_read_article(article_id, db)
@@ -119,14 +117,14 @@ async def import_self_folder(folder_name: str = Query(...), zip: UploadFile = Fi
119117
# 记入数据库
120118
result = await crud_import_self_folder(folder_name, article_names, user_id, db)
121119

122-
# 存储文献,暂时存储到本地
123-
os.makedirs("articles", exist_ok=True)
120+
# 存储文献到云存储
121+
os.makedirs("/lhcos-data", exist_ok=True)
124122
for i in range(0, len(result), 2):
125123
article_id = result[i]
126124
article_name = result[i + 1]
127125
pdf_filename_in_zip = f"{article_name}.pdf"
128126
with zip_file.open(pdf_filename_in_zip) as source_file:
129-
target_path = os.path.join("articles", f"{article_id}.pdf")
127+
target_path = os.path.join("/lhcos-data", f"{article_id}.pdf")
130128
with open(target_path, "wb") as out_file:
131129
out_file.write(source_file.read())
132130

@@ -141,7 +139,7 @@ async def export_self_folder(background_tasks: BackgroundTasks, folder_id: int =
141139

142140
with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zipf:
143141
for article_id, article_name in zip(article_ids, article_names):
144-
pdf_path = os.path.join("articles", f"{article_id}.pdf")
142+
pdf_path = os.path.join("/lhcos-data", f"{article_id}.pdf")
145143
arcname = f"{article_name}.pdf" # 压缩包内的文件名
146144
zipf.write(pdf_path, arcname=arcname)
147145

app/api/v1/endpoints/auth.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
from app.schemas.auth import UserCreate, UserLogin, UserSendCode, ReFreshToken
1414
from app.core.config import settings
1515
from app.curd.user import get_user_by_email, create_user
16-
from app.curd.article import crud_self_create_folder
16+
from app.curd.article import crud_self_create_folder, crud_article_statistic
1717
from app.utils.get_db import get_db
1818
from app.utils.redis import get_redis_client
1919

@@ -146,4 +146,9 @@ async def send_code(user_send_code: UserSendCode):
146146
return {"msg": "Verification code sent"}
147147

148148
except aiosmtplib.SMTPException as e:
149-
raise HTTPException(status_code=500, detail=f"Failed to send email: {str(e)}")
149+
raise HTTPException(status_code=500, detail=f"Failed to send email: {str(e)}")
150+
151+
@router.get("/articleStatistic", response_model="dict")
152+
async def article_statistic(db: AsyncSession = Depends(get_db)):
153+
articles = await crud_article_statistic(db)
154+
return {"articles": articles}

app/core/config.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ class Settings:
99
SQLALCHEMY_DATABASE_URL = "mysql+asyncmy://root:[email protected]:3306/JieNote" # 替换为实际的用户名、密码和数据库名称
1010
SECRET_KEY: str = os.getenv("SECRET_KEY", "default_secret_key") # JWT密钥
1111
ALGORITHM: str = "HS256" # JWT算法
12-
ACCESS_TOKEN_EXPIRE_MINUTES: int = 5 # token过期时间
12+
ACCESS_TOKEN_EXPIRE_MINUTES: int = 1440 # token过期时间
1313
REFRESH_TOKEN_EXPIRE_DAYS: int = 7 # 刷新token过期时间7天
1414
SMTP_SERVER: str = "smtp.163.com" # SMTP服务器
1515
SMTP_PORT: int = 465 # SMTP端口

app/curd/article.py

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
from sqlalchemy.ext.asyncio import AsyncSession
22
from sqlalchemy import select, delete
3+
from sqlalchemy import func, cast, Date
4+
from datetime import datetime, timedelta
35
from app.models.model import User, Group, Folder, Article, Note, Tag, user_group
46

57
async def crud_upload_to_self_folder(name: str, folder_id: int, db: AsyncSession):
@@ -148,4 +150,37 @@ async def crud_change_article_name(article_id: int, article_name: str, db: Async
148150

149151
article.name = article_name
150152
await db.commit()
151-
await db.refresh(article)
153+
await db.refresh(article)
154+
155+
async def crud_article_statistic(db: AsyncSession):
156+
# 获取明天日期和7天前的日期
157+
tomorrow = datetime.now().date() + timedelta(days=1)
158+
seven_days_ago = datetime.now().date() - timedelta(days=6)
159+
160+
# 查询近7天内的笔记数目,按日期分组
161+
query = (
162+
select(
163+
cast(Article.create_time, Date).label("date"), # 按日期分组
164+
func.count(Article.id).label("count") # 统计每日期的笔记数
165+
)
166+
.where(
167+
Article.create_time >= seven_days_ago, # 大于等于7天前的0点
168+
Article.create_time < tomorrow # 小于明天0点
169+
)
170+
.group_by(cast(Article.create_time, Date)) # 按日期分组
171+
.order_by(cast(Article.create_time, Date)) # 按日期排序
172+
)
173+
174+
# 执行查询
175+
result = await db.execute(query)
176+
data = result.fetchall()
177+
178+
# 格式化结果为字典列表
179+
articles = [{"date": row.date, "count": row.count} for row in data]
180+
181+
# 若某日期没有记录,则为0
182+
for i in range(0, 7):
183+
if i == len(articles) or articles[i].get("date") != seven_days_ago + timedelta(days=i):
184+
articles.insert(i, {"date": seven_days_ago + timedelta(days=i), "count": 0})
185+
186+
return articles

0 commit comments

Comments
 (0)