bot.go 7.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. package main
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "flag"
  6. "fmt"
  7. "github.com/jasonlvhit/gocron"
  8. "github.com/lamperi/e4bot/spotify"
  9. "io"
  10. "log"
  11. "os"
  12. "regexp"
  13. "strconv"
  14. "strings"
  15. "time"
  16. )
  17. type App struct {
  18. db *DB
  19. credentials Credentials
  20. }
  21. type Credentials struct {
  22. APIURL string
  23. UserName string
  24. Password string
  25. SpotifyClientID string
  26. SpotifyClientSecret string
  27. ListenAddr string
  28. }
  29. func (app *App) CreateSpotifyClient() *spotify.SpotifyClient {
  30. spotifyClient := spotify.NewClient(app.credentials.SpotifyClientID, app.credentials.SpotifyClientSecret)
  31. return spotifyClient
  32. }
  33. func (app *App) LaunchWeb() {
  34. spotifyClient := app.CreateSpotifyClient()
  35. go func() {
  36. webStart(app.credentials.ListenAddr, app.db, spotifyClient)
  37. }()
  38. }
  39. func appendSong(wikiText string, author string, newSong string) string {
  40. const AUTHOR_MARK = "<!-- Lisääjä -->"
  41. const SONG_MARK = "<!-- Kappale -->"
  42. lines := strings.Split(wikiText, "\n")
  43. authorPrevIndex := -2
  44. changedLines := make([]string, 0, len(lines))
  45. for index, line := range lines {
  46. if strings.Index(line, AUTHOR_MARK) != -1 && strings.Index(line, author) != -1 {
  47. authorPrevIndex = index
  48. }
  49. if authorPrevIndex == (index-1) && strings.Index(line, SONG_MARK) != -1 {
  50. changedLines = append(changedLines, "| "+SONG_MARK+" "+newSong)
  51. } else {
  52. changedLines = append(changedLines, line)
  53. }
  54. }
  55. return strings.Join(changedLines, "\n")
  56. }
  57. func (app *App) wikiClient() *WikiClient {
  58. wiki := CreateWikiClient(app.credentials.APIURL, app.credentials.UserName, app.credentials.Password)
  59. return wiki
  60. }
  61. func (app *App) AddSong(updateTitle, updateSection, author, song string) (bool, error) {
  62. wiki := app.wikiClient()
  63. sections, err := wiki.GetWikiPageSections(updateTitle)
  64. if err != nil {
  65. return false, err
  66. }
  67. for _, section := range sections {
  68. if updateSection == section.title {
  69. wikiText, err := wiki.GetWikiPageSectionText(updateTitle, section.index)
  70. if err != nil {
  71. return false, err
  72. }
  73. changedWikiText := appendSong(wikiText, author, song)
  74. if false {
  75. // Stub
  76. fmt.Println("Pretend to update wiki text to ", updateTitle, section.index, changedWikiText,
  77. fmt.Sprintf("Added %s song for %s", updateSection, author))
  78. return true, nil
  79. }
  80. return wiki.EditWikiPageSection(updateTitle, section.index, changedWikiText,
  81. fmt.Sprintf("Added %s song for %s", updateSection, author))
  82. }
  83. }
  84. return false, errors.New("Could not find matching section")
  85. }
  86. func (app *App) SongSynced(userId, roundId int) error {
  87. _, err := app.db.EntrySynced(userId, roundId)
  88. return err
  89. }
  90. func (app *App) SubmitSongs() {
  91. entries, err := app.db.FindEntriesToSync()
  92. if err != nil {
  93. log.Println("Error while finding entries to sync:", err)
  94. return
  95. }
  96. for _, entry := range entries {
  97. song := songWikiText(entry.spotifyURL, entry.artist, entry.title)
  98. fmt.Println("Time has passed for " + song)
  99. success, err := app.AddSong(entry.article, entry.section, entry.username, song)
  100. if err != nil {
  101. log.Println("Error while adding song:", err)
  102. }
  103. if success {
  104. err = app.SongSynced(entry.userId, entry.roundId)
  105. if err != nil {
  106. fmt.Println("Error received:", err)
  107. }
  108. }
  109. }
  110. }
  111. func isCurrentAuthor(line, author string) bool {
  112. authorIndex := strings.Index(line, author)
  113. endIndex := strings.Index(line, "-->")
  114. return authorIndex != -1 && authorIndex < endIndex
  115. }
  116. func parseScore(line string) string {
  117. parts := strings.Split(line, "-->")
  118. if len(parts) < 2 {
  119. return ""
  120. }
  121. score := strings.TrimRight(strings.Trim(parts[1], " \t\n"), "p")
  122. if score == "" {
  123. return score
  124. }
  125. number, _ := regexp.Compile("^\\d([.,]\\d)?$")
  126. if number.MatchString(score) {
  127. return strings.Replace(score, ",", ".", 1)
  128. }
  129. numberHalf, _ := regexp.Compile("^\\d½$")
  130. if numberHalf.MatchString(score) {
  131. return fmt.Sprintf("%c.5", score[0])
  132. }
  133. stars, _ := regexp.Compile("^\\*+$")
  134. if stars.MatchString(score) {
  135. return fmt.Sprintf("%d", len(score))
  136. }
  137. imageStars, _ := regexp.Compile("^(\\[\\[Image:[01]\\.png\\]\\]){5}$")
  138. if imageStars.MatchString(score) {
  139. return fmt.Sprintf("%d", strings.Count(score, "1"))
  140. }
  141. quarterScore, _ := regexp.Compile("^\\d-\\d½?$")
  142. if quarterScore.MatchString(score) {
  143. return fmt.Sprintf("%c.25", score[0])
  144. }
  145. thirdQuarterScore, _ := regexp.Compile("^\\d½?-\\d$")
  146. if thirdQuarterScore.MatchString(score) {
  147. return fmt.Sprintf("%c.75", score[0])
  148. }
  149. fmt.Printf("Could not match '%s'\n", score)
  150. return ""
  151. }
  152. func appendAverages(wikiText string) string {
  153. const AUTHOR_MARK = "<!-- Lisääjä -->"
  154. const SONG_MARK = "<!-- Kappale -->"
  155. const AVERAGE_MARK = "<!-- KA -->"
  156. lines := strings.Split(wikiText, "\n")
  157. isScore := false
  158. scores := make([]string, 0)
  159. count := 0
  160. currentAuthor := ""
  161. changedLines := make([]string, 0, len(lines))
  162. for _, line := range lines {
  163. if strings.Index(line, AUTHOR_MARK) != -1 {
  164. currentAuthor = strings.Trim(strings.Split(line, AUTHOR_MARK)[1], " \t")
  165. } else if strings.Index(line, SONG_MARK) != -1 {
  166. isScore = true
  167. scores = make([]string, 0)
  168. count = 0
  169. } else if isScore && strings.Index(line, AVERAGE_MARK) == -1 {
  170. if !isCurrentAuthor(line, currentAuthor) {
  171. score := parseScore(line)
  172. if score != "" {
  173. scores = append(scores, score)
  174. count += 1
  175. } else {
  176. scores = append(scores, "0")
  177. }
  178. }
  179. }
  180. if strings.Index(line, AVERAGE_MARK) != -1 && count > 2 {
  181. expression := fmt.Sprintf("'''{{#expr:(%s)/%d round 2}}'''", strings.Join(scores, "+"), count)
  182. newLine := "| " + AVERAGE_MARK + " " + expression
  183. changedLines = append(changedLines, newLine)
  184. if newLine != line {
  185. fmt.Printf("Difference for %s\n%s\n%s\n", currentAuthor, newLine, line)
  186. }
  187. } else {
  188. changedLines = append(changedLines, line)
  189. }
  190. }
  191. return strings.Join(changedLines, "\n")
  192. }
  193. func (app *App) FixAverages(title string) error {
  194. wiki := app.wikiClient()
  195. sections, err := wiki.GetWikiPageSections(title)
  196. if err != nil {
  197. return err
  198. }
  199. _, currentWeek := time.Now().ISOWeek()
  200. numberReg, _ := regexp.Compile("\\d+")
  201. for _, section := range sections {
  202. weekStr := numberReg.FindString(section.title)
  203. if weekStr != "" {
  204. weekNumber, _ := strconv.Atoi(weekStr)
  205. if weekNumber < currentWeek-1 {
  206. continue
  207. }
  208. if weekNumber > currentWeek {
  209. break
  210. }
  211. wikiText, err := wiki.GetWikiPageSectionText(title, section.index)
  212. if err != nil {
  213. return err
  214. }
  215. changedWikiText := appendAverages(wikiText)
  216. if changedWikiText != wikiText {
  217. //fmt.Println(wikiText)
  218. //fmt.Println(changedWikiText)
  219. _, err := wiki.EditWikiPageSection(title, section.index, changedWikiText,
  220. fmt.Sprintf("Calculate averages for week %d", weekNumber))
  221. if err != nil {
  222. return err
  223. }
  224. }
  225. }
  226. }
  227. return nil
  228. }
  229. func (app *App) FixAveragesTask() {
  230. err := app.FixAverages("Levyraati 2018")
  231. if err != nil {
  232. fmt.Println("Error while calculating averages:", err)
  233. }
  234. }
  235. func initCreds() (Credentials, error) {
  236. var credsFile string
  237. flag.StringVar(&credsFile, "credentials", "credentials.json", "JSON config to hold app credentials")
  238. flag.Parse()
  239. var credentials Credentials
  240. f, err := os.Open(credsFile)
  241. if err != nil {
  242. return credentials, err
  243. }
  244. defer f.Close()
  245. if err != nil {
  246. log.Fatal(err)
  247. return credentials, err
  248. }
  249. dec := json.NewDecoder(f)
  250. for {
  251. if err := dec.Decode(&credentials); err == io.EOF {
  252. break
  253. } else if err != nil {
  254. log.Fatal(err)
  255. }
  256. }
  257. return credentials, nil
  258. }
  259. func songWikiText(url string, artist string, title string) string {
  260. return "[" + url + " " + artist + " - " + title + "]"
  261. }
  262. func main() {
  263. creds, err := initCreds()
  264. if err != nil {
  265. panic(err)
  266. }
  267. a := App{InitDatabase(), creds}
  268. a.LaunchWeb()
  269. gocron.Every(1).Hour().Do(a.FixAveragesTask)
  270. gocron.Every(1).Second().Do(a.SubmitSongs)
  271. <-gocron.Start()
  272. }