diff --git a/cmd/main.go b/cmd/main.go index 192832ad..2a5ddaa1 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -48,7 +48,6 @@ func runApp() { if err != nil { panic(err) } - conf.GetPathIgnoreList() app, cleanup, err := initApplication( c.Debug, c.Server, c.Data.Database, c.Data.Cache, c.I18n, c.Swaggerui, c.ServiceConfig, log.GetLogger()) if err != nil { diff --git a/cmd/wire_gen.go b/cmd/wire_gen.go index 89f943bf..26355097 100644 --- a/cmd/wire_gen.go +++ b/cmd/wire_gen.go @@ -23,7 +23,6 @@ import ( "github.com/answerdev/answer/internal/repo/captcha" "github.com/answerdev/answer/internal/repo/collection" "github.com/answerdev/answer/internal/repo/comment" - "github.com/answerdev/answer/internal/repo/common" "github.com/answerdev/answer/internal/repo/config" "github.com/answerdev/answer/internal/repo/export" "github.com/answerdev/answer/internal/repo/meta" @@ -52,6 +51,7 @@ import ( "github.com/answerdev/answer/internal/service/collection_common" comment2 "github.com/answerdev/answer/internal/service/comment" "github.com/answerdev/answer/internal/service/comment_common" + config2 "github.com/answerdev/answer/internal/service/config" "github.com/answerdev/answer/internal/service/dashboard" export2 "github.com/answerdev/answer/internal/service/export" "github.com/answerdev/answer/internal/service/follow" @@ -109,22 +109,23 @@ func initApplication(debug bool, serverConf *conf.Server, dbConf *data.Database, langController := controller.NewLangController(i18nTranslator, siteInfoCommonService) authRepo := auth.NewAuthRepo(dataData) authService := auth2.NewAuthService(authRepo) - configRepo := config.NewConfigRepo(dataData) - userRepo := user.NewUserRepo(dataData, configRepo) + userRepo := user.NewUserRepo(dataData) uniqueIDRepo := unique.NewUniqueIDRepo(dataData) - activityRepo := activity_common.NewActivityRepo(dataData, uniqueIDRepo, configRepo) - userRankRepo := rank.NewUserRankRepo(dataData, configRepo) - userActiveActivityRepo := activity.NewUserActiveActivityRepo(dataData, activityRepo, userRankRepo, configRepo) + configRepo := config.NewConfigRepo(dataData) + configService := config2.NewConfigService(configRepo) + activityRepo := activity_common.NewActivityRepo(dataData, uniqueIDRepo, configService) + userRankRepo := rank.NewUserRankRepo(dataData, configService) + userActiveActivityRepo := activity.NewUserActiveActivityRepo(dataData, activityRepo, userRankRepo, configService) emailRepo := export.NewEmailRepo(dataData) - emailService := export2.NewEmailService(configRepo, emailRepo, siteInfoRepo) + emailService := export2.NewEmailService(configService, emailRepo, siteInfoRepo) userRoleRelRepo := role.NewUserRoleRelRepo(dataData) roleRepo := role.NewRoleRepo(dataData) roleService := role2.NewRoleService(roleRepo) userRoleRelService := role2.NewUserRoleRelService(userRoleRelRepo, roleService) - userCommon := usercommon.NewUserCommon(userRepo, userRoleRelService, authService) + userCommon := usercommon.NewUserCommon(userRepo, userRoleRelService, authService, siteInfoCommonService) userExternalLoginRepo := user_external_login.NewUserExternalLoginRepo(dataData) userExternalLoginService := user_external_login2.NewUserExternalLoginService(userRepo, userCommon, userExternalLoginRepo, emailService, siteInfoCommonService, userActiveActivityRepo) - userService := service.NewUserService(userRepo, userActiveActivityRepo, activityRepo, emailService, authService, serviceConf, siteInfoCommonService, userRoleRelService, userCommon, userExternalLoginService) + userService := service.NewUserService(userRepo, userActiveActivityRepo, activityRepo, emailService, authService, siteInfoCommonService, userRoleRelService, userCommon, userExternalLoginService) captchaRepo := captcha.NewCaptchaRepo(dataData) captchaService := action.NewCaptchaService(captchaRepo) uploaderService := uploader.NewUploaderService(serviceConf, siteInfoCommonService) @@ -144,13 +145,13 @@ func initApplication(debug bool, serverConf *conf.Server, dbConf *data.Database, commentService := comment2.NewCommentService(commentRepo, commentCommonRepo, userCommon, objService, voteRepo, emailService, userRepo) rolePowerRelRepo := role.NewRolePowerRelRepo(dataData) rolePowerRelService := role2.NewRolePowerRelService(rolePowerRelRepo, userRoleRelService) - rankService := rank2.NewRankService(userCommon, userRankRepo, objService, userRoleRelService, rolePowerRelService, configRepo) + rankService := rank2.NewRankService(userCommon, userRankRepo, objService, userRoleRelService, rolePowerRelService, configService) commentController := controller.NewCommentController(commentService, rankService) reportRepo := report.NewReportRepo(dataData, uniqueIDRepo) reportService := report2.NewReportService(reportRepo, objService) reportController := controller.NewReportController(reportService, rankService) - serviceVoteRepo := activity.NewVoteRepo(dataData, uniqueIDRepo, configRepo, activityRepo, userRankRepo, voteRepo) - voteService := service.NewVoteService(serviceVoteRepo, uniqueIDRepo, configRepo, questionRepo, answerRepo, commentCommonRepo, objService) + serviceVoteRepo := activity.NewVoteRepo(dataData, uniqueIDRepo, configService, activityRepo, userRankRepo, voteRepo) + voteService := service.NewVoteService(serviceVoteRepo, uniqueIDRepo, configService, questionRepo, answerRepo, commentCommonRepo, objService) voteController := controller.NewVoteController(voteService, rankService) followRepo := activity_common.NewFollowRepo(dataData, uniqueIDRepo, activityRepo) tagService := tag2.NewTagService(tagRepo, tagCommonService, revisionService, followRepo, siteInfoCommonService) @@ -164,7 +165,7 @@ func initApplication(debug bool, serverConf *conf.Server, dbConf *data.Database, answerCommon := answercommon.NewAnswerCommon(answerRepo) metaRepo := meta.NewMetaRepo(dataData) metaService := meta2.NewMetaService(metaRepo) - questionCommon := questioncommon.NewQuestionCommon(questionRepo, answerRepo, voteRepo, followRepo, tagCommonService, userCommon, collectionCommon, answerCommon, metaService, configRepo) + questionCommon := questioncommon.NewQuestionCommon(questionRepo, answerRepo, voteRepo, followRepo, tagCommonService, userCommon, collectionCommon, answerCommon, metaService, configService) collectionService := service.NewCollectionService(collectionRepo, collectionGroupRepo, questionCommon) collectionController := controller.NewCollectionController(collectionService) answerActivityRepo := activity.NewAnswerActivityRepo(dataData, activityRepo, userRankRepo) @@ -173,7 +174,7 @@ func initApplication(debug bool, serverConf *conf.Server, dbConf *data.Database, questionService := service.NewQuestionService(questionRepo, tagCommonService, questionCommon, userCommon, userRepo, revisionService, metaService, collectionCommon, answerActivityService, dataData, emailService) answerService := service.NewAnswerService(answerRepo, questionRepo, questionCommon, userCommon, collectionCommon, userRepo, revisionService, answerActivityService, answerCommon, voteRepo, emailService, userRoleRelService) questionController := controller.NewQuestionController(questionService, answerService, rankService) - dashboardService := dashboard.NewDashboardService(questionRepo, answerRepo, commentCommonRepo, voteRepo, userRepo, reportRepo, configRepo, siteInfoCommonService, serviceConf, dataData) + dashboardService := dashboard.NewDashboardService(questionRepo, answerRepo, commentCommonRepo, voteRepo, userRepo, reportRepo, configService, siteInfoCommonService, serviceConf, dataData) answerController := controller.NewAnswerController(answerService, rankService, dashboardService) searchParser := search_parser.NewSearchParser(tagCommonService, userCommon) searchRepo := search_common.NewSearchRepo(dataData, uniqueIDRepo, userCommon) @@ -182,18 +183,17 @@ func initApplication(debug bool, serverConf *conf.Server, dbConf *data.Database, serviceRevisionService := service.NewRevisionService(revisionRepo, userCommon, questionCommon, answerService, objService, questionRepo, answerRepo, tagRepo, tagCommonService) revisionController := controller.NewRevisionController(serviceRevisionService, rankService) rankController := controller.NewRankController(rankService) - commonRepo := common.NewCommonRepo(dataData, uniqueIDRepo) - reportHandle := report_handle_admin.NewReportHandle(questionCommon, commentRepo, configRepo) - reportAdminService := report_admin.NewReportAdminService(reportRepo, userCommon, commonRepo, answerRepo, questionRepo, commentCommonRepo, reportHandle, configRepo) + reportHandle := report_handle_admin.NewReportHandle(questionCommon, commentRepo, configService) + reportAdminService := report_admin.NewReportAdminService(reportRepo, userCommon, answerRepo, questionRepo, commentCommonRepo, reportHandle, configService, objService) controller_adminReportController := controller_admin.NewReportController(reportAdminService) userAdminRepo := user.NewUserAdminRepo(dataData, authRepo) - userAdminService := user_admin.NewUserAdminService(userAdminRepo, userRoleRelService, authService, userCommon, userActiveActivityRepo) + userAdminService := user_admin.NewUserAdminService(userAdminRepo, userRoleRelService, authService, userCommon, userActiveActivityRepo, siteInfoCommonService) userAdminController := controller_admin.NewUserAdminController(userAdminService) - reasonRepo := reason.NewReasonRepo(configRepo) + reasonRepo := reason.NewReasonRepo(configService) reasonService := reason2.NewReasonService(reasonRepo) reasonController := controller.NewReasonController(reasonService) themeController := controller_admin.NewThemeController() - siteInfoService := siteinfo.NewSiteInfoService(siteInfoRepo, siteInfoCommonService, emailService, tagCommonService, configRepo) + siteInfoService := siteinfo.NewSiteInfoService(siteInfoRepo, siteInfoCommonService, emailService, tagCommonService, configService) siteInfoController := controller_admin.NewSiteInfoController(siteInfoService) siteinfoController := controller.NewSiteinfoController(siteInfoCommonService) notificationRepo := notification.NewNotificationRepo(dataData) @@ -203,13 +203,13 @@ func initApplication(debug bool, serverConf *conf.Server, dbConf *data.Database, dashboardController := controller.NewDashboardController(dashboardService) uploadController := controller.NewUploadController(uploaderService) activityCommon := activity_common2.NewActivityCommon(activityRepo) - activityActivityRepo := activity.NewActivityRepo(dataData) + activityActivityRepo := activity.NewActivityRepo(dataData, configService) commentCommonService := comment_common.NewCommentCommonService(commentCommonRepo) - activityService := activity2.NewActivityService(activityActivityRepo, userCommon, activityCommon, tagCommonService, objService, commentCommonService, revisionService, metaService) + activityService := activity2.NewActivityService(activityActivityRepo, userCommon, activityCommon, tagCommonService, objService, commentCommonService, revisionService, metaService, configService) activityController := controller.NewActivityController(activityCommon, activityService) roleController := controller_admin.NewRoleController(roleService) pluginConfigRepo := plugin_config.NewPluginConfigRepo(dataData) - pluginCommonService := plugin_common.NewPluginCommonService(pluginConfigRepo, configRepo) + pluginCommonService := plugin_common.NewPluginCommonService(pluginConfigRepo, configService) pluginController := controller_admin.NewPluginController(pluginCommonService) permissionController := controller.NewPermissionController(rankService) answerAPIRouter := router.NewAnswerAPIRouter(langController, userController, commentController, reportController, voteController, tagController, followController, collectionController, questionController, answerController, searchController, revisionController, rankController, controller_adminReportController, userAdminController, reasonController, themeController, siteInfoController, siteinfoController, notificationController, dashboardController, uploadController, activityController, roleController, pluginController, permissionController) diff --git a/configs/reserved-usernames.json b/configs/reserved-usernames.json index 48ce6186..deb6c822 100644 --- a/configs/reserved-usernames.json +++ b/configs/reserved-usernames.json @@ -1 +1 @@ -["0","100","101","102","1xx","200","201","202","203","204","205","206","207","226","2xx","300","301","302","303","304","305","307","308","3xx","400","401","402","403","404","405","406","407","408","409","410","411","412","413","414","415","416","417","418","422","423","424","426","428","429","431","451","4xx","500","501","502","503","504","505","506","507","511","5xx","7xx","about","abuse","access","account","accounts","activate","activities","activity","ad","add","address","adm","admin","administration","administrator","ads","adult","advertising","affiliate","affiliates","ajax","all","alpha","analysis","analytics","android","anon","anonymous","api","app","apps","archive","archives","article","asct","asset","atom","auth","authentication","autoconfig","avatar","backup","balancer-manager","bank","banner","banners","beta","billing","bin","blog","blogs","board","book","bookmark","bot","bots","broadcasthost","bug","bugs","business","cache","cadastro","calendar","call","campaign","cancel","captcha","career","careers","cart","categories","category","cgi","cgi-bin","changelog","chat","check","checking","checkout","client","cliente","clients","code","codereview","comercial","comment","comments","communities","community","company","compare","compras","config","configuration","connect","contact","contact-us","contact_us","contactus","contest","contribute","corp","create","crypt","css","dashboard","data","db","default","delete","demo","design","designer","destroy","dev","devel","developer","developers","diagram","diary","dict","dictionary","die","dir","direct_messages","directory","dist","dns","doc","docker","docs","documentation","domain","download","downloads","ecommerce","edit","editor","edu","education","email","employment","empty","end","enterprise","entries","entry","error","errors","eval","event","everyone","exit","explore","export","facebook","faq","favorite","favorites","fbi","feature","features","feed","feedback","feeds","file","files","firewall","first","flash","fleet","fleets","flog","follow","followers","following","forgot","forgot-password","forgot_password","forgotpassword","form","forum","forums","founder","free","friend","friends","ftp","gadget","gadgets","game","games","get","ghost","gift","gifts","gist","git","github","graph","group","groups","guest","guests","help","home","homepage","hooks","host","hosting","hostmaster","hostname","howto","hpg","html","http","httpd","https","i","iamges","icon","icons","id","idea","ideas","image","images","imap","img","index","indice","info","information","inquiry","instagram","intranet","invitations","invite","ip","ipad","iphone","irc","is","isatap","issue","issues","it","item","items","java","javascript","job","jobs","join","js","json","jump","keys","keyserver","knowledgebase","language","languages","last","ldap-status","legal","license","link","links","linux","list","lists","local","localdomain","localhost","log","log-in","log-out","log_in","log_out","login","logout","logs","m","mac","mail","mail1","mail2","mail3","mail4","mail5","mailer","mailer-daemon","mailing","maintenance","manager","manual","map","maps","marketing","master","me","media","member","members","message","messages","messenger","microblog","microblogs","mine","mis","mob","mobile","movie","movies","mp3","msg","msn","music","musicas","mx","my","mysql","name","named","names","namespace","namespaces","nan","navi","navigation","net","network","new","news","newsletter","nick","nickname","no-reply","nobody","noc","noreply","notes","noticias","notification","notifications","notify","ns","ns1","ns10","ns2","ns3","ns4","ns5","ns6","ns7","ns8","ns9","null","oauth","oauth_clients","offer","offers","official","old","online","openid","operator","ops","order","orders","organization","organizations","orgs","overview","owner","owners","package","page","pager","pages","panel","passwd","password","patch","payment","perl","phone","photo","photoalbum","photos","php","phpmyadmin","phppgadmin","phpredisadmin","pic","pics","ping","plan","plans","plugin","plugins","policy","pop","pop3","popular","portal","post","postfix","postmaster","posts","pr","premium","press","price","pricing","privacy","privacy-policy","privacy_policy","privacypolicy","private","product","products","profile","project","projects","promo","pub","public","purpose","put","pw","python","query","random","ranking","read","readme","recent","recruit","recruitment","register","registration","release","releases","remote","remove","replies","reply","report","reports","repositories","repository","req","request","requests","res","reset","reset-password","reset_password","resetpassword","resource","resources","roc","root","rss","ruby","rule","rules","sag","sale","sales","sample","samples","save","school","script","scripts","search","secure","security","self","send","server","server-info","server-status","service","services","session","sessions","setting","settings","setup","share","shop","show","sign-in","sign-up","sign_in","sign_up","signin","signout","signup","site","sitemap","sites","smartphone","smtp","soporte","source","spec","special","sql","src","ssh","ssl","ssladmin","ssladministrator","sslwebmaster","staff","stage","staging","start","stat","state","static","stats","status","store","stores","stories","style","styleguide","styles","stylesheet","stylesheets","subdomain","subscribe","subscriptions","suporte","support","svn","swf","sys","sysadmin","sysadministrator","system","tablet","tablets","tag","tags","talk","task","tasks","team","teams","tech","telnet","term","terms","terms-of-service","terms_of_service","termsofservice","test","test1","test2","test3","teste","testing","tests","theme","themes","thread","threads","tls","tmp","todo","token","tokenserver","tool","tools","top","topic","topics","tos","tour","translations","trends","tutorial","tux","tv","twitter","undef","unfollow","unsubscribe","update","upload","uploads","uptime","url","usage","usenet","user","username","users","usr","usuario","util","uucp","vendas","ver","version","video","videos","visitor","vpn","watch","weather","web","webhook","webhooks","webmail","webmaster","website","websites","welcome","widget","widgets","wiki","win","windows","word","work","works","workshop","wpad","ww","wws","www","www1","www2","www3","www4","www5","www6","www7","wwws","wwww","xfn","xml","xmpp","xpg","xxx","yaml","year","yml","you","yourdomain","yourname","yoursite","yourusername"] \ No newline at end of file +["0","100","101","102","1xx","200","201","202","203","204","205","206","207","226","2xx","300","301","302","303","304","305","307","308","3xx","400","401","402","403","404","405","406","407","408","409","410","411","412","413","414","415","416","417","418","422","423","424","426","428","429","431","451","4xx","500","501","502","503","504","505","506","507","511","5xx","7xx","about","abuse","access","account","account-activation","account-recovery","account-suspended","accounts","activate","activities","activity","ad","add","address","adm","admin","administration","administrator","ads","adult","advertising","affiliate","affiliates","ajax","all","alpha","analysis","analytics","android","anon","anonymous","api","app","apps","archive","archives","article","asct","asset","atom","auth","auth-landing","authentication","autoconfig","avatar","backup","balancer-manager","bank","banner","banners","beta","billing","bin","blog","blogs","board","book","bookmark","bot","bots","broadcasthost","bug","bugs","business","cache","cadastro","calendar","call","campaign","cancel","captcha","career","careers","cart","categories","category","cgi","cgi-bin","changelog","change-email","chat","check","checking","checkout","client","cliente","clients","code","codereview","comercial","comment","comments","communities","community","company","compare","compras","config","configuration","confirm-new-email","confirm-email","connect","contact","contact-us","contact_us","contactus","contest","contribute","corp","create","crypt","css","dashboard","data","db","default","delete","demo","design","designer","destroy","dev","devel","developer","developers","diagram","diary","dict","dictionary","die","dir","direct_messages","directory","dist","dns","doc","docker","docs","documentation","domain","download","downloads","ecommerce","edit","editor","edu","education","email","employment","empty","end","enterprise","entries","entry","error","errors","eval","event","everyone","exit","explore","export","facebook","faq","favorite","favorites","fbi","feature","features","feed","feedback","feeds","file","files","firewall","first","flash","fleet","fleets","flog","follow","followers","following","forgot","forgot-password","forgot_password","forgotpassword","form","forum","forums","founder","free","friend","friends","ftp","gadget","gadgets","game","games","get","ghost","gift","gifts","gist","git","github","graph","group","groups","guest","guests","help","home","homepage","hooks","host","hosting","hostmaster","hostname","howto","hpg","html","http","httpd","https","i","iamges","icon","icons","id","idea","ideas","image","images","imap","img","index","indice","info","information","inquiry","instagram","intranet","invitations","invite","ip","ipad","iphone","irc","is","isatap","issue","issues","it","item","items","java","javascript","job","jobs","join","js","json","jump","keys","keyserver","knowledgebase","language","languages","last","ldap-status","legal","license","link","links","linux","list","lists","local","localdomain","localhost","log","log-in","log-out","log_in","log_out","login","logout","logs","m","mac","mail","mail1","mail2","mail3","mail4","mail5","mailer","mailer-daemon","mailing","maintenance","manager","manual","map","maps","marketing","master","me","media","member","members","message","messages","messenger","microblog","microblogs","mine","mis","mob","mobile","movie","movies","mp3","msg","msn","music","musicas","mx","my","mysql","name","named","names","namespace","namespaces","nan","navi","navigation","net","network","new","news","newsletter","nick","nickname","no-reply","nobody","noc","noreply","notes","noticias","notification","notifications","notify","ns","ns1","ns10","ns2","ns3","ns4","ns5","ns6","ns7","ns8","ns9","null","oauth","oauth_clients","offer","offers","official","old","online","openid","operator","ops","order","orders","organization","organizations","orgs","overview","owner","owners","package","page","pager","pages","panel","passwd","password","password-reset","patch","payment","perl","phone","photo","photoalbum","photos","php","phpmyadmin","phppgadmin","phpredisadmin","pic","pics","ping","plan","plans","plugin","plugins","policy","pop","pop3","popular","portal","post","postfix","postmaster","posts","pr","premium","press","price","pricing","privacy","privacy-policy","privacy_policy","privacypolicy","private","product","products","profile","project","projects","promo","pub","public","purpose","put","pw","python","query","random","ranking","read","readme","recent","recruit","recruitment","register","registration","release","releases","remote","remove","replies","reply","report","reports","repositories","repository","req","request","requests","res","reset","reset-password","reset_password","resetpassword","resource","resources","roc","root","rss","ruby","rule","rules","sag","sale","sales","sample","samples","save","school","script","scripts","search","secure","security","self","send","server","server-info","server-status","service","services","session","sessions","setting","settings","setup","share","shop","show","sign-in","sign-up","sign_in","sign_up","signin","signout","signup","site","sitemap","sites","smartphone","smtp","soporte","source","spec","special","sql","src","ssh","ssl","ssladmin","ssladministrator","sslwebmaster","staff","stage","staging","start","stat","state","static","stats","status","store","stores","stories","style","styleguide","styles","stylesheet","stylesheets","subdomain","subscribe","subscriptions","suporte","support","svn","swf","sys","sysadmin","sysadministrator","system","tablet","tablets","tag","tags","talk","task","tasks","team","teams","tech","telnet","term","terms","terms-of-service","terms_of_service","termsofservice","test","test1","test2","test3","teste","testing","tests","theme","themes","thread","threads","tls","tmp","todo","token","tokenserver","tool","tools","top","topic","topics","tos","tour","translations","trends","tutorial","tux","tv","twitter","undef","unfollow","unsubscribe","update","upload","uploads","uptime","url","usage","usenet","user","username","users","usr","usuario","util","uucp","vendas","ver","version","video","videos","visitor","vpn","watch","weather","web","webhook","webhooks","webmail","webmaster","website","websites","welcome","widget","widgets","wiki","win","windows","word","work","works","workshop","wpad","ww","wws","www","www1","www2","www3","www4","www5","www6","www7","wwws","wwww","xfn","xml","xmpp","xpg","xxx","yaml","year","yml","you","yourdomain","yourname","yoursite","yourusername"] \ No newline at end of file diff --git a/docs/docs.go b/docs/docs.go index 5601f442..96f9cf1a 100644 --- a/docs/docs.go +++ b/docs/docs.go @@ -3373,7 +3373,7 @@ const docTemplate = `{ "list": { "type": "array", "items": { - "$ref": "#/definitions/schema.GetRankPersonalWithPageResp" + "$ref": "#/definitions/schema.GetRankPersonalPageResp" } } } @@ -5071,7 +5071,7 @@ const docTemplate = `{ "type": "object", "properties": { "data": { - "$ref": "#/definitions/schema.GetUserResp" + "$ref": "#/definitions/schema.UserLoginResp" } } } @@ -5155,7 +5155,7 @@ const docTemplate = `{ "type": "object", "properties": { "data": { - "$ref": "#/definitions/schema.GetUserToSetShowResp" + "$ref": "#/definitions/schema.GetCurrentLoginUserInfoResp" } } } @@ -5340,7 +5340,7 @@ const docTemplate = `{ "type": "object", "properties": { "data": { - "$ref": "#/definitions/schema.GetUserResp" + "$ref": "#/definitions/schema.UserLoginResp" } } } @@ -5596,7 +5596,7 @@ const docTemplate = `{ "type": "object", "properties": { "data": { - "$ref": "#/definitions/schema.GetUserResp" + "$ref": "#/definitions/schema.UserLoginResp" } } } @@ -5642,7 +5642,7 @@ const docTemplate = `{ "type": "object", "properties": { "data": { - "$ref": "#/definitions/schema.GetUserResp" + "$ref": "#/definitions/schema.UserLoginResp" } } } @@ -6800,6 +6800,109 @@ const docTemplate = `{ } } }, + "schema.GetCurrentLoginUserInfoResp": { + "type": "object", + "properties": { + "access_token": { + "description": "access token", + "type": "string" + }, + "answer_count": { + "description": "answer count", + "type": "integer" + }, + "authority_group": { + "description": "authority group", + "type": "integer" + }, + "avatar": { + "$ref": "#/definitions/schema.AvatarInfo" + }, + "bio": { + "description": "bio markdown", + "type": "string" + }, + "bio_html": { + "description": "bio html", + "type": "string" + }, + "created_at": { + "description": "create time", + "type": "integer" + }, + "display_name": { + "description": "display name", + "type": "string" + }, + "e_mail": { + "description": "email", + "type": "string" + }, + "follow_count": { + "description": "follow count", + "type": "integer" + }, + "have_password": { + "type": "boolean" + }, + "id": { + "description": "user id", + "type": "string" + }, + "ip_info": { + "description": "ip info", + "type": "string" + }, + "language": { + "description": "language", + "type": "string" + }, + "last_login_date": { + "description": "last login date", + "type": "integer" + }, + "location": { + "description": "location", + "type": "string" + }, + "mail_status": { + "description": "mail status(1 pass 2 to be verified)", + "type": "integer" + }, + "mobile": { + "description": "mobile", + "type": "string" + }, + "notice_status": { + "description": "notice status(1 on 2off)", + "type": "integer" + }, + "question_count": { + "description": "question count", + "type": "integer" + }, + "rank": { + "description": "rank", + "type": "integer" + }, + "role_id": { + "description": "role id", + "type": "integer" + }, + "status": { + "description": "user status", + "type": "string" + }, + "username": { + "description": "username", + "type": "string" + }, + "website": { + "description": "website", + "type": "string" + } + } + }, "schema.GetFollowingTagsResp": { "type": "object", "properties": { @@ -6983,7 +7086,7 @@ const docTemplate = `{ } } }, - "schema.GetRankPersonalWithPageResp": { + "schema.GetRankPersonalPageResp": { "type": "object", "properties": { "answer_id": { @@ -7347,214 +7450,6 @@ const docTemplate = `{ } } }, - "schema.GetUserResp": { - "type": "object", - "properties": { - "access_token": { - "description": "access token", - "type": "string" - }, - "answer_count": { - "description": "answer count", - "type": "integer" - }, - "authority_group": { - "description": "authority group", - "type": "integer" - }, - "avatar": { - "description": "avatar", - "type": "string" - }, - "bio": { - "description": "bio markdown", - "type": "string" - }, - "bio_html": { - "description": "bio html", - "type": "string" - }, - "created_at": { - "description": "create time", - "type": "integer" - }, - "display_name": { - "description": "display name", - "type": "string" - }, - "e_mail": { - "description": "email", - "type": "string" - }, - "follow_count": { - "description": "follow count", - "type": "integer" - }, - "have_password": { - "description": "user have password", - "type": "boolean" - }, - "id": { - "description": "user id", - "type": "string" - }, - "ip_info": { - "description": "ip info", - "type": "string" - }, - "language": { - "description": "language", - "type": "string" - }, - "last_login_date": { - "description": "last login date", - "type": "integer" - }, - "location": { - "description": "location", - "type": "string" - }, - "mail_status": { - "description": "mail status(1 pass 2 to be verified)", - "type": "integer" - }, - "mobile": { - "description": "mobile", - "type": "string" - }, - "notice_status": { - "description": "notice status(1 on 2off)", - "type": "integer" - }, - "question_count": { - "description": "question count", - "type": "integer" - }, - "rank": { - "description": "rank", - "type": "integer" - }, - "role_id": { - "description": "role id", - "type": "integer" - }, - "status": { - "description": "user status", - "type": "string" - }, - "username": { - "description": "username", - "type": "string" - }, - "website": { - "description": "website", - "type": "string" - } - } - }, - "schema.GetUserToSetShowResp": { - "type": "object", - "properties": { - "access_token": { - "description": "access token", - "type": "string" - }, - "answer_count": { - "description": "answer count", - "type": "integer" - }, - "authority_group": { - "description": "authority group", - "type": "integer" - }, - "avatar": { - "$ref": "#/definitions/schema.AvatarInfo" - }, - "bio": { - "description": "bio markdown", - "type": "string" - }, - "bio_html": { - "description": "bio html", - "type": "string" - }, - "created_at": { - "description": "create time", - "type": "integer" - }, - "display_name": { - "description": "display name", - "type": "string" - }, - "e_mail": { - "description": "email", - "type": "string" - }, - "follow_count": { - "description": "follow count", - "type": "integer" - }, - "have_password": { - "type": "boolean" - }, - "id": { - "description": "user id", - "type": "string" - }, - "ip_info": { - "description": "ip info", - "type": "string" - }, - "language": { - "description": "language", - "type": "string" - }, - "last_login_date": { - "description": "last login date", - "type": "integer" - }, - "location": { - "description": "location", - "type": "string" - }, - "mail_status": { - "description": "mail status(1 pass 2 to be verified)", - "type": "integer" - }, - "mobile": { - "description": "mobile", - "type": "string" - }, - "notice_status": { - "description": "notice status(1 on 2off)", - "type": "integer" - }, - "question_count": { - "description": "question count", - "type": "integer" - }, - "rank": { - "description": "rank", - "type": "integer" - }, - "role_id": { - "description": "role id", - "type": "integer" - }, - "status": { - "description": "user status", - "type": "string" - }, - "username": { - "description": "username", - "type": "string" - }, - "website": { - "description": "website", - "type": "string" - } - } - }, "schema.GetVoteWithPageResp": { "type": "object", "properties": { @@ -9080,6 +8975,111 @@ const docTemplate = `{ } } }, + "schema.UserLoginResp": { + "type": "object", + "properties": { + "access_token": { + "description": "access token", + "type": "string" + }, + "answer_count": { + "description": "answer count", + "type": "integer" + }, + "authority_group": { + "description": "authority group", + "type": "integer" + }, + "avatar": { + "description": "avatar", + "type": "string" + }, + "bio": { + "description": "bio markdown", + "type": "string" + }, + "bio_html": { + "description": "bio html", + "type": "string" + }, + "created_at": { + "description": "create time", + "type": "integer" + }, + "display_name": { + "description": "display name", + "type": "string" + }, + "e_mail": { + "description": "email", + "type": "string" + }, + "follow_count": { + "description": "follow count", + "type": "integer" + }, + "have_password": { + "description": "user have password", + "type": "boolean" + }, + "id": { + "description": "user id", + "type": "string" + }, + "ip_info": { + "description": "ip info", + "type": "string" + }, + "language": { + "description": "language", + "type": "string" + }, + "last_login_date": { + "description": "last login date", + "type": "integer" + }, + "location": { + "description": "location", + "type": "string" + }, + "mail_status": { + "description": "mail status(1 pass 2 to be verified)", + "type": "integer" + }, + "mobile": { + "description": "mobile", + "type": "string" + }, + "notice_status": { + "description": "notice status(1 on 2off)", + "type": "integer" + }, + "question_count": { + "description": "question count", + "type": "integer" + }, + "rank": { + "description": "rank", + "type": "integer" + }, + "role_id": { + "description": "role id", + "type": "integer" + }, + "status": { + "description": "user status", + "type": "string" + }, + "username": { + "description": "username", + "type": "string" + }, + "website": { + "description": "website", + "type": "string" + } + } + }, "schema.UserModifyPasswordReq": { "type": "object", "required": [ diff --git a/docs/swagger.json b/docs/swagger.json index 5b1f3686..8a0db0e1 100644 --- a/docs/swagger.json +++ b/docs/swagger.json @@ -3361,7 +3361,7 @@ "list": { "type": "array", "items": { - "$ref": "#/definitions/schema.GetRankPersonalWithPageResp" + "$ref": "#/definitions/schema.GetRankPersonalPageResp" } } } @@ -5059,7 +5059,7 @@ "type": "object", "properties": { "data": { - "$ref": "#/definitions/schema.GetUserResp" + "$ref": "#/definitions/schema.UserLoginResp" } } } @@ -5143,7 +5143,7 @@ "type": "object", "properties": { "data": { - "$ref": "#/definitions/schema.GetUserToSetShowResp" + "$ref": "#/definitions/schema.GetCurrentLoginUserInfoResp" } } } @@ -5328,7 +5328,7 @@ "type": "object", "properties": { "data": { - "$ref": "#/definitions/schema.GetUserResp" + "$ref": "#/definitions/schema.UserLoginResp" } } } @@ -5584,7 +5584,7 @@ "type": "object", "properties": { "data": { - "$ref": "#/definitions/schema.GetUserResp" + "$ref": "#/definitions/schema.UserLoginResp" } } } @@ -5630,7 +5630,7 @@ "type": "object", "properties": { "data": { - "$ref": "#/definitions/schema.GetUserResp" + "$ref": "#/definitions/schema.UserLoginResp" } } } @@ -6788,6 +6788,109 @@ } } }, + "schema.GetCurrentLoginUserInfoResp": { + "type": "object", + "properties": { + "access_token": { + "description": "access token", + "type": "string" + }, + "answer_count": { + "description": "answer count", + "type": "integer" + }, + "authority_group": { + "description": "authority group", + "type": "integer" + }, + "avatar": { + "$ref": "#/definitions/schema.AvatarInfo" + }, + "bio": { + "description": "bio markdown", + "type": "string" + }, + "bio_html": { + "description": "bio html", + "type": "string" + }, + "created_at": { + "description": "create time", + "type": "integer" + }, + "display_name": { + "description": "display name", + "type": "string" + }, + "e_mail": { + "description": "email", + "type": "string" + }, + "follow_count": { + "description": "follow count", + "type": "integer" + }, + "have_password": { + "type": "boolean" + }, + "id": { + "description": "user id", + "type": "string" + }, + "ip_info": { + "description": "ip info", + "type": "string" + }, + "language": { + "description": "language", + "type": "string" + }, + "last_login_date": { + "description": "last login date", + "type": "integer" + }, + "location": { + "description": "location", + "type": "string" + }, + "mail_status": { + "description": "mail status(1 pass 2 to be verified)", + "type": "integer" + }, + "mobile": { + "description": "mobile", + "type": "string" + }, + "notice_status": { + "description": "notice status(1 on 2off)", + "type": "integer" + }, + "question_count": { + "description": "question count", + "type": "integer" + }, + "rank": { + "description": "rank", + "type": "integer" + }, + "role_id": { + "description": "role id", + "type": "integer" + }, + "status": { + "description": "user status", + "type": "string" + }, + "username": { + "description": "username", + "type": "string" + }, + "website": { + "description": "website", + "type": "string" + } + } + }, "schema.GetFollowingTagsResp": { "type": "object", "properties": { @@ -6971,7 +7074,7 @@ } } }, - "schema.GetRankPersonalWithPageResp": { + "schema.GetRankPersonalPageResp": { "type": "object", "properties": { "answer_id": { @@ -7335,214 +7438,6 @@ } } }, - "schema.GetUserResp": { - "type": "object", - "properties": { - "access_token": { - "description": "access token", - "type": "string" - }, - "answer_count": { - "description": "answer count", - "type": "integer" - }, - "authority_group": { - "description": "authority group", - "type": "integer" - }, - "avatar": { - "description": "avatar", - "type": "string" - }, - "bio": { - "description": "bio markdown", - "type": "string" - }, - "bio_html": { - "description": "bio html", - "type": "string" - }, - "created_at": { - "description": "create time", - "type": "integer" - }, - "display_name": { - "description": "display name", - "type": "string" - }, - "e_mail": { - "description": "email", - "type": "string" - }, - "follow_count": { - "description": "follow count", - "type": "integer" - }, - "have_password": { - "description": "user have password", - "type": "boolean" - }, - "id": { - "description": "user id", - "type": "string" - }, - "ip_info": { - "description": "ip info", - "type": "string" - }, - "language": { - "description": "language", - "type": "string" - }, - "last_login_date": { - "description": "last login date", - "type": "integer" - }, - "location": { - "description": "location", - "type": "string" - }, - "mail_status": { - "description": "mail status(1 pass 2 to be verified)", - "type": "integer" - }, - "mobile": { - "description": "mobile", - "type": "string" - }, - "notice_status": { - "description": "notice status(1 on 2off)", - "type": "integer" - }, - "question_count": { - "description": "question count", - "type": "integer" - }, - "rank": { - "description": "rank", - "type": "integer" - }, - "role_id": { - "description": "role id", - "type": "integer" - }, - "status": { - "description": "user status", - "type": "string" - }, - "username": { - "description": "username", - "type": "string" - }, - "website": { - "description": "website", - "type": "string" - } - } - }, - "schema.GetUserToSetShowResp": { - "type": "object", - "properties": { - "access_token": { - "description": "access token", - "type": "string" - }, - "answer_count": { - "description": "answer count", - "type": "integer" - }, - "authority_group": { - "description": "authority group", - "type": "integer" - }, - "avatar": { - "$ref": "#/definitions/schema.AvatarInfo" - }, - "bio": { - "description": "bio markdown", - "type": "string" - }, - "bio_html": { - "description": "bio html", - "type": "string" - }, - "created_at": { - "description": "create time", - "type": "integer" - }, - "display_name": { - "description": "display name", - "type": "string" - }, - "e_mail": { - "description": "email", - "type": "string" - }, - "follow_count": { - "description": "follow count", - "type": "integer" - }, - "have_password": { - "type": "boolean" - }, - "id": { - "description": "user id", - "type": "string" - }, - "ip_info": { - "description": "ip info", - "type": "string" - }, - "language": { - "description": "language", - "type": "string" - }, - "last_login_date": { - "description": "last login date", - "type": "integer" - }, - "location": { - "description": "location", - "type": "string" - }, - "mail_status": { - "description": "mail status(1 pass 2 to be verified)", - "type": "integer" - }, - "mobile": { - "description": "mobile", - "type": "string" - }, - "notice_status": { - "description": "notice status(1 on 2off)", - "type": "integer" - }, - "question_count": { - "description": "question count", - "type": "integer" - }, - "rank": { - "description": "rank", - "type": "integer" - }, - "role_id": { - "description": "role id", - "type": "integer" - }, - "status": { - "description": "user status", - "type": "string" - }, - "username": { - "description": "username", - "type": "string" - }, - "website": { - "description": "website", - "type": "string" - } - } - }, "schema.GetVoteWithPageResp": { "type": "object", "properties": { @@ -9068,6 +8963,111 @@ } } }, + "schema.UserLoginResp": { + "type": "object", + "properties": { + "access_token": { + "description": "access token", + "type": "string" + }, + "answer_count": { + "description": "answer count", + "type": "integer" + }, + "authority_group": { + "description": "authority group", + "type": "integer" + }, + "avatar": { + "description": "avatar", + "type": "string" + }, + "bio": { + "description": "bio markdown", + "type": "string" + }, + "bio_html": { + "description": "bio html", + "type": "string" + }, + "created_at": { + "description": "create time", + "type": "integer" + }, + "display_name": { + "description": "display name", + "type": "string" + }, + "e_mail": { + "description": "email", + "type": "string" + }, + "follow_count": { + "description": "follow count", + "type": "integer" + }, + "have_password": { + "description": "user have password", + "type": "boolean" + }, + "id": { + "description": "user id", + "type": "string" + }, + "ip_info": { + "description": "ip info", + "type": "string" + }, + "language": { + "description": "language", + "type": "string" + }, + "last_login_date": { + "description": "last login date", + "type": "integer" + }, + "location": { + "description": "location", + "type": "string" + }, + "mail_status": { + "description": "mail status(1 pass 2 to be verified)", + "type": "integer" + }, + "mobile": { + "description": "mobile", + "type": "string" + }, + "notice_status": { + "description": "notice status(1 on 2off)", + "type": "integer" + }, + "question_count": { + "description": "question count", + "type": "integer" + }, + "rank": { + "description": "rank", + "type": "integer" + }, + "role_id": { + "description": "role id", + "type": "integer" + }, + "status": { + "description": "user status", + "type": "string" + }, + "username": { + "description": "username", + "type": "string" + }, + "website": { + "description": "website", + "type": "string" + } + } + }, "schema.UserModifyPasswordReq": { "type": "object", "required": [ diff --git a/docs/swagger.yaml b/docs/swagger.yaml index 13d4db4c..4f73fe51 100644 --- a/docs/swagger.yaml +++ b/docs/swagger.yaml @@ -526,6 +526,82 @@ definitions: description: user vote amount type: integer type: object + schema.GetCurrentLoginUserInfoResp: + properties: + access_token: + description: access token + type: string + answer_count: + description: answer count + type: integer + authority_group: + description: authority group + type: integer + avatar: + $ref: '#/definitions/schema.AvatarInfo' + bio: + description: bio markdown + type: string + bio_html: + description: bio html + type: string + created_at: + description: create time + type: integer + display_name: + description: display name + type: string + e_mail: + description: email + type: string + follow_count: + description: follow count + type: integer + have_password: + type: boolean + id: + description: user id + type: string + ip_info: + description: ip info + type: string + language: + description: language + type: string + last_login_date: + description: last login date + type: integer + location: + description: location + type: string + mail_status: + description: mail status(1 pass 2 to be verified) + type: integer + mobile: + description: mobile + type: string + notice_status: + description: notice status(1 on 2off) + type: integer + question_count: + description: question count + type: integer + rank: + description: rank + type: integer + role_id: + description: role id + type: integer + status: + description: user status + type: string + username: + description: username + type: string + website: + description: website + type: string + type: object schema.GetFollowingTagsResp: properties: display_name: @@ -655,7 +731,7 @@ definitions: selected_level: type: integer type: object - schema.GetRankPersonalWithPageResp: + schema.GetRankPersonalPageResp: properties: answer_id: description: answer id @@ -915,160 +991,6 @@ definitions: description: username type: string type: object - schema.GetUserResp: - properties: - access_token: - description: access token - type: string - answer_count: - description: answer count - type: integer - authority_group: - description: authority group - type: integer - avatar: - description: avatar - type: string - bio: - description: bio markdown - type: string - bio_html: - description: bio html - type: string - created_at: - description: create time - type: integer - display_name: - description: display name - type: string - e_mail: - description: email - type: string - follow_count: - description: follow count - type: integer - have_password: - description: user have password - type: boolean - id: - description: user id - type: string - ip_info: - description: ip info - type: string - language: - description: language - type: string - last_login_date: - description: last login date - type: integer - location: - description: location - type: string - mail_status: - description: mail status(1 pass 2 to be verified) - type: integer - mobile: - description: mobile - type: string - notice_status: - description: notice status(1 on 2off) - type: integer - question_count: - description: question count - type: integer - rank: - description: rank - type: integer - role_id: - description: role id - type: integer - status: - description: user status - type: string - username: - description: username - type: string - website: - description: website - type: string - type: object - schema.GetUserToSetShowResp: - properties: - access_token: - description: access token - type: string - answer_count: - description: answer count - type: integer - authority_group: - description: authority group - type: integer - avatar: - $ref: '#/definitions/schema.AvatarInfo' - bio: - description: bio markdown - type: string - bio_html: - description: bio html - type: string - created_at: - description: create time - type: integer - display_name: - description: display name - type: string - e_mail: - description: email - type: string - follow_count: - description: follow count - type: integer - have_password: - type: boolean - id: - description: user id - type: string - ip_info: - description: ip info - type: string - language: - description: language - type: string - last_login_date: - description: last login date - type: integer - location: - description: location - type: string - mail_status: - description: mail status(1 pass 2 to be verified) - type: integer - mobile: - description: mobile - type: string - notice_status: - description: notice status(1 on 2off) - type: integer - question_count: - description: question count - type: integer - rank: - description: rank - type: integer - role_id: - description: role id - type: integer - status: - description: user status - type: string - username: - description: username - type: string - website: - description: website - type: string - type: object schema.GetVoteWithPageResp: properties: answer_id: @@ -2134,6 +2056,84 @@ definitions: - e_mail - pass type: object + schema.UserLoginResp: + properties: + access_token: + description: access token + type: string + answer_count: + description: answer count + type: integer + authority_group: + description: authority group + type: integer + avatar: + description: avatar + type: string + bio: + description: bio markdown + type: string + bio_html: + description: bio html + type: string + created_at: + description: create time + type: integer + display_name: + description: display name + type: string + e_mail: + description: email + type: string + follow_count: + description: follow count + type: integer + have_password: + description: user have password + type: boolean + id: + description: user id + type: string + ip_info: + description: ip info + type: string + language: + description: language + type: string + last_login_date: + description: last login date + type: integer + location: + description: location + type: string + mail_status: + description: mail status(1 pass 2 to be verified) + type: integer + mobile: + description: mobile + type: string + notice_status: + description: notice status(1 on 2off) + type: integer + question_count: + description: question count + type: integer + rank: + description: rank + type: integer + role_id: + description: role id + type: integer + status: + description: user status + type: string + username: + description: username + type: string + website: + description: website + type: string + type: object schema.UserModifyPasswordReq: properties: captcha_code: @@ -4325,7 +4325,7 @@ paths: - properties: list: items: - $ref: '#/definitions/schema.GetRankPersonalWithPageResp' + $ref: '#/definitions/schema.GetRankPersonalPageResp' type: array type: object type: object @@ -5355,7 +5355,7 @@ paths: - $ref: '#/definitions/handler.RespBody' - properties: data: - $ref: '#/definitions/schema.GetUserResp' + $ref: '#/definitions/schema.UserLoginResp' type: object summary: UserVerifyEmail tags: @@ -5404,7 +5404,7 @@ paths: - $ref: '#/definitions/handler.RespBody' - properties: data: - $ref: '#/definitions/schema.GetUserToSetShowResp' + $ref: '#/definitions/schema.GetCurrentLoginUserInfoResp' type: object security: - ApiKeyAuth: [] @@ -5518,7 +5518,7 @@ paths: - $ref: '#/definitions/handler.RespBody' - properties: data: - $ref: '#/definitions/schema.GetUserResp' + $ref: '#/definitions/schema.UserLoginResp' type: object summary: UserEmailLogin tags: @@ -5672,7 +5672,7 @@ paths: - $ref: '#/definitions/handler.RespBody' - properties: data: - $ref: '#/definitions/schema.GetUserResp' + $ref: '#/definitions/schema.UserLoginResp' type: object summary: UserRegisterCaptcha tags: @@ -5699,7 +5699,7 @@ paths: - $ref: '#/definitions/handler.RespBody' - properties: data: - $ref: '#/definitions/schema.GetUserResp' + $ref: '#/definitions/schema.UserLoginResp' type: object summary: UserRegisterByEmail tags: diff --git a/go.sum b/go.sum index e51c9462..e26ab91c 100644 --- a/go.sum +++ b/go.sum @@ -625,16 +625,12 @@ github.com/scottleedavis/go-exif-remove v0.0.0-20230314195146-7e059d593405 h1:2i github.com/scottleedavis/go-exif-remove v0.0.0-20230314195146-7e059d593405/go.mod h1:rIxVzVLKlBwLxO+lC+k/I4HJfRQcemg/f/76Xmmzsec= github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc= github.com/seccomp/libseccomp-golang v0.9.2-0.20210429002308-3879420cc921/go.mod h1:JA8cRccbGaA1s33RQf7Y1+q9gHmZX1yB/z9WDN1C6fg= -github.com/segmentfault/pacman v1.0.3 h1:/K8LJHQMiCaCIvC/e8GQITpYTEG6RH4KTLTZjPTghl4= -github.com/segmentfault/pacman v1.0.3/go.mod h1:5lNp5REd8QMThmBUvR3Fi9Y3AsOB4GRq7soCB4QLqOs= github.com/segmentfault/pacman v1.0.4 h1:6UIXuMHUeYMWe5toflV9SXZQizRny1RczjZJLj9kul0= github.com/segmentfault/pacman v1.0.4/go.mod h1:5lNp5REd8QMThmBUvR3Fi9Y3AsOB4GRq7soCB4QLqOs= github.com/segmentfault/pacman/contrib/cache/memory v0.0.0-20221219081300-f734f4a16aa0 h1:4x0qG7H2M3qH7Yo2BhGrVlji1iTmRAWgINY/JyENeHs= github.com/segmentfault/pacman/contrib/cache/memory v0.0.0-20221219081300-f734f4a16aa0/go.mod h1:rmf1TCwz67dyM+AmTwSd1BxTo2AOYHj262lP93bOZbs= github.com/segmentfault/pacman/contrib/conf/viper v0.0.0-20221018072427-a15dd1434e05 h1:BlqTgc3/MYKG6vMI2MI+6o+7P4Gy5PXlawu185wPXAk= github.com/segmentfault/pacman/contrib/conf/viper v0.0.0-20221018072427-a15dd1434e05/go.mod h1:prPjFam7MyZ5b3S9dcDOt2tMPz6kf7C9c243s9zSwPY= -github.com/segmentfault/pacman/contrib/i18n v0.0.0-20230516093245-f9384b820548 h1:R+FH23Qrdp5ECuHXmZy4BvoO/x7m2wZgNeiC46+jqCQ= -github.com/segmentfault/pacman/contrib/i18n v0.0.0-20230516093245-f9384b820548/go.mod h1:7QcRmnV7OYq4hNOOCWXT5HXnN/u756JUsqIW0Bw8n9E= github.com/segmentfault/pacman/contrib/i18n v0.0.0-20230516093754-b76aef1c1150 h1:OEuW1D7RGDE0CZDr0oGMw9Eiq7fAbD9C4WMrvSixamk= github.com/segmentfault/pacman/contrib/i18n v0.0.0-20230516093754-b76aef1c1150/go.mod h1:7QcRmnV7OYq4hNOOCWXT5HXnN/u756JUsqIW0Bw8n9E= github.com/segmentfault/pacman/contrib/log/zap v0.0.0-20221018072427-a15dd1434e05 h1:jcGZU2juv0L3eFEkuZYV14ESLUlWfGMWnP0mjOfrSZc= diff --git a/i18n/en_US.yaml b/i18n/en_US.yaml index f3adcd96..c8f8f143 100644 --- a/i18n/en_US.yaml +++ b/i18n/en_US.yaml @@ -1,4 +1,5 @@ # The following fields are used for back-end + backend: base: success: @@ -221,6 +222,8 @@ backend: no_permission: other: No permission to Revision. user: + external_login_missing_user_id: + other: The third-party platform does not provide a unique UserID, so you cannot login, please contact the website administrator. external_login_unbinding_forbidden: other: Please set a login password for your account before you remove this login. email_or_password_wrong: @@ -356,6 +359,8 @@ backend: other: answered modified: other: modified + deleted_title: + other: Deleted question notification: action: update_question: @@ -430,6 +435,19 @@ backend: other: "[{{.SiteName}}] Test Email" body: other: "This is a test email." + action_activity_type: + upvote: + other: upvote + upvoted: + other: upvoted + downvote: + other: downvote + downvoted: + other: downvoted + accept: + other: accept + accepted: + other: accepted # The following fields are used for interface presentation(Front-end) ui: diff --git a/i18n/zh_CN.yaml b/i18n/zh_CN.yaml index 1987e6e0..8bc80aee 100644 --- a/i18n/zh_CN.yaml +++ b/i18n/zh_CN.yaml @@ -344,6 +344,8 @@ backend: other: 回答于 modified: other: 修改于 + deleted_title: + other: 问题已被删除 notification: action: update_question: @@ -418,6 +420,19 @@ backend: other: "[{{.SiteName}}] 测试邮件" body: other: "这是一封测试邮件。" + action_activity_type: + upvote: + other: 点赞 + upvoted: + other: 被赞 + downvote: + other: 点踩 + downvoted: + other: 被踩 + accept: + other: 采纳 + accepted: + other: 被采纳 #The following fields are used for interface presentation(Front-end) ui: how_to_format: diff --git a/internal/base/conf/conf.go b/internal/base/conf/conf.go index 615405f1..b0401e1e 100644 --- a/internal/base/conf/conf.go +++ b/internal/base/conf/conf.go @@ -4,8 +4,6 @@ import ( "bytes" "path/filepath" - "github.com/answerdev/answer/configs" - "github.com/answerdev/answer/internal/base/constant" "github.com/answerdev/answer/internal/base/data" "github.com/answerdev/answer/internal/base/server" "github.com/answerdev/answer/internal/base/translator" @@ -14,7 +12,6 @@ import ( "github.com/answerdev/answer/internal/service/service_config" "github.com/answerdev/answer/pkg/writer" "github.com/segmentfault/pacman/contrib/conf/viper" - "github.com/segmentfault/pacman/log" "gopkg.in/yaml.v3" ) @@ -69,18 +66,3 @@ func RewriteConfig(configFilePath string, allConfig *AllConfig) error { } return writer.ReplaceFile(configFilePath, buf.String()) } - -func GetPathIgnoreList() map[string]bool { - list := make(map[string]bool, 0) - data := &PathIgnore{} - err := yaml.Unmarshal(configs.PathIgnore, data) - if err != nil { - log.Error(err) - return list - } - for _, item := range data.Users { - list[item] = true - } - constant.PathIgnoreMap = list - return list -} diff --git a/internal/base/constant/cache_key.go b/internal/base/constant/cache_key.go new file mode 100644 index 00000000..9e9f9949 --- /dev/null +++ b/internal/base/constant/cache_key.go @@ -0,0 +1,19 @@ +package constant + +import "time" + +const ( + UserStatusChangedCacheKey = "answer:user:status:" + UserStatusChangedCacheTime = 7 * 24 * time.Hour + UserTokenCacheKey = "answer:user:token:" + UserTokenCacheTime = 7 * 24 * time.Hour + AdminTokenCacheKey = "answer:admin:token:" + AdminTokenCacheTime = 7 * 24 * time.Hour + UserTokenMappingCacheKey = "answer:user-token:mapping:" + SiteInfoCacheKey = "answer:site-info:" + SiteInfoCacheTime = 1 * time.Hour + ConfigID2KEYCacheKeyPrefix = "answer:config:id:" + ConfigKEY2ContentCacheKeyPrefix = "answer:config:key:" + ConnectorUserExternalInfoCacheKey = "answer:connector:" + ConnectorUserExternalInfoCacheTime = 10 * time.Minute +) diff --git a/internal/base/constant/connector.go b/internal/base/constant/connector.go deleted file mode 100644 index fcf181f4..00000000 --- a/internal/base/constant/connector.go +++ /dev/null @@ -1,8 +0,0 @@ -package constant - -import "time" - -const ( - ConnectorUserExternalInfoCacheKey = "answer:connector:" - ConnectorUserExternalInfoCacheTime = 10 * time.Minute -) diff --git a/internal/base/constant/constant.go b/internal/base/constant/constant.go index b921c9f6..a6f271c9 100644 --- a/internal/base/constant/constant.go +++ b/internal/base/constant/constant.go @@ -1,76 +1,10 @@ package constant -import "time" - const ( - DefaultPageSize = 20 // Default number of pages - UserStatusChangedCacheKey = "answer:user:status:" - UserStatusChangedCacheTime = 7 * 24 * time.Hour - UserTokenCacheKey = "answer:user:token:" - UserTokenCacheTime = 7 * 24 * time.Hour - AdminTokenCacheKey = "answer:admin:token:" - AdminTokenCacheTime = 7 * 24 * time.Hour - AcceptLanguageFlag = "Accept-Language" - UserTokenMappingCacheKey = "answer:user-token:mapping:" - SiteInfoCacheKey = "answer:site-info:" - SiteInfoCacheTime = 1 * time.Hour + DefaultPageSize = 20 // Default number of pages ) -const ( - QuestionObjectType = "question" - AnswerObjectType = "answer" - TagObjectType = "tag" - UserObjectType = "user" - CollectionObjectType = "collection" - CommentObjectType = "comment" - ReportObjectType = "report" -) - -// ObjectTypeStrMapping key => value -// object TagID AnswerList -// key equal database's table name var ( Version string = "" Revision string = "" - - PathIgnoreMap map[string]bool - - ObjectTypeStrMapping = map[string]int{ - QuestionObjectType: 1, - AnswerObjectType: 2, - TagObjectType: 3, - UserObjectType: 4, - CollectionObjectType: 6, - CommentObjectType: 7, - ReportObjectType: 8, - } - - ObjectTypeNumberMapping = map[int]string{ - 1: QuestionObjectType, - 2: AnswerObjectType, - 3: TagObjectType, - 4: UserObjectType, - 6: CollectionObjectType, - 7: CommentObjectType, - 8: ReportObjectType, - } ) - -const ( - SiteTypeGeneral = "general" - SiteTypeInterface = "interface" - SiteTypeBranding = "branding" - SiteTypeWrite = "write" - SiteTypeLegal = "legal" - SiteTypeSeo = "seo" - SiteTypeLogin = "login" - SiteTypeCustomCssHTML = "css-html" - SiteTypeTheme = "theme" - SiteTypePrivileges = "privileges" - SiteTypeUsers = "users" -) - -func ExistInPathIgnore(name string) bool { - _, ok := PathIgnoreMap[name] - return ok -} diff --git a/internal/base/constant/http_header.go b/internal/base/constant/http_header.go new file mode 100644 index 00000000..a68db8b1 --- /dev/null +++ b/internal/base/constant/http_header.go @@ -0,0 +1,5 @@ +package constant + +const ( + AcceptLanguageFlag = "Accept-Language" +) diff --git a/internal/base/constant/object_type.go b/internal/base/constant/object_type.go new file mode 100644 index 00000000..9c2c7124 --- /dev/null +++ b/internal/base/constant/object_type.go @@ -0,0 +1,33 @@ +package constant + +const ( + QuestionObjectType = "question" + AnswerObjectType = "answer" + TagObjectType = "tag" + UserObjectType = "user" + CollectionObjectType = "collection" + CommentObjectType = "comment" + ReportObjectType = "report" +) + +var ( + ObjectTypeStrMapping = map[string]int{ + QuestionObjectType: 1, + AnswerObjectType: 2, + TagObjectType: 3, + UserObjectType: 4, + CollectionObjectType: 6, + CommentObjectType: 7, + ReportObjectType: 8, + } + + ObjectTypeNumberMapping = map[int]string{ + 1: QuestionObjectType, + 2: AnswerObjectType, + 3: TagObjectType, + 4: UserObjectType, + 6: CollectionObjectType, + 7: CommentObjectType, + 8: ReportObjectType, + } +) diff --git a/internal/base/constant/config_key.go b/internal/base/constant/plugin_config_key.go similarity index 100% rename from internal/base/constant/config_key.go rename to internal/base/constant/plugin_config_key.go diff --git a/internal/base/constant/rank.go b/internal/base/constant/privilege.go similarity index 100% rename from internal/base/constant/rank.go rename to internal/base/constant/privilege.go diff --git a/internal/base/constant/question.go b/internal/base/constant/question.go new file mode 100644 index 00000000..9f54ea5b --- /dev/null +++ b/internal/base/constant/question.go @@ -0,0 +1,5 @@ +package constant + +const ( + DeletedQuestionTitleTrKey = "question.deleted_title" +) diff --git a/internal/base/constant/site_info.go b/internal/base/constant/site_info.go index 88f3a4d8..7d7c0439 100644 --- a/internal/base/constant/site_info.go +++ b/internal/base/constant/site_info.go @@ -1,7 +1,13 @@ package constant -var ( - DefaultAvatar = "system" +const ( DefaultGravatarBaseURL = "https://www.gravatar.com/avatar/" - DefaultSiteURL = "" + DefaultAvatar = "system" + AvatarTypeDefault = "default" + AvatarTypeGravatar = "gravatar" + AvatarTypeCustom = "custom" +) + +var ( + DefaultSiteURL = "" ) diff --git a/internal/base/constant/site_type.go b/internal/base/constant/site_type.go new file mode 100644 index 00000000..72ad7b91 --- /dev/null +++ b/internal/base/constant/site_type.go @@ -0,0 +1,15 @@ +package constant + +const ( + SiteTypeGeneral = "general" + SiteTypeInterface = "interface" + SiteTypeBranding = "branding" + SiteTypeWrite = "write" + SiteTypeLegal = "legal" + SiteTypeSeo = "seo" + SiteTypeLogin = "login" + SiteTypeCustomCssHTML = "css-html" + SiteTypeTheme = "theme" + SiteTypePrivileges = "privileges" + SiteTypeUsers = "users" +) diff --git a/internal/base/reason/reason.go b/internal/base/reason/reason.go index b4cdbcb9..91ee74c6 100644 --- a/internal/base/reason/reason.go +++ b/internal/base/reason/reason.go @@ -16,65 +16,70 @@ const ( ) const ( - EmailOrPasswordWrong = "error.object.email_or_password_incorrect" - CommentNotFound = "error.comment.not_found" - CommentCannotEditAfterDeadline = "error.comment.cannot_edit_after_deadline" - QuestionNotFound = "error.question.not_found" - QuestionCannotDeleted = "error.question.cannot_deleted" - QuestionCannotClose = "error.question.cannot_close" - QuestionCannotUpdate = "error.question.cannot_update" - QuestionAlreadyDeleted = "error.question.already_deleted" - AnswerNotFound = "error.answer.not_found" - AnswerCannotDeleted = "error.answer.cannot_deleted" - AnswerCannotUpdate = "error.answer.cannot_update" - AnswerCannotAddByClosedQuestion = "error.answer.question_closed_cannot_add" - CommentEditWithoutPermission = "error.comment.edit_without_permission" - DisallowVote = "error.object.disallow_vote" - DisallowFollow = "error.object.disallow_follow" - DisallowVoteYourSelf = "error.object.disallow_vote_your_self" - CaptchaVerificationFailed = "error.object.captcha_verification_failed" - OldPasswordVerificationFailed = "error.object.old_password_verification_failed" - NewPasswordSameAsPreviousSetting = "error.object.new_password_same_as_previous_setting" - UserNotFound = "error.user.not_found" - UsernameInvalid = "error.user.username_invalid" - UsernameDuplicate = "error.user.username_duplicate" - UserSetAvatar = "error.user.set_avatar" - EmailDuplicate = "error.email.duplicate" - EmailVerifyURLExpired = "error.email.verify_url_expired" - EmailNeedToBeVerified = "error.email.need_to_be_verified" - EmailIllegalDomainError = "error.email.illegal_email_domain_error" - UserSuspended = "error.user.suspended" - ObjectNotFound = "error.object.not_found" - TagNotFound = "error.tag.not_found" - TagNotContainSynonym = "error.tag.not_contain_synonym_tags" - TagCannotUpdate = "error.tag.cannot_update" - TagIsUsedCannotDelete = "error.tag.is_used_cannot_delete" - TagAlreadyExist = "error.tag.already_exist" - RankFailToMeetTheCondition = "error.rank.fail_to_meet_the_condition" - VoteRankFailToMeetTheCondition = "error.rank.vote_fail_to_meet_the_condition" - NoEnoughRankToOperate = "error.rank.no_enough_rank_to_operate" - ThemeNotFound = "error.theme.not_found" - LangNotFound = "error.lang.not_found" - ReportHandleFailed = "error.report.handle_failed" - ReportNotFound = "error.report.not_found" - ReadConfigFailed = "error.config.read_config_failed" - DatabaseConnectionFailed = "error.database.connection_failed" - InstallCreateTableFailed = "error.database.create_table_failed" - InstallConfigFailed = "error.install.create_config_failed" - SiteInfoNotFound = "error.site_info.not_found" - UploadFileSourceUnsupported = "error.upload.source_unsupported" - UploadFileUnsupportedFileFormat = "error.upload.unsupported_file_format" - RecommendTagNotExist = "error.tag.recommend_tag_not_found" - RecommendTagEnter = "error.tag.recommend_tag_enter" - RevisionReviewUnderway = "error.revision.review_underway" - RevisionNoPermission = "error.revision.no_permission" - UserCannotUpdateYourRole = "error.user.cannot_update_your_role" - TagCannotSetSynonymAsItself = "error.tag.cannot_set_synonym_as_itself" - NotAllowedRegistration = "error.user.not_allowed_registration" - SMTPConfigFromNameCannotBeEmail = "error.smtp.config_from_name_cannot_be_email" - AdminCannotUpdateTheirPassword = "error.admin.cannot_update_their_password" - AdminCannotModifySelfStatus = "error.admin.cannot_modify_self_status" - UserExternalLoginUnbindingForbidden = "error.user.external_login_unbinding_forbidden" - UserAccessDenied = "error.user.access_denied" - UserPageAccessDenied = "error.user.page_access_denied" + EmailOrPasswordWrong = "error.object.email_or_password_incorrect" + CommentNotFound = "error.comment.not_found" + CommentCannotEditAfterDeadline = "error.comment.cannot_edit_after_deadline" + QuestionNotFound = "error.question.not_found" + QuestionCannotDeleted = "error.question.cannot_deleted" + QuestionCannotClose = "error.question.cannot_close" + QuestionCannotUpdate = "error.question.cannot_update" + QuestionAlreadyDeleted = "error.question.already_deleted" + AnswerNotFound = "error.answer.not_found" + AnswerCannotDeleted = "error.answer.cannot_deleted" + AnswerCannotUpdate = "error.answer.cannot_update" + AnswerCannotAddByClosedQuestion = "error.answer.question_closed_cannot_add" + CommentEditWithoutPermission = "error.comment.edit_without_permission" + DisallowVote = "error.object.disallow_vote" + DisallowFollow = "error.object.disallow_follow" + DisallowVoteYourSelf = "error.object.disallow_vote_your_self" + CaptchaVerificationFailed = "error.object.captcha_verification_failed" + OldPasswordVerificationFailed = "error.object.old_password_verification_failed" + NewPasswordSameAsPreviousSetting = "error.object.new_password_same_as_previous_setting" + UserNotFound = "error.user.not_found" + UsernameInvalid = "error.user.username_invalid" + UsernameDuplicate = "error.user.username_duplicate" + UserSetAvatar = "error.user.set_avatar" + EmailDuplicate = "error.email.duplicate" + EmailVerifyURLExpired = "error.email.verify_url_expired" + EmailNeedToBeVerified = "error.email.need_to_be_verified" + EmailIllegalDomainError = "error.email.illegal_email_domain_error" + UserSuspended = "error.user.suspended" + ObjectNotFound = "error.object.not_found" + TagNotFound = "error.tag.not_found" + TagNotContainSynonym = "error.tag.not_contain_synonym_tags" + TagCannotUpdate = "error.tag.cannot_update" + TagIsUsedCannotDelete = "error.tag.is_used_cannot_delete" + TagAlreadyExist = "error.tag.already_exist" + RankFailToMeetTheCondition = "error.rank.fail_to_meet_the_condition" + VoteRankFailToMeetTheCondition = "error.rank.vote_fail_to_meet_the_condition" + NoEnoughRankToOperate = "error.rank.no_enough_rank_to_operate" + ThemeNotFound = "error.theme.not_found" + LangNotFound = "error.lang.not_found" + ReportHandleFailed = "error.report.handle_failed" + ReportNotFound = "error.report.not_found" + ReadConfigFailed = "error.config.read_config_failed" + DatabaseConnectionFailed = "error.database.connection_failed" + InstallCreateTableFailed = "error.database.create_table_failed" + InstallConfigFailed = "error.install.create_config_failed" + SiteInfoNotFound = "error.site_info.not_found" + UploadFileSourceUnsupported = "error.upload.source_unsupported" + UploadFileUnsupportedFileFormat = "error.upload.unsupported_file_format" + RecommendTagNotExist = "error.tag.recommend_tag_not_found" + RecommendTagEnter = "error.tag.recommend_tag_enter" + RevisionReviewUnderway = "error.revision.review_underway" + RevisionNoPermission = "error.revision.no_permission" + UserCannotUpdateYourRole = "error.user.cannot_update_your_role" + TagCannotSetSynonymAsItself = "error.tag.cannot_set_synonym_as_itself" + NotAllowedRegistration = "error.user.not_allowed_registration" + SMTPConfigFromNameCannotBeEmail = "error.smtp.config_from_name_cannot_be_email" + AdminCannotUpdateTheirPassword = "error.admin.cannot_update_their_password" + AdminCannotModifySelfStatus = "error.admin.cannot_modify_self_status" + UserAccessDenied = "error.user.access_denied" + UserPageAccessDenied = "error.user.page_access_denied" +) + +// user external login reasons +const ( + UserExternalLoginUnbindingForbidden = "error.user.external_login_unbinding_forbidden" + UserExternalLoginMissingUserID = "error.user.external_login_missing_user_id" ) diff --git a/internal/controller/connector_controller.go b/internal/controller/connector_controller.go index a4ba035b..f3bfdc5a 100644 --- a/internal/controller/connector_controller.go +++ b/internal/controller/connector_controller.go @@ -129,6 +129,10 @@ func (cc *ConnectorController) ConnectorRedirect(connector plugin.Connector) (fn ctx.Redirect(http.StatusFound, "/50x") return } + if len(resp.ErrMsg) > 0 { + ctx.Redirect(http.StatusFound, fmt.Sprintf("/50x?title=%s&msg=%s", resp.ErrTitle, resp.ErrMsg)) + return + } if len(resp.AccessToken) > 0 { ctx.Redirect(http.StatusFound, fmt.Sprintf("%s/users/auth-landing?access_token=%s", siteGeneral.SiteUrl, resp.AccessToken)) diff --git a/internal/controller/notification_controller.go b/internal/controller/notification_controller.go index 7206fead..f42e9073 100644 --- a/internal/controller/notification_controller.go +++ b/internal/controller/notification_controller.go @@ -37,11 +37,7 @@ func NewNotificationController( // @Success 200 {object} handler.RespBody // @Router /answer/api/v1/notification/status [get] func (nc *NotificationController) GetRedDot(ctx *gin.Context) { - req := &schema.GetRedDot{} - - userID := middleware.GetLoginUserIDFromContext(ctx) - req.UserID = userID req.UserID = middleware.GetLoginUserIDFromContext(ctx) canList, err := nc.rankService.CheckOperationPermissions(ctx, req.UserID, []string{ permission.QuestionAudit, @@ -56,8 +52,8 @@ func (nc *NotificationController) GetRedDot(ctx *gin.Context) { req.CanReviewAnswer = canList[1] req.CanReviewTag = canList[2] - RedDot, err := nc.notificationService.GetRedDot(ctx, req) - handler.HandleResponse(ctx, err, RedDot) + resp, err := nc.notificationService.GetRedDot(ctx, req) + handler.HandleResponse(ctx, err, resp) } // ClearRedDot diff --git a/internal/controller/rank_controller.go b/internal/controller/rank_controller.go index b3340f61..4ad38750 100644 --- a/internal/controller/rank_controller.go +++ b/internal/controller/rank_controller.go @@ -27,7 +27,7 @@ func NewRankController( // @Param page query int false "page" // @Param page_size query int false "page size" // @Param username query string false "username" -// @Success 200 {object} handler.RespBody{data=pager.PageModel{list=[]schema.GetRankPersonalWithPageResp}} +// @Success 200 {object} handler.RespBody{data=pager.PageModel{list=[]schema.GetRankPersonalPageResp}} // @Router /answer/api/v1/personal/rank/page [get] func (cc *RankController) GetRankPersonalWithPage(ctx *gin.Context) { req := &schema.GetRankPersonalWithPageReq{} @@ -37,6 +37,6 @@ func (cc *RankController) GetRankPersonalWithPage(ctx *gin.Context) { req.UserID = middleware.GetLoginUserIDFromContext(ctx) - resp, err := cc.rankService.GetRankPersonalWithPage(ctx, req) + resp, err := cc.rankService.GetRankPersonalPage(ctx, req) handler.HandleResponse(ctx, err, resp) } diff --git a/internal/controller/template_controller.go b/internal/controller/template_controller.go index 3a2bd095..cf9dd5ee 100644 --- a/internal/controller/template_controller.go +++ b/internal/controller/template_controller.go @@ -14,6 +14,7 @@ import ( templaterender "github.com/answerdev/answer/internal/controller/template_render" "github.com/answerdev/answer/internal/schema" "github.com/answerdev/answer/internal/service/siteinfo_common" + "github.com/answerdev/answer/pkg/checker" "github.com/answerdev/answer/pkg/converter" "github.com/answerdev/answer/pkg/htmltext" "github.com/answerdev/answer/pkg/obj" @@ -183,9 +184,9 @@ func (tc *TemplateController) QuestionInfoeRdirect(ctx *gin.Context, siteInfo *s titleIsAnswerID = true } } - + siteInfo = tc.SiteInfo(ctx) url = fmt.Sprintf("%s/questions/%s", siteInfo.General.SiteUrl, id) - if siteInfo.SiteSeo.PermaLink == schema.PermaLinkQuestionID { + if siteInfo.SiteSeo.PermaLink == schema.PermaLinkQuestionID || siteInfo.SiteSeo.PermaLink == schema.PermaLinkQuestionIDByShortID { if len(ctx.Request.URL.Query()) > 0 { url = fmt.Sprintf("%s?%s", url, ctx.Request.URL.RawQuery) } @@ -229,8 +230,8 @@ func (tc *TemplateController) QuestionInfo(ctx *gin.Context) { id := ctx.Param("id") title := ctx.Param("title") answerid := ctx.Param("answerid") - - if id == "ask" { + if checker.IsQuestionsIgnorePath(id) { + // if id == "ask" { file, err := ui.Build.ReadFile("build/index.html") if err != nil { log.Error(err) @@ -421,7 +422,8 @@ func (tc *TemplateController) UserInfo(ctx *gin.Context) { tc.Page404(ctx) return } - exist := constant.ExistInPathIgnore(username) + + exist := checker.IsUsersIgnorePath(username) if exist { file, err := ui.Build.ReadFile("build/index.html") if err != nil { diff --git a/internal/controller/user_controller.go b/internal/controller/user_controller.go index 4fbf0482..88e57ca3 100644 --- a/internal/controller/user_controller.go +++ b/internal/controller/user_controller.go @@ -55,7 +55,7 @@ func NewUserController( // @Accept json // @Produce json // @Security ApiKeyAuth -// @Success 200 {object} handler.RespBody{data=schema.GetUserToSetShowResp} +// @Success 200 {object} handler.RespBody{data=schema.GetCurrentLoginUserInfoResp} // @Router /answer/api/v1/user/info [get] func (uc *UserController) GetUserInfoByUserID(ctx *gin.Context) { token := middleware.ExtractToken(ctx) @@ -102,7 +102,7 @@ func (uc *UserController) GetOtherUserInfoByUsername(ctx *gin.Context) { // @Accept json // @Produce json // @Param data body schema.UserEmailLogin true "UserEmailLogin" -// @Success 200 {object} handler.RespBody{data=schema.GetUserResp} +// @Success 200 {object} handler.RespBody{data=schema.UserLoginResp} // @Router /answer/api/v1/user/login/email [post] func (uc *UserController) UserEmailLogin(ctx *gin.Context) { req := &schema.UserEmailLogin{} @@ -215,7 +215,7 @@ func (uc *UserController) UserLogout(ctx *gin.Context) { // @Accept json // @Produce json // @Param data body schema.UserRegisterReq true "UserRegisterReq" -// @Success 200 {object} handler.RespBody{data=schema.GetUserResp} +// @Success 200 {object} handler.RespBody{data=schema.UserLoginResp} // @Router /answer/api/v1/user/register/email [post] func (uc *UserController) UserRegisterByEmail(ctx *gin.Context) { // check whether site allow register or not @@ -267,7 +267,7 @@ func (uc *UserController) UserRegisterByEmail(ctx *gin.Context) { // @Accept json // @Produce json // @Param code query string true "code" default() -// @Success 200 {object} handler.RespBody{data=schema.GetUserResp} +// @Success 200 {object} handler.RespBody{data=schema.UserLoginResp} // @Router /answer/api/v1/user/email/verification [post] func (uc *UserController) UserVerifyEmail(ctx *gin.Context) { req := &schema.UserVerifyEmailReq{} @@ -464,7 +464,7 @@ func (uc *UserController) ActionRecord(ctx *gin.Context) { // @Tags User // @Accept json // @Produce json -// @Success 200 {object} handler.RespBody{data=schema.GetUserResp} +// @Success 200 {object} handler.RespBody{data=schema.UserLoginResp} // @Router /answer/api/v1/user/register/captcha [get] func (uc *UserController) UserRegisterCaptcha(ctx *gin.Context) { resp, err := uc.actionService.UserRegisterCaptcha(ctx) diff --git a/internal/entity/config_entity.go b/internal/entity/config_entity.go index 361e7acc..908903a1 100644 --- a/internal/entity/config_entity.go +++ b/internal/entity/config_entity.go @@ -1,5 +1,11 @@ package entity +import ( + "encoding/json" + + "github.com/answerdev/answer/pkg/converter" +) + // Config config type Config struct { ID int `xorm:"not null pk autoincr INT(11) id"` @@ -8,6 +14,36 @@ type Config struct { } // TableName config table name -func (Config) TableName() string { +func (c *Config) TableName() string { return "config" } + +func (c *Config) BuildByJSON(data []byte) { + cf := &Config{} + _ = json.Unmarshal(data, cf) + c.ID = cf.ID + c.Key = cf.Key + c.Value = cf.Value +} + +func (c *Config) JsonString() string { + data, _ := json.Marshal(c) + return string(data) +} + +// GetIntValue get int value +func (c *Config) GetIntValue() int { + return converter.StringToInt(c.Value) +} + +// GetArrayStringValue get array string value +func (c *Config) GetArrayStringValue() []string { + var arr []string + _ = json.Unmarshal([]byte(c.Value), &arr) + return arr +} + +// GetByteValue get byte value +func (c *Config) GetByteValue() []byte { + return []byte(c.Value) +} diff --git a/internal/migrations/v12.go b/internal/migrations/v12.go index 2107228b..850146ed 100644 --- a/internal/migrations/v12.go +++ b/internal/migrations/v12.go @@ -14,7 +14,6 @@ type QuestionPostTime struct { CreatedAt time.Time `xorm:"not null default CURRENT_TIMESTAMP TIMESTAMP created_at"` UpdatedAt time.Time `xorm:"updated_at TIMESTAMP"` UserID string `xorm:"not null default 0 BIGINT(20) INDEX user_id"` - InviteUserID string `xorm:"TEXT invite_user_id"` LastEditUserID string `xorm:"not null default 0 BIGINT(20) last_edit_user_id"` Title string `xorm:"not null default '' VARCHAR(150) title"` OriginalText string `xorm:"not null MEDIUMTEXT original_text"` diff --git a/internal/repo/activity/activity_repo.go b/internal/repo/activity/activity_repo.go index 3f8ad4b2..c1c9f6b0 100644 --- a/internal/repo/activity/activity_repo.go +++ b/internal/repo/activity/activity_repo.go @@ -2,48 +2,41 @@ package activity import ( "context" - "fmt" - "github.com/answerdev/answer/internal/base/constant" "github.com/answerdev/answer/internal/base/data" "github.com/answerdev/answer/internal/base/reason" "github.com/answerdev/answer/internal/entity" - "github.com/answerdev/answer/internal/repo/config" "github.com/answerdev/answer/internal/service/activity" + "github.com/answerdev/answer/internal/service/activity_type" + "github.com/answerdev/answer/internal/service/config" "github.com/segmentfault/pacman/errors" + "github.com/segmentfault/pacman/log" ) // activityRepo activity repository type activityRepo struct { - data *data.Data + data *data.Data + configService *config.ConfigService } // NewActivityRepo new repository func NewActivityRepo( data *data.Data, + configService *config.ConfigService, ) activity.ActivityRepo { return &activityRepo{ - data: data, + data: data, + configService: configService, } } func (ar *activityRepo) GetObjectAllActivity(ctx context.Context, objectID string, showVote bool) ( activityList []*entity.Activity, err error) { activityList = make([]*entity.Activity, 0) - session := ar.data.DB.Desc("created_at") + session := ar.data.DB.Context(ctx).Desc("created_at") if !showVote { - var activityTypeNotShown []int - for _, obj := range []string{constant.AnswerObjectType, constant.QuestionObjectType, constant.CommentObjectType} { - for _, act := range []string{ - constant.ActVotedDown, - constant.ActVotedUp, - constant.ActVoteDown, - constant.ActVoteUp, - } { - activityTypeNotShown = append(activityTypeNotShown, config.Key2IDMapping[fmt.Sprintf("%s.%s", obj, act)]) - } - } + activityTypeNotShown := ar.getAllActivityType(ctx) session.NotIn("activity_type", activityTypeNotShown) } err = session.Find(&activityList, &entity.Activity{OriginalObjectID: objectID}) @@ -52,3 +45,16 @@ func (ar *activityRepo) GetObjectAllActivity(ctx context.Context, objectID strin } return activityList, nil } + +func (ar *activityRepo) getAllActivityType(ctx context.Context) (activityTypes []int) { + var activityTypeNotShown []int + for _, key := range activity_type.VoteActivityTypeList { + id, err := ar.configService.GetIDByKey(ctx, key) + if err != nil { + log.Errorf("get config id by key [%s] error: %v", key, err) + } else { + activityTypeNotShown = append(activityTypeNotShown, id) + } + } + return activityTypeNotShown +} diff --git a/internal/repo/activity/answer_repo.go b/internal/repo/activity/answer_repo.go index 02e9c511..6ed8bad4 100644 --- a/internal/repo/activity/answer_repo.go +++ b/internal/repo/activity/answer_repo.go @@ -63,7 +63,7 @@ func NewQuestionActivityRepo( func (ar *AnswerActivityRepo) DeleteQuestion(ctx context.Context, questionID string) (err error) { questionInfo := &entity.Question{} - exist, err := ar.data.DB.Where("id = ?", questionID).Get(questionInfo) + exist, err := ar.data.DB.Context(ctx).Where("id = ?", questionID).Get(questionInfo) if err != nil { return errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -73,7 +73,7 @@ func (ar *AnswerActivityRepo) DeleteQuestion(ctx context.Context, questionID str // get all this object activity activityList := make([]*entity.Activity, 0) - session := ar.data.DB.Where("has_rank = 1") + session := ar.data.DB.Context(ctx).Where("has_rank = 1") session.Where("cancelled = ?", entity.ActivityAvailable) err = session.Find(&activityList, &entity.Activity{ObjectID: questionID}) if err != nil { @@ -86,6 +86,7 @@ func (ar *AnswerActivityRepo) DeleteQuestion(ctx context.Context, questionID str log.Infof("questionInfo %s deleted will rollback activity %d", questionID, len(activityList)) _, err = ar.data.DB.Transaction(func(session *xorm.Session) (result any, err error) { + session = session.Context(ctx) for _, act := range activityList { log.Infof("user %s rollback rank %d", act.UserID, -act.Rank) _, e := ar.userRankRepo.TriggerUserRank( @@ -107,7 +108,7 @@ func (ar *AnswerActivityRepo) DeleteQuestion(ctx context.Context, questionID str // get all answers answerList := make([]*entity.Answer, 0) - err = ar.data.DB.Find(&answerList, &entity.Answer{QuestionID: questionID}) + err = ar.data.DB.Context(ctx).Find(&answerList, &entity.Answer{QuestionID: questionID}) if err != nil { return errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -149,11 +150,13 @@ func (ar *AnswerActivityRepo) AcceptAnswer(ctx context.Context, } if isSelf { addActivity.Rank = 0 + addActivity.HasRank = 0 } addActivityList = append(addActivityList, addActivity) } _, err = ar.data.DB.Transaction(func(session *xorm.Session) (result any, err error) { + session = session.Context(ctx) for _, addActivity := range addActivityList { existsActivity, exists, e := ar.activityRepo.GetActivity( ctx, session, answerObjID, addActivity.UserID, addActivity.ActivityType) @@ -164,13 +167,16 @@ func (ar *AnswerActivityRepo) AcceptAnswer(ctx context.Context, continue } - reachStandard, e := ar.userRankRepo.TriggerUserRank( - ctx, session, addActivity.UserID, addActivity.Rank, addActivity.ActivityType) - if e != nil { - return nil, errors.InternalServer(reason.DatabaseError).WithError(e).WithStack() - } - if reachStandard { - addActivity.Rank = 0 + // trigger user rank and send notification + if addActivity.Rank != 0 { + reachStandard, e := ar.userRankRepo.TriggerUserRank( + ctx, session, addActivity.UserID, addActivity.Rank, addActivity.ActivityType) + if e != nil { + return nil, errors.InternalServer(reason.DatabaseError).WithError(e).WithStack() + } + if reachStandard { + addActivity.Rank = 0 + } } if exists { @@ -251,6 +257,7 @@ func (ar *AnswerActivityRepo) CancelAcceptAnswer(ctx context.Context, } _, err = ar.data.DB.Transaction(func(session *xorm.Session) (result any, err error) { + session = session.Context(ctx) for _, addActivity := range addActivityList { existsActivity, exists, e := ar.activityRepo.GetActivity( ctx, session, answerObjID, addActivity.UserID, addActivity.ActivityType) @@ -264,10 +271,12 @@ func (ar *AnswerActivityRepo) CancelAcceptAnswer(ctx context.Context, continue } - _, e = ar.userRankRepo.TriggerUserRank( - ctx, session, addActivity.UserID, addActivity.Rank, addActivity.ActivityType) - if e != nil { - return nil, errors.InternalServer(reason.DatabaseError).WithError(e).WithStack() + if existsActivity.Rank != 0 { + _, e = ar.userRankRepo.TriggerUserRank( + ctx, session, addActivity.UserID, addActivity.Rank, addActivity.ActivityType) + if e != nil { + return nil, errors.InternalServer(reason.DatabaseError).WithError(e).WithStack() + } } if _, e := session.Where("id = ?", existsActivity.ID).Cols("cancelled", "cancelled_at"). @@ -293,14 +302,16 @@ func (ar *AnswerActivityRepo) CancelAcceptAnswer(ctx context.Context, msg.TriggerUserID = questionUserID msg.ObjectType = constant.AnswerObjectType } - notice_queue.AddNotification(msg) + if msg.TriggerUserID != msg.ReceiverUserID { + notice_queue.AddNotification(msg) + } } return err } func (ar *AnswerActivityRepo) DeleteAnswer(ctx context.Context, answerID string) (err error) { answerInfo := &entity.Answer{} - exist, err := ar.data.DB.Where("id = ?", answerID).Get(answerInfo) + exist, err := ar.data.DB.Context(ctx).Where("id = ?", answerID).Get(answerInfo) if err != nil { return errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -310,7 +321,7 @@ func (ar *AnswerActivityRepo) DeleteAnswer(ctx context.Context, answerID string) // get all this object activity activityList := make([]*entity.Activity, 0) - session := ar.data.DB.Where("has_rank = 1") + session := ar.data.DB.Context(ctx).Where("has_rank = 1") session.Where("cancelled = ?", entity.ActivityAvailable) err = session.Find(&activityList, &entity.Activity{ObjectID: answerID}) if err != nil { @@ -323,6 +334,7 @@ func (ar *AnswerActivityRepo) DeleteAnswer(ctx context.Context, answerID string) log.Infof("answerInfo %s deleted will rollback activity %d", answerID, len(activityList)) _, err = ar.data.DB.Transaction(func(session *xorm.Session) (result any, err error) { + session = session.Context(ctx) for _, act := range activityList { log.Infof("user %s rollback rank %d", act.UserID, -act.Rank) _, e := ar.userRankRepo.TriggerUserRank( diff --git a/internal/repo/activity/follow_repo.go b/internal/repo/activity/follow_repo.go index bb1a0a0c..8f9ade89 100644 --- a/internal/repo/activity/follow_repo.go +++ b/internal/repo/activity/follow_repo.go @@ -39,12 +39,17 @@ func NewFollowRepo( } func (ar *FollowRepo) Follow(ctx context.Context, objectID, userID string) error { - activityType, _, _, err := ar.activityRepo.GetActivityTypeByObjID(ctx, objectID, "follow") + objectTypeStr, err := obj.GetObjectTypeStrByObjectID(objectID) + if err != nil { + return errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() + } + activityType, err := ar.activityRepo.GetActivityTypeByObjKey(ctx, objectTypeStr, "follow") if err != nil { return err } _, err = ar.data.DB.Transaction(func(session *xorm.Session) (result any, err error) { + session = session.Context(ctx) var ( existsActivity entity.Activity has bool @@ -101,12 +106,17 @@ func (ar *FollowRepo) Follow(ctx context.Context, objectID, userID string) error } func (ar *FollowRepo) FollowCancel(ctx context.Context, objectID, userID string) error { - activityType, _, _, err := ar.activityRepo.GetActivityTypeByObjID(ctx, objectID, "follow") + objectTypeStr, err := obj.GetObjectTypeStrByObjectID(objectID) + if err != nil { + return errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() + } + activityType, err := ar.activityRepo.GetActivityTypeByObjKey(ctx, objectTypeStr, "follow") if err != nil { return err } _, err = ar.data.DB.Transaction(func(session *xorm.Session) (result any, err error) { + session = session.Context(ctx) var ( existsActivity entity.Activity has bool diff --git a/internal/repo/activity/user_active_repo.go b/internal/repo/activity/user_active_repo.go index 1b75adac..0f6099d1 100644 --- a/internal/repo/activity/user_active_repo.go +++ b/internal/repo/activity/user_active_repo.go @@ -16,10 +16,10 @@ import ( // UserActiveActivityRepo answer accepted type UserActiveActivityRepo struct { - data *data.Data - activityRepo activity_common.ActivityRepo - userRankRepo rank.UserRankRepo - configRepo config.ConfigRepo + data *data.Data + activityRepo activity_common.ActivityRepo + userRankRepo rank.UserRankRepo + configService *config.ConfigService } const ( @@ -31,37 +31,36 @@ func NewUserActiveActivityRepo( data *data.Data, activityRepo activity_common.ActivityRepo, userRankRepo rank.UserRankRepo, - configRepo config.ConfigRepo, + configService *config.ConfigService, ) activity.UserActiveActivityRepo { return &UserActiveActivityRepo{ - data: data, - activityRepo: activityRepo, - userRankRepo: userRankRepo, - configRepo: configRepo, + data: data, + activityRepo: activityRepo, + userRankRepo: userRankRepo, + configService: configService, } } // UserActive accept other answer func (ar *UserActiveActivityRepo) UserActive(ctx context.Context, userID string) (err error) { + cfg, err := ar.configService.GetConfigByKey(ctx, UserActivated) + if err != nil { + return err + } + activityType := cfg.ID + deltaRank := cfg.GetIntValue() + addActivity := &entity.Activity{ + UserID: userID, + ObjectID: "0", + OriginalObjectID: "0", + ActivityType: activityType, + Rank: deltaRank, + HasRank: 1, + } + _, err = ar.data.DB.Transaction(func(session *xorm.Session) (result any, err error) { + session = session.Context(ctx) - activityType, err := ar.configRepo.GetConfigType(UserActivated) - if err != nil { - return nil, err - } - deltaRank, err := ar.configRepo.GetInt(UserActivated) - if err != nil { - return nil, err - } - - addActivity := &entity.Activity{ - UserID: userID, - ObjectID: "0", - OriginalObjectID: "0", - ActivityType: activityType, - Rank: deltaRank, - HasRank: 1, - } _, exists, err := ar.activityRepo.GetActivity(ctx, session, "0", addActivity.UserID, activityType) if err != nil { return nil, errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() diff --git a/internal/repo/activity/vote_repo.go b/internal/repo/activity/vote_repo.go index 1303f3c7..58bf1510 100644 --- a/internal/repo/activity/vote_repo.go +++ b/internal/repo/activity/vote_repo.go @@ -30,30 +30,30 @@ import ( // VoteRepo activity repository type VoteRepo struct { - data *data.Data - uniqueIDRepo unique.UniqueIDRepo - configRepo config.ConfigRepo - activityRepo activity_common.ActivityRepo - userRankRepo rank.UserRankRepo - voteCommon activity_common.VoteRepo + data *data.Data + uniqueIDRepo unique.UniqueIDRepo + configService *config.ConfigService + activityRepo activity_common.ActivityRepo + userRankRepo rank.UserRankRepo + voteCommon activity_common.VoteRepo } // NewVoteRepo new repository func NewVoteRepo( data *data.Data, uniqueIDRepo unique.UniqueIDRepo, - configRepo config.ConfigRepo, + configService *config.ConfigService, activityRepo activity_common.ActivityRepo, userRankRepo rank.UserRankRepo, voteCommon activity_common.VoteRepo, ) service.VoteRepo { return &VoteRepo{ - data: data, - uniqueIDRepo: uniqueIDRepo, - configRepo: configRepo, - activityRepo: activityRepo, - userRankRepo: userRankRepo, - voteCommon: voteCommon, + data: data, + uniqueIDRepo: uniqueIDRepo, + configService: configService, + activityRepo: activityRepo, + userRankRepo: userRankRepo, + voteCommon: voteCommon, } } @@ -75,6 +75,7 @@ func (vr *VoteRepo) vote(ctx context.Context, objectID string, userID, objectUse sendInboxNotification := false upVote := false _, err = vr.data.DB.Transaction(func(session *xorm.Session) (result any, err error) { + session = session.Context(ctx) result = nil for _, action := range actions { var ( @@ -185,6 +186,7 @@ func (vr *VoteRepo) voteCancel(ctx context.Context, objectID string, userID, obj resp = &schema.VoteResp{} notificationUserIDs := make([]string, 0) _, err = vr.data.DB.Transaction(func(session *xorm.Session) (result any, err error) { + session = session.Context(ctx) for _, action := range actions { var ( existsActivity entity.Activity @@ -362,7 +364,7 @@ func (vr *VoteRepo) GetVoteResultByObjectId(ctx context.Context, objectID string activityType, _, _, _ = vr.activityRepo.GetActivityTypeByObjID(ctx, objectID, action) - votes, err = vr.data.DB.Where(builder.Eq{"object_id": objectID}). + votes, err = vr.data.DB.Context(ctx).Where(builder.Eq{"object_id": objectID}). And(builder.Eq{"activity_type": activityType}). And(builder.Eq{"cancelled": 0}). Count(&activity) @@ -389,7 +391,7 @@ func (vr *VoteRepo) ListUserVotes( req schema.GetVoteWithPageReq, activityTypes []int, ) (voteList []entity.Activity, total int64, err error) { - session := vr.data.DB.NewSession() + session := vr.data.DB.Context(ctx) cond := builder. And( builder.Eq{"user_id": userID}, diff --git a/internal/repo/activity_common/activity_repo.go b/internal/repo/activity_common/activity_repo.go index 008eeecb..a59b7085 100644 --- a/internal/repo/activity_common/activity_repo.go +++ b/internal/repo/activity_common/activity_repo.go @@ -21,34 +21,37 @@ import ( // ActivityRepo activity repository type ActivityRepo struct { - data *data.Data - uniqueIDRepo unique.UniqueIDRepo - configRepo config.ConfigRepo + data *data.Data + uniqueIDRepo unique.UniqueIDRepo + configService *config.ConfigService } // NewActivityRepo new repository func NewActivityRepo( data *data.Data, uniqueIDRepo unique.UniqueIDRepo, - configRepo config.ConfigRepo, + configService *config.ConfigService, ) activity_common.ActivityRepo { return &ActivityRepo{ - data: data, - uniqueIDRepo: uniqueIDRepo, - configRepo: configRepo, + data: data, + uniqueIDRepo: uniqueIDRepo, + configService: configService, } } -func (ar *ActivityRepo) GetActivityTypeByObjID(ctx context.Context, objectID string, action string) (activityType, rank, hasRank int, err error) { +func (ar *ActivityRepo) GetActivityTypeByObjID(ctx context.Context, objectID string, action string) ( + activityType, rank, hasRank int, err error) { objectKey, err := obj.GetObjectTypeStrByObjectID(objectID) if err != nil { return } confKey := fmt.Sprintf("%s.%s", objectKey, action) - activityType, _ = ar.configRepo.GetConfigType(confKey) - - rank, err = ar.configRepo.GetInt(confKey) + cfg, err := ar.configService.GetConfigByKey(ctx, confKey) + if err != nil { + return + } + activityType, rank = cfg.ID, cfg.GetIntValue() hasRank = 0 if rank != 0 { hasRank = 1 @@ -57,20 +60,20 @@ func (ar *ActivityRepo) GetActivityTypeByObjID(ctx context.Context, objectID str } func (ar *ActivityRepo) GetActivityTypeByObjKey(ctx context.Context, objectKey, action string) (activityType int, err error) { - confKey := fmt.Sprintf("%s.%s", objectKey, action) - activityType, err = ar.configRepo.GetConfigType(confKey) + configKey := fmt.Sprintf("%s.%s", objectKey, action) + cfg, err := ar.configService.GetConfigByKey(ctx, configKey) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } - return + return cfg.ID, nil } func (ar *ActivityRepo) GetActivityTypeByConfigKey(ctx context.Context, configKey string) (activityType int, err error) { - activityType, err = ar.configRepo.GetConfigType(configKey) + cfg, err := ar.configService.GetConfigByKey(ctx, configKey) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } - return + return cfg.ID, nil } func (ar *ActivityRepo) GetActivity(ctx context.Context, session *xorm.Session, @@ -87,7 +90,7 @@ func (ar *ActivityRepo) GetActivity(ctx context.Context, session *xorm.Session, func (ar *ActivityRepo) GetUserIDObjectIDActivitySum(ctx context.Context, userID, objectID string) (int, error) { sum := &entity.ActivityRankSum{} - _, err := ar.data.DB.Table(entity.Activity{}.TableName()). + _, err := ar.data.DB.Context(ctx).Table(entity.Activity{}.TableName()). Select("sum(`rank`) as `rank`"). Where("user_id =?", userID). And("object_id = ?", objectID). @@ -102,7 +105,7 @@ func (ar *ActivityRepo) GetUserIDObjectIDActivitySum(ctx context.Context, userID // AddActivity add activity func (ar *ActivityRepo) AddActivity(ctx context.Context, activity *entity.Activity) (err error) { - _, err = ar.data.DB.Insert(activity) + _, err = ar.data.DB.Context(ctx).Insert(activity) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -113,7 +116,7 @@ func (ar *ActivityRepo) AddActivity(ctx context.Context, activity *entity.Activi func (ar *ActivityRepo) GetUsersWhoHasGainedTheMostReputation( ctx context.Context, startTime, endTime time.Time, limit int) (rankStat []*entity.ActivityUserRankStat, err error) { rankStat = make([]*entity.ActivityUserRankStat, 0) - session := ar.data.DB.Select("user_id, SUM(`rank`) AS rank_amount").Table("activity") + session := ar.data.DB.Context(ctx).Select("user_id, SUM(`rank`) AS rank_amount").Table("activity") session.Where("has_rank = 1 AND cancelled = 0") session.Where("created_at >= ?", startTime) session.Where("created_at <= ?", endTime) @@ -134,13 +137,13 @@ func (ar *ActivityRepo) GetUsersWhoHasVoteMost( actIDs := make([]int, 0) for _, act := range activity_type.ActivityTypeList { - configType, err := ar.configRepo.GetConfigType(act) + cfg, err := ar.configService.GetConfigByKey(ctx, act) if err == nil { - actIDs = append(actIDs, configType) + actIDs = append(actIDs, cfg.ID) } } - session := ar.data.DB.Select("user_id, COUNT(*) AS vote_count").Table("activity") + session := ar.data.DB.Context(ctx).Select("user_id, COUNT(*) AS vote_count").Table("activity") session.Where("cancelled = 0") session.In("activity_type", actIDs) session.Where("created_at >= ?", startTime) diff --git a/internal/repo/activity_common/follow.go b/internal/repo/activity_common/follow.go index 5f7b0ec0..11b5763c 100644 --- a/internal/repo/activity_common/follow.go +++ b/internal/repo/activity_common/follow.go @@ -41,19 +41,19 @@ func (ar *FollowRepo) GetFollowAmount(ctx context.Context, objectID string) (fol switch objectType { case "question": model := &entity.Question{} - _, err = ar.data.DB.Where("id = ?", objectID).Cols("`follow_count`").Get(model) + _, err = ar.data.DB.Context(ctx).Where("id = ?", objectID).Cols("`follow_count`").Get(model) if err == nil { follows = int(model.FollowCount) } case "user": model := &entity.User{} - _, err = ar.data.DB.Where("id = ?", objectID).Cols("`follow_count`").Get(model) + _, err = ar.data.DB.Context(ctx).Where("id = ?", objectID).Cols("`follow_count`").Get(model) if err == nil { follows = int(model.FollowCount) } case "tag": model := &entity.Tag{} - _, err = ar.data.DB.Where("id = ?", objectID).Cols("`follow_count`").Get(model) + _, err = ar.data.DB.Context(ctx).Where("id = ?", objectID).Cols("`follow_count`").Get(model) if err == nil { follows = int(model.FollowCount) } @@ -79,7 +79,7 @@ func (ar *FollowRepo) GetFollowUserIDs(ctx context.Context, objectID string) (us } userIDs = make([]string, 0) - session := ar.data.DB.Select("user_id") + session := ar.data.DB.Context(ctx).Select("user_id") session.Table(entity.Activity{}.TableName()) session.Where("object_id = ?", objectID) session.Where("activity_type = ?", activityType) @@ -98,7 +98,7 @@ func (ar *FollowRepo) GetFollowIDs(ctx context.Context, userID, objectKey string if err != nil { return nil, errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } - session := ar.data.DB.Select("object_id") + session := ar.data.DB.Context(ctx).Select("object_id") session.Table(entity.Activity{}.TableName()) session.Where("user_id = ? AND activity_type = ?", userID, activityType) session.Where("cancelled = 0") @@ -110,14 +110,19 @@ func (ar *FollowRepo) GetFollowIDs(ctx context.Context, userID, objectKey string } // IsFollowed check user if follow object or not -func (ar *FollowRepo) IsFollowed(userID, objectID string) (bool, error) { - activityType, _, _, err := ar.activityRepo.GetActivityTypeByObjID(context.TODO(), objectID, "follow") +func (ar *FollowRepo) IsFollowed(ctx context.Context, userID, objectID string) (followed bool, err error) { + objectKey, err := obj.GetObjectTypeStrByObjectID(objectID) + if err != nil { + return false, err + } + + activityType, err := ar.activityRepo.GetActivityTypeByObjKey(ctx, objectKey, "follow") if err != nil { return false, err } at := &entity.Activity{} - has, err := ar.data.DB.Where("user_id = ? AND object_id = ? AND activity_type = ?", userID, objectID, activityType).Get(at) + has, err := ar.data.DB.Context(ctx).Where("user_id = ? AND object_id = ? AND activity_type = ?", userID, objectID, activityType).Get(at) if err != nil { return false, err } diff --git a/internal/repo/activity_common/vote.go b/internal/repo/activity_common/vote.go index 16f73fc4..56c33798 100644 --- a/internal/repo/activity_common/vote.go +++ b/internal/repo/activity_common/vote.go @@ -8,6 +8,7 @@ import ( "github.com/answerdev/answer/internal/entity" "github.com/answerdev/answer/internal/service/activity_common" "github.com/segmentfault/pacman/errors" + "github.com/segmentfault/pacman/log" ) // VoteRepo activity repository @@ -31,8 +32,9 @@ func (vr *VoteRepo) GetVoteStatus(ctx context.Context, objectID, userID string) if err != nil { return "" } - has, err := vr.data.DB.Where("object_id =? AND cancelled=0 AND activity_type=? AND user_id=?", objectID, activityType, userID).Get(at) + has, err := vr.data.DB.Context(ctx).Where("object_id =? AND cancelled=0 AND activity_type=? AND user_id=?", objectID, activityType, userID).Get(at) if err != nil { + log.Error(err) return "" } if has { @@ -44,7 +46,7 @@ func (vr *VoteRepo) GetVoteStatus(ctx context.Context, objectID, userID string) func (vr *VoteRepo) GetVoteCount(ctx context.Context, activityTypes []int) (count int64, err error) { list := make([]*entity.Activity, 0) - count, err = vr.data.DB.Where("cancelled =0").In("activity_type", activityTypes).FindAndCount(&list) + count, err = vr.data.DB.Context(ctx).Where("cancelled =0").In("activity_type", activityTypes).FindAndCount(&list) if err != nil { return count, errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } diff --git a/internal/repo/answer/answer_repo.go b/internal/repo/answer/answer_repo.go index ef6592aa..77b76779 100644 --- a/internal/repo/answer/answer_repo.go +++ b/internal/repo/answer/answer_repo.go @@ -53,7 +53,7 @@ func (ar *answerRepo) AddAnswer(ctx context.Context, answer *entity.Answer) (err return errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } answer.ID = ID - _, err = ar.data.DB.Insert(answer) + _, err = ar.data.DB.Context(ctx).Insert(answer) if err != nil { return errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() @@ -70,7 +70,7 @@ func (ar *answerRepo) RemoveAnswer(ctx context.Context, id string) (err error) { ID: id, Status: entity.AnswerStatusDeleted, } - _, err = ar.data.DB.Where("id = ?", id).Cols("status").Update(answer) + _, err = ar.data.DB.Context(ctx).Where("id = ?", id).Cols("status").Update(answer) if err != nil { return errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -81,7 +81,7 @@ func (ar *answerRepo) RemoveAnswer(ctx context.Context, id string) (err error) { func (ar *answerRepo) UpdateAnswer(ctx context.Context, answer *entity.Answer, Colar []string) (err error) { answer.ID = uid.DeShortID(answer.ID) answer.QuestionID = uid.DeShortID(answer.QuestionID) - _, err = ar.data.DB.ID(answer.ID).Cols(Colar...).Update(answer) + _, err = ar.data.DB.Context(ctx).ID(answer.ID).Cols(Colar...).Update(answer) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -92,7 +92,7 @@ func (ar *answerRepo) UpdateAnswerStatus(ctx context.Context, answer *entity.Ans now := time.Now() answer.ID = uid.DeShortID(answer.ID) answer.UpdatedAt = now - _, err = ar.data.DB.Where("id =?", answer.ID).Cols("status", "updated_at").Update(answer) + _, err = ar.data.DB.Context(ctx).Where("id =?", answer.ID).Cols("status", "updated_at").Update(answer) if err != nil { return errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -105,7 +105,7 @@ func (ar *answerRepo) GetAnswer(ctx context.Context, id string) ( ) { id = uid.DeShortID(id) answer = &entity.Answer{} - exist, err = ar.data.DB.ID(id).Get(answer) + exist, err = ar.data.DB.Context(ctx).ID(id).Get(answer) if err != nil { return nil, false, errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -118,7 +118,7 @@ func (ar *answerRepo) GetAnswer(ctx context.Context, id string) ( // GetQuestionCount func (ar *answerRepo) GetAnswerCount(ctx context.Context) (count int64, err error) { list := make([]*entity.Answer, 0) - count, err = ar.data.DB.Where("status = ?", entity.AnswerStatusAvailable).FindAndCount(&list) + count, err = ar.data.DB.Context(ctx).Where("status = ?", entity.AnswerStatusAvailable).FindAndCount(&list) if err != nil { return count, errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -130,7 +130,7 @@ func (ar *answerRepo) GetAnswerList(ctx context.Context, answer *entity.Answer) answerList = make([]*entity.Answer, 0) answer.ID = uid.DeShortID(answer.ID) answer.QuestionID = uid.DeShortID(answer.QuestionID) - err = ar.data.DB.Find(answerList, answer) + err = ar.data.DB.Context(ctx).Find(answerList, answer) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -146,7 +146,7 @@ func (ar *answerRepo) GetAnswerPage(ctx context.Context, page, pageSize int, ans answer.ID = uid.DeShortID(answer.ID) answer.QuestionID = uid.DeShortID(answer.QuestionID) answerList = make([]*entity.Answer, 0) - total, err = pager.Help(page, pageSize, answerList, answer, ar.data.DB.NewSession()) + total, err = pager.Help(page, pageSize, answerList, answer, ar.data.DB.Context(ctx)) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -169,13 +169,13 @@ func (ar *answerRepo) UpdateAccepted(ctx context.Context, id string, questionID data.ID = id data.Accepted = schema.AnswerAcceptedFailed - _, err := ar.data.DB.Where("question_id =?", questionID).Cols("adopted").Update(&data) + _, err := ar.data.DB.Context(ctx).Where("question_id =?", questionID).Cols("adopted").Update(&data) if err != nil { return err } if id != "0" { data.Accepted = schema.AnswerAcceptedEnable - _, err = ar.data.DB.Where("id = ?", id).Cols("adopted").Update(&data) + _, err = ar.data.DB.Context(ctx).Where("id = ?", id).Cols("adopted").Update(&data) if err != nil { return errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -187,7 +187,7 @@ func (ar *answerRepo) UpdateAccepted(ctx context.Context, id string, questionID func (ar *answerRepo) GetByID(ctx context.Context, id string) (*entity.Answer, bool, error) { var resp entity.Answer id = uid.DeShortID(id) - has, err := ar.data.DB.Where("id =? ", id).Get(&resp) + has, err := ar.data.DB.Context(ctx).Where("id =? ", id).Get(&resp) if err != nil { return &resp, false, errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -199,7 +199,7 @@ func (ar *answerRepo) GetByID(ctx context.Context, id string) (*entity.Answer, b func (ar *answerRepo) GetByUserIDQuestionID(ctx context.Context, userID string, questionID string) (*entity.Answer, bool, error) { questionID = uid.DeShortID(questionID) var resp entity.Answer - has, err := ar.data.DB.Where("question_id =? and user_id = ?", questionID, userID).Get(&resp) + has, err := ar.data.DB.Context(ctx).Where("question_id =? and user_id = ?", questionID, userID).Get(&resp) if err != nil { return &resp, false, errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -226,7 +226,7 @@ func (ar *answerRepo) SearchList(ctx context.Context, search *entity.AnswerSearc search.PageSize = constant.DefaultPageSize } offset := search.Page * search.PageSize - session := ar.data.DB.Where("") + session := ar.data.DB.Context(ctx).Where("") if search.QuestionID != "" { session = session.And("question_id = ?", search.QuestionID) @@ -262,7 +262,7 @@ func (ar *answerRepo) AdminSearchList(ctx context.Context, search *entity.AdminA var ( count int64 err error - session = ar.data.DB.Table([]string{entity.Answer{}.TableName(), "a"}).Select("a.*") + session = ar.data.DB.Context(ctx).Table([]string{entity.Answer{}.TableName(), "a"}).Select("a.*") ) if search.QuestionID != "" { search.QuestionID = uid.DeShortID(search.QuestionID) diff --git a/internal/repo/collection/collection_group_repo.go b/internal/repo/collection/collection_group_repo.go index 8f915bb6..df75de0c 100644 --- a/internal/repo/collection/collection_group_repo.go +++ b/internal/repo/collection/collection_group_repo.go @@ -26,7 +26,7 @@ func NewCollectionGroupRepo(data *data.Data) service.CollectionGroupRepo { // AddCollectionGroup add collection group func (cr *collectionGroupRepo) AddCollectionGroup(ctx context.Context, collectionGroup *entity.CollectionGroup) (err error) { - _, err = cr.data.DB.Insert(collectionGroup) + _, err = cr.data.DB.Context(ctx).Insert(collectionGroup) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -40,7 +40,7 @@ func (cr *collectionGroupRepo) AddCollectionDefaultGroup(ctx context.Context, us DefaultGroup: schema.CGDefault, UserID: userID, } - _, err = cr.data.DB.Insert(defaultGroup) + _, err = cr.data.DB.Context(ctx).Insert(defaultGroup) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() return @@ -51,7 +51,7 @@ func (cr *collectionGroupRepo) AddCollectionDefaultGroup(ctx context.Context, us // UpdateCollectionGroup update collection group func (cr *collectionGroupRepo) UpdateCollectionGroup(ctx context.Context, collectionGroup *entity.CollectionGroup, cols []string) (err error) { - _, err = cr.data.DB.ID(collectionGroup.ID).Cols(cols...).Update(collectionGroup) + _, err = cr.data.DB.Context(ctx).ID(collectionGroup.ID).Cols(cols...).Update(collectionGroup) if err != nil { return errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -63,7 +63,7 @@ func (cr *collectionGroupRepo) GetCollectionGroup(ctx context.Context, id string collectionGroup *entity.CollectionGroup, exist bool, err error, ) { collectionGroup = &entity.CollectionGroup{} - exist, err = cr.data.DB.ID(id).Get(collectionGroup) + exist, err = cr.data.DB.Context(ctx).ID(id).Get(collectionGroup) if err != nil { return nil, false, errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -74,7 +74,7 @@ func (cr *collectionGroupRepo) GetCollectionGroup(ctx context.Context, id string func (cr *collectionGroupRepo) GetCollectionGroupPage(ctx context.Context, page, pageSize int, collectionGroup *entity.CollectionGroup) (collectionGroupList []*entity.CollectionGroup, total int64, err error) { collectionGroupList = make([]*entity.CollectionGroup, 0) - session := cr.data.DB.NewSession() + session := cr.data.DB.Context(ctx) if collectionGroup.UserID != "" && collectionGroup.UserID != "0" { session = session.Where("user_id = ?", collectionGroup.UserID) } @@ -87,7 +87,7 @@ func (cr *collectionGroupRepo) GetCollectionGroupPage(ctx context.Context, page, func (cr *collectionGroupRepo) GetDefaultID(ctx context.Context, userID string) (collectionGroup *entity.CollectionGroup, has bool, err error) { collectionGroup = &entity.CollectionGroup{} - has, err = cr.data.DB.Where("user_id =? and default_group = ?", userID, schema.CGDefault).Get(collectionGroup) + has, err = cr.data.DB.Context(ctx).Where("user_id =? and default_group = ?", userID, schema.CGDefault).Get(collectionGroup) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() return diff --git a/internal/repo/collection/collection_repo.go b/internal/repo/collection/collection_repo.go index 7fcf9335..6c05a38d 100644 --- a/internal/repo/collection/collection_repo.go +++ b/internal/repo/collection/collection_repo.go @@ -32,6 +32,7 @@ func NewCollectionRepo(data *data.Data, uniqueIDRepo unique.UniqueIDRepo) collec func (cr *collectionRepo) AddCollection(ctx context.Context, collection *entity.Collection) (err error) { needAdd := false _, err = cr.data.DB.Transaction(func(session *xorm.Session) (result any, err error) { + session = session.Context(ctx) var has bool dbcollection := &entity.Collection{} result = nil @@ -52,7 +53,7 @@ func (cr *collectionRepo) AddCollection(ctx context.Context, collection *entity. id, err := cr.uniqueIDRepo.GenUniqueIDStr(ctx, collection.TableName()) if err == nil { collection.ID = id - _, err = cr.data.DB.Insert(collection) + _, err = cr.data.DB.Context(ctx).Insert(collection) if err != nil { return errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -64,7 +65,7 @@ func (cr *collectionRepo) AddCollection(ctx context.Context, collection *entity. // RemoveCollection delete collection func (cr *collectionRepo) RemoveCollection(ctx context.Context, id string) (err error) { - _, err = cr.data.DB.Where("id =?", id).Delete(&entity.Collection{}) + _, err = cr.data.DB.Context(ctx).Where("id =?", id).Delete(&entity.Collection{}) if err != nil { return errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -73,14 +74,14 @@ func (cr *collectionRepo) RemoveCollection(ctx context.Context, id string) (err // UpdateCollection update collection func (cr *collectionRepo) UpdateCollection(ctx context.Context, collection *entity.Collection, cols []string) (err error) { - _, err = cr.data.DB.ID(collection.ID).Cols(cols...).Update(collection) + _, err = cr.data.DB.Context(ctx).ID(collection.ID).Cols(cols...).Update(collection) return errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } // GetCollection get collection one func (cr *collectionRepo) GetCollection(ctx context.Context, id int) (collection *entity.Collection, exist bool, err error) { collection = &entity.Collection{} - exist, err = cr.data.DB.ID(id).Get(collection) + exist, err = cr.data.DB.Context(ctx).ID(id).Get(collection) if err != nil { return nil, false, errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -90,7 +91,7 @@ func (cr *collectionRepo) GetCollection(ctx context.Context, id int) (collection // GetCollectionList get collection list all func (cr *collectionRepo) GetCollectionList(ctx context.Context, collection *entity.Collection) (collectionList []*entity.Collection, err error) { collectionList = make([]*entity.Collection, 0) - err = cr.data.DB.Find(collectionList, collection) + err = cr.data.DB.Context(ctx).Find(collectionList, collection) err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() return } @@ -98,7 +99,7 @@ func (cr *collectionRepo) GetCollectionList(ctx context.Context, collection *ent // GetOneByObjectIDAndUser get one by object TagID and user func (cr *collectionRepo) GetOneByObjectIDAndUser(ctx context.Context, userID string, objectID string) (collection *entity.Collection, exist bool, err error) { collection = &entity.Collection{} - exist, err = cr.data.DB.Where("user_id = ? and object_id = ?", userID, objectID).Get(collection) + exist, err = cr.data.DB.Context(ctx).Where("user_id = ? and object_id = ?", userID, objectID).Get(collection) if err != nil { return nil, false, errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -108,7 +109,7 @@ func (cr *collectionRepo) GetOneByObjectIDAndUser(ctx context.Context, userID st // SearchByObjectIDsAndUser search by object IDs and user func (cr *collectionRepo) SearchByObjectIDsAndUser(ctx context.Context, userID string, objectIDs []string) ([]*entity.Collection, error) { collectionList := make([]*entity.Collection, 0) - err := cr.data.DB.Where("user_id = ?", userID).In("object_id", objectIDs).Find(&collectionList) + err := cr.data.DB.Context(ctx).Where("user_id = ?", userID).In("object_id", objectIDs).Find(&collectionList) if err != nil { return collectionList, err } @@ -118,7 +119,7 @@ func (cr *collectionRepo) SearchByObjectIDsAndUser(ctx context.Context, userID s // CountByObjectID count by object TagID func (cr *collectionRepo) CountByObjectID(ctx context.Context, objectID string) (total int64, err error) { collection := &entity.Collection{} - total, err = cr.data.DB.Where("object_id = ?", objectID).Count(collection) + total, err = cr.data.DB.Context(ctx).Where("object_id = ?", objectID).Count(collection) if err != nil { return 0, errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -129,7 +130,7 @@ func (cr *collectionRepo) CountByObjectID(ctx context.Context, objectID string) func (cr *collectionRepo) GetCollectionPage(ctx context.Context, page, pageSize int, collection *entity.Collection) (collectionList []*entity.Collection, total int64, err error) { collectionList = make([]*entity.Collection, 0) - session := cr.data.DB.NewSession() + session := cr.data.DB.Context(ctx) if collection.UserID != "" && collection.UserID != "0" { session = session.Where("user_id = ?", collection.UserID) } @@ -172,7 +173,7 @@ func (cr *collectionRepo) SearchList(ctx context.Context, search *entity.Collect search.PageSize = constant.DefaultPageSize } offset := search.Page * search.PageSize - session := cr.data.DB.Where("") + session := cr.data.DB.Context(ctx).Where("") if len(search.UserID) > 0 { session = session.And("user_id = ?", search.UserID) } else { diff --git a/internal/repo/comment/comment_repo.go b/internal/repo/comment/comment_repo.go index 992e6a2f..d3b3d8ac 100644 --- a/internal/repo/comment/comment_repo.go +++ b/internal/repo/comment/comment_repo.go @@ -41,7 +41,7 @@ func (cr *commentRepo) AddComment(ctx context.Context, comment *entity.Comment) if err != nil { return err } - _, err = cr.data.DB.Insert(comment) + _, err = cr.data.DB.Context(ctx).Insert(comment) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -50,7 +50,7 @@ func (cr *commentRepo) AddComment(ctx context.Context, comment *entity.Comment) // RemoveComment delete comment func (cr *commentRepo) RemoveComment(ctx context.Context, commentID string) (err error) { - session := cr.data.DB.ID(commentID) + session := cr.data.DB.Context(ctx).ID(commentID) _, err = session.Update(&entity.Comment{Status: entity.CommentStatusDeleted}) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() @@ -60,7 +60,7 @@ func (cr *commentRepo) RemoveComment(ctx context.Context, commentID string) (err // UpdateComment update comment func (cr *commentRepo) UpdateComment(ctx context.Context, comment *entity.Comment) (err error) { - _, err = cr.data.DB.ID(comment.ID).Where("user_id = ?", comment.UserID).Update(comment) + _, err = cr.data.DB.Context(ctx).ID(comment.ID).Where("user_id = ?", comment.UserID).Update(comment) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -72,7 +72,7 @@ func (cr *commentRepo) GetComment(ctx context.Context, commentID string) ( comment *entity.Comment, exist bool, err error, ) { comment = &entity.Comment{} - exist, err = cr.data.DB.ID(commentID).Get(comment) + exist, err = cr.data.DB.Context(ctx).ID(commentID).Get(comment) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -81,7 +81,7 @@ func (cr *commentRepo) GetComment(ctx context.Context, commentID string) ( func (cr *commentRepo) GetCommentCount(ctx context.Context) (count int64, err error) { list := make([]*entity.Comment, 0) - count, err = cr.data.DB.Where("status = ?", entity.CommentStatusAvailable).FindAndCount(&list) + count, err = cr.data.DB.Context(ctx).Where("status = ?", entity.CommentStatusAvailable).FindAndCount(&list) if err != nil { return count, errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -94,7 +94,7 @@ func (cr *commentRepo) GetCommentPage(ctx context.Context, commentQuery *comment ) { commentList = make([]*entity.Comment, 0) - session := cr.data.DB.NewSession() + session := cr.data.DB.Context(ctx) session.OrderBy(commentQuery.GetOrderBy()) session.Where("status = ?", entity.CommentStatusAvailable) diff --git a/internal/repo/common/common.go b/internal/repo/common/common.go deleted file mode 100644 index 59d1f304..00000000 --- a/internal/repo/common/common.go +++ /dev/null @@ -1,93 +0,0 @@ -package common - -import ( - "github.com/answerdev/answer/internal/base/data" - "github.com/answerdev/answer/internal/base/reason" - "github.com/answerdev/answer/internal/entity" - "github.com/answerdev/answer/internal/service/unique" - "github.com/answerdev/answer/pkg/obj" - "github.com/segmentfault/pacman/errors" - "github.com/segmentfault/pacman/log" -) - -type CommonRepo struct { - data *data.Data - uniqueIDRepo unique.UniqueIDRepo -} - -func NewCommonRepo(data *data.Data, uniqueIDRepo unique.UniqueIDRepo) *CommonRepo { - return &CommonRepo{ - data: data, - uniqueIDRepo: uniqueIDRepo, - } -} - -// GetRootObjectID get root object ID -func (cr *CommonRepo) GetRootObjectID(objectID string) (rootObjectID string, err error) { - var ( - exist bool - objectType string - answer = entity.Answer{} - comment = entity.Comment{} - ) - - objectType, err = obj.GetObjectTypeStrByObjectID(objectID) - switch objectType { - case "answer": - exist, err = cr.data.DB.ID(objectID).Get(&answer) - if !exist { - err = errors.BadRequest(reason.ObjectNotFound) - } - case "comment": - exist, _ = cr.data.DB.ID(objectID).Get(&comment) - if !exist { - err = errors.BadRequest(reason.ObjectNotFound) - } else { - _, err = cr.GetRootObjectID(comment.ObjectID) - } - default: - rootObjectID = objectID - } - return -} - -// GetObjectIDMap get object ID map from object id -func (cr *CommonRepo) GetObjectIDMap(objectID string) (objectIDMap map[string]string, err error) { - var ( - exist bool - ID, - objectType string - answer = entity.Answer{} - comment = entity.Comment{} - ) - - objectIDMap = map[string]string{} - // 10070000000000450 - objectType, err = obj.GetObjectTypeStrByObjectID(objectID) - if err != nil { - log.Error("get report object type:", objectID, ",err:", err) - return - } - switch objectType { - case "answer": - exist, _ = cr.data.DB.ID(objectID).Get(&answer) - if !exist { - err = errors.BadRequest(reason.ObjectNotFound) - } else { - objectIDMap, err = cr.GetObjectIDMap(answer.QuestionID) - ID = answer.ID - } - case "comment": - exist, _ = cr.data.DB.ID(objectID).Get(&comment) - if !exist { - err = errors.BadRequest(reason.ObjectNotFound) - } else { - objectIDMap, err = cr.GetObjectIDMap(comment.ObjectID) - ID = comment.ID - } - case "question": - ID = objectID - } - objectIDMap[objectType] = ID - return -} diff --git a/internal/repo/config/config_repo.go b/internal/repo/config/config_repo.go index 329e2b65..c81b9af7 100644 --- a/internal/repo/config/config_repo.go +++ b/internal/repo/config/config_repo.go @@ -1,29 +1,21 @@ package config import ( - "encoding/json" + "context" "fmt" - "sync" - - "github.com/answerdev/answer/internal/service/config" - "github.com/answerdev/answer/pkg/converter" + "github.com/answerdev/answer/internal/base/constant" "github.com/answerdev/answer/internal/base/data" "github.com/answerdev/answer/internal/base/reason" "github.com/answerdev/answer/internal/entity" + "github.com/answerdev/answer/internal/service/config" "github.com/segmentfault/pacman/errors" -) - -var ( - Key2ValueMapping = make(map[string]interface{}) - Key2IDMapping = make(map[string]int) - ID2KeyMapping = make(map[int]string) + "github.com/segmentfault/pacman/log" ) // configRepo config repository type configRepo struct { data *data.Data - mu sync.Mutex } // NewConfigRepo new repository @@ -31,110 +23,87 @@ func NewConfigRepo(data *data.Data) config.ConfigRepo { repo := &configRepo{ data: data, } - repo.init() return repo } -// init initializes the Key2ValueMapping map data structures -func (cr *configRepo) init() { - cr.mu.Lock() - defer cr.mu.Unlock() - rows := &[]entity.Config{} - err := cr.data.DB.Find(rows) - if err == nil { - for _, row := range *rows { - Key2ValueMapping[row.Key] = row.Value - Key2IDMapping[row.Key] = row.ID - ID2KeyMapping[row.ID] = row.Key +func (cr configRepo) GetConfigByID(ctx context.Context, id int) (c *entity.Config, err error) { + cacheKey := fmt.Sprintf("%s%d", constant.ConfigID2KEYCacheKeyPrefix, id) + if cacheData, err := cr.data.Cache.GetString(ctx, cacheKey); err == nil && len(cacheData) > 0 { + c = &entity.Config{} + c.BuildByJSON([]byte(cacheData)) + if c.ID > 0 { + return c, nil } } -} -// Get Base method for getting the config value -// Key string -func (cr *configRepo) Get(key string) (interface{}, error) { - value, ok := Key2ValueMapping[key] - if ok { - return value, nil - } else { - return value, errors.InternalServer(reason.DatabaseError).WithMsg(fmt.Sprintf("no such config key: %v", key)) - } -} - -// GetString method for getting the config value to string -// key string -func (cr *configRepo) GetString(key string) (string, error) { - value, err := cr.Get(key) + c = &entity.Config{} + exist, err := cr.data.DB.ID(id).Get(c) if err != nil { - return "", err + return nil, errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } - str, ok := value.(string) - if !ok { - return "", errors.InternalServer(reason.DatabaseError).WithMsg(fmt.Sprintf("config value is wrong type: %v", key)) + if !exist { + return nil, fmt.Errorf("config not found by id: %d", id) } - return str, nil + + // update cache + if err := cr.data.Cache.SetString(ctx, cacheKey, c.JsonString(), -1); err != nil { + log.Error(err) + } + return c, nil } -// GetInt method for getting the config value to int64 -// key string -func (cr *configRepo) GetInt(key string) (int, error) { - value, err := cr.GetString(key) - if err != nil { - return 0, err +func (cr configRepo) GetConfigByKey(ctx context.Context, key string) (c *entity.Config, err error) { + cacheKey := constant.ConfigKEY2ContentCacheKeyPrefix + key + if cacheData, err := cr.data.Cache.GetString(ctx, cacheKey); err == nil && len(cacheData) > 0 { + c = &entity.Config{} + c.BuildByJSON([]byte(cacheData)) + if c.ID > 0 { + return c, nil + } } - return converter.StringToInt(value), nil + + c = &entity.Config{Key: key} + exist, err := cr.data.DB.Context(ctx).Get(c) + if err != nil { + return nil, errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() + } + if !exist { + return nil, fmt.Errorf("config not found by key: %s", key) + } + + // update cache + if err := cr.data.Cache.SetString(ctx, cacheKey, c.JsonString(), -1); err != nil { + log.Error(err) + } + return c, nil } -// GetArrayString method for getting the config value to string array -func (cr *configRepo) GetArrayString(key string) ([]string, error) { - arr := &[]string{} - value, err := cr.GetString(key) +func (cr configRepo) UpdateConfig(ctx context.Context, key string, value string) (err error) { + // check if key exists + cf := &entity.Config{} + exist, err := cr.data.DB.Context(ctx).Get(cf) if err != nil { - return nil, err + return errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } - err = json.Unmarshal([]byte(value), arr) - return *arr, err -} - -// GetConfigType method for getting the config type -func (cr *configRepo) GetConfigType(key string) (int, error) { - value, ok := Key2IDMapping[key] - if !ok { - return 0, errors.InternalServer(reason.DatabaseError).WithMsg(fmt.Sprintf("no such config type: %v", key)) - } - return value, nil -} - -// GetJsonConfigByIDAndSetToObject get config key from config id -func (cr *configRepo) GetJsonConfigByIDAndSetToObject(id int, object any) (err error) { - key, ok := ID2KeyMapping[id] - if !ok { - return errors.InternalServer(reason.DatabaseError).WithMsg(fmt.Sprintf("no such config id: %v", id)) + if !exist { + return errors.BadRequest(reason.ObjectNotFound) } - conf, err := cr.Get(key) + // update database + _, err = cr.data.DB.Context(ctx).ID(cf.ID).Update(&entity.Config{Value: value}) if err != nil { - return errors.InternalServer(reason.DatabaseError).WithError(err) + return errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } - str, ok := conf.(string) - if !ok { - return errors.InternalServer(reason.DatabaseError).WithMsg(fmt.Sprintf("no such config id: %v", id)) + + cacheVal := cf.JsonString() + // update cache + if err := cr.data.Cache.SetString(ctx, + constant.ConfigKEY2ContentCacheKeyPrefix+key, cacheVal, -1); err != nil { + log.Error(err) } - err = json.Unmarshal([]byte(str), object) - if err != nil { - err = errors.InternalServer(reason.DatabaseError).WithMsg(fmt.Sprintf("no such config id: %v", id)) - } - return -} - -// SetConfig set config -func (cr *configRepo) SetConfig(key, value string) (err error) { - id := Key2IDMapping[key] - _, err = cr.data.DB.ID(id).Update(&entity.Config{Value: value}) - if err != nil { - err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() - } else { - Key2ValueMapping[key] = value + if err := cr.data.Cache.SetString(ctx, + fmt.Sprintf("%s%d", constant.ConfigID2KEYCacheKeyPrefix, cf.ID), cacheVal, -1); err != nil { + log.Error(err) } return } diff --git a/internal/repo/meta/meta_repo.go b/internal/repo/meta/meta_repo.go index 415ad428..fefa6748 100644 --- a/internal/repo/meta/meta_repo.go +++ b/internal/repo/meta/meta_repo.go @@ -25,7 +25,7 @@ func NewMetaRepo(data *data.Data) meta.MetaRepo { // AddMeta add meta func (mr *metaRepo) AddMeta(ctx context.Context, meta *entity.Meta) (err error) { - _, err = mr.data.DB.Insert(meta) + _, err = mr.data.DB.Context(ctx).Insert(meta) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -34,7 +34,7 @@ func (mr *metaRepo) AddMeta(ctx context.Context, meta *entity.Meta) (err error) // RemoveMeta delete meta func (mr *metaRepo) RemoveMeta(ctx context.Context, id int) (err error) { - _, err = mr.data.DB.ID(id).Delete(&entity.Meta{}) + _, err = mr.data.DB.Context(ctx).ID(id).Delete(&entity.Meta{}) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -43,7 +43,7 @@ func (mr *metaRepo) RemoveMeta(ctx context.Context, id int) (err error) { // UpdateMeta update meta func (mr *metaRepo) UpdateMeta(ctx context.Context, meta *entity.Meta) (err error) { - _, err = mr.data.DB.ID(meta.ID).Update(meta) + _, err = mr.data.DB.Context(ctx).ID(meta.ID).Update(meta) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -54,7 +54,7 @@ func (mr *metaRepo) UpdateMeta(ctx context.Context, meta *entity.Meta) (err erro func (mr *metaRepo) GetMetaByObjectIdAndKey(ctx context.Context, objectID, key string) ( meta *entity.Meta, exist bool, err error) { meta = &entity.Meta{} - exist, err = mr.data.DB.Where(builder.Eq{"object_id": objectID}.And(builder.Eq{"`key`": key})).Desc("created_at").Get(meta) + exist, err = mr.data.DB.Context(ctx).Where(builder.Eq{"object_id": objectID}.And(builder.Eq{"`key`": key})).Desc("created_at").Get(meta) if err != nil { return nil, false, errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -64,7 +64,7 @@ func (mr *metaRepo) GetMetaByObjectIdAndKey(ctx context.Context, objectID, key s // GetMetaList get meta list all func (mr *metaRepo) GetMetaList(ctx context.Context, meta *entity.Meta) (metaList []*entity.Meta, err error) { metaList = make([]*entity.Meta, 0) - err = mr.data.DB.Find(&metaList, meta) + err = mr.data.DB.Context(ctx).Find(&metaList, meta) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } diff --git a/internal/repo/notification/notification_repo.go b/internal/repo/notification/notification_repo.go index 21b7bcff..e8f712ec 100644 --- a/internal/repo/notification/notification_repo.go +++ b/internal/repo/notification/notification_repo.go @@ -29,7 +29,7 @@ func NewNotificationRepo(data *data.Data) notficationcommon.NotificationRepo { // AddNotification add notification func (nr *notificationRepo) AddNotification(ctx context.Context, notification *entity.Notification) (err error) { notification.ObjectID = uid.DeShortID(notification.ObjectID) - _, err = nr.data.DB.Insert(notification) + _, err = nr.data.DB.Context(ctx).Insert(notification) if err != nil { return errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -40,7 +40,7 @@ func (nr *notificationRepo) UpdateNotificationContent(ctx context.Context, notif now := time.Now() notification.UpdatedAt = now notification.ObjectID = uid.DeShortID(notification.ObjectID) - _, err = nr.data.DB.Where("id =?", notification.ID).Cols("content", "updated_at").Update(notification) + _, err = nr.data.DB.Context(ctx).Where("id =?", notification.ID).Cols("content", "updated_at").Update(notification) if err != nil { return errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -50,7 +50,7 @@ func (nr *notificationRepo) UpdateNotificationContent(ctx context.Context, notif func (nr *notificationRepo) ClearUnRead(ctx context.Context, userID string, notificationType int) (err error) { info := &entity.Notification{} info.IsRead = schema.NotificationRead - _, err = nr.data.DB.Where("user_id =?", userID).And("type =?", notificationType).Cols("is_read").Update(info) + _, err = nr.data.DB.Context(ctx).Where("user_id =?", userID).And("type =?", notificationType).Cols("is_read").Update(info) if err != nil { return errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -60,7 +60,7 @@ func (nr *notificationRepo) ClearUnRead(ctx context.Context, userID string, noti func (nr *notificationRepo) ClearIDUnRead(ctx context.Context, userID string, id string) (err error) { info := &entity.Notification{} info.IsRead = schema.NotificationRead - _, err = nr.data.DB.Where("user_id =?", userID).And("id =?", id).Cols("is_read").Update(info) + _, err = nr.data.DB.Context(ctx).Where("user_id =?", userID).And("id =?", id).Cols("is_read").Update(info) if err != nil { return errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -69,7 +69,7 @@ func (nr *notificationRepo) ClearIDUnRead(ctx context.Context, userID string, id func (nr *notificationRepo) GetById(ctx context.Context, id string) (*entity.Notification, bool, error) { info := &entity.Notification{} - exist, err := nr.data.DB.Where("id = ? ", id).Get(info) + exist, err := nr.data.DB.Context(ctx).Where("id = ? ", id).Get(info) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() return info, false, err @@ -79,7 +79,7 @@ func (nr *notificationRepo) GetById(ctx context.Context, id string) (*entity.Not func (nr *notificationRepo) GetByUserIdObjectIdTypeId(ctx context.Context, userID, objectID string, notificationType int) (*entity.Notification, bool, error) { info := &entity.Notification{} - exist, err := nr.data.DB.Where("user_id = ? ", userID).And("object_id = ?", objectID).And("type = ?", notificationType).Get(info) + exist, err := nr.data.DB.Context(ctx).Where("user_id = ? ", userID).And("object_id = ?", objectID).And("type = ?", notificationType).Get(info) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() return info, false, err @@ -94,7 +94,7 @@ func (nr *notificationRepo) GetNotificationPage(ctx context.Context, searchCond return notificationList, 0, nil } - session := nr.data.DB.NewSession() + session := nr.data.DB.Context(ctx) session = session.Desc("updated_at") cond := &entity.Notification{ diff --git a/internal/repo/plugin_config/plugin_config_repo.go b/internal/repo/plugin_config/plugin_config_repo.go index d615577f..aad97657 100644 --- a/internal/repo/plugin_config/plugin_config_repo.go +++ b/internal/repo/plugin_config/plugin_config_repo.go @@ -23,15 +23,15 @@ func NewPluginConfigRepo(data *data.Data) plugin_common.PluginConfigRepo { func (ur *pluginConfigRepo) SavePluginConfig(ctx context.Context, pluginSlugName, configValue string) (err error) { old := &entity.PluginConfig{PluginSlugName: pluginSlugName} - exist, err := ur.data.DB.Get(old) + exist, err := ur.data.DB.Context(ctx).Get(old) if err != nil { return errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } if exist { old.Value = configValue - _, err = ur.data.DB.ID(old.ID).Update(old) + _, err = ur.data.DB.Context(ctx).ID(old.ID).Update(old) } else { - _, err = ur.data.DB.InsertOne(&entity.PluginConfig{PluginSlugName: pluginSlugName, Value: configValue}) + _, err = ur.data.DB.Context(ctx).InsertOne(&entity.PluginConfig{PluginSlugName: pluginSlugName, Value: configValue}) } if err != nil { return errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() @@ -41,7 +41,7 @@ func (ur *pluginConfigRepo) SavePluginConfig(ctx context.Context, pluginSlugName func (ur *pluginConfigRepo) GetPluginConfigAll(ctx context.Context) (pluginConfigs []*entity.PluginConfig, err error) { pluginConfigs = make([]*entity.PluginConfig, 0) - err = ur.data.DB.Find(&pluginConfigs) + err = ur.data.DB.Context(ctx).Find(&pluginConfigs) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } diff --git a/internal/repo/provider.go b/internal/repo/provider.go index b0dc6f8a..10722cec 100644 --- a/internal/repo/provider.go +++ b/internal/repo/provider.go @@ -9,7 +9,6 @@ import ( "github.com/answerdev/answer/internal/repo/captcha" "github.com/answerdev/answer/internal/repo/collection" "github.com/answerdev/answer/internal/repo/comment" - "github.com/answerdev/answer/internal/repo/common" "github.com/answerdev/answer/internal/repo/config" "github.com/answerdev/answer/internal/repo/export" "github.com/answerdev/answer/internal/repo/meta" @@ -33,7 +32,6 @@ import ( // ProviderSetRepo is data providers. var ProviderSetRepo = wire.NewSet( - common.NewCommonRepo, data.NewData, data.NewDB, data.NewCache, diff --git a/internal/repo/question/question_repo.go b/internal/repo/question/question_repo.go index 75ef1ac2..01dd98e4 100644 --- a/internal/repo/question/question_repo.go +++ b/internal/repo/question/question_repo.go @@ -46,7 +46,7 @@ func (qr *questionRepo) AddQuestion(ctx context.Context, question *entity.Questi if err != nil { return errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } - _, err = qr.data.DB.Insert(question) + _, err = qr.data.DB.Context(ctx).Insert(question) if err != nil { return errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -57,7 +57,7 @@ func (qr *questionRepo) AddQuestion(ctx context.Context, question *entity.Questi // RemoveQuestion delete question func (qr *questionRepo) RemoveQuestion(ctx context.Context, id string) (err error) { id = uid.DeShortID(id) - _, err = qr.data.DB.Where("id =?", id).Delete(&entity.Question{}) + _, err = qr.data.DB.Context(ctx).Where("id =?", id).Delete(&entity.Question{}) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -67,7 +67,7 @@ func (qr *questionRepo) RemoveQuestion(ctx context.Context, id string) (err erro // UpdateQuestion update question func (qr *questionRepo) UpdateQuestion(ctx context.Context, question *entity.Question, Cols []string) (err error) { question.ID = uid.DeShortID(question.ID) - _, err = qr.data.DB.Where("id =?", question.ID).Cols(Cols...).Update(question) + _, err = qr.data.DB.Context(ctx).Where("id =?", question.ID).Cols(Cols...).Update(question) if err != nil { return errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -78,7 +78,7 @@ func (qr *questionRepo) UpdateQuestion(ctx context.Context, question *entity.Que func (qr *questionRepo) UpdatePvCount(ctx context.Context, questionID string) (err error) { questionID = uid.DeShortID(questionID) question := &entity.Question{} - _, err = qr.data.DB.Where("id =?", questionID).Incr("view_count", 1).Update(question) + _, err = qr.data.DB.Context(ctx).Where("id =?", questionID).Incr("view_count", 1).Update(question) if err != nil { return errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -88,7 +88,7 @@ func (qr *questionRepo) UpdatePvCount(ctx context.Context, questionID string) (e func (qr *questionRepo) UpdateAnswerCount(ctx context.Context, questionID string, num int) (err error) { questionID = uid.DeShortID(questionID) question := &entity.Question{} - _, err = qr.data.DB.Where("id =?", questionID).Incr("answer_count", num).Update(question) + _, err = qr.data.DB.Context(ctx).Where("id =?", questionID).Incr("answer_count", num).Update(question) if err != nil { return errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -98,7 +98,7 @@ func (qr *questionRepo) UpdateAnswerCount(ctx context.Context, questionID string func (qr *questionRepo) UpdateCollectionCount(ctx context.Context, questionID string, num int) (err error) { questionID = uid.DeShortID(questionID) question := &entity.Question{} - _, err = qr.data.DB.Where("id =?", questionID).Incr("collection_count", num).Update(question) + _, err = qr.data.DB.Context(ctx).Where("id =?", questionID).Incr("collection_count", num).Update(question) if err != nil { return errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -109,7 +109,7 @@ func (qr *questionRepo) UpdateQuestionStatus(ctx context.Context, question *enti question.ID = uid.DeShortID(question.ID) now := time.Now() question.UpdatedAt = now - _, err = qr.data.DB.Where("id =?", question.ID).Cols("status", "updated_at").Update(question) + _, err = qr.data.DB.Context(ctx).Where("id =?", question.ID).Cols("status", "updated_at").Update(question) if err != nil { return errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -118,7 +118,7 @@ func (qr *questionRepo) UpdateQuestionStatus(ctx context.Context, question *enti func (qr *questionRepo) UpdateQuestionStatusWithOutUpdateTime(ctx context.Context, question *entity.Question) (err error) { question.ID = uid.DeShortID(question.ID) - _, err = qr.data.DB.Where("id =?", question.ID).Cols("status").Update(question) + _, err = qr.data.DB.Context(ctx).Where("id =?", question.ID).Cols("status").Update(question) if err != nil { return errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -127,7 +127,7 @@ func (qr *questionRepo) UpdateQuestionStatusWithOutUpdateTime(ctx context.Contex func (qr *questionRepo) UpdateQuestionOperation(ctx context.Context, question *entity.Question) (err error) { question.ID = uid.DeShortID(question.ID) - _, err = qr.data.DB.Where("id =?", question.ID).Cols("pin", "show").Update(question) + _, err = qr.data.DB.Context(ctx).Where("id =?", question.ID).Cols("pin", "show").Update(question) if err != nil { return errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -136,7 +136,7 @@ func (qr *questionRepo) UpdateQuestionOperation(ctx context.Context, question *e func (qr *questionRepo) UpdateAccepted(ctx context.Context, question *entity.Question) (err error) { question.ID = uid.DeShortID(question.ID) - _, err = qr.data.DB.Where("id =?", question.ID).Cols("accepted_answer_id").Update(question) + _, err = qr.data.DB.Context(ctx).Where("id =?", question.ID).Cols("accepted_answer_id").Update(question) if err != nil { return errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -145,7 +145,7 @@ func (qr *questionRepo) UpdateAccepted(ctx context.Context, question *entity.Que func (qr *questionRepo) UpdateLastAnswer(ctx context.Context, question *entity.Question) (err error) { question.ID = uid.DeShortID(question.ID) - _, err = qr.data.DB.Where("id =?", question.ID).Cols("last_answer_id").Update(question) + _, err = qr.data.DB.Context(ctx).Where("id =?", question.ID).Cols("last_answer_id").Update(question) if err != nil { return errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -159,7 +159,7 @@ func (qr *questionRepo) GetQuestion(ctx context.Context, id string) ( id = uid.DeShortID(id) question = &entity.Question{} question.ID = id - exist, err = qr.data.DB.Where("id = ?", id).Get(question) + exist, err = qr.data.DB.Context(ctx).Where("id = ?", id).Get(question) if err != nil { return nil, false, errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -170,7 +170,7 @@ func (qr *questionRepo) GetQuestion(ctx context.Context, id string) ( // GetTagBySlugName get tag by slug name func (qr *questionRepo) SearchByTitleLike(ctx context.Context, title string) (questionList []*entity.Question, err error) { questionList = make([]*entity.Question, 0) - err = qr.data.DB.Table("question").Where("title like ?", "%"+title+"%").Limit(10, 0).Find(&questionList) + err = qr.data.DB.Context(ctx).Table("question").Where("title like ?", "%"+title+"%").Limit(10, 0).Find(&questionList) if err != nil { return nil, errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -185,7 +185,7 @@ func (qr *questionRepo) FindByID(ctx context.Context, id []string) (questionList id[key] = uid.DeShortID(itemID) } questionList = make([]*entity.Question, 0) - err = qr.data.DB.Table("question").In("id", id).Find(&questionList) + err = qr.data.DB.Context(ctx).Table("question").In("id", id).Find(&questionList) if err != nil { return nil, errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -199,7 +199,7 @@ func (qr *questionRepo) FindByID(ctx context.Context, id []string) (questionList func (qr *questionRepo) GetQuestionList(ctx context.Context, question *entity.Question) (questionList []*entity.Question, err error) { question.ID = uid.DeShortID(question.ID) questionList = make([]*entity.Question, 0) - err = qr.data.DB.Find(questionList, question) + err = qr.data.DB.Context(ctx).Find(questionList, question) if err != nil { return questionList, errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -212,7 +212,7 @@ func (qr *questionRepo) GetQuestionList(ctx context.Context, question *entity.Qu func (qr *questionRepo) GetQuestionCount(ctx context.Context) (count int64, err error) { questionList := make([]*entity.Question, 0) - count, err = qr.data.DB.In("question.status", []int{entity.QuestionStatusAvailable, entity.QuestionStatusClosed}).FindAndCount(&questionList) + count, err = qr.data.DB.Context(ctx).In("question.status", []int{entity.QuestionStatusAvailable, entity.QuestionStatusClosed}).FindAndCount(&questionList) if err != nil { return count, errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -221,7 +221,7 @@ func (qr *questionRepo) GetQuestionCount(ctx context.Context) (count int64, err func (qr *questionRepo) GetUserQuestionCount(ctx context.Context, userID string) (count int64, err error) { questionList := make([]*entity.Question, 0) - count, err = qr.data.DB.In("question.status", []int{entity.QuestionStatusAvailable, entity.QuestionStatusClosed}).And("user_id = ?", userID).Count(&questionList) + count, err = qr.data.DB.In("question.status", []int{entity.QuestionStatusAvailable, entity.QuestionStatusClosed}).And("question.user_id = ?", userID).FindAndCount(&questionList) if err != nil { return count, errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -249,7 +249,7 @@ func (qr *questionRepo) GetQuestionIDsPage(ctx context.Context, page, pageSize i pageSize = constant.DefaultPageSize } offset := page * pageSize - session := qr.data.DB.Table("question") + session := qr.data.DB.Context(ctx).Table("question") session = session.In("question.status", []int{entity.QuestionStatusAvailable, entity.QuestionStatusClosed}) session.And("question.show = ?", entity.QuestionShow) session = session.Limit(pageSize, offset) @@ -277,7 +277,7 @@ func (qr *questionRepo) GetQuestionPage(ctx context.Context, page, pageSize int, questionList []*entity.Question, total int64, err error) { questionList = make([]*entity.Question, 0) - session := qr.data.DB.Where("question.status = ? OR question.status = ?", + session := qr.data.DB.Context(ctx).Where("question.status = ? OR question.status = ?", entity.QuestionStatusAvailable, entity.QuestionStatusClosed) if len(tagID) > 0 { session.Join("LEFT", "tag_rel", "question.id = tag_rel.object_id") @@ -321,7 +321,7 @@ func (qr *questionRepo) AdminSearchList(ctx context.Context, search *schema.Admi var ( count int64 err error - session = qr.data.DB.Table("question") + session = qr.data.DB.Context(ctx).Table("question") ) session.Where(builder.Eq{ diff --git a/internal/repo/rank/user_rank_repo.go b/internal/repo/rank/user_rank_repo.go index fc97c6de..06570fec 100644 --- a/internal/repo/rank/user_rank_repo.go +++ b/internal/repo/rank/user_rank_repo.go @@ -19,15 +19,15 @@ import ( // UserRankRepo user rank repository type UserRankRepo struct { - data *data.Data - configRepo config.ConfigRepo + data *data.Data + configService *config.ConfigService } // NewUserRankRepo new repository -func NewUserRankRepo(data *data.Data, configRepo config.ConfigRepo) rank.UserRankRepo { +func NewUserRankRepo(data *data.Data, configService *config.ConfigService) rank.UserRankRepo { return &UserRankRepo{ - data: data, - configRepo: configRepo, + data: data, + configService: configService, } } @@ -94,14 +94,13 @@ func (ur *UserRankRepo) checkUserTodayRank(ctx context.Context, session *xorm.Session, userID string, activityType int, ) (isReachStandard bool, err error) { // exclude daily rank - exclude, _ := ur.configRepo.GetArrayString("daily_rank_limit.exclude") + exclude, _ := ur.configService.GetArrayStringValue(ctx, "daily_rank_limit.exclude") for _, item := range exclude { - var excludeActivityType int - excludeActivityType, err = ur.configRepo.GetInt(item) + cfg, err := ur.configService.GetConfigByKey(ctx, item) if err != nil { return false, err } - if activityType == excludeActivityType { + if activityType == cfg.ID { return false, nil } } @@ -121,7 +120,7 @@ func (ur *UserRankRepo) checkUserTodayRank(ctx context.Context, } // max rank - maxDailyRank, err := ur.configRepo.GetInt("daily_rank_limit") + maxDailyRank, err := ur.configService.GetIntValue(ctx, "daily_rank_limit") if err != nil { return false, err } @@ -138,7 +137,7 @@ func (ur *UserRankRepo) UserRankPage(ctx context.Context, userID string, page, p ) { rankPage = make([]*entity.Activity, 0) - session := ur.data.DB.Where(builder.Eq{"has_rank": 1}.And(builder.Eq{"cancelled": 0})).And(builder.Gt{"rank": 0}) + session := ur.data.DB.Context(ctx).Where(builder.Eq{"has_rank": 1}.And(builder.Eq{"cancelled": 0})).And(builder.Gt{"rank": 0}) session.Desc("created_at") cond := &entity.Activity{UserID: userID} diff --git a/internal/repo/reason/reason_repo.go b/internal/repo/reason/reason_repo.go index b9b8b4bd..251d1752 100644 --- a/internal/repo/reason/reason_repo.go +++ b/internal/repo/reason/reason_repo.go @@ -13,12 +13,12 @@ import ( ) type reasonRepo struct { - configRepo config.ConfigRepo + configService *config.ConfigService } -func NewReasonRepo(configRepo config.ConfigRepo) reason_common.ReasonRepo { +func NewReasonRepo(configService *config.ConfigService) reason_common.ReasonRepo { return &reasonRepo{ - configRepo: configRepo, + configService: configService, } } @@ -27,31 +27,25 @@ func (rr *reasonRepo) ListReasons(ctx context.Context, objectType, action string reasonAction := fmt.Sprintf("%s.%s.reasons", objectType, action) resp = make([]*schema.ReasonItem, 0) - reasonKeys, err := rr.configRepo.GetArrayString(reasonAction) + reasonKeys, err := rr.configService.GetArrayStringValue(ctx, reasonAction) if err != nil { return nil, err } for _, reasonKey := range reasonKeys { - cfgValue, err := rr.configRepo.GetString(reasonKey) + cfg, err := rr.configService.GetConfigByKey(ctx, reasonKey) if err != nil { log.Error(err) continue } reason := &schema.ReasonItem{} - err = json.Unmarshal([]byte(cfgValue), reason) + err = json.Unmarshal(cfg.GetByteValue(), reason) if err != nil { log.Error(err) continue } reason.Translate(reasonKey, lang) - - reason.ReasonType, err = rr.configRepo.GetConfigType(reasonKey) - if err != nil { - log.Error(err) - continue - } - + reason.ReasonType = cfg.ID resp = append(resp, reason) } return resp, nil diff --git a/internal/repo/repo_test/config_repo_test.go b/internal/repo/repo_test/config_repo_test.go index 5f76ddef..233abc51 100644 --- a/internal/repo/repo_test/config_repo_test.go +++ b/internal/repo/repo_test/config_repo_test.go @@ -3,19 +3,18 @@ package repo_test import ( "testing" - "github.com/answerdev/answer/internal/repo/config" "github.com/answerdev/answer/internal/schema" "github.com/stretchr/testify/assert" ) func Test_configRepo_Get(t *testing.T) { - configRepo := config.NewConfigRepo(testDataSource) + configRepo := config_common.NewConfigRepo(testDataSource) _, err := configRepo.Get("email.config") assert.NoError(t, err) } func Test_configRepo_GetArrayString(t *testing.T) { - configRepo := config.NewConfigRepo(testDataSource) + configRepo := config_common.NewConfigRepo(testDataSource) got, err := configRepo.GetArrayString("daily_rank_limit.exclude") assert.NoError(t, err) assert.Equal(t, 1, len(got)) @@ -23,7 +22,7 @@ func Test_configRepo_GetArrayString(t *testing.T) { } func Test_configRepo_GetConfigById(t *testing.T) { - configRepo := config.NewConfigRepo(testDataSource) + configRepo := config_common.NewConfigRepo(testDataSource) closeInfo := &schema.GetReportTypeResp{} err := configRepo.GetJsonConfigByIDAndSetToObject(74, closeInfo) @@ -33,27 +32,27 @@ func Test_configRepo_GetConfigById(t *testing.T) { } func Test_configRepo_GetConfigType(t *testing.T) { - configRepo := config.NewConfigRepo(testDataSource) + configRepo := config_common.NewConfigRepo(testDataSource) configType, err := configRepo.GetConfigType("answer.accepted") assert.NoError(t, err) assert.Equal(t, 1, configType) } func Test_configRepo_GetInt(t *testing.T) { - configRepo := config.NewConfigRepo(testDataSource) + configRepo := config_common.NewConfigRepo(testDataSource) got, err := configRepo.GetInt("answer.accepted") assert.NoError(t, err) assert.Equal(t, 15, got) } func Test_configRepo_GetString(t *testing.T) { - configRepo := config.NewConfigRepo(testDataSource) + configRepo := config_common.NewConfigRepo(testDataSource) _, err := configRepo.GetString("email.config") assert.NoError(t, err) } func Test_configRepo_SetConfig(t *testing.T) { - configRepo := config.NewConfigRepo(testDataSource) + configRepo := config_common.NewConfigRepo(testDataSource) got, err := configRepo.GetString("email.config") assert.NoError(t, err) diff --git a/internal/repo/repo_test/reason_repo_test.go b/internal/repo/repo_test/reason_repo_test.go index 0e3e91e9..c6092e57 100644 --- a/internal/repo/repo_test/reason_repo_test.go +++ b/internal/repo/repo_test/reason_repo_test.go @@ -4,13 +4,12 @@ import ( "context" "testing" - "github.com/answerdev/answer/internal/repo/config" "github.com/answerdev/answer/internal/repo/reason" "github.com/stretchr/testify/assert" ) func Test_reasonRepo_ListReasons(t *testing.T) { - configRepo := config.NewConfigRepo(testDataSource) + configRepo := config_common.NewConfigRepo(testDataSource) reasonRepo := reason.NewReasonRepo(configRepo) reasonItems, err := reasonRepo.ListReasons(context.TODO(), "question", "close") assert.NoError(t, err) diff --git a/internal/repo/repo_test/user_repo_test.go b/internal/repo/repo_test/user_repo_test.go index 7b6f24ac..105f9885 100644 --- a/internal/repo/repo_test/user_repo_test.go +++ b/internal/repo/repo_test/user_repo_test.go @@ -5,13 +5,12 @@ import ( "testing" "github.com/answerdev/answer/internal/entity" - "github.com/answerdev/answer/internal/repo/config" "github.com/answerdev/answer/internal/repo/user" "github.com/stretchr/testify/assert" ) func Test_userRepo_AddUser(t *testing.T) { - userRepo := user.NewUserRepo(testDataSource, config.NewConfigRepo(testDataSource)) + userRepo := user.NewUserRepo(testDataSource, config_common.NewConfigRepo(testDataSource)) userInfo := &entity.User{ Username: "answer", Pass: "answer", @@ -26,7 +25,7 @@ func Test_userRepo_AddUser(t *testing.T) { } func Test_userRepo_BatchGetByID(t *testing.T) { - userRepo := user.NewUserRepo(testDataSource, config.NewConfigRepo(testDataSource)) + userRepo := user.NewUserRepo(testDataSource, config_common.NewConfigRepo(testDataSource)) got, err := userRepo.BatchGetByID(context.TODO(), []string{"1"}) assert.NoError(t, err) assert.Equal(t, 1, len(got)) @@ -34,7 +33,7 @@ func Test_userRepo_BatchGetByID(t *testing.T) { } func Test_userRepo_GetByEmail(t *testing.T) { - userRepo := user.NewUserRepo(testDataSource, config.NewConfigRepo(testDataSource)) + userRepo := user.NewUserRepo(testDataSource, config_common.NewConfigRepo(testDataSource)) got, exist, err := userRepo.GetByEmail(context.TODO(), "admin@admin.com") assert.NoError(t, err) assert.True(t, exist) @@ -42,7 +41,7 @@ func Test_userRepo_GetByEmail(t *testing.T) { } func Test_userRepo_GetByUserID(t *testing.T) { - userRepo := user.NewUserRepo(testDataSource, config.NewConfigRepo(testDataSource)) + userRepo := user.NewUserRepo(testDataSource, config_common.NewConfigRepo(testDataSource)) got, exist, err := userRepo.GetByUserID(context.TODO(), "1") assert.NoError(t, err) assert.True(t, exist) @@ -50,7 +49,7 @@ func Test_userRepo_GetByUserID(t *testing.T) { } func Test_userRepo_GetByUsername(t *testing.T) { - userRepo := user.NewUserRepo(testDataSource, config.NewConfigRepo(testDataSource)) + userRepo := user.NewUserRepo(testDataSource, config_common.NewConfigRepo(testDataSource)) got, exist, err := userRepo.GetByUsername(context.TODO(), "admin") assert.NoError(t, err) assert.True(t, exist) @@ -58,7 +57,7 @@ func Test_userRepo_GetByUsername(t *testing.T) { } func Test_userRepo_IncreaseAnswerCount(t *testing.T) { - userRepo := user.NewUserRepo(testDataSource, config.NewConfigRepo(testDataSource)) + userRepo := user.NewUserRepo(testDataSource, config_common.NewConfigRepo(testDataSource)) err := userRepo.IncreaseAnswerCount(context.TODO(), "1", 1) assert.NoError(t, err) @@ -69,7 +68,7 @@ func Test_userRepo_IncreaseAnswerCount(t *testing.T) { } func Test_userRepo_IncreaseQuestionCount(t *testing.T) { - userRepo := user.NewUserRepo(testDataSource, config.NewConfigRepo(testDataSource)) + userRepo := user.NewUserRepo(testDataSource, config_common.NewConfigRepo(testDataSource)) err := userRepo.IncreaseQuestionCount(context.TODO(), "1", 1) assert.NoError(t, err) @@ -80,19 +79,19 @@ func Test_userRepo_IncreaseQuestionCount(t *testing.T) { } func Test_userRepo_UpdateEmail(t *testing.T) { - userRepo := user.NewUserRepo(testDataSource, config.NewConfigRepo(testDataSource)) + userRepo := user.NewUserRepo(testDataSource, config_common.NewConfigRepo(testDataSource)) err := userRepo.UpdateEmail(context.TODO(), "1", "admin@admin.com") assert.NoError(t, err) } func Test_userRepo_UpdateEmailStatus(t *testing.T) { - userRepo := user.NewUserRepo(testDataSource, config.NewConfigRepo(testDataSource)) + userRepo := user.NewUserRepo(testDataSource, config_common.NewConfigRepo(testDataSource)) err := userRepo.UpdateEmailStatus(context.TODO(), "1", entity.EmailStatusToBeVerified) assert.NoError(t, err) } func Test_userRepo_UpdateInfo(t *testing.T) { - userRepo := user.NewUserRepo(testDataSource, config.NewConfigRepo(testDataSource)) + userRepo := user.NewUserRepo(testDataSource, config_common.NewConfigRepo(testDataSource)) err := userRepo.UpdateInfo(context.TODO(), &entity.User{ID: "1", Bio: "test"}) assert.NoError(t, err) @@ -103,19 +102,19 @@ func Test_userRepo_UpdateInfo(t *testing.T) { } func Test_userRepo_UpdateLastLoginDate(t *testing.T) { - userRepo := user.NewUserRepo(testDataSource, config.NewConfigRepo(testDataSource)) + userRepo := user.NewUserRepo(testDataSource, config_common.NewConfigRepo(testDataSource)) err := userRepo.UpdateLastLoginDate(context.TODO(), "1") assert.NoError(t, err) } func Test_userRepo_UpdateNoticeStatus(t *testing.T) { - userRepo := user.NewUserRepo(testDataSource, config.NewConfigRepo(testDataSource)) + userRepo := user.NewUserRepo(testDataSource, config_common.NewConfigRepo(testDataSource)) err := userRepo.UpdateNoticeStatus(context.TODO(), "1", 1) assert.NoError(t, err) } func Test_userRepo_UpdatePass(t *testing.T) { - userRepo := user.NewUserRepo(testDataSource, config.NewConfigRepo(testDataSource)) + userRepo := user.NewUserRepo(testDataSource, config_common.NewConfigRepo(testDataSource)) err := userRepo.UpdatePass(context.TODO(), "1", "admin") assert.NoError(t, err) } diff --git a/internal/repo/report/report_repo.go b/internal/repo/report/report_repo.go index 3fa627f0..21f33cdf 100644 --- a/internal/repo/report/report_repo.go +++ b/internal/repo/report/report_repo.go @@ -35,7 +35,7 @@ func (rr *reportRepo) AddReport(ctx context.Context, report *entity.Report) (err if err != nil { return err } - _, err = rr.data.DB.Insert(report) + _, err = rr.data.DB.Context(ctx).Insert(report) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -48,7 +48,7 @@ func (rr *reportRepo) GetReportListPage(ctx context.Context, dto schema.GetRepor ok bool status int objectType int - session = rr.data.DB.NewSession() + session = rr.data.DB.Context(ctx) cond = entity.Report{} ) @@ -78,7 +78,7 @@ func (rr *reportRepo) GetReportListPage(ctx context.Context, dto schema.GetRepor // GetByID get report by ID func (rr *reportRepo) GetByID(ctx context.Context, id string) (report *entity.Report, exist bool, err error) { report = &entity.Report{} - exist, err = rr.data.DB.ID(id).Get(report) + exist, err = rr.data.DB.Context(ctx).ID(id).Get(report) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -87,7 +87,7 @@ func (rr *reportRepo) GetByID(ctx context.Context, id string) (report *entity.Re // UpdateByID handle report by ID func (rr *reportRepo) UpdateByID(ctx context.Context, id string, handleData entity.Report) (err error) { - _, err = rr.data.DB.ID(id).Update(&handleData) + _, err = rr.data.DB.Context(ctx).ID(id).Update(&handleData) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -96,7 +96,7 @@ func (rr *reportRepo) UpdateByID(ctx context.Context, id string, handleData enti func (rr *reportRepo) GetReportCount(ctx context.Context) (count int64, err error) { list := make([]*entity.Report, 0) - count, err = rr.data.DB.Where("status =?", entity.ReportStatusPending).FindAndCount(&list) + count, err = rr.data.DB.Context(ctx).Where("status =?", entity.ReportStatusPending).FindAndCount(&list) if err != nil { return count, errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } diff --git a/internal/repo/revision/revision_repo.go b/internal/repo/revision/revision_repo.go index 813be967..314276af 100644 --- a/internal/repo/revision/revision_repo.go +++ b/internal/repo/revision/revision_repo.go @@ -46,6 +46,7 @@ func (rr *revisionRepo) AddRevision(ctx context.Context, revision *entity.Revisi return nil } _, err = rr.data.DB.Transaction(func(session *xorm.Session) (interface{}, error) { + session = session.Context(ctx) _, err = session.Insert(revision) if err != nil { _ = session.Rollback() @@ -90,7 +91,7 @@ func (rr *revisionRepo) UpdateStatus(ctx context.Context, id string, status int, data.ID = id data.Status = status data.ReviewUserID = converter.StringToInt64(reviewUserID) - _, err = rr.data.DB.Where("id =?", id).Cols("status", "review_user_id").Update(&data) + _, err = rr.data.DB.Context(ctx).Where("id =?", id).Cols("status", "review_user_id").Update(&data) if err != nil { return errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -102,7 +103,7 @@ func (rr *revisionRepo) GetRevision(ctx context.Context, id string) ( revision *entity.Revision, exist bool, err error, ) { revision = &entity.Revision{} - exist, err = rr.data.DB.ID(id).Get(revision) + exist, err = rr.data.DB.Context(ctx).ID(id).Get(revision) if err != nil { return nil, false, errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -113,7 +114,7 @@ func (rr *revisionRepo) GetRevision(ctx context.Context, id string) ( func (rr *revisionRepo) GetRevisionByID(ctx context.Context, revisionID string) ( revision *entity.Revision, exist bool, err error) { revision = &entity.Revision{} - exist, err = rr.data.DB.Where("id = ?", revisionID).Get(revision) + exist, err = rr.data.DB.Context(ctx).Where("id = ?", revisionID).Get(revision) if err != nil { return nil, false, errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -123,7 +124,7 @@ func (rr *revisionRepo) GetRevisionByID(ctx context.Context, revisionID string) func (rr *revisionRepo) ExistUnreviewedByObjectID(ctx context.Context, objectID string) ( revision *entity.Revision, exist bool, err error) { revision = &entity.Revision{} - exist, err = rr.data.DB.Where("object_id = ?", objectID).And("status = ?", entity.RevisionUnreviewedStatus).Get(revision) + exist, err = rr.data.DB.Context(ctx).Where("object_id = ?", objectID).And("status = ?", entity.RevisionUnreviewedStatus).Get(revision) if err != nil { return nil, false, errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -135,7 +136,7 @@ func (rr *revisionRepo) GetLastRevisionByObjectID(ctx context.Context, objectID revision *entity.Revision, exist bool, err error, ) { revision = &entity.Revision{} - exist, err = rr.data.DB.Where("object_id = ?", objectID).OrderBy("created_at DESC").Get(revision) + exist, err = rr.data.DB.Context(ctx).Where("object_id = ?", objectID).OrderBy("created_at DESC").Get(revision) if err != nil { return nil, false, errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -145,7 +146,7 @@ func (rr *revisionRepo) GetLastRevisionByObjectID(ctx context.Context, objectID // GetRevisionList get revision list all func (rr *revisionRepo) GetRevisionList(ctx context.Context, revision *entity.Revision) (revisionList []entity.Revision, err error) { revisionList = []entity.Revision{} - err = rr.data.DB.Where(builder.Eq{ + err = rr.data.DB.Context(ctx).Where(builder.Eq{ "object_id": revision.ObjectID, }).OrderBy("created_at DESC").Find(&revisionList) if err != nil { @@ -175,7 +176,7 @@ func (rr *revisionRepo) GetUnreviewedRevisionPage(ctx context.Context, page int, if len(objectTypeList) == 0 { return revisionList, 0, nil } - session := rr.data.DB.NewSession() + session := rr.data.DB.Context(ctx) session = session.And("status = ?", entity.RevisionUnreviewedStatus) session = session.In("object_type", objectTypeList) session = session.OrderBy("created_at asc") diff --git a/internal/repo/role/power_repo.go b/internal/repo/role/power_repo.go index 1c902e6c..c2a5a402 100644 --- a/internal/repo/role/power_repo.go +++ b/internal/repo/role/power_repo.go @@ -25,7 +25,7 @@ func NewPowerRepo(data *data.Data) role.PowerRepo { // GetPowerList get list all func (pr *powerRepo) GetPowerList(ctx context.Context, power *entity.Power) (powerList []*entity.Power, err error) { powerList = make([]*entity.Power, 0) - err = pr.data.DB.Find(powerList, power) + err = pr.data.DB.Context(ctx).Find(powerList, power) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } diff --git a/internal/repo/role/role_power_rel_repo.go b/internal/repo/role/role_power_rel_repo.go index dc553eaa..73761c98 100644 --- a/internal/repo/role/role_power_rel_repo.go +++ b/internal/repo/role/role_power_rel_repo.go @@ -25,7 +25,7 @@ func NewRolePowerRelRepo(data *data.Data) role.RolePowerRelRepo { // GetRolePowerTypeList get role power type list func (rr *rolePowerRelRepo) GetRolePowerTypeList(ctx context.Context, roleID int) (powers []string, err error) { powers = make([]string, 0) - err = rr.data.DB.Table("role_power_rel"). + err = rr.data.DB.Context(ctx).Table("role_power_rel"). Cols("power_type").Where(builder.Eq{"role_id": roleID}).Find(&powers) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() diff --git a/internal/repo/role/role_repo.go b/internal/repo/role/role_repo.go index 4534795e..6ee42df1 100644 --- a/internal/repo/role/role_repo.go +++ b/internal/repo/role/role_repo.go @@ -25,7 +25,7 @@ func NewRoleRepo(data *data.Data) service.RoleRepo { // GetRoleAllList get role list all func (rr *roleRepo) GetRoleAllList(ctx context.Context) (roleList []*entity.Role, err error) { roleList = make([]*entity.Role, 0) - err = rr.data.DB.Find(&roleList) + err = rr.data.DB.Context(ctx).Find(&roleList) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } diff --git a/internal/repo/role/user_role_rel_repo.go b/internal/repo/role/user_role_rel_repo.go index 9398a5d9..b840e86e 100644 --- a/internal/repo/role/user_role_rel_repo.go +++ b/internal/repo/role/user_role_rel_repo.go @@ -27,6 +27,7 @@ func NewUserRoleRelRepo(data *data.Data) role.UserRoleRelRepo { // SaveUserRoleRel save user role rel func (ur *userRoleRelRepo) SaveUserRoleRel(ctx context.Context, userID string, roleID int) (err error) { _, err = ur.data.DB.Transaction(func(session *xorm.Session) (interface{}, error) { + session = session.Context(ctx) item := &entity.UserRoleRel{UserID: userID} exist, err := session.Get(item) if err != nil { @@ -53,7 +54,7 @@ func (ur *userRoleRelRepo) SaveUserRoleRel(ctx context.Context, userID string, r func (ur *userRoleRelRepo) GetUserRoleRelList(ctx context.Context, userIDs []string) ( userRoleRelList []*entity.UserRoleRel, err error) { userRoleRelList = make([]*entity.UserRoleRel, 0) - err = ur.data.DB.In("user_id", userIDs).Find(&userRoleRelList) + err = ur.data.DB.Context(ctx).In("user_id", userIDs).Find(&userRoleRelList) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -64,7 +65,7 @@ func (ur *userRoleRelRepo) GetUserRoleRelList(ctx context.Context, userIDs []str func (ur *userRoleRelRepo) GetUserRoleRelListByRoleID(ctx context.Context, roleIDs []int) ( userRoleRelList []*entity.UserRoleRel, err error) { userRoleRelList = make([]*entity.UserRoleRel, 0) - err = ur.data.DB.In("role_id", roleIDs).Find(&userRoleRelList) + err = ur.data.DB.Context(ctx).In("role_id", roleIDs).Find(&userRoleRelList) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -75,7 +76,7 @@ func (ur *userRoleRelRepo) GetUserRoleRelListByRoleID(ctx context.Context, roleI func (ur *userRoleRelRepo) GetUserRoleRel(ctx context.Context, userID string) ( rolePowerRel *entity.UserRoleRel, exist bool, err error) { rolePowerRel = &entity.UserRoleRel{} - exist, err = ur.data.DB.Where(builder.Eq{"user_id": userID}).Get(rolePowerRel) + exist, err = ur.data.DB.Context(ctx).Where(builder.Eq{"user_id": userID}).Get(rolePowerRel) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } diff --git a/internal/repo/search_common/search_repo.go b/internal/repo/search_common/search_repo.go index da32503c..1f46bdf4 100644 --- a/internal/repo/search_common/search_repo.go +++ b/internal/repo/search_common/search_repo.go @@ -190,12 +190,12 @@ func (sr *searchRepo) SearchContents(ctx context.Context, words []string, tagIDs countArgs = append(countArgs, argsQ...) countArgs = append(countArgs, argsA...) - res, err := sr.data.DB.Query(queryArgs...) + res, err := sr.data.DB.Context(ctx).Query(queryArgs...) if err != nil { return } - tr, err := sr.data.DB.Query(countArgs...) + tr, err := sr.data.DB.Context(ctx).Query(countArgs...) if len(tr) != 0 { total = converter.StringToInt64(string(tr[0]["total"])) } @@ -297,12 +297,12 @@ func (sr *searchRepo) SearchQuestions(ctx context.Context, words []string, tagID countArgs = append(countArgs, countSQL) countArgs = append(countArgs, args...) - res, err := sr.data.DB.Query(queryArgs...) + res, err := sr.data.DB.Context(ctx).Query(queryArgs...) if err != nil { return } - tr, err := sr.data.DB.Query(countArgs...) + tr, err := sr.data.DB.Context(ctx).Query(countArgs...) if err != nil { return } @@ -392,12 +392,12 @@ func (sr *searchRepo) SearchAnswers(ctx context.Context, words []string, tagIDs countArgs = append(countArgs, countSQL) countArgs = append(countArgs, args...) - res, err := sr.data.DB.Query(queryArgs...) + res, err := sr.data.DB.Context(ctx).Query(queryArgs...) if err != nil { return } - tr, err := sr.data.DB.Query(countArgs...) + tr, err := sr.data.DB.Context(ctx).Query(countArgs...) if err != nil { return } @@ -451,7 +451,7 @@ func (sr *searchRepo) parseResult(ctx context.Context, res []map[string][]byte) } // get tags - err = sr.data.DB. + err = sr.data.DB.Context(ctx). Select("`display_name`,`slug_name`,`main_tag_slug_name`,`recommend`,`reserved`"). Table("tag"). Join("INNER", "tag_rel", "tag.id = tag_rel.tag_id"). diff --git a/internal/repo/site_info/siteinfo_repo.go b/internal/repo/site_info/siteinfo_repo.go index bee8ae50..03c89416 100644 --- a/internal/repo/site_info/siteinfo_repo.go +++ b/internal/repo/site_info/siteinfo_repo.go @@ -27,14 +27,14 @@ func NewSiteInfo(data *data.Data) siteinfo_common.SiteInfoRepo { // SaveByType save site setting by type func (sr *siteInfoRepo) SaveByType(ctx context.Context, siteType string, data *entity.SiteInfo) (err error) { old := &entity.SiteInfo{} - exist, err := sr.data.DB.Where(builder.Eq{"type": siteType}).Get(old) + exist, err := sr.data.DB.Context(ctx).Where(builder.Eq{"type": siteType}).Get(old) if err != nil { return errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } if exist { - _, err = sr.data.DB.ID(old.ID).Update(data) + _, err = sr.data.DB.Context(ctx).ID(old.ID).Update(data) } else { - _, err = sr.data.DB.Insert(data) + _, err = sr.data.DB.Context(ctx).Insert(data) } if err != nil { return errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() @@ -50,7 +50,7 @@ func (sr *siteInfoRepo) GetByType(ctx context.Context, siteType string) (siteInf return siteInfo, true, nil } siteInfo = &entity.SiteInfo{} - exist, err = sr.data.DB.Where(builder.Eq{"type": siteType}).Get(siteInfo) + exist, err = sr.data.DB.Context(ctx).Where(builder.Eq{"type": siteType}).Get(siteInfo) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } diff --git a/internal/repo/tag/tag_rel_repo.go b/internal/repo/tag/tag_rel_repo.go index 4f07dfd2..62b3fe7a 100644 --- a/internal/repo/tag/tag_rel_repo.go +++ b/internal/repo/tag/tag_rel_repo.go @@ -32,7 +32,7 @@ func (tr *tagRelRepo) AddTagRelList(ctx context.Context, tagList []*entity.TagRe for _, item := range tagList { item.ObjectID = uid.DeShortID(item.ObjectID) } - _, err = tr.data.DB.Insert(tagList) + _, err = tr.data.DB.Context(ctx).Insert(tagList) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -45,7 +45,7 @@ func (tr *tagRelRepo) AddTagRelList(ctx context.Context, tagList []*entity.TagRe // RemoveTagRelListByObjectID delete tag list func (tr *tagRelRepo) RemoveTagRelListByObjectID(ctx context.Context, objectID string) (err error) { objectID = uid.DeShortID(objectID) - _, err = tr.data.DB.Where("object_id = ?", objectID).Update(&entity.TagRel{Status: entity.TagRelStatusDeleted}) + _, err = tr.data.DB.Context(ctx).Where("object_id = ?", objectID).Update(&entity.TagRel{Status: entity.TagRelStatusDeleted}) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -72,7 +72,7 @@ func (tr *tagRelRepo) ShowTagRelListByObjectID(ctx context.Context, objectID str // RemoveTagRelListByIDs delete tag list func (tr *tagRelRepo) RemoveTagRelListByIDs(ctx context.Context, ids []int64) (err error) { - _, err = tr.data.DB.In("id", ids).Update(&entity.TagRel{Status: entity.TagRelStatusDeleted}) + _, err = tr.data.DB.Context(ctx).In("id", ids).Update(&entity.TagRel{Status: entity.TagRelStatusDeleted}) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -85,7 +85,7 @@ func (tr *tagRelRepo) GetObjectTagRelWithoutStatus(ctx context.Context, objectID ) { objectID = uid.DeShortID(objectID) tagRel = &entity.TagRel{} - session := tr.data.DB.Where("object_id = ?", objectID).And("tag_id = ?", tagID) + session := tr.data.DB.Context(ctx).Where("object_id = ?", objectID).And("tag_id = ?", tagID) exist, err = session.Get(tagRel) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() @@ -96,7 +96,7 @@ func (tr *tagRelRepo) GetObjectTagRelWithoutStatus(ctx context.Context, objectID // EnableTagRelByIDs update tag status to available func (tr *tagRelRepo) EnableTagRelByIDs(ctx context.Context, ids []int64) (err error) { - _, err = tr.data.DB.In("id", ids).Update(&entity.TagRel{Status: entity.TagRelStatusAvailable}) + _, err = tr.data.DB.Context(ctx).In("id", ids).Update(&entity.TagRel{Status: entity.TagRelStatusAvailable}) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -107,7 +107,7 @@ func (tr *tagRelRepo) EnableTagRelByIDs(ctx context.Context, ids []int64) (err e func (tr *tagRelRepo) GetObjectTagRelList(ctx context.Context, objectID string) (tagListList []*entity.TagRel, err error) { objectID = uid.DeShortID(objectID) tagListList = make([]*entity.TagRel, 0) - session := tr.data.DB.Where("object_id = ?", objectID) + session := tr.data.DB.Context(ctx).Where("object_id = ?", objectID) session.In("status", []int{entity.TagRelStatusAvailable, entity.TagRelStatusHide}) err = session.Find(&tagListList) if err != nil { @@ -125,7 +125,7 @@ func (tr *tagRelRepo) BatchGetObjectTagRelList(ctx context.Context, objectIds [] objectIds[num] = uid.DeShortID(item) } tagListList = make([]*entity.TagRel, 0) - session := tr.data.DB.In("object_id", objectIds) + session := tr.data.DB.Context(ctx).In("object_id", objectIds) session.Where("status = ?", entity.TagRelStatusAvailable) err = session.Find(&tagListList) if err != nil { @@ -139,7 +139,7 @@ func (tr *tagRelRepo) BatchGetObjectTagRelList(ctx context.Context, objectIds [] // CountTagRelByTagID count tag relation func (tr *tagRelRepo) CountTagRelByTagID(ctx context.Context, tagID string) (count int64, err error) { - count, err = tr.data.DB.Count(&entity.TagRel{TagID: tagID, Status: entity.AnswerStatusAvailable}) + count, err = tr.data.DB.Context(ctx).Count(&entity.TagRel{TagID: tagID, Status: entity.AnswerStatusAvailable}) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } diff --git a/internal/repo/tag/tag_repo.go b/internal/repo/tag/tag_repo.go index 02604cb7..d5ea992b 100644 --- a/internal/repo/tag/tag_repo.go +++ b/internal/repo/tag/tag_repo.go @@ -32,7 +32,7 @@ func NewTagRepo( // RemoveTag delete tag func (tr *tagRepo) RemoveTag(ctx context.Context, tagID string) (err error) { - session := tr.data.DB.Where(builder.Eq{"id": tagID}) + session := tr.data.DB.Context(ctx).Where(builder.Eq{"id": tagID}) _, err = session.Update(&entity.Tag{Status: entity.TagStatusDeleted}) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() @@ -42,7 +42,7 @@ func (tr *tagRepo) RemoveTag(ctx context.Context, tagID string) (err error) { // UpdateTag update tag func (tr *tagRepo) UpdateTag(ctx context.Context, tag *entity.Tag) (err error) { - _, err = tr.data.DB.Where(builder.Eq{"id": tag.ID}).Update(tag) + _, err = tr.data.DB.Context(ctx).Where(builder.Eq{"id": tag.ID}).Update(tag) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -54,7 +54,7 @@ func (tr *tagRepo) UpdateTagSynonym(ctx context.Context, tagSlugNameList []strin mainTagSlugName string, ) (err error) { bean := &entity.Tag{MainTagID: mainTagID, MainTagSlugName: mainTagSlugName} - session := tr.data.DB.In("slug_name", tagSlugNameList).MustCols("main_tag_id", "main_tag_slug_name") + session := tr.data.DB.Context(ctx).In("slug_name", tagSlugNameList).MustCols("main_tag_id", "main_tag_slug_name") _, err = session.Update(bean) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() @@ -63,7 +63,7 @@ func (tr *tagRepo) UpdateTagSynonym(ctx context.Context, tagSlugNameList []strin } func (tr *tagRepo) GetTagSynonymCount(ctx context.Context, tagID string) (count int64, err error) { - count, err = tr.data.DB.Count(&entity.Tag{MainTagID: converter.StringToInt64(tagID), Status: entity.TagStatusAvailable}) + count, err = tr.data.DB.Context(ctx).Count(&entity.Tag{MainTagID: converter.StringToInt64(tagID), Status: entity.TagStatusAvailable}) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -73,7 +73,7 @@ func (tr *tagRepo) GetTagSynonymCount(ctx context.Context, tagID string) (count // GetTagList get tag list all func (tr *tagRepo) GetTagList(ctx context.Context, tag *entity.Tag) (tagList []*entity.Tag, err error) { tagList = make([]*entity.Tag, 0) - session := tr.data.DB.Where(builder.Eq{"status": entity.TagStatusAvailable}) + session := tr.data.DB.Context(ctx).Where(builder.Eq{"status": entity.TagStatusAvailable}) err = session.Find(&tagList, tag) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() diff --git a/internal/repo/tag_common/tag_common_repo.go b/internal/repo/tag_common/tag_common_repo.go index b12810e0..a7380028 100644 --- a/internal/repo/tag_common/tag_common_repo.go +++ b/internal/repo/tag_common/tag_common_repo.go @@ -34,7 +34,7 @@ func NewTagCommonRepo( // GetTagListByIDs get tag list all func (tr *tagCommonRepo) GetTagListByIDs(ctx context.Context, ids []string) (tagList []*entity.Tag, err error) { tagList = make([]*entity.Tag, 0) - session := tr.data.DB.In("id", ids) + session := tr.data.DB.Context(ctx).In("id", ids) session.Where(builder.Eq{"status": entity.TagStatusAvailable}) err = session.OrderBy("recommend desc,reserved desc,id desc").Find(&tagList) if err != nil { @@ -46,7 +46,7 @@ func (tr *tagCommonRepo) GetTagListByIDs(ctx context.Context, ids []string) (tag // GetTagBySlugName get tag by slug name func (tr *tagCommonRepo) GetTagBySlugName(ctx context.Context, slugName string) (tagInfo *entity.Tag, exist bool, err error) { tagInfo = &entity.Tag{} - session := tr.data.DB.Where("LOWER(slug_name) = ?", slugName) + session := tr.data.DB.Context(ctx).Where("LOWER(slug_name) = ?", slugName) session.Where(builder.Eq{"status": entity.TagStatusAvailable}) exist, err = session.Get(tagInfo) if err != nil { @@ -59,7 +59,7 @@ func (tr *tagCommonRepo) GetTagBySlugName(ctx context.Context, slugName string) func (tr *tagCommonRepo) GetTagListByName(ctx context.Context, name string, hasReserved bool) (tagList []*entity.Tag, err error) { tagList = make([]*entity.Tag, 0) cond := &entity.Tag{} - session := tr.data.DB.Where("") + session := tr.data.DB.Context(ctx).Where("") if name != "" { session.Where("slug_name LIKE LOWER(?) or display_name LIKE ?", name+"%", name+"%") } else { @@ -78,7 +78,7 @@ func (tr *tagCommonRepo) GetTagListByName(ctx context.Context, name string, hasR func (tr *tagCommonRepo) GetRecommendTagList(ctx context.Context) (tagList []*entity.Tag, err error) { tagList = make([]*entity.Tag, 0) cond := &entity.Tag{} - session := tr.data.DB.Where("") + session := tr.data.DB.Context(ctx).Where("") cond.Recommend = true // session.Where(builder.Eq{"status": entity.TagStatusAvailable}) session.Asc("slug_name") @@ -93,7 +93,7 @@ func (tr *tagCommonRepo) GetRecommendTagList(ctx context.Context) (tagList []*en func (tr *tagCommonRepo) GetReservedTagList(ctx context.Context) (tagList []*entity.Tag, err error) { tagList = make([]*entity.Tag, 0) cond := &entity.Tag{} - session := tr.data.DB.Where("") + session := tr.data.DB.Context(ctx).Where("") cond.Reserved = true // session.Where(builder.Eq{"status": entity.TagStatusAvailable}) session.Asc("slug_name") @@ -109,7 +109,7 @@ func (tr *tagCommonRepo) GetReservedTagList(ctx context.Context) (tagList []*ent func (tr *tagCommonRepo) GetTagListByNames(ctx context.Context, names []string) (tagList []*entity.Tag, err error) { tagList = make([]*entity.Tag, 0) - session := tr.data.DB.In("slug_name", names).UseBool("recommend", "reserved") + session := tr.data.DB.Context(ctx).In("slug_name", names).UseBool("recommend", "reserved") // session.Where(builder.Eq{"status": entity.TagStatusAvailable}) err = session.OrderBy("recommend desc,reserved desc,id desc").Find(&tagList) if err != nil { @@ -123,7 +123,7 @@ func (tr *tagCommonRepo) GetTagByID(ctx context.Context, tagID string, includeDe tag *entity.Tag, exist bool, err error, ) { tag = &entity.Tag{} - session := tr.data.DB.Where(builder.Eq{"id": tagID}) + session := tr.data.DB.Context(ctx).Where(builder.Eq{"id": tagID}) if !includeDeleted { session.Where(builder.Eq{"status": entity.TagStatusAvailable}) } @@ -139,7 +139,7 @@ func (tr *tagCommonRepo) GetTagPage(ctx context.Context, page, pageSize int, tag tagList []*entity.Tag, total int64, err error, ) { tagList = make([]*entity.Tag, 0) - session := tr.data.DB.NewSession() + session := tr.data.DB.Context(ctx) if len(tag.SlugName) > 0 { session.Where(builder.Or(builder.Like{"slug_name", fmt.Sprintf("LOWER(%s)", tag.SlugName)}, builder.Like{"display_name", tag.SlugName})) @@ -173,7 +173,7 @@ func (tr *tagCommonRepo) AddTagList(ctx context.Context, tagList []*entity.Tag) } item.RevisionID = "0" } - _, err = tr.data.DB.Insert(tagList) + _, err = tr.data.DB.Context(ctx).Insert(tagList) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -183,7 +183,7 @@ func (tr *tagCommonRepo) AddTagList(ctx context.Context, tagList []*entity.Tag) // UpdateTagQuestionCount update tag question count func (tr *tagCommonRepo) UpdateTagQuestionCount(ctx context.Context, tagID string, questionCount int) (err error) { cond := &entity.Tag{QuestionCount: questionCount} - _, err = tr.data.DB.Where(builder.Eq{"id": tagID}).MustCols("question_count").Update(cond) + _, err = tr.data.DB.Context(ctx).Where(builder.Eq{"id": tagID}).MustCols("question_count").Update(cond) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -200,7 +200,7 @@ func (tr *tagCommonRepo) UpdateTagsAttribute(ctx context.Context, tags []string, default: return } - session := tr.data.DB.In("slug_name", tags).Cols(attribute).UseBool(attribute) + session := tr.data.DB.Context(ctx).In("slug_name", tags).Cols(attribute).UseBool(attribute) _, err = session.Update(bean) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() diff --git a/internal/repo/unique/uniqid_repo.go b/internal/repo/unique/uniqid_repo.go index c460d904..eba2b527 100644 --- a/internal/repo/unique/uniqid_repo.go +++ b/internal/repo/unique/uniqid_repo.go @@ -29,7 +29,7 @@ func NewUniqueIDRepo(data *data.Data) unique.UniqueIDRepo { func (ur *uniqueIDRepo) GenUniqueIDStr(ctx context.Context, key string) (uniqueID string, err error) { objectType := constant.ObjectTypeStrMapping[key] bean := &entity.Uniqid{UniqidType: objectType} - _, err = ur.data.DB.Insert(bean) + _, err = ur.data.DB.Context(ctx).Insert(bean) if err != nil { return "", errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } diff --git a/internal/repo/user/user_backyard_repo.go b/internal/repo/user/user_backyard_repo.go index cebb2112..1af0a41a 100644 --- a/internal/repo/user/user_backyard_repo.go +++ b/internal/repo/user/user_backyard_repo.go @@ -42,7 +42,7 @@ func (ur *userAdminRepo) UpdateUserStatus(ctx context.Context, userID string, us case entity.UserStatusDeleted: cond.DeletedAt = time.Now() } - _, err = ur.data.DB.ID(userID).Update(cond) + _, err = ur.data.DB.Context(ctx).ID(userID).Update(cond) if err != nil { return errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -63,7 +63,7 @@ func (ur *userAdminRepo) UpdateUserStatus(ctx context.Context, userID string, us // AddUser add user func (ur *userAdminRepo) AddUser(ctx context.Context, user *entity.User) (err error) { - _, err = ur.data.DB.Insert(user) + _, err = ur.data.DB.Context(ctx).Insert(user) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -72,7 +72,7 @@ func (ur *userAdminRepo) AddUser(ctx context.Context, user *entity.User) (err er // UpdateUserPassword update user password func (ur *userAdminRepo) UpdateUserPassword(ctx context.Context, userID string, password string) (err error) { - _, err = ur.data.DB.ID(userID).Update(&entity.User{Pass: password}) + _, err = ur.data.DB.Context(ctx).ID(userID).Update(&entity.User{Pass: password}) if err != nil { return errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -82,7 +82,7 @@ func (ur *userAdminRepo) UpdateUserPassword(ctx context.Context, userID string, // GetUserInfo get user info func (ur *userAdminRepo) GetUserInfo(ctx context.Context, userID string) (user *entity.User, exist bool, err error) { user = &entity.User{} - exist, err = ur.data.DB.ID(userID).Get(user) + exist, err = ur.data.DB.Context(ctx).ID(userID).Get(user) if err != nil { return nil, false, errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -99,7 +99,7 @@ func (ur *userAdminRepo) GetUserInfo(ctx context.Context, userID string) (user * // GetUserInfoByEmail get user info func (ur *userAdminRepo) GetUserInfoByEmail(ctx context.Context, email string) (user *entity.User, exist bool, err error) { userInfo := &entity.User{} - exist, err = ur.data.DB.Where("e_mail = ?", email). + exist, err = ur.data.DB.Context(ctx).Where("e_mail = ?", email). Where("status != ?", entity.UserStatusDeleted).Get(userInfo) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() @@ -119,7 +119,7 @@ func (ur *userAdminRepo) GetUserInfoByEmail(ctx context.Context, email string) ( func (ur *userAdminRepo) GetUserPage(ctx context.Context, page, pageSize int, user *entity.User, usernameOrDisplayName string, isStaff bool) (users []*entity.User, total int64, err error) { users = make([]*entity.User, 0) - session := ur.data.DB.NewSession() + session := ur.data.DB.Context(ctx) switch user.Status { case entity.UserStatusDeleted: session.Desc("user.deleted_at") diff --git a/internal/repo/user/user_repo.go b/internal/repo/user/user_repo.go index 97be3837..72f7dc5c 100644 --- a/internal/repo/user/user_repo.go +++ b/internal/repo/user/user_repo.go @@ -8,7 +8,6 @@ import ( "github.com/answerdev/answer/internal/base/reason" "github.com/answerdev/answer/internal/entity" "github.com/answerdev/answer/internal/schema" - "github.com/answerdev/answer/internal/service/config" usercommon "github.com/answerdev/answer/internal/service/user_common" "github.com/answerdev/answer/pkg/converter" "github.com/answerdev/answer/plugin" @@ -19,21 +18,20 @@ import ( // userRepo user repository type userRepo struct { - data *data.Data - configRepo config.ConfigRepo + data *data.Data } // NewUserRepo new repository -func NewUserRepo(data *data.Data, configRepo config.ConfigRepo) usercommon.UserRepo { +func NewUserRepo(data *data.Data) usercommon.UserRepo { return &userRepo{ - data: data, - configRepo: configRepo, + data: data, } } // AddUser add user func (ur *userRepo) AddUser(ctx context.Context, user *entity.User) (err error) { _, err = ur.data.DB.Transaction(func(session *xorm.Session) (interface{}, error) { + session = session.Context(ctx) userInfo := &entity.User{} exist, err := session.Where("username = ?", user.Username).Get(userInfo) if err != nil { @@ -54,7 +52,7 @@ func (ur *userRepo) AddUser(ctx context.Context, user *entity.User) (err error) // IncreaseAnswerCount increase answer count func (ur *userRepo) IncreaseAnswerCount(ctx context.Context, userID string, amount int) (err error) { user := &entity.User{} - _, err = ur.data.DB.Where("id = ?", userID).Incr("answer_count", amount).Update(user) + _, err = ur.data.DB.Context(ctx).Where("id = ?", userID).Incr("answer_count", amount).Update(user) if err != nil { return errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -64,7 +62,7 @@ func (ur *userRepo) IncreaseAnswerCount(ctx context.Context, userID string, amou // IncreaseQuestionCount increase question count func (ur *userRepo) IncreaseQuestionCount(ctx context.Context, userID string, amount int) (err error) { user := &entity.User{} - _, err = ur.data.DB.Where("id = ?", userID).Incr("question_count", amount).Update(user) + _, err = ur.data.DB.Context(ctx).Where("id = ?", userID).Incr("question_count", amount).Update(user) if err != nil { return errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -94,7 +92,7 @@ func (ur *userRepo) UpdateAnswerCount(ctx context.Context, userID string, count // UpdateLastLoginDate update last login date func (ur *userRepo) UpdateLastLoginDate(ctx context.Context, userID string) (err error) { user := &entity.User{LastLoginDate: time.Now()} - _, err = ur.data.DB.Where("id = ?", userID).Cols("last_login_date").Update(user) + _, err = ur.data.DB.Context(ctx).Where("id = ?", userID).Cols("last_login_date").Update(user) if err != nil { return errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -104,7 +102,7 @@ func (ur *userRepo) UpdateLastLoginDate(ctx context.Context, userID string) (err // UpdateEmailStatus update email status func (ur *userRepo) UpdateEmailStatus(ctx context.Context, userID string, emailStatus int) error { cond := &entity.User{MailStatus: emailStatus} - _, err := ur.data.DB.Where("id = ?", userID).Cols("mail_status").Update(cond) + _, err := ur.data.DB.Context(ctx).Where("id = ?", userID).Cols("mail_status").Update(cond) if err != nil { return err } @@ -114,7 +112,7 @@ func (ur *userRepo) UpdateEmailStatus(ctx context.Context, userID string, emailS // UpdateNoticeStatus update notice status func (ur *userRepo) UpdateNoticeStatus(ctx context.Context, userID string, noticeStatus int) error { cond := &entity.User{NoticeStatus: noticeStatus} - _, err := ur.data.DB.Where("id = ?", userID).Cols("notice_status").Update(cond) + _, err := ur.data.DB.Context(ctx).Where("id = ?", userID).Cols("notice_status").Update(cond) if err != nil { return errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -122,7 +120,7 @@ func (ur *userRepo) UpdateNoticeStatus(ctx context.Context, userID string, notic } func (ur *userRepo) UpdatePass(ctx context.Context, userID, pass string) error { - _, err := ur.data.DB.Where("id = ?", userID).Cols("pass").Update(&entity.User{Pass: pass}) + _, err := ur.data.DB.Context(ctx).Where("id = ?", userID).Cols("pass").Update(&entity.User{Pass: pass}) if err != nil { return errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -130,7 +128,7 @@ func (ur *userRepo) UpdatePass(ctx context.Context, userID, pass string) error { } func (ur *userRepo) UpdateEmail(ctx context.Context, userID, email string) (err error) { - _, err = ur.data.DB.Where("id = ?", userID).Update(&entity.User{EMail: email}) + _, err = ur.data.DB.Context(ctx).Where("id = ?", userID).Update(&entity.User{EMail: email}) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -138,7 +136,7 @@ func (ur *userRepo) UpdateEmail(ctx context.Context, userID, email string) (err } func (ur *userRepo) UpdateLanguage(ctx context.Context, userID, language string) (err error) { - _, err = ur.data.DB.Where("id = ?", userID).Update(&entity.User{Language: language}) + _, err = ur.data.DB.Context(ctx).Where("id = ?", userID).Update(&entity.User{Language: language}) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -147,7 +145,7 @@ func (ur *userRepo) UpdateLanguage(ctx context.Context, userID, language string) // UpdateInfo update user info func (ur *userRepo) UpdateInfo(ctx context.Context, userInfo *entity.User) (err error) { - _, err = ur.data.DB.Where("id = ?", userInfo.ID). + _, err = ur.data.DB.Context(ctx).Where("id = ?", userInfo.ID). Cols("username", "display_name", "avatar", "bio", "bio_html", "website", "location").Update(userInfo) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() @@ -158,7 +156,7 @@ func (ur *userRepo) UpdateInfo(ctx context.Context, userInfo *entity.User) (err // GetByUserID get user info by user id func (ur *userRepo) GetByUserID(ctx context.Context, userID string) (userInfo *entity.User, exist bool, err error) { userInfo = &entity.User{} - exist, err = ur.data.DB.Where("id = ?", userID).Get(userInfo) + exist, err = ur.data.DB.Context(ctx).Where("id = ?", userID).Get(userInfo) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() return @@ -172,7 +170,7 @@ func (ur *userRepo) GetByUserID(ctx context.Context, userID string) (userInfo *e func (ur *userRepo) BatchGetByID(ctx context.Context, ids []string) ([]*entity.User, error) { list := make([]*entity.User, 0) - err := ur.data.DB.In("id", ids).Find(&list) + err := ur.data.DB.Context(ctx).In("id", ids).Find(&list) if err != nil { return nil, errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -183,7 +181,7 @@ func (ur *userRepo) BatchGetByID(ctx context.Context, ids []string) ([]*entity.U // GetByUsername get user by username func (ur *userRepo) GetByUsername(ctx context.Context, username string) (userInfo *entity.User, exist bool, err error) { userInfo = &entity.User{} - exist, err = ur.data.DB.Where("username = ?", username).Get(userInfo) + exist, err = ur.data.DB.Context(ctx).Where("username = ?", username).Get(userInfo) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() return @@ -209,7 +207,7 @@ func (ur *userRepo) GetByUsernames(ctx context.Context, usernames []string) ([]* // GetByEmail get user by email func (ur *userRepo) GetByEmail(ctx context.Context, email string) (userInfo *entity.User, exist bool, err error) { userInfo = &entity.User{} - exist, err = ur.data.DB.Where("e_mail = ?", email). + exist, err = ur.data.DB.Context(ctx).Where("e_mail = ?", email). Where("status != ?", entity.UserStatusDeleted).Get(userInfo) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() @@ -219,7 +217,7 @@ func (ur *userRepo) GetByEmail(ctx context.Context, email string) (userInfo *ent func (ur *userRepo) GetUserCount(ctx context.Context) (count int64, err error) { list := make([]*entity.User, 0) - count, err = ur.data.DB.Where("mail_status =?", entity.EmailStatusAvailable).And("status =?", entity.UserStatusAvailable).FindAndCount(&list) + count, err = ur.data.DB.Context(ctx).Where("mail_status =?", entity.EmailStatusAvailable).And("status =?", entity.UserStatusAvailable).FindAndCount(&list) if err != nil { return count, errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -253,7 +251,7 @@ func tryToDecorateUserInfoFromUserCenter(ctx context.Context, data *data.Data, o } userInfo := &entity.UserExternalLogin{} - session := data.DB.Where("user_id = ?", original.ID) + session := data.DB.Context(ctx).Where("user_id = ?", original.ID) session.Where("provider = ?", uc.Info().SlugName) exist, err := session.Get(userInfo) if err != nil { @@ -291,7 +289,7 @@ func tryToDecorateUserListFromUserCenter(ctx context.Context, data *data.Data, o } userExternalLoginList := make([]*entity.UserExternalLogin, 0) - session := data.DB.Where("provider = ?", uc.Info().SlugName) + session := data.DB.Context(ctx).Where("provider = ?", uc.Info().SlugName) session.In("user_id", ids) err := session.Find(&userExternalLoginList) if err != nil { diff --git a/internal/repo/user_external_login/user_external_login_repo.go b/internal/repo/user_external_login/user_external_login_repo.go index f7be790e..9c7c5e22 100644 --- a/internal/repo/user_external_login/user_external_login_repo.go +++ b/internal/repo/user_external_login/user_external_login_repo.go @@ -26,7 +26,7 @@ func NewUserExternalLoginRepo(data *data.Data) user_external_login.UserExternalL // AddUserExternalLogin add external login information func (ur *userExternalLoginRepo) AddUserExternalLogin(ctx context.Context, user *entity.UserExternalLogin) (err error) { - _, err = ur.data.DB.Insert(user) + _, err = ur.data.DB.Context(ctx).Insert(user) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -35,7 +35,7 @@ func (ur *userExternalLoginRepo) AddUserExternalLogin(ctx context.Context, user // UpdateInfo update user info func (ur *userExternalLoginRepo) UpdateInfo(ctx context.Context, userInfo *entity.UserExternalLogin) (err error) { - _, err = ur.data.DB.ID(userInfo.ID).Update(userInfo) + _, err = ur.data.DB.Context(ctx).ID(userInfo.ID).Update(userInfo) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -46,7 +46,7 @@ func (ur *userExternalLoginRepo) UpdateInfo(ctx context.Context, userInfo *entit func (ur *userExternalLoginRepo) GetByExternalID(ctx context.Context, provider, externalID string) ( userInfo *entity.UserExternalLogin, exist bool, err error) { userInfo = &entity.UserExternalLogin{} - exist, err = ur.data.DB.Where("external_id = ?", externalID).Where("provider = ?", provider).Get(userInfo) + exist, err = ur.data.DB.Context(ctx).Where("external_id = ?", externalID).Where("provider = ?", provider).Get(userInfo) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -57,7 +57,7 @@ func (ur *userExternalLoginRepo) GetByExternalID(ctx context.Context, provider, func (ur *userExternalLoginRepo) GetUserExternalLoginList(ctx context.Context, userID string) ( resp []*entity.UserExternalLogin, err error) { resp = make([]*entity.UserExternalLogin, 0) - err = ur.data.DB.Where("user_id = ?", userID).Find(&resp) + err = ur.data.DB.Context(ctx).Where("user_id = ?", userID).Find(&resp) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } @@ -67,7 +67,7 @@ func (ur *userExternalLoginRepo) GetUserExternalLoginList(ctx context.Context, u // DeleteUserExternalLogin delete external user login info func (ur *userExternalLoginRepo) DeleteUserExternalLogin(ctx context.Context, userID, externalID string) (err error) { cond := &entity.UserExternalLogin{} - _, err = ur.data.DB.Where("user_id = ? AND external_id = ?", userID, externalID).Delete(cond) + _, err = ur.data.DB.Context(ctx).Where("user_id = ? AND external_id = ?", userID, externalID).Delete(cond) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } diff --git a/internal/schema/rank_schema.go b/internal/schema/rank_schema.go index b09eb66b..a5eb20fb 100644 --- a/internal/schema/rank_schema.go +++ b/internal/schema/rank_schema.go @@ -12,8 +12,8 @@ type GetRankPersonalWithPageReq struct { UserID string `json:"-"` } -// GetRankPersonalWithPageResp rank response -type GetRankPersonalWithPageResp struct { +// GetRankPersonalPageResp rank response +type GetRankPersonalPageResp struct { // create time CreatedAt int64 `json:"created_at"` // object id diff --git a/internal/schema/user_schema.go b/internal/schema/user_schema.go index 79442cb2..b1155bf4 100644 --- a/internal/schema/user_schema.go +++ b/internal/schema/user_schema.go @@ -8,7 +8,6 @@ import ( "github.com/answerdev/answer/internal/entity" "github.com/answerdev/answer/pkg/checker" "github.com/answerdev/answer/pkg/converter" - "github.com/answerdev/answer/pkg/gravatar" "github.com/jinzhu/copier" ) @@ -20,8 +19,8 @@ type UserVerifyEmailReq struct { Content string `json:"-"` } -// GetUserResp get user response -type GetUserResp struct { +// UserLoginResp get user response +type UserLoginResp struct { // user id ID string `json:"id"` // create time @@ -74,80 +73,25 @@ type GetUserResp struct { HavePassword bool `json:"have_password"` } -func (r *GetUserResp) GetFromUserEntity(userInfo *entity.User) { +func (r *UserLoginResp) ConvertFromUserEntity(userInfo *entity.User) { _ = copier.Copy(r, userInfo) - r.Avatar = FormatAvatarInfo(userInfo.Avatar, userInfo.EMail) r.CreatedAt = userInfo.CreatedAt.Unix() r.LastLoginDate = userInfo.LastLoginDate.Unix() - statusShow, ok := UserStatusShow[userInfo.Status] - if ok { - r.Status = statusShow - } + r.Status = UserStatusShow[userInfo.Status] r.HavePassword = len(userInfo.Pass) > 0 } -type GetUserToSetShowResp struct { - *GetUserResp +type GetCurrentLoginUserInfoResp struct { + *UserLoginResp Avatar *AvatarInfo `json:"avatar"` HavePassword bool `json:"have_password"` } -func (r *GetUserToSetShowResp) GetFromUserEntity(userInfo *entity.User) { +func (r *GetCurrentLoginUserInfoResp) ConvertFromUserEntity(userInfo *entity.User) { _ = copier.Copy(r, userInfo) r.CreatedAt = userInfo.CreatedAt.Unix() r.LastLoginDate = userInfo.LastLoginDate.Unix() - statusShow, ok := UserStatusShow[userInfo.Status] - if ok { - r.Status = statusShow - } - - avatarInfo := &AvatarInfo{} - _ = json.Unmarshal([]byte(userInfo.Avatar), avatarInfo) - if len(avatarInfo.Type) == 0 && constant.DefaultAvatar == AvatarTypeGravatar { - avatarInfo.Type = AvatarTypeGravatar - avatarInfo.Gravatar = gravatar.GetAvatarURL(userInfo.EMail) - } else if avatarInfo.Type == AvatarTypeGravatar { - avatarInfo.Gravatar = gravatar.GetAvatarURL(userInfo.EMail) - } - r.Avatar = avatarInfo -} - -const ( - AvatarTypeDefault = "default" - AvatarTypeGravatar = "gravatar" - AvatarTypeCustom = "custom" -) - -func FormatAvatarInfo(avatarJson, email string) (res string) { - defer func() { - if constant.DefaultAvatar == AvatarTypeGravatar && len(res) == 0 { - res = gravatar.GetAvatarURL(email) - } - }() - - if avatarJson == "" { - return "" - } - avatarInfo := &AvatarInfo{} - err := json.Unmarshal([]byte(avatarJson), avatarInfo) - if err != nil { - return "" - } - switch avatarInfo.Type { - case AvatarTypeGravatar: - return gravatar.GetAvatarURL(email) - case AvatarTypeCustom: - return avatarInfo.Custom - default: - return "" - } -} - -func CustomAvatar(url string) *AvatarInfo { - return &AvatarInfo{ - Type: AvatarTypeCustom, - Custom: url, - } + r.Status = UserStatusShow[userInfo.Status] } // GetUserStatusResp get user status info @@ -193,11 +137,8 @@ type GetOtherUserInfoByUsernameResp struct { StatusMsg string `json:"status_msg,omitempty"` } -func (r *GetOtherUserInfoByUsernameResp) GetFromUserEntity(userInfo *entity.User) { +func (r *GetOtherUserInfoByUsernameResp) ConvertFromUserEntity(userInfo *entity.User) { _ = copier.Copy(r, userInfo) - Avatar := FormatAvatarInfo(userInfo.Avatar, userInfo.EMail) - r.Avatar = Avatar - r.CreatedAt = userInfo.CreatedAt.Unix() r.LastLoginDate = userInfo.LastLoginDate.Unix() statusShow, ok := UserStatusShow[userInfo.Status] @@ -325,6 +266,24 @@ func (a *AvatarInfo) ToJsonString() string { return string(data) } +func (a *AvatarInfo) GetURL() string { + switch a.Type { + case constant.AvatarTypeGravatar: + return a.Gravatar + case constant.AvatarTypeCustom: + return a.Custom + default: + return "" + } +} + +func CustomAvatar(url string) *AvatarInfo { + return &AvatarInfo{ + Type: constant.AvatarTypeCustom, + Custom: url, + } +} + func (req *UpdateInfoRequest) Check() (errFields []*validator.FormErrorField, err error) { req.BioHTML = converter.Markdown2BasicHTML(req.Bio) return nil, nil diff --git a/internal/service/activity/activity.go b/internal/service/activity/activity.go index 1688de42..ebd5e6df 100644 --- a/internal/service/activity/activity.go +++ b/internal/service/activity/activity.go @@ -8,10 +8,10 @@ import ( "github.com/answerdev/answer/internal/base/constant" "github.com/answerdev/answer/internal/entity" - "github.com/answerdev/answer/internal/repo/config" "github.com/answerdev/answer/internal/schema" "github.com/answerdev/answer/internal/service/activity_common" "github.com/answerdev/answer/internal/service/comment_common" + "github.com/answerdev/answer/internal/service/config" "github.com/answerdev/answer/internal/service/meta" "github.com/answerdev/answer/internal/service/object_info" "github.com/answerdev/answer/internal/service/revision_common" @@ -38,6 +38,7 @@ type ActivityService struct { commentCommonService *comment_common.CommentCommonService revisionService *revision_common.RevisionService metaService *meta.MetaService + configService *config.ConfigService } // NewActivityService new activity service @@ -50,6 +51,7 @@ func NewActivityService( commentCommonService *comment_common.CommentCommonService, revisionService *revision_common.RevisionService, metaService *meta.MetaService, + configService *config.ConfigService, ) *ActivityService { return &ActivityService{ objectInfoService: objectInfoService, @@ -60,6 +62,7 @@ func NewActivityService( commentCommonService: commentCommonService, revisionService: revisionService, metaService: metaService, + configService: configService, } } @@ -97,14 +100,19 @@ func (as *ActivityService) GetObjectTimeline(ctx context.Context, req *schema.Ge item.ObjectID = uid.EnShortID(act.ObjectID) } - // database save activity type is number, change to activity type string is like "question.asked". - // so we need to cut the front part of '.' - _, item.ActivityType, _ = strings.Cut(config.ID2KeyMapping[act.ActivityType], ".") - // format activity type string to show - if isHidden, formattedActivityType := formatActivity(item.ActivityType); isHidden { - continue + cfg, err := as.configService.GetConfigByID(ctx, act.ActivityType) + if err != nil { + log.Errorf("fail to get config by id: %d, err: %v, act id is: %s", act.ActivityType, err, act.ID) } else { - item.ActivityType = formattedActivityType + // database save activity type is number, change to activity type string is like "question.asked". + // so we need to cut the front part of '.', only need string like 'asked' + _, item.ActivityType, _ = strings.Cut(cfg.Key, ".") + // format activity type string to show + if isHidden, formattedActivityType := formatActivity(item.ActivityType); isHidden { + continue + } else { + item.ActivityType = formattedActivityType + } } // if activity is down vote, only admin can see who does it. diff --git a/internal/service/activity_common/follow.go b/internal/service/activity_common/follow.go index baeff38c..5d448868 100644 --- a/internal/service/activity_common/follow.go +++ b/internal/service/activity_common/follow.go @@ -6,5 +6,5 @@ type FollowRepo interface { GetFollowIDs(ctx context.Context, userID, objectType string) (followIDs []string, err error) GetFollowAmount(ctx context.Context, objectID string) (followAmount int, err error) GetFollowUserIDs(ctx context.Context, objectID string) (userIDs []string, err error) - IsFollowed(userId, objectId string) (bool, error) + IsFollowed(ctx context.Context, userId, objectId string) (bool, error) } diff --git a/internal/service/activity_type/activity_type.go b/internal/service/activity_type/activity_type.go index 22ab8490..93282257 100644 --- a/internal/service/activity_type/activity_type.go +++ b/internal/service/activity_type/activity_type.go @@ -1,60 +1,55 @@ package activity_type -import ( - "github.com/answerdev/answer/internal/repo/config" -) - const ( QuestionVoteUp = "question.vote_up" QuestionVoteDown = "question.vote_down" - AnswerVoteUp = "answer.vote_up" - AnswerVoteDown = "answer.vote_down" - CommentVoteUp = "comment.vote_up" - CommentVoteDown = "comment.vote_down" - AnswerAccepted = "answer.accepted" - AnswerAccept = "answer.accept" QuestionVotedUp = "question.voted_up" QuestionVotedDown = "question.voted_down" + AnswerVoteUp = "answer.vote_up" + AnswerVoteDown = "answer.vote_down" AnswerVotedUp = "answer.voted_up" AnswerVotedDown = "answer.voted_down" + AnswerAccepted = "answer.accepted" + AnswerAccept = "answer.accept" + CommentVoteUp = "comment.vote_up" ) var ( ActivityTypeList = []string{ QuestionVoteUp, QuestionVoteDown, - AnswerVoteUp, - AnswerVoteDown, - CommentVoteUp, - CommentVoteDown, - AnswerAccepted, - AnswerAccept, QuestionVotedUp, QuestionVotedDown, + AnswerVoteUp, + AnswerVoteDown, AnswerVotedUp, AnswerVotedDown, + AnswerAccepted, + AnswerAccept, + CommentVoteUp, } - activityTypeFlagMapping = map[string]string{ - QuestionVoteUp: "upvote", - QuestionVoteDown: "downvote", - AnswerVoteUp: "upvote", - AnswerVoteDown: "downvote", - CommentVoteUp: "upvote", - CommentVoteDown: "downvote", - AnswerAccepted: "accepted", - AnswerAccept: "accept", - QuestionVotedUp: "upvoted", - QuestionVotedDown: "downvoted", - AnswerVotedUp: "upvoted", - AnswerVotedDown: "downvoted", + VoteActivityTypeList = []string{ + QuestionVoteUp, + QuestionVoteDown, + QuestionVotedUp, + QuestionVotedDown, + AnswerVoteUp, + AnswerVoteDown, + AnswerVotedUp, + AnswerVotedDown, + CommentVoteUp, + } + ActivityTypeFlagMapping = map[string]string{ + QuestionVoteUp: "action_activity_type.upvote", + QuestionVoteDown: "action_activity_type.downvote", + QuestionVotedUp: "action_activity_type.upvoted", + QuestionVotedDown: "action_activity_type.downvoted", + AnswerVoteUp: "action_activity_type.upvote", + AnswerVoteDown: "action_activity_type.downvote", + AnswerVotedUp: "action_activity_type.upvoted", + AnswerVotedDown: "action_activity_type.downvoted", + AnswerAccepted: "action_activity_type.accepted", + AnswerAccept: "action_activity_type.accept", + CommentVoteUp: "action_activity_type.upvote", } ) - -func Format(activityTypeID int) string { - activityTypeStr := config.ID2KeyMapping[activityTypeID] - activityTypeFlag := activityTypeFlagMapping[activityTypeStr] - if len(activityTypeFlag) == 0 { - return "edit" // to edit - } - return activityTypeFlag // todo i18n support -} diff --git a/internal/service/config/config_service.go b/internal/service/config/config_service.go index 882b8fa5..6adc4177 100644 --- a/internal/service/config/config_service.go +++ b/internal/service/config/config_service.go @@ -1,14 +1,18 @@ package config +import ( + "context" + "encoding/json" + "fmt" + + "github.com/answerdev/answer/internal/entity" +) + // ConfigRepo config repository type ConfigRepo interface { - Get(key string) (interface{}, error) - GetString(key string) (string, error) - GetInt(key string) (int, error) - GetArrayString(key string) ([]string, error) - GetConfigType(key string) (int, error) - GetJsonConfigByIDAndSetToObject(id int, value any) (err error) - SetConfig(key, value string) (err error) + GetConfigByID(ctx context.Context, id int) (c *entity.Config, err error) + GetConfigByKey(ctx context.Context, key string) (c *entity.Config, err error) + UpdateConfig(ctx context.Context, key, value string) (err error) } // ConfigService user service @@ -16,8 +20,70 @@ type ConfigService struct { configRepo ConfigRepo } +// NewConfigService new config service func NewConfigService(configRepo ConfigRepo) *ConfigService { return &ConfigService{ configRepo: configRepo, } } + +// GetIntValue get config int value +func (cs *ConfigService) GetIntValue(ctx context.Context, key string) (val int, err error) { + cf, err := cs.configRepo.GetConfigByKey(ctx, key) + if err != nil { + return 0, err + } + return cf.GetIntValue(), nil +} + +// GetStringValue get config string value +func (cs *ConfigService) GetStringValue(ctx context.Context, key string) (val string, err error) { + cf, err := cs.configRepo.GetConfigByKey(ctx, key) + if err != nil { + return "", err + } + return cf.Value, nil +} + +// GetArrayStringValue get config array string value +func (cs *ConfigService) GetArrayStringValue(ctx context.Context, key string) (val []string, err error) { + cf, err := cs.configRepo.GetConfigByKey(ctx, key) + if err != nil { + return nil, err + } + return cf.GetArrayStringValue(), nil +} + +func (cs *ConfigService) GetJsonConfigByIDAndSetToObject(ctx context.Context, id int, obj any) (err error) { + cf, err := cs.configRepo.GetConfigByID(ctx, id) + if err != nil { + return err + } + err = json.Unmarshal([]byte(cf.Value), obj) + if err != nil { + return fmt.Errorf("[%s] config value is not json format", cf.Key) + } + return nil +} + +// GetConfigByID get config by id +func (cs *ConfigService) GetConfigByID(ctx context.Context, id int) (c *entity.Config, err error) { + return cs.configRepo.GetConfigByID(ctx, id) +} + +func (cs *ConfigService) GetConfigByKey(ctx context.Context, key string) (c *entity.Config, err error) { + return cs.configRepo.GetConfigByKey(ctx, key) +} + +// GetIDByKey get config id by key +func (cs *ConfigService) GetIDByKey(ctx context.Context, key string) (id int, err error) { + cf, err := cs.configRepo.GetConfigByKey(ctx, key) + if err != nil { + return 0, err + } + return cf.ID, nil +} + +func (cs *ConfigService) UpdateConfig(ctx context.Context, key, value string) (err error) { + return cs.configRepo.UpdateConfig(ctx, key, value) +} diff --git a/internal/service/dashboard/dashboard_service.go b/internal/service/dashboard/dashboard_service.go index d8fcc8cb..fa798e69 100644 --- a/internal/service/dashboard/dashboard_service.go +++ b/internal/service/dashboard/dashboard_service.go @@ -35,7 +35,7 @@ type DashboardService struct { voteRepo activity_common.VoteRepo userRepo usercommon.UserRepo reportRepo report_common.ReportRepo - configRepo config.ConfigRepo + configService *config.ConfigService siteInfoService *siteinfo_common.SiteInfoCommonService serviceConfig *service_config.ServiceConfig @@ -49,7 +49,7 @@ func NewDashboardService( voteRepo activity_common.VoteRepo, userRepo usercommon.UserRepo, reportRepo report_common.ReportRepo, - configRepo config.ConfigRepo, + configService *config.ConfigService, siteInfoService *siteinfo_common.SiteInfoCommonService, serviceConfig *service_config.ServiceConfig, @@ -62,7 +62,7 @@ func NewDashboardService( voteRepo: voteRepo, userRepo: userRepo, reportRepo: reportRepo, - configRepo: configRepo, + configService: configService, siteInfoService: siteInfoService, serviceConfig: serviceConfig, @@ -131,12 +131,11 @@ func (ds *DashboardService) Statistical(ctx context.Context) (*schema.DashboardI var activityTypes []int for _, typeKey := range typeKeys { - var t int - t, err = ds.configRepo.GetConfigType(typeKey) + cfg, err := ds.configService.GetConfigByKey(ctx, typeKey) if err != nil { continue } - activityTypes = append(activityTypes, t) + activityTypes = append(activityTypes, cfg.ID) } voteCount, err := ds.voteRepo.GetVoteCount(ctx, activityTypes) @@ -166,7 +165,7 @@ func (ds *DashboardService) Statistical(ctx context.Context) (*schema.DashboardI dashboardInfo.ReportCount = reportCount dashboardInfo.UploadingFiles = true - emailconfig, err := ds.GetEmailConfig() + emailconfig, err := ds.GetEmailConfig(ctx) if err != nil { return dashboardInfo, err } @@ -225,8 +224,8 @@ func (ds *DashboardService) RemoteVersion(ctx context.Context) string { return remoteVersion.Release.Version } -func (ds *DashboardService) GetEmailConfig() (ec *export.EmailConfig, err error) { - emailConf, err := ds.configRepo.GetString("email.config") +func (ds *DashboardService) GetEmailConfig(ctx context.Context) (ec *export.EmailConfig, err error) { + emailConf, err := ds.configService.GetStringValue(ctx, "email.config") if err != nil { return nil, err } diff --git a/internal/service/export/email_service.go b/internal/service/export/email_service.go index 4fd2fa9f..8ab8139f 100644 --- a/internal/service/export/email_service.go +++ b/internal/service/export/email_service.go @@ -24,9 +24,9 @@ import ( // EmailService kit service type EmailService struct { - configRepo config.ConfigRepo - emailRepo EmailRepo - siteInfoRepo siteinfo_common.SiteInfoRepo + configService *config.ConfigService + emailRepo EmailRepo + siteInfoRepo siteinfo_common.SiteInfoRepo } // EmailRepo email repository @@ -36,11 +36,11 @@ type EmailRepo interface { } // NewEmailService email service -func NewEmailService(configRepo config.ConfigRepo, emailRepo EmailRepo, siteInfoRepo siteinfo_common.SiteInfoRepo) *EmailService { +func NewEmailService(configService *config.ConfigService, emailRepo EmailRepo, siteInfoRepo siteinfo_common.SiteInfoRepo) *EmailService { return &EmailService{ - configRepo: configRepo, - emailRepo: emailRepo, - siteInfoRepo: siteInfoRepo, + configService: configService, + emailRepo: emailRepo, + siteInfoRepo: siteInfoRepo, } } @@ -114,7 +114,7 @@ func (es *EmailService) SendAndSaveCodeWithTime( // Send email send func (es *EmailService) Send(ctx context.Context, toEmailAddr, subject, body string) { log.Infof("try to send email to %s", toEmailAddr) - ec, err := es.GetEmailConfig() + ec, err := es.GetEmailConfig(ctx) if err != nil { log.Errorf("get email config failed: %s", err) return @@ -298,8 +298,8 @@ func (es *EmailService) NewCommentTemplate(ctx context.Context, raw *schema.NewC return title, body, nil } -func (es *EmailService) GetEmailConfig() (ec *EmailConfig, err error) { - emailConf, err := es.configRepo.GetString("email.config") +func (es *EmailService) GetEmailConfig(ctx context.Context) (ec *EmailConfig, err error) { + emailConf, err := es.configService.GetStringValue(ctx, "email.config") if err != nil { return nil, err } @@ -312,7 +312,7 @@ func (es *EmailService) GetEmailConfig() (ec *EmailConfig, err error) { } // SetEmailConfig set email config -func (es *EmailService) SetEmailConfig(ec *EmailConfig) (err error) { +func (es *EmailService) SetEmailConfig(ctx context.Context, ec *EmailConfig) (err error) { data, _ := json.Marshal(ec) - return es.configRepo.SetConfig("email.config", string(data)) + return es.configService.UpdateConfig(ctx, "email.config", string(data)) } diff --git a/internal/service/plugin_common/plugin_common_service.go b/internal/service/plugin_common/plugin_common_service.go index c8f7d799..8517e469 100644 --- a/internal/service/plugin_common/plugin_common_service.go +++ b/internal/service/plugin_common/plugin_common_service.go @@ -21,17 +21,17 @@ type PluginConfigRepo interface { // PluginCommonService user service type PluginCommonService struct { - configRepo config.ConfigRepo + configService *config.ConfigService pluginConfigRepo PluginConfigRepo } // NewPluginCommonService new report service func NewPluginCommonService( pluginConfigRepo PluginConfigRepo, - configRepo config.ConfigRepo) *PluginCommonService { + configService *config.ConfigService) *PluginCommonService { // init plugin status - pluginStatus, err := configRepo.GetString(constant.PluginStatus) + pluginStatus, err := configService.GetStringValue(context.TODO(), constant.PluginStatus) if err != nil { log.Error(err) } else { @@ -59,7 +59,7 @@ func NewPluginCommonService( } return &PluginCommonService{ - configRepo: configRepo, + configService: configService, pluginConfigRepo: pluginConfigRepo, } } @@ -70,7 +70,7 @@ func (ps *PluginCommonService) UpdatePluginStatus(ctx context.Context) (err erro if err != nil { return errors.InternalServer(reason.UnknownError).WithError(err) } - return ps.configRepo.SetConfig(constant.PluginStatus, string(content)) + return ps.configService.UpdateConfig(ctx, constant.PluginStatus, string(content)) } // UpdatePluginConfig update plugin config diff --git a/internal/service/provider.go b/internal/service/provider.go index 8273866c..69c30047 100644 --- a/internal/service/provider.go +++ b/internal/service/provider.go @@ -9,6 +9,7 @@ import ( collectioncommon "github.com/answerdev/answer/internal/service/collection_common" "github.com/answerdev/answer/internal/service/comment" "github.com/answerdev/answer/internal/service/comment_common" + "github.com/answerdev/answer/internal/service/config" "github.com/answerdev/answer/internal/service/dashboard" "github.com/answerdev/answer/internal/service/export" "github.com/answerdev/answer/internal/service/follow" @@ -84,4 +85,5 @@ var ProviderSetService = wire.NewSet( user_external_login.NewUserExternalLoginService, user_external_login.NewUserCenterLoginService, plugin_common.NewPluginCommonService, + config.NewConfigService, ) diff --git a/internal/service/question_common/question.go b/internal/service/question_common/question.go index 26eb2cc6..6ec1176f 100644 --- a/internal/service/question_common/question.go +++ b/internal/service/question_common/question.go @@ -6,6 +6,7 @@ import ( "time" "github.com/answerdev/answer/internal/base/constant" + "github.com/answerdev/answer/internal/base/handler" "github.com/answerdev/answer/internal/base/reason" "github.com/answerdev/answer/internal/service/activity_common" "github.com/answerdev/answer/internal/service/activity_queue" @@ -62,7 +63,7 @@ type QuestionCommon struct { collectionCommon *collectioncommon.CollectionCommon AnswerCommon *answercommon.AnswerCommon metaService *meta.MetaService - configRepo config.ConfigRepo + configService *config.ConfigService } func NewQuestionCommon(questionRepo QuestionRepo, @@ -74,7 +75,7 @@ func NewQuestionCommon(questionRepo QuestionRepo, collectionCommon *collectioncommon.CollectionCommon, answerCommon *answercommon.AnswerCommon, metaService *meta.MetaService, - configRepo config.ConfigRepo, + configService *config.ConfigService, ) *QuestionCommon { return &QuestionCommon{ questionRepo: questionRepo, @@ -86,7 +87,7 @@ func NewQuestionCommon(questionRepo QuestionRepo, collectionCommon: collectionCommon, AnswerCommon: answerCommon, metaService: metaService, - configRepo: configRepo, + configService: configService, } } @@ -201,14 +202,16 @@ func (qs *QuestionCommon) Info(ctx context.Context, questionID string, loginUser if err != nil { log.Error("json.Unmarshal CloseQuestionMeta error", err.Error()) } else { - closeinfo := &schema.GetReportTypeResp{} - err = qs.configRepo.GetJsonConfigByIDAndSetToObject(closemsg.CloseType, closeinfo) + cfg, err := qs.configService.GetConfigByID(ctx, closemsg.CloseType) if err != nil { log.Error("json.Unmarshal QuestionCloseJson error", err.Error()) } else { + reasonItem := &schema.ReasonItem{} + _ = json.Unmarshal(cfg.GetByteValue(), reasonItem) + reasonItem.Translate(cfg.Key, handler.GetLangByCtx(ctx)) operation := &schema.Operation{} - operation.Type = closeinfo.Name - operation.Description = closeinfo.Description + operation.Type = reasonItem.Name + operation.Description = reasonItem.Description operation.Msg = closemsg.CloseMsg operation.Time = metainfo.CreatedAt.Unix() operation.Level = schema.OperationLevelInfo @@ -259,7 +262,7 @@ func (qs *QuestionCommon) Info(ctx context.Context, questionID string, loginUser showinfo.VoteStatus = qs.voteRepo.GetVoteStatus(ctx, questionID, loginUserID) // // check is followed - isFollowed, _ := qs.followCommon.IsFollowed(loginUserID, questionID) + isFollowed, _ := qs.followCommon.IsFollowed(ctx, loginUserID, questionID) showinfo.IsFollowed = isFollowed has, err = qs.AnswerCommon.SearchAnswered(ctx, loginUserID, dbinfo.ID) diff --git a/internal/service/question_service.go b/internal/service/question_service.go index b456d473..a12026d9 100644 --- a/internal/service/question_service.go +++ b/internal/service/question_service.go @@ -304,11 +304,11 @@ func (qs *QuestionService) AddQuestion(ctx context.Context, req *schema.Question // user add question count userQuestionCount, err := qs.questioncommon.GetUserQuestionCount(ctx, question.UserID) if err != nil { - log.Error("user GetUserQuestionCount error", err.Error()) + log.Errorf("get user question count error %v", err) } else { err = qs.userCommon.UpdateQuestionCount(ctx, question.UserID, userQuestionCount) if err != nil { - log.Error("user IncreaseQuestionCount error", err.Error()) + log.Errorf("update user question count error %v", err) } } @@ -566,7 +566,10 @@ func (qs *QuestionService) UpdateQuestionInviteUser(ctx context.Context, req *sc for _, item := range req.InviteUser { _, ok := inviteUserInfoList[item] if ok { - inviteUserIDs = append(inviteUserIDs, inviteUserInfoList[item].ID) + //The inviter can't be himself. + if req.UserID != inviteUserInfoList[item].ID { + inviteUserIDs = append(inviteUserIDs, inviteUserInfoList[item].ID) + } } } inviteUserStr := "" diff --git a/internal/service/rank/rank_service.go b/internal/service/rank/rank_service.go index af60152b..307bc591 100644 --- a/internal/service/rank/rank_service.go +++ b/internal/service/rank/rank_service.go @@ -4,8 +4,10 @@ import ( "context" "github.com/answerdev/answer/internal/base/constant" + "github.com/answerdev/answer/internal/base/handler" "github.com/answerdev/answer/internal/base/pager" "github.com/answerdev/answer/internal/base/reason" + "github.com/answerdev/answer/internal/base/translator" "github.com/answerdev/answer/internal/entity" "github.com/answerdev/answer/internal/schema" "github.com/answerdev/answer/internal/service/activity_type" @@ -34,7 +36,7 @@ type UserRankRepo interface { // RankService rank service type RankService struct { userCommon *usercommon.UserCommon - configRepo config.ConfigRepo + configService *config.ConfigService userRankRepo UserRankRepo objectInfoService *object_info.ObjService roleService *role.UserRoleRelService @@ -48,10 +50,10 @@ func NewRankService( objectInfoService *object_info.ObjService, roleService *role.UserRoleRelService, rolePowerService *role.RolePowerRelService, - configRepo config.ConfigRepo) *RankService { + configService *config.ConfigService) *RankService { return &RankService{ userCommon: userCommon, - configRepo: configRepo, + configService: configService, userRankRepo: userRankRepo, objectInfoService: objectInfoService, roleService: roleService, @@ -221,7 +223,7 @@ func (rs *RankService) getUserPowerMapping(ctx context.Context, userID string) ( func (rs *RankService) checkUserRank(ctx context.Context, userID string, userRank int, action string) ( can bool, rank int) { // get the amount of rank required for the current operation - requireRank, err := rs.configRepo.GetInt(action) + requireRank, err := rs.configService.GetIntValue(ctx, action) if err != nil { log.Error(err) return false, requireRank @@ -234,8 +236,8 @@ func (rs *RankService) checkUserRank(ctx context.Context, userID string, userRan return true, requireRank } -// GetRankPersonalWithPage get personal comment list page -func (rs *RankService) GetRankPersonalWithPage(ctx context.Context, req *schema.GetRankPersonalWithPageReq) ( +// GetRankPersonalPage get personal comment list page +func (rs *RankService) GetRankPersonalPage(ctx context.Context, req *schema.GetRankPersonalWithPageReq) ( pageModel *pager.PageModel, err error) { if plugin.RankAgentEnabled() { return pager.NewPageModel(0, []string{}), nil @@ -258,32 +260,47 @@ func (rs *RankService) GetRankPersonalWithPage(ctx context.Context, req *schema. if err != nil { return nil, err } - resp := make([]*schema.GetRankPersonalWithPageResp, 0) + + resp := rs.decorateRankPersonalPageResp(ctx, userRankPage) + return pager.NewPageModel(total, resp), nil +} + +func (rs *RankService) decorateRankPersonalPageResp( + ctx context.Context, userRankPage []*entity.Activity) []*schema.GetRankPersonalPageResp { + resp := make([]*schema.GetRankPersonalPageResp, 0) + lang := handler.GetLangByCtx(ctx) + for _, userRankInfo := range userRankPage { if len(userRankInfo.ObjectID) == 0 || userRankInfo.ObjectID == "0" { continue } - commentResp := &schema.GetRankPersonalWithPageResp{ + objInfo, err := rs.objectInfoService.GetInfo(ctx, userRankInfo.ObjectID) + if err != nil { + log.Error(err) + continue + } + + commentResp := &schema.GetRankPersonalPageResp{ CreatedAt: userRankInfo.CreatedAt.Unix(), ObjectID: userRankInfo.ObjectID, Reputation: userRankInfo.Rank, } - objInfo, err := rs.objectInfoService.GetInfo(ctx, userRankInfo.ObjectID) + cfg, err := rs.configService.GetConfigByID(ctx, userRankInfo.ActivityType) if err != nil { log.Error(err) - } else { - commentResp.RankType = activity_type.Format(userRankInfo.ActivityType) - commentResp.ObjectType = objInfo.ObjectType - commentResp.Title = objInfo.Title - commentResp.UrlTitle = htmltext.UrlTitle(objInfo.Title) - commentResp.Content = objInfo.Content - if objInfo.QuestionStatus == entity.QuestionStatusDeleted { - commentResp.Title = "Deleted question" - } - commentResp.QuestionID = objInfo.QuestionID - commentResp.AnswerID = objInfo.AnswerID + continue } + commentResp.RankType = translator.Tr(lang, activity_type.ActivityTypeFlagMapping[cfg.Key]) + commentResp.ObjectType = objInfo.ObjectType + commentResp.Title = objInfo.Title + commentResp.UrlTitle = htmltext.UrlTitle(objInfo.Title) + commentResp.Content = objInfo.Content + if objInfo.QuestionStatus == entity.QuestionStatusDeleted { + commentResp.Title = translator.Tr(lang, constant.DeletedQuestionTitleTrKey) + } + commentResp.QuestionID = objInfo.QuestionID + commentResp.AnswerID = objInfo.AnswerID resp = append(resp, commentResp) } - return pager.NewPageModel(total, resp), nil + return resp } diff --git a/internal/service/report_admin/report_backyard.go b/internal/service/report_admin/report_backyard.go index cc0479c3..ee817fc7 100644 --- a/internal/service/report_admin/report_backyard.go +++ b/internal/service/report_admin/report_backyard.go @@ -2,17 +2,17 @@ package report_admin import ( "context" + "encoding/json" "github.com/answerdev/answer/internal/base/handler" - "github.com/answerdev/answer/internal/repo/config" - configrepo "github.com/answerdev/answer/internal/service/config" + "github.com/answerdev/answer/internal/service/config" + "github.com/answerdev/answer/internal/service/object_info" "github.com/answerdev/answer/pkg/htmltext" "github.com/segmentfault/pacman/log" "github.com/answerdev/answer/internal/base/pager" "github.com/answerdev/answer/internal/base/reason" "github.com/answerdev/answer/internal/entity" - "github.com/answerdev/answer/internal/repo/common" "github.com/answerdev/answer/internal/schema" answercommon "github.com/answerdev/answer/internal/service/answer_common" "github.com/answerdev/answer/internal/service/comment_common" @@ -28,33 +28,33 @@ import ( type ReportAdminService struct { reportRepo report_common.ReportRepo commonUser *usercommon.UserCommon - commonRepo *common.CommonRepo answerRepo answercommon.AnswerRepo questionRepo questioncommon.QuestionRepo commentCommonRepo comment_common.CommentCommonRepo reportHandle *report_handle_admin.ReportHandle - configRepo configrepo.ConfigRepo + configService *config.ConfigService + objectInfoService *object_info.ObjService } // NewReportAdminService new report service func NewReportAdminService( reportRepo report_common.ReportRepo, commonUser *usercommon.UserCommon, - commonRepo *common.CommonRepo, answerRepo answercommon.AnswerRepo, questionRepo questioncommon.QuestionRepo, commentCommonRepo comment_common.CommentCommonRepo, reportHandle *report_handle_admin.ReportHandle, - configRepo configrepo.ConfigRepo) *ReportAdminService { + configService *config.ConfigService, + objectInfoService *object_info.ObjService) *ReportAdminService { return &ReportAdminService{ reportRepo: reportRepo, commonUser: commonUser, - commonRepo: commonRepo, answerRepo: answerRepo, questionRepo: questionRepo, commentCommonRepo: commentCommonRepo, reportHandle: reportHandle, - configRepo: configRepo, + configService: configService, + objectInfoService: objectInfoService, } } @@ -98,9 +98,8 @@ func (rs *ReportAdminService) ListReportPage(ctx context.Context, dto schema.Get for _, r := range resp { r.ReportedUser = flaggedUsers[r.ReportedUserID] r.ReportUser = users[r.UserID] + rs.decorateReportResp(ctx, r) } - - rs.parseObject(ctx, &resp) return pager.NewPageModel(total, resp), nil } @@ -139,102 +138,38 @@ func (rs *ReportAdminService) HandleReported(ctx context.Context, req schema.Rep return } -func (rs *ReportAdminService) parseObject(ctx context.Context, resp *[]*schema.GetReportListPageResp) { +func (rs *ReportAdminService) decorateReportResp(ctx context.Context, resp *schema.GetReportListPageResp) { lang := handler.GetLangByCtx(ctx) - var ( - res = *resp - ) + objectInfo, err := rs.objectInfoService.GetInfo(ctx, resp.ObjectID) + if err != nil { + log.Error(err) + return + } - for i, r := range res { - var ( - objIds map[string]string - exists, - ok bool - err error - questionId, - answerId, - commentId string - question *entity.Question - answer *entity.Answer - cmt *entity.Comment - ) + resp.QuestionID = objectInfo.QuestionID + resp.AnswerID = objectInfo.AnswerID + resp.CommentID = objectInfo.CommentID + resp.Title = objectInfo.Title + resp.Excerpt = htmltext.FetchExcerpt(objectInfo.Content, "...", 240) - objIds, err = rs.commonRepo.GetObjectIDMap(r.ObjectID) + if resp.ReportType > 0 { + resp.Reason = &schema.ReasonItem{ReasonType: resp.ReportType} + cf, err := rs.configService.GetConfigByID(ctx, resp.ReportType) if err != nil { log.Error(err) - continue + } else { + _ = json.Unmarshal([]byte(cf.Value), resp.Reason) + resp.Reason.Translate(cf.Key, lang) } - - questionId, ok = objIds["question"] - if !ok { - continue + } + if resp.FlaggedType > 0 { + resp.FlaggedReason = &schema.ReasonItem{ReasonType: resp.FlaggedType} + cf, err := rs.configService.GetConfigByID(ctx, resp.FlaggedType) + if err != nil { + log.Error(err) + } else { + _ = json.Unmarshal([]byte(cf.Value), resp.Reason) + resp.Reason.Translate(cf.Key, lang) } - - question, exists, err = rs.questionRepo.GetQuestion(ctx, questionId) - if err != nil || !exists { - continue - } - - answerId, ok = objIds["answer"] - if ok { - answer, _, err = rs.answerRepo.GetAnswer(ctx, answerId) - if err != nil { - log.Error(err) - continue - } - } - - commentId, ok = objIds["comment"] - if ok { - cmt, _, err = rs.commentCommonRepo.GetComment(ctx, commentId) - if err != nil { - log.Error(err) - continue - } - } - - switch r.OType { - case "question": - r.QuestionID = questionId - r.Title = question.Title - r.Excerpt = htmltext.FetchExcerpt(question.ParsedText, "...", 240) - - case "answer": - r.QuestionID = questionId - r.AnswerID = answerId - r.Title = question.Title - r.Excerpt = htmltext.FetchExcerpt(answer.ParsedText, "...", 240) - - case "comment": - r.QuestionID = questionId - r.AnswerID = answerId - r.CommentID = commentId - r.Title = question.Title - r.Excerpt = htmltext.FetchExcerpt(cmt.ParsedText, "...", 240) - } - - // parse reason - if r.ReportType > 0 { - r.Reason = &schema.ReasonItem{ - ReasonType: r.ReportType, - } - err = rs.configRepo.GetJsonConfigByIDAndSetToObject(r.ReportType, r.Reason) - if err != nil { - log.Error(err) - } - r.Reason.Translate(config.ID2KeyMapping[r.ReportType], lang) - } - if r.FlaggedType > 0 { - r.FlaggedReason = &schema.ReasonItem{ - ReasonType: r.FlaggedType, - } - err = rs.configRepo.GetJsonConfigByIDAndSetToObject(r.FlaggedType, r.FlaggedReason) - if err != nil { - log.Error(err) - } - r.Reason.Translate(config.ID2KeyMapping[r.ReportType], lang) - } - - res[i] = r } } diff --git a/internal/service/report_handle_admin/report_handle.go b/internal/service/report_handle_admin/report_handle.go index a7a57272..65601aaa 100644 --- a/internal/service/report_handle_admin/report_handle.go +++ b/internal/service/report_handle_admin/report_handle.go @@ -17,28 +17,34 @@ import ( type ReportHandle struct { questionCommon *questioncommon.QuestionCommon commentRepo comment.CommentRepo - configRepo config.ConfigRepo + configService *config.ConfigService } func NewReportHandle( questionCommon *questioncommon.QuestionCommon, commentRepo comment.CommentRepo, - configRepo config.ConfigRepo) *ReportHandle { + configService *config.ConfigService) *ReportHandle { return &ReportHandle{ questionCommon: questionCommon, commentRepo: commentRepo, - configRepo: configRepo, + configService: configService, } } // HandleObject this handle object status func (rh *ReportHandle) HandleObject(ctx context.Context, reported *entity.Report, req schema.ReportHandleReq) (err error) { + reasonDeleteCfg, err := rh.configService.GetConfigByKey(ctx, "reason.needs_delete") + if err != nil { + return err + } + reasonCloseCfg, err := rh.configService.GetConfigByKey(ctx, "reason.needs_close") + if err != nil { + return err + } var ( - objectID = reported.ObjectID - reportedUserID = reported.ReportedUserID - objectKey string - reasonDelete, _ = rh.configRepo.GetConfigType("reason.needs_delete") - reasonClose, _ = rh.configRepo.GetConfigType("reason.needs_close") + objectID = reported.ObjectID + reportedUserID = reported.ReportedUserID + objectKey string ) objectKey, err = obj.GetObjectTypeStrByObjectID(objectID) @@ -48,9 +54,9 @@ func (rh *ReportHandle) HandleObject(ctx context.Context, reported *entity.Repor switch objectKey { case "question": switch req.FlaggedType { - case reasonDelete: + case reasonDeleteCfg.ID: err = rh.questionCommon.RemoveQuestion(ctx, &schema.RemoveQuestionReq{ID: objectID}) - case reasonClose: + case reasonCloseCfg.ID: err = rh.questionCommon.CloseQuestion(ctx, &schema.CloseQuestionReq{ ID: objectID, CloseType: req.FlaggedType, @@ -59,12 +65,12 @@ func (rh *ReportHandle) HandleObject(ctx context.Context, reported *entity.Repor } case "answer": switch req.FlaggedType { - case reasonDelete: + case reasonDeleteCfg.ID: err = rh.questionCommon.RemoveAnswer(ctx, objectID) } case "comment": switch req.FlaggedType { - case reasonDelete: + case reasonCloseCfg.ID: err = rh.commentRepo.RemoveComment(ctx, objectID) rh.sendNotification(ctx, reportedUserID, objectID, constant.NotificationYourCommentWasDeleted) } diff --git a/internal/service/siteinfo/siteinfo_service.go b/internal/service/siteinfo/siteinfo_service.go index 6edefd55..adb2ba34 100644 --- a/internal/service/siteinfo/siteinfo_service.go +++ b/internal/service/siteinfo/siteinfo_service.go @@ -16,6 +16,7 @@ import ( "github.com/answerdev/answer/internal/service/siteinfo_common" tagcommon "github.com/answerdev/answer/internal/service/tag_common" "github.com/answerdev/answer/pkg/uid" + "github.com/answerdev/answer/plugin" "github.com/jinzhu/copier" "github.com/segmentfault/pacman/errors" "github.com/segmentfault/pacman/log" @@ -26,7 +27,7 @@ type SiteInfoService struct { siteInfoCommonService *siteinfo_common.SiteInfoCommonService emailService *export.EmailService tagCommonService *tagcommon.TagCommonService - configRepo config.ConfigRepo + configService *config.ConfigService } func NewSiteInfoService( @@ -34,24 +35,23 @@ func NewSiteInfoService( siteInfoCommonService *siteinfo_common.SiteInfoCommonService, emailService *export.EmailService, tagCommonService *tagcommon.TagCommonService, - configRepo config.ConfigRepo, + configService *config.ConfigService, ) *SiteInfoService { - usersSiteInfo, _ := siteInfoCommonService.GetSiteUsers(context.Background()) - if usersSiteInfo != nil { - constant.DefaultAvatar = usersSiteInfo.DefaultAvatar - constant.DefaultGravatarBaseURL = usersSiteInfo.GravatarBaseURL - } - generalSiteInfo, _ := siteInfoCommonService.GetSiteGeneral(context.Background()) - if generalSiteInfo != nil { - constant.DefaultSiteURL = generalSiteInfo.SiteUrl - } + plugin.RegisterGetSiteURLFunc(func() string { + generalSiteInfo, err := siteInfoCommonService.GetSiteGeneral(context.Background()) + if err != nil { + log.Error(err) + return "" + } + return generalSiteInfo.SiteUrl + }) return &SiteInfoService{ siteInfoRepo: siteInfoRepo, siteInfoCommonService: siteInfoCommonService, emailService: emailService, tagCommonService: tagCommonService, - configRepo: configRepo, + configService: configService, } } @@ -227,19 +227,14 @@ func (s *SiteInfoService) SaveSiteUsers(ctx context.Context, req *schema.SiteUse Content: string(content), Status: 1, } - err = s.siteInfoRepo.SaveByType(ctx, constant.SiteTypeUsers, data) - if err == nil { - constant.DefaultAvatar = req.DefaultAvatar - constant.DefaultGravatarBaseURL = req.GravatarBaseURL - } - return err + return s.siteInfoRepo.SaveByType(ctx, constant.SiteTypeUsers, data) } // GetSMTPConfig get smtp config func (s *SiteInfoService) GetSMTPConfig(ctx context.Context) ( resp *schema.GetSMTPConfigResp, err error, ) { - emailConfig, err := s.emailService.GetEmailConfig() + emailConfig, err := s.emailService.GetEmailConfig(ctx) if err != nil { return nil, err } @@ -250,13 +245,13 @@ func (s *SiteInfoService) GetSMTPConfig(ctx context.Context) ( // UpdateSMTPConfig get smtp config func (s *SiteInfoService) UpdateSMTPConfig(ctx context.Context, req *schema.UpdateSMTPConfigReq) (err error) { - oldEmailConfig, err := s.emailService.GetEmailConfig() + oldEmailConfig, err := s.emailService.GetEmailConfig(ctx) if err != nil { return err } _ = copier.Copy(oldEmailConfig, req) - err = s.emailService.SetEmailConfig(oldEmailConfig) + err = s.emailService.SetEmailConfig(ctx, oldEmailConfig) if err != nil { return err } @@ -372,7 +367,7 @@ func (s *SiteInfoService) UpdatePrivilegesConfig(ctx context.Context, req *schem // update privilege in config for _, privilege := range chooseOption.Privileges { - err = s.configRepo.SetConfig(privilege.Key, fmt.Sprintf("%d", privilege.Value)) + err = s.configService.UpdateConfig(ctx, privilege.Key, fmt.Sprintf("%d", privilege.Value)) if err != nil { return err } diff --git a/internal/service/siteinfo_common/siteinfo_service.go b/internal/service/siteinfo_common/siteinfo_service.go index 7e2934a3..fff82a8d 100644 --- a/internal/service/siteinfo_common/siteinfo_service.go +++ b/internal/service/siteinfo_common/siteinfo_service.go @@ -7,6 +7,7 @@ import ( "github.com/answerdev/answer/internal/base/constant" "github.com/answerdev/answer/internal/entity" "github.com/answerdev/answer/internal/schema" + "github.com/answerdev/answer/pkg/gravatar" "github.com/answerdev/answer/pkg/uid" "github.com/segmentfault/pacman/log" ) @@ -76,6 +77,49 @@ func (s *SiteInfoCommonService) GetSiteUsers(ctx context.Context) (resp *schema. return resp, nil } +// FormatAvatar format avatar +func (s *SiteInfoCommonService) FormatAvatar(ctx context.Context, originalAvatarData, email string) *schema.AvatarInfo { + gravatarBaseURL, defaultAvatar := s.getAvatarDefaultConfig(ctx) + return s.selectedAvatar(originalAvatarData, defaultAvatar, gravatarBaseURL, email) +} + +// FormatListAvatar format avatar +func (s *SiteInfoCommonService) FormatListAvatar(ctx context.Context, userList []*entity.User) ( + avatarMapping map[string]*schema.AvatarInfo) { + gravatarBaseURL, defaultAvatar := s.getAvatarDefaultConfig(ctx) + avatarMapping = make(map[string]*schema.AvatarInfo) + for _, user := range userList { + avatarMapping[user.ID] = s.selectedAvatar(user.Avatar, defaultAvatar, gravatarBaseURL, user.EMail) + } + return avatarMapping +} + +func (s *SiteInfoCommonService) getAvatarDefaultConfig(ctx context.Context) (string, string) { + gravatarBaseURL, defaultAvatar := constant.DefaultGravatarBaseURL, constant.DefaultAvatar + usersConfig, err := s.GetSiteUsers(ctx) + if err != nil { + log.Error(err) + } else { + gravatarBaseURL = usersConfig.GravatarBaseURL + defaultAvatar = usersConfig.DefaultAvatar + } + return gravatarBaseURL, defaultAvatar +} + +func (s *SiteInfoCommonService) selectedAvatar( + originalAvatarData string, defaultAvatar string, gravatarBaseURL string, email string) *schema.AvatarInfo { + avatarInfo := &schema.AvatarInfo{} + _ = json.Unmarshal([]byte(originalAvatarData), avatarInfo) + + if len(avatarInfo.Type) == 0 && defaultAvatar == constant.AvatarTypeGravatar { + avatarInfo.Type = constant.AvatarTypeGravatar + avatarInfo.Gravatar = gravatar.GetAvatarURL(gravatarBaseURL, email) + } else if avatarInfo.Type == constant.AvatarTypeGravatar { + avatarInfo.Gravatar = gravatar.GetAvatarURL(gravatarBaseURL, email) + } + return avatarInfo +} + // GetSiteWrite get site info write func (s *SiteInfoCommonService) GetSiteWrite(ctx context.Context) (resp *schema.SiteWriteResp, err error) { resp = &schema.SiteWriteResp{} diff --git a/internal/service/tag/tag_service.go b/internal/service/tag/tag_service.go index e27cbc7d..23dc25de 100644 --- a/internal/service/tag/tag_service.go +++ b/internal/service/tag/tag_service.go @@ -380,7 +380,7 @@ func (ts *TagService) checkTagIsFollow(ctx context.Context, userID, tagID string if len(userID) == 0 { return false } - followed, err := ts.followCommon.IsFollowed(userID, tagID) + followed, err := ts.followCommon.IsFollowed(ctx, userID, tagID) if err != nil { log.Error(err) } diff --git a/internal/service/user_admin/user_backyard.go b/internal/service/user_admin/user_backyard.go index a98086ae..86270e08 100644 --- a/internal/service/user_admin/user_backyard.go +++ b/internal/service/user_admin/user_backyard.go @@ -15,6 +15,7 @@ import ( "github.com/answerdev/answer/internal/service/activity" "github.com/answerdev/answer/internal/service/auth" "github.com/answerdev/answer/internal/service/role" + "github.com/answerdev/answer/internal/service/siteinfo_common" usercommon "github.com/answerdev/answer/internal/service/user_common" "github.com/jinzhu/copier" "github.com/segmentfault/pacman/errors" @@ -35,11 +36,12 @@ type UserAdminRepo interface { // UserAdminService user service type UserAdminService struct { - userRepo UserAdminRepo - userRoleRelService *role.UserRoleRelService - authService *auth.AuthService - userCommonService *usercommon.UserCommon - userActivity activity.UserActiveActivityRepo + userRepo UserAdminRepo + userRoleRelService *role.UserRoleRelService + authService *auth.AuthService + userCommonService *usercommon.UserCommon + userActivity activity.UserActiveActivityRepo + siteInfoCommonService *siteinfo_common.SiteInfoCommonService } // NewUserAdminService new user admin service @@ -49,13 +51,15 @@ func NewUserAdminService( authService *auth.AuthService, userCommonService *usercommon.UserCommon, userActivity activity.UserActiveActivityRepo, + siteInfoCommonService *siteinfo_common.SiteInfoCommonService, ) *UserAdminService { return &UserAdminService{ - userRepo: userRepo, - userRoleRelService: userRoleRelService, - authService: authService, - userCommonService: userCommonService, - userActivity: userActivity, + userRepo: userRepo, + userRoleRelService: userRoleRelService, + authService: authService, + userCommonService: userCommonService, + userActivity: userActivity, + siteInfoCommonService: siteInfoCommonService, } } @@ -238,10 +242,10 @@ func (us *UserAdminService) GetUserPage(ctx context.Context, req *schema.GetUser if err != nil { return } + avatarMapping := us.siteInfoCommonService.FormatListAvatar(ctx, users) resp := make([]*schema.GetUserPageResp, 0) for _, u := range users { - avatar := schema.FormatAvatarInfo(u.Avatar, u.EMail) t := &schema.GetUserPageResp{ UserID: u.ID, CreatedAt: u.CreatedAt.Unix(), @@ -249,7 +253,7 @@ func (us *UserAdminService) GetUserPage(ctx context.Context, req *schema.GetUser EMail: u.EMail, Rank: u.Rank, DisplayName: u.DisplayName, - Avatar: avatar, + Avatar: avatarMapping[u.ID].GetURL(), } if u.Status == entity.UserStatusDeleted { t.Status = schema.UserDeleted diff --git a/internal/service/user_common/user.go b/internal/service/user_common/user.go index b6331e70..9a451265 100644 --- a/internal/service/user_common/user.go +++ b/internal/service/user_common/user.go @@ -10,6 +10,7 @@ import ( "github.com/answerdev/answer/internal/schema" "github.com/answerdev/answer/internal/service/auth" "github.com/answerdev/answer/internal/service/role" + "github.com/answerdev/answer/internal/service/siteinfo_common" "github.com/answerdev/answer/pkg/checker" "github.com/answerdev/answer/pkg/random" "github.com/segmentfault/pacman/errors" @@ -40,20 +41,23 @@ type UserRepo interface { // UserCommon user service type UserCommon struct { - userRepo UserRepo - userRoleService *role.UserRoleRelService - authService *auth.AuthService + userRepo UserRepo + userRoleService *role.UserRoleRelService + authService *auth.AuthService + siteInfoCommonService *siteinfo_common.SiteInfoCommonService } func NewUserCommon( userRepo UserRepo, userRoleService *role.UserRoleRelService, authService *auth.AuthService, + siteInfoCommonService *siteinfo_common.SiteInfoCommonService, ) *UserCommon { return &UserCommon{ - userRepo: userRepo, - userRoleService: userRoleService, - authService: authService, + userRepo: userRepo, + userRoleService: userRoleService, + authService: authService, + siteInfoCommonService: siteInfoCommonService, } } @@ -64,6 +68,7 @@ func (us *UserCommon) GetUserBasicInfoByID(ctx context.Context, ID string) ( return nil, exist, err } info := us.FormatUserBasicInfo(ctx, userInfo) + info.Avatar = us.siteInfoCommonService.FormatAvatar(ctx, userInfo.Avatar, userInfo.EMail).GetURL() return info, exist, nil } @@ -73,6 +78,7 @@ func (us *UserCommon) GetUserBasicInfoByUserName(ctx context.Context, username s return nil, exist, err } info := us.FormatUserBasicInfo(ctx, userInfo) + info.Avatar = us.siteInfoCommonService.FormatAvatar(ctx, userInfo.Avatar, userInfo.EMail).GetURL() return info, exist, nil } @@ -82,8 +88,10 @@ func (us *UserCommon) BatchGetUserBasicInfoByUserNames(ctx context.Context, user if err != nil { return infomap, err } + avatarMapping := us.siteInfoCommonService.FormatListAvatar(ctx, list) for _, user := range list { info := us.FormatUserBasicInfo(ctx, user) + info.Avatar = avatarMapping[user.ID].GetURL() infomap[user.Username] = info } return infomap, nil @@ -99,13 +107,15 @@ func (us *UserCommon) UpdateQuestionCount(ctx context.Context, userID string, nu func (us *UserCommon) BatchUserBasicInfoByID(ctx context.Context, IDs []string) (map[string]*schema.UserBasicInfo, error) { userMap := make(map[string]*schema.UserBasicInfo) - dbInfo, err := us.userRepo.BatchGetByID(ctx, IDs) + userList, err := us.userRepo.BatchGetByID(ctx, IDs) if err != nil { return userMap, err } - for _, item := range dbInfo { - info := us.FormatUserBasicInfo(ctx, item) - userMap[item.ID] = info + avatarMapping := us.siteInfoCommonService.FormatListAvatar(ctx, userList) + for _, user := range userList { + info := us.FormatUserBasicInfo(ctx, user) + info.Avatar = avatarMapping[user.ID].GetURL() + userMap[user.ID] = info } return userMap, nil } @@ -117,7 +127,6 @@ func (us *UserCommon) FormatUserBasicInfo(ctx context.Context, userInfo *entity. userBasicInfo.Username = userInfo.Username userBasicInfo.Rank = userInfo.Rank userBasicInfo.DisplayName = userInfo.DisplayName - userBasicInfo.Avatar = schema.FormatAvatarInfo(userInfo.Avatar, userInfo.EMail) userBasicInfo.Website = userInfo.Website userBasicInfo.Location = userInfo.Location userBasicInfo.IPInfo = userInfo.IPInfo diff --git a/internal/service/user_external_login/user_center_login_service.go b/internal/service/user_external_login/user_center_login_service.go index 14200298..9e870381 100644 --- a/internal/service/user_external_login/user_center_login_service.go +++ b/internal/service/user_external_login/user_center_login_service.go @@ -5,6 +5,7 @@ import ( "encoding/json" "time" + "github.com/answerdev/answer/internal/base/constant" "github.com/answerdev/answer/internal/base/handler" "github.com/answerdev/answer/internal/base/reason" "github.com/answerdev/answer/internal/base/translator" @@ -49,6 +50,12 @@ func NewUserCenterLoginService( func (us *UserCenterLoginService) ExternalLogin( ctx context.Context, userCenter plugin.UserCenter, basicUserInfo *plugin.UserCenterBasicUserInfo) ( resp *schema.UserExternalLoginResp, err error) { + if len(basicUserInfo.ExternalID) == 0 { + return &schema.UserExternalLoginResp{ + ErrTitle: translator.Tr(handler.GetLangByCtx(ctx), reason.UserAccessDenied), + ErrMsg: translator.Tr(handler.GetLangByCtx(ctx), reason.UserExternalLoginMissingUserID), + }, nil + } if len(basicUserInfo.Email) > 0 { // check whether site allow register or not @@ -124,7 +131,7 @@ func (us *UserCenterLoginService) registerNewUser(ctx context.Context, provider if len(basicUserInfo.Avatar) > 0 { avatarInfo := &schema.AvatarInfo{ - Type: schema.AvatarTypeCustom, + Type: constant.AvatarTypeCustom, Custom: basicUserInfo.Avatar, } avatar, _ := json.Marshal(avatarInfo) diff --git a/internal/service/user_external_login/user_external_login_service.go b/internal/service/user_external_login/user_external_login_service.go index 912d9135..4b10aef4 100644 --- a/internal/service/user_external_login/user_external_login_service.go +++ b/internal/service/user_external_login/user_external_login_service.go @@ -6,13 +6,17 @@ import ( "fmt" "time" + "github.com/answerdev/answer/internal/base/constant" + "github.com/answerdev/answer/internal/base/handler" "github.com/answerdev/answer/internal/base/reason" + "github.com/answerdev/answer/internal/base/translator" "github.com/answerdev/answer/internal/entity" "github.com/answerdev/answer/internal/schema" "github.com/answerdev/answer/internal/service/activity" "github.com/answerdev/answer/internal/service/export" "github.com/answerdev/answer/internal/service/siteinfo_common" usercommon "github.com/answerdev/answer/internal/service/user_common" + "github.com/answerdev/answer/pkg/checker" "github.com/answerdev/answer/pkg/random" "github.com/answerdev/answer/pkg/token" "github.com/answerdev/answer/plugin" @@ -64,6 +68,13 @@ func NewUserExternalLoginService( func (us *UserExternalLoginService) ExternalLogin( ctx context.Context, externalUserInfo *schema.ExternalLoginUserInfoCache) ( resp *schema.UserExternalLoginResp, err error) { + if len(externalUserInfo.ExternalID) == 0 { + return &schema.UserExternalLoginResp{ + ErrTitle: translator.Tr(handler.GetLangByCtx(ctx), reason.UserAccessDenied), + ErrMsg: translator.Tr(handler.GetLangByCtx(ctx), reason.UserExternalLoginMissingUserID), + }, nil + } + oldExternalLoginUserInfo, exist, err := us.userExternalLoginRepo.GetByExternalID(ctx, externalUserInfo.Provider, externalUserInfo.ExternalID) if err != nil { @@ -99,6 +110,19 @@ func (us *UserExternalLoginService) ExternalLogin( return &schema.UserExternalLoginResp{BindingKey: bindingKey}, nil } + // check whether site allow register or not + siteInfo, err := us.siteInfoCommonService.GetSiteLogin(ctx) + if err != nil { + return nil, err + } + if !checker.EmailInAllowEmailDomain(externalUserInfo.Email, siteInfo.AllowEmailDomains) { + log.Debugf("email domain not allowed: %s", externalUserInfo.Email) + return &schema.UserExternalLoginResp{ + ErrTitle: translator.Tr(handler.GetLangByCtx(ctx), reason.UserAccessDenied), + ErrMsg: translator.Tr(handler.GetLangByCtx(ctx), reason.EmailIllegalDomainError), + }, nil + } + oldUserInfo, exist, err := us.userRepo.GetByEmail(ctx, externalUserInfo.Email) if err != nil { return nil, err @@ -141,7 +165,7 @@ func (us *UserExternalLoginService) registerNewUser(ctx context.Context, if len(externalUserInfo.Avatar) > 0 { avatarInfo := &schema.AvatarInfo{ - Type: schema.AvatarTypeCustom, + Type: constant.AvatarTypeCustom, Custom: externalUserInfo.Avatar, } avatar, _ := json.Marshal(avatarInfo) @@ -199,9 +223,9 @@ func (us *UserExternalLoginService) activeUser(ctx context.Context, oldUserInfo } // try to update user avatar - if len(externalUserInfo.Avatar) > 0 && len(schema.FormatAvatarInfo(oldUserInfo.Avatar, oldUserInfo.EMail)) == 0 { + if len(externalUserInfo.Avatar) > 0 { avatarInfo := &schema.AvatarInfo{ - Type: schema.AvatarTypeCustom, + Type: constant.AvatarTypeCustom, Custom: externalUserInfo.Avatar, } avatar, _ := json.Marshal(avatarInfo) diff --git a/internal/service/user_service.go b/internal/service/user_service.go index c6ca63c2..2fa336ef 100644 --- a/internal/service/user_service.go +++ b/internal/service/user_service.go @@ -17,7 +17,6 @@ import ( "github.com/answerdev/answer/internal/service/auth" "github.com/answerdev/answer/internal/service/export" "github.com/answerdev/answer/internal/service/role" - "github.com/answerdev/answer/internal/service/service_config" "github.com/answerdev/answer/internal/service/siteinfo_common" usercommon "github.com/answerdev/answer/internal/service/user_common" "github.com/answerdev/answer/internal/service/user_external_login" @@ -37,7 +36,6 @@ type UserService struct { userRepo usercommon.UserRepo userActivity activity.UserActiveActivityRepo activityRepo activity_common.ActivityRepo - serviceConfig *service_config.ServiceConfig emailService *export.EmailService authService *auth.AuthService siteInfoService *siteinfo_common.SiteInfoCommonService @@ -50,7 +48,6 @@ func NewUserService(userRepo usercommon.UserRepo, activityRepo activity_common.ActivityRepo, emailService *export.EmailService, authService *auth.AuthService, - serviceConfig *service_config.ServiceConfig, siteInfoService *siteinfo_common.SiteInfoCommonService, userRoleService *role.UserRoleRelService, userCommonService *usercommon.UserCommon, @@ -62,7 +59,6 @@ func NewUserService(userRepo usercommon.UserRepo, userActivity: userActivity, activityRepo: activityRepo, emailService: emailService, - serviceConfig: serviceConfig, authService: authService, siteInfoService: siteInfoService, userRoleService: userRoleService, @@ -72,7 +68,7 @@ func NewUserService(userRepo usercommon.UserRepo, // GetUserInfoByUserID get user info by user id func (us *UserService) GetUserInfoByUserID(ctx context.Context, token, userID string) ( - resp *schema.GetUserToSetShowResp, err error) { + resp *schema.GetCurrentLoginUserInfoResp, err error) { userInfo, exist, err := us.userRepo.GetByUserID(ctx, userID) if err != nil { return nil, err @@ -83,14 +79,15 @@ func (us *UserService) GetUserInfoByUserID(ctx context.Context, token, userID st if userInfo.Status == entity.UserStatusDeleted { return nil, errors.Unauthorized(reason.UnauthorizedError) } - roleID, err := us.userRoleService.GetUserRole(ctx, userInfo.ID) + + resp = &schema.GetCurrentLoginUserInfoResp{} + resp.ConvertFromUserEntity(userInfo) + resp.RoleID, err = us.userRoleService.GetUserRole(ctx, userInfo.ID) if err != nil { log.Error(err) } - resp = &schema.GetUserToSetShowResp{} - resp.GetFromUserEntity(userInfo) + resp.Avatar = us.siteInfoService.FormatAvatar(ctx, userInfo.Avatar, userInfo.EMail) resp.AccessToken = token - resp.RoleID = roleID resp.HavePassword = len(userInfo.Pass) > 0 return resp, nil } @@ -106,12 +103,13 @@ func (us *UserService) GetOtherUserInfoByUsername(ctx context.Context, username return nil, errors.NotFound(reason.UserNotFound) } resp = &schema.GetOtherUserInfoByUsernameResp{} - resp.GetFromUserEntity(userInfo) + resp.ConvertFromUserEntity(userInfo) + resp.Avatar = us.siteInfoService.FormatAvatar(ctx, userInfo.Avatar, userInfo.EMail).GetURL() return resp, nil } // EmailLogin email login -func (us *UserService) EmailLogin(ctx context.Context, req *schema.UserEmailLogin) (resp *schema.GetUserResp, err error) { +func (us *UserService) EmailLogin(ctx context.Context, req *schema.UserEmailLogin) (resp *schema.UserLoginResp, err error) { userInfo, exist, err := us.userRepo.GetByEmail(ctx, req.Email) if err != nil { return nil, err @@ -140,8 +138,9 @@ func (us *UserService) EmailLogin(ctx context.Context, req *schema.UserEmailLogi log.Error(err) } - resp = &schema.GetUserResp{} - resp.GetFromUserEntity(userInfo) + resp = &schema.UserLoginResp{} + resp.ConvertFromUserEntity(userInfo) + resp.Avatar = us.siteInfoService.FormatAvatar(ctx, userInfo.Avatar, userInfo.EMail).GetURL() userCacheInfo := &entity.UserCacheInfo{ UserID: userInfo.ID, EmailStatus: userInfo.MailStatus, @@ -368,7 +367,7 @@ func (us *UserService) UserUpdateInterface(ctx context.Context, req *schema.Upda // UserRegisterByEmail user register func (us *UserService) UserRegisterByEmail(ctx context.Context, registerUserInfo *schema.UserRegisterReq) ( - resp *schema.GetUserResp, errFields []*validator.FormErrorField, err error, + resp *schema.UserLoginResp, errFields []*validator.FormErrorField, err error, ) { _, has, err := us.userRepo.GetByEmail(ctx, registerUserInfo.Email) if err != nil { @@ -425,8 +424,9 @@ func (us *UserService) UserRegisterByEmail(ctx context.Context, registerUserInfo } // return user info and token - resp = &schema.GetUserResp{} - resp.GetFromUserEntity(userInfo) + resp = &schema.UserLoginResp{} + resp.ConvertFromUserEntity(userInfo) + resp.Avatar = us.siteInfoService.FormatAvatar(ctx, userInfo.Avatar, userInfo.EMail).GetURL() userCacheInfo := &entity.UserCacheInfo{ UserID: userInfo.ID, EmailStatus: userInfo.MailStatus, @@ -489,7 +489,7 @@ func (us *UserService) UserNoticeSet(ctx context.Context, userID string, noticeS return &schema.UserNoticeSetResp{NoticeSwitch: noticeSwitch}, err } -func (us *UserService) UserVerifyEmail(ctx context.Context, req *schema.UserVerifyEmailReq) (resp *schema.GetUserResp, err error) { +func (us *UserService) UserVerifyEmail(ctx context.Context, req *schema.UserVerifyEmailReq) (resp *schema.UserLoginResp, err error) { data := &schema.EmailCodeContent{} err = data.FromJSONString(req.Content) if err != nil { @@ -528,8 +528,9 @@ func (us *UserService) UserVerifyEmail(ctx context.Context, req *schema.UserVeri return nil, err } - resp = &schema.GetUserResp{} - resp.GetFromUserEntity(userInfo) + resp = &schema.UserLoginResp{} + resp.ConvertFromUserEntity(userInfo) + resp.Avatar = us.siteInfoService.FormatAvatar(ctx, userInfo.Avatar, userInfo.EMail).GetURL() resp.AccessToken = accessToken // User verified email will update user email status. So user status cache should be updated. if err = us.authService.SetUserStatus(ctx, userCacheInfo); err != nil { @@ -610,7 +611,7 @@ func (us *UserService) UserChangeEmailSendCode(ctx context.Context, req *schema. } // UserChangeEmailVerify user change email verify code -func (us *UserService) UserChangeEmailVerify(ctx context.Context, content string) (resp *schema.GetUserResp, err error) { +func (us *UserService) UserChangeEmailVerify(ctx context.Context, content string) (resp *schema.UserLoginResp, err error) { data := &schema.EmailCodeContent{} err = data.FromJSONString(content) if err != nil { @@ -646,8 +647,9 @@ func (us *UserService) UserChangeEmailVerify(ctx context.Context, content string log.Error(err) } - resp = &schema.GetUserResp{} - resp.GetFromUserEntity(userInfo) + resp = &schema.UserLoginResp{} + resp.ConvertFromUserEntity(userInfo) + resp.Avatar = us.siteInfoService.FormatAvatar(ctx, userInfo.Avatar, userInfo.EMail).GetURL() userCacheInfo := &entity.UserCacheInfo{ UserID: userInfo.ID, EmailStatus: entity.EmailStatusAvailable, @@ -807,8 +809,9 @@ func (us *UserService) getUserInfoMapping(ctx context.Context, userIDs []string) if err != nil { return nil, err } + avatarMapping := us.siteInfoService.FormatListAvatar(ctx, userInfoList) for _, user := range userInfoList { - user.Avatar = schema.FormatAvatarInfo(user.Avatar, user.EMail) + user.Avatar = avatarMapping[user.ID].GetURL() userInfoMapping[user.ID] = user } return userInfoMapping, nil @@ -820,8 +823,10 @@ func (us *UserService) SearchUserListByName(ctx context.Context, name string) ([ if err != nil { return userinfolist, err } + avatarMapping := us.siteInfoService.FormatListAvatar(ctx, list) for _, user := range list { userinfo := us.userCommonService.FormatUserBasicInfo(ctx, user) + userinfo.Avatar = avatarMapping[user.ID].GetURL() userinfolist = append(userinfolist, userinfo) } return userinfolist, nil diff --git a/internal/service/vote_service.go b/internal/service/vote_service.go index 41ea00e5..022f9dca 100644 --- a/internal/service/vote_service.go +++ b/internal/service/vote_service.go @@ -3,7 +3,10 @@ package service import ( "context" + "github.com/answerdev/answer/internal/base/constant" + "github.com/answerdev/answer/internal/base/handler" "github.com/answerdev/answer/internal/base/pager" + "github.com/answerdev/answer/internal/base/translator" "github.com/answerdev/answer/internal/entity" "github.com/answerdev/answer/internal/service/activity_type" "github.com/answerdev/answer/internal/service/comment_common" @@ -35,7 +38,7 @@ type VoteRepo interface { type VoteService struct { voteRepo VoteRepo UniqueIDRepo unique.UniqueIDRepo - configRepo config.ConfigRepo + configService *config.ConfigService questionRepo questioncommon.QuestionRepo answerRepo answercommon.AnswerRepo commentCommonRepo comment_common.CommentCommonRepo @@ -45,7 +48,7 @@ type VoteService struct { func NewVoteService( VoteRepo VoteRepo, uniqueIDRepo unique.UniqueIDRepo, - configRepo config.ConfigRepo, + configService *config.ConfigService, questionRepo questioncommon.QuestionRepo, answerRepo answercommon.AnswerRepo, commentCommonRepo comment_common.CommentCommonRepo, @@ -54,7 +57,7 @@ func NewVoteService( return &VoteService{ voteRepo: VoteRepo, UniqueIDRepo: uniqueIDRepo, - configRepo: configRepo, + configService: configService, questionRepo: questionRepo, answerRepo: answerRepo, commentCommonRepo: commentCommonRepo, @@ -151,24 +154,22 @@ func (vs *VoteService) GetObjectUserID(ctx context.Context, objectID string) (us // ListUserVotes list user's votes func (vs *VoteService) ListUserVotes(ctx context.Context, req schema.GetVoteWithPageReq) (model *pager.PageModel, err error) { - var ( - resp []schema.GetVoteWithPageResp - typeKeys = []string{ - "question.vote_up", - "question.vote_down", - "answer.vote_up", - "answer.vote_down", - } - activityTypes []int - ) + typeKeys := []string{ + activity_type.QuestionVoteUp, + activity_type.QuestionVoteDown, + activity_type.AnswerVoteUp, + activity_type.AnswerVoteDown, + } + activityTypes := make([]int, 0) + activityTypeMapping := make(map[int]string, 0) for _, typeKey := range typeKeys { - var t int - t, err = vs.configRepo.GetConfigType(typeKey) + cfg, err := vs.configService.GetConfigByKey(ctx, typeKey) if err != nil { continue } - activityTypes = append(activityTypes, t) + activityTypes = append(activityTypes, cfg.ID) + activityTypeMapping[cfg.ID] = typeKey } voteList, total, err := vs.voteRepo.ListUserVotes(ctx, req.UserID, req, activityTypes) @@ -176,15 +177,17 @@ func (vs *VoteService) ListUserVotes(ctx context.Context, req schema.GetVoteWith return } + lang := handler.GetLangByCtx(ctx) + + resp := make([]*schema.GetVoteWithPageResp, 0) for _, voteInfo := range voteList { - var objInfo *schema.SimpleObjectInfo - objInfo, err = vs.objectService.GetInfo(ctx, voteInfo.ObjectID) + objInfo, err := vs.objectService.GetInfo(ctx, voteInfo.ObjectID) if err != nil { log.Error(err) continue } - item := schema.GetVoteWithPageResp{ + item := &schema.GetVoteWithPageResp{ CreatedAt: voteInfo.CreatedAt.Unix(), ObjectID: objInfo.ObjectID, QuestionID: objInfo.QuestionID, @@ -193,13 +196,13 @@ func (vs *VoteService) ListUserVotes(ctx context.Context, req schema.GetVoteWith Title: objInfo.Title, UrlTitle: htmltext.UrlTitle(objInfo.Title), Content: objInfo.Content, - VoteType: activity_type.Format(voteInfo.ActivityType), } + item.VoteType = translator.Tr(lang, + activity_type.ActivityTypeFlagMapping[activityTypeMapping[voteInfo.ActivityType]]) if objInfo.QuestionStatus == entity.QuestionStatusDeleted { - item.Title = "Deleted question" + item.Title = translator.Tr(lang, constant.DeletedQuestionTitleTrKey) } resp = append(resp, item) } - return pager.NewPageModel(total, resp), err } diff --git a/pkg/checker/path_ignore.go b/pkg/checker/path_ignore.go new file mode 100644 index 00000000..127ea7de --- /dev/null +++ b/pkg/checker/path_ignore.go @@ -0,0 +1,47 @@ +package checker + +import ( + "sync" + + "github.com/answerdev/answer/configs" + "github.com/segmentfault/pacman/log" + "gopkg.in/yaml.v3" +) + +type PathIgnore struct { + Users []string `yaml:"users"` + Questions []string `yaml:"questions"` +} + +var ( + ignorePathInit sync.Once + pathIgnore = &PathIgnore{} +) + +func initPathIgnore() { + if err := yaml.Unmarshal(configs.PathIgnore, pathIgnore); err != nil { + log.Error(err) + } +} + +// IsUsersIgnorePath checks whether the username is in ignore path +func IsUsersIgnorePath(username string) bool { + ignorePathInit.Do(initPathIgnore) + for _, u := range pathIgnore.Users { + if u == username { + return true + } + } + return false +} + +// IsQuestionsIgnorePath checks whether the questionID is in ignore path +func IsQuestionsIgnorePath(questionID string) bool { + ignorePathInit.Do(initPathIgnore) + for _, u := range pathIgnore.Questions { + if u == questionID { + return true + } + } + return false +} diff --git a/pkg/gravatar/gravatar.go b/pkg/gravatar/gravatar.go index 92afcdd9..baac92da 100644 --- a/pkg/gravatar/gravatar.go +++ b/pkg/gravatar/gravatar.go @@ -5,15 +5,13 @@ import ( "encoding/hex" "fmt" "net/url" - - "github.com/answerdev/answer/internal/base/constant" ) // GetAvatarURL get avatar url from gravatar by email -func GetAvatarURL(email string) string { +func GetAvatarURL(baseURL, email string) string { h := md5.New() h.Write([]byte(email)) - return constant.DefaultGravatarBaseURL + hex.EncodeToString(h.Sum(nil)) + return baseURL + hex.EncodeToString(h.Sum(nil)) } // Resize resize avatar by pixel diff --git a/plugin/agent.go b/plugin/agent.go index 7de90ce5..6ac38d84 100644 --- a/plugin/agent.go +++ b/plugin/agent.go @@ -1,7 +1,6 @@ package plugin import ( - "github.com/answerdev/answer/internal/base/constant" "github.com/gin-gonic/gin" ) @@ -15,10 +14,19 @@ type Agent interface { var ( CallAgent, registerAgent = MakePlugin[Agent](true) + siteURLFn func() string ) // SiteURL The site url is the domain address of the current site. e.g. http://localhost:8080 // When some Agent plugins want to redirect to the origin site, it can use this function to get the site url. func SiteURL() string { - return constant.DefaultSiteURL + if siteURLFn != nil { + return siteURLFn() + } + return "" +} + +// RegisterGetSiteURLFunc Register a function to get the site url. +func RegisterGetSiteURLFunc(fn func() string) { + siteURLFn = fn }