chore(style): fmt code (#534)

This commit is contained in:
q1anx1 2022-08-09 20:10:21 +08:00 committed by GitHub
parent 69d6098eb2
commit a6c327cfdf
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
42 changed files with 157 additions and 144 deletions

View File

@ -22,8 +22,10 @@ import (
"xorm.io/xorm" "xorm.io/xorm"
) )
var adapter *Adapter = nil var (
var CasdoorOrganization string adapter *Adapter = nil
CasdoorOrganization string
)
type Session struct { type Session struct {
SessionKey string `xorm:"char(64) notnull pk"` SessionKey string `xorm:"char(64) notnull pk"`

View File

@ -35,7 +35,7 @@ func (c *ApiController) AddThanks() {
user := c.GetSessionUser() user := c.GetSessionUser()
id := util.ParseInt(c.Input().Get("id")) id := util.ParseInt(c.Input().Get("id"))
thanksType := c.Input().Get("thanksType") //1 means topic, 2 means reply thanksType := c.Input().Get("thanksType") // 1 means topic, 2 means reply
var author *auth.User var author *auth.User
if thanksType == "2" { if thanksType == "2" {
@ -160,7 +160,7 @@ func (c *ApiController) GetCheckinBonus() {
bonus := rand.Intn(maxBonus) bonus := rand.Intn(maxBonus)
record := object.ConsumptionRecord{ record := object.ConsumptionRecord{
//Id: util.IntToString(object.GetConsumptionRecordId() + 1), // Id: util.IntToString(object.GetConsumptionRecordId() + 1),
Amount: bonus, Amount: bonus,
Balance: object.GetMemberBalance(user) + bonus, Balance: object.GetMemberBalance(user) + bonus,
ReceiverId: GetUserName(user), ReceiverId: GetUserName(user),

View File

@ -67,7 +67,7 @@ func (c *ApiController) GetSessionUser() *auth.User {
func (c *ApiController) SetSessionUser(user *auth.User) { func (c *ApiController) SetSessionUser(user *auth.User) {
if user == nil { if user == nil {
//c.DelSession("user") // c.DelSession("user")
return return
} }

View File

@ -43,7 +43,7 @@ func (c *ApiController) AddFavorites() {
username := c.GetSessionUsername() username := c.GetSessionUsername()
favorites := object.Favorites{ favorites := object.Favorites{
//Id: util.IntToString(object.GetFavoritesCount()) + username, // Id: util.IntToString(object.GetFavoritesCount()) + username,
FavoritesType: favoritesType, FavoritesType: favoritesType,
ObjectId: objectId, ObjectId: objectId,
CreatedTime: util.GetCurrentTime(), CreatedTime: util.GetCurrentTime(),
@ -74,7 +74,7 @@ func (c *ApiController) AddFavorites() {
if favoritesType == object.FavorTopic { if favoritesType == object.FavorTopic {
topicId := util.ParseInt(objectId) topicId := util.ParseInt(objectId)
notification := object.Notification{ notification := object.Notification{
//Id: util.IntToString(object.GetNotificationId()), // Id: util.IntToString(object.GetNotificationId()),
NotificationType: 4, NotificationType: 4,
ObjectId: topicId, ObjectId: topicId,
CreatedTime: util.GetCurrentTime(), CreatedTime: util.GetCurrentTime(),
@ -226,7 +226,7 @@ func (c *ApiController) GetAccountFavoriteNum() {
var res [6]int var res [6]int
var wg sync.WaitGroup var wg sync.WaitGroup
//favorite type set,5 object.favorTopic... // favorite type set,5 object.favorTopic...
typeSet := []string{object.FavorTopic, object.FollowUser, object.FavorNode, object.SubscribeTopic} typeSet := []string{object.FavorTopic, object.FollowUser, object.FavorNode, object.SubscribeTopic}
for i := 1; i <= len(typeSet); i++ { for i := 1; i <= len(typeSet); i++ {

View File

@ -191,7 +191,7 @@ func (c *ApiController) UpdateFileDescribe() {
} }
// @Title UploadFile // @Title UploadFile
// @Tag File API // @Tag File API
// @router /upload-file [post] // @router /upload-file [post]
func (c *ApiController) UploadFile() { func (c *ApiController) UploadFile() {
if c.RequireSignedIn() { if c.RequireSignedIn() {
@ -213,7 +213,7 @@ func (c *ApiController) UploadFile() {
} }
// @Title ModeratorUpload // @Title ModeratorUpload
// @Tag File API // @Tag File API
// @router /upload-moderator [post] // @router /upload-moderator [post]
func (c *ApiController) ModeratorUpload() { func (c *ApiController) ModeratorUpload() {
if c.RequireSignedIn() { if c.RequireSignedIn() {
@ -236,5 +236,5 @@ func (c *ApiController) ModeratorUpload() {
timeStamp := fmt.Sprintf("?time=%d", time.Now().UnixNano()) timeStamp := fmt.Sprintf("?time=%d", time.Now().UnixNano())
c.ResponseOk(fileUrl + timeStamp) c.ResponseOk(fileUrl + timeStamp)
//resp := Response{Status: "ok", Msg: fileName, Data: fileUrl + timeStamp} // resp := Response{Status: "ok", Msg: fileName, Data: fileUrl + timeStamp}
} }

View File

@ -59,7 +59,6 @@ func (c *ApiController) UpdateFrontConfById() {
err := json.Unmarshal(c.Ctx.Input.RequestBody, &value) err := json.Unmarshal(c.Ctx.Input.RequestBody, &value)
tags := service.Finalword(value) tags := service.Finalword(value)
affect, err := object.UpdateFrontConfById(id, value, tags) affect, err := object.UpdateFrontConfById(id, value, tags)
if err != nil { if err != nil {
c.ResponseError(err.Error()) c.ResponseError(err.Error())
} }

View File

@ -58,7 +58,6 @@ func (c *ApiController) GetNode() {
c.ServeJSON() c.ServeJSON()
} }
// @Title UpdateNode // @Title UpdateNode
// @router /update-node [post] // @router /update-node [post]
// @Tag Node API // @Tag Node API

View File

@ -30,7 +30,7 @@ func (c *ApiController) AddNotification() {
memberId := c.GetSessionUsername() memberId := c.GetSessionUsername()
notification := object.Notification{ notification := object.Notification{
//Id: util.IntToString(object.GetNotificationId()), // Id: util.IntToString(object.GetNotificationId()),
NotificationType: tempNotification.NotificationType, NotificationType: tempNotification.NotificationType,
ObjectId: tempNotification.ObjectId, ObjectId: tempNotification.ObjectId,
CreatedTime: util.GetCurrentTime(), CreatedTime: util.GetCurrentTime(),

View File

@ -74,4 +74,4 @@ func (c *ApiController) DelSensitive() {
func (c *ApiController) GetSensitive() { func (c *ApiController) GetSensitive() {
c.Data["json"] = object.GetSensitiveWords() c.Data["json"] = object.GetSensitiveWords()
c.ServeJSON() c.ServeJSON()
} }

View File

@ -115,7 +115,7 @@ func (c *ApiController) UpdateTab() {
} }
tab := object.Tab{ tab := object.Tab{
//Id: tabInfo.Id, // Id: tabInfo.Id,
Name: tabInfo.Name, Name: tabInfo.Name,
Sorter: tabInfo.Sorter, Sorter: tabInfo.Sorter,
CreatedTime: tabInfo.CreatedTime, CreatedTime: tabInfo.CreatedTime,

View File

@ -143,7 +143,7 @@ func (c *ApiController) GetTopic() {
// @Title GetTopicAdmin // @Title GetTopicAdmin
// @Description get topic for admin by id // @Description get topic for admin by id
//@Param id query string true "id" // @Param id query string true "id"
// @Success 200 {object} object.AdminTopicInfo The Response object // @Success 200 {object} object.AdminTopicInfo The Response object
// @router /get-topic-admin [get] // @router /get-topic-admin [get]
// @Tag Topic API // @Tag Topic API
@ -216,7 +216,7 @@ func (c *ApiController) AddTopic() {
} }
topic := object.Topic{ topic := object.Topic{
//Id: util.IntToString(object.GetTopicId()), // Id: util.IntToString(object.GetTopicId()),
Author: GetUserName(user), Author: GetUserName(user),
NodeId: node.Id, NodeId: node.Id,
NodeName: node.Name, NodeName: node.Name,
@ -242,9 +242,9 @@ func (c *ApiController) AddTopic() {
c.ResponseError("You don't have enough balance.") c.ResponseError("You don't have enough balance.")
return return
} }
//payRes := object.CreateTopicConsumption(c.GetSessionUser(), topic.Id) // payRes := object.CreateTopicConsumption(c.GetSessionUser(), topic.Id)
//object.AddTopicNotification(topic.Id, c.GetSessionUser(), body) // object.AddTopicNotification(topic.Id, c.GetSessionUser(), body)
err = json.Unmarshal(c.Ctx.Input.RequestBody, &topic) err = json.Unmarshal(c.Ctx.Input.RequestBody, &topic)
if err != nil { if err != nil {
@ -545,7 +545,6 @@ func (c *ApiController) GetHotTopic() {
res := object.GetHotTopic(limit) res := object.GetHotTopic(limit)
c.ResponseOk(res) c.ResponseOk(res)
} }
// @Title GetSortedTopics // @Title GetSortedTopics
@ -618,7 +617,7 @@ func (c *ApiController) UpdateTopicNode() {
} }
topic := object.Topic{ topic := object.Topic{
//Id: id, // Id: id,
NodeId: node.Id, NodeId: node.Id,
NodeName: node.Name, NodeName: node.Name,
TabId: node.TabId, TabId: node.TabId,
@ -702,7 +701,7 @@ func (c *ApiController) TranslateTopic() {
topicIdStr := c.Input().Get("id") topicIdStr := c.Input().Get("id")
targetLang := c.Input().Get("target") targetLang := c.Input().Get("target")
//ISO/IEC 15897 to ISO 639-1 // ISO/IEC 15897 to ISO 639-1
targetLang = targetLang[0:2] targetLang = targetLang[0:2]
topicId := util.ParseInt(topicIdStr) topicId := util.ParseInt(topicIdStr)
@ -741,10 +740,10 @@ func (c *ApiController) TopTopic() {
var res bool var res bool
nodeId := object.GetTopicNodeId(id) nodeId := object.GetTopicNodeId(id)
if object.CheckIsAdmin(user) || object.CheckNodeModerator(user, nodeId) { if object.CheckIsAdmin(user) || object.CheckNodeModerator(user, nodeId) {
//timeStr := c.Input().Get("time") // timeStr := c.Input().Get("time")
//time := util.ParseInt(timeStr) // time := util.ParseInt(timeStr)
//date := util.GetTimeMinute(time) // date := util.GetTimeMinute(time)
//res = object.ChangeTopicTopExpiredTime(id, date) // res = object.ChangeTopicTopExpiredTime(id, date)
topType := c.Input().Get("topType") topType := c.Input().Get("topType")
date := util.GetTimeYear(100) date := util.GetTimeYear(100)
res = object.ChangeTopicTopExpiredTime(id, date, topType) res = object.ChangeTopicTopExpiredTime(id, date, topType)

View File

@ -21,8 +21,10 @@ import (
var randomAvatarCount = 244 var randomAvatarCount = 244
var randomAvatarMap map[string][]byte var (
var randomAvatarMapMutex sync.RWMutex randomAvatarMap map[string][]byte
randomAvatarMapMutex sync.RWMutex
)
func initRandomAvatars() { func initRandomAvatars() {
randomAvatarMap = map[string][]byte{} randomAvatarMap = map[string][]byte{}

View File

@ -19,8 +19,10 @@ import (
"github.com/casbin/casnode/object" "github.com/casbin/casnode/object"
) )
var CasdoorOrganization = "" var (
var CasdoorApplication = "" CasdoorOrganization = ""
CasdoorApplication = ""
)
func init() { func init() {
object.InitConfig() object.InitConfig()

View File

@ -14,8 +14,10 @@
package discuzx package discuzx
var dbName = "ultrax" var (
var discuzxDomain = "https://www.discuz.net/" dbName = "ultrax"
var discuzxAttachmentBaseUrl = "https://attachment.discuz.net/forum/" discuzxDomain = "https://www.discuz.net/"
discuzxAttachmentBaseUrl = "https://attachment.discuz.net/forum/"
)
var avatarPoolBaseUrl = "https://cdn.casbin.com/avatar-pool/" var avatarPoolBaseUrl = "https://cdn.casbin.com/avatar-pool/"

View File

@ -33,7 +33,7 @@ type Post struct {
func getPosts() []*Post { func getPosts() []*Post {
posts := []*Post{} posts := []*Post{}
err := adapter.Engine.Table("pre_forum_post").Find(&posts) err := adapter.Engine.Table("pre_forum_post").Find(&posts)
//err := adapter.Engine.Table("pre_forum_post").Where("tid = ?", threadId).Find(&posts) // err := adapter.Engine.Table("pre_forum_post").Where("tid = ?", threadId).Find(&posts)
if err != nil { if err != nil {
panic(err) panic(err)
} }

View File

@ -80,7 +80,7 @@ func addThread(thread *Thread, threadPostsMap map[int][]*Post, attachments []*At
thread.Posts = posts thread.Posts = posts
//deleteWholeTopic(thread) // deleteWholeTopic(thread)
mutex := sync.RWMutex{} mutex := sync.RWMutex{}

View File

@ -34,11 +34,11 @@ func TestGetThreads(t *testing.T) {
if thread, ok := threadMap[post.Tid]; ok { if thread, ok := threadMap[post.Tid]; ok {
thread.Posts = append(thread.Posts, post) thread.Posts = append(thread.Posts, post)
} else { } else {
//fmt.Printf("Failed to find thread: %d for post: %s\n", post.Tid, post.Message) // fmt.Printf("Failed to find thread: %d for post: %s\n", post.Tid, post.Message)
} }
} }
//thread := threadMap[126152] // thread := threadMap[126152]
thread := threadMap[126239] thread := threadMap[126239]
println(thread) println(thread)

View File

@ -23,8 +23,10 @@ import (
"github.com/casbin/casnode/object" "github.com/casbin/casnode/object"
) )
var AddThreadsConcurrency = 100 var (
var AddThreadsBatchSize = 10000 AddThreadsConcurrency = 100
AddThreadsBatchSize = 10000
)
func addThreads(threads []*Thread, threadPostsMap map[int][]*Post, attachmentMap map[int][]*Attachment, forumMap map[int]*Forum, classMap map[int]*Class) { func addThreads(threads []*Thread, threadPostsMap map[int][]*Post, attachmentMap map[int][]*Attachment, forumMap map[int]*Forum, classMap map[int]*Class) {
arrayMutex := sync.RWMutex{} arrayMutex := sync.RWMutex{}

View File

@ -28,27 +28,27 @@ func getUserFromMember(memberEx *MemberEx) *auth.User {
CreatedTime: getTimeFromUnixSeconds(memberEx.Member.Regdate), CreatedTime: getTimeFromUnixSeconds(memberEx.Member.Regdate),
Id: strconv.Itoa(memberEx.Member.Uid), Id: strconv.Itoa(memberEx.Member.Uid),
Type: "normal-user", Type: "normal-user",
//Password: memberEx.UcenterMember.Password, // Password: memberEx.UcenterMember.Password,
//PasswordSalt: memberEx.UcenterMember.Salt, // PasswordSalt: memberEx.UcenterMember.Salt,
//DisplayName: displayName, // DisplayName: displayName,
Avatar: "", Avatar: "",
PermanentAvatar: "*", PermanentAvatar: "*",
Email: memberEx.Member.Email, Email: memberEx.Member.Email,
//Phone: memberEx.Profile.Mobile, // Phone: memberEx.Profile.Mobile,
//Location: memberEx.Profile.Residecity, // Location: memberEx.Profile.Residecity,
Address: []string{}, Address: []string{},
//Affiliation: memberEx.Profile.Occupation, // Affiliation: memberEx.Profile.Occupation,
//Title: memberEx.Profile.Position, // Title: memberEx.Profile.Position,
//IdCardType: idCardType, // IdCardType: idCardType,
//IdCard: idCard, // IdCard: idCard,
//Homepage: memberEx.Profile.Site, // Homepage: memberEx.Profile.Site,
//Bio: memberEx.Profile.Bio, // Bio: memberEx.Profile.Bio,
//Tag: memberEx.Profile.Interest, // Tag: memberEx.Profile.Interest,
Region: "CN", Region: "CN",
Language: "zh", Language: "zh",
//Gender: gender, // Gender: gender,
//Birthday: birthday, // Birthday: birthday,
//Education: memberEx.Profile.Education, // Education: memberEx.Profile.Education,
Score: memberEx.Member.Credits, Score: memberEx.Member.Credits,
Ranking: memberEx.Member.Uid, Ranking: memberEx.Member.Uid,
IsOnline: false, IsOnline: false,
@ -57,8 +57,8 @@ func getUserFromMember(memberEx *MemberEx) *auth.User {
IsForbidden: false, IsForbidden: false,
IsDeleted: false, IsDeleted: false,
SignupApplication: CasdoorApplication, SignupApplication: CasdoorApplication,
//CreatedIp: memberEx.UcenterMember.Regip, // CreatedIp: memberEx.UcenterMember.Regip,
//LastSigninTime: getTimeFromUnixSeconds(memberEx.UcenterMember.Lastlogintime), // LastSigninTime: getTimeFromUnixSeconds(memberEx.UcenterMember.Lastlogintime),
LastSigninIp: "", LastSigninIp: "",
Properties: map[string]string{}, Properties: map[string]string{},
} }

View File

@ -25,14 +25,16 @@ import (
"time" "time"
) )
var reBold *regexp.Regexp var (
var reAlign *regexp.Regexp reBold *regexp.Regexp
var reFont *regexp.Regexp reAlign *regexp.Regexp
var reUrl *regexp.Regexp reFont *regexp.Regexp
var reSize *regexp.Regexp reUrl *regexp.Regexp
var reSize2 *regexp.Regexp reSize *regexp.Regexp
var reSize3 *regexp.Regexp reSize2 *regexp.Regexp
var reVideo *regexp.Regexp reSize3 *regexp.Regexp
reVideo *regexp.Regexp
)
func init() { func init() {
reBold, _ = regexp.Compile("\\[b](.*?)\\[/b]") reBold, _ = regexp.Compile("\\[b](.*?)\\[/b]")
@ -42,7 +44,7 @@ func init() {
reSize, _ = regexp.Compile("\\[[a-z]+(=[^]]+)?]") reSize, _ = regexp.Compile("\\[[a-z]+(=[^]]+)?]")
reSize2, _ = regexp.Compile("\\[/align]") reSize2, _ = regexp.Compile("\\[/align]")
reSize3, _ = regexp.Compile("\\[/[a-z]+]") reSize3, _ = regexp.Compile("\\[/[a-z]+]")
//reSize, _ = regexp.Compile("\\[size=\\d+\\].*\\[/size\\]") // reSize, _ = regexp.Compile("\\[size=\\d+\\].*\\[/size\\]")
reVideo, _ = regexp.Compile("\\[media=x,(\\d+),(\\d+)\\].*/id_(.*)\\.html\\[/media\\]") reVideo, _ = regexp.Compile("\\[media=x,(\\d+),(\\d+)\\].*/id_(.*)\\.html\\[/media\\]")
} }

View File

@ -43,7 +43,7 @@ func main() {
AllowCredentials: true, AllowCredentials: true,
})) }))
//beego.DelStaticPath("/static") // beego.DelStaticPath("/static")
beego.SetStaticPath("/static", "web/build/static") beego.SetStaticPath("/static", "web/build/static")
beego.SetStaticPath("/swagger", "swagger") beego.SetStaticPath("/swagger", "swagger")
beego.BConfig.WebConfig.DirectoryIndex = true beego.BConfig.WebConfig.DirectoryIndex = true

View File

@ -23,9 +23,11 @@ import (
"xorm.io/xorm" "xorm.io/xorm"
) )
var adapter *Adapter var (
var CasdoorOrganization string adapter *Adapter
var CasdoorApplication string CasdoorOrganization string
CasdoorApplication string
)
type Session struct { type Session struct {
SessionKey string `xorm:"char(64) notnull pk"` SessionKey string `xorm:"char(64) notnull pk"`

View File

@ -176,7 +176,7 @@ func GetThanksStatus(memberId string, id, recordType int) bool {
func CreateTopicConsumption(user *auth.User, id int) bool { func CreateTopicConsumption(user *auth.User, id int) bool {
record := ConsumptionRecord{ record := ConsumptionRecord{
//Id: util.IntToString(GetConsumptionRecordId()), // Id: util.IntToString(GetConsumptionRecordId()),
ReceiverId: GetUserName(user), ReceiverId: GetUserName(user),
ObjectId: id, ObjectId: id,
CreatedTime: util.GetCurrentTime(), CreatedTime: util.GetCurrentTime(),
@ -199,7 +199,7 @@ func CreateTopicConsumption(user *auth.User, id int) bool {
func CreateReplyConsumption(user *auth.User, id int) bool { func CreateReplyConsumption(user *auth.User, id int) bool {
record := ConsumptionRecord{ record := ConsumptionRecord{
//Id: util.IntToString(GetConsumptionRecordId()), // Id: util.IntToString(GetConsumptionRecordId()),
ReceiverId: GetUserName(user), ReceiverId: GetUserName(user),
ObjectId: id, ObjectId: id,
CreatedTime: util.GetCurrentTime(), CreatedTime: util.GetCurrentTime(),
@ -226,7 +226,7 @@ func GetReplyBonus(author *auth.User, consumer *auth.User, id int) {
} }
record := ConsumptionRecord{ record := ConsumptionRecord{
//Id: util.IntToString(GetConsumptionRecordId()), // Id: util.IntToString(GetConsumptionRecordId()),
ConsumerId: consumer.Name, ConsumerId: consumer.Name,
ReceiverId: author.Name, ReceiverId: author.Name,
ObjectId: id, ObjectId: id,

View File

@ -30,8 +30,10 @@ type BasicInfo struct {
Value string `xorm:"mediumtext"` Value string `xorm:"mediumtext"`
} }
var fileDate, version string var (
var onlineMemberNum, highestOnlineNum int fileDate, version string
onlineMemberNum, highestOnlineNum int
)
func InitForumBasicInfo() { func InitForumBasicInfo() {
GetForumVersion() GetForumVersion()
@ -68,7 +70,7 @@ func GetForumVersion() string {
return "" return ""
} }
//Convert to full length // Convert to full length
temp := string(content) temp := string(content)
version = strings.ReplaceAll(temp, "\n", "") version = strings.ReplaceAll(temp, "\n", "")

View File

@ -117,7 +117,7 @@ func refreshCronTasks() bool {
} }
schedule := fmt.Sprintf("%s %s * * *", minutes, hours) schedule := fmt.Sprintf("%s %s * * *", minutes, hours)
//schedule := "* * * * *" // schedule := "* * * * *"
err := ctab.AddJob(schedule, schedulePost, post.Id) err := ctab.AddJob(schedule, schedulePost, post.Id)
if err != nil { if err != nil {
panic(err) panic(err)

View File

@ -35,7 +35,7 @@ const (
) )
func IsFavoritesExist(Type string) bool { func IsFavoritesExist(Type string) bool {
//check the if the string is in the enum // check the if the string is in the enum
if Type == FavorTopic || Type == FollowUser || Type == FavorNode || Type == SubscribeTopic { if Type == FavorTopic || Type == FollowUser || Type == FavorNode || Type == SubscribeTopic {
return true return true
} }

View File

@ -21,22 +21,20 @@ type FrontConf struct {
Tags []string `xorm:"varchar(200)" json:"tags"` Tags []string `xorm:"varchar(200)" json:"tags"`
} }
var ( var Confs = []*FrontConf{
Confs = []*FrontConf{ {Id: "forumName", Value: "Casnode", Field: "visualConf", Tags: nil},
{Id: "forumName", Value: "Casnode", Field: "visualConf", Tags: nil}, {Id: "logoImage", Value: "https://cdn.casbin.com/forum/static/img/logo.png", Field: "visualConf", Tags: nil},
{Id: "logoImage", Value: "https://cdn.casbin.com/forum/static/img/logo.png", Field: "visualConf", Tags: nil}, {Id: "footerLogoImage", Value: "https://cdn.casbin.com/forum/static/img/logo-footer.png", Field: "visualConf", Tags: nil},
{Id: "footerLogoImage", Value: "https://cdn.casbin.com/forum/static/img/logo-footer.png", Field: "visualConf", Tags: nil}, {Id: "footerLogoUrl", Value: "https://www.digitalocean.com/", Field: "visualConf", Tags: nil},
{Id: "footerLogoUrl", Value: "https://www.digitalocean.com/", Field: "visualConf", Tags: nil}, {Id: "signinBoxStrong", Value: "Casbin = way to authorization", Field: "visualConf", Tags: nil},
{Id: "signinBoxStrong", Value: "Casbin = way to authorization", Field: "visualConf", Tags: nil}, {Id: "signinBoxSpan", Value: "A place for Casbin developers and users", Field: "visualConf", Tags: nil},
{Id: "signinBoxSpan", Value: "A place for Casbin developers and users", Field: "visualConf", Tags: nil}, {Id: "footerDeclaration", Value: "World is powered by code", Field: "visualConf", Tags: nil},
{Id: "footerDeclaration", Value: "World is powered by code", Field: "visualConf", Tags: nil}, {Id: "footerAdvise", Value: "♥ Do have faith in what you're doing.", Field: "visualConf", Tags: nil},
{Id: "footerAdvise", Value: "♥ Do have faith in what you're doing.", Field: "visualConf", Tags: nil}, {Id: "faq", Value: "Not yet", Field: "", Tags: nil},
{Id: "faq", Value: "Not yet", Field: "", Tags: nil}, {Id: "mission", Value: "Not yet", Field: "", Tags: nil},
{Id: "mission", Value: "Not yet", Field: "", Tags: nil}, {Id: "advertise", Value: "Not yet", Field: "", Tags: nil},
{Id: "advertise", Value: "Not yet", Field: "", Tags: nil}, {Id: "thanks", Value: "Not yet", Field: "", Tags: nil},
{Id: "thanks", Value: "Not yet", Field: "", Tags: nil}, }
}
)
func InitFrontConf() { func InitFrontConf() {
var confs []*FrontConf var confs []*FrontConf

View File

@ -305,7 +305,7 @@ func createTopicWithMessages(messages []gitter.Message, room gitter.Room, node N
// create if user is not exist // create if user is not exist
user, err := auth.GetUser(msg.From.Username) user, err := auth.GetUser(msg.From.Username)
//fmt.Println("user:", user) // fmt.Println("user:", user)
if err != nil { if err != nil {
panic(err) panic(err)
} }
@ -326,7 +326,7 @@ func createTopicWithMessages(messages []gitter.Message, room gitter.Room, node N
} }
} }
var mentioned = false // if @user mentioned := false // if @user
for _, mention := range msg.Mentions { for _, mention := range msg.Mentions {
if mention.ScreenName == lastMsg.From.Username { if mention.ScreenName == lastMsg.From.Username {
mentioned = true mentioned = true

View File

@ -14,7 +14,7 @@
package object package object
//RecordType: 1 means node hit record // RecordType: 1 means node hit record
type BrowseRecord struct { type BrowseRecord struct {
Id int `xorm:"int notnull pk autoincr" json:"id"` Id int `xorm:"int notnull pk autoincr" json:"id"`
MemberId string `xorm:"varchar(100)" json:"memberId"` MemberId string `xorm:"varchar(100)" json:"memberId"`

View File

@ -29,7 +29,7 @@ func GetRankingRich() ([]*auth.User, error) {
} }
func GetRankingPlayer() ([]*auth.User, error) { func GetRankingPlayer() ([]*auth.User, error) {
return casdoor.GetSortedUsers("karma", 25), nil return casdoor.GetSortedUsers("karma", 25), nil
} }
func GetUser(id string) *auth.User { func GetUser(id string) *auth.User {

View File

@ -93,7 +93,7 @@ func UpdateNode(id string, node *Node) bool {
panic(err) panic(err)
} }
//return affected != 0 // return affected != 0
return true return true
} }

View File

@ -34,7 +34,7 @@ type Notification struct {
SenderId string `xorm:"varchar(100)" json:"senderId"` SenderId string `xorm:"varchar(100)" json:"senderId"`
ReceiverId string `xorm:"varchar(100) index" json:"receiverId"` ReceiverId string `xorm:"varchar(100) index" json:"receiverId"`
Status int `xorm:"tinyint" json:"-"` Status int `xorm:"tinyint" json:"-"`
//Deleted bool `xorm:"bool" json:"-"` // Deleted bool `xorm:"bool" json:"-"`
} }
func AddNotification(notification *Notification) bool { func AddNotification(notification *Notification) bool {
@ -207,7 +207,7 @@ func AddReplyNotification(senderId, content string, objectId, topicId int) {
if senderId != receiverId { if senderId != receiverId {
notification := Notification{ notification := Notification{
//Id: memberMap[receiverId], // Id: memberMap[receiverId],
NotificationType: 1, NotificationType: 1,
ObjectId: objectId, ObjectId: objectId,
CreatedTime: util.GetCurrentTime(), CreatedTime: util.GetCurrentTime(),
@ -228,7 +228,7 @@ func AddReplyNotification(senderId, content string, objectId, topicId int) {
} }
delete(memberMap, receiverId) delete(memberMap, receiverId)
for receiverId2, _ := range memberMap { for receiverId2 := range memberMap {
wg.Add(1) wg.Add(1)
go func(receiverId2 string) { go func(receiverId2 string) {
defer wg.Done() defer wg.Done()
@ -278,7 +278,7 @@ func AddTopicNotification(objectId int, author, content string) {
} }
} }
for k, _ := range memberMap { for k := range memberMap {
wg.Add(1) wg.Add(1)
k := k k := k
go func() { go func() {

View File

@ -83,34 +83,34 @@ func GetReplies(topicId int, user *auth.User, limit int, page int) ([]*ReplyWith
if enableNestedReply { if enableNestedReply {
replies = bulidReplies(replies) replies = bulidReplies(replies)
//Use limit to calculate offset // Use limit to calculate offset
//If limit is 2, but the first reply have 2 child replies(3 replies) // If limit is 2, but the first reply have 2 child replies(3 replies)
//We need put these replies to offset, so cannot use (page * limit) to calculate offset // We need put these replies to offset, so cannot use (page * limit) to calculate offset
pageLimit := limit pageLimit := limit
for index, reply := range replies { for index, reply := range replies {
replyLen := getReplyLen(reply) replyLen := getReplyLen(reply)
//Ignore replies until page == 1 // Ignore replies until page == 1
if page > 1 { if page > 1 {
//Calculate limit in every ignore page // Calculate limit in every ignore page
pageLimit -= replyLen pageLimit -= replyLen
//Get replices for init == true(get the latest replies) // Get replices for init == true(get the latest replies)
resultReplies = append(resultReplies, reply) resultReplies = append(resultReplies, reply)
if pageLimit <= 0 { if pageLimit <= 0 {
page-- page--
pageLimit = limit pageLimit = limit
if index+1 < len(replies) { if index+1 < len(replies) {
//If the page is a usable value when we get the latest replies, clear the result // If the page is a usable value when we get the latest replies, clear the result
resultReplies = nil resultReplies = nil
} }
} }
} else if limit > 0 { } else if limit > 0 {
//if page == 1, prove that we are processing current page now // if page == 1, prove that we are processing current page now
//So we can only calculate the limit and put replies to result slice // So we can only calculate the limit and put replies to result slice
limit -= replyLen limit -= replyLen
resultReplies = append(resultReplies, reply) resultReplies = append(resultReplies, reply)
page-- page--
} else { } else {
//if page == 1, and limit < 0, prove that we get all replies in this page now // if page == 1, and limit < 0, prove that we get all replies in this page now
break break
} }
} }
@ -290,7 +290,7 @@ func UpdateReply(id int, reply *Reply) bool {
panic(err) panic(err)
} }
//return affected != 0 // return affected != 0
return true return true
} }
@ -305,13 +305,13 @@ func UpdateReplyWithLimitCols(id int, reply *Reply) bool {
panic(err) panic(err)
} }
//return affected != 0 // return affected != 0
return true return true
} }
// AddReply returns add reply result and reply id. // AddReply returns add reply result and reply id.
func AddReply(reply *Reply) (bool, int) { func AddReply(reply *Reply) (bool, int) {
//reply.Content = strings.ReplaceAll(reply.Content, "\n", "<br/>") // reply.Content = strings.ReplaceAll(reply.Content, "\n", "<br/>")
reply.Content = FilterUnsafeHTML(reply.Content) reply.Content = FilterUnsafeHTML(reply.Content)
affected, err := adapter.Engine.Insert(reply) affected, err := adapter.Engine.Insert(reply)
if err != nil { if err != nil {

View File

@ -18,7 +18,7 @@ import "strings"
type SensitiveWord struct { type SensitiveWord struct {
Word string `xorm:"varchar(64) notnull"` Word string `xorm:"varchar(64) notnull"`
Id int64 Id int64
} }
var sensitiveWords []SensitiveWord var sensitiveWords []SensitiveWord
@ -86,4 +86,4 @@ func ContainsSensitiveWord(str string) bool {
} }
} }
return false return false
} }

View File

@ -69,7 +69,7 @@ func UpdateTab(id string, tab *Tab) bool {
panic(err) panic(err)
} }
//return affected != 0 // return affected != 0
return true return true
} }

View File

@ -414,7 +414,7 @@ func UpdateTopic(id int, topic *Topic) bool {
panic(err) panic(err)
} }
//return affected != 0 // return affected != 0
return true return true
} }
@ -437,7 +437,7 @@ func UpdateTopicWithLimitCols(id int, topic *Topic) bool {
panic(err) panic(err)
} }
//return affected != 0 // return affected != 0
return true return true
} }
@ -639,7 +639,7 @@ func GetHotTopic(limit int) []*TopicWithAvatar {
func GetSortedTopics(lastReplySort, hotSort, favCountSort, createdTimeSort string, limit int, offset int) []*TopicWithAvatar { func GetSortedTopics(lastReplySort, hotSort, favCountSort, createdTimeSort string, limit int, offset int) []*TopicWithAvatar {
var topics []*Topic var topics []*Topic
db := adapter.Engine.Table("topic") db := adapter.Engine.Table("topic")
//last reply time sort // last reply time sort
switch lastReplySort { switch lastReplySort {
case "1": case "1":
db = db.Asc("last_reply_time") db = db.Asc("last_reply_time")

View File

@ -14,10 +14,13 @@ import (
"github.com/astaxie/beego/context" "github.com/astaxie/beego/context"
) )
//var chromeCtx ctx.Context // var chromeCtx ctx.Context
var chromeCtxPool *SsrPool var chromeCtxPool *SsrPool
var isChromeInstalled bool
var isChromeInit bool var (
isChromeInstalled bool
isChromeInit bool
)
type PageCache struct { type PageCache struct {
time time.Time time time.Time

View File

@ -24,12 +24,11 @@ func init() {
} }
func initAPI() { func initAPI() {
ns := ns := beego.NewNamespace("/api",
beego.NewNamespace("/api", beego.NSInclude(
beego.NSInclude( &controllers.ApiController{},
&controllers.ApiController{}, ),
), )
)
beego.AddNamespace(ns) beego.AddNamespace(ns)
beego.Router("/api/get-topics", &controllers.ApiController{}, "GET:GetTopics") beego.Router("/api/get-topics", &controllers.ApiController{}, "GET:GetTopics")
@ -37,7 +36,7 @@ func initAPI() {
beego.Router("/api/get-topic", &controllers.ApiController{}, "GET:GetTopic") beego.Router("/api/get-topic", &controllers.ApiController{}, "GET:GetTopic")
beego.Router("/api/get-topic-admin", &controllers.ApiController{}, "GET:GetTopicAdmin") beego.Router("/api/get-topic-admin", &controllers.ApiController{}, "GET:GetTopicAdmin")
beego.Router("/api/get-topic-by-urlpath-and-title", &controllers.ApiController{}, "GET:GetTopicByUrlPathAndTitle") beego.Router("/api/get-topic-by-urlpath-and-title", &controllers.ApiController{}, "GET:GetTopicByUrlPathAndTitle")
//beego.Router("/api/update-topic", &controllers.ApiController{}, "POST:UpdateTopic") // no necessary to explore this api. // beego.Router("/api/update-topic", &controllers.ApiController{}, "POST:UpdateTopic") // no necessary to explore this api.
beego.Router("/api/add-topic", &controllers.ApiController{}, "POST:AddTopic") beego.Router("/api/add-topic", &controllers.ApiController{}, "POST:AddTopic")
beego.Router("/api/delete-topic", &controllers.ApiController{}, "POST:DeleteTopic") beego.Router("/api/delete-topic", &controllers.ApiController{}, "POST:DeleteTopic")
beego.Router("/api/translate-topic", &controllers.ApiController{}, "POST:TranslateTopic") beego.Router("/api/translate-topic", &controllers.ApiController{}, "POST:TranslateTopic")
@ -80,12 +79,12 @@ func initAPI() {
beego.Router("/api/get-ranking-rich", &controllers.ApiController{}, "GET:GetRankingRich") beego.Router("/api/get-ranking-rich", &controllers.ApiController{}, "GET:GetRankingRich")
beego.Router("/api/get-ranking-player", &controllers.ApiController{}, "GET:GetRankingPlayer") beego.Router("/api/get-ranking-player", &controllers.ApiController{}, "GET:GetRankingPlayer")
beego.Router("/api/update-poster", &controllers.ApiController{}, "POST:UpdatePoster") //Update poster api just for admin. beego.Router("/api/update-poster", &controllers.ApiController{}, "POST:UpdatePoster") // Update poster api just for admin.
beego.Router("/api/read-poster", &controllers.ApiController{}, "GET:ReadPoster") beego.Router("/api/read-poster", &controllers.ApiController{}, "GET:ReadPoster")
beego.Router("/api/update-translator", &controllers.ApiController{}, "POST:UpdateTranslator") //Update translator api just for admin. beego.Router("/api/update-translator", &controllers.ApiController{}, "POST:UpdateTranslator") // Update translator api just for admin.
beego.Router("/api/add-translator", &controllers.ApiController{}, "POST:AddTranslator") //Add translator api just for admin. beego.Router("/api/add-translator", &controllers.ApiController{}, "POST:AddTranslator") // Add translator api just for admin.
beego.Router("/api/del-translator", &controllers.ApiController{}, "POST:DelTranslator") //Delete translator api just for admin. beego.Router("/api/del-translator", &controllers.ApiController{}, "POST:DelTranslator") // Delete translator api just for admin.
beego.Router("/api/get-translator", &controllers.ApiController{}, "GET:GetTranslator") beego.Router("/api/get-translator", &controllers.ApiController{}, "GET:GetTranslator")
beego.Router("/api/visible-translator", &controllers.ApiController{}, "GET:VisibleTranslator") beego.Router("/api/visible-translator", &controllers.ApiController{}, "GET:VisibleTranslator")
@ -130,7 +129,7 @@ func initAPI() {
beego.Router("/api/get-plane", &controllers.ApiController{}, "GET:GetPlane") beego.Router("/api/get-plane", &controllers.ApiController{}, "GET:GetPlane")
beego.Router("/api/get-plane-admin", &controllers.ApiController{}, "GET:GetPlaneAdmin") beego.Router("/api/get-plane-admin", &controllers.ApiController{}, "GET:GetPlaneAdmin")
//beego.Router("/api/get-planes", &controllers.ApiController{}, "GET:GetPlanes") // beego.Router("/api/get-planes", &controllers.ApiController{}, "GET:GetPlanes")
beego.Router("/api/add-plane", &controllers.ApiController{}, "POST:AddPlane") // Add plane api just for admin. beego.Router("/api/add-plane", &controllers.ApiController{}, "POST:AddPlane") // Add plane api just for admin.
beego.Router("/api/get-plane-list", &controllers.ApiController{}, "GET:GetPlaneList") beego.Router("/api/get-plane-list", &controllers.ApiController{}, "GET:GetPlaneList")
beego.Router("/api/update-plane", &controllers.ApiController{}, "POST:UpdatePlane") // Update plane api just for admin. beego.Router("/api/update-plane", &controllers.ApiController{}, "POST:UpdatePlane") // Update plane api just for admin.

View File

@ -90,10 +90,10 @@ func render(chromeCtx ctx.Context, url string) (string, error) {
} }
func (pool *SsrPool) worker() { func (pool *SsrPool) worker() {
//chromeCtx, _ := chromedp.NewExecAllocator(ctx.Background(), append( // chromeCtx, _ := chromedp.NewExecAllocator(ctx.Background(), append(
// chromedp.DefaultExecAllocatorOptions[:], // chromedp.DefaultExecAllocatorOptions[:],
// chromedp.Flag("headless", false))...) // chromedp.Flag("headless", false))...)
//chromeCtx, _ = chromedp.NewContext(chromeCtx) // chromeCtx, _ = chromedp.NewContext(chromeCtx)
chromeCtx, _ := chromedp.NewContext(ctx.Background()) // set default context with headless mode chromeCtx, _ := chromedp.NewContext(ctx.Background()) // set default context with headless mode
for task := range pool.JobsChannel { for task := range pool.JobsChannel {
cancel := func() bool { cancel := func() bool {

View File

@ -57,7 +57,7 @@ func Keyword(word []string) []string {
for _, v := range word { for _, v := range word {
wordnum[v] = wordnum[v] + 1 wordnum[v] = wordnum[v] + 1
} }
for s, _ := range wordnum { for s := range wordnum {
words = append(words, s) words = append(words, s)
} }
if len(wordnum) < 5 { if len(wordnum) < 5 {

View File

@ -36,7 +36,7 @@ func GetIPInfo(clientIP string) string {
ip := strings.TrimSpace(ips[i]) ip := strings.TrimSpace(ips[i])
desc := "" // GetDescFromIP(ip) desc := "" // GetDescFromIP(ip)
ipstr := fmt.Sprintf("%s: %s", ip, desc) ipstr := fmt.Sprintf("%s: %s", ip, desc)
if i != len(ips) - 1 { if i != len(ips)-1 {
res += ipstr + " -> " res += ipstr + " -> "
} else { } else {
res += ipstr res += ipstr
@ -65,12 +65,12 @@ func getIPFromRequest(req *http.Request) string {
func LogInfo(ctx *context.Context, f string, v ...interface{}) { func LogInfo(ctx *context.Context, f string, v ...interface{}) {
ipString := fmt.Sprintf("(%s) ", getIPFromRequest(ctx.Request)) ipString := fmt.Sprintf("(%s) ", getIPFromRequest(ctx.Request))
logs.Info(ipString + f, v...) logs.Info(ipString+f, v...)
} }
func LogWarning(ctx *context.Context, f string, v ...interface{}) { func LogWarning(ctx *context.Context, f string, v ...interface{}) {
ipString := fmt.Sprintf("(%s) ", getIPFromRequest(ctx.Request)) ipString := fmt.Sprintf("(%s) ", getIPFromRequest(ctx.Request))
logs.Warning(ipString + f, v...) logs.Warning(ipString+f, v...)
} }
func ReadLog() []string { func ReadLog() []string {

View File

@ -45,7 +45,7 @@ func ReadStringFromPath(path string) string {
} }
func WriteStringToPath(s string, path string) { func WriteStringToPath(s string, path string) {
err := ioutil.WriteFile(path, []byte(s), 0644) err := ioutil.WriteFile(path, []byte(s), 0o644)
if err != nil { if err != nil {
panic(err) panic(err)
} }