This repository has been archived by the owner on Jan 3, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
redditHandler.go
196 lines (177 loc) · 4.69 KB
/
redditHandler.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
package main
import (
"fmt"
"math/rand"
"strconv"
"strings"
"time"
"github.com/turnage/graw/reddit"
)
// Replaces the "reddit.NewBotFromAgentFile" with a simple function call. Uses
// getRedditEnv and gets data from environment
func initBot() (reddit.Bot, error) {
var agent agentFile = getRedditEnv()
app := reddit.App{
ID: agent.ClientID,
Secret: agent.ClientSecret,
}
bot, err := reddit.NewBot(
reddit.BotConfig{
Agent: agent.UserAgent,
App: app,
Rate: 0,
},
)
return bot, err
}
// GuessPostType get the type of the post so a
func GuessPostType(post *reddit.Post) string {
selfText := post.SelfText
urlContent := post.URL
if selfText == "" {
urlItems := []string{".jpg", ".png", ".jpeg", "gfycat", "youtube", "youtu.be", "gif", "gifv"}
if !strings.Contains(urlContent, "v.redd.it") && ContainsAnySubstring(urlContent, urlItems) {
return "media"
}
return "link"
}
return "text"
}
// PingReddit tests reddit connection
func PingReddit() error {
bot, err := initBot()
if err != nil {
fmt.Println("Error pinging Reddit:", err)
return err
}
_, err = bot.Listing("/r/all", "")
if err != nil {
fmt.Println("Error pinging Reddit:", err)
}
return err
}
// GetPost gets reddit posts
func GetPost(subs []string, limit int, sort string, mode string) (QuickPost, string) {
var gottenPosts []QuickPost
var cachePosts []QuickPost
var gotPost QuickPost
var returnPost QuickPost
var subList []string
var sub string
var success bool
var s int
subList = getAllSubsFromMap()
sub = subs[rand.Intn(len(subs))]
cachePosts, success = GetFromCache(sub)
now := time.Now().Unix()
if now >= CacheTime && !CachePopulating {
fmt.Println("Clearing Cache...")
ClearCache()
success = false
CacheTime = time.Now().Unix() + 3600
fmt.Println("New cache time is " + strconv.FormatInt(CacheTime, 10))
CachePopulating = true
go PopulateCache()
}
if !success {
starttime := GetMillis()
bot, err := initBot()
if err != nil {
fmt.Println("Error creating new Reddit bot:", err)
return QuickPost{}, ""
}
rand.Seed(time.Now().Unix())
fmt.Println("Adding r/" + sub + " to cache.")
harvest, err := bot.Listing("/r/"+sub+"/"+sort, "") // the bot is locking up here
if err != nil {
fmt.Println("Error getting posts from sub '", sub, "':", err)
return QuickPost{}, sub
}
lengthPosts := len(harvest.Posts)
if lengthPosts < limit {
limit = lengthPosts
}
for _, post := range harvest.Posts[:limit] {
mode := GuessPostType(post)
switch {
case mode == "link" || mode == "media":
gotPost = QuickPost{
Title: post.Title,
Score: post.Score,
Content: post.URL,
Nsfw: post.NSFW,
Permalink: post.Permalink,
Sub: getSubFromPermalink(post.Permalink),
}
case mode == "text":
gotPost = QuickPost{
Title: post.Title,
Score: post.Score,
Content: post.SelfText,
Nsfw: post.NSFW,
Permalink: post.Permalink,
Sub: getSubFromPermalink(post.Permalink),
}
}
gottenPosts = append(gottenPosts, gotPost)
}
gottenLength := len(gottenPosts)
if gottenLength == 0 {
returnPost = QuickPost{
Title: "ERROR: Sub seems to be empty or does not exist.",
Score: 0,
Content: "",
Nsfw: false,
Permalink: "/r/" + sub + "/",
}
fmt.Println("Nothing to cache! Discarding....")
} else if ContainsAnySubstring(sub, subList) {
s = rand.Intn(gottenLength)
returnPost = gottenPosts[s]
} else {
AddToCache(sub, gottenPosts)
CacheTime = time.Now().Unix() + 1800
s = rand.Intn(gottenLength)
returnPost = gottenPosts[s]
endtime := GetMillis()
t := endtime - starttime
fmt.Println("Took " + strconv.FormatInt(t, 10) + "ms to add to cache.")
}
} else {
fmt.Println("Found r/" + sub + " in cache.")
minScore := MinScore(cachePosts)
for i := 0; i < len(cachePosts); i++ {
s := rand.Intn(len(cachePosts))
returnPost = cachePosts[s]
if returnPost.Score >= minScore {
break
}
}
}
return returnPost, getSubFromPermalink(returnPost.Permalink)
}
// MinScore Formula for calculating effective minimum score.
func MinScore(posts []QuickPost) int32 {
var total int32
var n int = len(posts)
for _, post := range posts {
total += post.Score
}
avg := total / int32(n)
return avg / 2
}
// getSubFromPermalink gets a sub from the link to the post
func getSubFromPermalink(permalink string) string {
var sub string
linkArray := strings.Split(permalink, "/")
sub = linkArray[2]
return sub
}
// getSubsFromMap gets the subreddits from RAM instead of from disk
func getAllSubsFromMap() []string {
var allSubs []string
for _, value := range SubMap {
allSubs = append(allSubs, value...)
}
return allSubs
}