discordo.go 9.4 KB

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