You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

280 lines
11 KiB

package com.community.pocket.repository.android;
import com.community.pocket.entity.po.CreditScore;
import com.community.pocket.entity.po.android.MyInfo;
import com.community.pocket.entity.vo.Page;
import com.community.pocket.entity.vo.android.*;
import com.community.pocket.entity.vo.web.EditScore;
import com.community.pocket.repository.BaseDao;
import com.community.pocket.repository.CreditScoreDao;
import com.community.pocket.repository.EmailDao;
import com.community.pocket.util.LookupOperationUtil;
import com.community.pocket.util.TableName;
import com.mongodb.client.result.UpdateResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
//用户数据接口
@Repository
public class UserDao extends BaseDao<MyInfo> {
private static final Logger LOG = LoggerFactory.getLogger(UserDao.class);
@Autowired
private CreditScoreDao creditScoreDao;
@Autowired
private EmailDao emailDao;
@Value("${register.credit-score}")
private int creditScore;
@Value("${register.credit-score-tip}")
private String creditScoreTip;
@Value("${spring.resources.static-locations}")
private String imgPath;
@Value("${spring.mvc.static-path-pattern}")
private String mvcPath;
//检查用户名是否已注册
public boolean hasUser(String username) {
if (!StringUtils.isEmpty(username)) {
return mongoTemplate.exists(new Query().addCriteria(Criteria.where("username").is(username)), entityClass());
} else {
return false;
}
}
//更新用户信用分
public boolean updateScore(EditScore editScore) {
if (mongoTemplate.updateFirst(new Query(Criteria.where(LookupOperationUtil.idKey).is(editScore.getUsername())), new Update().inc("creditScore", editScore.getScore()), entityClass()).wasAcknowledged()) {
CreditScore creditScore = new CreditScore();
creditScore.setUsername(editScore.getUsername());
creditScore.setBeforeScore(editScore.getBeforeScore());
creditScore.setScore(editScore.getScore());
creditScore.setNotes(editScore.getNotes());
creditScore.setTime(System.currentTimeMillis());
return creditScoreDao.save(creditScore) != null;
}
return false;
}
private boolean updateUserInfo(String username, String key) {
return mongoTemplate.updateFirst(new Query(Criteria.where(LookupOperationUtil.idKey).is(username)), new Update().inc(key, 1), entityClass()).wasAcknowledged();
}
//更新用户发帖数
public boolean updatePosts(ForumVo forumVo) {
return updateUserInfo(forumVo.getUsername(), "posts");
}
//更新用户访客数
public boolean updateVisitors(VisitorForm visitorForm) {
return updateUserInfo(visitorForm.getAppointment(), "visitors");
}
//获取所有用户
public Page<MyInfo> loadAll(QueryUserForm queryUserForm) {
Criteria criteria = new Criteria();
if (!StringUtils.isEmpty(queryUserForm.getUsername())) {
if (queryUserForm.isLike()) {
criteria = Criteria.where("username").regex(Pattern.compile(".*" + queryUserForm.getUsername() + ".*"));
} else {
criteria = Criteria.where("username").is(queryUserForm.getUsername());
}
}
Query query = new Query(criteria);
if (queryUserForm.isOrderScore()) {
Sort sort = Sort.by("creditScore");
if (queryUserForm.isDesc()) {
query = query.with(sort.descending());
} else {
query = query.with(sort.ascending());
}
}
long count = mongoTemplate.count(query, entityClass());
Page<MyInfo> page = new Page<>(count, queryUserForm.getCurrentPage(), pageSize);
List<MyInfo> myInfos = mongoTemplate.find(query.with(PageRequest.of(queryUserForm.getCurrentPage().intValue() - 1, pageSize)), entityClass());
page.setList(myInfos);
return page;
}
//检查手机是否已绑定
public boolean hasMobie(String mobie) {
if (!StringUtils.isEmpty(mobie)) {
return mongoTemplate.exists(new Query().addCriteria(Criteria.where("mobie").is(mobie)), entityClass());
} else {
return false;
}
}
//检查邮箱是否已绑定
public boolean hasEmail(String email){
if(!StringUtils.isEmpty(email)){
return mongoTemplate.exists(new Query().addCriteria(Criteria.where("email").is(email)),entityClass());
}else{
return false;
}
}
//检查用户和邮箱是否对应
public boolean hasUseWithEmail(String username, String email) {
if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(email)) {
return mongoTemplate.exists(new Query().addCriteria(Criteria.where("username").is(username).and("email").is(email)), entityClass());
} else {
return false;
}
}
//检查新密码是否和原密码重复
public boolean isNotDiffPwd(UserResetPwd userResetPwd) {
String md5Password = DigestUtils.md5DigestAsHex(userResetPwd.getPassword().getBytes());
MyInfo myInfo = mongoTemplate.findById(userResetPwd.getUsername(), entityClass());
return myInfo != null && myInfo.getPassword().equals(md5Password) && emailDao.clearEmail(myInfo.getEmail());
}
//重置密码
public boolean resetPwd(UserResetPwd userResetPwd) {
String username = userResetPwd.getUsername();
String password = userResetPwd.getPassword();
String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(md5Password)) {
UpdateResult result = mongoTemplate.updateFirst(new Query().addCriteria(
Criteria.where("username").is(username)),
Update.update("password", md5Password), entityClass());
return result.wasAcknowledged();
} else {
return false;
}
}
//登陆用户
public boolean login(String username, String password) {
if(!StringUtils.isEmpty(username)&&!StringUtils.isEmpty(password)){
String md5Password= DigestUtils.md5DigestAsHex(password.getBytes());
return mongoTemplate.exists(new Query(Criteria.where("username").is(username).and("password").is(md5Password)),entityClass());
}else{
return false;
}
}
//注册用户
public void save(UserRegister userRegister) {
MyInfo myInfo = new MyInfo();
myInfo.setUsername(userRegister.getUsername());
myInfo.setPassword(DigestUtils.md5DigestAsHex(userRegister.getPassword().getBytes()));
myInfo.setMobie(userRegister.getMobie());
myInfo.setEmail(userRegister.getEmail());
myInfo.setCreditScore(creditScore);
myInfo.setPosts(0);
myInfo.setVisitors(0);
EditScore editScore=new EditScore();
editScore.setUsername(userRegister.getUsername());
editScore.setBeforeScore(0);
editScore.setScore(creditScore);
editScore.setNotes(String.format(creditScoreTip,creditScore));
updateScore(editScore);
save(myInfo);
}
//上传头像
public boolean uploadImg(UserHeadImg userHeadImg) {
MultipartFile file = userHeadImg.getFile();
if (file != null) {
try {
String fileName = file.getOriginalFilename() == null ? System.currentTimeMillis() + ".png" : file.getOriginalFilename();
File loadFile = new File(getClass().getResource("/").getFile() + imgPath.replace("classpath:/", ""), fileName);
if (!loadFile.exists() && !loadFile.mkdirs()) {
throw new RuntimeException("无法建立目录" + loadFile.getAbsolutePath());
}
file.transferTo(loadFile);
return mongoTemplate.updateFirst(new Query(Criteria.where(LookupOperationUtil.idKey).is(userHeadImg.getUsername())), Update.update("headImg", mvcPath.replace("**", loadFile.getName())), entityClass()).wasAcknowledged();
} catch (IOException e) {
e.printStackTrace();
LOG.error(e.toString());
return false;
}
} else {
return false;
}
}
//获取用户以信用分降序排列
public List<UserHot> rankUser(int num) {
List<UserHot> userHots = new ArrayList<>();
List<MyInfo> myInfos = mongoTemplate.find(new Query().with(Sort.by("creditScore").descending()).limit(num), entityClass());
for (MyInfo info : myInfos) {
UserHot userHot = new UserHot();
userHot.setUserName(info.getUsername());
userHot.setCreditScore(info.getCreditScore());
userHots.add(userHot);
}
return userHots;
}
//根据关键字匹配用户
public List<String> queryUser(QueryUserForm userForm){
List<String> userNames=new ArrayList<>();
List<MyInfo> myInfos=mongoTemplate.find(new Query(new Criteria().andOperator(
Criteria.where("username").regex(Pattern.compile(".*"+userForm.getName()+".*")),
Criteria.where("username").ne(userForm.getUsername())))
,entityClass());
for(MyInfo info:myInfos){
userNames.add(info.getUsername());
}
return userNames;
}
//获取个人信息
public Info queryUser(String username) {
Aggregation aggregation = Aggregation.newAggregation(LookupOperationUtil.scoreHistoryLookup, Aggregation.match(Criteria.where(LookupOperationUtil.idKey).is(username)));
return mongoTemplate.aggregate(aggregation, TableName.info, Info.class).getUniqueMappedResult();
}
//修改密码
public boolean modifyPwd(ModifyPwdForm modifyPwdForm) {
String md5Password= DigestUtils.md5DigestAsHex(modifyPwdForm.getOldPassword().getBytes());
String newMd5password=DigestUtils.md5DigestAsHex(modifyPwdForm.getNewPassword().getBytes());
return mongoTemplate.updateFirst(new Query(Criteria.where("username").is(modifyPwdForm.getUsername()).and("password").is(md5Password)),Update.update("password",newMd5password),entityClass()).wasAcknowledged();
}
@Override
public MyInfo save(MyInfo myInfo) {
try {
mongoTemplate.save(myInfo);
} catch (Exception e) {
e.printStackTrace();
LOG.error(e.toString());
}
return null;
}
@Override
public Class<MyInfo> entityClass() {
return MyInfo.class;
}
}