discordo.go 9.6 KB

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