fmt all go file

This commit is contained in:
lealife
2015-11-13 17:58:41 +08:00
parent cba69444a8
commit 7809d00787
100 changed files with 3375 additions and 3331 deletions

View File

@ -2,7 +2,7 @@ package service
import (
"github.com/leanote/leanote/app/info"
// . "github.com/leanote/leanote/app/lea"
// . "github.com/leanote/leanote/app/lea"
"github.com/leanote/leanote/app/db"
"gopkg.in/mgo.v2/bson"
"time"
@ -30,9 +30,9 @@ func (this *AlbumService) GetAlbums(userId string) []info.Album {
// delete album
// presupposition: has no images under this ablum
func (this *AlbumService) DeleteAlbum(userId, albumId string) (bool, string) {
if db.Count(db.Files, bson.M{"AlbumId": bson.ObjectIdHex(albumId),
if db.Count(db.Files, bson.M{"AlbumId": bson.ObjectIdHex(albumId),
"UserId": bson.ObjectIdHex(userId),
}) == 0 {
}) == 0 {
return db.DeleteByIdAndUserId(db.Albums, albumId, userId), ""
}
return false, "has images"
@ -41,4 +41,4 @@ func (this *AlbumService) DeleteAlbum(userId, albumId string) (bool, string) {
// update album name
func (this *AlbumService) UpdateAlbum(albumId, userId, name string) bool {
return db.UpdateByIdAndUserIdField(db.Albums, albumId, userId, "Name", name)
}
}

View File

@ -20,9 +20,9 @@ type AttachService struct {
func (this *AttachService) AddAttach(attach info.Attach, fromApi bool) (ok bool, msg string) {
attach.CreatedTime = time.Now()
ok = db.Insert(db.Attachs, attach)
note := noteService.GetNoteById(attach.NoteId.Hex())
// api调用时, 添加attach之前是没有note的
var userId string
if note.NoteId != "" {
@ -35,13 +35,13 @@ func (this *AttachService) AddAttach(attach info.Attach, fromApi bool) (ok bool,
// 更新笔记的attachs num
this.updateNoteAttachNum(attach.NoteId, 1)
}
if !fromApi {
// 增长note's usn
noteService.IncrNoteUsn(attach.NoteId.Hex(), userId)
}
return
return
}
// 更新笔记的附件个数
@ -49,13 +49,13 @@ func (this *AttachService) AddAttach(attach info.Attach, fromApi bool) (ok bool,
func (this *AttachService) updateNoteAttachNum(noteId bson.ObjectId, addNum int) bool {
num := db.Count(db.Attachs, bson.M{"NoteId": noteId})
/*
note := info.Note{}
note = noteService.GetNoteById(noteId.Hex())
note.AttachNum += addNum
if note.AttachNum < 0 {
note.AttachNum = 0
}
Log(note.AttachNum)
note := info.Note{}
note = noteService.GetNoteById(noteId.Hex())
note.AttachNum += addNum
if note.AttachNum < 0 {
note.AttachNum = 0
}
Log(note.AttachNum)
*/
return db.UpdateByQField(db.Notes, bson.M{"_id": noteId}, "AttachNum", num)
}
@ -63,18 +63,18 @@ func (this *AttachService) updateNoteAttachNum(noteId bson.ObjectId, addNum int)
// list attachs
func (this *AttachService) ListAttachs(noteId, userId string) []info.Attach {
attachs := []info.Attach{}
// 判断是否有权限为笔记添加附件, userId为空时表示是分享笔记的附件
if userId != "" && !shareService.HasUpdateNotePerm(noteId, userId) {
return attachs
}
// 笔记是否是自己的
note := noteService.GetNoteByIdAndUserId(noteId, userId)
if note.NoteId == "" {
return attachs
}
// TODO 这里, 优化权限控制
db.ListByQ(db.Attachs, bson.M{"NoteId": bson.ObjectIdHex(noteId)}, &attachs)
@ -122,13 +122,13 @@ func (this *AttachService) DeleteAllAttachs(noteId, userId string) bool {
func (this *AttachService) DeleteAttach(attachId, userId string) (bool, string) {
attach := info.Attach{}
db.Get(db.Attachs, attachId, &attach)
if(attach.AttachId != "") {
if attach.AttachId != "" {
// 判断是否有权限为笔记添加附件
if !shareService.HasUpdateNotePerm(attach.NoteId.Hex(), userId) {
return false, "No Perm"
}
if db.Delete(db.Attachs, bson.M{"_id": bson.ObjectIdHex(attachId)}) {
this.updateNoteAttachNum(attach.NoteId, -1)
attach.Path = strings.TrimLeft(attach.Path, "/")
@ -137,7 +137,7 @@ func (this *AttachService) DeleteAttach(attachId, userId string) (bool, string)
// userService.UpdateAttachSize(note.UserId.Hex(), -attach.Size)
// 修改note Usn
noteService.IncrNoteUsn(attach.NoteId.Hex(), userId)
return true, "delete file success"
}
return false, "delete file error"

View File

@ -421,7 +421,7 @@ func (this *BlogService) PreNextBlog(userId string, sorterField string, isAsc bo
// Log(sortFieldR2)
q = db.Notes.Find(query)
q.Sort(sortFieldR2).Limit(1).One(&note2)
return this.FixNote(note), this.FixNote(note2)
}

View File

@ -1,32 +1,33 @@
package service
import (
"fmt"
"github.com/leanote/leanote/app/db"
"github.com/leanote/leanote/app/info"
. "github.com/leanote/leanote/app/lea"
"github.com/leanote/leanote/app/db"
"gopkg.in/mgo.v2/bson"
"github.com/revel/revel"
"time"
"gopkg.in/mgo.v2/bson"
"os"
"os/exec"
"fmt"
"strings"
"strconv"
"strings"
"time"
)
// 配置服务
// 只是全局的, 用户的配置没有
type ConfigService struct {
adminUserId string
siteUrl string
adminUserId string
siteUrl string
adminUsername string
// 全局的
GlobalAllConfigs map[string]interface{}
GlobalAllConfigs map[string]interface{}
GlobalStringConfigs map[string]string
GlobalArrayConfigs map[string][]string
GlobalMapConfigs map[string]map[string]string
GlobalArrayConfigs map[string][]string
GlobalMapConfigs map[string]map[string]string
GlobalArrMapConfigs map[string][]map[string]string
}
// appStart时 将全局的配置从数据库中得到作为全局
func (this *ConfigService) InitGlobalConfigs() bool {
this.GlobalAllConfigs = map[string]interface{}{}
@ -34,22 +35,22 @@ func (this *ConfigService) InitGlobalConfigs() bool {
this.GlobalArrayConfigs = map[string][]string{}
this.GlobalMapConfigs = map[string]map[string]string{}
this.GlobalArrMapConfigs = map[string][]map[string]string{}
this.adminUsername, _ = revel.Config.String("adminUsername")
if this.adminUsername == "" {
this.adminUsername = "admin"
}
this.siteUrl, _ = revel.Config.String("site.url")
userInfo := userService.GetUserInfoByAny(this.adminUsername)
if userInfo.UserId == "" {
return false
}
this.adminUserId = userInfo.UserId.Hex()
configs := []info.Config{}
db.ListByQ(db.Configs, bson.M{"UserId": userInfo.UserId}, &configs)
for _, config := range configs {
if config.IsArr {
this.GlobalArrayConfigs[config.Key] = config.ValueArr
@ -65,12 +66,12 @@ func (this *ConfigService) InitGlobalConfigs() bool {
this.GlobalAllConfigs[config.Key] = config.ValueStr
}
}
return true
}
func (this *ConfigService) GetSiteUrl() string {
return this.siteUrl;
return this.siteUrl
}
func (this *ConfigService) GetAdminUsername() string {
return this.adminUsername
@ -84,15 +85,15 @@ func (this *ConfigService) updateGlobalConfig(userId, key string, value interfac
// 判断是否存在
if _, ok := this.GlobalAllConfigs[key]; !ok {
// 需要添加
config := info.Config{ConfigId: bson.NewObjectId(),
UserId: bson.ObjectIdHex(userId),
Key: key,
IsArr: isArr,
IsMap: isMap,
IsArrMap: isArrMap,
config := info.Config{ConfigId: bson.NewObjectId(),
UserId: bson.ObjectIdHex(userId),
Key: key,
IsArr: isArr,
IsMap: isMap,
IsArrMap: isArrMap,
UpdatedTime: time.Now(),
}
if(isArr) {
if isArr {
v, _ := value.([]string)
config.ValueArr = v
this.GlobalArrayConfigs[key] = v
@ -113,7 +114,7 @@ func (this *ConfigService) updateGlobalConfig(userId, key string, value interfac
} else {
i := bson.M{"UpdatedTime": time.Now()}
this.GlobalAllConfigs[key] = value
if(isArr) {
if isArr {
v, _ := value.([]string)
i["ValueArr"] = v
this.GlobalArrayConfigs[key] = v
@ -177,25 +178,26 @@ func (this *ConfigService) GetGlobalArrMapConfig(key string) []map[string]string
func (this *ConfigService) IsOpenRegister() bool {
return this.GetGlobalStringConfig("openRegister") != ""
}
//-------
// 修改共享笔记的配置
func (this *ConfigService) UpdateShareNoteConfig(registerSharedUserId string,
registerSharedNotebookPerms, registerSharedNotePerms []int,
func (this *ConfigService) UpdateShareNoteConfig(registerSharedUserId string,
registerSharedNotebookPerms, registerSharedNotePerms []int,
registerSharedNotebookIds, registerSharedNoteIds, registerCopyNoteIds []string) (ok bool, msg string) {
defer func() {
defer func() {
if err := recover(); err != nil {
ok = false
msg = fmt.Sprint(err)
}
}();
}()
// 用户是否存在?
if registerSharedUserId == "" {
ok = true
msg = "share userId is blank, So it share nothing to register"
this.UpdateGlobalStringConfig(this.adminUserId, "registerSharedUserId", "")
return
return
} else {
user := userService.GetUserInfo(registerSharedUserId)
if user.UserId == "" {
@ -206,7 +208,7 @@ func (this *ConfigService) UpdateShareNoteConfig(registerSharedUserId string,
this.UpdateGlobalStringConfig(this.adminUserId, "registerSharedUserId", registerSharedUserId)
}
}
notebooks := []map[string]string{}
// 共享笔记本
if len(registerSharedNotebookIds) > 0 {
@ -222,7 +224,7 @@ func (this *ConfigService) UpdateShareNoteConfig(registerSharedUserId string,
msg = "The user has no such notebook: " + notebookId
return
} else {
perm := "0";
perm := "0"
if registerSharedNotebookPerms[i] == 1 {
perm = "1"
}
@ -231,7 +233,7 @@ func (this *ConfigService) UpdateShareNoteConfig(registerSharedUserId string,
}
}
this.UpdateGlobalArrMapConfig(this.adminUserId, "registerSharedNotebooks", notebooks)
notes := []map[string]string{}
// 共享笔记
if len(registerSharedNoteIds) > 0 {
@ -247,7 +249,7 @@ func (this *ConfigService) UpdateShareNoteConfig(registerSharedUserId string,
msg = "The user has no such note: " + noteId
return
} else {
perm := "0";
perm := "0"
if registerSharedNotePerms[i] == 1 {
perm = "1"
}
@ -256,7 +258,7 @@ func (this *ConfigService) UpdateShareNoteConfig(registerSharedUserId string,
}
}
this.UpdateGlobalArrMapConfig(this.adminUserId, "registerSharedNotes", notes)
// 复制
noteIds := []string{}
if len(registerCopyNoteIds) > 0 {
@ -277,7 +279,7 @@ func (this *ConfigService) UpdateShareNoteConfig(registerSharedUserId string,
}
}
this.UpdateGlobalArrayConfig(this.adminUserId, "registerCopyNoteIds", noteIds)
ok = true
return
}
@ -298,7 +300,7 @@ func (this *ConfigService) getBackupDirname() string {
}
func (this *ConfigService) Backup(remark string) (ok bool, msg string) {
binPath := configService.GetGlobalStringConfig("mongodumpPath")
config := revel.Config;
config := revel.Config
dbname, _ := config.String("db.dbname")
host, _ := revel.Config.String("db.host")
port, _ := revel.Config.String("db.port")
@ -318,20 +320,21 @@ func (this *ConfigService) Backup(remark string) (ok bool, msg string) {
msg = fmt.Sprintf("%v", err)
return
}
cmd := exec.Command("/bin/sh", "-c", binPath)
Log(binPath);
Log(binPath)
b, err := cmd.Output()
if err != nil {
msg = fmt.Sprintf("%v", err)
if err != nil {
msg = fmt.Sprintf("%v", err)
ok = false
Log("error:......")
Log(string(b))
return
}
Log("error:......")
Log(string(b))
return
}
ok = configService.AddBackup(dir, remark)
return ok, msg
return ok, msg
}
// 还原
func (this *ConfigService) Restore(createdTime string) (ok bool, msg string) {
backups := this.GetGlobalArrMapConfig("backups") // [{}, {}]
@ -339,22 +342,22 @@ func (this *ConfigService) Restore(createdTime string) (ok bool, msg string) {
var backup map[string]string
for i, backup = range backups {
if backup["createdTime"] == createdTime {
break;
break
}
}
if i == len(backups) {
return false, "Backup Not Found"
}
// 先备份当前
ok, msg = this.Backup("Auto backup when restore from " + backup["createdTime"] )
ok, msg = this.Backup("Auto backup when restore from " + backup["createdTime"])
if !ok {
return
}
// mongorestore -h localhost -d leanote --directoryperdb /home/user1/gopackage/src/github.com/leanote/leanote/mongodb_backup/leanote_install_data/
binPath := configService.GetGlobalStringConfig("mongorestorePath")
config := revel.Config;
config := revel.Config
dbname, _ := config.String("db.dbname")
host, _ := revel.Config.String("db.host")
port, _ := revel.Config.String("db.port")
@ -365,26 +368,26 @@ func (this *ConfigService) Restore(createdTime string) (ok bool, msg string) {
if username != "" {
binPath += " -u " + username + " -p " + password
}
path := backup["path"] + "/" + dbname
// 判断路径是否存在
if !IsDirExists(path) {
return false, path + " Is Not Exists"
}
binPath += " " + path
cmd := exec.Command("/bin/sh", "-c", binPath)
Log(binPath);
Log(binPath)
b, err := cmd.Output()
if err != nil {
msg = fmt.Sprintf("%v", err)
if err != nil {
msg = fmt.Sprintf("%v", err)
ok = false
Log("error:......")
Log(string(b))
return
}
Log("error:......")
Log(string(b))
return
}
return true, ""
}
func (this *ConfigService) DeleteBackup(createdTime string) (bool, string) {
@ -393,22 +396,22 @@ func (this *ConfigService) DeleteBackup(createdTime string) (bool, string) {
var backup map[string]string
for i, backup = range backups {
if backup["createdTime"] == createdTime {
break;
break
}
}
if i == len(backups) {
return false, "Backup Not Found"
}
// 删除文件夹之
err := os.RemoveAll(backups[i]["path"])
if err != nil {
return false, fmt.Sprintf("%v", err)
}
// 删除之
backups = append(backups[0:i], backups[i+1:]...)
ok := this.UpdateGlobalArrMapConfig(this.adminUserId, "backups", backups)
return ok, ""
}
@ -419,14 +422,14 @@ func (this *ConfigService) UpdateBackupRemark(createdTime, remark string) (bool,
var backup map[string]string
for i, backup = range backups {
if backup["createdTime"] == createdTime {
break;
break
}
}
if i == len(backups) {
return false, "Backup Not Found"
}
backup["remark"] = remark;
backup["remark"] = remark
ok := this.UpdateGlobalArrMapConfig(this.adminUserId, "backups", backups)
return ok, ""
}
@ -438,7 +441,7 @@ func (this *ConfigService) GetBackup(createdTime string) (map[string]string, boo
var backup map[string]string
for i, backup = range backups {
if backup["createdTime"] == createdTime {
break;
break
}
}
if i == len(backups) {
@ -456,15 +459,15 @@ var port string
func init() {
revel.OnAppStart(func() {
/*
不用配置的, 因为最终通过命令可以改, 而且有的使用nginx代理
port = strconv.Itoa(revel.HttpPort)
if port != "80" {
port = ":" + port
} else {
port = "";
}
不用配置的, 因为最终通过命令可以改, 而且有的使用nginx代理
port = strconv.Itoa(revel.HttpPort)
if port != "80" {
port = ":" + port
} else {
port = "";
}
*/
siteUrl, _ := revel.Config.String("site.url") // 已包含:9000, http, 去掉成 leanote.com
if strings.HasPrefix(siteUrl, "http://") {
defaultDomain = siteUrl[len("http://"):]
@ -472,7 +475,7 @@ func init() {
defaultDomain = siteUrl[len("https://"):]
schema = "https://"
}
// port localhost:9000
ports := strings.Split(defaultDomain, ":")
if len(ports) == 2 {
@ -487,49 +490,53 @@ func init() {
}
func (this *ConfigService) GetSchema() string {
return schema;
return schema
}
// 默认
func (this *ConfigService) GetDefaultDomain() string {
return defaultDomain
}
// 包含http://
func (this *ConfigService) GetDefaultUrl() string {
return schema + defaultDomain
}
// note
func (this *ConfigService) GetNoteDomain() string {
subDomain := this.GetGlobalStringConfig("noteSubDomain");
subDomain := this.GetGlobalStringConfig("noteSubDomain")
if subDomain != "" {
return subDomain + port
}
return this.GetDefaultDomain() + "/note"
}
func (this *ConfigService) GetNoteUrl() string {
return schema + this.GetNoteDomain();
return schema + this.GetNoteDomain()
}
// blog
func (this *ConfigService) GetBlogDomain() string {
subDomain := this.GetGlobalStringConfig("blogSubDomain");
subDomain := this.GetGlobalStringConfig("blogSubDomain")
if subDomain != "" {
return subDomain + port
}
return this.GetDefaultDomain() + "/blog"
}
func (this *ConfigService) GetBlogUrl() string {
return schema + this.GetBlogDomain();
return schema + this.GetBlogDomain()
}
// lea
func (this *ConfigService) GetLeaDomain() string {
subDomain := this.GetGlobalStringConfig("leaSubDomain");
subDomain := this.GetGlobalStringConfig("leaSubDomain")
if subDomain != "" {
return subDomain + port
}
return this.GetDefaultDomain() + "/lea"
}
func (this *ConfigService) GetLeaUrl() string {
return schema + this.GetLeaDomain();
return schema + this.GetLeaDomain()
}
func (this *ConfigService) GetUserUrl(domain string) string {
@ -543,6 +550,7 @@ func (this *ConfigService) GetUserSubUrl(subDomain string) string {
func (this *ConfigService) AllowCustomDomain() bool {
return configService.GetGlobalStringConfig("allowCustomDomain") != ""
}
// 是否是好的自定义域名
func (this *ConfigService) IsGoodCustomDomain(domain string) bool {
blacks := this.GetGlobalArrayConfig("blackCustomDomains")
@ -567,20 +575,21 @@ func (this *ConfigService) IsGoodSubDomain(domain string) bool {
// 上传大小
func (this *ConfigService) GetUploadSize(key string) float64 {
f, _ := strconv.ParseFloat(this.GetGlobalStringConfig(key), 64)
return f;
return f
}
func (this *ConfigService) GetUploadSizeLimit() map[string]float64 {
return map[string]float64{
"uploadImageSize": this.GetUploadSize("uploadImageSize"),
"uploadBlogLogoSize":this.GetUploadSize("uploadBlogLogoSize"),
"uploadAttachSize":this.GetUploadSize("uploadAttachSize"),
"uploadAvatarSize":this.GetUploadSize("uploadAvatarSize"),
"uploadImageSize": this.GetUploadSize("uploadImageSize"),
"uploadBlogLogoSize": this.GetUploadSize("uploadBlogLogoSize"),
"uploadAttachSize": this.GetUploadSize("uploadAttachSize"),
"uploadAvatarSize": this.GetUploadSize("uploadAvatarSize"),
}
}
// 为用户得到全局的配置
// NoteController调用
func (this *ConfigService) GetGlobalConfigForUser() map[string]interface{} {
uploadSizeConfigs := this.GetUploadSizeLimit();
uploadSizeConfigs := this.GetUploadSizeLimit()
config := map[string]interface{}{}
for k, v := range uploadSizeConfigs {
config[k] = v

View File

@ -1,17 +1,17 @@
package service
import (
"github.com/leanote/leanote/app/info"
"bytes"
"fmt"
"github.com/leanote/leanote/app/db"
"github.com/leanote/leanote/app/info"
. "github.com/leanote/leanote/app/lea"
"gopkg.in/mgo.v2/bson"
"time"
"strings"
"html/template"
"net/smtp"
"strconv"
"fmt"
"html/template"
"bytes"
"strings"
"time"
)
// 发送邮件
@ -20,7 +20,7 @@ type EmailService struct {
tpls map[string]*template.Template
}
func NewEmailService() (*EmailService) {
func NewEmailService() *EmailService {
return &EmailService{tpls: map[string]*template.Template{}}
}
@ -39,32 +39,32 @@ func InitEmailFromDb() {
func (this *EmailService) SendEmail(to, subject, body string) (ok bool, e string) {
InitEmailFromDb()
if host == "" || emailPort == "" || username == "" || password == "" {
return
return
}
hp := strings.Split(host, ":")
auth := smtp.PlainAuth("", username, password, hp[0])
var content_type string
mailtype := "html"
if mailtype == "html" {
content_type = "Content-Type: text/"+ mailtype + "; charset=UTF-8"
} else{
content_type = "Content-Type: text/" + mailtype + "; charset=UTF-8"
} else {
content_type = "Content-Type: text/plain" + "; charset=UTF-8"
}
msg := []byte("To: " + to + "\r\nFrom: " + username + "<"+ username +">\r\nSubject: " + subject + "\r\n" + content_type + "\r\n\r\n" + body)
msg := []byte("To: " + to + "\r\nFrom: " + username + "<" + username + ">\r\nSubject: " + subject + "\r\n" + content_type + "\r\n\r\n" + body)
send_to := strings.Split(to, ";")
err := smtp.SendMail(host+":"+emailPort, auth, username, send_to, msg)
if err != nil {
e = fmt.Sprint(err)
return
return
}
ok = true
return
return
}
// AddUser调用
@ -74,20 +74,20 @@ func (this *EmailService) RegisterSendActiveEmail(userInfo info.User, email stri
if token == "" {
return false
}
subject := configService.GetGlobalStringConfig("emailTemplateRegisterSubject");
tpl := configService.GetGlobalStringConfig("emailTemplateRegister");
if(tpl == "") {
subject := configService.GetGlobalStringConfig("emailTemplateRegisterSubject")
tpl := configService.GetGlobalStringConfig("emailTemplateRegister")
if tpl == "" {
return false
}
tokenUrl := configService.GetSiteUrl() + "/user/activeEmail?token=" + token
// {siteUrl} {tokenUrl} {token} {tokenTimeout} {user.id} {user.email} {user.username}
token2Value := map[string]interface{}{"siteUrl": configService.GetSiteUrl(), "tokenUrl": tokenUrl, "token": token, "tokenTimeout": strconv.Itoa(int(tokenService.GetOverHours(info.TokenActiveEmail))),
"user": map[string]interface{}{
"userId": userInfo.UserId.Hex(),
"email": userInfo.Email,
"userId": userInfo.UserId.Hex(),
"email": userInfo.Email,
"username": userInfo.Username,
},
}
@ -97,7 +97,7 @@ func (this *EmailService) RegisterSendActiveEmail(userInfo info.User, email stri
if !ok {
return false
}
// 发送邮件
ok, _ = this.SendEmail(email, subject, tpl)
return ok
@ -113,66 +113,66 @@ func (this *EmailService) UpdateEmailSendActiveEmail(userInfo info.User, email s
}
token := tokenService.NewToken(userInfo.UserId.Hex(), email, info.TokenUpdateEmail)
if token == "" {
return
}
subject := configService.GetGlobalStringConfig("emailTemplateUpdateEmailSubject");
tpl := configService.GetGlobalStringConfig("emailTemplateUpdateEmail");
subject := configService.GetGlobalStringConfig("emailTemplateUpdateEmailSubject")
tpl := configService.GetGlobalStringConfig("emailTemplateUpdateEmail")
// 发送邮件
tokenUrl := configService.GetSiteUrl() + "/user/updateEmail?token=" + token
// {siteUrl} {tokenUrl} {token} {tokenTimeout} {user.userId} {user.email} {user.username}
token2Value := map[string]interface{}{"siteUrl": configService.GetSiteUrl(), "tokenUrl": tokenUrl, "token": token, "tokenTimeout": strconv.Itoa(int(tokenService.GetOverHours(info.TokenActiveEmail))),
"newEmail": email,
"user": map[string]interface{}{
"userId": userInfo.UserId.Hex(),
"email": userInfo.Email,
"userId": userInfo.UserId.Hex(),
"email": userInfo.Email,
"username": userInfo.Username,
},
}
ok, msg, subject, tpl = this.renderEmail(subject, tpl, token2Value)
if !ok {
return
return
}
// 发送邮件
ok, msg = this.SendEmail(email, subject, tpl)
return
}
func (this *EmailService) FindPwdSendEmail(token, email string) (ok bool, msg string) {
subject := configService.GetGlobalStringConfig("emailTemplateFindPasswordSubject");
tpl := configService.GetGlobalStringConfig("emailTemplateFindPassword");
subject := configService.GetGlobalStringConfig("emailTemplateFindPasswordSubject")
tpl := configService.GetGlobalStringConfig("emailTemplateFindPassword")
// 发送邮件
tokenUrl := configService.GetSiteUrl() + "/findPassword/" + token
// {siteUrl} {tokenUrl} {token} {tokenTimeout} {user.id} {user.email} {user.username}
token2Value := map[string]interface{}{"siteUrl": configService.GetSiteUrl(), "tokenUrl": tokenUrl,
token2Value := map[string]interface{}{"siteUrl": configService.GetSiteUrl(), "tokenUrl": tokenUrl,
"token": token, "tokenTimeout": strconv.Itoa(int(tokenService.GetOverHours(info.TokenActiveEmail)))}
ok, msg, subject, tpl = this.renderEmail(subject, tpl, token2Value)
if !ok {
return
return
}
// 发送邮件
ok, msg = this.SendEmail(email, subject, tpl)
return
return
}
// 发送邀请链接
func (this *EmailService) SendInviteEmail(userInfo info.User, email, content string) bool {
subject := configService.GetGlobalStringConfig("emailTemplateInviteSubject");
tpl := configService.GetGlobalStringConfig("emailTemplateInvite");
subject := configService.GetGlobalStringConfig("emailTemplateInviteSubject")
tpl := configService.GetGlobalStringConfig("emailTemplateInvite")
token2Value := map[string]interface{}{"siteUrl": configService.GetSiteUrl(),
"registerUrl": configService.GetSiteUrl() + "/register?from=" + userInfo.Username,
"content": content,
"content": content,
"user": map[string]interface{}{
"username": userInfo.Username,
"email": userInfo.Email,
"email": userInfo.Email,
},
}
var ok bool
@ -187,32 +187,32 @@ func (this *EmailService) SendInviteEmail(userInfo info.User, email, content str
// 发送评论
func (this *EmailService) SendCommentEmail(note info.Note, comment info.BlogComment, userId, content string) bool {
subject := configService.GetGlobalStringConfig("emailTemplateCommentSubject");
tpl := configService.GetGlobalStringConfig("emailTemplateComment");
subject := configService.GetGlobalStringConfig("emailTemplateCommentSubject")
tpl := configService.GetGlobalStringConfig("emailTemplateComment")
// title := "评论提醒"
/*
toUserId := note.UserId.Hex()
// title := "评论提醒"
// 表示回复回复的内容, 那么发送给之前回复的
if comment.CommentId != "" {
toUserId = comment.UserId.Hex()
}
toUserInfo := userService.GetUserInfo(toUserId)
sendUserInfo := userService.GetUserInfo(userId)
subject := note.Title + " 收到 " + sendUserInfo.Username + " 的评论";
if comment.CommentId != "" {
subject = "您在 " + note.Title + " 发表的评论收到 " + sendUserInfo.Username;
if userId == note.UserId.Hex() {
subject += "(作者)";
toUserId := note.UserId.Hex()
// title := "评论提醒"
// 表示回复回复的内容, 那么发送给之前回复的
if comment.CommentId != "" {
toUserId = comment.UserId.Hex()
}
toUserInfo := userService.GetUserInfo(toUserId)
sendUserInfo := userService.GetUserInfo(userId)
subject := note.Title + " 收到 " + sendUserInfo.Username + " 的评论";
if comment.CommentId != "" {
subject = "您在 " + note.Title + " 发表的评论收到 " + sendUserInfo.Username;
if userId == note.UserId.Hex() {
subject += "(作者)";
}
subject += " 的评论";
}
subject += " 的评论";
}
*/
toUserId := note.UserId.Hex()
// 表示回复回复的内容, 那么发送给之前回复的
if comment.CommentId != "" {
@ -220,28 +220,28 @@ func (this *EmailService) SendCommentEmail(note info.Note, comment info.BlogComm
}
toUserInfo := userService.GetUserInfo(toUserId) // 被评论者
sendUserInfo := userService.GetUserInfo(userId) // 评论者
// {siteUrl} {blogUrl}
// {siteUrl} {blogUrl}
// {blog.id} {blog.title} {blog.url}
// {commentUser.userId} {commentUser.username} {commentUser.email}
// {commentUser.userId} {commentUser.username} {commentUser.email}
// {commentedUser.userId} {commentedUser.username} {commentedUser.email}
token2Value := map[string]interface{}{"siteUrl": configService.GetSiteUrl(), "blogUrl": configService.GetBlogUrl(),
"blog": map[string]string{
"id": note.NoteId.Hex(),
"id": note.NoteId.Hex(),
"title": note.Title,
"url": configService.GetBlogUrl() + "/view/" + note.NoteId.Hex(),
"url": configService.GetBlogUrl() + "/view/" + note.NoteId.Hex(),
},
"commentContent": content,
// 评论者信息
"commentUser": map[string]interface{}{"userId": sendUserInfo.UserId.Hex(),
"username": sendUserInfo.Username,
"email": sendUserInfo.Email,
"commentUser": map[string]interface{}{"userId": sendUserInfo.UserId.Hex(),
"username": sendUserInfo.Username,
"email": sendUserInfo.Email,
"isBlogAuthor": userId == note.UserId.Hex(),
},
// 被评论者信息
"commentedUser": map[string]interface{}{"userId": toUserId,
"username": toUserInfo.Username,
"email": toUserInfo.Email,
"username": toUserInfo.Username,
"email": toUserInfo.Email,
"isBlogAuthor": toUserId == note.UserId.Hex(),
},
}
@ -251,53 +251,52 @@ func (this *EmailService) SendCommentEmail(note info.Note, comment info.BlogComm
if !ok {
return false
}
// 发送邮件
ok, _ = this.SendEmail(toUserInfo.Email, subject, tpl)
return ok
}
// 验证模板是否正确
func (this *EmailService) ValidTpl(str string) (ok bool, msg string){
defer func() {
func (this *EmailService) ValidTpl(str string) (ok bool, msg string) {
defer func() {
if err := recover(); err != nil {
ok = false
msg = fmt.Sprint(err)
}
}();
header := configService.GetGlobalStringConfig("emailTemplateHeader");
footer := configService.GetGlobalStringConfig("emailTemplateFooter");
}()
header := configService.GetGlobalStringConfig("emailTemplateHeader")
footer := configService.GetGlobalStringConfig("emailTemplateFooter")
str = strings.Replace(str, "{{header}}", header, -1)
str = strings.Replace(str, "{{footer}}", footer, -1)
_, err := template.New("tpl name").Parse(str)
if err != nil {
if err != nil {
msg = fmt.Sprint(err)
return
}
ok = true
return
}
ok = true
return
}
// ok, msg, subject, tpl
func (this *EmailService) getTpl(str string) (ok bool, msg string, tpl *template.Template){
defer func() {
func (this *EmailService) getTpl(str string) (ok bool, msg string, tpl *template.Template) {
defer func() {
if err := recover(); err != nil {
ok = false
msg = fmt.Sprint(err)
}
}();
}()
var err error
var has bool
if tpl, has = this.tpls[str]; !has {
tpl, err = template.New("tpl name").Parse(str)
if err != nil {
tpl, err = template.New("tpl name").Parse(str)
if err != nil {
msg = fmt.Sprint(err)
return
}
this.tpls[str] = tpl
return
}
this.tpls[str] = tpl
}
ok = true
return
@ -310,67 +309,67 @@ func (this *EmailService) renderEmail(subject, body string, values map[string]in
defer func() { // 必须要先声明defer否则不能捕获到panic异常
if err := recover(); err != nil {
ok = false
msg = fmt.Sprint(err) // 这里的err其实就是panic传入的内容
msg = fmt.Sprint(err) // 这里的err其实就是panic传入的内容
}
}();
}()
var tpl *template.Template
values["siteUrl"] = configService.GetSiteUrl();
values["siteUrl"] = configService.GetSiteUrl()
// subject
if subject != "" {
ok, msg, tpl = this.getTpl(subject)
if(!ok) {
if !ok {
return
}
var buffer bytes.Buffer
err := tpl.Execute(&buffer, values)
if err != nil {
err := tpl.Execute(&buffer, values)
if err != nil {
msg = fmt.Sprint(err)
return
}
o = buffer.String()
} else {
o = ""
}
// content
header := configService.GetGlobalStringConfig("emailTemplateHeader");
footer := configService.GetGlobalStringConfig("emailTemplateFooter");
}
o = buffer.String()
} else {
o = ""
}
// content
header := configService.GetGlobalStringConfig("emailTemplateHeader")
footer := configService.GetGlobalStringConfig("emailTemplateFooter")
body = strings.Replace(body, "{{header}}", header, -1)
body = strings.Replace(body, "{{footer}}", footer, -1)
values["subject"] = o
ok, msg, tpl = this.getTpl(body)
if(!ok) {
if !ok {
return
}
var buffer2 bytes.Buffer
err := tpl.Execute(&buffer2, values)
if err != nil {
err := tpl.Execute(&buffer2, values)
if err != nil {
msg = fmt.Sprint(err)
return
}
b = buffer2.String()
return
}
b = buffer2.String()
return
}
// 发送email给用户
// 需要记录
func (this *EmailService) SendEmailToUsers(users []info.User, subject, body string) (ok bool, msg string) {
if(users == nil || len(users) == 0) {
if users == nil || len(users) == 0 {
msg = "no users"
return
return
}
// 尝试renderHtml
ok, msg, _, _ = this.renderEmail(subject, body, map[string]interface{}{})
if(!ok) {
if !ok {
Log(msg)
return
return
}
go func() {
for _, user := range users {
LogJ(user)
@ -381,8 +380,8 @@ func (this *EmailService) SendEmailToUsers(users []info.User, subject, body stri
ok2, msg2, subject2, body2 := this.renderEmail(subject, body, m)
ok = ok2
msg = msg2
if(ok2) {
sendOk, msg := this.SendEmail(user.Email, subject2, body2);
if ok2 {
sendOk, msg := this.SendEmail(user.Email, subject2, body2)
this.AddEmailLog(user.Email, subject, body, sendOk, msg) // 把模板记录下
// 记录到Email Log
if sendOk {
@ -395,47 +394,47 @@ func (this *EmailService) SendEmailToUsers(users []info.User, subject, body stri
}
}
}()
return
return
}
func (this *EmailService) SendEmailToEmails(emails []string, subject, body string) (ok bool, msg string) {
if(emails == nil || len(emails) == 0) {
if emails == nil || len(emails) == 0 {
msg = "no emails"
return
return
}
// 尝试renderHtml
ok, msg, _, _ = this.renderEmail(subject, body, map[string]interface{}{})
if(!ok) {
if !ok {
Log(msg)
return
return
}
// go func() {
for _, email := range emails {
if email == "" {
continue
}
m := map[string]interface{}{}
m["email"] = email
ok, msg, subject, body = this.renderEmail(subject, body, m)
if(ok) {
sendOk, msg := this.SendEmail(email, subject, body);
this.AddEmailLog(email, subject, body, sendOk, msg)
// 记录到Email Log
if sendOk {
Log("ok " + email)
} else {
Log("no " + email)
}
} else {
Log(msg);
}
// go func() {
for _, email := range emails {
if email == "" {
continue
}
// }()
return
m := map[string]interface{}{}
m["email"] = email
ok, msg, subject, body = this.renderEmail(subject, body, m)
if ok {
sendOk, msg := this.SendEmail(email, subject, body)
this.AddEmailLog(email, subject, body, sendOk, msg)
// 记录到Email Log
if sendOk {
Log("ok " + email)
} else {
Log("no " + email)
}
} else {
Log(msg)
}
}
// }()
return
}
// 添加邮件日志
@ -443,6 +442,7 @@ func (this *EmailService) AddEmailLog(email, subject, body string, ok bool, msg
log := info.EmailLog{LogId: bson.NewObjectId(), Email: email, Subject: subject, Body: body, Ok: ok, Msg: msg, CreatedTime: time.Now()}
db.Insert(db.EmailLogs, log)
}
// 展示邮件日志
func (this *EmailService) DeleteEmails(ids []string) bool {
@ -451,7 +451,7 @@ func (this *EmailService) DeleteEmails(ids []string) bool {
idsO[i] = bson.ObjectIdHex(id)
}
db.DeleteAll(db.EmailLogs, bson.M{"_id": bson.M{"$in": idsO}})
return true
}
func (this *EmailService) ListEmailLogs(pageNumber, pageSize int, sortField string, isAsc bool, email string) (page info.Page, emailLogs []info.EmailLog) {
@ -461,7 +461,7 @@ func (this *EmailService) ListEmailLogs(pageNumber, pageSize int, sortField stri
if email != "" {
query["Email"] = bson.M{"$regex": bson.RegEx{".*?" + email + ".*", "i"}}
}
q := db.EmailLogs.Find(query);
q := db.EmailLogs.Find(query)
// 总记录数
count, _ := q.Count()
// 列表
@ -471,4 +471,4 @@ func (this *EmailService) ListEmailLogs(pageNumber, pageSize int, sortField stri
All(&emailLogs)
page = info.NewPage(pageNumber, pageSize, count, nil)
return
}
}

View File

@ -30,7 +30,7 @@ func (this *FileService) AddImage(image info.File, albumId, userId string, needC
image.IsDefaultAlbum = true
}
image.UserId = bson.ObjectIdHex(userId)
ok = db.Insert(db.Files, image)
return
}
@ -40,28 +40,28 @@ func (this *FileService) AddImage(image info.File, albumId, userId string, needC
func (this *FileService) ListImagesWithPage(userId, albumId, key string, pageNumber, pageSize int) info.Page {
skipNum, sortFieldR := parsePageAndSort(pageNumber, pageSize, "CreatedTime", false)
files := []info.File{}
q := bson.M{"UserId": bson.ObjectIdHex(userId), "Type": ""} // life
if albumId != "" {
q["AlbumId"] = bson.ObjectIdHex(albumId);
q["AlbumId"] = bson.ObjectIdHex(albumId)
} else {
q["IsDefaultAlbum"] = true
}
if key != "" {
q["Title"] = bson.M{"$regex": bson.RegEx{".*?" + key + ".*", "i"}}
q["Title"] = bson.M{"$regex": bson.RegEx{".*?" + key + ".*", "i"}}
}
// LogJ(q)
count := db.Count(db.Files, q);
// LogJ(q)
count := db.Count(db.Files, q)
db.Files.
Find(q).
Sort(sortFieldR).
Skip(skipNum).
Limit(pageSize).
All(&files)
return info.Page{Count: count, List: files}
}
@ -75,12 +75,12 @@ func (this *FileService) GetAllImageNamesMap(userId string) (m map[string]bool)
q := bson.M{"UserId": bson.ObjectIdHex(userId)}
files := []info.File{}
db.ListByQWithFields(db.Files, q, []string{"Name"}, &files)
m = make(map[string]bool)
if len(files) == 0 {
return
}
for _, file := range files {
m[file.Name] = true
}
@ -91,8 +91,8 @@ func (this *FileService) GetAllImageNamesMap(userId string) (m map[string]bool)
func (this *FileService) DeleteImage(userId, fileId string) (bool, string) {
file := info.File{}
db.GetByIdAndUserId(db.Files, fileId, userId, &file)
if(file.FileId != "") {
if file.FileId != "" {
if db.DeleteByIdAndUserId(db.Files, fileId, userId) {
// delete image
// TODO
@ -173,63 +173,63 @@ func (this *FileService) GetFile(userId, fileId string) string {
if fileId == "" {
return ""
}
file := info.File{}
db.Get(db.Files, fileId, &file)
path := file.Path
if path == "" {
return ""
}
// 1. 判断权限
// 是否是我的文件
if userId != "" && file.UserId.Hex() == userId {
return path
}
// 得到使用过该fileId的所有笔记NoteId
// 这些笔记是否有public的, 若有则ok
// 这些笔记(笔记本)是否有共享给我的, 若有则ok
noteIds := noteImageService.GetNoteIds(fileId)
if noteIds != nil && len(noteIds) > 0 {
// 这些笔记是否有public的
if db.Has(db.Notes, bson.M{"_id": bson.M{"$in": noteIds}, "IsBlog": true}) {
return path
}
// 2014/12/28 修复, 如果是分享给用户组, 那就不行, 这里可以实现
for _, noteId := range noteIds {
note := noteService.GetNoteById(noteId.Hex())
if shareService.HasReadPerm(note.UserId.Hex(), userId, noteId.Hex()) {
return path;
}
}
/*
// 若有共享给我的笔记?
// 对该笔记可读?
if db.Has(db.ShareNotes, bson.M{"ToUserId": bson.ObjectIdHex(userId), "NoteId": bson.M{"$in": noteIds}}) {
return path
}
// 笔记本是否共享给我?
// 通过笔记得到笔记本
notes := []info.Note{}
db.ListByQWithFields(db.Notes, bson.M{"_id": bson.M{"$in": noteIds}}, []string{"NotebookId"}, &notes)
if notes != nil && len(notes) > 0 {
notebookIds := make([]bson.ObjectId, len(notes))
for i := 0; i < len(notes); i++ {
notebookIds[i] = notes[i].NotebookId
}
if db.Has(db.ShareNotebooks, bson.M{"ToUserId": bson.ObjectIdHex(userId), "NotebookId": bson.M{"$in": notebookIds}}) {
return path
}
}
/*
// 若有共享给我的笔记?
// 对该笔记可读?
if db.Has(db.ShareNotes, bson.M{"ToUserId": bson.ObjectIdHex(userId), "NoteId": bson.M{"$in": noteIds}}) {
return path
}
// 笔记本是否共享给我?
// 通过笔记得到笔记本
notes := []info.Note{}
db.ListByQWithFields(db.Notes, bson.M{"_id": bson.M{"$in": noteIds}}, []string{"NotebookId"}, &notes)
if notes != nil && len(notes) > 0 {
notebookIds := make([]bson.ObjectId, len(notes))
for i := 0; i < len(notes); i++ {
notebookIds[i] = notes[i].NotebookId
}
if db.Has(db.ShareNotebooks, bson.M{"ToUserId": bson.ObjectIdHex(userId), "NotebookId": bson.M{"$in": notebookIds}}) {
return path
}
}
*/
}
// 可能是刚复制到owner上, 但内容又没有保存, 所以没有note->imageId的映射, 此时看是否有fromFileId
if file.FromFileId != "" {
fromFile := info.File{}
@ -238,7 +238,7 @@ func (this *FileService) GetFile(userId, fileId string) string {
return fromFile.Path
}
}
return ""
}
@ -248,44 +248,44 @@ func (this *FileService) CopyImage(userId, fileId, toUserId string) (bool, strin
file2 := info.File{}
db.GetByQ(db.Files, bson.M{"UserId": bson.ObjectIdHex(toUserId), "FromFileId": bson.ObjectIdHex(fileId)}, &file2)
if file2.FileId != "" {
return true, file2.FileId.Hex();
return true, file2.FileId.Hex()
}
// 复制之
file := info.File{}
db.GetByIdAndUserId(db.Files, fileId, userId, &file)
if file.FileId == "" || file.UserId.Hex() != userId {
return false, ""
}
_, ext := SplitFilename(file.Name)
newFilename := NewGuid() + ext
dir := "files/" + toUserId + "/images"
filePath := dir + "/" + newFilename
err := os.MkdirAll(dir, 0755)
if err != nil {
return false, ""
}
_, err = CopyFile(revel.BasePath + "/" + file.Path, revel.BasePath + "/" + filePath)
_, err = CopyFile(revel.BasePath+"/"+file.Path, revel.BasePath+"/"+filePath)
if err != nil {
Log(err)
return false, ""
}
fileInfo := info.File{Name: newFilename,
Title: file.Title,
Path: filePath,
Size: file.Size,
Title: file.Title,
Path: filePath,
Size: file.Size,
FromFileId: file.FileId}
id := bson.NewObjectId();
id := bson.NewObjectId()
fileInfo.FileId = id
fileId = id.Hex()
Ok, _ := this.AddImage(fileInfo, "", toUserId, false)
if Ok {
return Ok, id.Hex()
}
@ -296,7 +296,7 @@ func (this *FileService) CopyImage(userId, fileId, toUserId string) (bool, strin
func (this *FileService) IsMyFile(userId, fileId string) bool {
// 如果有问题会panic
if !bson.IsObjectIdHex(fileId) || !bson.IsObjectIdHex(userId) {
return false;
return false
}
return db.Has(db.Files, bson.M{"UserId": bson.ObjectIdHex(userId), "_id": bson.ObjectIdHex(fileId)})
}

View File

@ -1,12 +1,12 @@
package service
import (
"github.com/leanote/leanote/app/info"
"github.com/leanote/leanote/app/db"
// . "github.com/leanote/leanote/app/lea"
"github.com/leanote/leanote/app/info"
// . "github.com/leanote/leanote/app/lea"
"gopkg.in/mgo.v2/bson"
"time"
// "strings"
// "strings"
)
// 用户组, 用户组用户管理
@ -16,34 +16,35 @@ type GroupService struct {
// 添加分组
func (this *GroupService) AddGroup(userId, title string) (bool, info.Group) {
group := info.Group {
GroupId: bson.NewObjectId(),
UserId: bson.ObjectIdHex(userId),
Title: title,
group := info.Group{
GroupId: bson.NewObjectId(),
UserId: bson.ObjectIdHex(userId),
Title: title,
CreatedTime: time.Now(),
}
return db.Insert(db.Groups, group), group
}
// 删除分组
// 判断是否有好友
func (this *GroupService) DeleteGroup(userId, groupId string) (ok bool, msg string) {
/*
if db.Has(db.GroupUsers, bson.M{"GroupId": bson.ObjectIdHex(groupId)}) {
return false, "groupHasUsers"
}
if db.Has(db.GroupUsers, bson.M{"GroupId": bson.ObjectIdHex(groupId)}) {
return false, "groupHasUsers"
}
*/
if !this.isMyGroup(userId, groupId) {
return false, "notMyGroup"
}
// 删除分组后, 需要删除所有用户分享到该组的笔记本, 笔记
shareService.DeleteAllShareNotebookGroup(groupId);
shareService.DeleteAllShareNoteGroup(groupId);
shareService.DeleteAllShareNotebookGroup(groupId)
shareService.DeleteAllShareNoteGroup(groupId)
db.DeleteAll(db.GroupUsers, bson.M{"GroupId": bson.ObjectIdHex(groupId)})
return db.DeleteByIdAndUserId(db.Groups, groupId, userId), ""
// TODO 删除分组后, 在shareNote, shareNotebook中也要删除
}
@ -53,15 +54,15 @@ func (this *GroupService) UpdateGroupTitle(userId, groupId, title string) (ok bo
}
// 得到用户的所有分组(包括下的所有用户)
func (this *GroupService) GetGroupsAndUsers(userId string) ([]info.Group) {
/*
// 得到我的分组
groups := []info.Group{}
db.ListByQ(db.Groups, bson.M{"UserId": bson.ObjectIdHex(userId)}, &groups)
*/
func (this *GroupService) GetGroupsAndUsers(userId string) []info.Group {
/*
// 得到我的分组
groups := []info.Group{}
db.ListByQ(db.Groups, bson.M{"UserId": bson.ObjectIdHex(userId)}, &groups)
*/
// 我的分组, 及我所属的分组
groups := this.GetGroupsContainOf(userId);
groups := this.GetGroupsContainOf(userId)
// 得到其下的用户
for i, group := range groups {
group.Users = this.GetUsers(group.GroupId.Hex())
@ -69,8 +70,9 @@ func (this *GroupService) GetGroupsAndUsers(userId string) ([]info.Group) {
}
return groups
}
// 仅仅得到所有分组
func (this *GroupService) GetGroups(userId string) ([]info.Group) {
func (this *GroupService) GetGroups(userId string) []info.Group {
// 得到分组s
groups := []info.Group{}
db.ListByQ(db.Groups, bson.M{"UserId": bson.ObjectIdHex(userId)}, &groups)
@ -78,24 +80,24 @@ func (this *GroupService) GetGroups(userId string) ([]info.Group) {
}
// 得到我的和我所属组的ids
func (this *GroupService) GetMineAndBelongToGroupIds(userId string) ([]bson.ObjectId) {
func (this *GroupService) GetMineAndBelongToGroupIds(userId string) []bson.ObjectId {
// 所属组
groupIds := this.GetBelongToGroupIds(userId)
m := map[bson.ObjectId]bool{}
for _, groupId := range groupIds {
m[groupId] = true
}
// 我的组
myGroups := this.GetGroups(userId)
for _, group := range myGroups {
if !m[group.GroupId] {
groupIds = append(groupIds, group.GroupId)
}
}
return groupIds
}
@ -105,28 +107,28 @@ func (this *GroupService) GetGroupsContainOf(userId string) []info.Group {
// 我的组
myGroups := this.GetGroups(userId)
myGroupMap := map[bson.ObjectId]bool{}
for _, group := range myGroups {
myGroupMap[group.GroupId] = true
}
// 所属组
groupIds := this.GetBelongToGroupIds(userId)
groups := []info.Group{}
db.ListByQ(db.Groups, bson.M{"_id": bson.M{"$in": groupIds}}, &groups)
for _, group := range groups {
if !myGroupMap[group.GroupId] {
myGroups = append(myGroups, group)
}
}
return myGroups
}
// 得到分组, shareService用
func (this *GroupService) GetGroup(userId, groupId string) (info.Group) {
func (this *GroupService) GetGroup(userId, groupId string) info.Group {
// 得到分组s
group := info.Group{}
db.GetByIdAndUserId(db.Groups, groupId, userId, &group)
@ -134,7 +136,7 @@ func (this *GroupService) GetGroup(userId, groupId string) (info.Group) {
}
// 得到某分组下的用户
func (this *GroupService) GetUsers(groupId string) ([]info.User) {
func (this *GroupService) GetUsers(groupId string) []info.User {
// 得到UserIds
groupUsers := []info.GroupUser{}
db.ListByQWithFields(db.GroupUsers, bson.M{"GroupId": bson.ObjectIdHex(groupId)}, []string{"UserId"}, &groupUsers)
@ -150,7 +152,7 @@ func (this *GroupService) GetUsers(groupId string) ([]info.User) {
}
// 得到我所属的所有分组ids
func (this *GroupService) GetBelongToGroupIds(userId string) ([]bson.ObjectId) {
func (this *GroupService) GetBelongToGroupIds(userId string) []bson.ObjectId {
// 得到UserIds
groupUsers := []info.GroupUser{}
db.ListByQWithFields(db.GroupUsers, bson.M{"UserId": bson.ObjectIdHex(userId)}, []string{"GroupId"}, &groupUsers)
@ -182,23 +184,23 @@ func (this *GroupService) IsExistsGroupUser(userId, groupId string) (ok bool) {
func (this *GroupService) AddUser(ownUserId, groupId, userId string) (ok bool, msg string) {
// groupId是否是ownUserId的?
/*
if !this.IsExistsGroupUser(ownUserId, groupId) {
return false, "forbidden"
}
if !this.IsExistsGroupUser(ownUserId, groupId) {
return false, "forbidden"
}
*/
if !this.isMyGroup(ownUserId, groupId) {
return false, "forbidden"
}
// 是否已存在
if db.Has(db.GroupUsers, bson.M{"GroupId": bson.ObjectIdHex(groupId), "UserId": bson.ObjectIdHex(userId)}) {
return false, "hasUsers"
}
return db.Insert(db.GroupUsers, info.GroupUser{
GroupUserId: bson.NewObjectId(),
GroupId: bson.ObjectIdHex(groupId),
UserId: bson.ObjectIdHex(userId),
GroupId: bson.ObjectIdHex(groupId),
UserId: bson.ObjectIdHex(userId),
CreatedTime: time.Now(),
}), ""
}
@ -207,17 +209,17 @@ func (this *GroupService) AddUser(ownUserId, groupId, userId string) (ok bool, m
func (this *GroupService) DeleteUser(ownUserId, groupId, userId string) (ok bool, msg string) {
// groupId是否是ownUserId的?
/*
if !this.IsExistsGroupUser(ownUserId, groupId) {
return false, "forbidden"
}
if !this.IsExistsGroupUser(ownUserId, groupId) {
return false, "forbidden"
}
*/
if !this.isMyGroup(ownUserId, groupId) {
return false, "forbidden"
}
// 删除该用户分享到本组的笔记本, 笔记
shareService.DeleteShareNotebookGroupWhenDeleteGroupUser(userId, groupId);
shareService.DeleteShareNoteGroupWhenDeleteGroupUser(userId, groupId);
shareService.DeleteShareNotebookGroupWhenDeleteGroupUser(userId, groupId)
shareService.DeleteShareNoteGroupWhenDeleteGroupUser(userId, groupId)
return db.Delete(db.GroupUsers, bson.M{"GroupId": bson.ObjectIdHex(groupId), "UserId": bson.ObjectIdHex(userId)}), ""
}

View File

@ -1,11 +1,11 @@
package service
import (
"github.com/leanote/leanote/app/info"
"github.com/leanote/leanote/app/db"
// . "github.com/leanote/leanote/app/lea"
"github.com/leanote/leanote/app/info"
// . "github.com/leanote/leanote/app/lea"
"gopkg.in/mgo.v2/bson"
// "time"
// "time"
)
// 历史记录
@ -22,7 +22,7 @@ func (this *NoteContentHistoryService) AddHistory(noteId, userId string, eachHis
if eachHistory.Content == "" {
return
}
// 先查是否存在历史记录, 没有则添加之
history := info.NoteContentHistory{}
db.GetByIdAndUserId(db.NoteContentHistories, noteId, userId, &history)
@ -38,8 +38,8 @@ func (this *NoteContentHistoryService) AddHistory(noteId, userId string, eachHis
}
newHistory := []info.EachHistory{eachHistory}
newHistory = append(newHistory, history.Histories...) // 在开头加了, 最近的在最前
history.Histories = newHistory
history.Histories = newHistory
// 更新之
db.UpdateByIdAndUserId(db.NoteContentHistories, noteId, userId, history)
}
@ -48,13 +48,13 @@ func (this *NoteContentHistoryService) AddHistory(noteId, userId string, eachHis
// 新建历史
func (this *NoteContentHistoryService) newHistory(noteId, userId string, eachHistory info.EachHistory) {
history := info.NoteContentHistory{NoteId: bson.ObjectIdHex(noteId),
UserId: bson.ObjectIdHex(userId),
history := info.NoteContentHistory{NoteId: bson.ObjectIdHex(noteId),
UserId: bson.ObjectIdHex(userId),
Histories: []info.EachHistory{eachHistory},
}
// 保存之
db.Insert(db.NoteContentHistories, history)
db.Insert(db.NoteContentHistories, history)
}
// 列表展示

View File

@ -1,22 +1,22 @@
package service
import (
"github.com/leanote/leanote/app/info"
"github.com/leanote/leanote/app/db"
"github.com/leanote/leanote/app/info"
. "github.com/leanote/leanote/app/lea"
"gopkg.in/mgo.v2/bson"
"regexp"
// "time"
// "time"
)
type NoteImageService struct {
}
// 通过id, userId得到noteIds
func (this *NoteImageService) GetNoteIds(imageId string) ([]bson.ObjectId) {
func (this *NoteImageService) GetNoteIds(imageId string) []bson.ObjectId {
noteImages := []info.NoteImage{}
db.ListByQWithFields(db.NoteImages, bson.M{"ImageId": bson.ObjectIdHex(imageId)}, []string{"NoteId"}, &noteImages)
db.ListByQWithFields(db.NoteImages, bson.M{"ImageId": bson.ObjectIdHex(imageId)}, []string{"NoteId"}, &noteImages)
if noteImages != nil && len(noteImages) > 0 {
noteIds := make([]bson.ObjectId, len(noteImages))
cnt := len(noteImages)
@ -25,7 +25,7 @@ func (this *NoteImageService) GetNoteIds(imageId string) ([]bson.ObjectId) {
}
return noteIds
}
return nil
}
@ -67,7 +67,7 @@ func (this *NoteImageService) UpdateNoteImages(userId, noteId, imgSrc, content s
}
}
}
return true
}
@ -101,7 +101,7 @@ func (this *NoteImageService) CopyNoteImages(fromNoteId, fromUserId, newNoteId,
// each = getImage?fileId=541bd2f599c37b4f3r000003
fileId := each[len(each)-24:] // 得到后24位, 也即id
if _, ok := replaceMap[fileId]; !ok {
if bson.IsObjectIdHex(fileId) {
ok2, newImageId := fileService.CopyImage(fromUserId, fileId, toUserId)
@ -123,25 +123,25 @@ func (this *NoteImageService) CopyNoteImages(fromNoteId, fromUserId, newNoteId,
return "getImage?fileId=" + replaceFileId
}
return each
});
})
return content;
return content
}
//
//
func (this *NoteImageService) getImagesByNoteIds(noteIds []bson.ObjectId) map[string][]info.File {
noteNoteImages := []info.NoteImage{}
db.ListByQ(db.NoteImages, bson.M{"NoteId": bson.M{"$in": noteIds}}, &noteNoteImages)
// 得到imageId, 再去files表查所有的Files
imageIds := []bson.ObjectId{}
// 图片1 => N notes
imageIdNotes := map[string][]string{} // imageId => [noteId1, noteId2, ...]
for _, noteImage := range noteNoteImages {
imageId := noteImage.ImageId
imageIds = append(imageIds, imageId)
imageIdHex := imageId.Hex()
noteId := noteImage.NoteId.Hex()
if notes, ok := imageIdNotes[imageIdHex]; ok {
@ -150,11 +150,11 @@ func (this *NoteImageService) getImagesByNoteIds(noteIds []bson.ObjectId) map[st
imageIdNotes[imageIdHex] = []string{noteId}
}
}
// 得到所有files
files := []info.File{}
db.ListByQ(db.Files, bson.M{"_id": bson.M{"$in": imageIds}}, &files)
// 建立note->file关联
noteImages := make(map[string][]info.File)
for _, file := range files {

View File

@ -1,8 +1,8 @@
package service
import (
"github.com/leanote/leanote/app/info"
"github.com/leanote/leanote/app/db"
"github.com/leanote/leanote/app/info"
. "github.com/leanote/leanote/app/lea"
"gopkg.in/mgo.v2/bson"
"time"
@ -17,6 +17,7 @@ func (this *NoteService) GetNote(noteId, userId string) (note info.Note) {
db.GetByIdAndUserId(db.Notes, noteId, userId, &note)
return
}
// fileService调用
// 不能是已经删除了的, life bug, 客户端删除后, 竟然还能在web上打开
func (this *NoteService) GetNoteById(noteId string) (note info.Note) {
@ -35,14 +36,16 @@ func (this *NoteService) GetNoteByIdAndUserId(noteId, userId string) (note info.
db.GetByQ(db.Notes, bson.M{"_id": bson.ObjectIdHex(noteId), "UserId": bson.ObjectIdHex(userId), "IsDeleted": false}, &note)
return
}
// 得到blog, blogService用
// 不要传userId, 因为是公开的
func (this *NoteService) GetBlogNote(noteId string) (note info.Note) {
note = info.Note{}
db.GetByQ(db.Notes, bson.M{"_id": bson.ObjectIdHex(noteId),
db.GetByQ(db.Notes, bson.M{"_id": bson.ObjectIdHex(noteId),
"IsBlog": true, "IsTrash": false, "IsDeleted": false}, &note)
return
}
// 通过id, userId得到noteContent
func (this *NoteService) GetNoteContent(noteContentId, userId string) (noteContent info.NoteContent) {
noteContent = info.NoteContent{}
@ -62,11 +65,11 @@ func (this *NoteService) GetNoteAndContent(noteId, userId string) (noteAndConten
func (this *NoteService) GetSyncNotes(userId string, afterUsn, maxEntry int) []info.ApiNote {
notes := []info.Note{}
q := db.Notes.Find(bson.M{
"UserId": bson.ObjectIdHex(userId),
"Usn": bson.M{"$gt": afterUsn},
});
"UserId": bson.ObjectIdHex(userId),
"Usn": bson.M{"$gt": afterUsn},
})
q.Sort("Usn").Limit(maxEntry).All(&notes)
return this.ToApiNotes(notes)
}
@ -75,7 +78,7 @@ func (this *NoteService) ToApiNotes(notes []info.Note) []info.ApiNote {
// 2, 得到所有图片, 附件信息
// 查images表, attachs表
if len(notes) > 0 {
noteIds := make([]bson.ObjectId, len(notes));
noteIds := make([]bson.ObjectId, len(notes))
for i, note := range notes {
noteIds[i] = note.NoteId
}
@ -92,24 +95,23 @@ func (this *NoteService) ToApiNotes(notes []info.Note) []info.ApiNote {
return []info.ApiNote{}
}
// note与apiNote的转换
func (this *NoteService) ToApiNote(note *info.Note, files []info.NoteFile) info.ApiNote {
apiNote := info.ApiNote{
NoteId: note.NoteId.Hex(),
NotebookId: note.NotebookId.Hex(),
UserId : note.UserId.Hex(),
Title : note.Title,
Tags : note.Tags,
IsMarkdown : note.IsMarkdown,
IsBlog : note.IsBlog,
IsTrash : note.IsTrash,
IsDeleted : note.IsDeleted,
Usn : note.Usn,
CreatedTime : note.CreatedTime,
UpdatedTime : note.UpdatedTime,
PublicTime : note.PublicTime,
Files: files,
NoteId: note.NoteId.Hex(),
NotebookId: note.NotebookId.Hex(),
UserId: note.UserId.Hex(),
Title: note.Title,
Tags: note.Tags,
IsMarkdown: note.IsMarkdown,
IsBlog: note.IsBlog,
IsTrash: note.IsTrash,
IsDeleted: note.IsDeleted,
Usn: note.Usn,
CreatedTime: note.CreatedTime,
UpdatedTime: note.UpdatedTime,
PublicTime: note.PublicTime,
Files: files,
}
return apiNote
}
@ -121,11 +123,11 @@ func (this *NoteService) ToApiNote(note *info.Note, files []info.NoteFile) info.
// 查images表, attachs表
// [待测]
func (this *NoteService) getFiles(noteIds []bson.ObjectId) map[string][]info.NoteFile {
noteImages := noteImageService.getImagesByNoteIds(noteIds);
noteImages := noteImageService.getImagesByNoteIds(noteIds)
noteAttachs := attachService.getAttachsByNoteIds(noteIds)
noteFilesMap := map[string][]info.NoteFile{}
for _, noteId := range noteIds {
noteIdHex := noteId.Hex()
noteFiles := []info.NoteFile{}
@ -134,36 +136,36 @@ func (this *NoteService) getFiles(noteIds []bson.ObjectId) map[string][]info.Not
for _, image := range images {
noteFiles = append(noteFiles, info.NoteFile{
FileId: image.FileId.Hex(),
Type: image.Type,
});
Type: image.Type,
})
}
}
// attach
if attachs, ok := noteAttachs[noteIdHex]; ok {
for _, attach := range attachs {
noteFiles = append(noteFiles, info.NoteFile{
FileId: attach.AttachId.Hex(),
Type: attach.Type,
Title: attach.Title,
FileId: attach.AttachId.Hex(),
Type: attach.Type,
Title: attach.Title,
IsAttach: true,
});
})
}
}
noteFilesMap[noteIdHex] = noteFiles
}
return noteFilesMap
}
// 列出note, 排序规则, 还有分页
// CreatedTime, UpdatedTime, title 来排序
func (this *NoteService) ListNotes(userId, notebookId string,
isTrash bool, pageNumber, pageSize int, sortField string, isAsc bool, isBlog bool) (count int, notes []info.Note) {
isTrash bool, pageNumber, pageSize int, sortField string, isAsc bool, isBlog bool) (count int, notes []info.Note) {
notes = []info.Note{}
skipNum, sortFieldR := parsePageAndSort(pageNumber, pageSize, sortField, isAsc)
// 不是trash的
query := bson.M{"UserId": bson.ObjectIdHex(userId), "IsTrash": isTrash, "IsDeleted": false}
if isBlog {
@ -172,12 +174,12 @@ func (this *NoteService) ListNotes(userId, notebookId string,
if notebookId != "" {
query["NotebookId"] = bson.ObjectIdHex(notebookId)
}
q := db.Notes.Find(query);
q := db.Notes.Find(query)
// 总记录数
count, _ = q.Count()
q.Sort(sortFieldR).
Skip(skipNum).
Limit(pageSize).
@ -187,11 +189,11 @@ func (this *NoteService) ListNotes(userId, notebookId string,
// 通过noteIds来查询
// ShareService调用
func (this *NoteService) ListNotesByNoteIdsWithPageSort(noteIds []bson.ObjectId, userId string,
pageNumber, pageSize int, sortField string, isAsc bool, isBlog bool) (notes []info.Note) {
func (this *NoteService) ListNotesByNoteIdsWithPageSort(noteIds []bson.ObjectId, userId string,
pageNumber, pageSize int, sortField string, isAsc bool, isBlog bool) (notes []info.Note) {
skipNum, sortFieldR := parsePageAndSort(pageNumber, pageSize, sortField, isAsc)
notes = []info.Note{}
// 不是trash
db.Notes.
Find(bson.M{"_id": bson.M{"$in": noteIds}, "IsTrash": false}).
@ -201,24 +203,27 @@ func (this *NoteService) ListNotesByNoteIdsWithPageSort(noteIds []bson.ObjectId,
All(&notes)
return
}
// shareService调用
func (this *NoteService) ListNotesByNoteIds(noteIds []bson.ObjectId) (notes []info.Note) {
notes = []info.Note{}
db.Notes.
Find(bson.M{"_id": bson.M{"$in": noteIds}}).
All(&notes)
return
}
// blog需要
func (this *NoteService) ListNoteContentsByNoteIds(noteIds []bson.ObjectId) (notes []info.NoteContent) {
notes = []info.NoteContent{}
db.NoteContents.
Find(bson.M{"_id": bson.M{"$in": noteIds}}).
All(&notes)
return
}
// 只得到abstract, 不需要content
func (this *NoteService) ListNoteAbstractsByNoteIds(noteIds []bson.ObjectId) (notes []info.NoteContent) {
notes = []info.NoteContent{}
@ -236,9 +241,9 @@ func (this *NoteService) ListNoteContentByNoteIds(noteIds []bson.ObjectId) (note
// [ok]
func (this *NoteService) AddNote(note info.Note, fromApi bool) info.Note {
if(note.NoteId.Hex() == "") {
noteId := bson.NewObjectId();
note.NoteId = noteId;
if note.NoteId.Hex() == "" {
noteId := bson.NewObjectId()
note.NoteId = noteId
}
note.CreatedTime = time.Now()
note.UpdatedTime = note.CreatedTime
@ -246,26 +251,26 @@ func (this *NoteService) AddNote(note info.Note, fromApi bool) info.Note {
note.UpdatedUserId = note.UserId
note.UrlTitle = GetUrTitle(note.UserId.Hex(), note.Title, "note")
note.Usn = userService.IncrUsn(note.UserId.Hex())
notebookId := note.NotebookId.Hex()
// api会传IsBlog, web不会传
if !fromApi {
// 设为blog
note.IsBlog = notebookService.IsBlog(notebookId)
}
// if note.IsBlog {
// if note.IsBlog {
note.PublicTime = note.UpdatedTime
// }
// }
db.Insert(db.Notes, note)
// tag1
tagService.AddTags(note.UserId.Hex(), note.Tags)
// recount notebooks' notes number
notebookService.ReCountNotebookNumberNotes(notebookId)
return note
}
@ -279,19 +284,18 @@ func (this *NoteService) AddSharedNote(note info.Note, myUserId bson.ObjectId) i
return info.Note{}
}
// 添加笔记本内容
// [ok]
func (this *NoteService) AddNoteContent(noteContent info.NoteContent) info.NoteContent {
noteContent.CreatedTime = time.Now()
noteContent.UpdatedTime = noteContent.CreatedTime
noteContent.UpdatedTime = noteContent.CreatedTime
noteContent.UpdatedUserId = noteContent.UserId
db.Insert(db.NoteContents, noteContent)
// 更新笔记图片
noteImageService.UpdateNoteImages(noteContent.UserId.Hex(), noteContent.NoteId.Hex(), "", noteContent.Content)
return noteContent;
return noteContent
}
// API, abstract, desc需要这里获取
@ -308,7 +312,7 @@ func (this *NoteService) AddNoteAndContentApi(note info.Note, noteContent info.N
note.UpdatedUserId = note.UserId
note.UrlTitle = GetUrTitle(note.UserId.Hex(), note.Title, "note")
note.Usn = userService.IncrUsn(note.UserId.Hex())
// desc这里获取
desc := SubStringHTMLToRaw(noteContent.Content, 50)
note.Desc = desc;
@ -316,24 +320,24 @@ func (this *NoteService) AddNoteAndContentApi(note info.Note, noteContent info.N
// 设为blog
notebookId := note.NotebookId.Hex()
note.IsBlog = notebookService.IsBlog(notebookId)
if note.IsBlog {
note.PublicTime = note.UpdatedTime
}
db.Insert(db.Notes, note)
// tag1, 不需要了
// tagService.AddTags(note.UserId.Hex(), note.Tags)
// recount notebooks' notes number
notebookService.ReCountNotebookNumberNotes(notebookId)
// 这里, 添加到内容中
abstract := SubStringHTML(noteContent.Content, 200, "")
noteContent.Abstract = abstract
this.AddNoteContent(noteContent)
return note
}*/
@ -348,15 +352,15 @@ func (this *NoteService) AddNoteAndContentForController(note info.Note, noteCont
Log("HAS AUTH -----------")
}
}
return this.AddNoteAndContent(note, noteContent, bson.ObjectIdHex(updatedUserId));
return this.AddNoteAndContent(note, noteContent, bson.ObjectIdHex(updatedUserId))
}
func (this *NoteService) AddNoteAndContent(note info.Note, noteContent info.NoteContent, myUserId bson.ObjectId) info.Note {
if(note.NoteId.Hex() == "") {
if note.NoteId.Hex() == "" {
noteId := bson.NewObjectId()
note.NoteId = noteId
}
noteContent.NoteId = note.NoteId
if note.UserId != myUserId {
if note.UserId != myUserId {
note = this.AddSharedNote(note, myUserId)
} else {
note = this.AddNote(note, false)
@ -368,12 +372,12 @@ func (this *NoteService) AddNoteAndContent(note info.Note, noteContent info.Note
}
func (this *NoteService) AddNoteAndContentApi(note info.Note, noteContent info.NoteContent, myUserId bson.ObjectId) info.Note {
if(note.NoteId.Hex() == "") {
if note.NoteId.Hex() == "" {
noteId := bson.NewObjectId()
note.NoteId = noteId
}
noteContent.NoteId = note.NoteId
if note.UserId != myUserId {
if note.UserId != myUserId {
note = this.AddSharedNote(note, myUserId)
} else {
note = this.AddNote(note, true)
@ -392,7 +396,7 @@ func (this *NoteService) UpdateNote(updatedUserId, noteId string, needUpdate bso
if note.NoteId == "" {
return false, "notExists", 0
}
userId := note.UserId.Hex()
// updatedUserId 要修改userId的note, 此时需要判断是否有修改权限
if userId != updatedUserId {
@ -403,34 +407,34 @@ func (this *NoteService) UpdateNote(updatedUserId, noteId string, needUpdate bso
Log("HAS AUTH -----------")
}
}
if usn > 0 && note.Usn != usn {
if usn > 0 && note.Usn != usn {
return false, "conflict", 0
}
// 是否已自定义
if note.IsBlog && note.HasSelfDefined {
delete(needUpdate, "ImgSrc")
delete(needUpdate, "Desc")
}
needUpdate["UpdatedUserId"] = bson.ObjectIdHex(updatedUserId);
needUpdate["UpdatedTime"] = time.Now();
afterUsn := userService.IncrUsn(userId);
needUpdate["UpdatedUserId"] = bson.ObjectIdHex(updatedUserId)
needUpdate["UpdatedTime"] = time.Now()
afterUsn := userService.IncrUsn(userId)
needUpdate["Usn"] = afterUsn
// 添加tag2
// TODO 这个tag去掉, 添加tag另外添加, 不要这个
if tags, ok := needUpdate["Tags"]; ok {
tagService.AddTagsI(userId, tags)
}
// 是否修改了isBlog
// 也要修改noteContents的IsBlog
if isBlog, ok := needUpdate["IsBlog"]; ok {
isBlog2 := isBlog.(bool)
if note.IsBlog != isBlog2 {
this.UpdateNoteContentIsBlog(noteId, userId, isBlog2);
this.UpdateNoteContentIsBlog(noteId, userId, isBlog2)
// 重新发布成博客
if !note.IsBlog {
@ -438,17 +442,17 @@ func (this *NoteService) UpdateNote(updatedUserId, noteId string, needUpdate bso
}
}
}
ok := db.UpdateByIdAndUserIdMap(db.Notes, noteId, userId, needUpdate)
if !ok {
return ok, "", 0
}
// 重新获取之
note = this.GetNoteById(noteId)
hasRecount := false
// 如果修改了notebookId, 则更新notebookId'count
// 两方的notebook也要修改
notebookIdI := needUpdate["NotebookId"]
@ -460,14 +464,14 @@ func (this *NoteService) UpdateNote(updatedUserId, noteId string, needUpdate bso
notebookService.ReCountNotebookNumberNotes(notebookId.Hex())
}
}
// 不要多次更新, isTrash = false, = true都要重新统计
if !hasRecount {
if _, ok := needUpdate["IsTrash"]; ok {
notebookService.ReCountNotebookNumberNotes(note.NotebookId.Hex())
}
}
return true, "", afterUsn
}
@ -479,7 +483,7 @@ func (this *NoteService) UpdateNoteContentIsBlog(noteId, userId string, isBlog b
// 附件修改, 增加noteIncr
func (this *NoteService) IncrNoteUsn(noteId, userId string) int {
afterUsn := userService.IncrUsn(userId)
db.UpdateByIdAndUserIdMap(db.Notes, noteId, userId,
db.UpdateByIdAndUserIdMap(db.Notes, noteId, userId,
bson.M{"UpdatedTime": time.Now(), "Usn": afterUsn})
return afterUsn
}
@ -495,7 +499,7 @@ func (this *NoteService) UpdateNoteTitle(userId, updatedUserId, noteId, title st
}
}
return db.UpdateByIdAndUserIdMap(db.Notes, noteId, userId,
return db.UpdateByIdAndUserIdMap(db.Notes, noteId, userId,
bson.M{"UpdatedUserId": bson.ObjectIdHex(updatedUserId), "Title": title, "UpdatedTime": time.Now(), "Usn": userService.IncrUsn(userId)})
}
@ -517,17 +521,17 @@ func (this *NoteService) UpdateNoteContent(updatedUserId, noteId, content, abstr
return false, "noAuth", 0
}
}
// abstract重置
data := bson.M{"UpdatedUserId": bson.ObjectIdHex(updatedUserId),
"Content": content,
"Abstract": abstract,
data := bson.M{"UpdatedUserId": bson.ObjectIdHex(updatedUserId),
"Content": content,
"Abstract": abstract,
"UpdatedTime": time.Now()}
if note.IsBlog && note.HasSelfDefined {
delete(data, "Abstract")
}
// usn, 修改笔记不可能单独修改内容
afterUsn := 0
// 如果之前没有修改note其它信息, 那么usn++
@ -542,14 +546,14 @@ func (this *NoteService) UpdateNoteContent(updatedUserId, noteId, content, abstr
if db.UpdateByIdAndUserIdMap(db.NoteContents, noteId, userId, data) {
// 这里, 添加历史记录
noteContentHistoryService.AddHistory(noteId, userId, info.EachHistory{UpdatedUserId: bson.ObjectIdHex(updatedUserId),
Content: content,
noteContentHistoryService.AddHistory(noteId, userId, info.EachHistory{UpdatedUserId: bson.ObjectIdHex(updatedUserId),
Content: content,
UpdatedTime: time.Now(),
})
// 更新笔记图片
noteImageService.UpdateNoteImages(userId, noteId, note.ImgSrc, content)
return true, "", afterUsn
}
return false, "", 0
@ -585,12 +589,12 @@ func (this *NoteService) ToBlog(userId, noteId string, isBlog, isTop bool) bool
noteUpdate["HasSelfDefined"] = false
}
noteUpdate["Usn"] = userService.IncrUsn(userId)
ok := db.UpdateByIdAndUserIdMap(db.Notes, noteId, userId, noteUpdate)
// 重新计算tags
go (func() {
this.UpdateNoteContentIsBlog(noteId, userId, isBlog);
this.UpdateNoteContentIsBlog(noteId, userId, isBlog)
blogService.ReCountBlogTags(userId)
})()
return ok
@ -604,17 +608,17 @@ func (this *NoteService) MoveNote(noteId, notebookId, userId string) info.Note {
if notebookService.IsMyNotebook(notebookId, userId) {
note := this.GetNote(noteId, userId)
preNotebookId := note.NotebookId.Hex()
re := db.UpdateByIdAndUserId(db.Notes, noteId, userId,
bson.M{"$set": bson.M{"IsTrash": false,
re := db.UpdateByIdAndUserId(db.Notes, noteId, userId,
bson.M{"$set": bson.M{"IsTrash": false,
"NotebookId": bson.ObjectIdHex(notebookId),
"Usn": userService.IncrUsn(userId),
}})
"Usn": userService.IncrUsn(userId),
}})
if re {
// 更新blog状态
this.updateToNotebookBlog(noteId, notebookId, userId)
// recount notebooks' notes number
notebookService.ReCountNotebookNumberNotes(notebookId)
// 之前不是trash才统计, trash本不在统计中的
@ -622,13 +626,13 @@ func (this *NoteService) MoveNote(noteId, notebookId, userId string) info.Note {
notebookService.ReCountNotebookNumberNotes(preNotebookId)
}
}
return this.GetNote(noteId, userId);
return this.GetNote(noteId, userId)
}
return info.Note{}
}
// 如果自己的blog状态是true, 不用改变,
// 如果自己的blog状态是true, 不用改变,
// 否则, 如果notebookId的blog是true, 则改为true之
// 返回blog状态
// move, copy时用
@ -637,16 +641,17 @@ func (this *NoteService) updateToNotebookBlog(noteId, notebookId, userId string)
return true
}
if notebookService.IsBlog(notebookId) {
db.UpdateByIdAndUserId(db.Notes, noteId, userId,
db.UpdateByIdAndUserId(db.Notes, noteId, userId,
bson.M{"$set": bson.M{"IsBlog": true, "PublicTime": time.Now()}}) // life
return true
}
return false
}
// 判断是否是blog
func (this *NoteService) IsBlog(noteId string) bool {
note := info.Note{}
db.GetByQWithFields(db.Notes, bson.M{"_id": bson.ObjectIdHex(noteId)}, []string{"IsBlog"}, &note);
db.GetByQWithFields(db.Notes, bson.M{"_id": bson.ObjectIdHex(noteId)}, []string{"IsBlog"}, &note)
return note.IsBlog
}
@ -658,25 +663,25 @@ func (this *NoteService) CopyNote(noteId, notebookId, userId string) info.Note {
if notebookService.IsMyNotebook(notebookId, userId) {
note := this.GetNote(noteId, userId)
noteContent := this.GetNoteContent(noteId, userId)
// 重新生成noteId
note.NoteId = bson.NewObjectId();
note.NoteId = bson.NewObjectId()
note.NotebookId = bson.ObjectIdHex(notebookId)
noteContent.NoteId = note.NoteId
note = this.AddNoteAndContent(note, noteContent, note.UserId);
note = this.AddNoteAndContent(note, noteContent, note.UserId)
// 更新blog状态
isBlog := this.updateToNotebookBlog(note.NoteId.Hex(), notebookId, userId)
// recount
notebookService.ReCountNotebookNumberNotes(notebookId)
note.IsBlog = isBlog
return note
}
return info.Note{}
}
@ -693,37 +698,37 @@ func (this *NoteService) CopySharedNote(noteId, notebookId, fromUserId, myUserId
noteContent := this.GetNoteContent(noteId, fromUserId)
// 重新生成noteId
note.NoteId = bson.NewObjectId();
note.NoteId = bson.NewObjectId()
note.NotebookId = bson.ObjectIdHex(notebookId)
note.UserId = bson.ObjectIdHex(myUserId)
note.IsTop = false
note.IsBlog = false // 别人的可能是blog
note.ImgSrc = "" // 为什么清空, 因为图片需要复制, 先清空
// content
noteContent.NoteId = note.NoteId
noteContent.UserId = note.UserId
// 复制图片, 把note的图片都copy给我, 且修改noteContent图片路径
noteContent.Content = noteImageService.CopyNoteImages(noteId, fromUserId, note.NoteId.Hex(), noteContent.Content, myUserId)
// 复制附件
attachService.CopyAttachs(noteId, note.NoteId.Hex(), myUserId)
// 添加之
note = this.AddNoteAndContent(note, noteContent, note.UserId);
note = this.AddNoteAndContent(note, noteContent, note.UserId)
// 更新blog状态
isBlog := this.updateToNotebookBlog(note.NoteId.Hex(), notebookId, myUserId)
// recount
notebookService.ReCountNotebookNumberNotes(notebookId)
note.IsBlog = isBlog
return note
}
return info.Note{}
}
@ -743,31 +748,31 @@ func (this *NoteService) GetNotebookId(noteId string) bson.ObjectId {
func (this *NoteService) SearchNote(key, userId string, pageNumber, pageSize int, sortField string, isAsc, isBlog bool) (count int, notes []info.Note) {
notes = []info.Note{}
skipNum, sortFieldR := parsePageAndSort(pageNumber, pageSize, sortField, isAsc)
// 利用标题和desc, 不用content
orQ := []bson.M{
bson.M{"Title": bson.M{"$regex": bson.RegEx{".*?" + key + ".*", "i"}}},
bson.M{"Desc": bson.M{"$regex": bson.RegEx{".*?" + key + ".*", "i"}}},
}
// 不是trash的
query := bson.M{"UserId": bson.ObjectIdHex(userId),
"IsTrash": false,
query := bson.M{"UserId": bson.ObjectIdHex(userId),
"IsTrash": false,
"IsDeleted": false, // 不能搜索已删除了的
"$or": orQ,
"$or": orQ,
}
if isBlog {
query["IsBlog"] = true
}
q := db.Notes.Find(query);
q := db.Notes.Find(query)
// 总记录数
count, _ = q.Count()
q.Sort(sortFieldR).
Skip(skipNum).
Limit(pageSize).
All(&notes)
// 如果 < pageSize 那么搜索content, 且id不在这些id之间的
if len(notes) < pageSize {
notes = this.searchNoteFromContent(notes, userId, key, pageSize, sortFieldR, isBlog)
@ -794,19 +799,19 @@ func (this *NoteService) searchNoteFromContent(notes []info.Note, userId, key st
Select(bson.M{"_id": true}).
All(&noteContents)
var lenContent = len(noteContents)
if(lenContent == 0) {
if lenContent == 0 {
return notes
}
// 收集ids
noteIds2 := make([]bson.ObjectId, lenContent)
for i, content := range noteContents {
noteIds2[i] = content.NoteId
}
// 得到notes
notes2 := this.ListNotesByNoteIds(noteIds2)
// 合并之
notes = append(notes, notes2...)
return notes
@ -817,17 +822,17 @@ func (this *NoteService) searchNoteFromContent(notes []info.Note, userId, key st
func (this *NoteService) SearchNoteByTags(tags []string, userId string, pageNumber, pageSize int, sortField string, isAsc bool) (count int, notes []info.Note) {
notes = []info.Note{}
skipNum, sortFieldR := parsePageAndSort(pageNumber, pageSize, sortField, isAsc)
// 不是trash的
query := bson.M{"UserId": bson.ObjectIdHex(userId),
"IsTrash": false,
"Tags": bson.M{"$all": tags}}
q := db.Notes.Find(query);
query := bson.M{"UserId": bson.ObjectIdHex(userId),
"IsTrash": false,
"Tags": bson.M{"$all": tags}}
q := db.Notes.Find(query)
// 总记录数
count, _ = q.Count()
q.Sort(sortFieldR).
Skip(skipNum).
Limit(pageSize).
@ -857,17 +862,17 @@ func (this *NoteService) CountNoteByTag(userId string, tag string) int {
if tag == "" {
return 0
}
query := bson.M{"UserId": bson.ObjectIdHex(userId),
// "IsTrash": false,
query := bson.M{"UserId": bson.ObjectIdHex(userId),
// "IsTrash": false,
"IsDeleted": false,
"Tags": bson.M{"$in": []string{tag}}}
"Tags": bson.M{"$in": []string{tag}}}
return db.Count(db.Notes, query)
}
// 删除tag
// 返回所有note的Usn
func (this *NoteService) UpdateNoteToDeleteTag(userId string, targetTag string) map[string]int {
query := bson.M{"UserId": bson.ObjectIdHex(userId),
query := bson.M{"UserId": bson.ObjectIdHex(userId),
"Tags": bson.M{"$in": []string{targetTag}}}
notes := []info.Note{}
db.ListByQ(db.Notes, query, &notes)
@ -881,7 +886,7 @@ func (this *NoteService) UpdateNoteToDeleteTag(userId string, targetTag string)
if tag == targetTag {
tags = tags
tags = append(tags[:i], tags[i+1:]...)
break;
break
}
}
usn := userService.IncrUsn(userId)

View File

@ -1,15 +1,15 @@
package service
import (
// "fmt"
"gopkg.in/mgo.v2/bson"
// "fmt"
"github.com/leanote/leanote/app/db"
"github.com/leanote/leanote/app/info"
. "github.com/leanote/leanote/app/lea"
"gopkg.in/mgo.v2/bson"
"sort"
"time"
"strings"
// "html"
"time"
// "html"
)
// 笔记本
@ -42,8 +42,8 @@ func ParseAndSortNotebooks(userNotebooks []info.Notebook, noParentDelete, needSo
for _, each := range userNotebooks {
newNotebooks := info.Notebooks{Subs: info.SubNotebooks{}}
newNotebooks.NotebookId = each.NotebookId
newNotebooks.Title = each.Title;
// newNotebooks.Title = html.EscapeString(each.Title)
newNotebooks.Title = each.Title
// newNotebooks.Title = html.EscapeString(each.Title)
newNotebooks.Title = strings.Replace(strings.Replace(each.Title, "<script>", "", -1), "</script", "", -1)
newNotebooks.Seq = each.Seq
newNotebooks.UserId = each.UserId
@ -51,13 +51,13 @@ func ParseAndSortNotebooks(userNotebooks []info.Notebook, noParentDelete, needSo
newNotebooks.NumberNotes = each.NumberNotes
newNotebooks.IsTrash = each.IsTrash
newNotebooks.IsBlog = each.IsBlog
// 存地址
userNotebooksMap[each.NotebookId] = &newNotebooks
}
// 第二遍, 追加到父下
// 需要删除的id
needDeleteNotebookId := map[bson.ObjectId]bool{}
for id, each := range userNotebooksMap {
@ -70,7 +70,7 @@ func ParseAndSortNotebooks(userNotebooks []info.Notebook, noParentDelete, needSo
needDeleteNotebookId[id] = true
// delete(userNotebooksMap, id)
} else if noParentDelete {
// 没有父, 且设置了要删除
// 没有父, 且设置了要删除
needDeleteNotebookId[id] = true
// delete(userNotebooksMap, id)
}
@ -116,9 +116,9 @@ func (this *NotebookService) GetNotebookByUserIdAndUrlTitle(userId, notebookIdOr
}
// 同步的方法
func (this *NotebookService) GeSyncNotebooks(userId string, afterUsn, maxEntry int) ([]info.Notebook) {
func (this *NotebookService) GeSyncNotebooks(userId string, afterUsn, maxEntry int) []info.Notebook {
notebooks := []info.Notebook{}
q := db.Notebooks.Find(bson.M{"UserId": bson.ObjectIdHex(userId), "Usn": bson.M{"$gt": afterUsn}});
q := db.Notebooks.Find(bson.M{"UserId": bson.ObjectIdHex(userId), "Usn": bson.M{"$gt": afterUsn}})
q.Sort("Usn").Limit(maxEntry).All(&notebooks)
return notebooks
}
@ -137,7 +137,7 @@ func (this *NotebookService) GetNotebooks(userId string) info.SubNotebooks {
if len(userNotebooks) == 0 {
return nil
}
return ParseAndSortNotebooks(userNotebooks, true, true)
}
@ -147,11 +147,11 @@ func (this *NotebookService) GetNotebooks(userId string) info.SubNotebooks {
func (this *NotebookService) GetNotebooksByNotebookIds(notebookIds []bson.ObjectId) info.SubNotebooks {
userNotebooks := []info.Notebook{}
db.Notebooks.Find(bson.M{"_id": bson.M{"$in": notebookIds}}).All(&userNotebooks)
if len(userNotebooks) == 0 {
return nil
}
return ParseAndSortNotebooks(userNotebooks, false, false)
}
@ -169,12 +169,13 @@ func (this *NotebookService) AddNotebook(notebook info.Notebook) (bool, info.Not
}
return true, notebook
}
// 更新笔记, api
func (this *NotebookService) UpdateNotebookApi(userId, notebookId, title, parentNotebookId string, seq, usn int) (bool, string, info.Notebook) {
if notebookId == "" {
return false, "notebookIdNotExists", info.Notebook{}
}
// 先判断usn是否和数据库的一样, 如果不一样, 则冲突, 不保存
notebook := this.GetNotebookById(notebookId)
// 不存在
@ -183,16 +184,16 @@ func (this *NotebookService) UpdateNotebookApi(userId, notebookId, title, parent
} else if notebook.Usn != usn {
return false, "conflict", notebook
}
notebook.Usn = userService.IncrUsn(userId);
notebook.Title = title;
updates := bson.M{"Title": title, "Usn": notebook.Usn, "Seq": seq, "UpdatedTime": time.Now()};
if(parentNotebookId != "" && bson.IsObjectIdHex(parentNotebookId)) {
updates["ParentNotebookId"] = bson.ObjectIdHex(parentNotebookId);
notebook.Usn = userService.IncrUsn(userId)
notebook.Title = title
updates := bson.M{"Title": title, "Usn": notebook.Usn, "Seq": seq, "UpdatedTime": time.Now()}
if parentNotebookId != "" && bson.IsObjectIdHex(parentNotebookId) {
updates["ParentNotebookId"] = bson.ObjectIdHex(parentNotebookId)
} else {
updates["ParentNotebookId"] = "";
updates["ParentNotebookId"] = ""
}
ok := db.UpdateByIdAndUserIdMap(db.Notebooks, notebookId, userId, updates);
ok := db.UpdateByIdAndUserIdMap(db.Notebooks, notebookId, userId, updates)
if ok {
return ok, "", this.GetNotebookById(notebookId)
}
@ -202,7 +203,7 @@ func (this *NotebookService) UpdateNotebookApi(userId, notebookId, title, parent
// 判断是否是blog
func (this *NotebookService) IsBlog(notebookId string) bool {
notebook := info.Notebook{}
db.GetByQWithFields(db.Notebooks, bson.M{"_id": bson.ObjectIdHex(notebookId)}, []string{"IsBlog"}, &notebook);
db.GetByQWithFields(db.Notebooks, bson.M{"_id": bson.ObjectIdHex(notebookId)}, []string{"IsBlog"}, &notebook)
return notebook.IsBlog
}
@ -228,20 +229,20 @@ func (this *NotebookService) UpdateNotebookTitle(notebookId, userId, title strin
// 更新notebook
func (this *NotebookService) UpdateNotebook(userId, notebookId string, needUpdate bson.M) bool {
needUpdate["UpdatedTime"] = time.Now();
needUpdate["UpdatedTime"] = time.Now()
needUpdate["Usn"] = userService.IncrUsn(userId)
return db.UpdateByIdAndUserIdMap(db.Notebooks, notebookId, userId, needUpdate)
}
// ToBlog or Not
func (this *NotebookService) ToBlog(userId, notebookId string, isBlog bool) (bool) {
func (this *NotebookService) ToBlog(userId, notebookId string, isBlog bool) bool {
updates := bson.M{"IsBlog": isBlog, "Usn": userService.IncrUsn(userId)}
// 笔记本
db.UpdateByIdAndUserIdMap(db.Notebooks, notebookId, userId, updates)
// 更新笔记
q := bson.M{"UserId": bson.ObjectIdHex(userId),
"NotebookId": bson.ObjectIdHex(notebookId)}
q := bson.M{"UserId": bson.ObjectIdHex(userId),
"NotebookId": bson.ObjectIdHex(notebookId)}
data := bson.M{"IsBlog": isBlog}
if isBlog {
data["PublicTime"] = time.Now()
@ -251,7 +252,7 @@ func (this *NotebookService) ToBlog(userId, notebookId string, isBlog bool) (boo
// usn
data["Usn"] = userService.IncrUsn(userId)
db.UpdateByQMap(db.Notes, q, data)
// noteContents也更新, 这个就麻烦了, noteContents表没有NotebookId
// 先查该notebook下所有notes, 得到id
notes := []info.Note{}
@ -263,12 +264,12 @@ func (this *NotebookService) ToBlog(userId, notebookId string, isBlog bool) (boo
}
db.UpdateByQMap(db.NoteContents, bson.M{"_id": bson.M{"$in": noteIds}}, bson.M{"IsBlog": isBlog})
}
// 重新计算tags
go (func() {
blogService.ReCountBlogTags(userId)
})()
return true
}
@ -276,18 +277,18 @@ func (this *NotebookService) ToBlog(userId, notebookId string, isBlog bool) (boo
// 先查看该notebookId下是否有notes, 没有则删除
func (this *NotebookService) DeleteNotebook(userId, notebookId string) (bool, string) {
if db.Count(db.Notebooks, bson.M{
"ParentNotebookId": bson.ObjectIdHex(notebookId),
"UserId": bson.ObjectIdHex(userId),
"IsDeleted": false,
}) == 0 { // 无
if db.Count(db.Notes, bson.M{"NotebookId": bson.ObjectIdHex(notebookId),
"UserId": bson.ObjectIdHex(userId),
"IsTrash": false,
"ParentNotebookId": bson.ObjectIdHex(notebookId),
"UserId": bson.ObjectIdHex(userId),
"IsDeleted": false,
}) == 0 { // 无
if db.Count(db.Notes, bson.M{"NotebookId": bson.ObjectIdHex(notebookId),
"UserId": bson.ObjectIdHex(userId),
"IsTrash": false,
"IsDeleted": false}) == 0 { // 不包含trash
// 不是真删除 1/20, 为了同步笔记本
ok := db.UpdateByQMap(db.Notebooks, bson.M{"_id": bson.ObjectIdHex(notebookId)}, bson.M{"IsDeleted": true, "Usn": userService.IncrUsn(userId)})
return ok, ""
// return db.DeleteByIdAndUserId(db.Notebooks, notebookId, userId), ""
// return db.DeleteByIdAndUserId(db.Notebooks, notebookId, userId), ""
}
return false, "笔记本下有笔记"
} else {
@ -321,7 +322,7 @@ func (this *NotebookService) SortNotebooks(userId string, notebookId2Seqs map[st
return false
}
}
return true
}
@ -329,12 +330,12 @@ func (this *NotebookService) SortNotebooks(userId string, notebookId2Seqs map[st
func (this *NotebookService) DragNotebooks(userId string, curNotebookId string, parentNotebookId string, siblings []string) bool {
ok := false
// 如果没parentNotebookId, 则parentNotebookId设空
if(parentNotebookId == "") {
ok = db.UpdateByIdAndUserIdMap(db.Notebooks, curNotebookId, userId, bson.M{"ParentNotebookId": "", "Usn": userService.IncrUsn(userId)});
if parentNotebookId == "" {
ok = db.UpdateByIdAndUserIdMap(db.Notebooks, curNotebookId, userId, bson.M{"ParentNotebookId": "", "Usn": userService.IncrUsn(userId)})
} else {
ok = db.UpdateByIdAndUserIdMap(db.Notebooks, curNotebookId, userId, bson.M{"ParentNotebookId": bson.ObjectIdHex(parentNotebookId), "Usn": userService.IncrUsn(userId)});
ok = db.UpdateByIdAndUserIdMap(db.Notebooks, curNotebookId, userId, bson.M{"ParentNotebookId": bson.ObjectIdHex(parentNotebookId), "Usn": userService.IncrUsn(userId)})
}
if !ok {
return false
}
@ -345,7 +346,7 @@ func (this *NotebookService) DragNotebooks(userId string, curNotebookId string,
return false
}
}
return true
}
@ -362,12 +363,12 @@ func (this *NotebookService) ReCountNotebookNumberNotes(notebookId string) bool
func (this *NotebookService) ReCountAll() {
/*
// 得到所有笔记本
notebooks := []info.Notebook{}
db.ListByQWithFields(db.Notebooks, bson.M{}, []string{"NotebookId"}, &notebooks)
for _, each := range notebooks {
this.ReCountNotebookNumberNotes(each.NotebookId.Hex())
}
// 得到所有笔记本
notebooks := []info.Notebook{}
db.ListByQWithFields(db.Notebooks, bson.M{}, []string{"NotebookId"}, &notebooks)
for _, each := range notebooks {
this.ReCountNotebookNumberNotes(each.NotebookId.Hex())
}
*/
}

View File

@ -1,10 +1,10 @@
package service
import (
"gopkg.in/mgo.v2/bson"
"github.com/leanote/leanote/app/db"
"github.com/leanote/leanote/app/info"
. "github.com/leanote/leanote/app/lea"
"gopkg.in/mgo.v2/bson"
)
// 找回密码
@ -14,7 +14,7 @@ var overHours = 2.0 // 小时后过期
type PwdService struct {
}
// 1. 找回密码, 通过email找用户,
// 1. 找回密码, 通过email找用户,
// 用户存在, 生成code
func (this *PwdService) FindPwd(email string) (ok bool, msg string) {
ok = false
@ -23,12 +23,12 @@ func (this *PwdService) FindPwd(email string) (ok bool, msg string) {
msg = "用户不存在"
return
}
token := tokenService.NewToken(userId, email, info.TokenPwd)
if token == "" {
return false, "db error"
}
// 发送邮件
ok, msg = emailService.FindPwdSendEmail(token, email)
return
@ -40,21 +40,21 @@ func (this *PwdService) UpdatePwd(token, pwd string) (bool, string) {
var tokenInfo info.Token
var ok bool
var msg string
// 先验证
if ok, msg, tokenInfo = tokenService.VerifyToken(token, info.TokenPwd); !ok {
return ok, msg
}
digest, err := GenerateHash(pwd)
if err != nil {
return false,"GenerateHash error"
return false, "GenerateHash error"
}
passwd := string(digest)
passwd := string(digest)
// 修改密码之
ok = db.UpdateByQField(db.Users, bson.M{"_id": tokenInfo.UserId}, "Pwd", passwd)
// 删除token
tokenService.DeleteToken(tokenInfo.UserId.Hex(), info.TokenPwd)
return ok, ""
}
}

View File

@ -1,12 +1,12 @@
package service
import (
"github.com/leanote/leanote/app/info"
"github.com/leanote/leanote/app/db"
"github.com/leanote/leanote/app/info"
. "github.com/leanote/leanote/app/lea"
"gopkg.in/mgo.v2/bson"
"time"
// "strings"
// "strings"
)
// Session存储到mongodb中
@ -14,9 +14,10 @@ type SessionService struct {
}
func (this *SessionService) Update(sessionId, key string, value interface{}) bool {
return db.UpdateByQMap(db.Sessions, bson.M{"SessionId": sessionId},
return db.UpdateByQMap(db.Sessions, bson.M{"SessionId": sessionId},
bson.M{key: value, "UpdatedTime": time.Now()})
}
// 注销时清空session
func (this *SessionService) Clear(sessionId string) bool {
return db.Delete(db.Sessions, bson.M{"SessionId": sessionId})
@ -24,7 +25,7 @@ func (this *SessionService) Clear(sessionId string) bool {
func (this *SessionService) Get(sessionId string) info.Session {
session := info.Session{}
db.GetByQ(db.Sessions, bson.M{"SessionId": sessionId}, &session)
// 如果没有session, 那么插入一条之
if session.Id == "" {
session.Id = bson.NewObjectId()
@ -33,7 +34,7 @@ func (this *SessionService) Get(sessionId string) info.Session {
session.UpdatedTime = session.CreatedTime
db.Insert(db.Sessions, session)
}
return session
}
@ -45,14 +46,16 @@ func (this *SessionService) LoginTimesIsOver(sessionId string) bool {
session := this.Get(sessionId)
return session.LoginTimes > 5
}
// 登录成功后清空错误次数
func (this *SessionService) ClearLoginTimes(sessionId string) bool {
return this.Update(sessionId, "LoginTimes", 0)
}
// 增加错误次数
func (this *SessionService) IncrLoginTimes(sessionId string) bool {
session := this.Get(sessionId)
return this.Update(sessionId, "LoginTimes", session.LoginTimes + 1)
return this.Update(sessionId, "LoginTimes", session.LoginTimes+1)
}
//----------
@ -75,7 +78,7 @@ func (this *SessionService) SetCaptcha(sessionId, captcha string) bool {
func (this *SessionService) GetUserId(sessionId string) string {
session := this.Get(sessionId)
// 更新updateTime, 避免过期
db.UpdateByQMap(db.Sessions, bson.M{"SessionId": sessionId},
db.UpdateByQMap(db.Sessions, bson.M{"SessionId": sessionId},
bson.M{"UpdatedTime": time.Now()})
return session.UserId
}

View File

@ -1,12 +1,12 @@
package service
import (
"github.com/leanote/leanote/app/info"
"github.com/leanote/leanote/app/db"
. "github.com/leanote/leanote/app/lea"
"github.com/leanote/leanote/app/info"
. "github.com/leanote/leanote/app/lea"
"gopkg.in/mgo.v2/bson"
"time"
"sort"
"time"
)
// 共享Notebook, Note服务
@ -35,7 +35,7 @@ type ShareService struct {
func (this *ShareService) getOrQ(userId string) bson.M {
// 得到我和和我参与的组织
groupIds := groupService.GetMineAndBelongToGroupIds(userId)
q := bson.M{}
if len(groupIds) > 0 {
orQ := []bson.M{
@ -45,7 +45,7 @@ func (this *ShareService) getOrQ(userId string) bson.M {
// 不是trash的
q["$or"] = orQ
} else {
q["ToUserId"] = bson.ObjectIdHex(userId);
q["ToUserId"] = bson.ObjectIdHex(userId)
}
return q
}
@ -53,44 +53,44 @@ func (this *ShareService) getOrQ(userId string) bson.M {
// 得到共享给我的笔记本和用户(谁共享给了我)
func (this *ShareService) GetShareNotebooks(userId string) (info.ShareNotebooksByUser, []info.User) {
myUserId := userId
// 得到共享给我的用户s信息
// 得到我参与的组织
q := this.getOrQ(userId)
// 不查hasShareNotes
// 直接查shareNotes, shareNotebooks表得到userId
userIds1 := []bson.ObjectId{}
db.Distinct(db.ShareNotes, q, "UserId", &userIds1)
userIds2 := []bson.ObjectId{}
db.Distinct(db.ShareNotebooks, q, "UserId", &userIds2) // BUG之前是userId1, 2014/12/29
userIds := append(userIds1, userIds2...)
userInfos := userService.GetUserInfosOrderBySeq(userIds);
userInfos := userService.GetUserInfosOrderBySeq(userIds)
// 不要我的id
for i, userInfo := range userInfos {
if userInfo.UserId.Hex() == myUserId {
userInfos = append(userInfos[:i], userInfos[i+1:]...)
break;
break
}
}
//--------------------
// 得到他们共享给我的notebooks
// 这里可能会得到重复的记录
// 权限: 笔记本分享给个人 > 笔记本分享给组织
shareNotebooks := []info.ShareNotebook{}
db.ShareNotebooks.Find(q).Sort("-ToUserId").All(&shareNotebooks) // 按ToUserId降序排序, 那么有ToUserId的在前面
if len(shareNotebooks) == 0 {
return nil, userInfos
}
shareNotebooksLen := len(shareNotebooks)
// 找到了所有的notbookId, 那么找notebook表得到其详细信息
notebookIds := []bson.ObjectId{}
shareNotebooksMap := make(map[bson.ObjectId]info.ShareNotebook, shareNotebooksLen)
@ -102,34 +102,34 @@ func (this *ShareService) GetShareNotebooks(userId string) (info.ShareNotebooksB
shareNotebooksMap[each.NotebookId] = each
}
}
// 1, 2
subNotebooks := notebookService.GetNotebooksByNotebookIds(notebookIds)
// 填充其它信息变成SubShareNotebooks
subShareNotebooks := this.parseToSubShareNotebooks(&subNotebooks, &shareNotebooksMap)
// 3 按用户进行分组成ShareNotebooksByUser
shareNotebooksByUsersMap := map[bson.ObjectId] []info.ShareNotebooks{}
shareNotebooksByUsersMap := map[bson.ObjectId][]info.ShareNotebooks{}
// 先建立userId => []
for _, eachSub := range subShareNotebooks {
userId := eachSub.Notebook.UserId
// 我自己的, 算了
if userId.Hex() == myUserId {
continue;
continue
}
if _, ok := shareNotebooksByUsersMap[userId]; ok {
shareNotebooksByUsersMap[userId] = append(shareNotebooksByUsersMap[userId], eachSub)
} else {
shareNotebooksByUsersMap[userId] = []info.ShareNotebooks{eachSub}
}
}
shareNotebooksByUser := info.ShareNotebooksByUser{};
shareNotebooksByUser := info.ShareNotebooksByUser{}
for userId, eachShareNotebooks := range shareNotebooksByUsersMap {
// 4, 按用户排序
shareNotebooksByUser[userId.Hex()] = sortSubShareNotebooks(eachShareNotebooks)
}
return shareNotebooksByUser, userInfos
}
@ -152,46 +152,46 @@ func (this *ShareService) parseToSubShareNotebooks(subNotebooks *info.SubNoteboo
subShareNotebooks := info.SubShareNotebooks{}
for _, each := range *subNotebooks {
shareNotebooks := info.ShareNotebooks{}
shareNotebooks.Notebook = each.Notebook // 基本信息有了
shareNotebooks.Notebook = each.Notebook // 基本信息有了
shareNotebooks.ShareNotebook = (*shareNotebooksMap)[each.NotebookId] // perm有了
// 公用的, 单独赋值
shareNotebooks.Seq = shareNotebooks.ShareNotebook.Seq
shareNotebooks.NotebookId = shareNotebooks.ShareNotebook.NotebookId
// 还有其子, 递归解析之
if each.Subs != nil && len(each.Subs) > 0 {
shareNotebooks.Subs = this.parseToSubShareNotebooks(&each.Subs, shareNotebooksMap)
}
subShareNotebooks = append(subShareNotebooks, shareNotebooks)
}
return subShareNotebooks
}
//-------------
// 得到共享笔记本下的notes
func (this *ShareService) ListShareNotesByNotebookId(notebookId, myUserId, sharedUserId string,
page, pageSize int, sortField string, isAsc bool) ([]info.ShareNoteWithPerm) {
func (this *ShareService) ListShareNotesByNotebookId(notebookId, myUserId, sharedUserId string,
page, pageSize int, sortField string, isAsc bool) []info.ShareNoteWithPerm {
// 1 首先判断是否真的sharedUserId 共享了 notebookId 给 myUserId
q := this.getOrQ(myUserId)
q["NotebookId"] = bson.ObjectIdHex(notebookId);
q["UserId"] = bson.ObjectIdHex(sharedUserId);
q["NotebookId"] = bson.ObjectIdHex(notebookId)
q["UserId"] = bson.ObjectIdHex(sharedUserId)
shareNotebook := info.ShareNotebook{}
db.GetByQ(db.ShareNotebooks,
db.GetByQ(db.ShareNotebooks,
q,
&shareNotebook)
if shareNotebook.NotebookId == "" {
return nil
}
perm := shareNotebook.Perm
// 2 得到该notebook下分页显示所有的notes
_, notes := noteService.ListNotes(sharedUserId, notebookId, false, page, pageSize, sortField, isAsc, false);
_, notes := noteService.ListNotes(sharedUserId, notebookId, false, page, pageSize, sortField, isAsc, false)
// 3 添加权限信息
// 3.1 如果该notebook自己有其它权限信息, 比如1, 那么覆盖notebook的权限信息
noteIds := make([]bson.ObjectId, len(notes))
@ -201,7 +201,7 @@ func (this *ShareService) ListShareNotesByNotebookId(notebookId, myUserId, share
// 笔记的权限
shareNotes := []info.ShareNote{}
delete(q, "NotebookId")
q["NoteId"] = bson.M{"$in": noteIds}
q["NoteId"] = bson.M{"$in": noteIds}
db.ShareNotes.Find(q).Sort("-ToUserId").All(&shareNotes) // 给个的权限>给组织的权限
notePerms := map[bson.ObjectId]int{}
for _, each := range shareNotes {
@ -210,16 +210,16 @@ func (this *ShareService) ListShareNotesByNotebookId(notebookId, myUserId, share
}
}
Log("笔记权限")
LogJ(notePerms);
LogJ(notePerms)
// 3.2 组合
notesWithPerm := make([]info.ShareNoteWithPerm, len(notes))
for i, each := range notes {
thisPerm := perm;
thisPerm := perm
if selfPerm, ok := notePerms[each.NoteId]; ok {
thisPerm = selfPerm
}
notesWithPerm[i] = info.ShareNoteWithPerm{each, thisPerm}
}
return notesWithPerm
@ -228,17 +228,17 @@ func (this *ShareService) ListShareNotesByNotebookId(notebookId, myUserId, share
// 得到note的perm信息
//func (this *ShareService) getNotesPerm(noteIds []bson.ObjectId, myUserId, sharedUserId string) map[bson.ObjectId]int {
// shareNotes := []info.ShareNote{}
// db.ListByQ(db.ShareNotes,
// db.ListByQ(db.ShareNotes,
// bson.M{
// "NoteId": bson.M{"$in": noteIds},
// "UserId": bson.ObjectIdHex(sharedUserId),
// "NoteId": bson.M{"$in": noteIds},
// "UserId": bson.ObjectIdHex(sharedUserId),
// "ToUserId": bson.ObjectIdHex(myUserId)}, &shareNotes)
//
//
// notesPerm := make(map[bson.ObjectId]int, len(shareNotes))
// for _, each := range shareNotes {
// notesPerm[each.NoteId] = each.Perm
// }
//
//
// return notesPerm
//}
@ -246,26 +246,26 @@ func (this *ShareService) ListShareNotesByNotebookId(notebookId, myUserId, share
// 如果真要支持排序, 这里得到所有共享的notes, 到noteService方再sort和limit
// 可以这样! 到时将零散的共享noteId放在用户基本数据中
// 这里不好排序
func (this *ShareService) ListShareNotes(myUserId, sharedUserId string,
pageNumber, pageSize int, sortField string, isAsc bool) ([]info.ShareNoteWithPerm) {
func (this *ShareService) ListShareNotes(myUserId, sharedUserId string,
pageNumber, pageSize int, sortField string, isAsc bool) []info.ShareNoteWithPerm {
skipNum, _ := parsePageAndSort(pageNumber, pageSize, sortField, isAsc)
shareNotes := []info.ShareNote{}
q := this.getOrQ(myUserId)
q["UserId"] = bson.ObjectIdHex(sharedUserId);
q["UserId"] = bson.ObjectIdHex(sharedUserId)
db.ShareNotes.
Find(q).
Sort("-ToUserId"). // 给个人的权限 > 给组织的权限
Skip(skipNum).
Limit(pageSize).
All(&shareNotes)
if len(shareNotes) == 0 {
return nil
}
noteIds := make([]bson.ObjectId, len(shareNotes))
for i, each := range shareNotes {
noteIds[i] = each.NoteId
@ -275,7 +275,7 @@ func (this *ShareService) ListShareNotes(myUserId, sharedUserId string,
for _, each := range notes {
notesMap[each.NoteId] = each
}
// 将shareNotes与notes结合起来
notesWithPerm := []info.ShareNoteWithPerm{}
hasAdded := map[bson.ObjectId]bool{} // 防止重复, 只要前面权限高的
@ -297,8 +297,8 @@ func (this *ShareService) notes2NotesWithPerm(notes []info.Note) {
// [ok]
func (this *ShareService) AddShareNotebook1(shareNotebook info.ShareNotebook) bool {
// 添加一条记录说明两者存在关系
this.AddHasShareNote(shareNotebook.UserId.Hex(), shareNotebook.ToUserId.Hex());
this.AddHasShareNote(shareNotebook.UserId.Hex(), shareNotebook.ToUserId.Hex())
shareNotebook.CreatedTime = time.Now()
return db.Insert(db.ShareNotebooks, shareNotebook)
}
@ -312,22 +312,22 @@ func (this *ShareService) AddShareNotebook(notebookId string, perm int, userId,
}
return this.AddShareNotebookToUserId(notebookId, perm, userId, toUserId)
}
// 第三方注册时没有email
func (this *ShareService) AddShareNotebookToUserId(notebookId string, perm int, userId, toUserId string) (bool, string, string) {
// 添加一条记录说明两者存在关系
this.AddHasShareNote(userId, toUserId);
this.AddHasShareNote(userId, toUserId)
// 先删除之
db.Delete(db.ShareNotebooks, bson.M{"NotebookId": bson.ObjectIdHex(notebookId),
"UserId": bson.ObjectIdHex(userId),
"UserId": bson.ObjectIdHex(userId),
"ToUserId": bson.ObjectIdHex(toUserId),
});
shareNotebook := info.ShareNotebook{NotebookId: bson.ObjectIdHex(notebookId),
UserId: bson.ObjectIdHex(userId),
ToUserId: bson.ObjectIdHex(toUserId),
Perm: perm,
})
shareNotebook := info.ShareNotebook{NotebookId: bson.ObjectIdHex(notebookId),
UserId: bson.ObjectIdHex(userId),
ToUserId: bson.ObjectIdHex(toUserId),
Perm: perm,
CreatedTime: time.Now(),
}
return db.Insert(db.ShareNotebooks, shareNotebook), "", toUserId
@ -350,27 +350,26 @@ func (this *ShareService) AddShareNote(noteId string, perm int, userId, email st
return this.AddShareNoteToUserId(noteId, perm, userId, toUserId)
}
// 第三方测试没有userId
// 第三方测试没有userId
func (this *ShareService) AddShareNoteToUserId(noteId string, perm int, userId, toUserId string) (bool, string, string) {
// 添加一条记录说明两者存在关系
this.AddHasShareNote(userId, toUserId);
this.AddHasShareNote(userId, toUserId)
// 先删除之
db.Delete(db.ShareNotes, bson.M{"NoteId": bson.ObjectIdHex(noteId),
"UserId": bson.ObjectIdHex(userId),
"UserId": bson.ObjectIdHex(userId),
"ToUserId": bson.ObjectIdHex(toUserId),
});
shareNote := info.ShareNote{NoteId: bson.ObjectIdHex(noteId),
UserId: bson.ObjectIdHex(userId),
ToUserId: bson.ObjectIdHex(toUserId),
Perm: perm,
})
shareNote := info.ShareNote{NoteId: bson.ObjectIdHex(noteId),
UserId: bson.ObjectIdHex(userId),
ToUserId: bson.ObjectIdHex(toUserId),
Perm: perm,
CreatedTime: time.Now(),
}
return db.Insert(db.ShareNotes, shareNote), "", toUserId
}
// updatedUserId是否有查看userId noteId的权限?
// userId是所有者
func (this *ShareService) HasReadPerm(userId, updatedUserId, noteId string) bool {
@ -383,16 +382,16 @@ func (this *ShareService) HasReadPerm(userId, updatedUserId, noteId string) bool
if notebookId.Hex() == "" {
return false
}
delete(q, "NoteId")
q["NotebookId"] = notebookId
// 判断notebook是否被共享
if !db.Has(db.ShareNotebooks, q) {
return false
} else {
return true
}
} else {
return true
}
} else {
return true
}
@ -403,20 +402,20 @@ func (this *ShareService) HasUpdatePerm(userId, updatedUserId, noteId string) bo
q := this.getOrQ(updatedUserId) // (toUserId == "xxx" || ToGroupId in (1, 2,3))
q["UserId"] = bson.ObjectIdHex(userId)
q["NoteId"] = bson.ObjectIdHex(noteId)
// note的权限
shares := []info.ShareNote{}
db.ShareNotes.Find(q).Sort("-ToUserId").All(&shares) // 个人 > 组织
for _, share := range shares {
return share.Perm == 1 // 第1个权限最大
}
// notebook的权限
notebookId := noteService.GetNotebookId(noteId)
if notebookId.Hex() == "" {
return false
}
delete(q, "NoteId")
q["NotebookId"] = notebookId
shares2 := []info.ShareNotebook{}
@ -443,19 +442,20 @@ func (this *ShareService) HasUpdateNotebookPerm(userId, updatedUserId, notebookI
// 共享note, notebook时使用
func (this *ShareService) AddHasShareNote(userId, toUserId string) bool {
db.Insert(db.HasShareNotes, info.HasShareNote{UserId: bson.ObjectIdHex(userId), ToUserId: bson.ObjectIdHex(toUserId)})
return true;
return true
}
// userId是否被共享了noteId
func (this *ShareService) HasSharedNote(noteId, myUserId string) bool {
return db.Has(db.ShareNotes, bson.M{"ToUserId": bson.ObjectIdHex(myUserId), "NoteId": bson.ObjectIdHex(noteId)})
}
// noteId的notebook是否共享了给我
func (this *ShareService) HasSharedNotebook(noteId, myUserId, sharedUserId string) bool {
notebookId := noteService.GetNotebookId(noteId)
if notebookId != "" {
return db.Has(db.ShareNotebooks, bson.M{"NotebookId": notebookId,
"UserId": bson.ObjectIdHex(sharedUserId),
"UserId": bson.ObjectIdHex(sharedUserId),
"ToUserId": bson.ObjectIdHex(myUserId),
})
}
@ -468,11 +468,11 @@ func (this *ShareService) GetShareNoteContent(noteId, myUserId, sharedUserId str
noteContent = info.NoteContent{}
// 是否单独共享了该notebook
// 或者, 其notebook共享了我
// Log(this.HasSharedNote(noteId, myUserId))
// Log(this.HasSharedNotebook(noteId, myUserId, sharedUserId))
// Log(this.HasSharedNote(noteId, myUserId))
// Log(this.HasSharedNotebook(noteId, myUserId, sharedUserId))
Log(this.HasReadPerm(sharedUserId, myUserId, noteId))
if this.HasReadPerm(sharedUserId, myUserId, noteId) {
// if this.HasSharedNote(noteId, myUserId) || this.HasSharedNotebook(noteId, myUserId, sharedUserId) {
// if this.HasSharedNote(noteId, myUserId) || this.HasSharedNotebook(noteId, myUserId, sharedUserId) {
db.Get(db.NoteContents, noteId, &noteContent)
} else {
}
@ -486,16 +486,16 @@ func (this *ShareService) GetShareNoteContent(noteId, myUserId, sharedUserId str
func (this *ShareService) ListNoteShareUserInfo(noteId, userId string) []info.ShareUserInfo {
// 得到shareNote信息, 得到所有的ToUserId
shareNotes := []info.ShareNote{}
db.ListByQLimit(db.ShareNotes,
db.ListByQLimit(db.ShareNotes,
bson.M{
"NoteId": bson.ObjectIdHex(noteId),
"UserId": bson.ObjectIdHex(userId),
"NoteId": bson.ObjectIdHex(noteId),
"UserId": bson.ObjectIdHex(userId),
"ToGroupId": bson.M{"$exists": false},
}, &shareNotes, 100)
// Log("<<>>>>")
// Log(len(shareNotes))
// Log("<<>>>>")
// Log(len(shareNotes))
if len(shareNotes) == 0 {
return nil
}
@ -504,45 +504,45 @@ func (this *ShareService) ListNoteShareUserInfo(noteId, userId string) []info.Sh
for _, each := range shareNotes {
shareNotesMap[each.ToUserId] = each
}
toUserIds := make([]bson.ObjectId, len(shareNotes))
for i, eachShareNote := range shareNotes {
toUserIds[i] = eachShareNote.ToUserId
}
note := noteService.GetNote(noteId, userId)
if note.NoteId == "" {
return nil
}
// 查看其notebook的shareNotebooks信息
shareNotebooks := []info.ShareNotebook{}
db.ListByQ(db.ShareNotebooks,
bson.M{"NotebookId": note.NotebookId, "UserId": bson.ObjectIdHex(userId), "ToUserId": bson.M{"$in": toUserIds}},
db.ListByQ(db.ShareNotebooks,
bson.M{"NotebookId": note.NotebookId, "UserId": bson.ObjectIdHex(userId), "ToUserId": bson.M{"$in": toUserIds}},
&shareNotebooks)
shareNotebooksMap := make(map[bson.ObjectId]info.ShareNotebook, len(shareNotebooks))
for _, each := range shareNotebooks {
shareNotebooksMap[each.ToUserId] = each
}
// 得到用户信息
userInfos := userService.ListUserInfosByUserIds(toUserIds)
if len(userInfos) == 0 {
return nil
}
shareUserInfos := make([]info.ShareUserInfo, len(userInfos))
for i, userInfo := range userInfos {
_, hasNotebook := shareNotebooksMap[userInfo.UserId]
shareUserInfos[i] = info.ShareUserInfo{ToUserId: userInfo.UserId,
Email: userInfo.Email,
Perm: shareNotesMap[userInfo.UserId].Perm,
shareUserInfos[i] = info.ShareUserInfo{ToUserId: userInfo.UserId,
Email: userInfo.Email,
Perm: shareNotesMap[userInfo.UserId].Perm,
NotebookHasShared: hasNotebook,
}
}
}
return shareUserInfos
}
@ -551,63 +551,62 @@ func (this *ShareService) ListNoteShareUserInfo(noteId, userId string) []info.Sh
func (this *ShareService) ListNotebookShareUserInfo(notebookId, userId string) []info.ShareUserInfo {
// notebook的shareNotebooks信息
shareNotebooks := []info.ShareNotebook{}
db.ListByQLimit(db.ShareNotebooks,
db.ListByQLimit(db.ShareNotebooks,
bson.M{
"NotebookId": bson.ObjectIdHex(notebookId),
"UserId": bson.ObjectIdHex(userId),
"ToGroupId": bson.M{"$exists": false},
},
"NotebookId": bson.ObjectIdHex(notebookId),
"UserId": bson.ObjectIdHex(userId),
"ToGroupId": bson.M{"$exists": false},
},
&shareNotebooks, 100)
if len(shareNotebooks) == 0 {
return nil
}
// 得到用户信息
toUserIds := make([]bson.ObjectId, len(shareNotebooks))
for i, each := range shareNotebooks {
toUserIds[i] = each.ToUserId
}
userInfos := userService.ListUserInfosByUserIds(toUserIds)
if len(userInfos) == 0 {
return nil
}
shareNotebooksMap := make(map[bson.ObjectId]info.ShareNotebook, len(shareNotebooks))
for _, each := range shareNotebooks {
shareNotebooksMap[each.ToUserId] = each
}
shareUserInfos := make([]info.ShareUserInfo, len(userInfos))
for i, userInfo := range userInfos {
shareUserInfos[i] = info.ShareUserInfo{ToUserId: userInfo.UserId,
shareUserInfos[i] = info.ShareUserInfo{ToUserId: userInfo.UserId,
Email: userInfo.Email,
Perm: shareNotebooksMap[userInfo.UserId].Perm,
}
Perm: shareNotebooksMap[userInfo.UserId].Perm,
}
}
return shareUserInfos
}
//----------------
// 改变note share权限
func (this *ShareService) UpdateShareNotePerm(noteId string, perm int, userId, toUserId string) bool {
return db.UpdateByQField(db.ShareNotes,
return db.UpdateByQField(db.ShareNotes,
bson.M{"NoteId": bson.ObjectIdHex(noteId), "UserId": bson.ObjectIdHex(userId), "ToUserId": bson.ObjectIdHex(toUserId)},
"Perm",
"Perm",
perm,
)
)
}
func (this *ShareService) UpdateShareNotebookPerm(notebookId string, perm int, userId, toUserId string) bool {
return db.UpdateByQField(db.ShareNotebooks,
return db.UpdateByQField(db.ShareNotebooks,
bson.M{"NotebookId": bson.ObjectIdHex(notebookId), "UserId": bson.ObjectIdHex(userId), "ToUserId": bson.ObjectIdHex(toUserId)},
"Perm",
"Perm",
perm,
)
)
}
//---------------
@ -622,6 +621,7 @@ func (this *ShareService) DeleteShareNoteAll(noteId string, userId string) bool
return db.DeleteAll(db.ShareNotes,
bson.M{"NoteId": bson.ObjectIdHex(noteId), "UserId": bson.ObjectIdHex(userId)})
}
// 删除share notebook
func (this *ShareService) DeleteShareNotebook(notebookId string, userId, toUserId string) bool {
return db.DeleteAll(db.ShareNotebooks,
@ -631,20 +631,20 @@ func (this *ShareService) DeleteShareNotebook(notebookId string, userId, toUserI
// 删除userId分享给toUserId的所有
func (this *ShareService) DeleteUserShareNoteAndNotebook(userId, toUserId string) bool {
query := bson.M{"UserId": bson.ObjectIdHex(userId), "ToUserId": bson.ObjectIdHex(toUserId)}
db.DeleteAll(db.ShareNotebooks, query);
db.DeleteAll(db.ShareNotes, query);
db.DeleteAll(db.HasShareNotes, query);
db.DeleteAll(db.ShareNotebooks, query)
db.DeleteAll(db.ShareNotes, query)
db.DeleteAll(db.HasShareNotes, query)
return true
}
// 用户userId是否有修改noteId的权限
// 用户userId是否有修改noteId的权限
func (this *ShareService) HasUpdateNotePerm(noteId, userId string) bool {
if noteId == "" || userId == "" {
return false;
return false
}
note := noteService.GetNoteById(noteId)
LogJ(note);
LogJ(note)
if note.UserId != "" {
noteUserId := note.UserId.Hex()
if noteUserId != userId {
@ -652,20 +652,20 @@ func (this *ShareService) HasUpdateNotePerm(noteId, userId string) bool {
if this.HasUpdatePerm(noteUserId, userId, noteId) {
return true
} else {
return false;
return false
}
} else {
return true
}
} else {
return false;
return false
}
}
// 用户userId是否有查看noteId的权限
// 用户userId是否有查看noteId的权限
func (this *ShareService) HasReadNotePerm(noteId, userId string) bool {
if noteId == "" || userId == "" {
return false;
return false
}
note := noteService.GetNoteById(noteId)
if note.UserId != "" {
@ -675,13 +675,13 @@ func (this *ShareService) HasReadNotePerm(noteId, userId string) bool {
if this.HasReadPerm(noteUserId, userId, noteId) {
return true
} else {
return false;
return false
}
} else {
return true
}
} else {
return false;
return false
}
}
@ -691,16 +691,16 @@ func (this *ShareService) HasReadNotePerm(noteId, userId string) bool {
// 得到笔记分享给的groups
func (this *ShareService) GetNoteShareGroups(noteId, userId string) []info.ShareNote {
groups := groupService.GetGroupsContainOf(userId)
// 得到有分享的分组
shares := []info.ShareNote{}
db.ListByQ(db.ShareNotes,
bson.M{"NoteId": bson.ObjectIdHex(noteId), "UserId": bson.ObjectIdHex(userId), "ToGroupId": bson.M{"$exists":true}}, &shares)
db.ListByQ(db.ShareNotes,
bson.M{"NoteId": bson.ObjectIdHex(noteId), "UserId": bson.ObjectIdHex(userId), "ToGroupId": bson.M{"$exists": true}}, &shares)
mapShares := map[bson.ObjectId]info.ShareNote{}
for _, share := range shares {
mapShares[share.ToGroupId] = share
mapShares[share.ToGroupId] = share
}
// 所有的groups都有share, 但没有share的group没有shareId
shares2 := make([]info.ShareNote, len(groups))
for i, group := range groups {
@ -708,26 +708,26 @@ func (this *ShareService) GetNoteShareGroups(noteId, userId string) []info.Share
if !ok {
share = info.ShareNote{}
}
share.ToGroup = group;
share.ToGroup = group
shares2[i] = share
}
return shares2
}
// 共享笔记给分组
func (this *ShareService) AddShareNoteGroup(userId, noteId, groupId string, perm int) (bool) {
func (this *ShareService) AddShareNoteGroup(userId, noteId, groupId string, perm int) bool {
if !groupService.IsExistsGroupUser(userId, groupId) {
return false
}
// 先删除之
this.DeleteShareNoteGroup(userId, noteId, groupId)
shareNote := info.ShareNote{NoteId: bson.ObjectIdHex(noteId),
UserId: bson.ObjectIdHex(userId), // 冗余字段
ToGroupId: bson.ObjectIdHex(groupId),
Perm: perm,
shareNote := info.ShareNote{NoteId: bson.ObjectIdHex(noteId),
UserId: bson.ObjectIdHex(userId), // 冗余字段
ToGroupId: bson.ObjectIdHex(groupId),
Perm: perm,
CreatedTime: time.Now(),
}
return db.Insert(db.ShareNotes, shareNote)
@ -736,27 +736,27 @@ func (this *ShareService) AddShareNoteGroup(userId, noteId, groupId string, perm
// 删除
func (this *ShareService) DeleteShareNoteGroup(userId, noteId, groupId string) bool {
return db.Delete(db.ShareNotes, bson.M{"NoteId": bson.ObjectIdHex(noteId),
"UserId": bson.ObjectIdHex(userId),
"UserId": bson.ObjectIdHex(userId),
"ToGroupId": bson.ObjectIdHex(groupId),
});
})
}
//-------
// 得到笔记本分享给的groups
func (this *ShareService) GetNotebookShareGroups(notebookId, userId string) []info.ShareNotebook {
groups := groupService.GetGroupsContainOf(userId)
// 得到有分享的分组
shares := []info.ShareNotebook{}
db.ListByQ(db.ShareNotebooks,
bson.M{"NotebookId": bson.ObjectIdHex(notebookId), "UserId": bson.ObjectIdHex(userId), "ToGroupId": bson.M{"$exists":true}}, &shares)
db.ListByQ(db.ShareNotebooks,
bson.M{"NotebookId": bson.ObjectIdHex(notebookId), "UserId": bson.ObjectIdHex(userId), "ToGroupId": bson.M{"$exists": true}}, &shares)
mapShares := map[bson.ObjectId]info.ShareNotebook{}
for _, share := range shares {
mapShares[share.ToGroupId] = share
mapShares[share.ToGroupId] = share
}
LogJ(shares)
// 所有的groups都有share, 但没有share的group没有shareId
shares2 := make([]info.ShareNotebook, len(groups))
for i, group := range groups {
@ -764,25 +764,26 @@ func (this *ShareService) GetNotebookShareGroups(notebookId, userId string) []in
if !ok {
share = info.ShareNotebook{}
}
share.ToGroup = group;
share.ToGroup = group
shares2[i] = share
}
return shares2
}
// 共享笔记给分组
func (this *ShareService) AddShareNotebookGroup(userId, notebookId, groupId string, perm int) (bool) {
func (this *ShareService) AddShareNotebookGroup(userId, notebookId, groupId string, perm int) bool {
if !groupService.IsExistsGroupUser(userId, groupId) {
return false
}
// 先删除之
this.DeleteShareNotebookGroup(userId, notebookId, groupId)
shareNotebook := info.ShareNotebook{NotebookId: bson.ObjectIdHex(notebookId),
UserId: bson.ObjectIdHex(userId), // 冗余字段
ToGroupId: bson.ObjectIdHex(groupId),
Perm: perm,
shareNotebook := info.ShareNotebook{NotebookId: bson.ObjectIdHex(notebookId),
UserId: bson.ObjectIdHex(userId), // 冗余字段
ToGroupId: bson.ObjectIdHex(groupId),
Perm: perm,
CreatedTime: time.Now(),
}
return db.Insert(db.ShareNotebooks, shareNotebook)
@ -791,9 +792,9 @@ func (this *ShareService) AddShareNotebookGroup(userId, notebookId, groupId stri
// 删除
func (this *ShareService) DeleteShareNotebookGroup(userId, notebookId, groupId string) bool {
return db.Delete(db.ShareNotebooks, bson.M{"NotebookId": bson.ObjectIdHex(notebookId),
"UserId": bson.ObjectIdHex(userId),
"UserId": bson.ObjectIdHex(userId),
"ToGroupId": bson.ObjectIdHex(groupId),
});
})
}
//--------------------
@ -803,12 +804,12 @@ func (this *ShareService) DeleteShareNotebookGroup(userId, notebookId, groupId s
func (this *ShareService) DeleteAllShareNotebookGroup(groupId string) bool {
return db.Delete(db.ShareNotebooks, bson.M{
"ToGroupId": bson.ObjectIdHex(groupId),
});
})
}
func (this *ShareService) DeleteAllShareNoteGroup(groupId string) bool {
return db.Delete(db.ShareNotes, bson.M{
"ToGroupId": bson.ObjectIdHex(groupId),
});
})
}
//--------------------
@ -817,14 +818,14 @@ func (this *ShareService) DeleteAllShareNoteGroup(groupId string) bool {
func (this *ShareService) DeleteShareNotebookGroupWhenDeleteGroupUser(userId, groupId string) bool {
return db.Delete(db.ShareNotebooks, bson.M{
"UserId": bson.ObjectIdHex(userId),
"UserId": bson.ObjectIdHex(userId),
"ToGroupId": bson.ObjectIdHex(groupId),
});
})
}
func (this *ShareService) DeleteShareNoteGroupWhenDeleteGroupUser(userId, groupId string) bool {
return db.Delete(db.ShareNotes, bson.M{
"UserId": bson.ObjectIdHex(userId),
"UserId": bson.ObjectIdHex(userId),
"ToGroupId": bson.ObjectIdHex(groupId),
});
})
}

View File

@ -1,12 +1,12 @@
package service
import (
"github.com/leanote/leanote/app/info"
"github.com/leanote/leanote/app/db"
// . "github.com/leanote/leanote/app/lea"
"github.com/leanote/leanote/app/info"
// . "github.com/leanote/leanote/app/lea"
"gopkg.in/mgo.v2/bson"
// "time"
// "sort"
// "time"
// "sort"
)
type SuggestionService struct {
@ -18,4 +18,4 @@ func (this *SuggestionService) AddSuggestion(suggestion info.Suggestion) bool {
suggestion.Id = bson.NewObjectId()
}
return db.Insert(db.Suggestions, suggestion)
}
}

View File

@ -1,9 +1,9 @@
package service
import (
"github.com/leanote/leanote/app/info"
"github.com/leanote/leanote/app/db"
// . "github.com/leanote/leanote/app/lea"
"github.com/leanote/leanote/app/info"
// . "github.com/leanote/leanote/app/lea"
"gopkg.in/mgo.v2/bson"
"time"
)
@ -31,8 +31,8 @@ func (this *TagService) AddTagsI(userId string, tags interface{}) bool {
}
func (this *TagService) AddTags(userId string, tags []string) bool {
for _, tag := range tags {
if !db.Upsert(db.Tags,
bson.M{"_id": bson.ObjectIdHex(userId)},
if !db.Upsert(db.Tags,
bson.M{"_id": bson.ObjectIdHex(userId)},
bson.M{"$addToSet": bson.M{"Tags": tag}}) {
return false
}
@ -53,18 +53,18 @@ func (this *TagService) AddOrUpdateTag(userId string, tag string) info.NoteTag {
userIdO := bson.ObjectIdHex(userId)
noteTag := info.NoteTag{}
db.GetByQ(db.NoteTags, bson.M{"UserId": userIdO, "Tag": tag}, &noteTag)
// 存在, 则更新之
if noteTag.TagId != "" {
// 统计note数
count := noteService.CountNoteByTag(userId, tag)
noteTag.Count = count
noteTag.UpdatedTime = time.Now()
// noteTag.Usn = userService.IncrUsn(userId), 更新count而已
// noteTag.Usn = userService.IncrUsn(userId), 更新count而已
db.UpdateByIdAndUserId(db.NoteTags, noteTag.TagId.Hex(), userId, noteTag)
return noteTag
}
// 不存在, 则创建之
noteTag.TagId = bson.NewObjectId()
noteTag.Count = 1
@ -75,7 +75,7 @@ func (this *TagService) AddOrUpdateTag(userId string, tag string) info.NoteTag {
noteTag.Usn = userService.IncrUsn(userId)
noteTag.IsDeleted = false
db.Insert(db.NoteTags, noteTag)
return noteTag
}
@ -83,7 +83,7 @@ func (this *TagService) AddOrUpdateTag(userId string, tag string) info.NoteTag {
func (this *TagService) GetTags(userId string) []info.NoteTag {
tags := []info.NoteTag{}
query := bson.M{"UserId": bson.ObjectIdHex(userId), "IsDeleted": false}
q := db.NoteTags.Find(query);
q := db.NoteTags.Find(query)
sortFieldR := "-UpdatedTime"
q.Sort(sortFieldR).All(&tags)
return tags
@ -95,7 +95,7 @@ func (this *TagService) GetTags(userId string) []info.NoteTag {
func (this *TagService) DeleteTag(userId string, tag string) map[string]int {
usn := userService.IncrUsn(userId)
if db.UpdateByQMap(db.NoteTags, bson.M{"UserId": bson.ObjectIdHex(userId), "Tag": tag}, bson.M{"Usn": usn, "IsDeleted": true}) {
return noteService.UpdateNoteToDeleteTag(userId, tag);
return noteService.UpdateNoteToDeleteTag(userId, tag)
}
return map[string]int{}
}
@ -104,7 +104,7 @@ func (this *TagService) DeleteTag(userId string, tag string) map[string]int {
func (this *TagService) DeleteTagApi(userId string, tag string, usn int) (ok bool, msg string, toUsn int) {
noteTag := info.NoteTag{}
db.GetByQ(db.NoteTags, bson.M{"UserId": bson.ObjectIdHex(userId), "Tag": tag}, &noteTag)
if noteTag.TagId == "" {
return false, "notExists", 0
}
@ -124,14 +124,14 @@ func (this *TagService) reCountTagCount(userId string, tags []string) {
return
}
for _, tag := range tags {
this.AddOrUpdateTag(userId, tag);
this.AddOrUpdateTag(userId, tag)
}
}
// 同步用
func (this *TagService) GeSyncTags(userId string, afterUsn, maxEntry int) ([]info.NoteTag) {
func (this *TagService) GeSyncTags(userId string, afterUsn, maxEntry int) []info.NoteTag {
noteTags := []info.NoteTag{}
q := db.NoteTags.Find(bson.M{"UserId": bson.ObjectIdHex(userId), "Usn": bson.M{"$gt": afterUsn}});
q := db.NoteTags.Find(bson.M{"UserId": bson.ObjectIdHex(userId), "Usn": bson.M{"$gt": afterUsn}})
q.Sort("Usn").Limit(maxEntry).All(&noteTags)
return noteTags
}

View File

@ -1,20 +1,20 @@
package service
import (
"github.com/revel/revel"
"github.com/leanote/leanote/app/info"
"encoding/json"
"fmt"
"github.com/leanote/leanote/app/db"
"github.com/leanote/leanote/app/info"
. "github.com/leanote/leanote/app/lea"
"github.com/leanote/leanote/app/lea/archive"
"github.com/revel/revel"
"gopkg.in/mgo.v2/bson"
"time"
"strings"
"os"
"fmt"
"html/template"
"regexp"
"io/ioutil"
"encoding/json"
"os"
"regexp"
"strings"
"time"
)
// 主题
@ -29,6 +29,7 @@ var fixedStyle = "blog_left_fixed"
func (this *ThemeService) getDefaultThemeBasePath() string {
return revel.BasePath + "/public/blog/themes"
}
// 默认主题路径
func (this *ThemeService) getDefaultThemePath(style string) string {
if style == elegantStyle {
@ -39,6 +40,7 @@ func (this *ThemeService) getDefaultThemePath(style string) string {
return this.getDefaultThemeBasePath() + "/default"
}
}
// blogService用
func (this *ThemeService) GetDefaultThemePath(style string) string {
if style == elegantStyle {
@ -51,34 +53,34 @@ func (this *ThemeService) GetDefaultThemePath(style string) string {
}
// 得到默认主题
// style是之前的值, 有3个值 blog_default, blog_daqi, blog_left_fixed
// style是之前的值, 有3个值 blog_default, blog_daqi, blog_left_fixed
func (this *ThemeService) getDefaultTheme(style string) info.Theme {
if style == elegantStyle {
return info.Theme{
IsDefault: true,
Path: "public/blog/themes/elegant",
Name: "leanote elegant",
Author: "leanote",
Path: "public/blog/themes/elegant",
Name: "leanote elegant",
Author: "leanote",
AuthorUrl: "http://leanote.com",
Version: "1.0",
Version: "1.0",
}
} else if style == fixedStyle {
return info.Theme{
IsDefault: true,
Path: "public/blog/themes/nav_fixed",
Name: "leanote nav fixed",
Author: "leanote",
Path: "public/blog/themes/nav_fixed",
Name: "leanote nav fixed",
Author: "leanote",
AuthorUrl: "http://leanote.com",
Version: "1.0",
Version: "1.0",
}
} else { // blog default
return info.Theme{
IsDefault: true,
Path: "public/blog/themes/default",
Name: "leanote default",
Author: "leanote",
Path: "public/blog/themes/default",
Name: "leanote default",
Author: "leanote",
AuthorUrl: "http://leanote.com",
Version: "1.0",
Version: "1.0",
}
}
}
@ -103,15 +105,15 @@ func (this *ThemeService) CopyDefaultTheme(userBlog info.UserBlog) (ok bool, the
themePath := this.getUserThemePath(userId, themeId)
err := os.MkdirAll(themePath, 0755)
if err != nil {
return
return
}
// 复制默认主题
defaultThemePath := this.getDefaultThemePath(userBlog.Style)
err = CopyDir(defaultThemePath, themePath)
if err != nil {
return
return
}
// 保存到数据库中
theme, _ := this.getThemeConfig(themePath)
theme.ThemeId = newThemeId
@ -119,7 +121,7 @@ func (this *ThemeService) CopyDefaultTheme(userBlog info.UserBlog) (ok bool, the
theme.CreatedTime = time.Now()
theme.UpdatedTime = theme.CreatedTime
theme.UserId = bson.ObjectIdHex(userId)
ok = db.Insert(db.Themes, theme)
return ok, themeId
}
@ -141,7 +143,7 @@ func (this *ThemeService) NewTheme(userId string) (ok bool, themeId string) {
themeService.NewThemeForFirst(userBlog)
}
// 再copy一个默认主题
userBlog.Style = "defaultStyle";
userBlog.Style = "defaultStyle"
ok, themeId = this.CopyDefaultTheme(userBlog)
return
}
@ -151,37 +153,37 @@ func (this *ThemeService) parseConfig(configStr string) (theme info.Theme, err e
theme = info.Theme{}
// 除去/**/注释
reg, _ := regexp.Compile("/\\*[\\s\\S]*?\\*/")
configStr = reg.ReplaceAllString(configStr, "")
configStr = reg.ReplaceAllString(configStr, "")
// 转成map
config := map[string]interface{}{}
err = json.Unmarshal([]byte(configStr), &config)
if err != nil {
return
}
// 没有错, 则将Name, Version, Author, AuthorUrl
Name := config["Name"]
if Name != nil {
theme.Name = Name.(string)
}
Version := config["Version"]
if Version != nil {
theme.Version = Version.(string)
}
Author := config["Author"]
if Author != nil {
theme.Author = Author.(string)
}
AuthorUrl := config["AuthorUrl"]
if AuthorUrl != nil {
theme.AuthorUrl = AuthorUrl.(string)
}
theme.Info = config
return
if err != nil {
return
}
// 没有错, 则将Name, Version, Author, AuthorUrl
Name := config["Name"]
if Name != nil {
theme.Name = Name.(string)
}
Version := config["Version"]
if Version != nil {
theme.Version = Version.(string)
}
Author := config["Author"]
if Author != nil {
theme.Author = Author.(string)
}
AuthorUrl := config["AuthorUrl"]
if AuthorUrl != nil {
theme.AuthorUrl = AuthorUrl.(string)
}
theme.Info = config
return
}
// 读取theme.json得到值
func (this *ThemeService) getThemeConfig(themePath string) (theme info.Theme, err error) {
func (this *ThemeService) getThemeConfig(themePath string) (theme info.Theme, err error) {
theme = info.Theme{}
configStr := GetFileStrContent(themePath + "/theme.json")
theme, err = this.parseConfig(configStr)
@ -222,12 +224,12 @@ func (this *ThemeService) GetThemeInfo(themeId, style string) map[string]interfa
func (this *ThemeService) GetUserThemes(userId string) (theme info.Theme, themes []info.Theme) {
theme = info.Theme{}
themes = []info.Theme{}
// db.ListByQ(db.Themes, bson.M{"UserId": bson.ObjectIdHex(userId)}, &themes)
// db.ListByQ(db.Themes, bson.M{"UserId": bson.ObjectIdHex(userId)}, &themes)
// 创建时间逆序
query := bson.M{"UserId": bson.ObjectIdHex(userId)}
q := db.Themes.Find(query);
q := db.Themes.Find(query)
q.Sort("-CreatedTime").All(&themes)
if len(themes) == 0 {
userBlog := blogService.GetUserBlog(userId)
@ -285,6 +287,7 @@ func (this *ThemeService) GetThemePath(userId, themeId string) string {
}
return ""
}
// 更新模板内容
func (this *ThemeService) UpdateTplContent(userId, themeId, filename, content string) (ok bool, msg string) {
basePath := this.GetThemeAbsolutePath(userId, themeId)
@ -305,13 +308,13 @@ func (this *ThemeService) UpdateTplContent(userId, themeId, filename, content st
return false, fmt.Sprintf("%v", err)
}
// 正确, 更新theme信息
ok = db.UpdateByQMap(db.Themes, bson.M{"_id": bson.ObjectIdHex(themeId), "UserId": bson.ObjectIdHex(userId)},
ok = db.UpdateByQMap(db.Themes, bson.M{"_id": bson.ObjectIdHex(themeId), "UserId": bson.ObjectIdHex(userId)},
bson.M{
"Name": theme.Name,
"Version": theme.Version,
"Author": theme.Author,
"Name": theme.Name,
"Version": theme.Version,
"Author": theme.Author,
"AuthorUrl": theme.AuthorUrl,
"Info": theme.Info,
"Info": theme.Info,
})
if ok {
ok = PutFileStrContent(path, content)
@ -351,7 +354,7 @@ func (this *ThemeService) ActiveTheme(userId, themeId string) (ok bool) {
db.UpdateByQField(db.Themes, bson.M{"UserId": bson.ObjectIdHex(userId), "IsActive": true}, "IsActive", false)
// 现在的设为true
db.UpdateByQField(db.Themes, bson.M{"_id": bson.ObjectIdHex(themeId)}, "IsActive", true)
// UserBlog ThemeId
db.UpdateByQField(db.UserBlogs, bson.M{"_id": bson.ObjectIdHex(userId)}, "ThemeId", bson.ObjectIdHex(themeId))
return true
@ -361,7 +364,7 @@ func (this *ThemeService) ActiveTheme(userId, themeId string) (ok bool) {
// 删除主题
func (this *ThemeService) DeleteTheme(userId, themeId string) (ok bool) {
return db.Delete(db.Themes,bson.M{"_id": bson.ObjectIdHex(themeId), "UserId": bson.ObjectIdHex(userId), "IsActive": false})
return db.Delete(db.Themes, bson.M{"_id": bson.ObjectIdHex(themeId), "UserId": bson.ObjectIdHex(userId), "IsActive": false})
}
// 公开主题, 只有管理员才有权限, 之前没公开的变成公开
@ -375,37 +378,37 @@ func (this *ThemeService) PublicTheme(userId, themeId string) (ok bool) {
return false
}
// 导出主题
func (this *ThemeService) ExportTheme(userId, themeId string) (ok bool, path string) {
theme := this.GetThemeById(themeId)
// 打包
// 验证路径, 别把整个项目打包了
Log(theme.Path)
if theme.Path == "" ||
if theme.Path == "" ||
(!strings.HasPrefix(theme.Path, "public/upload") &&
!strings.HasPrefix(theme.Path, "public/blog/themes")) ||
!strings.HasPrefix(theme.Path, "public/blog/themes")) ||
strings.Contains(theme.Path, "..") {
return
}
sourcePath := revel.BasePath + "/" + theme.Path
sourcePath := revel.BasePath + "/" + theme.Path
targetPath := revel.BasePath + "/public/upload/" + userId + "/tmp"
err := os.MkdirAll(targetPath, 0755)
if err != nil {
Log(err)
return
return
}
targetName := targetPath + "/" + theme.Name + ".zip"
Log(sourcePath)
Log(targetName)
ok = archive.Zip(sourcePath, targetName)
ok = archive.Zip(sourcePath, targetName)
if !ok {
return
}
return true, targetName
}
// 导入主题
// path == /llllllll/..../public/upload/.../aa.zip, 绝对路径
func (this *ThemeService) ImportTheme(userId, path string) (ok bool, msg string) {
@ -416,14 +419,14 @@ func (this *ThemeService) ImportTheme(userId, path string) (ok bool, msg string)
err := os.MkdirAll(targetPath, 0755)
if err != nil {
msg = "error"
return
return
}
if ok, msg = archive.Unzip(path, targetPath); !ok {
DeleteFile(targetPath)
Log("oh no")
return
}
// 主题验证
if ok, msg = this.ValidateTheme(targetPath, "", ""); !ok {
DeleteFile(targetPath)
@ -443,13 +446,13 @@ func (this *ThemeService) ImportTheme(userId, path string) (ok bool, msg string)
theme.CreatedTime = time.Now()
theme.UpdatedTime = theme.CreatedTime
theme.UserId = bson.ObjectIdHex(userId)
ok = db.Insert(db.Themes, theme)
if !ok {
DeleteFile(targetPath)
}
DeleteFile(path)
return
return
}
// 升级用
@ -492,28 +495,28 @@ func (this *ThemeService) InstallTheme(userId, themeId string) (ok bool) {
if !theme.IsDefault {
return false
}
// 用户之前是否有主题?
userBlog := blogService.GetUserBlog(userId)
if userBlog.ThemeId == "" {
this.NewThemeForFirst(userBlog)
}
// 生成新主题
newThemeId := bson.NewObjectId()
themeId = newThemeId.Hex()
themePath := this.getUserThemePath(userId, themeId)
err := os.MkdirAll(themePath, 0755)
if err != nil {
return
return
}
// 复制默认主题
sourceThemePath := revel.BasePath + "/" + theme.Path
err = CopyDir(sourceThemePath, themePath)
if err != nil {
return
return
}
// 保存到数据库中
theme, _ = this.getThemeConfig(themePath)
theme.ThemeId = newThemeId
@ -521,11 +524,11 @@ func (this *ThemeService) InstallTheme(userId, themeId string) (ok bool) {
theme.CreatedTime = time.Now()
theme.UpdatedTime = theme.CreatedTime
theme.UserId = bson.ObjectIdHex(userId)
ok = db.Insert(db.Themes, theme)
// 激活之
this.ActiveTheme(userId, themeId);
this.ActiveTheme(userId, themeId)
return ok
}
@ -535,39 +538,39 @@ func (this *ThemeService) InstallTheme(userId, themeId string) (ok bool) {
func (this *ThemeService) ValidateTheme(path string, filename, newContent string) (ok bool, msg string) {
Log("theme Path")
Log(path)
// 建立一个有向图
// 建立一个有向图
// 将该path下的所有文件提出, 得到文件的引用情况
files := ListDir(path)
LogJ(files);
LogJ(files)
size := len(files)
if(size > 100) {
ok = false;
if size > 100 {
ok = false
msg = "tooManyFiles"
return
}
/*
111111111
111000000
111111111
111000000
*/
vector := make([][]int, size)
for i := 0; i < size; i++ {
vector[i] = make([]int, size)
}
fileIndexMap := map[string]int{} // fileName => index
fileIndexMap := map[string]int{} // fileName => index
fileContent := map[string]string{} // fileName => content
index := 0
// 得到文件内容, 和建立索引, 每个文件都有一个index, 对应数组位置
for _, t := range files {
if !strings.Contains(t, ".html") {
continue;
continue
}
if t != filename {
fileBytes, err := ioutil.ReadFile(path + "/" + t)
if err != nil {
continue
}
fileIndexMap[t] = index;
fileIndexMap[t] = index
// html内容
fileStr := string(fileBytes)
fileContent[t] = fileStr
@ -583,7 +586,7 @@ func (this *ThemeService) ValidateTheme(path string, filename, newContent string
thisIndex := fileIndexMap[filename]
finds := reg.FindAllStringSubmatch(content, -1) // 子匹配
LogJ(finds)
// Log(content)
// Log(content)
if finds != nil && len(finds) > 0 {
for _, includes := range finds {
include := includes[1]
@ -597,7 +600,7 @@ func (this *ThemeService) ValidateTheme(path string, filename, newContent string
}
}
}
LogJ(vector)
LogJ(fileIndexMap)
// 建立图后, 判断是否有环
@ -607,7 +610,7 @@ func (this *ThemeService) ValidateTheme(path string, filename, newContent string
} else {
ok = true
}
return;
return
}
// 检测有向图是否有环, DFS
@ -616,8 +619,8 @@ func (this *ThemeService) hasRound(vector [][]int, size int) (ok bool) {
visited := make([]int, size)
if this.hasRoundEach(vector, i, size, visited) {
Log(">>")
Log(i);
return true;
Log(i)
return true
}
}
return false
@ -630,13 +633,13 @@ func (this *ThemeService) hasRoundEach(vector [][]int, index int, size int, visi
Log(index)
return true
}
visited[index] = 1;
visited[index] = 1
// 遍历它的孩子
for i := 0; i < size; i++ {
if vector[index][i] > 0 {
return this.hasRoundEach(vector, i, size, visited);
return this.hasRoundEach(vector, i, size, visited)
}
}
visited[index] = 0;
return false;
visited[index] = 0
return false
}

View File

@ -1,10 +1,10 @@
package service
import (
"gopkg.in/mgo.v2/bson"
"github.com/leanote/leanote/app/db"
"github.com/leanote/leanote/app/info"
. "github.com/leanote/leanote/app/lea"
"gopkg.in/mgo.v2/bson"
"time"
)
@ -18,11 +18,11 @@ type TokenService struct {
// 生成token
func (this *TokenService) NewToken(userId string, email string, tokenType int) string {
token := info.Token{UserId: bson.ObjectIdHex(userId), Token: NewGuidWith(email), CreatedTime: time.Now(), Email: email, Type: tokenType}
if db.Upsert(db.Tokens, bson.M{"_id": token.UserId}, token) {
return token.Token
}
return ""
}
@ -50,23 +50,23 @@ func (this *TokenService) VerifyToken(token string, tokenType int) (ok bool, msg
msg = "不存在"
return
}
db.GetByQ(db.Tokens, bson.M{"Token": token}, &tokenInfo)
if tokenInfo.UserId == "" {
msg = "不存在"
return
}
// 验证是否过时
now := time.Now()
duration := now.Sub(tokenInfo.CreatedTime)
if duration.Hours() > overHours {
msg = "过期"
return
}
ok = true
return
}
}

View File

@ -1,9 +1,9 @@
package service
import (
"gopkg.in/mgo.v2/bson"
"github.com/leanote/leanote/app/db"
"github.com/leanote/leanote/app/info"
"gopkg.in/mgo.v2/bson"
)
// 回收站
@ -25,9 +25,9 @@ type TrashService struct {
// 应该放在回收站里
// 有trashService
func (this *TrashService) DeleteNote(noteId, userId string) bool {
note := noteService.GetNote(noteId, userId);
note := noteService.GetNote(noteId, userId)
// 如果是垃圾, 则彻底删除
if (note.IsTrash) {
if note.IsTrash {
return this.DeleteTrash(noteId, userId)
}
@ -42,7 +42,7 @@ func (this *TrashService) DeleteNote(noteId, userId string) bool {
return true
}
}
return false
}
@ -59,16 +59,16 @@ func (this *TrashService) DeleteSharedNote(noteId, myUserId string) bool {
// recover
func (this *TrashService) recoverNote(noteId, notebookId, userId string) bool {
re := db.UpdateByIdAndUserId(db.Notes, noteId, userId,
bson.M{"$set": bson.M{"IsTrash": false,
"Usn": userService.IncrUsn(userId),
re := db.UpdateByIdAndUserId(db.Notes, noteId, userId,
bson.M{"$set": bson.M{"IsTrash": false,
"Usn": userService.IncrUsn(userId),
"NotebookId": bson.ObjectIdHex(notebookId)}})
return re;
return re
}
// 删除trash
func (this *TrashService) DeleteTrash(noteId, userId string) bool {
note := noteService.GetNote(noteId, userId);
note := noteService.GetNote(noteId, userId)
if note.NoteId == "" {
return false
}
@ -76,52 +76,52 @@ func (this *TrashService) DeleteTrash(noteId, userId string) bool {
ok := attachService.DeleteAllAttachs(noteId, userId)
// 设置删除位
ok = db.UpdateByIdAndUserIdMap(db.Notes, noteId, userId,
bson.M{"IsDeleted": true,
ok = db.UpdateByIdAndUserIdMap(db.Notes, noteId, userId,
bson.M{"IsDeleted": true,
"Usn": userService.IncrUsn(userId)})
// delete note
// ok = db.DeleteByIdAndUserId(db.Notes, noteId, userId)
// ok = db.DeleteByIdAndUserId(db.Notes, noteId, userId)
// delete content
ok = db.DeleteByIdAndUserId(db.NoteContents, noteId, userId)
// 重新统计tag's count
// TODO 这里会改变tag's Usn
tagService.reCountTagCount(userId, note.Tags)
return ok
}
func (this *TrashService) DeleteTrashApi(noteId, userId string, usn int) (bool, string, int) {
note := noteService.GetNote(noteId, userId)
if note.NoteId == "" || note.IsDeleted {
return false, "notExists", 0
}
if note.Usn != usn {
return false, "conflict", 0
}
// delete note's attachs
ok := attachService.DeleteAllAttachs(noteId, userId)
// 设置删除位
afterUsn := userService.IncrUsn(userId)
ok = db.UpdateByIdAndUserIdMap(db.Notes, noteId, userId,
bson.M{"IsDeleted": true,
ok = db.UpdateByIdAndUserIdMap(db.Notes, noteId, userId,
bson.M{"IsDeleted": true,
"Usn": afterUsn})
// delete content
ok = db.DeleteByIdAndUserId(db.NoteContents, noteId, userId)
return ok, "", afterUsn
}
// 列出note, 排序规则, 还有分页
// CreatedTime, UpdatedTime, title 来排序
func (this *TrashService) ListNotes(userId string,
pageNumber, pageSize int, sortField string, isAsc bool) (notes []info.Note) {
func (this *TrashService) ListNotes(userId string,
pageNumber, pageSize int, sortField string, isAsc bool) (notes []info.Note) {
_, notes = noteService.ListNotes(userId, "", true, pageNumber, pageSize, sortField, isAsc, false)
return
}

View File

@ -1,14 +1,13 @@
package service
import (
"github.com/leanote/leanote/app/db"
"github.com/leanote/leanote/app/info"
. "github.com/leanote/leanote/app/lea"
"github.com/leanote/leanote/app/db"
"gopkg.in/mgo.v2/bson"
"time"
)
type UpgradeService struct {
}
@ -16,7 +15,7 @@ type UpgradeService struct {
func (this *UpgradeService) UpgradeBlog() bool {
notes := []info.Note{}
db.ListByQ(db.Notes, bson.M{"IsBlog": true}, &notes)
// PublicTime, RecommendTime = UpdatedTime
for _, note := range notes {
if note.IsBlog && note.PublicTime.Year() < 100 {
@ -24,7 +23,7 @@ func (this *UpgradeService) UpgradeBlog() bool {
Log(note.NoteId.Hex())
}
}
return true
}
@ -40,25 +39,25 @@ func (this *UpgradeService) UpgradeBetaToBeta2(userId string) (ok bool, msg stri
if configService.GetGlobalStringConfig("UpgradeBetaToBeta2") != "" {
return false, "Leanote have been upgraded"
}
// 1. aboutMe -> page
userBlogs := []info.UserBlog{}
db.ListByQ(db.UserBlogs, bson.M{}, &userBlogs)
for _, userBlog := range userBlogs {
blogService.AddOrUpdateSingle(userBlog.UserId.Hex(), "", "About Me", userBlog.AboutMe)
}
// 2. 默认主题, 给admin用户
themeService.UpgradeThemeBeta2()
// 3. UrlTitles
// 3.1 note
notes := []info.Note{}
db.ListByQ(db.Notes, bson.M{}, &notes)
for _, note := range notes {
data := bson.M{}
data := bson.M{}
noteId := note.NoteId.Hex()
// PublicTime, RecommendTime = UpdatedTime
if note.IsBlog && note.PublicTime.Year() < 100 {
@ -70,7 +69,7 @@ func (this *UpgradeService) UpgradeBetaToBeta2(userId string) (ok bool, msg stri
db.UpdateByIdAndUserIdMap2(db.Notes, note.NoteId, note.UserId, data)
Log(noteId)
}
// 3.2
Log("notebook")
notebooks := []info.Notebook{}
@ -82,24 +81,24 @@ func (this *UpgradeService) UpgradeBetaToBeta2(userId string) (ok bool, msg stri
db.UpdateByIdAndUserIdMap2(db.Notebooks, notebook.NotebookId, notebook.UserId, data)
Log(notebookId)
}
// 3.3 single
/*
singles := []info.BlogSingle{}
db.ListByQ(db.BlogSingles, bson.M{}, &singles)
for _, single := range singles {
singleId := single.SingleId.Hex()
blogService.UpdateSingleUrlTitle(single.UserId.Hex(), singleId, single.Title)
Log(singleId)
}
singles := []info.BlogSingle{}
db.ListByQ(db.BlogSingles, bson.M{}, &singles)
for _, single := range singles {
singleId := single.SingleId.Hex()
blogService.UpdateSingleUrlTitle(single.UserId.Hex(), singleId, single.Title)
Log(singleId)
}
*/
// 删除索引
db.ShareNotes.DropIndex("UserId", "ToUserId", "NoteId")
ok = true
msg = "success"
configService.UpdateGlobalStringConfig(userId, "UpgradeBetaToBeta2", "1")
return
}
@ -134,8 +133,8 @@ func (this *UpgradeService) moveTag() {
func (this *UpgradeService) setNotebookUsn() {
usnI := 1
notebooks := []info.Notebook{}
db.ListByQWithFields(db.Notebooks, bson.M{}, []string{"UserId"}, &notebooks)
db.ListByQWithFields(db.Notebooks, bson.M{}, []string{"UserId"}, &notebooks)
for _, notebook := range notebooks {
db.UpdateByQField(db.Notebooks, bson.M{"_id": notebook.NotebookId}, "Usn", usnI)
usnI++
@ -145,8 +144,8 @@ func (this *UpgradeService) setNotebookUsn() {
func (this *UpgradeService) setNoteUsn() {
usnI := 1
notes := []info.Note{}
db.ListByQWithFields(db.Notes, bson.M{}, []string{"UserId"}, &notes)
db.ListByQWithFields(db.Notes, bson.M{}, []string{"UserId"}, &notes)
for _, note := range notes {
db.UpdateByQField(db.Notes, bson.M{"_id": note.NoteId}, "Usn", usnI)
usnI++
@ -158,25 +157,25 @@ func (this *UpgradeService) Api(userId string) (ok bool, msg string) {
if configService.GetGlobalStringConfig("UpgradeBetaToBeta4") != "" {
return false, "Leanote have been upgraded"
}
// user
db.UpdateByQField(db.Users, bson.M{}, "Usn", 200000)
// notebook
db.UpdateByQField(db.Notebooks, bson.M{}, "IsDeleted", false)
this.setNotebookUsn();
this.setNotebookUsn()
// note
// 1-N
db.UpdateByQField(db.Notes, bson.M{}, "IsDeleted", false)
this.setNoteUsn();
this.setNoteUsn()
// tag
// 1-N
/// tag, 要重新插入, 将之前的Tag表迁移到NoteTag中
this.moveTag();
this.moveTag()
configService.UpdateGlobalStringConfig(userId, "UpgradeBetaToBeta4", "1")
return true, ""
}

View File

@ -1,12 +1,12 @@
package service
import (
"github.com/leanote/leanote/app/info"
"github.com/leanote/leanote/app/db"
"github.com/leanote/leanote/app/info"
. "github.com/leanote/leanote/app/lea"
"gopkg.in/mgo.v2/bson"
"time"
"strings"
"time"
)
type UserService struct {
@ -23,7 +23,7 @@ func (this *UserService) IncrUsn(userId string) int {
Log("inc Usn")
db.UpdateByQField(db.Users, query, "Usn", usn)
return usn
// return db.Update(db.Notes, bson.M{"_id": bson.ObjectIdHex(noteId)}, bson.M{"$inc": bson.M{"ReadNum": 1}})
// return db.Update(db.Notes, bson.M{"_id": bson.ObjectIdHex(noteId)}, bson.M{"$inc": bson.M{"ReadNum": 1}})
}
func (this *UserService) GetUsn(userId string) int {
@ -39,18 +39,18 @@ func (this *UserService) AddUser(user info.User) bool {
user.UserId = bson.NewObjectId()
}
user.CreatedTime = time.Now()
if user.Email != "" {
user.Email = strings.ToLower(user.Email)
// 发送验证邮箱
go func() {
emailService.RegisterSendActiveEmail(user, user.Email)
// 发送给我 life@leanote.com
emailService.SendEmail("life@leanote.com", "新增用户", "{header}用户名" + user.Email + "{footer}");
}();
emailService.SendEmail("life@leanote.com", "新增用户", "{header}用户名"+user.Email+"{footer}")
}()
}
return db.Insert(db.Users, user)
}
@ -94,11 +94,11 @@ func (this *UserService) GetUserInfoByAny(idEmailUsername string) info.User {
if IsObjectId(idEmailUsername) {
return this.GetUserInfo(idEmailUsername)
}
if strings.Contains(idEmailUsername, "@") {
return this.GetUserInfoByEmail(idEmailUsername)
}
// username
return this.GetUserInfoByUsername(idEmailUsername)
}
@ -111,7 +111,7 @@ func (this *UserService) setUserLogo(user *info.User) {
if user.Logo != "" && !strings.HasPrefix(user.Logo, "http") {
user.Logo = strings.Trim(user.Logo, "/")
user.Logo = configService.GetSiteUrl() + "/" + user.Logo
}
}
}
// 仅得到用户
@ -129,6 +129,7 @@ func (this *UserService) GetUserInfo(userId string) info.User {
this.setUserLogo(&user)
return user
}
// 得到用户信息 email
func (this *UserService) GetUserInfoByEmail(email string) info.User {
user := info.User{}
@ -137,6 +138,7 @@ func (this *UserService) GetUserInfoByEmail(email string) info.User {
this.setUserLogo(&user)
return user
}
// 得到用户信息 username
func (this *UserService) GetUserInfoByUsername(username string) info.User {
user := info.User{}
@ -163,11 +165,12 @@ func (this *UserService) ListUserInfosByEmails(emails []string) []info.User {
db.ListByQ(db.Users, bson.M{"Email": bson.M{"$in": emails}}, &users)
return users
}
// 用户信息即可
func (this *UserService) MapUserInfoByUserIds(userIds []bson.ObjectId) map[bson.ObjectId]info.User {
users := []info.User{}
db.ListByQ(db.Users, bson.M{"_id": bson.M{"$in": userIds}}, &users)
userMap := make(map[bson.ObjectId]info.User, len(users))
for _, user := range users {
this.setUserLogo(&user)
@ -175,6 +178,7 @@ func (this *UserService) MapUserInfoByUserIds(userIds []bson.ObjectId) map[bson.
}
return userMap
}
// 用户信息和博客设置信息
func (this *UserService) MapUserInfoAndBlogInfosByUserIds(userIds []bson.ObjectId) map[bson.ObjectId]info.User {
return this.MapUserInfoByUserIds(userIds)
@ -184,33 +188,33 @@ func (this *UserService) MapUserInfoAndBlogInfosByUserIds(userIds []bson.ObjectI
func (this *UserService) MapUserAndBlogByUserIds(userIds []bson.ObjectId) map[string]info.UserAndBlog {
users := []info.User{}
db.ListByQ(db.Users, bson.M{"_id": bson.M{"$in": userIds}}, &users)
userBlogs := []info.UserBlog{}
db.ListByQ(db.UserBlogs, bson.M{"_id": bson.M{"$in": userIds}}, &userBlogs)
userBlogMap := make(map[bson.ObjectId]info.UserBlog, len(userBlogs))
for _, user := range userBlogs {
userBlogMap[user.UserId] = user
}
userAndBlogMap := make(map[string]info.UserAndBlog, len(users))
for _, user := range users {
this.setUserLogo(&user)
userBlog, ok := userBlogMap[user.UserId]
if !ok {
continue
}
userAndBlogMap[user.UserId.Hex()] = info.UserAndBlog{
UserId: user.UserId,
Username: user.Username,
Email: user.Email,
Logo: user.Logo,
UserId: user.UserId,
Username: user.Username,
Email: user.Email,
Logo: user.Logo,
BlogTitle: userBlog.Title,
BlogLogo: userBlog.Logo,
BlogUrl: blogService.GetUserBlogUrl(&userBlog, user.Username),
BlogLogo: userBlog.Logo,
BlogUrl: blogService.GetUserBlogUrl(&userBlog, user.Username),
}
}
return userAndBlogMap
@ -220,11 +224,11 @@ func (this *UserService) MapUserAndBlogByUserIds(userIds []bson.ObjectId) map[st
func (this *UserService) GetUserAndBlogUrl(userId string) info.UserAndBlogUrl {
user := this.GetUserInfo(userId)
userBlog := blogService.GetUserBlog(userId)
blogUrls := blogService.GetBlogUrls(&userBlog, &user)
return info.UserAndBlogUrl{
User: user,
User: user,
BlogUrl: blogUrls.IndexUrl,
PostUrl: blogUrls.PostUrl,
}
@ -249,15 +253,15 @@ func (this *UserService) GetUserAndBlog(userId string) info.UserAndBlog {
// 通过ids得到users, 按id的顺序组织users
func (this *UserService) GetUserInfosOrderBySeq(userIds []bson.ObjectId) []info.User {
users := []info.User{}
db.ListByQ(db.Users, bson.M{"_id": bson.M{"$in": userIds}}, &users);
db.ListByQ(db.Users, bson.M{"_id": bson.M{"$in": userIds}}, &users)
usersMap := map[bson.ObjectId]info.User{}
for _, user := range users {
usersMap[user.UserId] = user
}
hasAppend := map[bson.ObjectId]bool{} // 为了防止userIds有重复的
users2 := []info.User{};
users2 := []info.User{}
for _, userId := range userIds {
if user, ok := usersMap[userId]; ok && !hasAppend[userId] {
hasAppend[userId] = true
@ -270,7 +274,7 @@ func (this *UserService) GetUserInfosOrderBySeq(userIds []bson.ObjectId) []info.
// 使用email(username), 得到用户信息
func (this *UserService) GetUserInfoByName(emailOrUsername string) info.User {
emailOrUsername = strings.ToLower(emailOrUsername)
user := info.User{}
if strings.Contains(emailOrUsername, "@") {
db.GetByQ(db.Users, bson.M{"Email": emailOrUsername}, &user)
@ -288,19 +292,19 @@ func (this *UserService) UpdateUsername(userId, username string) (bool, string)
}
usernameRaw := username // 原先的, 可能是同一个, 但有大小写
username = strings.ToLower(username)
// 先判断是否存在
userIdO := bson.ObjectIdHex(userId)
if db.Has(db.Users, bson.M{"Username": username, "_id": bson.M{"$ne": userIdO}}) {
return false, "usernameIsExisted"
}
ok := db.UpdateByQMap(db.Users, bson.M{"_id": userIdO}, bson.M{"Username": username, "UsernameRaw": usernameRaw})
return ok, ""
}
// 修改头像
func (this *UserService) UpdateAvatar(userId, avatarPath string) (bool) {
func (this *UserService) UpdateAvatar(userId, avatarPath string) bool {
userIdO := bson.ObjectIdHex(userId)
return db.UpdateByQField(db.Users, bson.M{"_id": userIdO}, "Logo", avatarPath)
}
@ -327,7 +331,7 @@ func (this *UserService) ResetPwd(adminUserId, userId, pwd string) (ok bool, msg
if configService.GetAdminUserId() != adminUserId {
return
}
passwd := GenPwd(pwd)
if passwd == "" {
return false, "GenerateHash error"
@ -337,24 +341,24 @@ func (this *UserService) ResetPwd(adminUserId, userId, pwd string) (ok bool, msg
}
// 修改主题
func (this *UserService) UpdateTheme(userId, theme string) (bool) {
func (this *UserService) UpdateTheme(userId, theme string) bool {
ok := db.UpdateByQField(db.Users, bson.M{"_id": bson.ObjectIdHex(userId)}, "Theme", theme)
return ok
}
// 帐户类型设置
func (this *UserService) UpdateAccount(userId, accountType string, accountStartTime, accountEndTime time.Time,
func (this *UserService) UpdateAccount(userId, accountType string, accountStartTime, accountEndTime time.Time,
maxImageNum, maxImageSize, maxAttachNum, maxAttachSize, maxPerAttachSize int) bool {
return db.UpdateByQI(db.Users, bson.M{"_id": bson.ObjectIdHex(userId)}, info.UserAccount{
AccountType: accountType,
AccountStartTime: accountStartTime,
AccountEndTime: accountEndTime,
MaxImageNum: maxImageNum,
MaxImageSize: maxImageSize,
MaxAttachNum: maxAttachNum,
MaxAttachSize: maxAttachSize,
MaxPerAttachSize: maxPerAttachSize,
})
AccountType: accountType,
AccountStartTime: accountStartTime,
AccountEndTime: accountEndTime,
MaxImageNum: maxImageNum,
MaxImageSize: maxImageSize,
MaxAttachNum: maxAttachNum,
MaxAttachSize: maxAttachSize,
MaxPerAttachSize: maxPerAttachSize,
})
}
//---------------
@ -370,14 +374,14 @@ func (this *UserService) ActiveEmail(token string) (ok bool, msg, email string)
if userInfo.UserId == "" {
ok = false
msg = "不存在该用户"
return
return
}
// 修改之, 并将verified = true
ok = db.UpdateByQMap(db.Users, bson.M{"_id": userInfo.UserId}, bson.M{"Verified": true})
return
}
ok = false
msg = "该链接已过期"
return
@ -397,12 +401,12 @@ func (this *UserService) UpdateEmail(token string) (ok bool, msg, email string)
msg = "该邮箱已注册"
return
}
// 修改之, 并将verified = true
ok = db.UpdateByQMap(db.Users, bson.M{"_id": tokenInfo.UserId}, bson.M{"Email": email, "Verified": true})
return
}
ok = false
msg = "该链接已过期"
return
@ -417,13 +421,13 @@ func (this *UserService) ThirdAddUser(userId, email, pwd string) (ok bool, msg s
msg = "你已有帐户"
return
}
// 判断email是否存在
if this.IsExistsUser(email) {
msg = "该用户已存在"
return
}
ok = db.UpdateByQMap(db.Users, bson.M{"_id": bson.ObjectIdHex(userId)}, bson.M{"Email": email, "Pwd": Md5(pwd)})
return
}
@ -432,12 +436,13 @@ func (this *UserService) ThirdAddUser(userId, email, pwd string) (ok bool, msg s
// 偏好设置
// 宽度
func (this *UserService)UpdateColumnWidth(userId string, notebookWidth, noteListWidth, mdEditorWidth int) bool {
return db.UpdateByQMap(db.Users, bson.M{"_id": bson.ObjectIdHex(userId)},
bson.M{"NotebookWidth": notebookWidth, "NoteListWidth": noteListWidth, "MdEditorWidth": mdEditorWidth})
func (this *UserService) UpdateColumnWidth(userId string, notebookWidth, noteListWidth, mdEditorWidth int) bool {
return db.UpdateByQMap(db.Users, bson.M{"_id": bson.ObjectIdHex(userId)},
bson.M{"NotebookWidth": notebookWidth, "NoteListWidth": noteListWidth, "MdEditorWidth": mdEditorWidth})
}
// 左侧是否隐藏
func (this *UserService)UpdateLeftIsMin(userId string, leftIsMin bool) bool {
func (this *UserService) UpdateLeftIsMin(userId string, leftIsMin bool) bool {
return db.UpdateByQMap(db.Users, bson.M{"_id": bson.ObjectIdHex(userId)}, bson.M{"LeftIsMin": leftIsMin})
}
@ -454,7 +459,7 @@ func (this *UserService) ListUsers(pageNumber, pageSize int, sortField string, i
}
query["$or"] = orQ
}
q := db.Users.Find(query);
q := db.Users.Find(query)
// 总记录数
count, _ := q.Count()
// 列表
@ -468,44 +473,44 @@ func (this *UserService) ListUsers(pageNumber, pageSize int, sortField string, i
func (this *UserService) GetAllUserByFilter(userFilterEmail, userFilterWhiteList, userFilterBlackList string, verified bool) []info.User {
query := bson.M{}
if verified {
query["Verified"] = true
}
orQ := []bson.M{}
if userFilterEmail != "" {
orQ = append(orQ, bson.M{"Email": bson.M{"$regex": bson.RegEx{".*?" + userFilterEmail + ".*", "i"}}},
orQ = append(orQ, bson.M{"Email": bson.M{"$regex": bson.RegEx{".*?" + userFilterEmail + ".*", "i"}}},
bson.M{"Username": bson.M{"$regex": bson.RegEx{".*?" + userFilterEmail + ".*", "i"}}},
)
}
if(userFilterWhiteList != "") {
if userFilterWhiteList != "" {
userFilterWhiteList = strings.Replace(userFilterWhiteList, "\r", "", -1)
emails := strings.Split(userFilterWhiteList, "\n");
emails := strings.Split(userFilterWhiteList, "\n")
orQ = append(orQ, bson.M{"Email": bson.M{"$in": emails}})
}
if len(orQ) > 0 {
query["$or"] = orQ
}
emailQ := bson.M{}
if(userFilterBlackList != "") {
if userFilterBlackList != "" {
userFilterWhiteList = strings.Replace(userFilterBlackList, "\r", "", -1)
bEmails := strings.Split(userFilterBlackList, "\n");
bEmails := strings.Split(userFilterBlackList, "\n")
emailQ["$nin"] = bEmails
query["Email"] = emailQ
}
LogJ(query)
users := []info.User{}
q := db.Users.Find(query);
q := db.Users.Find(query)
q.All(&users)
Log(len(users))
return users
}
// 统计
// 统计
func (this *UserService) CountUser() int {
return db.Count(db.Users, bson.M{})
}

View File

@ -1,7 +1,6 @@
package service
import (
)
import ()
// service 通用方法
@ -17,4 +16,4 @@ func parsePageAndSort(pageNumber, pageSize int, sortField string, isAsc bool) (s
sortFieldR = sortField
}
return
}
}

View File

@ -1,13 +1,13 @@
package service
import (
"regexp"
"strings"
"net/url"
"strconv"
"gopkg.in/mgo.v2"
"github.com/leanote/leanote/app/db"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
"net/url"
"regexp"
"strconv"
"strings"
)
// init service, for share service bettween services
@ -61,7 +61,7 @@ func InitService() {
UpgradeS = &UpgradeService{}
SessionS = &SessionService{}
ThemeS = &ThemeService{}
notebookService = NotebookS
noteService = NoteS
noteContentHistoryService = NoteContentHistoryS