You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

histserv.go 7.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. // Copyright (c) 2020 Shivaram Lingamneni <slingamn@cs.stanford.edu>
  2. // released under the MIT license
  3. package irc
  4. import (
  5. "bufio"
  6. "fmt"
  7. "os"
  8. "runtime/debug"
  9. "strconv"
  10. "time"
  11. "github.com/ergochat/ergo/irc/history"
  12. "github.com/ergochat/ergo/irc/modes"
  13. "github.com/ergochat/ergo/irc/utils"
  14. )
  15. const (
  16. histservHelp = `HistServ provides commands related to history.`
  17. )
  18. func histservEnabled(config *Config) bool {
  19. return config.History.Enabled
  20. }
  21. func historyComplianceEnabled(config *Config) bool {
  22. return config.History.Enabled && config.History.Persistent.Enabled && config.History.Retention.EnableAccountIndexing
  23. }
  24. var (
  25. histservCommands = map[string]*serviceCommand{
  26. "forget": {
  27. handler: histservForgetHandler,
  28. help: `Syntax: $bFORGET <account>$b
  29. FORGET deletes all history messages sent by an account.`,
  30. helpShort: `$bFORGET$b deletes all history messages sent by an account.`,
  31. capabs: []string{"history"},
  32. enabled: histservEnabled,
  33. minParams: 1,
  34. maxParams: 1,
  35. },
  36. "delete": {
  37. handler: histservDeleteHandler,
  38. help: `Syntax: $bDELETE [target] <msgid>$b
  39. DELETE deletes an individual message by its msgid. The target is a channel
  40. name or nickname; depending on the history implementation, this may or may not
  41. be necessary to locate the message.`,
  42. helpShort: `$bDELETE$b deletes an individual message by its msgid.`,
  43. enabled: histservEnabled,
  44. minParams: 1,
  45. maxParams: 2,
  46. },
  47. "export": {
  48. handler: histservExportHandler,
  49. help: `Syntax: $bEXPORT <account>$b
  50. EXPORT exports all messages sent by an account as JSON. This can be used at
  51. the request of the account holder.`,
  52. helpShort: `$bEXPORT$b exports all messages sent by an account as JSON.`,
  53. enabled: historyComplianceEnabled,
  54. capabs: []string{"history"},
  55. minParams: 1,
  56. maxParams: 1,
  57. },
  58. "play": {
  59. handler: histservPlayHandler,
  60. help: `Syntax: $bPLAY <target> [limit]$b
  61. PLAY plays back history messages, rendering them into direct messages from
  62. HistServ. 'target' is a channel name or nickname to query, and 'limit'
  63. is a message count or a time duration. Note that message playback may be
  64. incomplete or degraded, relative to direct playback from /HISTORY or
  65. CHATHISTORY.`,
  66. helpShort: `$bPLAY$b plays back history messages.`,
  67. enabled: histservEnabled,
  68. minParams: 1,
  69. maxParams: 2,
  70. },
  71. }
  72. )
  73. func histservForgetHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  74. accountName := server.accounts.AccountToAccountName(params[0])
  75. if accountName == "" {
  76. service.Notice(rb, client.t("Could not look up account name, proceeding anyway"))
  77. accountName = params[0]
  78. }
  79. server.ForgetHistory(accountName)
  80. service.Notice(rb, fmt.Sprintf(client.t("Enqueued account %s for message deletion"), accountName))
  81. }
  82. func histservDeleteHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  83. var target, msgid string
  84. if len(params) == 1 {
  85. msgid = params[0]
  86. } else {
  87. target, msgid = params[0], params[1]
  88. }
  89. // operators can delete; if individual delete is allowed, a chanop or
  90. // the message author can delete
  91. accountName := "*"
  92. isChanop := false
  93. isOper := client.HasRoleCapabs("history")
  94. if !isOper {
  95. if server.Config().History.Retention.AllowIndividualDelete {
  96. channel := server.channels.Get(target)
  97. if channel != nil && channel.ClientIsAtLeast(client, modes.Operator) {
  98. isChanop = true
  99. } else {
  100. accountName = client.AccountName()
  101. }
  102. }
  103. }
  104. if !isOper && !isChanop && accountName == "*" {
  105. service.Notice(rb, client.t("Insufficient privileges"))
  106. return
  107. }
  108. err := server.DeleteMessage(target, msgid, accountName)
  109. if err == nil {
  110. service.Notice(rb, client.t("Successfully deleted message"))
  111. } else {
  112. if isOper {
  113. service.Notice(rb, fmt.Sprintf(client.t("Error deleting message: %v"), err))
  114. } else {
  115. service.Notice(rb, client.t("Could not delete message"))
  116. }
  117. }
  118. }
  119. func histservExportHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  120. cfAccount, err := CasefoldName(params[0])
  121. if err != nil {
  122. service.Notice(rb, client.t("Invalid account name"))
  123. return
  124. }
  125. config := server.Config()
  126. // don't include the account name in the filename because of escaping concerns
  127. filename := fmt.Sprintf("%s-%s.json", utils.GenerateSecretToken(), time.Now().UTC().Format(IRCv3TimestampFormat))
  128. pathname := config.getOutputPath(filename)
  129. outfile, err := os.Create(pathname)
  130. if err != nil {
  131. service.Notice(rb, fmt.Sprintf(client.t("Error opening export file: %v"), err))
  132. } else {
  133. service.Notice(rb, fmt.Sprintf(client.t("Started exporting data for account %[1]s to file %[2]s"), cfAccount, filename))
  134. }
  135. go histservExportAndNotify(service, server, cfAccount, outfile, filename, client.Nick())
  136. }
  137. func histservExportAndNotify(service *ircService, server *Server, cfAccount string, outfile *os.File, filename, alertNick string) {
  138. defer func() {
  139. if r := recover(); r != nil {
  140. server.logger.Error("history",
  141. fmt.Sprintf("Panic in history export routine: %v\n%s", r, debug.Stack()))
  142. }
  143. }()
  144. defer outfile.Close()
  145. writer := bufio.NewWriter(outfile)
  146. defer writer.Flush()
  147. server.historyDB.Export(cfAccount, writer)
  148. client := server.clients.Get(alertNick)
  149. if client != nil && client.HasRoleCapabs("history") {
  150. client.Send(nil, service.prefix, "NOTICE", client.Nick(), fmt.Sprintf(client.t("Data export for %[1]s completed and written to %[2]s"), cfAccount, filename))
  151. }
  152. }
  153. func histservPlayHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  154. items, _, err := easySelectHistory(server, client, params)
  155. if err != nil {
  156. service.Notice(rb, client.t("Could not retrieve history"))
  157. return
  158. }
  159. playMessage := func(timestamp time.Time, nick, message string) {
  160. service.Notice(rb, fmt.Sprintf("%s <%s> %s", timestamp.Format("15:04:05"), NUHToNick(nick), message))
  161. }
  162. for _, item := range items {
  163. // TODO: support a few more of these, maybe JOIN/PART/QUIT
  164. if item.Type != history.Privmsg && item.Type != history.Notice {
  165. continue
  166. }
  167. if len(item.Message.Split) == 0 {
  168. playMessage(item.Message.Time, item.Nick, item.Message.Message)
  169. } else {
  170. for _, pair := range item.Message.Split {
  171. playMessage(item.Message.Time, item.Nick, pair.Message)
  172. }
  173. }
  174. }
  175. service.Notice(rb, client.t("End of history playback"))
  176. }
  177. // handles parameter parsing and history queries for /HISTORY and /HISTSERV PLAY
  178. func easySelectHistory(server *Server, client *Client, params []string) (items []history.Item, channel *Channel, err error) {
  179. channel, sequence, err := server.GetHistorySequence(nil, client, params[0])
  180. if sequence == nil || err != nil {
  181. return nil, nil, errNoSuchChannel
  182. }
  183. var duration time.Duration
  184. maxChathistoryLimit := server.Config().History.ChathistoryMax
  185. limit := 100
  186. if maxChathistoryLimit < limit {
  187. limit = maxChathistoryLimit
  188. }
  189. if len(params) > 1 {
  190. providedLimit, err := strconv.Atoi(params[1])
  191. if err == nil && providedLimit != 0 {
  192. limit = providedLimit
  193. if maxChathistoryLimit < limit {
  194. limit = maxChathistoryLimit
  195. }
  196. } else if err != nil {
  197. duration, err = time.ParseDuration(params[1])
  198. if err == nil {
  199. limit = maxChathistoryLimit
  200. }
  201. }
  202. }
  203. if duration == 0 {
  204. items, err = sequence.Between(history.Selector{}, history.Selector{}, limit)
  205. } else {
  206. now := time.Now().UTC()
  207. start := history.Selector{Time: now}
  208. end := history.Selector{Time: now.Add(-duration)}
  209. items, err = sequence.Between(start, end, limit)
  210. }
  211. return
  212. }