forked from Ptt-official-app/Ptt-backend
/
route_borads_articles.go
101 lines (84 loc) · 2.47 KB
/
route_borads_articles.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package main
import (
"github.com/PichuChen/go-bbs"
"encoding/base64"
"encoding/json"
"fmt"
"net/http"
)
// getBoardArticles handles request with `/v1/boards/SYSOP/articles` and will return
// article list to client
func getBoardArticles(w http.ResponseWriter, r *http.Request, boardId string) {
logger.Debugf("getBoardArticles: %v", r)
token := getTokenFromRequest(r)
// Check permission for board
err := checkTokenPermission(token,
[]permission{PermissionReadBoardInformation},
map[string]string{
"board_id": boardId,
})
if err != nil {
// TODO: record unauthorized access
w.WriteHeader(http.StatusUnauthorized)
return
}
var fileHeaders []bbs.ArticleRecord
fileHeaders, err = db.ReadBoardArticleRecordsFile(boardId)
if err != nil {
logger.Warningf("open directory file error: %v", err)
// The board may not contain any article
}
items := []interface{}{}
for _, f := range fileHeaders {
m := map[string]interface{}{
"filename": f.Filename(),
// Bug(pichu): f.Modified time will be 0 when file is vote
"modified_time": f.Modified(),
"recommend_count": f.Recommend(),
"post_date": f.Date(),
"title": f.Title(),
"money": fmt.Sprintf("%v", f.Money()),
"owner": f.Owner(),
// "aid": ""
"url": getArticleURL(boardId, f.Filename()),
}
items = append(items, m)
}
logger.Debugf("fh: %v", fileHeaders)
responseMap := map[string]interface{}{
"data": map[string]interface{}{
"items": items,
},
}
b, _ := json.MarshalIndent(responseMap, "", " ")
w.Write(b)
}
func getBoardArticlesFile(w http.ResponseWriter, r *http.Request, boardId string, filename string) {
logger.Debugf("getBoardArticlesFile: %v", r)
token := getTokenFromRequest(r)
err := checkTokenPermission(token,
[]permission{PermissionReadBoardInformation},
map[string]string{
"board_id": boardId,
})
if err != nil {
// TODO: record unauthorized access
w.WriteHeader(http.StatusUnauthorized)
return
}
buf, err := db.ReadBoardArticleFile(boardId, filename)
if err != nil {
logger.Errorf("read file %v/%v error: %v", boardId, filename, err)
}
bufStr := base64.StdEncoding.EncodeToString(buf)
responseMap := map[string]interface{}{
"data": map[string]interface{}{
"raw": bufStr,
},
}
b, _ := json.MarshalIndent(responseMap, "", " ")
w.Write(b)
}
func getArticleURL(boardId string, filename string) string {
return fmt.Sprintf("https://ptt-app-dev-codingman.pichuchen.tw/bbs/%s/%s.html", boardId, filename)
}