송용우

Merge commit '7a39581f' into feature/frontend_page

jaksimsamil
.vscode/
*.csv
# Jaksimsamil Crawler Documentation
## Overview
- https://acmicpc.net와 https://solved.ac에서 사용자와 문제정보를 크롤링합니다.
- Python 3.8.3, Pip 20.2.1 환경에서 개발되었습니다.
## Usuage
- Install
```bash
pip install -r requirements.txt
```
- Run
```bash
python main.py
```
import requests
from bs4 import BeautifulSoup
import pandas as pd
from dotenv import load_dotenv
import sys
import pymongo
import os
from datetime import datetime
import json
import numpy as np
SAVE_EVERY=10
SAVE_PATH='problems.csv'
def setup():
try:
load_dotenv(dotenv_path='../jaksimsamil-server/.env')
client=pymongo.MongoClient('/'.join(os.getenv('MONGO_URL').split('/')[:-1]))
print('MongoDB Connected')
return client
except FileNotFoundError:
print('.env is not found',file=sys.stderr)
exit(1)
def save(df,path='problems.csv'):
print('Saving to {}...'.format(path),end='')
df.to_csv(path)
print('Done.')
def load(path='problems.csv'):
problems=pd.read_csv(path,index_col=0)
return problems
def get_khu_problem_list():
pageNum=1
idx=0
problems=pd.DataFrame(columns=['problemNum','problemTitle','solvedacLevel','submitNum','correctNum','category','count'])
while True:
res=requests.get('https://www.acmicpc.net/school/ranklist/211/{}'.format(pageNum))
status_code=res.status_code
if status_code==404:
break
soup=BeautifulSoup(res.text,'html.parser')
userlinks=soup.select('#ranklist > tbody > tr > td:nth-child(2) > a')
for userlink in userlinks:
href=userlink['href']
res=requests.get('https://acmicpc.net'+href)
print('Collecting user data...:',href.split('/')[-1])
user_soup=BeautifulSoup(res.text,'html.parser')
problemNums=user_soup.select('body > div.wrapper > div.container.content > div.row > div:nth-child(2) > div:nth-child(3) > div.col-md-9 > div:nth-child(1) > div.panel-body > span.problem_number')
for problemNum in problemNums:
if not problemNum.text in problems['problemNum'].tolist():
problems=problems.append({'problemNum':problemNum.text,'count':1},ignore_index=True)
else:
problems.loc[problems.problemNum==problemNum.text,'count']=problems.loc[problems.problemNum==problemNum.text,'count']+1
if idx%SAVE_EVERY==0:
save(problems,SAVE_PATH)
idx+=1
pageNum+=1
save(problems,SAVE_PATH)
return problems
def get_problem_info(problems):
for idx,problemNum in enumerate(problems['problemNum'].values):
res=requests.get('https://acmicpc.net/problem/{}'.format(problemNum))
print('Collecting problem data...:',problemNum)
soup=BeautifulSoup(res.text,'html.parser')
problemTitle=soup.select('#problem_title')[0].text
soup=soup.select('#problem-info > tbody > tr > td')
submitNum=soup[2].text
correctNum=soup[4].text
problems.loc[problems.problemNum==problemNum,'problemTitle']=problemTitle
problems.loc[problems.problemNum==problemNum,'submitNum']=submitNum
problems.loc[problems.problemNum==problemNum,'correctNum']=correctNum
if idx%SAVE_EVERY==0:
save(problems,SAVE_PATH)
save(problems,SAVE_PATH)
return problems
def get_solvedac_level(problems):
for idx,problemNum in enumerate(problems['problemNum'].values):
res=requests.get('https://api.solved.ac/v2/search/problems.json?query={}&page=1&sort=id&sort_direction=ascending'.format(problemNum))
print('Collecting solved.ac level data...:',problemNum)
result=json.loads(res.text)
for problem in result['result']['problems']:
if int(problem['id'])==int(problemNum):
problems.loc[problems.problemNum==problemNum,'solvedacLevel']=problem['level']
break
if idx%SAVE_EVERY==0:
save(problems,SAVE_PATH)
save(problems,SAVE_PATH)
return problems
def get_category(problems):
problems.sort_values(['problemNum'],inplace=True,ignore_index=True)
problems['category']=problems['category'].fillna(json.dumps([]))
pageNum=1
res=requests.get('https://api.solved.ac/v2/tags/stats.json?page={}'.format(pageNum))
tagsResult=json.loads(res.text)
totalPages=tagsResult['result']['total_page']
tags=[]
tags.extend(tagsResult['result']['tags'])
for pageNum in range(2,totalPages+1):
res=requests.get('https://api.solved.ac/v2/tags/stats.json?page={}'.format(pageNum))
tagsResult=json.loads(res.text)
tags.extend(tagsResult['result']['tags'])
print('total tags:',len(tags))
for tag in tags:
problemList=[]
pageNum=1
res=requests.get('https://api.solved.ac/v2/search/problems.json?query=solvable:true+tag:{}&page={}&sort=id&sort_direction=ascending'.format(tag['tag_name'],pageNum))
problemResult=json.loads(res.text)
totalPages=problemResult['result']['total_page']
problemList.extend(problemResult['result']['problems'])
for pageNum in range(2,totalPages+1):
res=requests.get('https://api.solved.ac/v2/search/problems.json?query=solvable:true+tag:{}&page={}&sort=id&sort_direction=ascending'.format(tag['tag_name'],pageNum))
problemResult=json.loads(res.text)
problemList.extend(problemResult['result']['problems'])
idx=0
problemListLen=len(problemList)
for problemNum in problems['problemNum'].values:
if idx<problemListLen and int(problemList[idx]['id'])==int(problemNum):
category=json.loads(problems.loc[problems.problemNum==problemNum,'category'].values[0])
category.append(tag['full_name_ko'])
problems.loc[problems.problemNum==problemNum,'category']=json.dumps(category,ensure_ascii=False)
idx+=1
print('Problem {} in category {}'.format(problemNum,tag['full_name_ko']))
save(problems,SAVE_PATH)
return problems
def update_database(problems,client):
database=client['jaksimsamil']
collection=database['problem']
dictedProblems=problems.to_dict('records')
print('len of records:',len(dictedProblems))
for dictedProblem in dictedProblems:
dictedProblem['category']=json.loads(dictedProblem['category'])
collection.update_one({'problemNum':dictedProblem['problemNum']},{'$set':dictedProblem},upsert=True)
if __name__=="__main__":
startTime=datetime.now()
client=setup()
problems=get_khu_problem_list()
problems=get_problem_info(problems)
problems=get_solvedac_level(problems)
problems=get_category(problems)
update_database(problems,client)
print('Time elapsed :',(datetime.now()-startTime)/60,'mins')
beautifulsoup4==4.9.1
bs4==0.0.1
certifi==2020.6.20
chardet==3.0.4
idna==2.10
numpy==1.19.1
pandas==1.1.0
pymongo==3.11.0
python-dateutil==2.8.1
python-dotenv==0.14.0
pytz==2020.1
requests==2.24.0
six==1.15.0
soupsieve==2.0.1
urllib3==1.25.10
......@@ -8,3 +8,4 @@ access.log
# dependencies
/node_modules
......
......@@ -26,17 +26,18 @@ POST http://facerain.dcom.club/profile/getprofile
## API Table
| group | description | method | URL | Detail | Auth |
| ------- | -------------------------------------- | ------ | ----------------------- | -------------------------------------- | --------- |
| profile | 유저가 푼 문제 조회(백준) | GET | api/profile/solvedBJ:id | [바로가기](/src/api/profile/README.md) | None |
| profile | 유저가 푼 문제 동기화(백준) | PATCH | api/profile/syncBJ | [바로가기](/src/api/profile/README.md) | None |
| profile | 유저 정보 수정 | POST | api/profile/setprofile | [바로가기](/src/api/profile/README.md) | JWT TOKEN |
| profile | 유저 정보 받아오기 | POST | api/profile/getprofile | [바로가기](/src/api/profile/README.md) | JWT |
| profile | 추천 문제 조회 | POST | api/profile/recommend | [바로가기](/src/api/profile/README.md) | None |
| profile | 친구 추가 | POST | /api/profile/addfriend | [바로가기](/src/api/profile/README.md) | JWT TOKEN |
| notify | 슬랙 메시지 전송 요청 (목표 성취 여부) | POST | api/notify/goal | [바로가기](/src/api/notify/README.md) | Jwt Token |
| notify | 슬랙 메시지 전송 요청 (문제 추천) | POST | api/notify/recommend | [바로가기](/src/api/notify/README.md) | None |
| auth | 로그인 | POST | api/auth/login | [바로가기](/src/api/auth/README.md) | None |
| auth | 로그아웃 | POST | api/auth/logout | [바로가기](/src/api/auth/README.md) | JWT Token |
| auth | 회원가입 | POST | api/auth/register | [바로가기](/src/api/auth/README.md) | None |
| auth | 로그인 확인 | GET | api/auth/check | [바로가기](/src/api/auth/README.md) | None |
| group | description | method | URL | Detail | Auth |
| --------- | -------------------------------------- | ------ | -------------------------- | -------------------------------------- | --------- |
| profile | 유저가 푼 문제 조회(백준) | GET | api/profile/solvedBJ:id | [바로가기](/src/api/profile/README.md) | None |
| profile | 유저가 푼 문제 동기화(백준) | PATCH | api/profile/syncBJ | [바로가기](/src/api/profile/README.md) | None |
| profile | 유저 정보 수정 | POST | api/profile/setprofile | [바로가기](/src/api/profile/README.md) | JWT TOKEN |
| profile | 유저 정보 받아오기 | POST | api/profile/getprofile | [바로가기](/src/api/profile/README.md) | JWT |
| profile | 추천 문제 조회 | POST | api/profile/recommend | [바로가기](/src/api/profile/README.md) | None |
| profile | 친구 추가 | POST | /api/profile/addfriend | [바로가기](/src/api/profile/README.md) | JWT TOKEN |
| notify | 슬랙 메시지 전송 요청 (목표 성취 여부) | POST | api/notify/goal | [바로가기](/src/api/notify/README.md) | Jwt Token |
| notify | 슬랙 메시지 전송 요청 (문제 추천) | POST | api/notify/recommend | [바로가기](/src/api/notify/README.md) | None |
| auth | 로그인 | POST | api/auth/login | [바로가기](/src/api/auth/README.md) | None |
| auth | 로그아웃 | POST | api/auth/logout | [바로가기](/src/api/auth/README.md) | JWT Token |
| auth | 회원가입 | POST | api/auth/register | [바로가기](/src/api/auth/README.md) | None |
| auth | 로그인 확인 | GET | api/auth/check | [바로가기](/src/api/auth/README.md) | None |
| challenge | 특정 챌린지 조회(이름) | POST | api/challenge/getChallenge | [바로가기]() | None |
......
......@@ -402,12 +402,12 @@
}
},
"bcrypt": {
"version": "3.0.8",
"resolved": "https://registry.npmjs.org/bcrypt/-/bcrypt-3.0.8.tgz",
"integrity": "sha512-jKV6RvLhI36TQnPDvUFqBEnGX9c8dRRygKxCZu7E+MgLfKZbmmXL8a7/SFFOyHoPNX9nV81cKRC5tbQfvEQtpw==",
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/bcrypt/-/bcrypt-5.0.0.tgz",
"integrity": "sha512-jB0yCBl4W/kVHM2whjfyqnxTmOHkCX4kHEa5nYKSoGeYe8YrjTYTc87/6bwt1g8cmV0QrbhKriETg9jWtcREhg==",
"requires": {
"nan": "2.14.0",
"node-pre-gyp": "0.14.0"
"node-addon-api": "^3.0.0",
"node-pre-gyp": "0.15.0"
}
},
"bcrypt-pbkdf": {
......@@ -2415,11 +2415,6 @@
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz",
"integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w=="
},
"nan": {
"version": "2.14.0",
"resolved": "https://registry.npmjs.org/nan/-/nan-2.14.0.tgz",
"integrity": "sha512-INOFj37C7k3AfaNTtX8RhsTw7qRy7eLET14cROi9+5HAVbbHuIWUHEauBv5qT4Av2tWasiTY1Jw6puUNqRJXQg=="
},
"natural-compare": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz",
......@@ -2451,14 +2446,19 @@
"resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.2.tgz",
"integrity": "sha512-hZXc7K2e+PgeI1eDBe/10Ard4ekbfrrqG8Ep+8Jmf4JID2bNg7NvCPOZN+kfF574pFQI7mum2AUqDidoKqcTOw=="
},
"node-addon-api": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-3.0.0.tgz",
"integrity": "sha512-sSHCgWfJ+Lui/u+0msF3oyCgvdkhxDbkCS6Q8uiJquzOimkJBvX6hl5aSSA7DR1XbMpdM8r7phjcF63sF4rkKg=="
},
"node-pre-gyp": {
"version": "0.14.0",
"resolved": "https://registry.npmjs.org/node-pre-gyp/-/node-pre-gyp-0.14.0.tgz",
"integrity": "sha512-+CvDC7ZttU/sSt9rFjix/P05iS43qHCOOGzcr3Ry99bXG7VX953+vFyEuph/tfqoYu8dttBkE86JSKBO2OzcxA==",
"version": "0.15.0",
"resolved": "https://registry.npmjs.org/node-pre-gyp/-/node-pre-gyp-0.15.0.tgz",
"integrity": "sha512-7QcZa8/fpaU/BKenjcaeFF9hLz2+7S9AqyXFhlH/rilsQ/hPZKK32RtR5EQHJElgu+q5RfbJ34KriI79UWaorA==",
"requires": {
"detect-libc": "^1.0.2",
"mkdirp": "^0.5.1",
"needle": "^2.2.1",
"mkdirp": "^0.5.3",
"needle": "^2.5.0",
"nopt": "^4.0.1",
"npm-packlist": "^1.1.6",
"npmlog": "^4.0.2",
......
......@@ -5,7 +5,7 @@
"license": "MIT",
"dependencies": {
"axios": "^0.19.2",
"bcrypt": "^3.0.0",
"bcrypt": "^5.0.0",
"body-parser": "^1.19.0",
"cheerio": "^1.0.0-rc.3",
"cookie-parser": "^1.4.5",
......
const Joi = require("joi");
const User = require("../../models/user");
const Profile = require("../../models/profile");
/*
POST /api/auth/register
{
......@@ -28,14 +27,10 @@ exports.register = async (ctx) => {
ctx.status = 409;
return;
}
const profile = new Profile({
username,
});
const user = new User({
username,
});
await user.setPassword(password);
await profile.save();
await user.save();
ctx.body = user.serialize();
......
const Challenge = require("../../models/challenge");
const Session = require("../../models/session");
const Participation = require("../../models/participation");
const Group = require("../../models/group");
const User = require('../../models/user');
const Joi = require("joi");
/*POST /api/challenge/getChallenge
{
challengeName: "challengeName"
}
*/
exports.getChallenge = async (ctx) => {
try {
const { challengeName } = ctx.request.body;
const challenge = await Challenge.findByChallengeName(challengeName).select('-_id');
if (!challenge) {
ctx.status = 401;
return;
}
ctx.body = challenge;
} catch (e) {
ctx.throw(500, e);
}
};
/*POST /api/challenge/addChallenge
{
challengeName: "challengeName",
startDate: Date Object,
endDate: Date Object,
durationPerSession: "2w", // '1d' means one day per session, '2w' means 2 weeks per session, '3m' means 3 months per session.
goalPerSession: 3,
}
*/
exports.addChallenge = async (ctx) => {
const schema = Joi.object()
.keys({
challengeName: Joi.string(),
startDate: Joi.date(),
endDate: Joi.date(),
durationPerSession: Joi.string(),
goalPerSession: Joi.number()
})
.unknown();
const result = Joi.validate(ctx.request.body, schema);
if (result.error) {
ctx.status = 400;
ctx.body = result.error;
return;
}
let {
challengeName,
startDate,
endDate,
durationPerSession,
goalPerSession,
} = ctx.request.body;
try {
const isChallengeExist = await Challenge.findByChallengeName(challengeName).select('-_id');
if (isChallengeExist) {
ctx.status = 409;
return;
}
const challenge = new Challenge({
challengeName,
startDate,
endDate,
durationPerSession,
goalPerSession,
});
await challenge.save();
const newChallenge=await Challenge.findByChallengeName(challengeName);
const newChallenge_id=newChallenge._id;
const timeStep=Number(durationPerSession.slice(0,-1))
if(typeof(startDate)=='string'){
startDate=new Date(startDate);
}
if(typeof(endDate)=='string'){
endDate=new Date(endDate);
}
for(let s_date=new Date(startDate);s_date<endDate;){
let e_date=new Date(s_date);
if(durationPerSession[durationPerSession.length-1]==='d'){
console.log('day');
e_date.setDate(s_date.getDate()+timeStep);
}
else if(durationPerSession[durationPerSession.length-1]==='w'){
console.log('week');
e_date.setDate(s_date.getDate()+timeStep*7);
}
else if(durationPerSession[durationPerSession.length-1]==='m'){
console.log('month');
e_date.setMonth(s_date.getMonth()+timeStep);
}
e_date.setMinutes(e_date.getMinutes()-1);
if(e_date>endDate){
break;
}
let status="";
if (s_date>new Date()){
status="enrolled";
}
else if (s_date<=new Date() && new Date() <= e_date){
status="progress";
}
else{
status="end";
}
console.log(`start:${s_date}\nend:${e_date}`);
const session=new Session({
challengeId:newChallenge_id,
sessionStartDate:s_date,
sessionEndDate:e_date,
status:status,
});
await session.save();
s_date=new Date(e_date);
s_date.setMinutes(s_date.getMinutes()+1);
}
ctx.body = challenge;
} catch (e) {
ctx.throw(500, e);
}
};
/* GET /api/challenge/list?status
query string status can be in ['all','enrolled','progress','end']
*/
exports.list = async (ctx) => {
try{
const status = ctx.query.status;
if (status!=='all'){
const challenges = await Challenge.find({status:status}).select('-_id');
ctx.body = challenges;
}
else {
const challenges = await Challenge.find({}).select('-_id');
ctx.body = challenges;
}
}
catch(e){
ctx.throw(500,e);
}
};
/* POST /api/challenge/participate
{
username: 'username',
challengeName: 'challengename'
}
*/
exports.participate=async (ctx)=>{
try{
/*
TODO: access token validation,
recommend:get username from access_token
*/
console.log(ctx.request.body);
const {username,challengeName}=ctx.request.body;
const challenge=await Challenge.findByChallengeName(challengeName);
const challenge_id=challenge._id;
const user=await User.findByUsername(username);
const user_id=user._id;
const newGroup=new Group({
members:[user_id],
});
let newGroup_id=""
await newGroup.save(async (err,product)=>{
if(err){
throw err;
}
newGroup_id=product._id;
const sessions=await Session.findByChallengeId(challenge_id);
sessions.forEach(async (elem) => {
const newParticipation=new Participation({
sessionId:elem._id,
groupId:newGroup_id,
problems:[],
});
await newParticipation.save();
});
});
}
catch(e){
console.error(e);
ctx.throw(500,e);
}
};
\ No newline at end of file
const Router = require('koa-router');
const challenge = new Router();
const challengeCtrl = require('./challege.ctrl');
challenge.post("/getchallenge",challengeCtrl.getChallenge);
challenge.post("/addchallenge",challengeCtrl.addChallenge);
challenge.get("/list",challengeCtrl.list);
challenge.post("/participate",challengeCtrl.participate);
module.exports = challenge;
\ No newline at end of file
......@@ -6,11 +6,13 @@ const friend = require("./friend");
const notify = require("./notify");
const user = require("./user");
const profile = require("./profile");
const challenge = require("./challenge");
api.use("/auth", auth.routes());
api.use("/friend", friend.routes());
api.use("/notify", notify.routes());
api.use("/user", user.routes());
api.use("/profile", profile.routes());
api.use("/challenge",challenge.routes());
module.exports = api;
......
const Profile = require("../../models/profile");
const User = require("../../models/user");
const sendSlack = require("../../util/sendSlack");
const problem_set = require("../../data/problem_set");
const compareBJ = require("../../util/compareBJ");
......@@ -12,7 +12,7 @@ exports.slackGoal = async (ctx) => {
try {
const { username } = ctx.request.body;
const profile = await Profile.findByUsername(username);
const profile = await User.findByUsername(username);
if (!profile) {
ctx.status = 401;
return;
......@@ -62,7 +62,7 @@ exports.slackRecommend = async (ctx) => {
console.log("1");
const { username } = ctx.request.body;
const profile = await Profile.findByUsername(username);
const profile = await User.findByUsername(username);
if (!profile) {
ctx.status = 401;
return;
......
const Profile = require("../../models/profile");
const User = require("../../models/user");
const mongoose = require("mongoose");
const getBJ = require("../../util/getBJ");
const Joi = require("joi");
......@@ -16,6 +16,7 @@ exports.checkObjectId = (ctx, next) => {
}
return next();
};
/*POST /api/profile/getprofile
{
username: "username"
......@@ -24,7 +25,7 @@ exports.checkObjectId = (ctx, next) => {
exports.getProfile = async (ctx) => {
try {
const { username } = ctx.request.body;
const profile = await Profile.findByUsername(username);
const profile = await User.findByUsername(username);
if (!profile) {
ctx.status = 401;
return;
......@@ -50,7 +51,6 @@ exports.setProfile = async (ctx) => {
//freindList: Joi.array().items(Joi.string()),
})
.unknown();
console.log(ctx.request.body);
const result = Joi.validate(ctx.request.body, schema);
if (result.error) {
ctx.status = 400;
......@@ -59,7 +59,7 @@ exports.setProfile = async (ctx) => {
}
try {
const profile = await Profile.findOneAndUpdate(
const profile = await User.findOneAndUpdate(
{ username: ctx.request.body.username },
ctx.request.body,
{
......@@ -91,7 +91,7 @@ exports.syncBJ = async function (ctx) {
}
try {
const profile = await Profile.findByUsername(username);
const profile = await User.findByUsername(username);
if (!profile) {
ctx.status = 401;
return;
......@@ -99,7 +99,7 @@ exports.syncBJ = async function (ctx) {
const BJID = await profile.getBJID();
let BJdata = await getBJ.getBJ(BJID);
let BJdata_date = await analyzeBJ.analyzeBJ(BJdata);
const updateprofile = await Profile.findOneAndUpdate(
const updateprofile = await User.findOneAndUpdate(
{ username: username },
{ solvedBJ: BJdata, solvedBJ_date: BJdata_date },
{ new: true }
......@@ -124,7 +124,7 @@ exports.recommend = async (ctx) => {
return;
}
try {
const profile = await Profile.findByUsername(username);
const profile = await User.findByUsername(username);
if (!profile) {
ctx.status = 401;
return;
......@@ -134,7 +134,7 @@ exports.recommend = async (ctx) => {
problem_set.problem_set
);
ctx.body = compareBJ.randomItem(unsolved_data);
//데이터가 비었을 떄 예외처리 필요
//TODO: 데이터가 비었을 떄 예외처리 필요
} catch (e) {
ctx.throw(500, e);
}
......
......@@ -2,61 +2,48 @@ const mongoose = require("mongoose");
const { Schema } = mongoose;
const GroupSchema = new Schema({
members: { type: [String] },
const ChallengeSchema=new Schema({
challengeName: {type: String, required: true},
startDate: {type: Object, required: true},
endDate: {type: Object, required: true},
durationPerSession: {type: String, required: true}, // '1d' means one day per session, '2w' means 2 weeks per session, '3m' means 3 months per session.
goalPerSession: {type: Number, required:true}, // number of problems for one session
status: { type: String }
},{
collection: 'challenge'
});
const ChallengeSchema = new Schema({
challengeName: { type: String, required: true },
startDate: { type: Object, required: true },
endDate: { type: Object, required: true },
durationPerSession: { type: String, required: true }, // '1d' means one day per session, '2w' means 2 weeks per session, '3m' means 3 months per session.
goalPerSession: { type: Number, required: true }, // number of problems for one session
groups: { type: [GroupSchema], required: true }, // groups attending challenge, group of only one member supposed to be single
});
ChallengeSchema.statics.findByChallengeName = function (challengeName) {
return this.findOne({ challengeName: challengeName });
};
ChallengeSchema.methods.addNewGroup = function (group) {
this.groups.push(group);
return this.save();
};
ChallengeSchema.methods.removeGroup = function (group_id) {
const idx = this.groups.findIndex((item) => item._id === group_id);
this.groups.splice(idx, 1);
return this.save();
};
ChallengeSchema.statics.findByChallengeName=function(challengeName){
return this.findOne({challengeName:challengeName});
}
ChallengeSchema.methods.getChallengeName = function () {
return this.challengeName;
};
ChallengeSchema.methods.getChallengeName=function(){
return this.challengeName;
}
ChallengeSchema.methods.getStartDate = function () {
return this.startDate;
};
ChallengeSchema.methods.getStartDate=function(){
return this.startDate;
}
ChallengeSchema.methods.getEndDate = function () {
return this.endDate;
};
ChallengeSchema.methods.getEndDate=function(){
return this.endDate;
}
ChallengeSchema.methods.getDurationPerSession = function () {
return this.durationPerSession;
};
ChallengeSchema.method.getDurationPerSession=function(){
return this.durationPerSession;
}
ChallengeSchema.methods.getGoalPerSession = function () {
return this.goalPerSession;
};
ChallengeSchema.methods.getGoalPerSession=function(){
return this.goalPerSession;
}
ChallengeSchema.methods.getGroups = function () {
return this.groups;
};
ChallengeSchema.methods.getStatus=function(){
return this.status;
}
ChallengeSchema.methods.serialize = function () {
return this.toJSON();
};
ChallengeSchema.methods.serialize=function(){
return this.toJSON();
}
const Challenge = mongoose.model("Challenge", ChallengeSchema);
module.exports = Challenge;
const Challenge = mongoose.model('Challenge', ChallengeSchema);
module.exports = Challenge;
\ No newline at end of file
......
const mongoose = require("mongoose");
const { Schema } = mongoose;
const GroupSchema = new Schema({
members: [{ type: Schema.Types.ObjectId, ref: 'User' }]
},{
collection: 'group'
});
GroupSchema.methods.addGroupMemeber=function(user){
this.members.push(user._id);
return this.save();
}
GroupSchema.methods.getMembers=function(){
return this.members;
}
GroupSchema.methods.serialize=function(){
return this.toJSON();
}
const Group = mongoose.model('Group',GroupSchema);
module.exports = Group;
\ No newline at end of file
const mongoose = require("mongoose");
const { Schema } = mongoose;
const SelectedProblemSchema=new Schema({
problemNum: {type: Number, required: true},
isSolved: {type:Boolean, default: false},
},{
_id: false
});
const ParticipationSchema = new Schema({
sessionId: { type: Schema.Types.ObjectId, ref: 'Session' },
groupId: { type: Schema.Types.ObjectId, ref: 'Group' },
problems: [{type:SelectedProblemSchema}]
},{
collection: 'particiaption'
});
ParticipationSchema.statics.findBySessionId=function(session){
return this.find({sessionId:session._id});
}
ParticipationSchema.statics.findByGroupId=function(group){
return this.find({groupId:group._id});
}
ParticipationSchema.methods.addProblem=function(problem){
this.problems.push({problemNum:problem.problemNum,isSolved:problem.isSolved});
}
const Participation = mongoose.model('Participation', ParticipationSchema);
module.exports = Participation;
\ No newline at end of file
......@@ -8,7 +8,10 @@ const ProblemSchema=new Schema({
solvedacLevel: {type: Number},
sumbitNum: {type: Number, required: true},
correctNum: {type: Number, required: true},
category: {type:[String]}
count: { type: Number },
category: [{ type:String }],
},{
collection: 'problem'
});
ProblemSchema.statics.findByProblemNum=function(problemNum){
......@@ -46,6 +49,10 @@ ProblemSchema.methods.getCorrectNum=function(){
return this.correctNum;
}
ProblemSchema.methods.getCount=function(){
return this.count;
}
ProblemSchema.methods.getCategory=function(){
return this.category;
}
......@@ -54,5 +61,5 @@ ProblemSchema.methods.serialize=function(){
return this.toJSON();
}
const Problem=mongoose.model('Problem',ProblemSchema);
module.exports=Problem;
\ No newline at end of file
const Problem = mongoose.model('Problem',ProblemSchema);
module.exports = Problem;
\ No newline at end of file
......
const mongoose = require("mongoose");
const { Schema } = mongoose;
const ProfileSchema = new Schema({
username: { type: String, required: true, unique: true },
userBJID: String,
solvedBJ: Object,
solvedBJ_date: Object,
friendList: [String],
slackWebHookURL: String,
goalNum: Number,
});
ProfileSchema.statics.findByUsername = function (username) {
return this.findOne({ username });
};
ProfileSchema.methods.getBJID = function () {
return this.userBJID;
};
ProfileSchema.methods.getBJdata = function () {
return this.solvedBJ;
};
ProfileSchema.methods.getslackURL = function () {
return this.slackWebHookURL;
};
ProfileSchema.methods.getgoalNum = function () {
return this.goalNum;
};
ProfileSchema.methods.getTodaySovled = function () {
if (this.solvedBJ_date) {
return this.solvedBJ_date.presentNum;
}
};
ProfileSchema.methods.serialize = function () {
const data = this.toJSON();
return data;
};
const Profile = mongoose.model("Profile", ProfileSchema);
module.exports = Profile;
const mongoose = require("mongoose");
const { Schema } = mongoose;
const SessionSchema = new Schema({
challengeId: { type: Schema.Types.ObjectId, ref: 'Challenge' },
sessionStartDate: { type: Object },
sessionEndDate: { type: Object },
status: { type: String }
},{
collection: 'session'
});
SessionSchema.statics.findByChallengeId=function(challenge){
return this.find({challengeId:challenge._id});
}
SessionSchema.methods.getSessionStartDate=function(){
return this.sessionStartDate;
}
SessionSchema.methods.getSessionEndDate=function(){
return this.sessionEndDate;
}
SessionSchema.methods.getStatus=function(){
return this.status;
}
SessionSchema.methods.serialize=function(){
return this.toJSON();
}
const Session = mongoose.model('Session', SessionSchema);
module.exports = Session;
\ No newline at end of file
......@@ -7,8 +7,25 @@ const Schema = mongoose.Schema;
const UserSchema = new Schema({
username: String,
hashedPassword: String,
userBJID: String,
sovledBJ: Object,
solvedBJ_date: Object,
friendList: [{ type: Schema.Types.ObjectId, ref: 'User' }],
slackWebHookURL: String,
goalNum: Number,
},{
collection: 'user'
});
UserSchema.statics.findByUsername = function (username) {
return this.findOne({ username });
};
UserSchema.methods.addFriend=function(friend){
this.friendList.push(friend._id);
return this.save();
}
UserSchema.methods.setPassword = async function (password) {
const hash = await bcrypt.hash(password, 10);
this.hashedPassword = hash;
......@@ -17,14 +34,13 @@ UserSchema.methods.checkPassword = async function (password) {
const result = await bcrypt.compare(password, this.hashedPassword);
return result;
};
UserSchema.statics.findByUsername = function (username) {
return this.findOne({ username });
};
UserSchema.methods.serialize = function () {
const data = this.toJSON();
delete data.hashedPassword;
return data;
};
UserSchema.methods.generateToken = function () {
const token = jwt.sign(
{
......@@ -38,5 +54,32 @@ UserSchema.methods.generateToken = function () {
);
return token;
};
UserSchema.statics.findByUsername = function (username) {
return this.findOne({ username });
};
UserSchema.methods.getBJID = function () {
return this.userBJID;
};
UserSchema.methods.getBJdata = function () {
return this.solvedBJ;
};
UserSchema.methods.getslackURL = function () {
return this.slackWebHookURL;
};
UserSchema.methods.getgoalNum = function () {
return this.goalNum;
};
UserSchema.methods.getTodaySovled = function () {
if (this.solvedBJ_date) {
return this.solvedBJ_date.presentNum;
}
};
const User = mongoose.model("User", UserSchema);
module.exports = User;
......
This diff is collapsed. Click to expand it.