bot.go 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  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. "reflect"
  13. "regexp"
  14. "strconv"
  15. "strings"
  16. "time"
  17. )
  18. type App struct {
  19. db *DB
  20. credentials Credentials
  21. spotifyClient *spotify.SpotifyClient
  22. }
  23. type Credentials struct {
  24. APIURL string
  25. UserName string
  26. Password string
  27. SpotifyClientID string
  28. SpotifyClientSecret string
  29. SpotifyUser string
  30. SpotifyCallback string
  31. ListenAddr string
  32. }
  33. func (app *App) CreateSpotifyClient() *spotify.SpotifyClient {
  34. spotifyClient := spotify.NewClient(app.credentials.SpotifyClientID, app.credentials.SpotifyClientSecret)
  35. spotifyClient.SetupUserAuthenticate(app.credentials.SpotifyCallback)
  36. return spotifyClient
  37. }
  38. func (app *App) LaunchWeb() {
  39. app.spotifyClient = app.CreateSpotifyClient()
  40. go func() {
  41. webStart(app.credentials.ListenAddr, app.db, app.spotifyClient)
  42. }()
  43. }
  44. func appendSong(wikiText string, author string, newSong string) string {
  45. const AUTHOR_MARK = "<!-- Lisääjä -->"
  46. const SONG_MARK = "<!-- Kappale -->"
  47. lines := strings.Split(wikiText, "\n")
  48. authorPrevIndex := -2
  49. changedLines := make([]string, 0, len(lines))
  50. for index, line := range lines {
  51. if strings.Index(line, AUTHOR_MARK) != -1 && strings.Index(line, author) != -1 {
  52. authorPrevIndex = index
  53. }
  54. if authorPrevIndex == (index-1) && strings.Index(line, SONG_MARK) != -1 {
  55. changedLines = append(changedLines, "| "+SONG_MARK+" "+newSong)
  56. } else {
  57. changedLines = append(changedLines, line)
  58. }
  59. }
  60. return strings.Join(changedLines, "\n")
  61. }
  62. func (app *App) wikiClient() *WikiClient {
  63. wiki := CreateWikiClient(app.credentials.APIURL, app.credentials.UserName, app.credentials.Password)
  64. return wiki
  65. }
  66. func (app *App) AddSong(updateTitle, updateSection, author, song string) (bool, error) {
  67. wiki := app.wikiClient()
  68. sections, err := wiki.GetWikiPageSections(updateTitle)
  69. if err != nil {
  70. return false, err
  71. }
  72. for _, section := range sections {
  73. if updateSection == section.title {
  74. wikiText, err := wiki.GetWikiPageSectionText(updateTitle, section.index)
  75. if err != nil {
  76. return false, err
  77. }
  78. changedWikiText := appendSong(wikiText, author, song)
  79. if false {
  80. // Stub
  81. log.Println("Pretend to update wiki text to ", updateTitle, section.index, changedWikiText,
  82. fmt.Sprintf("Added %s song for %s", updateSection, author))
  83. return true, nil
  84. }
  85. return wiki.EditWikiPageSection(updateTitle, section.index, changedWikiText,
  86. fmt.Sprintf("Added %s song for %s", updateSection, author))
  87. }
  88. }
  89. return false, errors.New("Could not find matching section")
  90. }
  91. func (app *App) SongSynced(userId, roundId int) error {
  92. _, err := app.db.EntrySynced(userId, roundId)
  93. return err
  94. }
  95. func (app *App) SubmitSongs() {
  96. entries, err := app.db.FindEntriesToSync()
  97. if err != nil {
  98. log.Println("Error while finding entries to sync:", err)
  99. return
  100. }
  101. for _, entry := range entries {
  102. song := songWikiText(entry.spotifyURL, entry.artist, entry.title)
  103. log.Println("Time has passed for " + song)
  104. success, err := app.AddSong(entry.article, entry.section, entry.username, song)
  105. if err != nil {
  106. log.Println("Error while adding song:", err)
  107. }
  108. if success {
  109. err = app.SongSynced(entry.userId, entry.roundId)
  110. if err != nil {
  111. log.Println("Error received:", err)
  112. }
  113. }
  114. }
  115. }
  116. func isCurrentAuthor(line, author string) bool {
  117. authorIndex := strings.Index(line, author)
  118. endIndex := strings.Index(line, "-->")
  119. return authorIndex != -1 && authorIndex < endIndex
  120. }
  121. func parseScore(line string) string {
  122. parts := strings.Split(line, "-->")
  123. if len(parts) < 2 {
  124. return ""
  125. }
  126. score := strings.TrimRight(strings.Trim(parts[1], " \t\n"), "p")
  127. if score == "" {
  128. return score
  129. }
  130. rating, _ := regexp.Compile("^\\{\\{Rating\\|\\d([.,]\\d)?\\|5\\}\\}$")
  131. if rating.MatchString(score) {
  132. score = strings.Replace(score, "{{Rating|", "", 1)
  133. score = strings.Replace(score, "|5}}", "", 1)
  134. }
  135. number, _ := regexp.Compile("^\\d([.,]\\d)?$")
  136. if number.MatchString(score) {
  137. return strings.Replace(score, ",", ".", 1)
  138. }
  139. numberHalf, _ := regexp.Compile("^\\d½$")
  140. if numberHalf.MatchString(score) {
  141. return fmt.Sprintf("%c.5", score[0])
  142. }
  143. stars, _ := regexp.Compile("^\\*+$")
  144. if stars.MatchString(score) {
  145. return fmt.Sprintf("%d", len(score))
  146. }
  147. imageStars, _ := regexp.Compile("^(\\[\\[Image:[01]\\.png\\]\\]){5}$")
  148. if imageStars.MatchString(score) {
  149. return fmt.Sprintf("%d", strings.Count(score, "1"))
  150. }
  151. quarterScore, _ := regexp.Compile("^\\d-\\d½?$")
  152. if quarterScore.MatchString(score) {
  153. return fmt.Sprintf("%c.25", score[0])
  154. }
  155. thirdQuarterScore, _ := regexp.Compile("^\\d½?-\\d$")
  156. if thirdQuarterScore.MatchString(score) {
  157. return fmt.Sprintf("%c.75", score[0])
  158. }
  159. log.Printf("Could not match '%s'\n", score)
  160. return ""
  161. }
  162. func appendAverages(wikiText string) string {
  163. const AUTHOR_MARK = "<!-- Lisääjä -->"
  164. const SONG_MARK = "<!-- Kappale -->"
  165. const AVERAGE_MARK = "<!-- KA -->"
  166. lines := strings.Split(wikiText, "\n")
  167. isScore := false
  168. scores := make([]string, 0)
  169. count := 0
  170. currentAuthor := ""
  171. changedLines := make([]string, 0, len(lines))
  172. for _, line := range lines {
  173. if strings.Index(line, AUTHOR_MARK) != -1 {
  174. currentAuthor = strings.Trim(strings.Split(line, AUTHOR_MARK)[1], " \t")
  175. } else if strings.Index(line, SONG_MARK) != -1 {
  176. isScore = true
  177. scores = make([]string, 0)
  178. count = 0
  179. } else if isScore && strings.Index(line, AVERAGE_MARK) == -1 {
  180. if !isCurrentAuthor(line, currentAuthor) {
  181. score := parseScore(line)
  182. if score != "" {
  183. scores = append(scores, score)
  184. count += 1
  185. } else {
  186. scores = append(scores, "0")
  187. }
  188. }
  189. }
  190. if strings.Index(line, AVERAGE_MARK) != -1 && count > 2 {
  191. expression := fmt.Sprintf("'''{{#expr:(%s)/%d round 2}}'''", strings.Join(scores, "+"), count)
  192. newLine := "| " + AVERAGE_MARK + " " + expression
  193. changedLines = append(changedLines, newLine)
  194. if newLine != line {
  195. log.Printf("Difference for %s\n%s\n%s\n", currentAuthor, newLine, line)
  196. }
  197. } else {
  198. changedLines = append(changedLines, line)
  199. }
  200. }
  201. return strings.Join(changedLines, "\n")
  202. }
  203. func findPlaylist(wikiText string) (string, []string) {
  204. const SONG_MARK = "<!-- Kappale -->"
  205. const SPOTIFY_MARK = "https://open.spotify.com/track/"
  206. const SPOTIFY_PLAYLIST_MARK = "/playlist/"
  207. const PLAYLIST_MARK = " Spotify-soittolista]"
  208. lines := strings.Split(wikiText, "\n")
  209. playlistId := ""
  210. tracks := make([]string, 0)
  211. for _, line := range lines {
  212. if strings.Index(line, SONG_MARK) != -1 {
  213. i := strings.Index(line, SPOTIFY_MARK)
  214. if i != -1 {
  215. j := strings.Index(line[i:], " ")
  216. if j != -1 {
  217. j += i
  218. }
  219. trackId := line[i+len(SPOTIFY_MARK) : j]
  220. tracks = append(tracks, trackId)
  221. }
  222. } else if strings.Index(line, SPOTIFY_PLAYLIST_MARK) != -1 && strings.Index(line, PLAYLIST_MARK) != -1 {
  223. i := strings.Index(line, SPOTIFY_PLAYLIST_MARK)
  224. j := strings.Index(line[i:], PLAYLIST_MARK)
  225. playlistId = line[i+len(SPOTIFY_PLAYLIST_MARK) : i+j]
  226. q := strings.Index(playlistId, "?")
  227. if q != -1 {
  228. playlistId = playlistId[:q]
  229. }
  230. }
  231. }
  232. log.Printf("Found playlist %s and tracks %s\n", playlistId, tracks)
  233. return playlistId, tracks
  234. }
  235. func appendPlaylist(wikiText string, playlist *spotify.PlaylistInfo) string {
  236. changedText := wikiText + `
  237. [` + playlist.ExternalUrls.Spotify + ` Spotify-soittolista]
  238. `
  239. return changedText
  240. }
  241. func (app *App) AutomateSection(title string) error {
  242. wiki := app.wikiClient()
  243. sections, err := wiki.GetWikiPageSections(title)
  244. if err != nil {
  245. return err
  246. }
  247. _, currentWeek := time.Now().ISOWeek()
  248. numberReg, _ := regexp.Compile("\\d+")
  249. for _, section := range sections {
  250. weekStr := numberReg.FindString(section.title)
  251. if weekStr != "" {
  252. weekNumber, _ := strconv.Atoi(weekStr)
  253. if weekNumber < currentWeek-1 {
  254. continue
  255. }
  256. if weekNumber > currentWeek {
  257. break
  258. }
  259. log.Println("Checking section", section.title)
  260. wikiText, err := wiki.GetWikiPageSectionText(title, section.index)
  261. if err != nil {
  262. return err
  263. }
  264. message := ""
  265. changedWikiText := appendAverages(wikiText)
  266. if changedWikiText != wikiText {
  267. message = message + fmt.Sprintf("Calculate averages for week %d. ", weekNumber)
  268. }
  269. if app.spotifyClient.HasUserLogin() {
  270. playlistId, tracks := findPlaylist(changedWikiText)
  271. currentTracks, err := app.db.FindPlaylistBySection(section.title)
  272. if len(tracks) > 0 && (err != nil || reflect.DeepEqual(currentTracks, tracks)) {
  273. spotify := app.spotifyClient
  274. if playlistId == "" {
  275. info, err := spotify.NewPlaylist(title+" "+section.title, app.credentials.SpotifyUser)
  276. if err != nil {
  277. log.Println("Error creating playlist")
  278. return err
  279. }
  280. playlistId = info.Id
  281. changedWikiText = appendPlaylist(changedWikiText, info)
  282. message = message + fmt.Sprintf("Added link to Spotify playlist for week %d.", weekNumber)
  283. }
  284. err := spotify.UpdatePlaylist(app.credentials.SpotifyUser, playlistId, tracks)
  285. if err != nil {
  286. log.Println("Error updating playlist")
  287. return err
  288. }
  289. _, err = app.db.UpdatePlaylistBySection(section.title, tracks)
  290. if err != nil {
  291. return err
  292. }
  293. }
  294. }
  295. if message != "" {
  296. _, err := wiki.EditWikiPageSection(title, section.index, changedWikiText,
  297. fmt.Sprintf("Calculate averages for week %d", weekNumber))
  298. err = nil
  299. if err != nil {
  300. return err
  301. }
  302. }
  303. }
  304. }
  305. return nil
  306. }
  307. func (app *App) AutomateSectionTask() {
  308. panels, err := app.db.FindAllPanels()
  309. if err != nil {
  310. log.Println("Error while checking db for panels:", err)
  311. return
  312. }
  313. for _, panel := range panels {
  314. log.Println("Checking panel", panel)
  315. err := app.AutomateSection(panel)
  316. if err != nil {
  317. log.Println("Error while processing panel:", err)
  318. }
  319. }
  320. }
  321. func initCreds() (Credentials, error) {
  322. var credsFile string
  323. flag.StringVar(&credsFile, "credentials", "credentials.json", "JSON config to hold app credentials")
  324. flag.Parse()
  325. var credentials Credentials
  326. f, err := os.Open(credsFile)
  327. if err != nil {
  328. return credentials, err
  329. }
  330. defer f.Close()
  331. if err != nil {
  332. log.Fatal(err)
  333. return credentials, err
  334. }
  335. dec := json.NewDecoder(f)
  336. for {
  337. if err := dec.Decode(&credentials); err == io.EOF {
  338. break
  339. } else if err != nil {
  340. log.Fatal(err)
  341. }
  342. }
  343. return credentials, nil
  344. }
  345. func songWikiText(url string, artist string, title string) string {
  346. return "[" + url + " " + artist + " - " + title + "]"
  347. }
  348. func main() {
  349. creds, err := initCreds()
  350. if err != nil {
  351. panic(err)
  352. }
  353. a := App{InitDatabase(), creds, nil}
  354. a.LaunchWeb()
  355. gocron.Every(1).Hour().Do(a.AutomateSectionTask)
  356. gocron.Every(1).Second().Do(a.SubmitSongs)
  357. <-gocron.Start()
  358. }