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.6KB

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