add leaui_image plugin for replace leanote_image. on a train to ChangSha

This commit is contained in:
life
2014-06-28 23:07:34 +08:00
parent 06eb27faab
commit 1494b25129
15 changed files with 369 additions and 12 deletions

View File

@ -0,0 +1,46 @@
package controllers
import (
"github.com/revel/revel"
// "encoding/json"
"github.com/leanote/leanote/app/info"
"labix.org/v2/mgo/bson"
// . "github.com/leanote/leanote/app/lea"
// "io/ioutil"
)
type Album struct {
BaseController
}
// all albums by userId
func (c Album) GetAlbums() revel.Result {
re := albumService.GetAlbums(c.GetUserId())
return c.RenderJson(re)
}
func (c Album) DeleteAlbum(albumId string) revel.Result {
re, msg := albumService.DeleteAlbum(c.GetUserId(), albumId)
return c.RenderJson(info.Re{Ok: re, Msg: msg})
}
// add album
func (c Album) AddAlbum(name string) revel.Result {
album := info.Album{
AlbumId: bson.NewObjectId(),
Name: name,
Seq: -1,
UserId: c.GetObjectUserId()}
re := albumService.AddAlbum(album)
if(re) {
return c.RenderJson(album)
} else {
return c.RenderJson(false)
}
}
// update alnum name
func (c Album) UpdateAlbum(albumId, name string) revel.Result {
return c.RenderJson(albumService.UpdateAlbum(albumId, c.GetUserId(), name))
}

View File

