discordo.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. package main
  2. import (
  3. "sort"
  4. "strings"
  5. "github.com/atotto/clipboard"
  6. "github.com/gdamore/tcell/v2"
  7. "github.com/rigormorrtiss/discordgo"
  8. "github.com/rigormorrtiss/discordo/ui"
  9. "github.com/rigormorrtiss/discordo/util"
  10. "github.com/rivo/tview"
  11. "github.com/zalando/go-keyring"
  12. )
  13. var (
  14. app *tview.Application
  15. loginForm *tview.Form
  16. guildsView *tview.TreeView
  17. messagesView *tview.TextView
  18. messageInputField *tview.InputField
  19. mainFlex *tview.Flex
  20. config *util.Config
  21. session *discordgo.Session
  22. selectedChannel *discordgo.Channel
  23. selectedMessage *discordgo.Message
  24. )
  25. func main() {
  26. config = util.NewConfig()
  27. if config.Theme != nil {
  28. tview.Styles = *config.Theme
  29. }
  30. app = tview.NewApplication().
  31. EnableMouse(config.Mouse).
  32. SetInputCapture(onAppInputCapture)
  33. guildsView = ui.NewGuildsView(onGuildsTreeViewSelected)
  34. messagesView = ui.NewMessagesView(
  35. app,
  36. onMessagesTextViewInputCapture,
  37. )
  38. messageInputField = ui.NewMessageInputField(onMessageInputFieldInputCapture)
  39. mainFlex = ui.NewMainFlex(
  40. guildsView,
  41. messagesView,
  42. messageInputField,
  43. )
  44. token := config.Token
  45. if t, _ := keyring.Get("discordo", "token"); t != "" {
  46. token = t
  47. }
  48. if token != "" {
  49. app.
  50. SetRoot(mainFlex, true).
  51. SetFocus(guildsView)
  52. session = newSession()
  53. session.Token = token
  54. session.Identify.Token = token
  55. if err := session.Open(); err != nil {
  56. panic(err)
  57. }
  58. } else {
  59. loginForm = ui.NewLoginForm(onLoginFormLoginButtonSelected, false)
  60. app.SetRoot(loginForm, true)
  61. }
  62. if err := app.Run(); err != nil {
  63. panic(err)
  64. }
  65. }
  66. func onAppInputCapture(e *tcell.EventKey) *tcell.EventKey {
  67. if e.Modifiers() == tcell.ModAlt {
  68. switch e.Rune() {
  69. case '1':
  70. app.SetFocus(guildsView)
  71. case '2':
  72. app.SetFocus(messagesView)
  73. case '3':
  74. app.SetFocus(messageInputField)
  75. }
  76. }
  77. return e
  78. }
  79. func findByMessageID(ms []*discordgo.Message, mID string) (int, *discordgo.Message) {
  80. for i, m := range ms {
  81. if mID == m.ID {
  82. return i, m
  83. }
  84. }
  85. return -1, nil
  86. }
  87. func onMessagesTextViewInputCapture(e *tcell.EventKey) *tcell.EventKey {
  88. if selectedChannel == nil {
  89. return nil
  90. }
  91. switch {
  92. case e.Key() == tcell.KeyUp || e.Rune() == 'k': // Up
  93. ms := selectedChannel.Messages
  94. hs := messagesView.GetHighlights()
  95. // If there are no currently highlighted message, highlight the last
  96. // message in the TextView.
  97. if len(hs) == 0 {
  98. messagesView.
  99. Highlight(ms[len(ms)-1].ID).
  100. ScrollToHighlight()
  101. } else {
  102. // Find the index of the currently highlighted message in the
  103. // *discordgo.Channel.Messages slice.
  104. idx, _ := findByMessageID(ms, hs[0])
  105. // If the index of the currently highlighted message is equal to
  106. // zero
  107. // (first message in the TextView), do not handle the event.
  108. if idx == -1 || idx == 0 {
  109. return nil
  110. }
  111. // Highlight the message just before the currently highlighted
  112. // message.
  113. messagesView.
  114. Highlight(ms[idx-1].ID).
  115. ScrollToHighlight()
  116. }
  117. return nil
  118. case e.Key() == tcell.KeyDown || e.Rune() == 'j': // Down
  119. ms := selectedChannel.Messages
  120. hs := messagesView.GetHighlights()
  121. // If there are no currently highlighted message, highlight the last
  122. // message in the TextView.
  123. if len(hs) == 0 {
  124. messagesView.
  125. Highlight(ms[len(ms)-1].ID).
  126. ScrollToHighlight()
  127. } else {
  128. // Find the index of the highlighted message in the
  129. // *discordgo.Channel.Messages slice.
  130. idx, _ := findByMessageID(ms, hs[0])
  131. // If the index of the currently highlighted message is equal to the
  132. // total number of elements in the *discordgo.Channel.Messages
  133. // slice, do not handle the event.
  134. if idx == -1 || idx == len(ms)-1 {
  135. return nil
  136. }
  137. // Highlight the message just after the currently highlighted
  138. // message.
  139. messagesView.
  140. Highlight(ms[idx+1].ID).
  141. ScrollToHighlight()
  142. }
  143. return nil
  144. case e.Key() == tcell.KeyHome || e.Rune() == 'g': // Top
  145. ms := selectedChannel.Messages
  146. // Highlight the last message in the selectedChannel.Messages slice
  147. // (the first message rendered in the TextView).
  148. messagesView.
  149. Highlight(ms[0].ID).
  150. ScrollToHighlight()
  151. case e.Key() == tcell.KeyEnd || e.Rune() == 'G': // Bottom
  152. ms := selectedChannel.Messages
  153. // Highlight the first message in the selectedChannel.Messages slice
  154. // (the last message rendered in the TextView).
  155. messagesView.
  156. Highlight(ms[len(ms)-1].ID).
  157. ScrollToHighlight()
  158. case e.Rune() == 'r': // Reply
  159. ms := selectedChannel.Messages
  160. hs := messagesView.GetHighlights()
  161. if len(hs) == 0 {
  162. return nil
  163. }
  164. _, selectedMessage = findByMessageID(ms, hs[0])
  165. messageInputField.SetTitle(
  166. "Replying to " + selectedMessage.Author.Username,
  167. )
  168. app.SetFocus(messageInputField)
  169. }
  170. return e
  171. }
  172. func onMessageInputFieldInputCapture(e *tcell.EventKey) *tcell.EventKey {
  173. // If the "Alt" modifier key is pressed, do not handle the event.
  174. if e.Modifiers() == tcell.ModAlt {
  175. return nil
  176. }
  177. switch e.Key() {
  178. case tcell.KeyEnter:
  179. if selectedChannel == nil {
  180. return nil
  181. }
  182. t := strings.TrimSpace(messageInputField.GetText())
  183. if t == "" {
  184. return nil
  185. }
  186. if selectedMessage != nil {
  187. messageInputField.SetTitle("")
  188. go session.ChannelMessageSendReply(
  189. selectedMessage.ChannelID,
  190. t,
  191. selectedMessage.Reference(),
  192. )
  193. selectedMessage = nil
  194. } else {
  195. go session.ChannelMessageSend(selectedChannel.ID, t)
  196. }
  197. messageInputField.SetText("")
  198. case tcell.KeyCtrlV:
  199. text, _ := clipboard.ReadAll()
  200. text = messageInputField.GetText() + text
  201. messageInputField.SetText(text)
  202. case tcell.KeyEscape: // Cancel
  203. messageInputField.SetTitle("")
  204. selectedMessage = nil
  205. }
  206. return e
  207. }
  208. func newSession() *discordgo.Session {
  209. s, err := discordgo.New()
  210. if err != nil {
  211. panic(err)
  212. }
  213. s.UserAgent = "" +
  214. "Mozilla/5.0 (X11; Linux x86_64) " +
  215. "AppleWebKit/537.36 (KHTML, like Gecko) " +
  216. "Chrome/92.0.4515.131 Safari/537.36"
  217. s.Identify.Compress = false
  218. s.Identify.Intents = 0
  219. s.Identify.LargeThreshold = 0
  220. s.Identify.Properties.Device = ""
  221. s.Identify.Properties.Browser = "Chrome"
  222. s.Identify.Properties.OS = "Linux"
  223. s.AddHandlerOnce(onSessionReady)
  224. s.AddHandler(onSessionMessageCreate)
  225. return s
  226. }
  227. func onSessionReady(_ *discordgo.Session, r *discordgo.Ready) {
  228. sort.Slice(r.Guilds, func(a, b int) bool {
  229. found := false
  230. for _, gID := range r.Settings.GuildPositions {
  231. if found {
  232. if gID == r.Guilds[b].ID {
  233. return true
  234. }
  235. } else {
  236. if gID == r.Guilds[a].ID {
  237. found = true
  238. }
  239. }
  240. }
  241. return false
  242. })
  243. n := guildsView.GetRoot()
  244. for _, g := range r.Guilds {
  245. gn := tview.NewTreeNode(g.Name).
  246. SetReference(g.ID)
  247. n.AddChild(gn)
  248. }
  249. guildsView.SetCurrentNode(n)
  250. }
  251. func onSessionMessageCreate(_ *discordgo.Session, m *discordgo.MessageCreate) {
  252. if selectedChannel == nil || selectedChannel.ID != m.ChannelID {
  253. return
  254. }
  255. selectedChannel.Messages = append(selectedChannel.Messages, m.Message)
  256. util.WriteMessage(
  257. messagesView,
  258. m.Message,
  259. session.State.Ready.User.ID,
  260. )
  261. }
  262. func onGuildsTreeViewSelected(n *tview.TreeNode) {
  263. selectedChannel = nil
  264. selectedMessage = nil
  265. messagesView.
  266. Clear().
  267. SetTitle("")
  268. switch n.GetLevel() {
  269. case 1:
  270. if len(n.GetChildren()) != 0 {
  271. n.SetExpanded(!n.IsExpanded())
  272. return
  273. }
  274. n.ClearChildren()
  275. gID := n.GetReference().(string)
  276. g, _ := session.State.Guild(gID)
  277. cs := g.Channels
  278. sort.Slice(cs, func(i, j int) bool {
  279. return cs[i].Position < cs[j].Position
  280. })
  281. // Top-level channels
  282. ui.CreateTopLevelChannelsTreeNodes(session.State, n, cs)
  283. // Category channels
  284. ui.CreateCategoryChannelsTreeNodes(session.State, n, cs)
  285. // Second-level channels
  286. ui.CreateSecondLevelChannelsTreeNodes(session.State, guildsView, cs)
  287. default:
  288. cID := n.GetReference().(string)
  289. c, _ := session.State.Channel(cID)
  290. if c.Type == discordgo.ChannelTypeGuildCategory {
  291. n.SetExpanded(!n.IsExpanded())
  292. } else if c.Type == discordgo.ChannelTypeGuildNews || c.Type == discordgo.ChannelTypeGuildText {
  293. selectedChannel = c
  294. app.SetFocus(messageInputField)
  295. title := "#" + c.Name
  296. if c.Topic != "" {
  297. title += " - " + c.Topic
  298. }
  299. messagesView.
  300. Clear().
  301. SetTitle(title)
  302. go writeMessages(c.ID)
  303. }
  304. }
  305. }
  306. func writeMessages(cID string) {
  307. msgs, _ := session.ChannelMessages(cID, config.GetMessagesLimit, "", "", "")
  308. for i := len(msgs) - 1; i >= 0; i-- {
  309. selectedChannel.Messages = append(selectedChannel.Messages, msgs[i])
  310. util.WriteMessage(
  311. messagesView,
  312. msgs[i],
  313. session.State.Ready.User.ID,
  314. )
  315. }
  316. }
  317. func onLoginFormLoginButtonSelected() {
  318. email := loginForm.GetFormItem(0).(*tview.InputField).GetText()
  319. password := loginForm.GetFormItem(1).(*tview.InputField).GetText()
  320. if email == "" || password == "" {
  321. return
  322. }
  323. session = newSession()
  324. // Try to login without TOTP
  325. lr, err := util.Login(session, email, password)
  326. if err != nil {
  327. panic(err)
  328. }
  329. if lr.Token != "" && !lr.MFA {
  330. app.
  331. SetRoot(mainFlex, true).
  332. SetFocus(guildsView)
  333. session.Token = lr.Token
  334. session.Identify.Token = lr.Token
  335. if err = session.Open(); err != nil {
  336. panic(err)
  337. }
  338. go keyring.Set("discordo", "token", lr.Token)
  339. } else if lr.MFA {
  340. loginForm = ui.NewLoginForm(func() {
  341. code := loginForm.GetFormItem(0).(*tview.InputField).GetText()
  342. if code == "" {
  343. return
  344. }
  345. lr, err = util.TOTP(session, code, lr.Ticket)
  346. if err != nil {
  347. panic(err)
  348. }
  349. app.
  350. SetRoot(mainFlex, true).
  351. SetFocus(guildsView)
  352. session.Token = lr.Token
  353. session.Identify.Token = lr.Token
  354. if err = session.Open(); err != nil {
  355. panic(err)
  356. }
  357. go keyring.Set("discordo", "token", lr.Token)
  358. }, true)
  359. app.SetRoot(loginForm, true)
  360. }
  361. }