bot.go 10KB

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