main.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. package main
  2. import (
  3. "bytes"
  4. "database/sql"
  5. "encoding/json"
  6. "fmt"
  7. "log"
  8. "net/http"
  9. "regexp"
  10. "strconv"
  11. "strings"
  12. "time"
  13. // https://golang.org/ref/spec#Import_declarations
  14. _ "github.com/lib/pq"
  15. )
  16. // Faction is a struct that holds data about a faction
  17. type Faction struct {
  18. webhookGeneral string
  19. webhookWar string
  20. name string
  21. id int
  22. }
  23. // Event from http://api.orn.com/user
  24. type Event struct {
  25. id int
  26. timestamp time.Time
  27. news string
  28. }
  29. // Events array of Event
  30. type Events []Event
  31. // Attack struct
  32. type Attack struct {
  33. id int
  34. timestamp time.Time
  35. news string
  36. }
  37. // Attacks array of Attack
  38. type Attacks []Attack
  39. // News to be broadcast
  40. type News struct {
  41. Content string `json:"content"`
  42. }
  43. func main() {
  44. duration := time.Duration(10) * time.Second
  45. time.Sleep(duration)
  46. var err error
  47. var e Event
  48. timeFormat := "2006-01-02 15:04:05"
  49. // Faction data (Relentless, Unrelenting) is in secret.go
  50. factions := []Faction{relentless}
  51. for _, faction := range factions {
  52. e, err = getEventsFromDatabase(faction.name)
  53. if err != nil {
  54. log.Println("Database error:", err)
  55. }
  56. if e.id > 0 {
  57. fmt.Println("*** Processing: " + faction.name)
  58. var code int
  59. e.news = strings.Replace(e.news, "[", "\\[", -1)
  60. news := replaceLinks(e.news)
  61. news = strings.Replace(news, "http:", "https:", -1)
  62. news = "`" + e.timestamp.UTC().Format(timeFormat) + "`: " + news
  63. fmt.Println(faction.name + ": " + news)
  64. code, err = broadcastNews(news, faction.webhookGeneral) // general
  65. if err != nil {
  66. log.Println("broadcast error:", err)
  67. }
  68. fmt.Println(faction.name + ": " + strconv.Itoa(code))
  69. if code == 204 {
  70. // Assuming sent
  71. err = setBroadcastTrue(e.id)
  72. if err != nil {
  73. log.Fatal(err)
  74. }
  75. }
  76. }
  77. // Attacks
  78. attacks, err := getAttackFromDatabase(faction.name)
  79. if err != nil {
  80. log.Println("Database error:", err)
  81. }
  82. for key, attack := range attacks {
  83. fmt.Printf("attacks[%d].id: %d\n", key, attack.id)
  84. err = broadcastSingleAttack(attack, faction)
  85. if err != nil {
  86. log.Println(err)
  87. }
  88. }
  89. //a := attacks[0]
  90. }
  91. }
  92. func getEventsFromDatabase(factionName string) (Event, error) {
  93. var err error
  94. var e Event
  95. db, err := sql.Open("postgres", "user="+pgUser+" dbname="+pgTable+" password="+pgPasswd)
  96. if err != nil {
  97. return e, err
  98. }
  99. defer db.Close()
  100. rows, err := db.Query(`SELECT id, timestamp, news FROM events WHERE faction = '` +
  101. factionName + `' AND broadcast = FALSE ORDER BY id ASC LIMIT 1;`)
  102. if err != nil {
  103. return e, err
  104. }
  105. defer rows.Close()
  106. for rows.Next() {
  107. err = rows.Scan(&e.id, &e.timestamp, &e.news)
  108. if err != nil {
  109. return e, err
  110. }
  111. fmt.Println(e)
  112. }
  113. if err := rows.Err(); err != nil {
  114. return e, err
  115. }
  116. return e, nil
  117. }
  118. func getAttackFromDatabase(factionName string) (Attacks, error) {
  119. var err error
  120. var a Attack
  121. var attacks Attacks
  122. db, err := sql.Open("postgres", "user="+pgUser+" dbname="+pgTable+" password="+pgPasswd)
  123. if err != nil {
  124. return attacks, err
  125. }
  126. defer db.Close()
  127. rows, err := db.Query("SELECT id, timestamp, news FROM attacks WHERE faction = '" +
  128. factionName + "' AND broadcast = FALSE ORDER BY id ASC;")
  129. if err != nil {
  130. return attacks, err
  131. }
  132. defer rows.Close()
  133. for rows.Next() {
  134. err = rows.Scan(&a.id, &a.timestamp, &a.news)
  135. if err != nil {
  136. return attacks, err
  137. }
  138. attacks = append(attacks, a)
  139. fmt.Println(a)
  140. }
  141. if err := rows.Err(); err != nil {
  142. return attacks, err
  143. }
  144. return attacks, nil
  145. }
  146. func (e Event) String() string {
  147. line := fmt.Sprintf("{\n\t\"id\": %d,", e.id)
  148. line += fmt.Sprintf("\n\t\"timestamp\": %s,", e.timestamp)
  149. line += fmt.Sprintf("\n\t\"news\": %s", e.news)
  150. line += fmt.Sprintf("\n}")
  151. return line
  152. }
  153. func (a Attack) String() string {
  154. line := fmt.Sprintf("{\n\t\"id\": %d,", a.id)
  155. line += fmt.Sprintf("\n\t\"timestamp\": %s,", a.timestamp)
  156. line += fmt.Sprintf("\n\t\"news\": %s", a.news)
  157. line += fmt.Sprintf("\n}")
  158. return line
  159. }
  160. func replaceLinks(news string) string {
  161. // re := regexp.MustCompile(`<[aA].*?href\s?=\s?"?(.*?)[ "]?(?: .*?)?>(.*?)</a>`)
  162. re := regexp.MustCompile(`<[aA].*?href\s?=\s?"?https?://www.torn.com/profiles.php\?XID=(\d+)[ "]?>(.*?)</a>`)
  163. fmt.Println(re.FindAllStringSubmatch(news, -1))
  164. return re.ReplaceAllString(news, "[${2} [${1}]](https://www.torn.com/profiles.php?XID=${1})")
  165. //return news
  166. }
  167. func broadcastNews(new string, webhook string) (int, error) {
  168. // var err error
  169. var news News
  170. news.Content = new
  171. jsonValue, err := json.Marshal(news)
  172. if err != nil {
  173. return -1, err
  174. }
  175. fmt.Println(string(jsonValue))
  176. resp, err := http.Post(webhook, "application/json", bytes.NewBuffer(jsonValue))
  177. if err != nil {
  178. return -1, err
  179. }
  180. return resp.StatusCode, nil
  181. }
  182. func broadcastSingleAttack(attack Attack, faction Faction) error {
  183. timeFormat := "2006-01-02 15:04:05"
  184. if attack.id > 0 {
  185. members, err := getRelentlessMembers()
  186. if err != nil {
  187. log.Println("Database error:", err)
  188. }
  189. news := replaceLinks(attack.news)
  190. fmt.Println("Links replaced", news)
  191. news = strings.Replace(news, "http:", "https:", -1)
  192. for _, val := range members {
  193. news = strings.Replace(news, val, "**"+val+"**", -1)
  194. }
  195. news = strings.Replace(news, "_", "\\_", -1)
  196. news = attack.timestamp.UTC().Format(timeFormat) + ": " + news
  197. code, err := broadcastNews(news, faction.webhookWar) // war
  198. if err != nil {
  199. log.Println("broadcast error:", err)
  200. }
  201. fmt.Println(faction.name + ": " + strconv.Itoa(code))
  202. if code == 204 {
  203. // Assuming sent
  204. err = setAttackBroadcastTrue(attack.id)
  205. if err != nil {
  206. return err
  207. }
  208. }
  209. }
  210. return nil
  211. }
  212. func setBroadcastTrue(id int) error {
  213. fmt.Println(id)
  214. var err error
  215. db, err := sql.Open("postgres", "user="+pgUser+" dbname="+pgTable+" password="+pgPasswd)
  216. if err != nil {
  217. return err
  218. }
  219. defer db.Close()
  220. tx, err := db.Begin()
  221. if err != nil {
  222. log.Fatal(err)
  223. }
  224. defer tx.Rollback()
  225. _, err = tx.Exec(`SET TIME ZONE 'utc'`)
  226. stmt, err := tx.Prepare("UPDATE events SET broadcast = TRUE WHERE id = $1;")
  227. if err != nil {
  228. return err
  229. }
  230. _, err = stmt.Exec(fmt.Sprintf("%d", id))
  231. if err != nil {
  232. return err
  233. }
  234. err = tx.Commit()
  235. if err != nil {
  236. return err
  237. }
  238. return nil
  239. }
  240. func setAttackBroadcastTrue(id int) error {
  241. fmt.Println(id)
  242. var err error
  243. db, err := sql.Open("postgres", "user="+pgUser+" dbname="+pgTable+" password="+pgPasswd)
  244. if err != nil {
  245. return err
  246. }
  247. defer db.Close()
  248. tx, err := db.Begin()
  249. if err != nil {
  250. log.Fatal(err)
  251. }
  252. defer tx.Rollback()
  253. _, err = tx.Exec(`SET TIME ZONE 'utc'`)
  254. stmt, err := tx.Prepare("UPDATE attacks SET broadcast = TRUE WHERE id = $1;")
  255. if err != nil {
  256. return err
  257. }
  258. _, err = stmt.Exec(fmt.Sprintf("%d", id))
  259. if err != nil {
  260. return err
  261. }
  262. err = tx.Commit()
  263. if err != nil {
  264. return err
  265. }
  266. return nil
  267. }
  268. func getRelentlessMembers() ([]string, error) {
  269. var members []string
  270. var err error
  271. db, err := sql.Open("postgres", "user="+pgUser+" dbname="+pgTable+" password="+pgPasswd)
  272. if err != nil {
  273. return members, err
  274. }
  275. defer db.Close()
  276. rows, err := db.Query("SELECT member_name FROM members WHERE status = 'joined';")
  277. if err != nil {
  278. return members, err
  279. }
  280. defer rows.Close()
  281. var name string
  282. for rows.Next() {
  283. err = rows.Scan(&name)
  284. if err != nil {
  285. return members, err
  286. }
  287. members = append(members, name)
  288. }
  289. if err := rows.Err(); err != nil {
  290. return members, err
  291. }
  292. return members, nil
  293. }