-
Notifications
You must be signed in to change notification settings - Fork 3
/
fivethirtyeight.go
97 lines (85 loc) · 2.09 KB
/
fivethirtyeight.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
package main
import (
"fmt"
fte "github.com/munrocape/fivethirtyeight/fivethirtyeightclient"
"strings"
"time"
)
var (
FteClient *fte.Client
currentFteResponses map[string]string
fteTimestamps map[string]time.Time
)
func GetFteTop10(category string) (string, error) {
var err error
var rep string
if expiredFteResponse(fteTimestamps[category]) {
rep, err = generateNewFteResponse(category)
currentFteResponses[category] = rep
}
return currentFteResponses[category], err
}
func expiredFteResponse(timestamp time.Time) bool {
timeSinceLast := time.Since(timestamp)
if timeSinceLast > timeToExpire {
return true
}
return false
}
func generateNewFteResponse(category string) (string, error) {
c := getFteClient()
rss, err := c.GetFeed(category)
if err != nil {
return "", err
}
var urls [11]string
pretty := c.GetPretty(category)
uri := c.GetUri(category)
homepage := fmt.Sprintf("http://www.fivethirtyeight.com/%s", uri)
title := fmt.Sprintf("Top Stories from <%s|Five Thirty Eight %s>", homepage, pretty)
urls[0] = title
items := rss.Channel.Items
for index, element := range items {
index = index + 1
if index < 11 {
urls[index] = fmt.Sprintf("%d. <%s|%s>", index, element.Link, element.Title)
}
}
response := strings.Join(urls[:], "\n")
fteTimestamps[category] = time.Now().Local()
return response, nil
}
func GetFteSources() string {
c := getFteClient()
res := ""
first := true
for k, _ := range c.Categories {
if first {
res = res + k
first = false
} else {
res = res + ", " + k
}
}
return res
}
func getFteClient() *fte.Client {
if FteClient == nil {
FteClient = fte.NewClient()
currentFteResponses = make(map[string]string)
fteTimestamps = make(map[string]time.Time)
initializeFteTimestampMap(FteClient)
initializeFteResponseMap(FteClient)
}
return FteClient
}
func initializeFteTimestampMap(c *fte.Client) {
for k, _ := range c.Categories {
fteTimestamps[k] = time.Now().Local().AddDate(0, 0, -11)
}
}
func initializeFteResponseMap(c *fte.Client) {
for k, _ := range c.Categories {
currentFteResponses[k] = ""
}
}