-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
265 lines (212 loc) · 6.3 KB
/
server.go
File metadata and controls
265 lines (212 loc) · 6.3 KB
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
package main
import (
"context"
"io"
"log"
"net/http"
"regexp"
"strings"
"github.com/a-h/templ"
"github.com/Meowcenary/information_agent/scraper"
)
type Flash struct {
Message string;
Type string;
}
var GlobalFlash *Flash
func NewFlashMessage(message, flashType string) *Flash {
return &Flash {
Message: message,
Type: flashType,
}
}
func main() {
log.Println("starting...")
// Http handlers
http.Handle("/home", NewHomeHandler())
http.Handle("/wiki_page_json/", NewPagesHandler())
http.Handle("/search", NewSearchHandler())
http.Handle("/about", NewAboutHandler())
http.Handle("/scrape_wikipedia", NewScrapeWikipediaHandler())
http.Handle("/delete_wiki_page/", NewDeleteWikiPageHandler())
// Start the server.
log.Println("listening on http://localhost:8000")
log.Println("home page: http:/localhost:8000/home")
if err := http.ListenAndServe("localhost:8000", nil); err != nil {
log.Printf("error listening: %v", err)
}
}
// Data Getters
func getPages(dirPath string) ([]scraper.WikiPage, error) {
wikiPages, err := scraper.ReadWikiPagesFromDirectory(dirPath)
return wikiPages, err
}
func getPage(filepath string) (scraper.WikiPage, error) {
wikiPage, err := scraper.ReadWikiPageJson(filepath)
return *wikiPage, err
}
func deletePage(filepath string) error {
return scraper.DeleteWikiPageJson(filepath)
}
// Home Handler
func NewHomeHandler() HomeHandler {
return HomeHandler {
Log: log.Default(),
}
}
type HomeHandler struct {
Log *log.Logger
}
func (hh HomeHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
hh.Log.Println("getting pages from wiki_page_json/")
pages, err := getPages("wiki_page_json")
if err != nil {
hh.Log.Printf("failed to get pages: %v\n", err)
return
}
hh.Log.Println("rendering home")
templ.Handler(home(pages, GlobalFlash)).ServeHTTP(w, r)
}
// Scrape Wikipedia Handler
func NewScrapeWikipediaHandler() ScrapeWikipediaHandler {
return ScrapeWikipediaHandler {
Log: log.Default(),
}
}
type ScrapeWikipediaHandler struct {
Log *log.Logger
}
func (swh ScrapeWikipediaHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
url := r.URL.Query().Get("url")
swh.Log.Println("scraping url: ", url)
page := scraper.ScrapeWikiUrls([]string{url})[0]
filepath := "wiki_page_json" + "/" + page.FilenameFromTitle()
log.Println("writing to", filepath)
scraper.WriteWikiPageJson(filepath, page)
pages, _ := getPages("wiki_page_json")
// Render Home
log.Println("setting flash")
flashMessage := NewFlashMessage("Successfully added " + page.Title + " to system", "success")
templ.Handler(home(pages, flashMessage)).ServeHTTP(w, r)
}
// Search Handler
func NewSearchHandler() SearchHandler {
return SearchHandler {
Log: log.Default(),
}
}
type SearchHandler struct {
Log *log.Logger
}
func SearchPostHandler(w http.ResponseWriter, r *http.Request) {
logger := log.Default()
logger.Println("search post handler")
var queryResults []scraper.WikiQueryResult
r.ParseForm()
var query string
if r.Form.Has("search") {
query = strings.ReplaceAll(r.Form["search"][0], " ", "_")
logger.Println("searching wikipedia with query: ", query)
queryResults = scraper.SearchWikipedia(query)
}
logger.Println("rendering search results")
templ.Handler(searchResults(query, queryResults)).ServeHTTP(w, r)
}
func (sh SearchHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost {
sh.Log.Println("running passthrough search")
SearchPostHandler(w, r)
return
}
sh.Log.Println("rendering search")
templ.Handler(search()).ServeHTTP(w, r)
}
// About Handler
func NewAboutHandler() AboutHandler {
return AboutHandler {
Log: log.Default(),
}
}
type AboutHandler struct {
Log *log.Logger
}
func (ah AboutHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ah.Log.Println("rendering about")
templ.Handler(about()).ServeHTTP(w, r)
}
// Page Handler
func NewPagesHandler() PagesHandler {
return PagesHandler {
Log: log.Default(),
}
}
type PagesHandler struct {
Log *log.Logger
}
func (ph PagesHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
filepath := scraper.FilenameFromTitle(r.URL.Path[1:])
log.Println("retrieving page from filepath: ", filepath)
wikipage, err := getPage(filepath)
if err != nil {
ph.Log.Printf("failed to get page: %v", err)
http.Error(w, "failed to retrieve pages", http.StatusInternalServerError)
return
}
log.Println("formatting page html")
html := FormatPageHtml(wikipage)
html = RemoveScriptTags(html)
html = RemoveAnchorTags(html)
log.Println("creating templ component")
content := Unsafe(html)
ph.Log.Println("rendering pages")
templ.Handler(page(content)).ServeHTTP(w, r)
}
// Delete Wiki Page Handler
func NewDeleteWikiPageHandler() DeleteWikiPageHandler {
return DeleteWikiPageHandler {
Log: log.Default(),
}
}
type DeleteWikiPageHandler struct {
Log *log.Logger;
}
func (dwph DeleteWikiPageHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
dwph.Log.Println("delete called")
title := strings.Split(r.URL.Path[1:], "/")[1]
filepath := scraper.FilenameFromTitle(title)
err := deletePage("wiki_page_json/" + filepath)
if err != nil {
dwph.Log.Panic(err)
}
dwph.Log.Println("deleting page from filepath: ", filepath)
log.Println("setting flash")
GlobalFlash = NewFlashMessage("Successfully deleted " + title + " from system", "success")
http.Redirect(w, r, "/home", 302)
}
// Page Component Building
func FormatPageHtml(wikipage scraper.WikiPage) string {
html := "<html><body><h1>" + wikipage.Title + "</h1><hr></hr>"
for _, paragraph := range wikipage.Paragraphs {
html += "<p>" + paragraph.Text + "</p>"
}
html += "</body></html>"
return html
}
// RemoveScriptTags removes script tags and their content from an HTML formatted string
func RemoveScriptTags(html string) string {
scriptTagRegex := regexp.MustCompile(`<script(.*?)>(.*?)</script>`)
html = scriptTagRegex.ReplaceAllString(html, "")
return html
}
// RemoveAnchorTags removes anchor tags from an HTML formatted string but keeps the link text
func RemoveAnchorTags(html string) string {
anchorTagRegex := regexp.MustCompile(`<a(.*?)>(.*?)</a>`)
html = anchorTagRegex.ReplaceAllString(html, "$2")
return html
}
func Unsafe(html string) templ.Component {
return templ.ComponentFunc(func(ctx context.Context, w io.Writer) (err error) {
_, err = io.WriteString(w, html)
return
})
}