-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.go
305 lines (255 loc) · 7.07 KB
/
main.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
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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"math"
"net/http"
"os"
"regexp"
"strconv"
"strings"
"time"
)
// LogMsg takes a message and pipes it to stdout if the verbose flag is set.
func LogMsg(msg string) {
if GetConfigBool("verbose") {
log.Print(msg)
}
}
type webError struct {
Error string
}
type report struct {
ID string
URL string
Type string
Title string
PublishedAt string
TotalComments uint64
CollectedComments uint64
CommentCoveragePercent float64
CommentAvgPerDay float64
Keywords map[string]uint64
Sentiment map[string]uint64
Metadata Post
SampleComments []*Comment
TopComments []*Comment
DailySentiment map[string]map[string]uint64
EmojiCount map[string]uint64
}
// Post is the interface for all the various post types (YouTubeVideo, etc...)
type Post interface {
GetComments() CommentList
GetMetadata() bool
}
func jsonError(msg string) []byte {
errorJSON, _ := json.Marshal(webError{Error: msg})
return errorJSON
}
func parseURL(url string) (string, []string, string) {
sites := map[string]map[string]string{
"instagram": {
"default": "instag\\.?ram(\\.com)?/p/([\\w\\-]*)/?",
},
"youtube": {
"default": "youtu\\.?be(\\.?com)?/(watch\\?v=)?([\\w\\-_]*)",
},
"facebook": {
"default": "facebook\\.com/([\\w]*)/posts/([\\d]*)/?",
"videos": "facebook\\.com/([\\w]+)/videos/\\w{2}\\.([\\d]+)/([\\d]*)/?",
},
}
var domain string
var matches []string
var format string
for d, rgxs := range sites {
for f, rstr := range rgxs {
r, _ := regexp.Compile(rstr)
matches = r.FindStringSubmatch(url)
if len(matches) > 0 {
domain = d
format = f
break
}
}
if domain != "" {
break
}
}
return domain, matches, format
}
func verifyToken(token string) bool {
// Custom token verification logic.
return true
}
func webHandler(w http.ResponseWriter, r *http.Request) {
if r.URL.Path[1:] == "api" {
postURL := r.URL.Query().Get("vid")
userToken := r.URL.Query().Get("token")
var jsonBytes []byte
if verifyToken(userToken) {
if postURL != "" {
jsonBytes = runReport(postURL)
} else {
jsonBytes, _ = json.Marshal(webError{Error: "Missing post URL."})
}
} else {
jsonBytes, _ = json.Marshal(webError{Error: "Invalid token."})
}
// w.Header().Set("Access-Control-Allow-Origin", "*") /// USEFUL FOR DEV ONLY
w.Header().Set("Content-Type", "application/json")
w.Write(jsonBytes)
} else if r.URL.Path[1:] == "oauth" {
// Custom oauth link generation logic.
} else if r.URL.Path[1:] == "login" {
// Custom login logic
} else {
data, err := Asset("static/gui/index.html")
if err != nil {
LogMsg("Web GUI asset not found!")
os.Exit(1)
}
htmlPath := GetConfigString("html")
if htmlPath != "" {
data, err = ioutil.ReadFile(htmlPath)
if err != nil {
LogMsg("Unable to read html file path.")
os.Exit(1)
}
}
w.Header().Set("Content-Type", "text/html")
w.Write(data)
}
}
func runReport(postURL string) []byte {
// Parse URL
domain, urlParts, urlFormat := parseURL(postURL)
if domain == "" || len(urlParts) == 0 {
return jsonError("Unable to parse post url.")
}
// Create Report
theReport := report{URL: postURL}
var thePost Post
switch domain {
case "youtube":
if GetConfigString("ytkey") == "" {
return jsonError("API key for YouTube not configured.")
}
thePost = &YouTubeVideo{ID: urlParts[len(urlParts)-1]}
case "instagram":
thePost = &InstagramPic{ShortCode: urlParts[len(urlParts)-1]}
case "facebook":
if GetConfigString("fbkey") == "" || GetConfigString("fbsecret") == "" {
return jsonError("Missing Facebook API credentials.")
}
switch urlFormat {
case "default":
thePost = &FacebookPost{PageName: urlParts[len(urlParts)-2], ID: urlParts[len(urlParts)-1]}
case "videos":
thePost = &FacebookPost{PageName: urlParts[len(urlParts)-3], PageID: urlParts[len(urlParts)-2], ID: urlParts[len(urlParts)-1]}
}
}
// Fetch the metadata
flag := thePost.GetMetadata()
if !flag {
return jsonError("Could not fetch metadata.")
}
switch p := thePost.(type) {
case *YouTubeVideo:
theReport.Type = "YouTubeVideo"
theReport.ID = p.ID
theReport.Title = p.Title
theReport.PublishedAt = p.PublishedAt
theReport.TotalComments = p.TotalComments
theReport.Metadata = p
case *InstagramPic:
theReport.Type = "InstagramPic"
theReport.ID = p.ID
theReport.Title = p.Caption
theReport.PublishedAt = p.PublishedAt
theReport.TotalComments = p.TotalComments
theReport.Metadata = p
case *FacebookPost:
theReport.Type = "FacebookPost"
theReport.ID = p.ID
//theReport.Title = p.Title
theReport.PublishedAt = p.PublishedAt
theReport.TotalComments = p.TotalComments
theReport.Metadata = p
}
// Fetch the comments
LogMsg("Fetching the comments...")
comments := thePost.GetComments()
// If we don't get an comments back, wait for the metadata call to return and send an error.
if comments.IsEmpty() {
return jsonError("No comments found for this post.")
} else {
LogMsg(fmt.Sprintf("Collected %d comments", comments.GetTotal()))
}
// Set comments returned
theReport.CollectedComments = comments.GetTotal()
theReport.CommentCoveragePercent = math.Ceil((float64(theReport.CollectedComments) / float64(theReport.TotalComments)) * float64(100))
done := make(chan bool)
// Count Keywords
go func() {
theReport.Keywords = comments.GetKeywords()
done <- true
}()
// Count Emoji
go func() {
theReport.EmojiCount = comments.GetEmojiCount()
done <- true
}()
// Sentiment Tagging
go func() {
LogMsg("Starting sentiment analysis...")
theReport.Sentiment = comments.GetSentimentSummary()
theReport.DailySentiment = comments.GetDailySentiment()
done <- true
}()
// Wait for everything to finish up
for i := 0; i < 3; i++ {
<-done
}
// Pull a few sample comments
theReport.SampleComments = comments.GetRandom(3)
// Pull the top liked comments
if theReport.Type == "YouTubeVideo" {
theReport.TopComments = comments.GetMostLiked(3)
}
// Calculate Average Daily Comments
timestamp, _ := strconv.ParseInt(theReport.PublishedAt, 10, 64)
t := time.Unix(timestamp, 0)
delta := time.Now().Sub(t)
theReport.CommentAvgPerDay = float64(theReport.TotalComments) / (float64(delta.Hours()) / float64(24))
reportJSON, err := json.Marshal(theReport)
if err != nil {
LogMsg(err.Error())
}
// Output Report
return reportJSON
}
func main() {
LoadConfig()
// Train the classifier
InitClassifier()
if !GetConfigBool("server") && GetConfigString("post") == "" {
LogMsg("Post URL is required.")
os.Exit(1)
}
if GetConfigString("stopwords") != "" {
swFiles := strings.Split(GetConfigString("stopwords"), ",")
for _, path := range swFiles {
LoadStopWords(path)
}
}
if GetConfigBool("server") {
LogMsg("Web server running on " + GetConfigString("port"))
http.HandleFunc("/", webHandler)
http.ListenAndServe(":"+GetConfigString("port"), nil)
} else {
LogMsg(string(runReport(GetConfigString("post"))))
}
}