Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 1097646

Browse files
committed
图书功能
1 parent 59d4abd commit 1097646

File tree

11 files changed

+773
-3
lines changed

11 files changed

+773
-3
lines changed

config/db.sql

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -375,6 +375,32 @@ CREATE TABLE IF NOT EXISTS `image` (
375375
KEY `created_at` (`created_at`)
376376
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='图片表';
377377

378+
CREATE TABLE IF NOT EXISTS `book` (
379+
`id` int unsigned NOT NULL AUTO_INCREMENT,
380+
`name` varchar(63) NOT NULL DEFAULT '' COMMENT '书名',
381+
`ename` varchar(63) NOT NULL DEFAULT '' COMMENT '英文书名',
382+
`lang` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '语言:0-中文;1-英文',
383+
`author` varchar(15) NOT NULL DEFAULT '' COMMENT '作者',
384+
`translator` varchar(15) NOT NULL DEFAULT '' COMMENT '译者',
385+
`cover` varchar(127) NOT NULL DEFAULT '' COMMENT '封面',
386+
`pub_date` varchar(10) NOT NULL DEFAULT '' COMMENT '出版日期,2017-04-01',
387+
`desc` varchar(1022) NOT NULL DEFAULT '' COMMENT '简介',
388+
`catalogue` varchar(2046) NOT NULL DEFAULT '' COMMENT '目录',
389+
`is_free` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '是否免费;0-否;1-是',
390+
`online_url` varchar(127) NOT NULL DEFAULT '' COMMENT '在线阅读url',
391+
`download_url` varchar(127) NOT NULL DEFAULT '' COMMENT '下载url',
392+
`buy_url` varchar(127) NOT NULL DEFAULT '' COMMENT '购买url',
393+
`price` decimal(10,2) unsigned NOT NULL DEFAULT 0.0 COMMENT '参考价格',
394+
`viewnum` int unsigned NOT NULL DEFAULT 0 COMMENT '浏览数',
395+
`cmtnum` int unsigned NOT NULL DEFAULT 0 COMMENT '评论数',
396+
`likenum` int unsigned NOT NULL DEFAULT 0 COMMENT '赞数(推荐数)',
397+
`created_at` timestamp NOT NULL DEFAULT 0 COMMENT '创建时间',
398+
`updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后更新时间',
399+
PRIMARY KEY (`id`),
400+
KEY `name` (`name`),
401+
KEY `created_at` (`created_at`)
402+
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Go语言图书表';
403+
378404
CREATE TABLE IF NOT EXISTS `advertisement` (
379405
`id` int unsigned NOT NULL AUTO_INCREMENT,
380406
`name` varchar(20) NOT NULL DEFAULT '' COMMENT '广告名称',

src/http/controller/book.go

Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
1+
// Copyright 2017 The StudyGolang Authors. All rights reserved.
2+
// Use of this source code is governed by a BSD-style
3+
// license that can be found in the LICENSE file.
4+
// http://studygolang.com
5+
// Author: polaris [email protected]
6+
7+
package controller
8+
9+
import (
10+
"logic"
11+
"net/http"
12+
13+
"github.com/labstack/echo"
14+
"github.com/polaris1119/goutils"
15+
"github.com/polaris1119/logger"
16+
17+
. "http"
18+
"model"
19+
)
20+
21+
// 在需要评论(喜欢)且要回调的地方注册评论(喜欢)对象
22+
func init() {
23+
// 注册评论(喜欢)对象
24+
logic.RegisterCommentObject(model.TypeBook, logic.BookComment{})
25+
logic.RegisterLikeObject(model.TypeBook, logic.BookLike{})
26+
}
27+
28+
type BookController struct{}
29+
30+
// 注册路由
31+
func (self BookController) RegisterRoute(g *echo.Group) {
32+
g.Get("/books", self.ReadList)
33+
34+
g.Get("/book/:id", self.Detail)
35+
}
36+
37+
// ReadList 图书列表页
38+
func (BookController) ReadList(ctx echo.Context) error {
39+
limit := 20
40+
41+
lastId := goutils.MustInt(ctx.QueryParam("lastid"))
42+
books := logic.DefaultGoBook.FindBy(ctx, limit+1, lastId)
43+
if books == nil {
44+
logger.Errorln("book controller: find book error")
45+
return ctx.Redirect(http.StatusSeeOther, "/books")
46+
}
47+
48+
num := len(books)
49+
if num == 0 {
50+
if lastId == 0 {
51+
return ctx.Redirect(http.StatusSeeOther, "/")
52+
}
53+
return ctx.Redirect(http.StatusSeeOther, "/books")
54+
}
55+
56+
var (
57+
hasPrev, hasNext bool
58+
prevId, nextId int
59+
)
60+
61+
if lastId > 0 {
62+
prevId = lastId
63+
64+
if prevId-books[0].Id > 1 {
65+
hasPrev = false
66+
} else {
67+
prevId += limit
68+
hasPrev = true
69+
}
70+
}
71+
72+
if num > limit {
73+
hasNext = true
74+
books = books[:limit]
75+
nextId = books[limit-1].Id
76+
} else {
77+
nextId = books[num-1].Id
78+
}
79+
80+
pageInfo := map[string]interface{}{
81+
"has_prev": hasPrev,
82+
"prev_id": prevId,
83+
"has_next": hasNext,
84+
"next_id": nextId,
85+
}
86+
87+
// 获取当前用户喜欢对象信息
88+
me, ok := ctx.Get("user").(*model.Me)
89+
var likeFlags map[int]int
90+
if ok {
91+
likeFlags, _ = logic.DefaultLike.FindUserLikeObjects(ctx, me.Uid, model.TypeBook, books[0].Id, nextId)
92+
}
93+
94+
return render(ctx, "books/list.html", map[string]interface{}{"books": books, "activeBooks": "active", "page": pageInfo, "likeflags": likeFlags})
95+
}
96+
97+
// Detail 图书详细页
98+
func (BookController) Detail(ctx echo.Context) error {
99+
book, err := logic.DefaultGoBook.FindById(ctx, ctx.Param("id"))
100+
if err != nil {
101+
return ctx.Redirect(http.StatusSeeOther, "/books")
102+
}
103+
104+
if book == nil || book.Id == 0 {
105+
return ctx.Redirect(http.StatusSeeOther, "/books")
106+
}
107+
108+
likeFlag := 0
109+
hadCollect := 0
110+
me, ok := ctx.Get("user").(*model.Me)
111+
if ok {
112+
likeFlag = logic.DefaultLike.HadLike(ctx, me.Uid, book.Id, model.TypeBook)
113+
hadCollect = logic.DefaultFavorite.HadFavorite(ctx, me.Uid, book.Id, model.TypeBook)
114+
}
115+
116+
logic.Views.Incr(Request(ctx), model.TypeBook, book.Id)
117+
118+
// 为了阅读数即时看到
119+
book.Viewnum++
120+
121+
return render(ctx, "books/detail.html,common/comment.html", map[string]interface{}{"activeBooks": "active", "book": book, "likeflag": likeFlag, "hadcollect": hadCollect})
122+
}

src/http/controller/routes.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ func RegisterRoutes(g *echo.Group) {
2727
new(WideController).RegisterRoute(g)
2828
new(ImageController).RegisterRoute(g)
2929
new(CaptchaController).RegisterRoute(g)
30+
new(BookController).RegisterRoute(g)
3031
new(WebsocketController).RegisterRoute(g)
3132

3233
new(InstallController).RegisterRoute(g)

src/http/http.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -219,7 +219,7 @@ func executeTpl(ctx echo.Context, tpl *template.Template, data map[string]interf
219219
cdnDomain = global.App.CDNHttps
220220
}
221221
data["app"] = global.App
222-
data["is_https"] = goutils.MustBool(ctx.Request().Header().Get("X-Https"))
222+
data["is_https"] = isHttps
223223
data["cdn_domain"] = cdnDomain
224224

225225
data["online_users"] = map[string]int{"online": logic.Book.Len(), "maxonline": logic.MaxOnlineNum()}

src/logic/gobook.go

Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
// Copyright 2017 The StudyGolang Authors. All rights reserved.
2+
// Use of this source code is governed by a BSD-style
3+
// license that can be found in the LICENSE file.
4+
// http://studygolang.com
5+
// Author:polaris [email protected]
6+
7+
package logic
8+
9+
import (
10+
. "db"
11+
"model"
12+
"time"
13+
14+
"github.com/polaris1119/logger"
15+
"golang.org/x/net/context"
16+
)
17+
18+
type GoBookLogic struct{}
19+
20+
var DefaultGoBook = GoBookLogic{}
21+
22+
// FindBy 获取图书列表(分页)
23+
func (GoBookLogic) FindBy(ctx context.Context, limit int, lastIds ...int) []*model.Book {
24+
objLog := GetLogger(ctx)
25+
26+
dbSession := MasterDB.OrderBy("id DESC")
27+
28+
if len(lastIds) > 0 && lastIds[0] > 0 {
29+
dbSession.And("id<?", lastIds[0])
30+
}
31+
32+
books := make([]*model.Book, 0)
33+
err := dbSession.OrderBy("id DESC").Limit(limit).Find(&books)
34+
if err != nil {
35+
objLog.Errorln("GoBookLogic FindBy Error:", err)
36+
return nil
37+
}
38+
39+
return books
40+
}
41+
42+
// FindByIds 获取多个图书详细信息
43+
func (GoBookLogic) FindByIds(ids []int) []*model.Book {
44+
if len(ids) == 0 {
45+
return nil
46+
}
47+
books := make([]*model.Book, 0)
48+
err := MasterDB.In("id", ids).Find(&books)
49+
if err != nil {
50+
logger.Errorln("GoBookLogic FindByIds error:", err)
51+
return nil
52+
}
53+
return books
54+
}
55+
56+
// FindById 获取一本图书信息
57+
func (GoBookLogic) FindById(ctx context.Context, id string) (*model.Book, error) {
58+
book := &model.Book{}
59+
_, err := MasterDB.Id(id).Get(book)
60+
if err != nil {
61+
logger.Errorln("book logic FindById Error:", err)
62+
}
63+
64+
return book, err
65+
}
66+
67+
// 图书评论
68+
type BookComment struct{}
69+
70+
// UpdateComment 更新该图书的评论信息
71+
// cid:评论id;objid:被评论对象id;uid:评论者;cmttime:评论时间
72+
func (self BookComment) UpdateComment(cid, objid, uid int, cmttime time.Time) {
73+
// 更新评论数(TODO:暂时每次都更新表)
74+
_, err := MasterDB.Id(objid).Incr("cmtnum", 1).Update(new(model.Article))
75+
if err != nil {
76+
logger.Errorln("更新图书评论数失败:", err)
77+
}
78+
}
79+
80+
func (self BookComment) String() string {
81+
return "book"
82+
}
83+
84+
// SetObjinfo 实现 CommentObjecter 接口
85+
func (self BookComment) SetObjinfo(ids []int, commentMap map[int][]*model.Comment) {
86+
books := DefaultGoBook.FindByIds(ids)
87+
if len(books) == 0 {
88+
return
89+
}
90+
91+
for _, book := range books {
92+
objinfo := make(map[string]interface{})
93+
objinfo["name"] = book.Name
94+
objinfo["uri"] = model.PathUrlMap[model.TypeBook]
95+
objinfo["type_name"] = model.TypeNameMap[model.TypeBook]
96+
97+
for _, comment := range commentMap[book.Id] {
98+
comment.Objinfo = objinfo
99+
}
100+
}
101+
}
102+
103+
// 图书推荐
104+
type BookLike struct{}
105+
106+
// 更新该图书的推荐数
107+
// objid:被喜欢对象id;num: 喜欢数(负数表示取消喜欢)
108+
func (self BookLike) UpdateLike(objid, num int) {
109+
// 更新喜欢数(TODO:暂时每次都更新表)
110+
_, err := MasterDB.Where("id=?", objid).Incr("likenum", num).Update(new(model.Book))
111+
if err != nil {
112+
logger.Errorln("更新图书喜欢数失败:", err)
113+
}
114+
}
115+
116+
func (self BookLike) String() string {
117+
return "book"
118+
}

src/logic/view.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,8 @@ func (this *view) flush() {
5656
session.Incr("viewnum", this.num).Update(new(model.OpenProject))
5757
case model.TypeWiki:
5858
session.Incr("viewnum", this.num).Update(new(model.Wiki))
59+
case model.TypeBook:
60+
session.Incr("viewnum", this.num).Update(new(model.Book))
5961
}
6062

6163
this.num = 0

src/model/book.go

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
// Copyright 2017 The StudyGolang Authors. All rights reserved.
2+
// Use of this source code is governed by a BSD-style
3+
// license that can be found in the LICENSE file.
4+
// http://studygolang.com
5+
// Author: polaris [email protected]
6+
7+
package model
8+
9+
const (
10+
IsFreeFalse = iota
11+
IsFreeTrue
12+
)
13+
14+
type Book struct {
15+
Id int `json:"id" xorm:"pk autoincr"`
16+
Name string `json:"name"`
17+
Ename string `json:"ename"`
18+
Cover string `json:"cover"`
19+
Author string `json:"author"`
20+
Translator string `json:"translator"`
21+
Lang int `json:"lang"`
22+
PubDate string `json:"pub_date"`
23+
Desc string `json:"desc"`
24+
Catalogue string `json:"catalogue"`
25+
IsFree bool `json:"is_free"`
26+
OnlineUrl string `json:"online_url"`
27+
DownloadUrl string `json:"download_url"`
28+
BuyUrl string `json:"buy_url"`
29+
Price float32 `json:"price"`
30+
Viewnum int `json:"viewnum"`
31+
Cmtnum int `json:"cmtnum"`
32+
Likenum int `json:"likenum"`
33+
CreatedAt OftenTime `json:"created_at" xorm:"created"`
34+
UpdatedAt OftenTime `json:"updated_at" xorm:"<-"`
35+
}
36+
37+
func (*Book) TableName() string {
38+
return "book"
39+
}

src/model/comment.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ const (
1313
TypeResource // 资源
1414
TypeWiki // WIKI
1515
TypeProject // 开源项目
16+
TypeBook // 图书
1617
)
1718

1819
var PathUrlMap = map[int]string{
@@ -21,6 +22,7 @@ var PathUrlMap = map[int]string{
2122
TypeResource: "/resources/",
2223
TypeWiki: "/wiki/",
2324
TypeProject: "/p/",
25+
TypeBook: "/book/",
2426
}
2527

2628
var TypeNameMap = map[int]string{
@@ -29,6 +31,7 @@ var TypeNameMap = map[int]string{
2931
TypeResource: "资源",
3032
TypeWiki: "Wiki",
3133
TypeProject: "项目",
34+
TypeBook: "图书",
3235
}
3336

3437
// 评论信息(通用)

0 commit comments

Comments
 (0)