@ -7,6 +7,7 @@ import (
"github.com/leanote/leanote/app/info"
"io/ioutil"
"os"
"strconv"
)
// 首页
@ -20,7 +21,7 @@ func (c File) UploadImage(renderHtml string) revel.Result {
renderHtml = "file/image.html"
}
re := c.uploadImage("");
re := c.uploadImage("", "");
c.RenderArgs["fileUrlPath"] = siteUrl + re.Id
c.RenderArgs["resultCode"] = re.Code
@ -36,14 +37,22 @@ func (c File) UploadBlogLogo() revel.Result {
// 拖拉上传, pasteImage
func (c File) UploadImageJson(renderHtml, from string) revel.Result {
re := c.uploadImage(from);
re := c.uploadImage(from, "");
re.Id = siteUrl + re.Id
// re.Id = re.Id
return c.RenderJson(re)
}
// leaui image plugin
func (c File) UploadImageLeaui(albumId string) revel.Result {
re := c.uploadImage("", albumId);
re.Id = siteUrl + re.Id
// re.Id = re.Id
return c.RenderJson(re)
}
// 上传图片, 公用方法
func (c File) uploadImage(from string) (re info.Re) {
func (c File) uploadImage(from, albumId string) (re info.Re) {
var fileUrlPath = ""
var resultCode = 0 // 1表示正常
var resultMsg = "内部错误" // 错误信息
@ -105,11 +114,87 @@ func (c File) uploadImage(from string) (re info.Re) {
}
// 改变成gif图片
_, toPathGif := TransToGif(toPath, 0, true)
fileUrlPath += "/" + GetFilename(toPathGif)
filename = GetFilename(toPathGif)
filesize := GetFilesize(toPathGif)
fileUrlPath += "/" + filename
resultCode = 1
Ok = true
resultMsg = "上传成功!"
// File
fileInfo := info.File{Name: filename,
Title: filename,
Path: fileUrlPath,
Size: filesize}
Ok = fileService.AddImage(fileInfo, albumId, c.GetUserId())
re.Item = fileInfo
return re
}
// get all images by userId with page
func (c File) GetImages(albumId, key string, page int) revel.Result {
re := fileService.ListImagesWithPage(c.GetUserId(), albumId, key, page, 12)
return c.RenderJson(re)
}
func (c File) UpdateImageTitle(fileId, title string) revel.Result {
re := info.NewRe()
re.Ok = fileService.UpdateImageTitle(c.GetUserId(), fileId, title)
return c.RenderJson(re)
}
func (c File) DeleteImage(fileId string) revel.Result {
re := info.NewRe()
re.Ok, re.Msg = fileService.DeleteImage(c.GetUserId(), fileId)
return c.RenderJson(re)
}
// update image uploader to leaui image,
// scan all user's images and insert into db
func (c File) UpgradeLeauiImage() revel.Result {
re := info.NewRe()
if ok, _ := revel.Config.Bool("upgradeLeauiImage"); !ok {
re.Msg = "Not allowed"
return c.RenderJson(re)
}
uploadPath := revel.BasePath + "/public/upload";
userIds := ListDir(uploadPath)
if userIds == nil {
re.Msg = "no user"
return c.RenderJson(re)
}
msg := "";
for _, userId := range userIds {
dirPath := uploadPath + "/" + userId + "/images"
images := ListDir(dirPath)
if images == nil {
msg += userId + " no images "
continue;
}
hadImages := fileService.GetAllImageNamesMap(userId)
i := 0
for _, filename := range images {
if _, ok := hadImages[filename]; !ok {
fileUrlPath := "/upload/" + userId + "/images/" + filename
fileInfo := info.File{Name: filename,
Title: filename,
Path: fileUrlPath,
Size: GetFilesize(dirPath + "/" + filename)}
fileService.AddImage(fileInfo, "", userId)
i++
}
}
msg += userId + ": " + strconv.Itoa(len(images)) + " -- " + strconv.Itoa(i) + " images "
}
re.Msg = msg
return c.RenderJson(re)
}

View File

@ -23,6 +23,9 @@ var pwdService *service.PwdService
var tokenService *service.TokenService
var suggestionService *service.SuggestionService
var albumService *service.AlbumService
var fileService *service.FileService
var pageSize = 1000
var defaultSortField = "UpdatedTime"
var leanoteUserId = "52d26b4e99c37b609a000001"

View File

@ -33,6 +33,10 @@ var Tokens *mgo.Collection
var Suggestions *mgo.Collection
// Album & file(image)
var Albums *mgo.Collection
var Files *mgo.Collection
// 初始化时连接数据库
func Init() {
var url string
@ -94,8 +98,12 @@ func Init() {
// find password
Tokens = Session.DB(dbname).C("tokens")
//
// Suggestion
Suggestions = Session.DB(dbname).C("suggestions")
// Album & file
Albums = Session.DB(dbname).C("albums")
Files = Session.DB(dbname).C("files")
}
func init() {

15
app/info/AlbumInfo.go Normal file
View File

@ -0,0 +1,15 @@
package info
import (
"labix.org/v2/mgo/bson"
"time"
)
type Album struct {
AlbumId bson.ObjectId `bson:"_id,omitempty"` //
UserId bson.ObjectId `bson:"UserId"`
Name string `Name` // album name
Type int `Type` // type, the default is image: 0
Seq int `Seq`
CreatedTime time.Time `CreatedTime`
}

19
app/info/FileInfo.go Normal file
View File

@ -0,0 +1,19 @@
package info
import (
"labix.org/v2/mgo/bson"
"time"
)
type File struct {
FileId bson.ObjectId `bson:"_id,omitempty"` //
UserId bson.ObjectId `bson:"UserId"`
AlbumId bson.ObjectId `bson:"AlbumId"`
Name string `Name` // file name
Title string `Title` // file name or user defined for search
Size int64 `Size` // file size (byte)
Type string `Type` // file type, such as image/jpg
Path string `Path` // the file path, based on /upload
IsDefaultAlbum bool `IsDefaultAlbum`
CreatedTime time.Time `CreatedTime`
}

View File

@ -8,5 +8,6 @@ import (
type Page struct {
CurPage int // 当前页码
TotalPage int // 总页
Count int // 总记录数
List interface{}
}

View File

@ -30,6 +30,16 @@ func GetFilename(path string) string {
return filepath.Base(path)
}
// file size
// length in bytes
func GetFilesize(path string) int64 {
fileinfo, err := os.Stat(path)
if err == nil {
return fileinfo.Size()
}
return 0;
}
// 清空dir下所有的文件和文件夹
// RemoveAll会清空本文件夹, 所以还要创建之
func ClearDir(dir string) bool {
@ -43,3 +53,13 @@ func ClearDir(dir string) bool {
}
return true
}
// list dir's all file, return filenames
func ListDir(dir string) []string {
f, err := os.Open(dir)
if err != nil {
return nil
}
names, _ := f.Readdirnames(0)
return names
}

View File

@ -0,0 +1,44 @@
package service
import (
"github.com/leanote/leanote/app/info"
// . "github.com/leanote/leanote/app/lea"
"github.com/leanote/leanote/app/db"
"labix.org/v2/mgo/bson"
"time"
)
const IMAGE_TYPE = 0
type AlbumService struct {
}
// add album
func (this *AlbumService) AddAlbum(album info.Album) bool {
album.CreatedTime = time.Now()
album.Type = IMAGE_TYPE
return db.Insert(db.Albums, album)
}
// get albums
func (this *AlbumService) GetAlbums(userId string) []info.Album {
albums := []info.Album{}
db.ListByQ(db.Albums, bson.M{"UserId": bson.ObjectIdHex(userId)}, &albums)
return albums
}
// 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),
"UserId": bson.ObjectIdHex(userId),
}) == 0 {
return db.DeleteByIdAndUserId(db.Albums, albumId, userId), ""
}
return false, "has images"
}
// update album name
func (this *AlbumService) UpdateAlbum(albumId, userId, name string) bool {
return db.UpdateByIdAndUserIdField(db.Albums, albumId, userId, "Name", name)
}

106
app/service/FileService.go Normal file
View File

@ -0,0 +1,106 @@
package service
import (
// . "github.com/leanote/leanote/app/lea"
"github.com/revel/revel"
"github.com/leanote/leanote/app/info"
"github.com/leanote/leanote/app/db"
"labix.org/v2/mgo/bson"
"time"
"os"
)
const DEFAULT_ALBUM_ID = "52d3e8ac99c37b7f0d000001"
type FileService struct {
}
// add Image
func (this *FileService) AddImage(image info.File, albumId, userId string) bool {
image.CreatedTime = time.Now()
if albumId != "" {
image.AlbumId = bson.ObjectIdHex(albumId)
} else {
image.AlbumId = bson.ObjectIdHex(DEFAULT_ALBUM_ID)
image.IsDefaultAlbum = true
}
image.UserId = bson.ObjectIdHex(userId)
return db.Insert(db.Files, image)
}
// list images
// if albumId == "" get default album images
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)}
if albumId != "" {
q["AlbumId"] = bson.ObjectIdHex(albumId);
} else {
q["IsDefaultAlbum"] = true
}
if key != "" {
q["Title"] = bson.M{"$regex": bson.RegEx{".*?" + key + ".*", "i"}}
}
// 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}
}
func (this *FileService) UpdateImageTitle(userId, fileId, title string) bool {
return db.UpdateByIdAndUserIdField(db.Files, fileId, userId, "Title", title)
}
// get all images names
// for upgrade
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
}
return
}
// delete image
func (this *FileService) DeleteImage(userId, fileId string) (bool, string) {
file := info.File{}
db.GetByIdAndUserId(db.Files, fileId, userId, &file)
if(file.FileId != "") {
if db.DeleteByIdAndUserId(db.Files, fileId, userId) {
// delete image
err := os.Remove(revel.BasePath + "/public/" + file.Path)
if err == nil {
return true, ""
}
return false, "delete file error!"
}
return false, "db error"
}
return false, "no such item"
}
// update image title
func (this *FileService) UpdateImage(userId, fileId, title string) bool {
return db.UpdateByIdAndUserIdField(db.Files, fileId, userId, "Title", title)
}

View File

@ -181,8 +181,15 @@ make<br>make --- install</pre>
`, "/Users/life/Desktop/a.png")
fmt.Printf("time cost %v\n", time.Now().Sub(start))
}
func testLea() {
names := ListDir("/Users/life/Documents/Go/package/src/leanote")
fmt.Println(names);
}
func main() {
revel.BasePath = "/Users/life/Documents/Go/package/src/leanote"
testLea();
// a, b := SplitFilename("http://ab/c/a.gif#??")
// println(a)
// println(b)
@ -199,7 +206,7 @@ func main() {
//_, err := mgo.Dial("mongodb://leanote:nKFAkxKnWkEQy8Vv2LlM@115.28.133.226:27017/leanote")
// testNotebookService();
testNoteService();
// testNoteService();
// testShareService()
// testAuthService()

File diff suppressed because one or more lines are too long

View File

@ -194,11 +194,11 @@ $(function() {
skin : "custom",
language: LEA.locale, // 语言
plugins : [
"autolink link leanote_image lists charmap hr", "paste",
"autolink link leaui_image leanote_image lists charmap hr", "paste",
"searchreplace leanote_nav leanote_code tabfocus",
"table directionality textcolor codemirror" ], // nonbreaking
toolbar1 : "formatselect | forecolor backcolor | bold italic underline strikethrough | leanote_image | leanote_code | bullist numlist | alignleft aligncenter alignright alignjustify",
toolbar1 : "formatselect | forecolor backcolor | bold italic underline strikethrough | leaui_image | leanote_image | leanote_code | bullist numlist | alignleft aligncenter alignright alignjustify",
toolbar2 : "outdent indent blockquote | link unlink | table | hr removeformat | subscript superscript |searchreplace | code | pastetext | fontselect fontsizeselect",
// 使用tab键: http://www.tinymce.com/wiki.php/Plugin3x:nonbreaking

Submodule public/tinymce/plugins/leaui_image added at 4abe32dd55

File diff suppressed because one or more lines are too long